Compare commits

...
Author SHA1 Message Date
agrynco 0ce99e5af9 Release KSwitcher v0.7.2
Scale Settings navigation indentation with monitor DPI.
2026-11-24 18:23:02 +02:00
agrynco a517b6ceb0 Release KSwitcher v0.7.2 with DPI-aware Settings indentation 2026-11-24 18:22:49 +02:00
agrynco ab41b4383c Release KSwitcher v0.7.1
Embed OpenBao synchronization in the settings tree.
2026-11-24 17:54:01 +02:00
agrynco 0e9e5dd2ef Release KSwitcher v0.7.1 with embedded OpenBao settings 2026-11-24 17:53:50 +02:00
agrynco 40884cfc9e Release KSwitcher v0.7.0
Publish the native settings redesign.
2026-11-24 17:10:32 +02:00
agrynco 9db4a25c46 Release KSwitcher v0.7.0 with the native settings redesign 2026-11-24 17:08:16 +02:00
agrynco 15a95e5d74 Release KSwitcher v0.6.132
Record snippet keys with live feedback and improve clipboard snapshot capture.
2026-11-23 23:39:25 +02:00
agrynco 0de58834cf Release KSwitcher v0.6.132 with snippet key recording 2026-11-23 23:38:58 +02:00
agrynco 777af43c66 Release KSwitcher v0.6.131 2026-11-23 20:21:03 +02:00
agrynco c4a4f5e488 Release KSwitcher v0.6.131 with trusted LAN clients 2026-11-23 20:18:38 +02:00
agrynco 00966549d8 Release KSwitcher v0.6.130 (#76) 2026-11-22 15:22:05 +02:00
agrynco 783a6d69af Show the input state on the tray icon in KSwitcher v0.6.130 2026-11-22 15:21:22 +02:00
agrynco 4cd127a597 Release KSwitcher v0.6.129 (#75) 2026-11-22 14:40:31 +02:00
agrynco ff0d57d16b Prepare KSwitcher v0.6.129 with the tray input switch 2026-11-22 14:39:46 +02:00
agrynco 3be628cd8f Pause and resume resident input processing from the tray 2026-11-22 12:30:53 +02:00
agrynco f5fc7d205c Release KSwitcher v0.6.128 (#74) 2026-11-22 12:08:55 +02:00
agrynco 7387058dce Release the snippet window picker in KSwitcher v0.6.128 2026-11-22 12:08:25 +02:00
agrynco 8b3fe947a6 Release KSwitcher v0.6.127 (#73)
Confirm a single snippet suggestion with Enter before the focused application receives the key.
2026-11-21 23:56:17 +02:00
agrynco 7626e6c9c2 Release KSwitcher v0.6.126 (#72)
Ship literal snippet key presses and the configured pause without application-specific suggestion handling.
2026-11-21 23:45:42 +02:00
agrynco 3af1f09088 Release KSwitcher v0.6.125 (#71)
Run macros at their position in verified snippets and select Codex skills without submitting the draft.
2026-11-21 23:33:19 +02:00
agrynco 53842935a7 Release KSwitcher v0.6.124 (#70)
Ship keyboard macros and pauses in verified snippets, align the editor buttons, and include the verified Windows x64 package manifest and checksum.
2026-11-21 22:23:50 +02:00
agrynco bdd058f493 Release KSwitcher v0.6.123 (#69)
Ship the offline tray state and discovery-driven LAN input reconnection. Include the verified Windows x64 package manifest and checksum.
2026-11-20 20:40:01 +02:00
agrynco e7624b620e Release KSwitcher v0.6.122 (#68)
Ship LAN input reconnection and a tray connection indicator. Include the verified Windows x64 package manifest and checksum.
2026-11-20 18:44:21 +02:00
agrynco 367a5fd9f7 Release KSwitcher v0.6.121 (#67)
Ship the Files Markdown startup retry and apply word-boundary checks to all snippet triggers.
2026-11-20 16:40:10 +02:00
agrynco 4095c889c1 Release KSwitcher v0.6.120 (#66) 2026-11-20 00:42:13 +02:00
agrynco d8c329c265 Prepare KSwitcher v0.6.120
Keep image clipboard backups in a short-lived helper to reduce layout conversion latency while preserving newer copies.
2026-11-20 00:40:46 +02:00
agrynco debd2b9cd9 Release KSwitcher v0.6.119 (#65) 2026-11-18 13:08:23 +02:00
55 changed files with 5802 additions and 1586 deletions

No files matched your search

+14 -3
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.119 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.7.2 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
@@ -52,7 +52,10 @@ target_link_libraries(KSwitcherFiles PRIVATE kscore)
target_include_directories(kscore PUBLIC src PRIVATE vendor)
target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore)
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1")
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-paused.ico")
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
target_link_libraries(KSwitcher PRIVATE kscore)
@@ -84,7 +87,7 @@ if(MSVC)
else()
target_link_options(KSwitcherFarSnippetTests PRIVATE -municode -static -static-libgcc -static-libstdc++)
endif()
add_executable(KSwitcherInputTests tests/input.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
add_executable(KSwitcherInputTests tests/input.cpp tests/input_pause.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
target_link_libraries(KSwitcherInputTests PRIVATE kscore)
target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES)
add_executable(KSwitcherScreenshotUITests tests/screenshot_ui.cpp resources/app.rc)
@@ -143,6 +146,13 @@ else()
target_link_options(KSwitcherLanTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
add_test(NAME lan-pairing-regressions COMMAND KSwitcherLanTests)
add_executable(KSwitcherLanClientsTests tests/lan_clients.cpp)
target_link_libraries(KSwitcherLanClientsTests PRIVATE kscore)
if(NOT MSVC)
target_link_options(KSwitcherLanClientsTests PRIVATE -static)
endif()
add_test(NAME lan-trusted-clients COMMAND KSwitcherLanClientsTests)
set_tests_properties(lan-trusted-clients PROPERTIES TIMEOUT 15)
add_executable(KSwitcherLanFilesTests tests/lan_files.cpp)
target_link_libraries(KSwitcherLanFilesTests PRIVATE kscore)
add_test(NAME lan-files-regressions COMMAND KSwitcherLanFilesTests)
@@ -268,6 +278,7 @@ add_test(NAME utilities-regressions COMMAND KSwitcherUtilitiesTests)
add_test(NAME stayhere-lifecycle COMMAND powershell -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/stayhere.ps1" -Executable "$<TARGET_FILE:StayHereTest>")
add_test(NAME scroll-regressions COMMAND KSwitcherScrollTests)
add_test(NAME input-regressions COMMAND KSwitcherInputTests)
add_test(NAME tray-input-pause COMMAND KSwitcherInputTests --input-pause)
add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests)
add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --save-only)
add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$<TARGET_FILE:KSwitcher>")
+4 -2
View File
@@ -331,8 +331,10 @@ Warning і початковий фокус на No.
перерендерюється зі збереженням позиції прокрутки.
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
8 МіБ, F3 відкриває текстовий перегляд.
кліку. Mermaid працює офлайн і завантажується лише для документів із
діаграмами Mermaid. Якщо WebView2 не завершує запуск, Files один раз
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
позначених папок в інших рядках рахує позначені папки. Без позначок
+31 -18
View File
@@ -7,21 +7,22 @@ arranged on a monitor grid. Mouse and keyboard follow neighboring cells, includi
A → B → C, without relaying input through B. New text and images are also shared
with all online paired computers: history and the active clipboard.
## Files and diagnostic logs
## Trusted LAN clients
In **Settings → Computers → Manage computers…**, select an online paired
computer and choose **Send file…**. Both computers need a build with file transfer.
Files up to 16 MiB travel over encrypted LAN. On the destination, open
**Incoming files…** to save or discard each file. The save dialog suggests the
original filename. KSwitcher shows a Windows notification when a file is ready
to save, and its tray tooltip shows the pending count. Pending files are held
in memory until saved, discarded, or KSwitcher closes.
Open **Settings → Computers → Manage computers → Trusted clients** and choose **Add client…**. Select the Dirlume executable and confirm. Dirlume can list existing LAN pairs, browse their drives, and download regular files using each remote computer’s file-access permissions. Pairing credentials stay in the resident KSwitcher process.
To retrieve the current or rotated diagnostic log, enable **Allow paired
computers to download diagnostic logs** on the computer that owns the logs.
This setting defaults to off. On the requesting PC, select that computer and
choose **Download log…** or **Previous log…**. Diagnostic logs may contain
text copied from applications.
Select an executable and choose **Remove** to revoke access. Add the executable again after updating it, since KSwitcher checks the approved path and SHA-256 fingerprint.
## Remote files and diagnostic logs
Use **KSwitcher Files → Change drive** or Dirlume with a trusted-client entry
to browse and copy remote files. Starting in v0.7.0, Manage computers
focuses on pairing, shared input and diagnostic logs.
On the computer that owns the logs, enable **Allow paired computers to download
logs** in **Diagnostic logs** (off by default). On the requesting computer,
select the paired PC and choose **Current log…** or **Previous log…**.
Diagnostic logs may contain text copied from applications.
### MCP
@@ -37,10 +38,10 @@ the local resident process running and log downloads enabled on the remote PC.
## Set up multiple computers
1. Install the v0.6.58 or newer on every participating PC. Input protocol v2 requires all participants to update; earlier one-pair builds cannot connect. Preserve local data; do not copy pairing identities between PCs.
2. Open **Settings → Computers → Manage computers…** and enable discovery on both PCs.
2. Open **Settings → Computers → Manage computers** and enable discovery on both PCs.
Only running LAN-enabled KSwitcher instances appear, not generic network devices.
The computer list and pairing controls are on the left, the monitor grid and
input sharing are on the right, and file, log and help actions are below.
In wide windows, Pairing and Input sharing appear side by side. In narrow
windows, they stack above Diagnostic logs. Connection help is under Input sharing.
3. Match the computer name and instance-ID prefix displayed on the other PC.
Select each other, generate one code, enter that same code on both, then click
Pair on both within two minutes. Spaces, hyphens and uppercase hex are accepted.
@@ -59,6 +60,12 @@ the local resident process running and log downloads enabled on the remote PC.
into the source computer restores its cursor at the corresponding edge. Empty
cells, diagonal-only neighbors and offline PCs do not transfer control.
When input sharing is enabled, the tray icon shows a steady gray dot if all
paired PCs are offline, a pulsing amber dot while a discovered PC is connecting,
a green dot when all online paired PCs are connected, and a red dot if the LAN
worker stops. Hover over the icon to see the connection status and the connected
count when only some paired PCs are connected.
The source cursor is parked and hidden beneath a tiny no-activation window. A
small banner identifies remote control; no full-screen layered bitmap is retained.
The destination uses its own keyboard layout and runs its own hotkeys/snippets.
@@ -105,8 +112,14 @@ VLANs, public IPv4 and IPv6-only networks are not supported by discovery yet.
A second LAN-enabled KSwitcher cannot use the same ports on one computer.
Input first tries TCP in the usual direction, then reverse TCP after 1.5 seconds.
If TCP has not authenticated after 5 seconds, the lower-ID peer negotiates an
encrypted UDP input session on the existing discovery socket (UDP 45883).
LAN discovery authenticates paired PCs before starting new input connections.
Discovery remains active while all paired PCs are offline and wakes input sharing
when one reappears. An authenticated input connection survives missed discovery
announcements. Once discovery has expired and the channel closes, further input
attempts wait for fresh discovery.
After at least 5 seconds, the lower-ID peer starts encrypted UDP fallback on the
discovery socket (UDP 45883) once its current TCP connection attempt has failed
or reached its 10-second deadline.
UDP uses fresh session challenges, authenticated encryption, ordered event
numbers, acknowledgements and bounded retries; duplicated packets do not repeat
key presses. Two seconds without authenticated traffic or acknowledgement
+79 -35
View File
@@ -7,11 +7,11 @@ The original [Typlo](https://github.com/bitcodepro/Typlo) project and its data r
**[User guide / Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki)** — setup, features, shortcuts, dictionaries, screenshots and troubleshooting in **English** and **[Українська](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk)**. Each wiki page links to its translation.
From v0.6.72, use **Settings → Snippets** to edit snippets in place and
**Save snippets** to save them independently. **Clipboard** contains OCR
**Save** to apply snippet edits together with other settings. **Clipboard** contains OCR
options. **Sync**, **Computers**, and **Diagnostics** have their own tabs.
**Українською.** З v0.6.72 сніпети редагуються у **Settings → Snippets**
і зберігаються окремою кнопкою **Save snippets**. OCR розміщено у
і зберігаються разом з іншими налаштуваннями кнопкою **Save**. OCR розміщено у
**Clipboard**, а для синхронізації, ПК та журналу є окремі вкладки
**Sync**, **Computers** і **Diagnostics**.
@@ -185,10 +185,10 @@ Exit [Typlo](https://github.com/bitcodepro/Typlo) when using overlapping shortcu
This also works for each layout's **Direct layout shortcut**. Backspace or Delete without modifiers
clears a shortcut. Tab moves to the next field. The recorded shortcut is suppressed while the field
has focus, so recording the conversion shortcut does not perform a conversion.
All configured shortcuts use the existing keyboard hook and can replace ordinary Windows/app
The Files shortcut is registered with Windows. The other configured shortcuts use the keyboard hook and can replace ordinary Windows/app
shortcuts, including **Win+V** and **Win+Shift+S**, while KSwitcher is running. Only exact configured
combinations are intercepted. Unassigned shortcuts and simulated copy/paste pass through.
Choose another shortcut or exit KSwitcher to restore the original action. Windows protects
Pause input processing, choose another shortcut or exit KSwitcher to restore the original action. Windows protects
Ctrl+Alt+Delete and Win+L; these cannot be assigned.
Keyboard and mouse input forwarded by Microsoft Mouse Without Borders follows the same input
@@ -201,6 +201,28 @@ keys cannot trigger recursive commands or overwrite the recorded typing run. Oth
is accepted, including key-up events and VK-only keyboard events. Unicode packets do not provide
physical key positions and therefore reset recent-word tracking; selection conversion still works.
### Pause input processing
Right-click the KSwitcher tray icon and choose **Pause input processing** before testing another keyboard tool.
The purple **K** changes to two white pause bars on a gray tile. The tooltip says **Input processing paused** once KSwitcher releases its shortcuts and
stops keyboard and mouse actions, autocorrection, snippets, automatic layout switching, LAN mouse and keyboard
control, and simulated F15 activity. Clipboard history has its own pause control. You can browse entries
during an input pause and paste them after resuming. If you launched the standalone **StayHere** utility,
its own tray icon controls its F15 activity.
Choose **Resume input processing** in the same menu after testing. The tooltip then shows **Input processing active**. If another program still holds a shortcut,
KSwitcher identifies the combination and stays paused. Release it in the other program and retry.
The pause lasts for the current run.
**Українською.** Перед тестуванням іншої програми клацни правою кнопкою значок KSwitcher у треї й вибери
**Pause input processing**. Фіолетова **K** зміниться на дві білі смуги на сірому тлі. Підказка **Input processing paused** підтвердить паузу. KSwitcher
звільняє гарячі клавіші й призупиняє дії клавіатури та миші, автокорекцію, сніпети, автоматичне перемикання
розкладки, LAN-керування й імітацію F15. Історія буфера обміну має окремий перемикач. Записи можна переглядати
під час паузи та вставляти після відновлення. Якщо окремо запущена утиліта **StayHere**, її імітація F15
керується з її власного значка в треї.
Для відновлення вибери **Resume input processing**. Підказка покаже **Input processing active**. Якщо комбінація зайнята, звільни вказаний хоткей
в іншій програмі та повтори спробу. Пауза діє до завершення поточного запуску.
### Screen capture and annotations
Press **Win+Shift+S**, choose **Capture screen region…** in the tray menu, or run
@@ -411,8 +433,9 @@ thumbnails and source labels aligned with the scaled fonts and spacing.
> З v0.6.50: OCR чатів Viber тимчасово вимкнений. Збережені профілі Viber залишаються, але не діють. Профілі Telegram і Teams та OCR зображень/буфера працюють як раніше.
Settings separates General, Languages, Shortcuts, Clipboard and Tools into native tabs.
Switching tabs preserves edits; Save, Cancel, Import and Export stay available below every page.
In Settings, choose a section in the navigation tree or use **Search settings** to find an individual option.
Drag the divider to resize navigation. The window remembers its size, position, and active section.
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
@@ -433,9 +456,9 @@ profile. Telegram unread counters are ignored. Teams currently recognizes the de
Experimental Viber profiles introduced in v0.6.49 are disabled in v0.6.50 because repeated OCR caused delays. There is no background Viber OCR, recognition during language switching, or recognition when opening profiles. Saved Viber profiles are retained and marked inactive; Windows switching and Next layout use their normal/global behavior in Viber. Clipboard and image OCR are unchanged.
From v0.6.53, chat profiles (application, visible chat name and ordered language IDs) are included in settings synchronization and manual export/import. Update every synchronizing PC to v0.6.53 or newer first: older clients reject this shared field. Profiles for different chats merge independently; conflicting edits or deletion versus editing of one chat require a choice. Missing Windows layouts stay saved and are skipped during switching, with global-cycle fallback if none are installed. Keep this PC's layouts preserves the global cycle and shortcuts while chat profiles still synchronize. Downloading a pre-v0.6.53 profile preserves existing chat profiles. Chat matching is unchanged; Viber profiles remain inactive.
**Українською.** Налаштування розділено на вкладки General, Languages, Shortcuts, Clipboard
і Tools. Перехід між ними зберігає незбережені зміни; Save, Cancel, Import і Export доступні
на кожній вкладці. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages
**Українською.** Вибирайте розділ у дереві Settings або шукайте окремий параметр через **Search settings**.
Перетягніть розділювач, щоб змінити ширину дерева. Settings запам’ятовує розмір і положення вікна
та активний розділ. Перехід між розділами зберігає чернетку. Save, Cancel, Import і Export доступні знизу. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages
for a chat…**. Вибери чат і потрібні мови, натисни **Use languages**, а потім **Save**.
Набір діє для **Alt+Shift**, **Win+Space**, **Win+Shift+Space** та **Next layout** KSwitcher.
Можна вибрати й одну мову; порядок зберігається із загального списку під час редагування профілю. **Remove profile**
@@ -461,10 +484,11 @@ Recognition uses Chrome accessibility: the address bar and active document must
### Snippet autocomplete — v0.6.69
Starting with v0.6.71, **Enter** accepts a suggestion after you navigate
the list with **↑ / ↓**. Without arrow navigation, **Enter** goes to the
editor. З v0.6.71 **Enter** після вибору стрілками вставляє сніпет. Без
переміщення списком **Enter** надходить до редактора.
**Enter** accepts a single visible suggestion directly. When several suggestions
are visible, navigate the list with **↑ / ↓** to select one for **Enter**.
**Українською.** **Enter** одразу підтверджує єдину видиму підказку. Якщо
підказок кілька, виберіть потрібну стрілками **↑ / ↓**, а тоді натисніть **Enter**.
Starting with v0.6.70, suggestions open at the text caret. If the editor
provides no caret position, you can still type the complete trigger to
@@ -473,14 +497,16 @@ expand the snippet.
Type `;` at the start of a trigger to open suggestions near the caret, or
type the first three characters of another trigger. The list filters as you
type and fits the widest matching trigger. Use **↑ / ↓** and **Tab** or click
an entry. **Esc** dismisses the list. Full triggers still expand
automatically. See the [snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
an entry. **Esc** dismisses the list. Full triggers expand automatically at the
start of a word, including when typed in another keyboard layout. See the
[snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
**Українською.** Введіть `;` на початку тригера або три перші символи іншого
тригера, щоб відкрити підказки біля курсора. Список фільтрується під час набору
й підлаштовує ширину під найдовший збіг. Для вибору натисніть **↑ / ↓** і
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери й далі
спрацьовують автоматично. Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери спрацьовують
автоматично на межі перед словом, зокрема під час набору в іншій розкладці.
Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
З v0.6.70 підказки відкриваються біля текстового курсора. Якщо редактор не
надає його позицію, введіть повний тригер для розгортання сніпета.
@@ -491,15 +517,35 @@ ChatGPT and Codex desktop editors use paced selection for snippet triggers. If o
**Українською.** У настільних ChatGPT і Codex тригер виділяється з паузами між натисканнями. Якщо виділилася лише перевірена кінцева частина, KSwitcher доповнює виділення й перевіряє весь тригер перед заміною. Інший текст або зміна фокусу скасовують операцію. Тригери розпізнаються в різних розкладках. Один сніпет можна прив’язати до кількох програм через **Add app** або назви процесів через кому; ці прив’язки вже підтримують синхронізацію.
### Snippet macros
In **Settings → Snippets**, choose **Insert macro or marker…**. Enter a pause duration or click the recording field and press the keys. They appear as you press them. Release the keys and click **Insert**. You can also type expressions into the replacement text. KSwitcher runs each macro between text segments in the listed order. A leading macro runs after the first text segment, as in earlier versions. A snippet needs some replacement text.
- `{{shift}}`, `{{alt}}` and `{{tab}}` tap individual keys. Key names are case-insensitive. Letters, digits, `F1`–`F24`, navigation and editing keys also work.
- `{{altr}}+{{ctrl}}` holds both keys together. Join key markers with `+` without spaces and put modifiers before the final key, as in `{{ctrl}}+{{shift}}+{{A}}`. Use `l` or `r` after `ctrl`, `alt`, `shift` or `win` to select a side. The unsuffixed names use the left keys.
- `rider .{pause:50}{enter}` inserts `rider .`, waits 50 milliseconds, then presses Enter. One pause can be 0–10,000 milliseconds. Use `{{return}}` for Enter inside a chord, as in `{{ctrl}}+{{return}}`.
- Write `{{cursor}}`, `{{enter}}`, `{{pause:50}}` or `{{{shift}}}` to insert the corresponding marker literally.
**Українською.** У **Settings → Snippets** натисни **Insert macro or marker…**. Для паузи введи тривалість, а для клавіш клацни поле запису й натисни потрібні клавіші. Вони з’являються під час натискання. Відпусти їх і натисни **Insert**. Макроси також можна вписати в текст заміни. KSwitcher виконує макроси між частинами тексту за порядком запису. Макрос на початку, як і раніше, виконується після першої частини тексту. Сніпет має містити текст заміни.
- `{{shift}}`, `{{alt}}` і `{{tab}}` натискають окремі клавіші. Регістр назви клавіші не має значення. Також підтримуються літери, цифри, `F1`–`F24`, клавіші навігації та редагування.
- `{{altr}}+{{ctrl}}` затискає обидві клавіші разом. З’єднуй маркери знаком `+` без пробілів і став модифікатори перед основною клавішею, як у `{{ctrl}}+{{shift}}+{{A}}`. Суфікси `l` і `r` у назвах `ctrl`, `alt`, `shift` і `win` вибирають ліву й праву клавіші. Без суфікса використовується ліва.
- `rider .{pause:50}{enter}` вставляє `rider .`, чекає 50 мілісекунд і натискає Enter. Допустимий діапазон однієї паузи — від 0 до 10 000 мілісекунд. Для Enter у комбінації використовуй `{{return}}`, наприклад `{{ctrl}}+{{return}}`.
- Записуй `{{cursor}}`, `{{enter}}`, `{{pause:50}}` або `{{{shift}}}`, щоб вставити відповідний маркер як звичайний текст.
For example, `$skill-name{pause:500}{enter} Draft text{cursor}` types the token, waits 500 milliseconds, presses Enter once, then types the draft. The focused application handles Enter. Each `{enter}` sends a separate press.
Наприклад, `$skill-name{pause:500}{enter} Текст чернетки{cursor}` вводить назву, чекає 500 мілісекунд, натискає Enter один раз і вводить чернетку. Enter обробляє програма у фокусі. Кожен `{enter}` надсилає окреме натискання.
### Application-specific snippets — v0.6.51
In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Enter executable names separated by commas, or select a currently open application's process and choose **Add app**. For example: `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Use **Save snippets** to apply the changes.
In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application. You can also select a process from the dropdown and click **Add app**, or type executable names separated by commas, such as `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Click **Save** at the bottom of Settings to apply the changes.
A matching application-specific snippet takes precedence over a global snippet with the same trigger. The same trigger can be used for different applications; overlapping scopes for the same trigger are rejected. Existing snippets without a scope remain global. Matching is case-insensitive by process name, with or without `.exe`, and is checked before insertion. No OCR or timer is involved. Chrome scope means the entire browser, not one website.
Scopes are saved with snippets and included in manual import/export and synchronization; merge conflicts consider the application scopes. Use v0.6.51 or newer on every synchronizing PC before sharing scoped snippets: older versions do not understand the restriction and may treat the snippet as global.
**Українською.** У **Settings → Snippets** вибери сніпет, увімкни **Only in these applications** та задай назви процесів через кому або вибери відкриту програму зі списку й натисни **Add app**. Наприклад: `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. Натисни **Save snippets**, щоб застосувати зміни.
**Українською.** У **Settings → Snippets** вибери сніпет і ввімкни **Only in these applications**. Перетягни мішень поруч із **Add app** на відкрите вікно, щоб додати його програму. Повтори для кожної потрібної програми. Також можна вибрати процес зі списку й натиснути **Add app** або вписати назви процесів через кому, наприклад `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. Натисни **Save** внизу Settings, щоб застосувати зміни.
Сніпет конкретної програми має пріоритет над глобальним із тим самим тригером. Для різних програм однакові тригери дозволені, для перетинних областей — ні. Старі сніпети залишаються глобальними. Зіставлення за назвою процесу не залежить від регістру та суфікса `.exe`; OCR і таймерів немає. Для Chrome це весь браузер, а не окремий сайт. Обмеження входять до експорту/імпорту та синхронізації. Перед синхронізацією онови всі ПК до v0.6.51 або новішої: старі версії не розуміють обмеження та можуть застосувати сніпет глобально.
### Existing features
@@ -516,12 +562,12 @@ Scopes are saved with snippets and included in manual import/export and synchron
editor selection metadata remain identical. Unobserved or altered foreign copies are rejected.
Snippets normally require accessibility verification of their selected trigger and pasted text,
even with logging disabled. If verification is unavailable or the paste differs, expansion
stops without running cursor or Enter actions. Clipboard changes during paste also cancel actions.
stops before placing the cursor or running key actions. Clipboard changes during paste also cancel actions.
Far Manager uses its native Alt+Shift+Arrow selection, Ctrl+Insert copy and Shift+Insert
paste commands instead: both the trigger and inserted text must match verified clipboard
copies from Far. Cancellation restores the full temporary selection, not one cursor step.
Far supports nonempty single-line replacements up to 4096 caret steps, including
`{cursor}` and verified `{enter}` actions. Empty or multiline replacements are rejected
`{cursor}` and key macros after verification. Empty or multiline replacements are rejected
before selection; pasting a newline could execute a command before it can be verified.
- Teams recent-word conversion uses a single word-selection command and validates the copied range.
If the editor's word boundary differs from the recorded typing, it falls back to paced character
@@ -538,12 +584,10 @@ Scopes are saved with snippets and included in manual import/export and synchron
repeat-conversion state and does not switch the Windows layout.
- Case cycling, Russian/Ukrainian transliteration, verified undo and repeated conversion.
- Text snippets across layouts, multiline insertion and a verified `{cursor}` position;
`{enter}` presses Enter after insertion and cursor placement (once per marker), before buffered typing resumes.
For example, `rider .{enter}` inserts `rider .` and presses Enter.
macros run between text segments, before buffered typing resumes.
Automatic correction is suppressed during snippet expansion and for typing buffered by that expansion; the global setting is preserved.
If the trigger cannot be verified after the copy attempts, it is preserved, queued typing resumes,
and no Enter action is sent.
`{{cursor}}` and `{{enter}}` insert literal markers. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo).
and no key actions are sent. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo).
- Clipboard history for text, HTML/RTF, file lists, DIB and PNG images; plain-text paste;
full-text search, pinning, deletion, full text viewing and image previews.
- Image thumbnails and text/file icons appear directly in the history list. Only visible rows
@@ -666,7 +710,7 @@ Conversion is cancelled rather than pasting into a different window or replacing
## OpenBao synchronization (experimental, opt-in)
The **Sync...** button is available in Settings for everyone. Synchronization remains disabled
Open **Settings → Sync → OpenBao**. Synchronization remains disabled
until you configure your own OpenBao and enable it. Connection configuration is saved separately
in `sync.json`. The portable data directory is normally `data/` beside the executable; installations
without a writable application directory use the existing local-app-data fallback.
@@ -678,11 +722,11 @@ authentication mount (default `userpass`). Use the same profile on each of your
administrator-provisioned private access, not public account registration. Non-root namespaces,
reverse-proxy URL prefixes, MFA login flows and other providers are not implemented yet.
Enable synchronization and choose **Save / Sign in / Sync**. The dialog saves connection changes
immediately; the main Settings window's Save/Cancel does not control this separate configuration.
Enable synchronization and choose **Save and sync** on the OpenBao page. This button saves the
connection settings separately from the main Settings draft.
When synchronization is disabled, connection fields and sync actions are inactive. Check **Enable
synchronization** to make them available. To disable an existing connection, uncheck it and click
**Save**; this preserves the saved connection and password without starting a sync request.
**Save connection**. This preserves the saved connection and password without starting a sync request.
**Disconnect / forget password** remains available while synchronization is disabled.
A blank password keeps the existing Windows credential for that server, login mount and username.
The password is saved in Windows Credential Manager, not in settings exports, logs or the remote
@@ -694,7 +738,7 @@ saved credential. A request already sent to the server may still complete; its d
will not be applied after the connection changes. Old credentials for other connection identities
can be removed in Windows Credential Manager under `KSwitcher.Sync/`.
On the first connection, **Save / Sign in / Sync** merges the existing profiles without
On the first connection, **Save and sync** merges the existing profiles without
requiring a whole-profile replacement. Independent entries (such as snippets, exclusions and
replacement pairs) are combined. Different values for the same setting remain on their respective
sides and appear in **Resolve individual conflicts...**; no value is guessed without a common history.
@@ -703,7 +747,7 @@ Nonconflicting changes synchronize immediately, and unresolved conflicts survive
- **Upload local** creates the remote profile or replaces it with this PC's saved shared settings.
- **Download remote** replaces this PC's shared settings with the server profile.
- If the server has no profile yet, choose **Upload local** to create it.
- Unsaved edits in Settings are not synchronized. After a successful **Download remote**, the open Settings window refreshes automatically and keeps the selected tab. The download confirmation warns that unsaved edits will be discarded.
- Unsaved edits in Settings are not synchronized. After a successful **Download remote**, the open Settings window refreshes automatically and keeps the selected section. The download confirmation warns that unsaved edits will be discarded.
- The status distinguishes downloading, downloaded settings, no local changes and failure. HTTP 400 errors identify authentication, download or upload; field errors remain visible until the next action.
Once connected, the resident checks at startup, every **10 minutes**, and about two seconds after saving settings, on a separate
@@ -742,8 +786,8 @@ paths refer to the same locations and may need updating on a fresh installation.
Connection details and credentials stay local so you can sign in again after reinstalling.
Clipboard history, screenshots and dictionary files are never uploaded. Full synchronization identifies
missing keyboard layouts by language (when Windows can identify it) and exact ID.
Install the same layout variant, or select **Keep this PC's layouts and layout shortcuts (sync
other settings)** and click **Save / Sign in / Sync**. This device-local option keeps the entire
Install the same layout variant, or select **Keep this PC's layouts and layout shortcuts**
and click **Save and sync**. This device-local option keeps the entire
local layout cycle and its direct shortcuts unchanged while synchronizing the other shared settings.
The server's layout cycle and direct shortcuts are preserved on automatic sync and explicit Upload;
Download also keeps the local layout configuration. Later syncs cannot erase missing server layouts
@@ -832,7 +876,7 @@ Target layouts must also be enabled in the layout cycle.
### Custom replacements and spelling typos
Two optional modes in **Auto-correction options…** extend layout correction. Both are off by
Two optional modes in **General → Correction options** extend layout correction. Both are off by
default and require the main **Automatic correction (experimental)** checkbox to be enabled.
- **Use custom replacements**: enter one `typo=correction` pair per line, for example
@@ -1027,7 +1071,7 @@ History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc**
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels.
History reuses separate helper processes for OCR and thumbnails so recognition can run alongside previews.
Idle helpers exit after 30 seconds, and closing the history host stops its helpers. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
Idle history helpers exit after 30 seconds, and closing the history host stops its helpers. During text conversion, a short-lived instance of **KSwitcher.Screenshot.exe** holds the image clipboard backup in memory and restores it only if the clipboard sequence still matches. Selection reads avoid loading image formats. Keep the executables from the same ZIP together. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
A live development-build test measured **4.37 MiB before history and 4.35 MiB after two open/Esc cycles**, compared with an earlier roughly 8–9 MiB plateau. A same-image clipboard-backup benchmark retained **12.78 MiB before versus 0.05 MiB after**. These measure private working set, not a guaranteed total footprint. Include all helpers when measuring active use: combined memory can be higher while history is open. No forced working-set trimming is used. Existing screenshots and shortcuts remain applicable. The v0.6.38 approach of retaining a hidden history window/RichEdit control is superseded by process termination.
+139 -1
View File
@@ -1,5 +1,143 @@
# Latest Windows release
## v0.7.2 — 2026-11-24
Nested entries in the Settings navigation tree have a compact indent that follows Windows display scaling, including when you move Settings between monitors.
**Українською.** Вкладені пункти в дереві налаштувань мають компактний відступ, який враховує масштаб Windows і перераховується при перенесенні вікна між моніторами.
## v0.7.1 — 2026-11-24
OpenBao connection and synchronization actions are now on **Settings → Sync → OpenBao**. Choose **Save and sync** on that page to save the connection and start synchronization. Settings search can find OpenBao fields, and switching sections preserves the connection draft.
**Українською.** Підключення й дії синхронізації OpenBao тепер доступні в **Settings → Sync → OpenBao**. Натисніть **Save and sync** на цій сторінці, щоб зберегти підключення й запустити синхронізацію. Пошук Settings знаходить поля OpenBao, а перехід між розділами зберігає чернетку підключення.
## v0.7.0 — 2026-11-24
- The native Settings window has a resizable navigation tree and a **Search settings** field. Search finds individual settings, highlights matches, and scrolls the selected control into view.
- Settings remembers its window position, size, sidebar width, and last section. Pages adapt to narrower windows. **General → Correction options** groups dictionaries, exceptions, word boundaries, and substitutions.
- **Computers → Manage computers** opens in Settings and groups pairing, input sharing, and diagnostic logs. Use KSwitcher Files or Dirlume for browsing and copying remote files.
**Українською.**
- У нативному вікні Settings з’явилися дерево розділів зі змінною шириною та поле **Search settings**. Пошук знаходить окремі параметри, підсвічує збіги й прокручує до вибраного поля.
- Settings запам’ятовує положення й розмір вікна, ширину дерева та останній розділ. Сторінки підлаштовуються під вузькі вікна. У **General → Correction options** згруповано словники, винятки, межі слів і заміни.
- **Computers → Manage computers** відкривається в Settings і групує спарювання, спільний ввід та діагностичні журнали. Для перегляду й копіювання файлів з іншого ПК використовуйте KSwitcher Files або Dirlume.
## v0.6.132 — 2026-11-23
In **Settings → Snippets**, **Insert macro or marker…** can add cursor and Enter markers, a pause in milliseconds, or a recorded key or key combination. Keys appear as you press them. Release the keys, click **Insert**, and use the main **Save** button to apply snippet edits together with other settings.
Clipboard snapshots track the sequence after Windows prepares delayed formats. A sequence advance caused by the read can no longer abort the text operation. When image backup fails, diagnostics include the helper's error.
**Українською.** У **Settings → Snippets** кнопка **Insert macro or marker…** додає маркери курсора й Enter, паузу в мілісекундах або записану клавішу чи комбінацію. Клавіші видно під час натискання. Відпустіть їх, натисніть **Insert** і збережіть правки головною кнопкою **Save**.
Під час створення копії буфера KSwitcher бере номер послідовності після підготовки відкладених форматів Windows. Зміна номера під час самого читання більше не перериває текстову операцію. Якщо резервне копіювання зображення не вдалося, журнал показує помилку допоміжного процесу.
## v0.6.131 — 2026-11-23
In **Settings → Computers → Manage computers… → Trusted clients**, choose **Add client…** and select Dirlume.exe. Dirlume can then browse drives on computers already paired in KSwitcher and download regular files. Remove the executable to revoke access. After updating Dirlume, add the new executable again.
**Українською.**
У **Settings → Computers → Manage computers… → Trusted clients** натисніть **Add client…** і виберіть Dirlume.exe. У Dirlume можна відкривати диски комп’ютерів, які вже спарені в KSwitcher, і завантажувати файли. Видаліть виконуваний файл зі списку, щоб відкликати доступ. Після оновлення Dirlume додайте новий файл повторно.
## v0.6.130 — 2026-11-22
The tray shows a purple **K** while KSwitcher processes input. Choose **Pause input processing** to see two white pause bars on a gray tile. The purple **K** returns after **Resume input processing** succeeds. If another program still holds a shortcut, the pause bars stay visible.
**Українською.**
Фіолетова **K** у треї означає, що KSwitcher обробляє введення. Після вибору **Pause input processing** з’являються дві білі смуги на сірому тлі. Фіолетова **K** повертається після успішного **Resume input processing**. Якщо інша програма ще утримує гарячу клавішу, значок паузи залишається.
## v0.6.129 — 2026-11-22
Choose **Pause input processing** in the tray to test another keyboard tool. The tooltip shows **Input processing paused** once KSwitcher releases its shortcuts and stops keyboard and mouse actions, snippets, autocorrection, automatic layout switching, LAN input and simulated F15 activity. Clipboard history can still record entries. Choose **Resume input processing** to restore input. If a shortcut is occupied, KSwitcher names it and stays paused until you retry. Restarting KSwitcher also clears the pause.
**Українською.**
Щоб протестувати іншу програму для клавіатури, виберіть **Pause input processing** у треї. Підказка **Input processing paused** з’явиться, коли KSwitcher звільнить гарячі клавіші та призупинить дії клавіатури й миші, сніпети, автокорекцію, автоматичне перемикання розкладки, LAN-керування й імітацію F15. Історія буфера може й далі записувати нові елементи. Виберіть **Resume input processing** для відновлення. Якщо комбінація зайнята, KSwitcher покаже її та залишиться на паузі до повторної спроби. Перезапуск KSwitcher також скидає паузу.
## v0.6.128 — 2026-11-22
In **Settings → Snippets**, drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application, then choose **Save snippets**. Esc cancels a drag. Picking the same application twice adds it only once.
**Українською.**
На вкладці **Settings → Snippets** перетягніть мішень поруч із **Add app** на відкрите вікно, щоб додати його програму. Повторіть для кожної потрібної програми й натисніть **Save snippets**. Esc скасовує перетягування. Повторний вибір програми не створює дубліката.
## v0.6.127 — 2026-11-21
When the snippet popup shows one match, pressing Enter expands it immediately and consumes the key. With several matches, use the arrow keys and then press Enter to confirm.
**Українською.**
Якщо у списку підказок є один збіг, Enter одразу розгортає сніпет. KSwitcher перехоплює це натискання. Якщо збігів кілька, виберіть потрібний стрілками й підтвердьте через Enter.
## v0.6.126 — 2026-11-21 (withdrawn / відкликано)
Snippet macros send the configured keys at the position where they appear. `$skill{pause:500}{enter} Draft text` types the name, waits 500 milliseconds, presses Enter once, then types the remaining text. The focused application handles each key.
**Українською.**
Макроси сніпетів натискають задані клавіші в указаній позиції. `$skill{pause:500}{enter} Текст` вводить назву, чекає 500 мілісекунд, один раз натискає Enter і вводить решту тексту. Кожне натискання обробляє програма у фокусі.
## v0.6.125 — 2026-11-21 (withdrawn / відкликано)
Snippet macros between text segments run before the next segment is inserted. In Codex, `$skill{pause:500}{enter} Draft text` selects the matching skill suggestion and leaves the following text in the composer. Extra Enter markers at the same selection point do not submit the draft. Expansion stops when the suggestion cannot be verified.
**Українською.**
Макроси між частинами сніпета виконуються перед вставленням наступної частини. У Codex `$skill{pause:500}{enter} Текст чернетки` вибирає відповідний скіл із підказок і залишає наступний текст у редакторі. Повторні маркери Enter у тій самій позиції не надсилають чернетку. Якщо підказку не вдалося перевірити, розгортання зупиняється.
## v0.6.124 — 2026-11-21
Snippets can tap keys such as `{{shift}}`, hold combinations such as `{{altr}}+{{ctrl}}`, and wait with `{pause:50}`. After verifying the inserted text and placing `{cursor}`, KSwitcher runs the macros in order. The Snippets tab groups marker buttons and **Macro help…** below the editor, with **Save snippets** at the right.
**Українською.**
Сніпети підтримують окремі клавіші, як-от `{{shift}}`, комбінації на кшталт `{{altr}}+{{ctrl}}` і паузи, як-от `{pause:50}` на 50 мс. KSwitcher виконує макроси за порядком запису після перевірки вставленого тексту й встановлення `{cursor}`. На вкладці **Snippets** кнопки маркерів і **Macro help…** згруповані під редактором, а **Save snippets** розташована праворуч.
## v0.6.123 — 2026-11-20
- The tray shows a steady gray dot when all paired PCs are offline. The amber dot pulses while a discovered PC is connecting. Green means every online paired PC is connected.
- LAN discovery stays active. Once discovery has expired and the last input channel closes, KSwitcher pauses mouse and keyboard connection attempts until a paired PC reappears.
**Українською.**
- Коли всі спаровані ПК офлайн, у треї видно статичну сіру крапку. Жовта крапка пульсує під час підключення до знайденого ПК. Зелена означає, що всі доступні спаровані ПК під’єднані.
- Пошук у LAN продовжує працювати. Коли строк дії підтвердження присутності спливає й останній канал вводу закривається, KSwitcher призупиняє спроби підключення миші та клавіатури до появи спарованого ПК.
## v0.6.122 — 2026-11-20
- LAN mouse and keyboard sharing lets a TCP attempt finish or time out before starting the encrypted UDP fallback.
- The tray icon pulses amber while reconnecting, shows green when all paired PCs are connected, and shows red if the LAN service stops. Hover to see connection status and how many PCs are connected. Diagnostic logs distinguish a declined cursor handoff from returned control.
**Українською.**
- Під час передавання миші та клавіатури KSwitcher чекає завершення TCP-спроби або її тайм-ауту, перш ніж запустити резервне з’єднання через зашифрований UDP.
- Іконка в треї пульсує жовтим під час перепідключення, показує зелену крапку, коли всі спаровані ПК під’єднані, і червону, якщо LAN-модуль зупинився. Наведіть курсор, щоб побачити стан і кількість підключених ПК. У діагностичному журналі видно, коли другий ПК відхилив перехід курсора або повернув керування.
## v0.6.121 — 2026-11-20
KSwitcher Files retries WebView2 startup once when a Markdown preview fails to initialize. If the retry succeeds, the same window displays the formatted document. The Markdown viewer loads the bundled Mermaid library only for documents with Mermaid diagrams.
Snippet expansion now requires a word boundary before the trigger, even after a pause. The same rule applies across keyboard layouts and in Far Manager.
**Українською.**
Якщо перегляд Markdown не запускається, KSwitcher Files один раз повторює запуск WebView2. Після успішної спроби форматований документ з’являється в тому самому вікні. Бібліотека Mermaid завантажується лише для документів із діаграмами Mermaid.
KSwitcher розгортає сніпети, коли тригер відокремлено від попереднього слова. Перевірка діє після паузи, у різних розкладках і у Far Manager.
## v0.6.120 — 2026-11-20
Layout conversion starts faster when the Windows clipboard contains an image. KSwitcher keeps the image and accompanying formats in memory for the duration of the operation. It restores them after conversion if the clipboard still belongs to the operation. A newer copy takes precedence.
**Українською.**
Перетворення розкладки починається швидше, коли в буфері обміну Windows є зображення. KSwitcher тримає зображення й супровідні формати в пам’яті до завершення операції. Копія відновлюється, якщо буфер усе ще належить операції. Новіше копіювання має пріоритет.
## v0.6.119 — 2026-11-18
KSwitcher Files runs local commands in the folder shown at the command prompt. After switching panes or opening a different folder, commands such as `git clone` and relative path suggestions use that folder in the same PowerShell session.
@@ -534,6 +672,6 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
Choose **Update** in the tray menu. For v0.3.x–v0.4.1, install the [v0.4.2 bridge](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2) manually first. Close KSwitcher and its editors, extract the bridge ZIP into the installation folder while keeping personal data, dictionaries, and tools, then start v0.4.2 and choose **Update**. v0.2.3 and earlier require manual installation.
For a manual upgrade, exit KSwitcher and its configurator and screenshot editors, then extract the entire **KSwitcher-win-x64.zip** into its installation folder. Verify it with **SHA256SUMS.txt**. Keep personal data, customized dictionaries and tools. Keep the three KSwitcher executables together.
For a manual upgrade, save your work and exit KSwitcher, Settings, Files, screenshot editors and bundled StayHere. Verify **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**, then extract the entire ZIP into the installation folder. Keep personal data, customized dictionaries and tools.
See the [English Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home) or [Українська Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk).
+1 -1
View File
@@ -1 +1 @@
566cda1b26bbc5980e3e19f804ae500bf029fe6f5a503cfd609be6f6ad4409ea KSwitcher-win-x64.zip
e363ed0f3eaae5b893f05734194bcf3f74f79bd93d373c0be4e631579c6fe8b4 KSwitcher-win-x64.zip
+76 -76
View File
@@ -1,166 +1,166 @@
{
"version": "0.6.119",
"schema": 1,
"files": [
{
"size": 2479104,
"path": "KSwitcher.exe",
"sha256": "e6b98679ac0a460e42ec9f593e88cc802cedaaaf887bce79c3f8577419143aa1"
"size": 2431488,
"sha256": "e48f79af357cbf98b993678164ae02a340da0640831d4087fb428dab1dca81ac",
"path": "KSwitcher.exe"
},
{
"size": 2458112,
"path": "KSwitcher.Config.exe",
"sha256": "43e4ea0d087d70658fd2cca47b2f06b919eb86acc65dce1afa7db1e02cbdcded"
"size": 2457600,
"sha256": "59b11034a4671c3db921db86138ace31565860363583dc15261252356de2a4f5",
"path": "KSwitcher.Config.exe"
},
{
"size": 3060224,
"path": "KSwitcher.Screenshot.exe",
"sha256": "9b791b2dbf623f50ab92cde4017b07c9f8df4bbb7ac3526d0d18e0d770061f43"
"size": 3397632,
"sha256": "d6dbaa721ff896b3ec1c3101dab75b81a63a0c3c1e5c57cfe9d84e52f1d821c7",
"path": "KSwitcher.Screenshot.exe"
},
{
"size": 4370944,
"path": "KSwitcher.Files.exe",
"sha256": "e44a923d3e686e0e273e6dd167f6bd66dafd66e2870b4950fcbd8824d286a61d"
"size": 4403712,
"sha256": "69c95a3135878d8974e144ef630ec7cf53df43a61e7243482642fc721b6eadcb",
"path": "KSwitcher.Files.exe"
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"path": "WebView2Loader.dll"
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"path": "terminal/addon-fit-LICENSE.txt"
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"path": "terminal/addon-fit.js"
},
{
"size": 527,
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"path": "terminal/index.html"
},
{
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"path": "terminal/markdown-it-LICENSE.txt"
},
{
"size": 100786,
"path": "terminal/markdown-it.js",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"path": "terminal/markdown-it.js"
},
{
"size": 3635,
"path": "terminal/markdown.html",
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79"
"size": 3599,
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
"path": "terminal/markdown.html"
},
{
"size": 16944,
"path": "terminal/markdown.js",
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8"
"size": 17575,
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
"path": "terminal/markdown.js"
},
{
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"path": "terminal/mermaid-LICENSE.txt"
},
{
"size": 5537838,
"path": "terminal/mermaid.js",
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"path": "terminal/mermaid.js"
},
{
"size": 5065,
"path": "terminal/terminal.js",
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"path": "terminal/terminal.js"
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"path": "terminal/xterm-LICENSE.txt"
},
{
"size": 7112,
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"path": "terminal/xterm.css"
},
{
"size": 488663,
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"path": "terminal/xterm.js"
},
{
"size": 4401,
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"path": "LICENSE"
},
{
"size": 1096,
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"path": "json-LICENSE.txt"
},
{
"size": 883,
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"path": "files-text-license.txt"
},
{
"size": 95317,
"path": "README.md",
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8"
"size": 101324,
"sha256": "74e79e56a1ed04a6a617d626aedbf4c0a20e9dc83cd1c42d787244c1b48c5330",
"path": "README.md"
},
{
"size": 11577,
"path": "LAN-PREVIEW.md",
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
"size": 12354,
"sha256": "a2521642266d88eb5a2e579b8c514eecb63b0586e09dac2bbeea964df92b2474",
"path": "LAN-PREVIEW.md"
},
{
"size": 732485,
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"path": "dictionaries/en.txt"
},
{
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
},
{
"size": 2265,
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"path": "dictionaries/README.md"
},
{
"size": 1109134,
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"path": "dictionaries/ru.txt"
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"path": "dictionaries/sources.json"
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"path": "dictionaries/uk.txt"
},
{
"size": 993,
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"path": "tools/README.txt"
},
{
"size": 133120,
"path": "tools/StayHere.exe",
"sha256": "d689b74a0c5ba018d3f26eb32c4fab88a8404627ee69be1e326d60b1167b5667"
"size": 134656,
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
"path": "tools/StayHere.exe"
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"path": "tools/StayHere-README.md"
}
]
],
"schema": 1,
"version": "0.7.2"
}
+3 -1
View File
@@ -107,10 +107,12 @@ try {
if ($LASTEXITCODE) { throw 'Test build failed' }
& .\build\KSwitcherTests.exe
if ($LASTEXITCODE) { throw 'Tests failed' }
& $compiler @common tests/input.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe
& $compiler @common tests/input.cpp tests/input_pause.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe
if ($LASTEXITCODE) { throw 'Input test build failed' }
& .\build\KSwitcherInputTests.exe
if ($LASTEXITCODE) { throw 'Input tests failed' }
& .\build\KSwitcherInputTests.exe --input-pause
if ($LASTEXITCODE) { throw 'Tray pause/resume test failed' }
& $compiler @common tests/chat_profiles.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe
if ($LASTEXITCODE) { throw 'Chat profile test build failed' }
& .\build\KSwitcherChatProfileTests.exe
+4 -3
View File
@@ -2,6 +2,7 @@
#include <windows.h>
#include "resource.h"
IDI_KSWITCHER ICON "kswitcher.ico"
IDI_KSWITCHER_PAUSED ICON "kswitcher-paused.ico"
#ifdef KS_SCREENSHOT_RESOURCES
IDI_SCREENSHOT_QUESTION ICON "icons/question.ico"
IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
@@ -9,8 +10,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,6,119,0
PRODUCTVERSION 0,6,119,0
FILEVERSION 0,7,2,0
PRODUCTVERSION 0,7,2,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -20,7 +21,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.6.119"
VALUE "FileVersion", "0.7.2"
END
END
BLOCK "VarFileInfo"
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+1
View File
@@ -4,4 +4,5 @@
#define IDI_FILES_VIEWER 103
#define IDI_FILES_EDITOR 104
#define IDI_FILES_COMPARE 105
#define IDI_KSWITCHER_PAUSED 106
#define IDC_SCREENSHOT_PENCIL 500
-1
View File
@@ -52,6 +52,5 @@ figure svg .edgeLabel rect { fill: Canvas !important; opacity: 1 !important; str
</nav>
<main></main>
<script src="markdown-it.js"></script>
<script src="mermaid.js"></script>
<script src="markdown.js"></script>
</html>
+24 -8
View File
@@ -18,14 +18,28 @@ let activeMatch = -1;
let taskMarkers = new WeakMap();
let pendingTask;
let previewRevision = 0;
let mermaidReady;
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
function loadMermaid() {
mermaidReady ??= new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'mermaid.js';
script.onload = resolve;
script.onerror = () => reject(new Error('Could not load Mermaid'));
document.head.append(script);
}).then(() => {
const renderer = window.mermaid;
renderer.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
return renderer;
});
return mermaidReady;
}
markdown.core.ruler.after('inline', 'task_lists', ({ tokens, src, env }) => {
const lines = src.split('\n');
@@ -254,7 +268,9 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
for (const [index, block] of blocks.entries()) {
try {
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
const renderer = await loadMermaid();
if (current !== generation) return;
const { svg } = await renderer.render('diagram-' + current + '-' + index, block.textContent);
if (current !== generation) return;
const figure = document.createElement('figure');
figure.innerHTML = svg;
+470 -117
View File
@@ -143,6 +143,16 @@ ULONG_PTR snippetReplayMarker()
return reinterpret_cast<ULONG_PTR>(&marker);
}
constexpr int OpenFiles = 25, FilesHotkeyFirst = 0x4B10, FilesHotkeySecond = 0x4B11;
constexpr int ToggleInputProcessing = 26;
constexpr int ShortcutProbeId = FilesHotkeySecond + 1;
constexpr UINT_PTR PauseDrainTimer = 23;
bool shortcutAvailable(HWND window, Hotkey key)
{
if (!RegisterHotKey(window, ShortcutProbeId, key.modifiers | MOD_NOREPEAT, key.key)) return false;
UnregisterHotKey(window, ShortcutProbeId);
return true;
}
bool activateFilesWindow()
{
@@ -200,6 +210,14 @@ std::vector<std::wstring> buildSnippetVariants(const std::wstring &trigger, cons
}
return variants;
}
bool snippetWordCharacter(wchar_t character)
{
WORD type{};
if (character == L'_' ||
(GetStringTypeW(CT_CTYPE1, &character, 1, &type) && (type & (C1_ALPHA | C1_DIGIT))))
return true;
return GetStringTypeW(CT_CTYPE3, &character, 1, &type) && (type & (C3_NONSPACING | C3_VOWELMARK));
}
size_t caretSteps(std::wstring text)
{
size_t n = 0;
@@ -225,6 +243,28 @@ std::wstring newlines(std::wstring text)
}
return out;
}
bool canTypeSnippetText(const std::wstring &text)
{
return std::all_of(text.begin(), text.end(), [](wchar_t ch) { return ch >= L' ' && ch != L'\x7f'; });
}
bool typeSnippetText(const std::wstring &text, const std::function<bool()> &valid)
{
constexpr size_t batchSize = 64;
for (size_t offset = 0; offset < text.size(); offset += batchSize)
{
std::vector<INPUT> inputs;
for (wchar_t ch : std::wstring_view(text).substr(offset, batchSize))
for (DWORD flags : {DWORD{0}, DWORD{KEYEVENTF_KEYUP}})
{
auto input = keyboardInput(0, flags | KEYEVENTF_UNICODE);
input.ki.wScan = ch;
inputs.push_back(input);
}
if (!valid() || SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT)) != inputs.size())
return false;
}
return valid();
}
// Every transaction checks input, foreground and clipboard ownership before replacing text.
class Transaction
{
@@ -259,9 +299,8 @@ class Transaction
try
{
auto started = GetTickCount64();
const bool image = IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"));
snapshot.capture(app.window, expected);
const bool image = clipboardHasImage();
expected = snapshot.capture(app.window, expected);
if (expected != GetClipboardSequenceNumber())
throw std::runtime_error("Clipboard changed while taking snapshot");
diagnosticEvent(L"Clipboard snapshot captured: elapsedMs=" +
@@ -292,9 +331,7 @@ class Transaction
if (captured && clipboardModified && GetClipboardSequenceNumber() == expected)
try
{
auto started = GetTickCount64();
app.ownSequence = snapshot.restore(app.window, expected);
diagnosticEvent(L"Clipboard snapshot restored: elapsedMs=" + std::to_wstring(GetTickCount64() - started));
restoreClipboard();
}
catch (...)
{
@@ -339,6 +376,13 @@ class Transaction
expected = now;
}
}
void restoreClipboard()
{
const auto started = GetTickCount64();
clipboardModified = false;
app.ownSequence = snapshot.restore(app.window, expected);
diagnosticEvent(L"Clipboard snapshot restored: elapsedMs=" + std::to_wstring(GetTickCount64() - started));
}
void write(const Clip &c)
{
check();
@@ -535,12 +579,16 @@ class Transaction
farSelectedSteps = 0;
return valid() && chord(VK_LEFT);
}
while (farSelectedSteps && valid())
return narrowFarSelection(0);
}
bool narrowFarSelection(size_t count)
{
while (farSelectedSteps > count && valid())
{
if (!chord(VK_RIGHT, MOD_ALT | MOD_SHIFT)) return false;
--farSelectedSteps;
}
return !farSelectedSteps && valid();
return farSelectedSteps == count && valid();
}
std::optional<std::wstring> readFarSnippet(size_t count)
{
@@ -549,6 +597,21 @@ class Transaction
if (!finishSelection(false) || observed.empty()) return {};
return observed;
}
std::optional<bool> farSnippetWordBoundary(std::wstring_view trigger)
{
// Select to the beginning of Far's input line in one operation, then
// use the copied prefix to find the preceding character and restore the range.
if (!valid() || !chord(VK_HOME, MOD_ALT | MOD_SHIFT)) return {};
const auto context = copy();
if (!valid() || !context.ends_with(trigger)) return {};
if (context == trigger) return true;
const auto triggerSteps = farSelectedSteps;
farSelectedSteps = caretSteps(context);
if (snippetWordCharacter(context[context.size() - trigger.size() - 1]))
return false;
if (!narrowFarSelection(triggerSteps) || copy() != trigger || !valid()) return {};
return true;
}
std::wstring copyRange(size_t count, const std::wstring &wordCandidate,
const std::function<bool(const std::wstring &)> &matches,
const std::function<bool(const std::wstring &)> &suffixMatches = {})
@@ -690,6 +753,20 @@ class Transaction
content.substr(LOWORD(range), original.size()) == original;
}
};
bool placeSnippetCursor(Transaction &tx, const std::wstring &suffix)
{
if (suffix.empty()) return tx.valid();
if (!tx.select(caretSteps(suffix))) return false;
const auto selected = tx.copy();
if (!tx.valid()) return false;
if (newlines(selected) != newlines(suffix))
{
tx.finishSelection(false);
return false;
}
return tx.finishSelection(true);
}
} // namespace
App::App(HINSTANCE h, bool test, const std::filesystem::path &dataRoot, HWND service)
: historyService(service), instance(h), smoke(test)
@@ -728,7 +805,7 @@ App::App(HINSTANCE h, bool test, const std::filesystem::path &dataRoot, HWND ser
}
App::~App()
{
if (filesHotkeyId) UnregisterHotKey(window, filesHotkeyId);
releaseInputHooks();
if (snippetPopup) DestroyWindow(snippetPopup);
lanService.reset();
stopBrowserChatMonitor();
@@ -738,10 +815,6 @@ App::~App()
if (syncWorker.joinable()) syncWorker.join();
if (updateWorker.joinable())
updateWorker.join();
if (keyboardHook)
UnhookWindowsHookEx(keyboardHook);
if (mouseHook)
UnhookWindowsHookEx(mouseHook);
{
std::lock_guard lock(jobsMutex);
stop = true;
@@ -862,31 +935,150 @@ void App::report(const std::wstring &text)
}
constexpr UINT_PTR TrayRetryTimer = 20;
constexpr UINT TrayRetryIntervalMs = 1000;
constexpr UINT_PTR TrayInputTimer = 22;
constexpr UINT TrayInputPulseMs = 450;
void App::addTray()
namespace
{
HICON trayInputIcon(HICON base, int width, int height, uint32_t color)
{
if (!base || width < 8 || height < 8) return nullptr;
BITMAPINFO bitmapInfo{};
bitmapInfo.bmiHeader = {sizeof(BITMAPINFOHEADER), width, -height, 1, 32, BI_RGB};
void *bits{};
HBITMAP bitmap = CreateDIBSection(nullptr, &bitmapInfo, DIB_RGB_COLORS, &bits, nullptr, 0);
if (!bitmap) return nullptr;
HDC dc = CreateCompatibleDC(nullptr);
HICON icon{};
if (dc)
{
auto previous = SelectObject(dc, bitmap);
auto pixels = static_cast<uint32_t *>(bits);
std::fill_n(pixels, size_t(width) * height, 0);
if (DrawIconEx(dc, 0, 0, base, width, height, 0, nullptr, DI_NORMAL))
{
GdiFlush();
const int radius = std::max(3, MulDiv(std::min(width, height), 3, 16));
const int cx = width - 1 - radius, cy = height - 1 - radius;
for (int y = -radius; y <= radius; ++y)
for (int x = -radius; x <= radius; ++x)
{
const int distance = x * x + y * y;
if (distance <= radius * radius)
pixels[(cy + y) * width + cx + x] = distance <= (radius - 1) * (radius - 1)
? color : 0xff242424;
}
// The 32-bit DIB supplies the transparency. The fallback mask is initialized as well.
std::vector<unsigned char> maskBits(size_t((width + 15) / 16) * 2 * height);
if (auto mask = CreateBitmap(width, height, 1, 1, maskBits.data()))
{
ICONINFO info{TRUE, 0, 0, mask, bitmap};
icon = CreateIconIndirect(&info);
DeleteObject(mask);
}
}
SelectObject(dc, previous);
DeleteDC(dc);
}
DeleteObject(bitmap);
return icon;
}
}
HICON App::trayBaseIcon(int width, int height) const
{
const auto resource = inputState == InputState::Active ? IDI_KSWITCHER : IDI_KSWITCHER_PAUSED;
return static_cast<HICON>(LoadImageW(instance, MAKEINTRESOURCEW(resource), IMAGE_ICON, width, height, LR_SHARED));
}
bool App::updateTray(DWORD action)
{
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = window;
icon.uID = 1;
icon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP;
icon.uFlags = NIF_ICON | NIF_TIP | NIF_SHOWTIP;
if (action == NIM_ADD) icon.uFlags |= NIF_MESSAGE;
icon.uCallbackMessage = TrayMessage;
icon.hIcon = (HICON)LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED);
auto tip = incomingLanFileCount ? L"KSwitcher — files ready to save: " + std::to_wstring(incomingLanFileCount)
: localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
const int width = GetSystemMetrics(SM_CXSMICON), height = GetSystemMetrics(SM_CYSMICON);
icon.hIcon = trayBaseIcon(width, height);
HICON badge{};
auto tip = localBuildTitle(L"KSwitcher");
const auto state = inputState.load();
tip += state == InputState::Active ? L" — Input processing active" :
state == InputState::Paused ? L" — Input processing paused" : L" — Pausing input processing…";
if (state == InputState::Active && trayInput.paired)
{
const bool reconnecting = trayInput.reconnecting();
const uint32_t color = trayInput.stopped ? 0xfff16b66 : !trayInput.online ? 0xffa0a4ab :
!reconnecting ? 0xff45d58c : trayInputPulse ? 0xffffc457 : 0xffac7830;
badge = trayInputIcon(icon.hIcon, width, height, color);
if (badge) icon.hIcon = badge;
tip += L"\nMouse & keyboard: ";
if (trayInput.stopped) tip += L"connection stopped";
else if (!trayInput.online) tip += L"all paired PCs offline. Waiting for LAN discovery.";
else
{
tip += reconnecting ? L"reconnecting" : L"connected";
if (trayInput.connected < trayInput.paired)
tip += L" (" + std::to_wstring(trayInput.connected) + L"/" +
std::to_wstring(trayInput.paired) + L" PCs connected)";
}
}
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
if (Shell_NotifyIconW(NIM_ADD, &icon))
const bool updated = Shell_NotifyIconW(action, &icon) != FALSE;
if (badge) DestroyIcon(badge);
return updated;
}
void App::refreshTrayInput()
{
const auto state = lanService ? lanService->inputConnections() : LanInputConnections{};
if (state == trayInput) return;
trayInput = state;
trayInputPulse = true;
if (state.reconnecting())
SetTimer(window, TrayInputTimer, TrayInputPulseMs, nullptr);
else
KillTimer(window, TrayInputTimer);
updateTray(NIM_MODIFY);
}
void App::addTray()
{
if (updateTray(NIM_ADD))
{
KillTimer(window, TrayRetryTimer);
trayRetryPending = false;
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = window;
icon.uID = 1;
icon.uVersion = NOTIFYICON_VERSION_4;
Shell_NotifyIconW(NIM_SETVERSION, &icon);
}
else if (!trayRetryPending)
{
trayRetryPending = SetTimer(window, TrayRetryTimer, TrayRetryIntervalMs, nullptr) != 0;
}
icon.uVersion = NOTIFYICON_VERSION_4;
Shell_NotifyIconW(NIM_SETVERSION, &icon);
}
bool App::installInputHooks()
{
keyboardHook = SetWindowsHookExW(WH_KEYBOARD_LL, keyProc, instance, 0);
if (keyboardHook) mouseHook = SetWindowsHookExW(WH_MOUSE_LL, mouseProc, instance, 0);
if (keyboardHook && mouseHook) return true;
registrationWarning = lastError(L"Keyboard and mouse interception could not start");
releaseInputHooks();
return false;
}
void App::releaseInputHooks()
{
if (filesHotkeyId) UnregisterHotKey(window, std::exchange(filesHotkeyId, 0));
registeredFilesHotkey = {};
hookBindings.clear();
if (keyboardHook) UnhookWindowsHookEx(std::exchange(keyboardHook, nullptr));
if (mouseHook) UnhookWindowsHookEx(std::exchange(mouseHook, nullptr));
}
bool App::registerHotkeys(const Settings &s, bool rollback)
{
std::vector<std::pair<int, Hotkey>> bindings;
@@ -908,7 +1100,7 @@ bool App::registerHotkeys(const Settings &s, bool rollback)
const int next = filesHotkeyId == FilesHotkeyFirst ? FilesHotkeySecond : FilesHotkeyFirst;
if (files.key && !RegisterHotKey(window, next, files.modifiers | MOD_NOREPEAT, files.key))
{
if (!rollback) registrationWarning = L"The KSwitcher Files shortcut is unavailable. Choose another shortcut.";
if (!rollback) registrationWarning = L"The KSwitcher Files shortcut (" + *s.filesHotkey + L") is unavailable.";
return false;
}
if (filesHotkeyId) UnregisterHotKey(window, filesHotkeyId);
@@ -921,13 +1113,28 @@ bool App::registerHotkeys(const Settings &s, bool rollback)
Bytes App::lanCommand(const Bytes &command)
{
if (!lanService) lanService = std::make_unique<LanService>(data,window);
if (!lanService)
{
lanService = std::make_unique<LanService>(data,window,inputState != InputState::Active);
if (!smoke) lanService->startClients();
}
auto reply = lanService->command(command);
if (lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
else KillTimer(window, 7);
updateLanInputTimer();
if (lanService->takeInputChange()) resetLanInput();
refreshTrayInput();
return reply;
}
void App::updateLanInputTimer()
{
if (lanService && lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
else KillTimer(window, 7);
}
void App::pollLanInput()
{
// Temporary text transactions only block new handoffs. A tray pause removes
// the router entirely, including for already queued network notifications.
if (lanService && lanService->tickInput(!busy && !suspended && !hotkeyCapture)) resetLanInput();
}
void App::applySettings(const Settings &requested)
{
applySettings(requested, true);
@@ -1004,7 +1211,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation)
}
predictor.configure(std::filesystem::path(executable()).parent_path() / L"dictionaries", s.autoLanguages);
}
if (!registerHotkeys(s))
if (inputState == InputState::Active && !registerHotkeys(s))
{
registerHotkeys(settings, true);
throw std::runtime_error(utf8(registrationWarning));
@@ -1028,7 +1235,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation)
catch (...)
{
}
registerHotkeys(settings, true);
if (inputState == InputState::Active) registerHotkeys(settings, true);
throw;
}
{
@@ -1072,7 +1279,7 @@ void App::reloadLayouts()
++inputVersion;
if (busy) diagnosticEvent(L"Input context changed: layouts reloaded version=" + std::to_wstring(inputVersion.load()));
}
registerHotkeys(settings);
if (inputState == InputState::Active) registerHotkeys(settings);
}
void App::clearHistory()
{
@@ -1231,7 +1438,16 @@ void App::matchSnippets(HWND fg, bool expandExact)
trigger = sn.trigger;
}
if (expandExact && std::any_of(variants.begin(), variants.end(), [&](const auto &trigger) {
return keys.ends_with(trigger);
if (!keys.ends_with(trigger)) return false;
// A fresh key run can start inside existing text. The editor
// verifies the boundary before expansion even when this check passes.
if (keys.size() == trigger.size()) return true;
const auto layout = std::find_if(layouts.begin(), layouts.end(), [&](const auto &candidate) {
return candidate.handle == run.layout && candidate.convertible;
});
const auto previous = keys[keys.size() - trigger.size() - 1];
return layout == layouts.end() ||
!snippetWordCharacter(layout->at(physicalLayout().code(previous)));
}))
{
queueSnippet(fg, i, sn.trigger.size());
@@ -1261,7 +1477,7 @@ bool App::queueSnippet(HWND target, size_t index, size_t length, HWND editor)
typingTarget = target;
snippetPending = static_cast<int>(index);
snippetPendingLength = length;
snippetPendingEditor = editor;
snippetPendingEditor = editor ? editor : snippetGuiInfo(target).hwndFocus;
snippetTyping = true;
busy = true;
if (PostMessageW(window, SnippetMessage, index, static_cast<LPARAM>(inputVersion.load())))
@@ -1391,7 +1607,8 @@ void App::selectSnippet(size_t row)
}
bool App::handleSnippetKey(DWORD vk, UINT mods)
{
const bool accept = vk == VK_TAB || (vk == VK_RETURN && snippetNavigated);
const bool accept = vk == VK_TAB ||
(vk == VK_RETURN && (snippetNavigated || snippetMatches.size() == 1));
if (mods || (!accept && vk != VK_UP && vk != VK_DOWN && vk != VK_ESCAPE) ||
!snippetPopup || !IsWindowVisible(snippetPopup) || !snippetPopupCurrent())
return false;
@@ -1472,7 +1689,8 @@ void App::switchChatLayout(bool reverse)
enqueue([this, target, key, cycle, available, reverse, profileSettings = settings]
{
struct Reset { std::atomic<bool> &busy; ~Reset() { busy = false; } } reset{busy};
auto valid = [&] { return GetForegroundWindow() == target && windowLanguageProfileKey(profileSettings, target) == key; };
auto valid = [&] { return inputState == InputState::Active && GetForegroundWindow() == target &&
windowLanguageProfileKey(profileSettings, target) == key; };
if (key.starts_with(L"telegram-web\n") && readChromeChat(target) != key) return;
if (!valid()) return;
auto next = nextChatLayout(cycle, available, windowLayout(target), reverse);
@@ -1483,7 +1701,7 @@ bool App::handleKeyboard(const KBDLLHOOKSTRUCT &key, bool down, UINT mods)
{
// Filter before capture, hotkey latching and typing history. External injected
// down AND up events use exactly the same path as physical keyboard input.
if (ownKeyboardInput(key) || installingUpdate)
if (inputState != InputState::Active || ownKeyboardInput(key) || installingUpdate)
return false;
if (key.vkCode < snippetKeys.size() && snippetKeys[key.vkCode])
{
@@ -1626,7 +1844,7 @@ void App::replayTyping()
}
LRESULT CALLBACK App::keyProc(int code, WPARAM wp, LPARAM lp)
{
if (code == HC_ACTION && current && current->lanService &&
if (code == HC_ACTION && current && current->inputState == InputState::Active && current->lanService &&
(wp == WM_KEYDOWN || wp == WM_SYSKEYDOWN || wp == WM_KEYUP || wp == WM_SYSKEYUP))
{
bool consumed = current->lanService->keyboard(*(KBDLLHOOKSTRUCT *)lp, wp == WM_KEYDOWN || wp == WM_SYSKEYDOWN);
@@ -1881,7 +2099,7 @@ void App::dispatchMouseActions()
LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp)
{
if (code == HC_ACTION && current)
if (code == HC_ACTION && current && current->inputState == InputState::Active)
{
auto &app = *current;
const auto &mouse = *reinterpret_cast<const MSLLHOOKSTRUCT *>(lp);
@@ -1946,8 +2164,9 @@ LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp)
const bool restricted = ownWindow || shellSurface || name.empty();
wchar_t targetClass[64]{};
if (ownWindow) GetClassNameW(target, targetClass, std::size(targetClass));
const bool testButton = ownWindow && (hit == GetDlgItem(target, 737) ||
wcscmp(targetClass, L"KSwitcher.AddMouseEvent") == 0);
const bool testButton = ownWindow &&
((wcscmp(targetClass, L"KSwitcher.Settings") == 0 && GetDlgCtrlID(hit) == 737) ||
wcscmp(targetClass, L"KSwitcher.AddMouseEvent") == 0);
const auto *fallback = restricted ? effectiveMouseAction(app.settings, L"", event, false) : nullptr;
const auto *restrictedAction = isMouseVolumeAction(fallback) ? fallback : globalLaunch ? global : nullptr;
const bool eligible = target && !testButton && (!restricted || (event >= 2 && restrictedAction)) &&
@@ -2075,7 +2294,7 @@ void App::dispatch(int command)
}
void App::transform(int command, int snippet, size_t snippetLength, HWND snippetEditor)
{
if (installingUpdate) return;
if (installingUpdate || inputState != InputState::Active) return;
const auto attempt = ++transformAttempt;
const auto requestedAt = GetTickCount64();
HWND target = GetForegroundWindow();
@@ -2207,6 +2426,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
{"command", transformCommandName(command)}, {"source", layout(text.empty() ? hint : detect(text, layouts, hint))}, {"target", layout(to)},
{"outcome", utf8(reason)}, {"verification", utf8(verification)},
{"problem", reason != L"Paste verified" && reason != L"layout-only" &&
reason != L"snippet-inside-word" &&
!(command == 0 && reason == L"paste-sent-unverified")},
{"elapsedMs", GetTickCount64() - start}, {"verificationMs", verificationMs},
{"foregroundSame", GetForegroundWindow() == target},
@@ -2230,7 +2450,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
};
for (int i = 0; i < 8 && !modifiersReleased(); ++i)
Sleep(10);
if (!modifiersReleased() && command == AutoCorrect)
if (!valid() || (!modifiersReleased() && command == AutoCorrect))
return;
if (!modifiersReleased())
releaseModifiers();
@@ -2299,6 +2519,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
std::to_wstring(recent.at ? start - recent.at : 0) +
L" id=" + std::to_wstring(attempt));
bool automatic = false;
Template snippetTemplate;
if (command == AutoCorrect)
{
// The editor must select the complete previous word. Unlike manual
@@ -2367,15 +2588,20 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
if (snippet >= (int)config.snippets.size() || recent.window != target)
return;
const auto &sn = config.snippets[snippet];
if (!snippetAppPriority(sn, processName(target))) return;
const auto process = lower(processName(target));
if (!snippetAppPriority(sn, process)) return;
const auto length = snippetLength ? snippetLength : sn.trigger.size();
if (recent.keys.size() < length)
return;
result = parseTemplate(sn.text).text;
snippetTemplate = parseTemplate(sn.text);
const auto end = snippetTemplate.actions.empty() ? snippetTemplate.text.size() :
snippetTemplate.actions.front().offset;
result = snippetTemplate.text.substr(0, end);
// A multiline clipboard paste can execute a console command
// before readback. Only explicit, verified {enter} may do so.
if (farSnippet && (result.empty() || result.find_first_of(L"\r\n") != result.npos ||
caretSteps(result) > 4096))
// before readback. Explicit key actions run after verification.
if (farSnippet && (snippetTemplate.text.empty() ||
snippetTemplate.text.find_first_of(L"\r\n") != result.npos ||
caretSteps(snippetTemplate.text) > 4096))
{
reason = L"far-snippet-template-unsupported";
return;
@@ -2489,11 +2715,13 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
}
bool sent = false;
const bool requireReadback = tx.recoveredSelection() || snippet >= 0;
const bool verifySelection = snippet >= 0 || (requireReadback && result != text);
auto probeStarted = GetTickCount64();
PasteProbe probe(!farSnippet && ((config.writeLog && manual) || requireReadback) && result != text, text, target);
PasteProbe probe(!farSnippet && (verifySelection || (config.writeLog && manual && result != text)),
text, target, snippet >= 0);
verificationMs = GetTickCount64() - probeStarted;
diagnosticEvent(L"Paste probe prepared: elapsedMs=" + std::to_wstring(verificationMs) + L" status=" + probe.status);
if (requireReadback && !farSnippet && result != text && probe.status != L"ready")
if (!farSnippet && verifySelection && probe.status != L"ready")
{
verification = probe.status;
reason = snippet >= 0 ? L"snippet-verification-unavailable" : L"recovered-selection-unavailable";
@@ -2502,10 +2730,38 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
run.reset();
return;
}
if (snippet >= 0)
{
std::optional<bool> boundary;
if (farSnippet)
boundary = tx.farSnippetWordBoundary(text);
else if (const auto &preceding = probe.precedingCharacter)
boundary = preceding->empty() || !snippetWordCharacter(preceding->back());
if (!boundary.value_or(false))
{
reason = boundary ? L"snippet-inside-word" : L"snippet-word-boundary-unavailable";
return;
}
}
diagnosticEvent(L"Conversion source=" + std::to_wstring(hint) + L" target=" + std::to_wstring(to) +
L" changed=" + std::to_wstring(result != text));
const auto cursor = snippetTemplate.text.size() - snippetTemplate.suffix.size();
auto cursorSuffix = [&](size_t start, size_t end) {
return cursor >= start && cursor < end ?
snippetTemplate.text.substr(cursor, end - cursor) : std::wstring{};
};
const bool ordered = snippet >= 0 && result.size() < snippetTemplate.text.size();
const bool typeFirst = ordered && !farSnippet && canTypeSnippetText(result);
bool clipboardRestored = false;
if (result != text && typeFirst && cursor >= result.size())
{
tx.check();
tx.restoreClipboard();
clipboardRestored = true;
suspended = false;
}
if (result != text)
sent = tx.paste(textClip(result));
sent = typeFirst ? typeSnippetText(result, valid) : tx.paste(textClip(result));
else if (automatic && tx.valid())
tx.finishSelection(false);
if (requireReadback && result != text && !sent)
@@ -2525,7 +2781,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
reason = L"Conversion unchanged";
verification = L"calculated-result-equals-original";
}
if (sent && ((manual && config.writeLog) || requireReadback))
if (sent && !typeFirst && ((manual && config.writeLog) || requireReadback))
{
verification = probe.status;
if (tx.valid())
@@ -2590,27 +2846,62 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
}
if (snippet >= 0 && sent && tx.valid())
{
tx.check();
auto t = parseTemplate(config.snippets[snippet].text);
if (!t.suffix.empty())
{
if (!tx.select(caretSteps(t.suffix))) return;
auto suffix = tx.copy();
if (!tx.valid()) return;
if (newlines(suffix) != newlines(t.suffix))
{
tx.finishSelection(false);
return;
}
if (!tx.finishSelection(true)) return;
}
// Action markers run after insertion and cursor placement,
// before any physical typing buffered during expansion.
for (int i = 0; i < t.enters && tx.valid(); ++i)
size_t emitted = result.size();
if (!clipboardRestored)
{
tx.check();
if (!chord(VK_RETURN)) break;
if (!placeSnippetCursor(tx, cursorSuffix(0, emitted))) return;
if (!snippetTemplate.actions.empty())
{
tx.check();
// Clipboard shortcuts read and change the user's clipboard.
tx.restoreClipboard();
suspended = false;
}
}
auto insertSegment = [&](size_t end)
{
if (end == emitted) return true;
if (!tx.valid()) return false;
const auto segment = snippetTemplate.text.substr(emitted, end - emitted);
const auto suffix = cursorSuffix(emitted, end);
if (!farSnippet && canTypeSnippetText(segment) && suffix.empty())
{
if (!typeSnippetText(segment, valid)) return false;
}
else
{
Transaction segmentTx(*this, target, version, farSnippet, snippetEditor);
if (!segmentTx.paste(textClip(segment)) || !segmentTx.valid()) return false;
const auto count = caretSteps(segment);
const auto actual = farSnippet ? segmentTx.readFarSnippet(count) : probe.read(static_cast<int>(count));
if (!actual || !segmentTx.valid() || newlines(*actual) != newlines(segment) ||
!placeSnippetCursor(segmentTx, suffix))
return false;
}
emitted = end;
return true;
};
for (const auto &action : snippetTemplate.actions)
{
if (!tx.valid()) return;
if (!insertSegment(action.offset)) return;
if (const auto *keys = std::get_if<std::vector<WORD>>(&action.value))
{
if (!chord(*keys))
throw std::runtime_error("Windows could not send all snippet keys");
}
else
{
const auto deadline = GetTickCount64() + std::get<DWORD>(action.value);
for (auto now = GetTickCount64(); now < deadline; now = GetTickCount64())
{
if (!tx.valid()) return;
Sleep(static_cast<DWORD>(std::min<ULONGLONG>(deadline - now, 15)));
}
}
}
if (!insertSegment(snippetTemplate.text.size())) return;
}
if (to >= 0 && config.switchLayout && tx.valid() && (sent || result == text))
{
@@ -2631,6 +2922,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
void App::pasteEntry(std::wstring id, bool plain)
{
if (historyService) { remoteHistory("paste", id, plain); return; }
if (inputState != InputState::Active) { report(L"Resume input processing in the tray to paste from history."); return; }
if (installingUpdate) return;
if (!history || busy.exchange(true))
return;
@@ -2754,9 +3046,7 @@ void App::captureHistory()
if(sequence==GetClipboardSequenceNumber())publishClipboard(std::move(clip),app);
return;
}
if (IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
IsClipboardFormatAvailable(CF_BITMAP) ||
IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")))
if (clipboardHasImage())
{
if (history->captureImage(sequence, app, config))
{
@@ -2831,6 +3121,65 @@ void App::recognizeEntry(std::wstring id)
}
});
}
void App::toggleInputProcessing()
{
if (inputState == InputState::Pausing) return;
if (inputState == InputState::Active)
{
inputState = InputState::Pausing;
// Some hook shortcuts intentionally override shell-owned combinations.
// Detect new Windows registrations across the pause without rejecting those.
availableBeforePause.clear();
for (const auto &binding : hookBindings)
if (shortcutAvailable(window, binding.second)) availableBeforePause.push_back(binding.second);
releaseInputHooks();
resetLanInput();
mousePresses = {};
KillTimer(window, MouseClickTimer);
for (size_t i = 0; i < mousePresses.size(); ++i) KillTimer(window, FirstMouseVolumeTimer + i);
PostMessageW(window, MouseVolumeReleasedMessage, 0, 0);
hideSnippetPopup();
if (lanService) lanService->setInputPaused(true);
KillTimer(window, 8);
stopBrowserChatMonitor();
// Cancel the worker via inputVersion. Its normal completion path restores
// the clipboard and handles any typing already buffered before the pause.
if (busy) SetTimer(window, PauseDrainTimer, 50, nullptr);
else inputState = InputState::Paused;
}
else
{
// Discard deliveries queued for the previous hook/registration before
// acquiring shortcuts again, even if Windows reuses a registration ID.
MSG stale{};
while (PeekMessageW(&stale, window, WM_HOTKEY, WM_HOTKEY, PM_REMOVE)) {}
try
{
if (!installInputHooks() || !registerHotkeys(settings))
throw std::runtime_error(utf8(registrationWarning));
for (const auto &[id, key] : hookBindings)
if (std::find(availableBeforePause.begin(), availableBeforePause.end(), key) != availableBeforePause.end() &&
!shortcutAvailable(window, key))
throw std::runtime_error(utf8(L"The shortcut " + key.format() + L" is now in use."));
if (!smoke) startBrowserChatMonitor();
if (lanService) lanService->setInputPaused(false);
}
catch (const std::exception &e)
{
releaseInputHooks();
stopBrowserChatMonitor();
if (lanService) lanService->setInputPaused(true);
report(wide(e.what()) + L" Input remains paused. Retry from the tray when ready.");
return;
}
inputState = InputState::Active;
if (!smoke) SetTimer(window, 8, 250, nullptr);
}
updateLanInputTimer();
refreshTrayInput();
updateTray(NIM_MODIFY);
}
void App::trayMenu()
{
constexpr int utilityCommandBase = 1000;
@@ -2838,6 +3187,10 @@ void App::trayMenu()
auto utilities = discoverUtilities(std::filesystem::path(executable()).parent_path() / L"tools", utilitiesError);
if (utilities.size() > 50000) utilities.resize(50000);
HMENU menu = CreatePopupMenu();
AppendMenuW(menu, MF_STRING | (inputState == InputState::Pausing ? MF_GRAYED : 0), ToggleInputProcessing,
inputState == InputState::Active ? L"Pause &input processing" :
inputState == InputState::Paused ? L"Resume &input processing" : L"Pausing input processing…");
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
AppendMenuW(menu, MF_STRING, 10, L"Clipboard &history");
AppendMenuW(menu, MF_STRING, 24, L"&Capture screen region…");
AppendMenuW(menu, MF_STRING, 11, L"&Settings…");
@@ -2868,7 +3221,7 @@ void App::trayMenu()
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
AppendMenuW(menu, MF_STRING, 16, L"&About KSwitcher");
AppendMenuW(menu, MF_STRING, 17, L"E&xit");
POINT pt;
POINT pt{};
GetCursorPos(&pt);
pasteTarget = GetForegroundWindow();
SetForegroundWindow(window);
@@ -2894,6 +3247,9 @@ void App::trayMenu()
}
switch (cmd)
{
case ToggleInputProcessing:
toggleInputProcessing();
break;
case OpenFiles:
dispatch(OpenFiles);
break;
@@ -3094,6 +3450,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
return 0;
}
case WM_HOTKEY:
if (app->inputState != InputState::Active || wp == ShortcutProbeId) return 0;
if (app->filesHotkeyId && wp == static_cast<WPARAM>(app->filesHotkeyId))
{
if(!activateFilesWindow()) app->dispatch(OpenFiles);
@@ -3119,10 +3476,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
return 0;
case TrayMessage:
if (LOWORD(lp) == NIN_BALLOONUSERCLICK)
{
if (std::exchange(app->incomingFileBalloon, false)) app->dispatch(20);
else showLogs(*app);
}
showLogs(*app);
else if (LOWORD(lp) == WM_CONTEXTMENU)
app->trayMenu();
else if (LOWORD(lp) == WM_LBUTTONDBLCLK)
@@ -3138,7 +3492,8 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case AutoCorrectMessage:
if (app->autoPending)
{
if (!app->installingUpdate && !app->snippetTyping && app->settings.autoCorrect && app->inputVersion.load() == (uint64_t)wp)
if (app->inputState == InputState::Active && !app->installingUpdate && !app->snippetTyping &&
app->settings.autoCorrect && app->inputVersion.load() == (uint64_t)wp)
app->transform(AutoCorrect);
else
app->replayTyping();
@@ -3147,7 +3502,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case SnippetMessage:
if (app->snippetPending == (int)wp)
{
if (!app->installingUpdate && app->inputVersion.load() == (uint64_t)lp &&
if (app->inputState == InputState::Active && !app->installingUpdate && app->inputVersion.load() == (uint64_t)lp &&
(!app->snippetPendingEditor || GetForegroundWindow() == app->typingTarget))
app->transform(0, (int)wp, app->snippetPendingLength, app->snippetPendingEditor);
else
@@ -3194,30 +3549,12 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
wcsncpy_s(icon.szInfo, text->c_str(), _TRUNCATE);
wcscpy_s(icon.szInfoTitle, L"KSwitcher");
icon.dwInfoFlags = NIIF_WARNING;
app->incomingFileBalloon = false;
Shell_NotifyIconW(NIM_MODIFY, &icon);
return 0;
}
case LanFilesChangedMessage:
{
app->incomingLanFileCount = wp;
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = hwnd;
icon.uID = 1;
icon.uFlags = NIF_TIP | NIF_SHOWTIP;
auto tip = wp ? L"KSwitcher — files ready to save: " + std::to_wstring(wp)
: localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
if (lp)
{
icon.uFlags |= NIF_INFO;
wcscpy_s(icon.szInfoTitle, L"Incoming file ready to save");
wcscpy_s(icon.szInfo, L"Open Settings → Computers → Manage computers → Incoming files.");
icon.dwInfoFlags = NIIF_INFO;
}
if (Shell_NotifyIconW(NIM_MODIFY, &icon) && lp) app->incomingFileBalloon = true;
case LanInputStatusMessage:
app->refreshTrayInput();
return 0;
}
case CheckAutostartMessage:
app->checkAutostartPath();
return 0;
@@ -3247,9 +3584,22 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
case LanClipboardReadyMessage: app->receiveClipboard();return 0;
case LanInputReadyMessage:
if(app->lanService&&app->lanService->tickInput(!app->busy&&!app->suspended&&!app->hotkeyCapture))app->resetLanInput();
app->pollLanInput();
return 0;
case WM_TIMER:
if (wp == PauseDrainTimer)
{
if (!app->busy)
{
KillTimer(hwnd, PauseDrainTimer);
if (app->inputState == InputState::Pausing)
{
app->inputState = InputState::Paused;
app->updateTray(NIM_MODIFY);
}
}
return 0;
}
if (wp == SnippetPopupTimer)
{
if (!app->snippetPopupCurrent()) app->hideSnippetPopup();
@@ -3260,6 +3610,15 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
if (app->trayRetryPending) app->addTray();
return 0;
}
if (wp == TrayInputTimer)
{
if (app->trayInput.reconnecting())
{
app->trayInputPulse = !app->trayInputPulse;
app->updateTray(NIM_MODIFY);
}
return 0;
}
if (wp == MouseClickTimer) { app->flushMouseClicks(); return 0; }
if (wp >= FirstMouseVolumeTimer && wp < FirstMouseVolumeTimer + std::size(MouseButtonNames))
{
@@ -3268,7 +3627,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
if (wp == 8)
{
if (app->settings.appLanguageSets.empty() || app->busy || app->installingUpdate) return 0;
if (app->inputState != InputState::Active || app->settings.appLanguageSets.empty() || app->busy || app->installingUpdate) return 0;
app->refreshChatContext();
if (!app->activeChat.starts_with(L"app\n")) return 0;
auto cycle = chatCycle(app->settings, app->activeChat, app->layouts);
@@ -3282,13 +3641,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
if (wp == 7)
{
if (app->lanService)
{
// suspended also guards clipboard/text transactions (correction,
// conversion, snippets). Those must not disconnect remote input.
// Actual system suspension is handled by WM_POWERBROADCAST.
if (app->lanService->tickInput(!app->busy && !app->suspended && !app->hotkeyCapture)) app->resetLanInput();
}
app->pollLanInput();
return 0;
}
if (wp == 6)
@@ -3326,7 +3679,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
PostMessageW(hwnd, WM_CLOSE, 0, 0);
return 0;
}
if (app->settings.awake)
if (wp == 1 && app->inputState == InputState::Active && app->settings.awake)
{
LASTINPUTINFO idle{sizeof(idle)};
if (GetLastInputInfo(&idle) && DWORD(GetTickCount() - idle.dwTime) >= 180000)
@@ -3422,8 +3775,6 @@ int App::execute()
}
return int(message.wParam);
}
keyboardHook = SetWindowsHookExW(WH_KEYBOARD_LL, keyProc, instance, 0);
mouseHook = SetWindowsHookExW(WH_MOUSE_LL, mouseProc, instance, 0);
const bool useDefaultFilesHotkey = !settings.filesHotkey;
if (useDefaultFilesHotkey)
{
@@ -3435,27 +3786,29 @@ int App::execute()
});
settings.filesHotkey = conflict ? L"" : L"Ctrl+Alt+F";
}
if (!registerHotkeys(settings) && settings.filesHotkey && !settings.filesHotkey->empty())
if (!installInputHooks())
inputState = InputState::Paused;
else if (!registerHotkeys(settings) && settings.filesHotkey && !settings.filesHotkey->empty())
{
if (useDefaultFilesHotkey) settings.filesHotkey = L"";
auto fallback = settings;
fallback.filesHotkey = L"";
registerHotkeys(fallback, true);
}
if (!keyboardHook || !mouseHook)
report(L"Input tracking could not start. Automatic recent-text conversion is unavailable.");
AddClipboardFormatListener(window);
// Resume pending OCR, including older images without a saved OCR state.
scheduleHistoryOcr(settings);
addTray();
if (!smoke) startBrowserChatMonitor();
if (!smoke && std::filesystem::exists(data / L"lan-pairing.bin"))
try { lanService = std::make_unique<LanService>(data,window); }
if (!smoke && inputState == InputState::Active) startBrowserChatMonitor();
if (!smoke && (std::filesystem::exists(data / L"lan-pairing.bin") ||
std::filesystem::exists(data / L"lan-clients.bin")))
try { lanService = std::make_unique<LanService>(data,window,inputState != InputState::Active); lanService->startClients(); }
catch (const std::exception &e) { report(L"LAN module: " + wide(e.what())); }
if (lanService && lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
updateLanInputTimer();
refreshTrayInput();
SetTimer(window, 1, 60000, nullptr);
if (!smoke) SetTimer(window, 6, 1000, nullptr);
if (!smoke) SetTimer(window, 8, 250, nullptr);
if (!smoke && inputState == InputState::Active) SetTimer(window, 8, 250, nullptr);
SetThreadExecutionState(ES_CONTINUOUS |
(settings.awake ? (ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED) : 0));
if (!registrationWarning.empty())
+13 -2
View File
@@ -110,6 +110,13 @@ class App
void checkAutostartPath();
bool checkingAutostartPath{};
HHOOK keyboardHook{}, mouseHook{};
enum class InputState { Active, Pausing, Paused };
std::atomic<InputState> inputState{InputState::Active};
bool installInputHooks();
void releaseInputHooks();
void toggleInputProcessing();
void updateLanInputTimer();
void pollLanInput();
struct MousePress
{
HWND target{};
@@ -161,14 +168,18 @@ class App
bool stop{};
UINT taskbarCreated{};
bool trayRetryPending{};
LanInputConnections trayInput;
bool trayInputPulse{};
HICON trayBaseIcon(int width, int height) const;
bool updateTray(DWORD action);
void refreshTrayInput();
uint64_t transformAttempt{}, previousAttemptVersion{};
size_t incomingLanFileCount{};
bool incomingFileBalloon{};
std::atomic<uint64_t> activeTransformAttempt{};
ULONGLONG previousAttemptAt{};
HWND previousAttemptWindow{};
int previousAttemptCommand{}, repeatAttempts{};
std::vector<std::pair<int, Hotkey>> hookBindings;
std::vector<Hotkey> availableBeforePause;
Hotkey registeredFilesHotkey{};
int filesHotkeyId{};
HotkeyHook hotkeyHook;
+4 -3
View File
@@ -229,16 +229,17 @@ int runConfigurator(HINSTANCE instance, bool snippets, bool logs)
MSG message;
while ((app.settingsWindow || app.snippetsWindow || app.logWindow) && GetMessageW(&message, nullptr, 0, 0) > 0)
{
if (app.settingsWindow && !IsWindowEnabled(app.settingsWindow))
const auto editor = app.settingsWindow ? app.settingsWindow : app.snippetsWindow;
if (editor && !IsWindowEnabled(editor))
{
HWND popup = GetLastActivePopup(app.settingsWindow);
HWND popup = GetLastActivePopup(editor);
while (!IsWindowEnabled(popup))
{
HWND next = GetLastActivePopup(popup);
if (next == popup) break;
popup = next;
}
if (popup != app.settingsWindow && IsDialogMessageW(popup, &message)) continue;
if (popup != editor && IsDialogMessageW(popup, &message)) continue;
}
if (app.settingsWindow && IsDialogMessageW(app.settingsWindow, &message)) continue;
if (app.snippetsWindow && IsDialogMessageW(app.snippetsWindow, &message)) continue;
+170 -60
View File
@@ -319,40 +319,6 @@ std::wstring transliterate(const std::wstring &text)
}
return out;
}
Template parseTemplate(const std::wstring &text)
{
Template t;
size_t cursor = std::wstring::npos;
for (size_t i = 0; i < text.size();)
{
if (text.compare(i, 9, L"{{enter}}") == 0)
{
t.text += L"{enter}";
i += 9;
}
else if (text.compare(i, 7, L"{enter}") == 0)
{
++t.enters;
i += 7;
}
else if (text.compare(i, 10, L"{{cursor}}\0", 10) == 0)
{
t.text += L"{cursor}";
i += 10;
}
else if (text.compare(i, 8, L"{cursor}") == 0)
{
cursor = t.text.size();
++t.cursors;
i += 8;
}
else
t.text += text[i++];
}
if (cursor != text.npos)
t.suffix = t.text.substr(cursor);
return t;
}
namespace
{
const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
@@ -377,7 +343,176 @@ const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
{VK_DIVIDE, L"Divide"}, {VK_DECIMAL, L"Decimal"}};
return names;
}
WORD namedKey(const std::wstring &token)
{
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
return upper(token)[0];
if (token.size() == 4 && token.starts_with(L"num") && token[3] >= L'0' && token[3] <= L'9')
return VK_NUMPAD0 + token[3] - L'0';
if (token.size() >= 2 && token[0] == L'f')
{
wchar_t *tail{};
long n = wcstol(token.c_str() + 1, &tail, 10);
if (!*tail && n >= 1 && n <= 24) return static_cast<WORD>(VK_F1 + n - 1);
return 0;
}
for (const auto &[key, name] : namedKeys())
if (lower(name) == token) return static_cast<WORD>(key);
return 0;
}
WORD snippetKey(std::wstring_view name)
{
const auto token = lower(std::wstring(name));
static constexpr std::pair<std::wstring_view, WORD> modifiers[] = {
{L"shift", VK_LSHIFT}, {L"shiftl", VK_LSHIFT}, {L"shiftr", VK_RSHIFT},
{L"ctrl", VK_LCONTROL}, {L"ctrll", VK_LCONTROL}, {L"ctrlr", VK_RCONTROL},
{L"alt", VK_LMENU}, {L"altl", VK_LMENU}, {L"altr", VK_RMENU},
{L"win", VK_LWIN}, {L"winl", VK_LWIN}, {L"winr", VK_RWIN}};
for (const auto &[label, key] : modifiers)
if (label == token) return key;
if (token == L"return") return VK_RETURN;
// The old double-braced Enter marker is still an escape.
return token == L"enter" ? 0 : namedKey(token);
}
struct SnippetMarker
{
std::wstring_view name;
size_t length, depth;
};
std::optional<SnippetMarker> snippetMarker(std::wstring_view input)
{
if (!input.starts_with(L'{')) return {};
size_t depth = 1;
while (depth < 3 && depth < input.size() && input[depth] == L'{') ++depth;
const auto end = input.find_first_of(L"{}", depth);
if (end == input.npos || !input.substr(end).starts_with(std::wstring_view(L"}}}", depth)))
return {};
return SnippetMarker{input.substr(depth, end - depth), end + depth, depth};
}
std::optional<DWORD> snippetPause(std::wstring_view token)
{
constexpr std::wstring_view prefix = L"pause:";
constexpr DWORD maxPause = 10000;
if (!token.starts_with(prefix) || token.size() == prefix.size()) return {};
DWORD duration = 0;
for (wchar_t digit : token.substr(prefix.size()))
{
if (digit < L'0' || digit > L'9') return {};
duration = duration * 10 + (digit - L'0');
if (duration > maxPause) return {};
}
return duration;
}
} // namespace
std::wstring snippetKeyName(WORD key)
{
switch (key)
{
case VK_LSHIFT: return L"Shift";
case VK_RSHIFT: return L"ShiftR";
case VK_LCONTROL: return L"Ctrl";
case VK_RCONTROL: return L"CtrlR";
case VK_LMENU: return L"Alt";
case VK_RMENU: return L"AltR";
case VK_LWIN: return L"Win";
case VK_RWIN: return L"WinR";
default: return Hotkey{0, key}.format();
}
}
std::wstring formatSnippetInsertion(SnippetInsertion type, std::wstring_view parameter)
{
if (type == SnippetInsertion::Cursor) return L"{cursor}";
if (type == SnippetInsertion::Enter) return L"{enter}";
if (type == SnippetInsertion::Pause)
{
auto pause = L"pause:" + std::wstring(parameter);
return snippetPause(pause) ? L"{" + pause + L"}" : std::wstring{};
}
const bool chord = type == SnippetInsertion::Chord;
if (!chord && type != SnippetInsertion::Key) return {};
std::wstring text;
std::vector<WORD> keys;
while (true)
{
const auto end = parameter.find(L'+');
const auto token = parameter.substr(0, end);
const auto first = token.find_first_not_of(L" \t");
if (first == token.npos) return {};
auto name = lower(std::wstring(token.substr(first, token.find_last_not_of(L" \t") - first + 1)));
if (name == L"enter") name = L"return";
const auto key = snippetKey(name);
if (!key || std::find(keys.begin(), keys.end(), key) != keys.end()) return {};
keys.push_back(key);
if (!text.empty()) text += L'+';
text += L"{{" + name + L"}}";
if (end == parameter.npos) break;
if (!chord) return {};
parameter.remove_prefix(end + 1);
}
return chord && keys.size() < 2 ? std::wstring{} : text;
}
Template parseTemplate(const std::wstring &text)
{
Template t;
std::wstring_view remaining(text);
size_t cursor = text.npos;
while (!remaining.empty())
{
const auto marker = snippetMarker(remaining);
if (!marker)
{
t.text += remaining.front();
remaining.remove_prefix(1);
continue;
}
const auto [name, length, depth] = *marker;
const auto pause = depth <= 2 ? snippetPause(name) : std::nullopt;
const WORD key = depth >= 2 ? snippetKey(name) : 0;
const bool legacyEscape = name == L"cursor" || name == L"enter";
if (depth == 1 && name == L"cursor")
{
cursor = t.text.size();
++t.cursors;
}
else if (depth == 1 && name == L"enter")
t.actions.push_back({t.text.size(), std::vector<WORD>{VK_RETURN}});
else if (depth == 1 && pause)
t.actions.push_back({t.text.size(), *pause});
else if (depth == 2 && key)
{
std::vector<WORD> keys{key};
remaining.remove_prefix(length);
while (remaining.starts_with(L'+'))
{
const auto next = snippetMarker(remaining.substr(1));
if (!next || next->depth != 2) break;
const WORD nextKey = snippetKey(next->name);
if (!nextKey) break;
if (std::find(keys.begin(), keys.end(), nextKey) == keys.end())
keys.push_back(nextKey);
remaining.remove_prefix(1 + next->length);
}
t.actions.push_back({t.text.size(), std::move(keys)});
continue;
}
else if ((depth >= 2 && legacyEscape) || (depth == 2 && pause) || (depth == 3 && key))
t.text += remaining.substr(1, length - 2);
else
t.text += remaining.substr(0, length);
remaining.remove_prefix(length);
}
if (cursor != text.npos)
t.suffix = t.text.substr(cursor);
// A leading action has historically followed replacement of the trigger.
// Keep that behavior while allowing actions between text segments.
const auto first = std::find_if(t.actions.begin(), t.actions.end(),
[](const SnippetAction &action) { return action.offset != 0; });
const auto firstText = first == t.actions.end() ? t.text.size() : first->offset;
for (auto it = t.actions.begin(); it != first; ++it)
it->offset = firstText;
return t;
}
std::wstring Hotkey::format() const
{
if (!key)
@@ -423,32 +558,7 @@ std::optional<Hotkey> Hotkey::parse(std::wstring s)
h.modifiers |= MOD_WIN;
else
{
if (h.key)
return {};
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
h.key = upper(token)[0];
else if (token.size() == 4 && token.substr(0, 3) == L"num" && token[3] >= L'0' &&
token[3] <= L'9')
h.key = VK_NUMPAD0 + token[3] - L'0';
else if (token.size() >= 2 && token[0] == L'f')
{
wchar_t *tail{};
long n = wcstol(token.c_str() + 1, &tail, 10);
if (*tail || n < 1 || n > 24)
return {};
h.key = VK_F1 + (UINT)n - 1;
}
else
{
for (auto &[key, name] : namedKeys())
if (lower(name) == token)
{
h.key = key;
break;
}
if (!h.key)
return {};
}
if (h.key || !(h.key = namedKey(token))) return {};
}
if (end == s.npos)
break;
+11 -1
View File
@@ -5,6 +5,7 @@
#include <optional>
#include <set>
#include <string>
#include <variant>
#include <vector>
#include <windows.h>
@@ -42,13 +43,22 @@ std::wstring snippetAppName(std::wstring);
int snippetAppPriority(const Snippet &, const std::wstring &process);
std::wstring snippetId(const Snippet &);
std::wstring newSnippetId();
struct SnippetAction
{
size_t offset;
std::variant<std::vector<WORD>, DWORD> value;
bool operator==(const SnippetAction &) const = default;
};
struct Template
{
std::wstring text, suffix;
std::vector<SnippetAction> actions;
int cursors = 0;
int enters = 0;
};
Template parseTemplate(const std::wstring &);
enum class SnippetInsertion { Cursor, Enter, Pause, Key, Chord };
std::wstring snippetKeyName(WORD);
std::wstring formatSnippetInsertion(SnippetInsertion, std::wstring_view parameter);
struct Hotkey
{
UINT modifiers{}, key{};
+20 -7
View File
@@ -806,7 +806,7 @@ private:
bool uploadPending{};
bool switchAfterSave{};
FilesTerminalView preview;
bool previewWanted{}, previewVisible{};
bool previewWanted{}, previewVisible{}, previewRetried{};
ULONGLONG previewDeadline{};
ULONGLONG nextFileCheck{};
struct FileStamp
@@ -918,6 +918,7 @@ private:
bool needsSave() const;
bool canPreview() const;
void updatePreview();
bool startPreviewBrowser();
void stopPreview(bool refresh=true,bool keepBrowser=false);
void renderPreview(bool keepPosition=false);
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
@@ -1598,14 +1599,21 @@ void TextWindow::updatePreview()
return;
}
previewWanted=true;
previewDeadline=GetTickCount64()+8000;
previewRetried=false;
previewStamp=previewFileStamp();
nextFileCheck=GetTickCount64()+350;
cancelImages=std::make_shared<std::atomic<bool>>(false);
if(!SetTimer(window,previewTimer,50,nullptr)) { stopPreview(); return; }
if(preview.initialized()) renderPreview();
else if(!preview.create(window,[this](const auto &value){previewMessage(value);},
[this]{PostMessageW(window,previewFailed,0,0);},true,[this](UINT key)
else if(!startPreviewBrowser()) { stopPreview(); return; }
layout();
}
bool TextWindow::startPreviewBrowser()
{
previewDeadline=GetTickCount64()+8000;
return preview.create(window,[this](const auto &value){previewMessage(value);},
[this]{previewDeadline=GetTickCount64()+300;},true,[this](UINT key)
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
@@ -1628,9 +1636,7 @@ void TextWindow::updatePreview()
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0);
return true;
}))
stopPreview();
layout();
});
}
void TextWindow::stopPreview(bool refresh,bool keepBrowser)
@@ -2027,6 +2033,13 @@ void TextWindow::pollImages()
refreshPreview();
if(!previewVisible && GetTickCount64()>=previewDeadline)
{
if(!preview.initialized() && !previewRetried)
{
// The previous window's WebView2 process may still be shutting down.
previewRetried=true;
preview.close();
if(startPreviewBrowser()) return;
}
stopPreview();
return;
}
+212 -35
View File
@@ -9,6 +9,7 @@
#include "lan_layout.h"
#include "lan_network.h"
#include "lan_wake.h"
#include "lan_clients.h"
#include <atomic>
#include <mutex>
#include <thread>
@@ -110,7 +111,14 @@ void lan::wakeFilesPeer(const std::string &id)
struct LanService::Impl
{
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; };
struct Peer
{
std::string name,epoch;
sockaddr_in address{};
uint64_t seen{},verified{};
bool files{};
bool present(uint64_t now)const{return verified && now-verified<lan::PeerLifetime;}
};
std::filesystem::path path;
std::string id,epoch=lan::randomHex(16),name=hostName(),status="Disabled.";
std::map<std::string,Peer> peers;
@@ -127,9 +135,12 @@ struct LanService::Impl
std::mutex mutex;
std::thread worker;
bool shareInput{};
bool inputPaused{};
std::mutex transportMutex;
bool resetInputChannels{};
std::string inputPeer;
int inputEdge=1;
std::atomic<bool> inputConnected{false},abortInput{false};
std::atomic<bool> abortInput{false};
std::atomic<uint64_t> inputEpoch{0};
std::atomic<uint64_t> inputConfiguration{0};
std::atomic<bool> layoutChanged{false};
@@ -139,9 +150,13 @@ struct LanService::Impl
std::map<std::string,uint64_t> inputReady;
std::unique_ptr<lan::InputMesh> router;
std::string inputStatus="Input sharing disabled.";
size_t inputConnectedPeers{}, inputOnlinePeers{};
bool inputWorkerStopped{};
bool inputNeedsHelp{};
HWND inputWindow{};std::atomic<bool> inputNotification{false};
explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window)
lan::LanClients clients;
explicit Impl(const std::filesystem::path &root,HWND window,bool paused)
: path(root/L"lan-pairing.bin"),inputPaused(paused),inputWindow(window),clients(root)
{
if(std::filesystem::exists(path))
{
@@ -165,7 +180,105 @@ struct LanService::Impl
configureRouter();
if(enabled) start();
}
~Impl() { stop(); }
~Impl() { clients.stop(); stop(); }
void startClients()
{
clients.start([this](const Json &request, const auto &allowed, const auto &send) {
const auto action = request.at("action").get<std::string>();
auto reply = [&](const Json &result) {
const auto text = result.dump();
send(text.data(), DWORD(text.size()));
};
lan::FilesPeer target;
std::string local, key;
auto machines = Json::array();
{
std::lock_guard gate(commandGate);
std::lock_guard lock(mutex);
const auto now = GetTickCount64();
const auto reachable = [&](const Peer &peer) {
return enabled && peer.files && peer.verified && now - peer.verified < lan::PeerLifetime;
};
if (action == "peers")
{
refreshFiles = true;
for (const auto &[peer, pair] : trusted.items())
{
const auto found = peers.find(peer);
machines.push_back({{"id", peer}, {"name", pair.at("name")},
{"online", found != peers.end() && reachable(found->second)}});
}
}
else
{
if (action != "drives" && action != "list" && action != "download")
throw std::runtime_error("Unsupported LAN client operation.");
const auto peer = request.at("peer").get<std::string>();
const auto found = peers.find(peer);
if (!trusted.contains(peer) || found == peers.end() || !reachable(found->second))
throw std::runtime_error("The paired computer is offline or file browsing is unavailable.");
char address[INET_ADDRSTRLEN]{};
auto ip = found->second.address.sin_addr;
if (!InetNtopA(AF_INET, &ip, address, sizeof(address)))
throw std::runtime_error("The paired computer has no usable address.");
target = {peer, address, wide(found->second.name), lan::FilesPort, true};
local = id;
key = trusted.at(peer).at("key").get<std::string>();
}
}
if (action == "peers")
{
reply(machines);
return;
}
lan::FilesConnection connection(target, local, key);
if (action == "drives")
{
const auto result = connection.call({{"action", "drives"}});
lan::checkFileReply(result);
reply(result.at("drives"));
return;
}
const auto path = lan::filePath(request.at("path"));
if (action == "list")
{
auto page = connection.call(lan::fileRequest("list", path));
auto entries = Json::array();
size_t bytes{};
for (;;)
{
lan::checkFileReply(page);
for (auto &entry : page.at("entries"))
{
bytes += entry.dump().size() + 1;
if (bytes > 8 * 1024 * 1024) throw std::runtime_error("The remote directory listing is too large.");
entries.push_back(std::move(entry));
}
if (!page.at("more").get<bool>()) break;
allowed();
page = connection.call({{"action", "listNext"}});
}
reply(entries);
return;
}
const auto file = connection.call(lan::fileRequest("stat", path));
lan::checkFileReply(file);
auto open = lan::fileRequest("openRead", path);
open["size"] = file.at("size");
open["modified"] = file.at("modified");
lan::checkFileReply(connection.call(open));
reply({{"size", file.at("size")}});
for (;;)
{
allowed();
const auto chunk = connection.call({{"action", "read"}});
lan::checkFileReply(chunk);
const auto &data = chunk.at("data").get_binary();
send(data.data(), DWORD(data.size()));
if (data.empty()) break;
}
});
}
void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted},
{"shareInput",shareInput},{"shareLogs",shareLogs},{"inputPeer",inputPeer},{"inputEdge",inputEdge},{"positions",positions}}))); }
bool queue(const std::string &peer,lan::InputFrame frame)
@@ -183,13 +296,32 @@ struct LanService::Impl
{
if(router)router->cancel(GetTickCount64());
router.reset();++inputConfiguration;
if(enabled&&shareInput){
if(enabled&&shareInput&&!inputPaused){
std::map<std::string,POINT> layout;for(auto &[peer,cell]:positions.items())if(trusted.contains(peer))layout[peer]={cell[0].get<LONG>(),cell[1].get<LONG>()};
router=std::make_unique<lan::InputMesh>(id,lan::windowsInputEnvironment(),std::move(layout),[this](const auto &peer,auto f){return queue(peer,f);});
}
inputStatus=enabled&&shareInput?"Connecting input channels...":"Input sharing disabled.";
observedRevision=0;
}
void setInputPaused(bool paused)
{
// A poll can own a batch outside the queues. Finish that poll before
// cancelling the router and discarding both directions of the old session.
std::lock_guard transportLock(transportMutex);
std::lock_guard lock(mutex);
if (inputPaused == paused) return;
inputPaused = paused;
configureRouter();
if (paused)
{
resetInputChannels = true;
std::lock_guard queueLock(inputMutex);
inputIn.clear();
inputOut.clear();
inputReady.clear();
inputConnectedPeers = inputOnlinePeers = 0;
}
}
bool takeChange()
{
auto revision=router?router->revision():0;auto configuration=inputConfiguration.load();
@@ -212,6 +344,7 @@ struct LanService::Impl
void start()
{
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
updateInputStatus(0,0,"Waiting for paired computers...",false);
worker=std::thread([this]{ run(); });
}
void stop()
@@ -219,17 +352,38 @@ struct LanService::Impl
if(router)router->cancel(GetTickCount64());
stopping=true;
if(worker.joinable()) worker.join();
inputConnected=false;++inputEpoch;
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
std::lock_guard lock(mutex); pending.reset(); peers.clear();clipboard=std::make_unique<lan::ClipboardExchange>(id);
transfers=std::make_unique<lan::ClipboardExchange>(id,"file-transfer");incomingFiles.clear();logDownload.reset();
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,0,FALSE);
}
void updateInputStatus(size_t connected,size_t online,std::string status,bool needsHelp,bool stopped=false)
{
bool changed;
{
std::lock_guard lock(mutex);
changed=connected!=inputConnectedPeers||online!=inputOnlinePeers||stopped!=inputWorkerStopped;
inputConnectedPeers=connected;
inputOnlinePeers=online;
inputWorkerStopped=stopped;
inputStatus=std::move(status);
inputNeedsHelp=needsHelp;
}
if(changed&&inputWindow)PostMessageW(inputWindow,LanInputStatusMessage,0,0);
}
void send(SOCKET socket,const sockaddr_in &address,const Json &j)
{
auto bytes=j.dump(); if(bytes.size()>2048) return;
sendto(socket,bytes.data(),int(bytes.size()),0,(const sockaddr*)&address,sizeof(address));
}
Json discoveryAnnouncement(bool filesListening)const
{
auto hello=lan::envelope("hello",id);
hello["name"]=name;
hello["epoch"]=epoch;
hello["clipboardSession"]=clipboard->session();
hello["fileSession"]=transfers->session();
hello["filesBrowse"]=filesListening;
return hello;
}
std::string heartbeat(const std::string &from,const std::string &to,const std::string &a,const std::string &b)
{ return "KSwitcher LAN v1|presence|"+from+"|"+to+"|"+a+"|"+b; }
void receiveTransfers(uint64_t now)
@@ -241,10 +395,7 @@ struct LanService::Impl
auto end=std::find(item.bytes.begin(),item.bytes.end(),0);
if(end!=item.bytes.begin() && end!=item.bytes.end() && end-item.bytes.begin()<=1024 &&
item.bytes.end()-end-1<=16*1024*1024)
{
incomingFiles.push_back(std::move(item));
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),TRUE);
}
}
else if(item.app=="log-request" && item.bytes.size()==33)
{
@@ -267,7 +418,7 @@ struct LanService::Impl
}
transfers->deliveries.clear();
}
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now)
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now,bool filesListening)
{
if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return;
auto other=j.value("id",""); if(!lan::identifier(other)||other==id) return;
@@ -278,19 +429,23 @@ struct LanService::Impl
if(display.empty()||display.size()>128||!lan::identifier(session)||
std::any_of(display.begin(),display.end(),[](unsigned char c){return c<32||c==127;})) return;
// Discovery is untrusted and never grants input access.
if(!peers.contains(other) && peers.size()>=64) return;
const bool firstAnnouncement=!peers.contains(other);
if(firstAnnouncement && peers.size()>=64) return;
auto &peer=peers[other];
// A fresh announcement rotates the challenge every three seconds; it
// does not revoke a recent successful proof for the same address.
// Only a valid presence response renews verified, so untrusted/replayed
// announcements cannot extend its PeerLifetime expiry.
if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0;
const bool addressChanged=peer.address.sin_addr.s_addr!=address.sin_addr.s_addr;
if(addressChanged) peer.verified=0;
clipboard->peerSession(other,j.value("clipboardSession",""));
transfers->peerSession(other,j.value("fileSession",""));
peer.files=j.value("filesBrowse",false);
peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now;
if(trusted.contains(other))
{
// A returning peer can prove presence right away using our current challenge.
if(firstAnnouncement) send(socket,address,discoveryAnnouncement(filesListening));
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
const auto &key=trusted[other].at("key");
const auto challenge=heartbeat(id,other,epoch,session);
@@ -408,14 +563,17 @@ struct LanService::Impl
if(peers.contains(target))send(socket,peers.at(target).address,packet);
});
clipboardActive=clipboard->active()||transfers->active();
if(shareInput)for(auto &[peer,entry]:trusted.items())
endpoints.push_back({peer,entry.at("key"),peers.contains(peer)?peers.at(peer).address.sin_addr.s_addr:0});
if(shareInput&&!inputPaused)for(auto &[peer,entry]:trusted.items())
{
const auto found=peers.find(peer);
const bool discovered=found!=peers.end()&&found->second.present(now);
endpoints.push_back({.id=peer,.key=entry.at("key"),
.address=discovered?found->second.address.sin_addr.s_addr:0,.discovered=discovered});
}
if(refreshFiles.exchange(false) || now>=nextHello)
{
epoch=lan::randomHex(16); // Fresh challenge prevents replayed presence from staying online.
auto hello=lan::envelope("hello",id); hello["name"]=name; hello["epoch"]=epoch;hello["clipboardSession"]=clipboard->session();
hello["fileSession"]=transfers->session();
hello["filesBrowse"]=filesListening;
const auto hello=discoveryAnnouncement(filesListening);
for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); }
nextHello=now+3000;
}
@@ -431,10 +589,17 @@ struct LanService::Impl
}
}
std::vector<lan::RoutedInput> out,in;
std::unique_lock transportLock(transportMutex);
if (resetInputChannels)
{
hub.poll({}, {}, in, now);
resetInputChannels = false;
}
if (inputPaused) endpoints.clear();
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
hub.poll(endpoints,out,in,now);
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
auto readyPeers=hub.ready();const auto connected=readyPeers.size();
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
for(auto &frame:in){
if(!inputIn.empty()&&inputIn.back().peer==frame.peer&&inputIn.back().epoch==frame.epoch){
@@ -447,8 +612,11 @@ struct LanService::Impl
}
if(!in.empty()&&inputWindow&&!inputNotification.exchange(true))
if(!PostMessageW(inputWindow,LanInputReadyMessage,0,0))inputNotification=false;
{std::lock_guard lock(mutex);inputStatus=hub.status();inputNeedsHelp=hub.needsHelp();}
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,!endpoints.empty()||clipboardActive?5000:100000};
const auto online=hub.onlinePeers();
updateInputStatus(connected,online,online||endpoints.empty()?hub.status():
"All paired PCs are offline. Waiting for LAN discovery.",hub.needsHelp());
transportLock.unlock();
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,online||clipboardActive?5000:100000};
int ready=select(0,&read,nullptr,nullptr,&delay);
if(ready==SOCKET_ERROR) throw std::runtime_error("LAN discovery socket failed.");
if(ready>0) for(int count=0;count<64;++count)
@@ -461,17 +629,18 @@ struct LanService::Impl
auto j=Json::parse(buffer,buffer+received);
if(j.value("type","")=="input-udp"){
bool allowed=false;auto peer=j.value("id","");
{std::lock_guard lock(mutex);allowed=shareInput&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
{std::lock_guard lock(mutex);allowed=shareInput&&!inputPaused&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
if(allowed)hub.receiveDatagram(j,GetTickCount64());
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64());}
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64(),filesListening);}
}
catch(const Json::exception &) {} // Malformed network data cannot interrupt discovery.
}
}
}
catch(const std::exception &e) { std::lock_guard lock(mutex); status=std::string("LAN stopped: ")+e.what(); }
inputConnected=false;++inputEpoch;
{std::lock_guard lock(mutex);if(shareInput)inputStatus="Input connection closed.";}
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
++inputEpoch;
updateInputStatus(0,0,"Input connection closed.",false,true);
if(socket!=INVALID_SOCKET) closesocket(socket);
if(winsock) WSACleanup();
}
@@ -480,6 +649,8 @@ struct LanService::Impl
{
std::lock_guard commandLock(commandGate);
auto j=Json::parse(input); auto action=j.value("action","status");
if (action == "trustedClients" || action == "trustClient" || action == "removeClient")
return encoded(clients.settings(action, j));
if(action=="enable")
{
stop();
@@ -503,8 +674,7 @@ struct LanService::Impl
{
auto peer=j.at("peer").get<std::string>();
const auto checkPeer = [&] {
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
now-peers.at(peer).verified>=lan::PeerLifetime)
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).present(now))
throw std::runtime_error("Select an online paired computer.");
if(!transfers->hasSession(peer))
throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers.");
@@ -574,7 +744,6 @@ struct LanService::Impl
found=findFile();
}
if(found!=incomingFiles.end()) incomingFiles.erase(found);
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
}
if(action=="position")
{
@@ -621,15 +790,14 @@ struct LanService::Impl
trusted.erase(peer);positions.erase(peer);if(trusted.empty())shareInput=false;
try{save();}catch(...){trusted=std::move(oldTrusted);positions=std::move(oldPositions);shareInput=oldSharing;throw;}
std::erase_if(incomingFiles,[&](const auto &file){return file.peer==peer;});
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
if(logDownload && logDownload->peer==peer)logDownload.reset();
if(pending&&pending->peer==peer)pending.reset();
configureRouter();
status="Pair removed on this computer.";
}
Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()},
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnected.load()},
{"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnectedPeers!=0},
{"inputStatus",inputPaused?"Input processing paused in the tray.":enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",!inputPaused&&enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
result["shareLogs"]=shareLogs;
result["files"]=Json::array();
@@ -649,7 +817,7 @@ struct LanService::Impl
if(action=="filesPeers" && !trusted.contains(peer)) continue;
char ip[INET_ADDRSTRLEN]{}; InetNtopA(AF_INET,(void*)&p.address.sin_addr,ip,sizeof(ip));
result["peers"].push_back({{"id",peer},{"name",p.name},{"address",ip},{"paired",trusted.contains(peer)},
{"verified",p.verified && now-p.verified<lan::PeerLifetime},{"online",true},
{"verified",p.present(now)},{"online",true},
{"fileTransfer",transfers->hasSession(peer)},{"filesBrowse",p.files}});
}
for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer))
@@ -657,9 +825,10 @@ struct LanService::Impl
return encoded(result);
}
};
LanService::LanService(const std::filesystem::path &path,HWND window) : impl(std::make_unique<Impl>(path,window)) {}
LanService::LanService(const std::filesystem::path &path,HWND window,bool paused) : impl(std::make_unique<Impl>(path,window,paused)) {}
LanService::~LanService()=default;
Bytes LanService::command(const Bytes &command) { return impl->command(command); }
void LanService::startClients() { impl->startClients(); }
bool LanService::clipboardEnabled()const
{
std::lock_guard lock(impl->mutex);
@@ -681,7 +850,15 @@ std::vector<LanClipboard> LanService::takeClipboard()
result.push_back({d.peer,impl->trusted.at(d.peer).at("name"),d.app,std::move(d.bytes),d.sequence});
impl->clipboard->deliveries.clear();return result;
}
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput;}
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput&&!impl->inputPaused;}
void LanService::setInputPaused(bool paused){impl->setInputPaused(paused);}
LanInputConnections LanService::inputConnections()const
{
std::lock_guard lock(impl->mutex);
if(!inputEnabled())return {};
const auto paired=impl->trusted.size();
return {std::min(impl->inputConnectedPeers,paired),std::min(impl->inputOnlinePeers,paired),paired,impl->inputWorkerStopped};
}
bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);}
bool LanService::keyboard(const KBDLLHOOKSTRUCT &k,bool down){return impl->router&&impl->router->keyboard(k,down,GetTickCount64());}
bool LanService::mouse(UINT message,const MSLLHOOKSTRUCT &m,bool allowEnter){return impl->router&&impl->router->mouse(message,m,GetTickCount64(),allowEnter);}
+12 -2
View File
@@ -5,22 +5,32 @@
namespace ks
{
inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69;
inline constexpr UINT LanFilesChangedMessage=WM_APP+70;
inline constexpr UINT LanUpdateRequestedMessage=WM_APP+90;
inline constexpr UINT LanInputStatusMessage=WM_APP+91;
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
struct LanInputConnections
{
size_t connected{}, online{}, paired{};
bool stopped{};
bool reconnecting()const{return !stopped&&connected<online;}
bool operator==(const LanInputConnections &) const = default;
};
// Discovery, pairing and optional encrypted input within the resident process.
class LanService
{
struct Impl;
std::unique_ptr<Impl> impl;
public:
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr);
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr, bool inputPaused=false);
~LanService();
Bytes command(const Bytes &);
void startClients();
bool clipboardEnabled() const;
void publishClipboard(Bytes, const std::string &);
std::vector<LanClipboard> takeClipboard();
bool inputEnabled() const;
void setInputPaused(bool);
LanInputConnections inputConnections() const;
bool tickInput(bool allowEnter = true);
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
bool mouse(UINT, const MSLLHOOKSTRUCT &, bool allowEnter);
+25 -11
View File
@@ -213,6 +213,7 @@ bool InputChannel::adopt(uintptr_t accepted,uint64_t now)
impl->connecting=false;impl->begin(now);impl->socket=SOCKET(accepted);return true;
}
bool InputChannel::ready()const{return impl->authenticated;}
bool InputChannel::handshaking()const{return impl->socket!=INVALID_SOCKET&&!impl->authenticated;}
uint64_t InputChannel::generation()const{return impl->changed;}
std::string InputChannel::status()const{
return impl->lastError.empty() ? impl->state : impl->lastError+" Retrying automatically.";
@@ -221,7 +222,16 @@ void InputChannel::disconnect(){impl->reset(GetTickCount64(),"Input disconnected
std::string InputChannel::transport()const{return impl->reverse?"reverse TCP":"direct TCP";}
struct InputHub::Impl
{
struct Link { InputEndpoint endpoint;std::unique_ptr<InputChannel> channel;std::unique_ptr<InputDatagram> udp;uint64_t generation{},epoch{},since{},failedSince{};bool udpReady{};std::string lastState; };
struct Link
{
InputEndpoint endpoint;
std::unique_ptr<InputChannel> channel;
std::unique_ptr<InputDatagram> udp;
uint64_t generation{},epoch{},since{},failedSince{};
bool udpReady{};
std::string lastState;
bool ready()const{return channel->ready()||udp->ready();}
};
struct Pending {SOCKET socket;uint32_t address;uint64_t since;};
std::string local;uint16_t port;SOCKET listener=INVALID_SOCKET;
std::map<std::string,Link> links;std::vector<Pending> pending;uint64_t epoch{},retry{};
@@ -235,17 +245,18 @@ struct InputHub::Impl
currentTime=now;
for(auto it=links.begin();it!=links.end();){
auto match=std::find_if(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id==it->first&&e.key==it->second.endpoint.key&&e.port==it->second.endpoint.port;});
if(match==endpoints.end())it=links.erase(it);else ++it;
// Discovery gates new attempts. An authenticated connection can outlive discovery.
if(match==endpoints.end()||(!match->discovered&&!it->second.ready()))it=links.erase(it);else ++it;
}
for(auto &e:endpoints)if(e.id!=local&&!links.contains(e.id)){
for(auto &e:endpoints)if(e.discovered&&e.id!=local&&!links.contains(e.id)){
Link link;link.endpoint=e;link.channel=std::make_unique<InputChannel>(local,e.id,e.key,0,e.port,true);
link.udp=std::make_unique<InputDatagram>(local,e.id,e.key);link.since=link.failedSince=now;link.epoch=++epoch;links.emplace(e.id,std::move(link));
}
// Discovery is a hint, not the lifetime of authenticated input sessions.
// Keep the last usable address across missed announcements. A new address
// is used only once a channel is down, never to tear down working input.
for(auto &e:endpoints){if(e.id==local)continue;auto &link=links.at(e.id);
if(e.address&&!link.channel->ready()&&e.address!=link.endpoint.address){
for(auto &e:endpoints){if(!e.discovered||e.id==local)continue;auto &link=links.at(e.id);
if(e.address&&!link.ready()&&e.address!=link.endpoint.address){
link.channel->disconnect();link.endpoint.address=e.address;
}
}
@@ -279,14 +290,16 @@ struct InputHub::Impl
}
for(auto &[id,link]:links){
std::vector<InputFrame> frames,received;for(auto &f:out)if(f.peer==id&&(!f.epoch||f.epoch==link.epoch))enqueueInput(frames,f.frame);
if(sendDatagram&&!link.channel->ready()&&!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);link.channel->disconnect();frames.clear();}
// Let an in-flight TCP connection finish or hit its own deadline.
// Check before poll() so another TCP retry cannot starve UDP fallback.
if(sendDatagram&&!link.channel->ready()&&!link.channel->handshaking()&&
!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);frames.clear();}
if(link.udp->active()){
link.udp->poll(frames,received,now,sendDatagram);
if(!link.udp->active()){link.since=now;link.channel->disconnect();received.clear();}
}else link.channel->poll(link.endpoint.address,frames,received,now);
if(link.udpReady!=link.udp->ready()){link.udpReady=link.udp->ready();link.epoch=++epoch;}
bool ready=link.channel->ready()||link.udp->ready();
if(ready)link.failedSince=link.since=now;
if(link.ready())link.failedSince=link.since=now;
auto state=link.udp->ready()?"Input connected via encrypted UDP.":link.udp->active()?"Trying encrypted UDP over discovery...":link.channel->ready()?"Input connected via "+link.channel->transport()+".":link.channel->status();
if(state!=link.lastState){link.lastState=state;log(L"LAN input peer "+wide(id.substr(0,8))+L": "+wide(state));}
if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;}
@@ -297,7 +310,8 @@ struct InputHub::Impl
InputHub::InputHub(std::string id,uint16_t port):impl(std::make_unique<Impl>(std::move(id),port)){}
InputHub::~InputHub()=default;
void InputHub::poll(const std::vector<InputEndpoint> &peers,const std::vector<RoutedInput> &out,std::vector<RoutedInput> &in,uint64_t now){impl->poll(peers,out,in,now);}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.channel->ready()||l.udp->ready())result[id]=l.epoch;return result;}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.ready())result[id]=l.epoch;return result;}
size_t InputHub::onlinePeers()const{return impl->links.size();}
std::string InputHub::status()const{
auto count=ready().size();if(count==impl->links.size()&&count){
std::string routes;for(auto &[id,l]:impl->links){if(!routes.empty())routes+=", ";routes+=id.substr(0,8)+": "+(l.udp->ready()?"encrypted UDP":l.channel->transport());}
@@ -305,7 +319,7 @@ std::string InputHub::status()const{
}
if(needsHelp())return "Automatic connection attempts have not succeeded for every PC. Enable input on both PCs. Open Connection help for firewall commands.";
if(!impl->error.empty())return impl->error;
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready())return l.lastState;
for(auto &[id,l]:impl->links)if(!l.ready())return l.lastState;
return "Waiting for paired computers...";
}
void InputHub::disconnect(){for(auto &[id,l]:impl->links){l.channel->disconnect();l.udp->reset();l.since=impl->currentTime;}}
@@ -318,7 +332,7 @@ void InputHub::receiveDatagram(const Json &j,uint64_t now){
if(!active&&link.udp->active())link.channel->disconnect();
}
bool InputHub::needsHelp()const{
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready()&&impl->currentTime-l.failedSince>=15000)return true;
for(auto &[id,l]:impl->links)if(!l.ready()&&impl->currentTime-l.failedSince>=15000)return true;
return false;
}
}
+9 -1
View File
@@ -55,12 +55,19 @@ class InputChannel
void poll(uint32_t peerAddress,const std::vector<InputFrame> &out,std::vector<InputFrame> &in,uint64_t now);
bool adopt(uintptr_t socket,uint64_t now);
bool ready() const;
bool handshaking() const;
uint64_t generation() const;
std::string status() const;
void disconnect();
std::string transport()const;
};
struct InputEndpoint {std::string id,key;uint32_t address{};uint16_t port=45884;};
struct InputEndpoint
{
std::string id,key;
uint32_t address{};
uint16_t port=45884;
bool discovered=true;
};
struct RoutedInput {std::string peer;InputFrame frame;uint64_t epoch{};};
class InputHub
{
@@ -70,6 +77,7 @@ class InputHub
~InputHub();
void poll(const std::vector<InputEndpoint> &,const std::vector<RoutedInput> &,std::vector<RoutedInput> &,uint64_t now);
std::map<std::string,uint64_t> ready()const;
size_t onlinePeers()const;
std::string status()const;
void disconnect();
using SendDatagram=std::function<void(const std::string &,const Json &)>;
+250
View File
@@ -0,0 +1,250 @@
#pragma once
#include "lan_pairing.h"
#include <bcrypt.h>
#include <sddl.h>
#include <array>
#include <functional>
#include <mutex>
#include <thread>
namespace ks::lan
{
class LanClients
{
struct Handle
{
HANDLE value{};
~Handle() { if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value); }
explicit operator bool() const { return value && value != INVALID_HANDLE_VALUE; }
};
struct ClientImage
{
Handle file;
std::wstring path;
std::string digest;
FILETIME modified{};
explicit ClientImage(const std::wstring &filename)
: file{CreateFileW(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, nullptr)}
{
if (!file || GetFileType(file.value) != FILE_TYPE_DISK)
throw std::runtime_error("Choose a readable executable.");
wchar_t finalPath[32768];
const auto length = GetFinalPathNameByHandleW(file.value, finalPath, DWORD(std::size(finalPath)), 0);
if (!length || length >= std::size(finalPath) ||
_wcsicmp(std::filesystem::path(std::wstring(finalPath, length)).extension().c_str(), L".exe") ||
!GetFileTime(file.value, nullptr, nullptr, &modified))
throw std::runtime_error("Choose a Windows .exe file.");
path.assign(finalPath, length);
struct Hash
{
BCRYPT_HASH_HANDLE handle{};
~Hash() { if (handle) BCryptDestroyHash(handle); }
} hash;
std::array<unsigned char, 65536> buffer{};
std::array<unsigned char, 32> bytes{};
if (BCryptCreateHash(BCRYPT_SHA256_ALG_HANDLE, &hash.handle, nullptr, 0, nullptr, 0, 0) < 0)
throw std::runtime_error("Could not fingerprint the executable.");
DWORD count{};
do
{
if (!ReadFile(file.value, buffer.data(), DWORD(buffer.size()), &count, nullptr) ||
(count && BCryptHashData(hash.handle, buffer.data(), count, 0) < 0))
throw std::runtime_error("Could not fingerprint the executable.");
} while (count);
if (BCryptFinishHash(hash.handle, bytes.data(), ULONG(bytes.size()), 0) < 0)
throw std::runtime_error("Could not fingerprint the executable.");
for (auto byte : bytes)
{
digest += "0123456789abcdef"[byte >> 4];
digest += "0123456789abcdef"[byte & 15];
}
}
};
const std::filesystem::path store;
mutable std::mutex storeMutex;
Handle stopped{CreateEventW(nullptr, TRUE, FALSE, nullptr)};
std::jthread thread;
bool io(HANDLE pipe, void *buffer, DWORD length, bool write) const
{
auto *cursor = static_cast<unsigned char *>(buffer);
while (length)
{
Handle event{CreateEventW(nullptr, TRUE, FALSE, nullptr)};
if (!event) return false;
OVERLAPPED op{};
op.hEvent = event.value;
DWORD count{};
const auto completed = write ? WriteFile(pipe, cursor, length, &count, &op) :
ReadFile(pipe, cursor, length, &count, &op);
if (!completed && (GetLastError() != ERROR_IO_PENDING || !wait(pipe, op, count, 10000))) return false;
if (!count) return false;
cursor += count;
length -= count;
}
return true;
}
bool wait(HANDLE pipe, OVERLAPPED &op, DWORD &count, DWORD timeout) const
{
const HANDLE events[]{stopped.value, op.hEvent};
if (WaitForMultipleObjects(2, events, FALSE, timeout) != WAIT_OBJECT_0 + 1)
{
CancelIoEx(pipe, &op);
GetOverlappedResult(pipe, &op, &count, TRUE);
return false;
}
return GetOverlappedResult(pipe, &op, &count, FALSE) != FALSE;
}
bool writeFrame(HANDLE pipe, const void *buffer, DWORD length) const
{
return io(pipe, &length, sizeof(length), true) &&
(!length || io(pipe, const_cast<void *>(buffer), length, true));
}
Json clients() const
{
return std::filesystem::exists(store) ? Json::parse(unprotect(readFile(store, 256 * 1024))) : Json::array();
}
using Rule = std::function<void()>;
Rule authorize(HANDLE pipe) const
{
ULONG pid{};
if (!GetNamedPipeClientProcessId(pipe, &pid))
throw std::runtime_error("Could not identify the local client.");
auto process = std::make_shared<Handle>();
process->value = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, pid);
wchar_t filename[32768];
DWORD length = DWORD(std::size(filename));
FILETIME started{}, exited{}, kernel{}, user{};
if (!*process || !QueryFullProcessImageNameW(process->value, 0, filename, &length) ||
!GetProcessTimes(process->value, &started, &exited, &kernel, &user))
throw std::runtime_error("Could not identify the local client.");
auto image = std::make_shared<ClientImage>(std::wstring(filename, length));
if (CompareFileTime(&image->modified, &started) > 0)
throw std::runtime_error("Restart the client after replacing its executable.");
Rule check = [this, process, image] {
if (WaitForSingleObject(stopped.value, 0) != WAIT_TIMEOUT ||
WaitForSingleObject(process->value, 0) != WAIT_TIMEOUT)
throw std::runtime_error("The local client disconnected.");
std::lock_guard lock(storeMutex);
for (const auto &entry : clients())
if (!_wcsicmp(wide(entry.at("path").get<std::string>()).c_str(), image->path.c_str()) &&
entry.at("sha256") == image->digest) return;
throw std::runtime_error("Authorize this executable in KSwitcher → Computers → Trusted clients.");
};
check();
return check;
}
struct LocalMemory
{
void *value{};
~LocalMemory() { if (value) LocalFree(value); }
};
using Send = std::function<void(const void *, DWORD)>;
using Route = std::function<void(const Json &, const Rule &, const Send &)>;
void serve(const Route &route, const std::wstring &instance) const
{
HANDLE rawToken{};
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &rawToken)) return;
Handle token{rawToken};
DWORD size{};
GetTokenInformation(token.value, TokenUser, nullptr, 0, &size);
Bytes info(size);
if (!size || !GetTokenInformation(token.value, TokenUser, info.data(), size, &size)) return;
LPWSTR sid{};
if (!ConvertSidToStringSidW(reinterpret_cast<TOKEN_USER *>(info.data())->User.Sid, &sid)) return;
LocalMemory sidOwner{sid};
const auto sddl = std::wstring(L"D:P(A;;GA;;;") + sid + L")";
PSECURITY_DESCRIPTOR descriptor{};
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(), SDDL_REVISION_1, &descriptor, nullptr)) return;
LocalMemory descriptorOwner{descriptor};
SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE};
DWORD session{};
if (!ProcessIdToSessionId(GetCurrentProcessId(), &session)) return;
const auto name = L"\\\\.\\pipe\\KSwitcher.LAN.Clients.v1." + std::to_wstring(session) + instance;
Handle pipe{CreateNamedPipeW(name.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_REJECT_REMOTE_CLIENTS, 1, 65536, 65536, 0, &security)};
if (!pipe) return;
while (WaitForSingleObject(stopped.value, 0) == WAIT_TIMEOUT)
{
Handle event{CreateEventW(nullptr, TRUE, FALSE, nullptr)};
if (!event) return;
OVERLAPPED op{};
op.hEvent = event.value;
DWORD count{};
if (!ConnectNamedPipe(pipe.value, &op))
{
const auto error = GetLastError();
if (error == ERROR_NO_DATA)
{
DisconnectNamedPipe(pipe.value);
continue;
}
if (error != ERROR_PIPE_CONNECTED &&
(error != ERROR_IO_PENDING || !wait(pipe.value, op, count, INFINITE))) return;
}
try
{
DWORD length{};
if (io(pipe.value, &length, sizeof(length), false) && length && length <= 16384)
{
std::string request(length, '\0');
if (io(pipe.value, request.data(), length, false))
{
auto check = authorize(pipe.value);
route(Json::parse(request), check, [&](const void *data, DWORD bytes) {
check();
if (!writeFrame(pipe.value, data, bytes)) throw std::runtime_error("The local client disconnected.");
});
}
}
}
catch (const std::exception &e)
{
const auto error = Json{{"error", e.what()}}.dump(-1, ' ', false, Json::error_handler_t::replace);
writeFrame(pipe.value, error.data(), DWORD(error.size()));
}
// Let the client consume the final response before recycling the pipe.
char acknowledgement{};
io(pipe.value, &acknowledgement, 1, false);
DisconnectNamedPipe(pipe.value);
}
}
public:
explicit LanClients(const std::filesystem::path &root) : store(root / L"lan-clients.bin") {}
~LanClients() { if (stopped) SetEvent(stopped.value); }
void start(Route route, std::wstring instance = {})
{
if (stopped) thread = std::jthread([this, route = std::move(route), instance = std::move(instance)] {
serve(route, instance);
});
}
void stop() { if (stopped) SetEvent(stopped.value); if (thread.joinable()) thread.join(); }
Json settings(const std::string &action, const Json &request) const
{
std::lock_guard lock(storeMutex);
auto entries = clients();
if (action == "trustedClients") return entries;
const auto path = wide(request.at("path").get<std::string>());
if (action == "trustClient")
{
ClientImage image(path);
std::erase_if(entries.get_ref<Json::array_t &>(), [&](const auto &entry) {
return !_wcsicmp(wide(entry.at("path").template get<std::string>()).c_str(), image.path.c_str());
});
if (entries.size() >= 64) throw std::runtime_error("The trusted client list is full.");
entries.push_back({{"path", utf8(image.path)}, {"sha256", image.digest}});
}
else
{
std::erase_if(entries.get_ref<Json::array_t &>(), [&](const auto &entry) {
return !_wcsicmp(wide(entry.at("path").template get<std::string>()).c_str(), path.c_str());
});
}
const auto text = entries.dump();
atomicWrite(store, protect(Bytes(text.begin(), text.end())));
return entries;
}
};
}
+16 -4
View File
@@ -211,9 +211,18 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
if(!connected||!env.desktop()){cancel(now);return;}
if(f.type==InputType::Enter)
{
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535||held()||returning||
mode_==ControlMode::Sending||mode_==ControlMode::Receiving||(mode_==ControlMode::Requesting&&preferLocal))
{post({InputType::Return,f.token,32768});return;}
const wchar_t *declined=nullptr;
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535)
declined=L"invalid edge or position";
else if(held())declined=L"a local key or mouse button is held";
else if(returning||mode_==ControlMode::Sending||mode_==ControlMode::Receiving||
(mode_==ControlMode::Requesting&&preferLocal))
declined=L"another handoff is active";
if(declined)
{
log(std::wstring(L"LAN input: declined cursor handoff: ")+declined);
post({InputType::Return,f.token,32768});return;
}
if(mode_==ControlMode::Requesting)cancel(now);
if(multi)edge=f.a^1;
crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
@@ -231,7 +240,10 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
return;
}
if(f.token!=token||!token)return;
if(f.type==InputType::Return){log(L"LAN input: peer returned control");local(now,std::clamp(f.a,0,65535));return;}
if(f.type==InputType::Return){
log(mode_==ControlMode::Requesting?L"LAN input: peer declined cursor handoff":L"LAN input: peer returned control");
local(now,std::clamp(f.a,0,65535));return;
}
if(mode_!=ControlMode::Receiving)return;
bool ok=true;
if(f.type==InputType::Move)
+1
View File
@@ -50,6 +50,7 @@ class InputMesh
if(!ready.contains(peer)||!positions.contains(peer))return;
if(f.type==InputType::Enter){
if(!allowEnter||f.a<0||f.a>3||(router.mode()!=ControlMode::Local&&active!=peer)){
if(!allowEnter)log(L"LAN input: declined cursor handoff during a local text operation or shortcut capture");
send(peer,{InputType::Return,f.token,32768});return;
}
if(router.mode()==ControlMode::Local)select(peer,f.a^1,now);
+29 -11
View File
@@ -11,8 +11,19 @@ class PasteProbe
IUIAutomationElement *element{};
IUIAutomationTextPattern *pattern{};
static std::optional<std::wstring> rangeText(IUIAutomationTextRange *range)
{
BSTR value{};
const HRESULT hr = range->GetText(8193, &value);
std::wstring text(value ? value : L"", SysStringLen(value));
SysFreeString(value);
if (FAILED(hr)) return {};
return text;
}
public:
std::wstring status = L"not-requested";
std::optional<std::wstring> precedingCharacter;
PasteProbe(bool enabled, HWND target)
{
if (!enabled)
@@ -48,11 +59,11 @@ class PasteProbe
!pattern)
return;
}
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr)
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr, bool readPreceding = false)
: PasteProbe(enabled, target)
{
if (!pattern) return;
auto selected = read(1, false);
auto selected = read(1, false, readPreceding);
auto normalize = [](std::wstring value)
{
for (size_t at = 0; (at = value.find(L"\r\n", at)) != value.npos;)
@@ -80,7 +91,7 @@ class PasteProbe
if (automation)
automation->Release();
}
std::optional<std::wstring> read(int characters, bool allowCaret = true)
std::optional<std::wstring> read(int characters, bool allowCaret = true, bool readPreceding = false)
{
if (!pattern)
return {};
@@ -162,19 +173,26 @@ class PasteProbe
if (SUCCEEDED(hr) && moved != -characters)
hr = E_FAIL;
}
BSTR value{};
if (SUCCEEDED(hr))
hr = range->GetText(8193, &value);
auto text = SUCCEEDED(hr) ? rangeText(range) : std::nullopt;
if (readPreceding && text &&
SUCCEEDED(range->MoveEndpointByRange(TextPatternRangeEndpoint_End, range, TextPatternRangeEndpoint_Start)))
{
int moved{};
if (SUCCEEDED(range->MoveEndpointByUnit(TextPatternRangeEndpoint_Start, TextUnit_Character, -1, &moved)))
{
if (moved == 0)
precedingCharacter.emplace();
else if (auto previous = rangeText(range); previous && !previous->empty())
precedingCharacter = std::move(previous);
}
}
range->Release();
if (FAILED(hr))
if (!text)
{
SysFreeString(value);
status = L"range-read-failed";
return {};
}
std::wstring text(value ? value : L"", SysStringLen(value));
SysFreeString(value);
if (text.size() > 8192)
if (text->size() > 8192)
{
status = L"readback-size-limit";
return {};
+38 -20
View File
@@ -349,14 +349,18 @@ bool launchThroughExplorer(const std::wstring &path)
SysFreeString(executable);
return SUCCEEDED(hr);
}
Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<DWORD> expected)
bool clipboardHasImage()
{
return IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"));
}
Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<DWORD> expected,
DWORD *capturedSequence)
{
ClipboardLock lock(window);
if (expected && *expected != GetClipboardSequenceNumber())
throw std::runtime_error("Clipboard changed while taking snapshot");
if (mode == ClipboardRead::WithoutImages &&
(IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))))
if (mode == ClipboardRead::WithoutImages && clipboardHasImage())
throw std::runtime_error("Clipboard changed to an image");
Clip c;
size_t total = 0;
@@ -392,6 +396,8 @@ Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<
total += size;
c.formats.push_back(std::move(format));
}
// Delayed rendering can advance the sequence while this read holds the clipboard open.
if (capturedSequence) *capturedSequence = GetClipboardSequenceNumber();
return c;
}
DWORD writeClipboard(HWND window, const Clip &c) { return writeClipboardGuarded(window, c, {}); }
@@ -490,32 +496,44 @@ INPUT keyboardInput(WORD key, DWORD flags)
return input;
}
bool chord(WORD key, UINT mods)
{
WORD keys[5];
size_t count = 0;
for (auto [modifier, vk] : {std::pair<UINT, WORD>{MOD_CONTROL, VK_CONTROL},
{MOD_ALT, VK_MENU}, {MOD_SHIFT, VK_SHIFT}, {MOD_WIN, VK_LWIN}})
if (mods & modifier)
keys[count++] = vk;
keys[count++] = key;
return chord(std::span<const WORD>(keys, count));
}
bool chord(std::span<const WORD> keys)
{
std::vector<INPUT> inputs;
inputs.reserve(2 * keys.size());
auto add = [&](WORD k, bool up)
{
INPUT i = keyboardInput(k, up ? KEYEVENTF_KEYUP : 0);
if (k >= VK_LSHIFT && k <= VK_RMENU)
{
i.ki.wScan = static_cast<WORD>(MapVirtualKeyW(k, MAPVK_VK_TO_VSC));
i.ki.dwFlags |= KEYEVENTF_SCANCODE;
}
if ((k >= VK_PRIOR && k <= VK_DOWN) || k == VK_INSERT || k == VK_DELETE ||
k == VK_DIVIDE || k == VK_LWIN || k == VK_SNAPSHOT ||
k == VK_DIVIDE || k == VK_LWIN || k == VK_RWIN || k == VK_RMENU ||
k == VK_RCONTROL || k == VK_SNAPSHOT ||
(k >= VK_VOLUME_MUTE && k <= VK_VOLUME_UP))
i.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
inputs.push_back(i);
};
for (auto [m, k] : {std::pair<UINT, WORD>{MOD_CONTROL, VK_CONTROL},
{MOD_ALT, VK_MENU},
{MOD_SHIFT, VK_SHIFT},
{MOD_WIN, VK_LWIN}})
if (mods & m)
add(k, false);
add(key, false);
add(key, true);
for (auto [m, k] : {std::pair<UINT, WORD>{MOD_WIN, VK_LWIN},
{MOD_SHIFT, VK_SHIFT},
{MOD_ALT, VK_MENU},
{MOD_CONTROL, VK_CONTROL}})
if (mods & m)
add(k, true);
return SendInput((UINT)inputs.size(), inputs.data(), sizeof(INPUT)) == inputs.size();
for (WORD key : keys) add(key, false);
for (auto it = keys.rbegin(); it != keys.rend(); ++it) add(*it, true);
const auto sent = SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT));
if (sent == inputs.size()) return true;
// Release any keys already pressed if Windows accepted only part of the chord.
const auto pending = std::min<size_t>(sent, inputs.size() - sent);
if (pending)
SendInput(static_cast<UINT>(pending), inputs.data() + inputs.size() - pending, sizeof(INPUT));
return false;
}
std::optional<SystemVolume> changeSystemVolume(MouseActionType action, int step)
{
+4 -1
View File
@@ -50,12 +50,15 @@ std::wstring processName(HWND);
std::wstring mouseApplicationName(HWND);
bool launchThroughExplorer(const std::wstring &);
enum class ClipboardRead { All, Selection, WithoutImages };
bool clipboardHasImage();
Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024,
ClipboardRead = ClipboardRead::All, std::optional<DWORD> expected = {});
ClipboardRead = ClipboardRead::All, std::optional<DWORD> expected = {},
DWORD *capturedSequence = nullptr);
DWORD writeClipboard(HWND, const Clip &);
DWORD writeClipboardGuarded(HWND, const Clip &, std::optional<DWORD> expected);
Clip textClip(const std::wstring &);
bool chord(WORD key, UINT modifiers = 0);
bool chord(std::span<const WORD> keys);
struct SystemVolume
{
int percent{};
+7 -7
View File
@@ -50,13 +50,12 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
std::wstring token;
bool autoOpenEditor=false, writeLog=false;
int argc{}; auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
if(argc==3 && std::wstring(argv[1])==L"--clipboard-snapshot") {
std::filesystem::path request=argv[2]; LocalFree(argv);
return ks::runClipboardSnapshot(request);
}
if(argc==5 && std::wstring_view(argv[1])==L"--history-image-worker") {
HANDLE handles[3]{};
for(int i=0;i<3;++i)
const bool clipboardSnapshot = argc == 6 && std::wstring_view(argv[1]) == L"--clipboard-snapshot";
const bool historyImageWorker = argc == 5 && std::wstring_view(argv[1]) == L"--history-image-worker";
if (clipboardSnapshot || historyImageWorker)
{
HANDLE handles[4]{};
for (int i = 0; i < argc - 2; ++i)
{
wchar_t *end{};
const auto value=std::wcstoull(argv[i+2],&end,10);
@@ -64,6 +63,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
handles[i]=reinterpret_cast<HANDLE>(static_cast<uintptr_t>(value));
}
LocalFree(argv);
if (clipboardSnapshot) return ks::runClipboardSnapshot(handles[0], handles[1], handles[2], handles[3]);
const auto initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
if(FAILED(initialized)) return 1;
const auto result=ks::runHistoryImageWorker(handles[0],handles[1],handles[2]);
+165 -142
View File
@@ -703,26 +703,99 @@ struct ImageWorkerHandle
if(value) CloseHandle(std::exchange(value,nullptr));
}
};
template <typename Control>
struct ImageWorkerView
{
ImageWorkerControl *control{};
Control *control{};
~ImageWorkerView() { reset(); }
void reset()
{
if(control) UnmapViewOfFile(std::exchange(control,nullptr));
}
};
template <typename Control>
struct ImageWorkerChannel
{
ImageWorkerHandle mapping, requestReady, responseReady, process;
ImageWorkerView<Control> view;
~ImageWorkerChannel() { stop(); }
void stop() noexcept
{
if (process.value && WaitForSingleObject(process.value, 0) == WAIT_TIMEOUT)
{
TerminateProcess(process.value, ERROR_CANCELLED);
WaitForSingleObject(process.value, INFINITE);
}
process.reset();
view.reset();
mapping.reset();
requestReady.reset();
responseReady.reset();
}
void open()
{
SECURITY_ATTRIBUTES security{sizeof(security), nullptr, TRUE};
mapping.value = CreateFileMappingW(INVALID_HANDLE_VALUE, &security, PAGE_READWRITE, 0, sizeof(Control), nullptr);
requestReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
responseReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
if (!mapping.value || !requestReady.value || !responseReady.value)
throw std::runtime_error("Cannot create image helper channel");
view.control = static_cast<Control *>(MapViewOfFile(mapping.value, FILE_MAP_WRITE, 0, 0, sizeof(Control)));
if (!view.control) throw std::runtime_error("Cannot map image helper channel");
}
void start(std::wstring_view mode, HANDLE parent = nullptr)
{
std::vector<HANDLE> inherited{mapping.value, requestReady.value, responseReady.value};
if (parent) inherited.push_back(parent);
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr, 1, 0, &bytes);
Bytes storage(bytes);
auto attributes = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if (!InitializeProcThreadAttributeList(attributes, 1, 0, &bytes))
throw std::runtime_error("Cannot initialize image helper startup");
struct Attributes
{
LPPROC_THREAD_ATTRIBUTE_LIST value;
~Attributes() { DeleteProcThreadAttributeList(value); }
} cleanup{attributes};
if (!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inherited.data(), inherited.size() * sizeof(HANDLE), nullptr, nullptr))
throw std::runtime_error("Cannot configure image helper startup");
const auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" ";
command += mode;
for (auto handle : inherited) command += L" " + std::to_wstring(reinterpret_cast<uintptr_t>(handle));
STARTUPINFOEXW startup{};
startup.StartupInfo.cb = sizeof(startup);
startup.lpAttributeList = attributes;
PROCESS_INFORMATION child{};
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, TRUE,
CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, nullptr, helper.parent_path().c_str(),
&startup.StartupInfo, &child))
throw std::runtime_error(utf8(lastError(L"Cannot start image helper")));
process.value = child.hProcess;
CloseHandle(child.hThread);
for (auto handle : inherited) SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
}
DWORD waitForResponse(DWORD timeout) const
{
HANDLE signals[]{responseReady.value, process.value};
return WaitForMultipleObjects(2, signals, FALSE, timeout);
}
};
struct HistoryImageWorker
{
std::timed_mutex mutex;
ImageWorkerHandle mapping, requestReady, responseReady, process;
ImageWorkerView view;
~HistoryImageWorker() { stop(); }
void stop();
void start();
ImageWorkerChannel<ImageWorkerControl> channel;
int perform(const std::filesystem::path &, const std::function<bool()> &);
};
struct ClipboardSnapshotControl
{
DWORD sequence;
char captureError[256];
};
}
struct HistoryImageWorkers
@@ -778,84 +851,91 @@ void History::reload()
std::lock_guard lock(mutex_);
loadIndex();
}
void ClipboardSnapshot::cleanup() noexcept
struct ClipboardSnapshot::Helper
{
if (request_.empty()) return;
std::error_code ignored;
for (const auto *suffix : {L"", L".snapshot", L".result"})
std::filesystem::remove(std::filesystem::path(request_.wstring() + suffix), ignored);
request_.clear();
}
ClipboardSnapshot::~ClipboardSnapshot() { cleanup(); }
DWORD ClipboardSnapshot::run(bool restore, DWORD sequence)
ImageWorkerChannel<ClipboardSnapshotControl> channel;
};
ClipboardSnapshot::ClipboardSnapshot() = default;
ClipboardSnapshot::~ClipboardSnapshot() = default;
DWORD ClipboardSnapshot::capture(HWND window, DWORD sequence)
{
atomicWrite(request_, protect(jsonBytes(Json{{"schema", 1}, {"restore", restore}, {"sequence", sequence}})));
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" --clipboard-snapshot \"" + request_.wstring() + L"\"";
STARTUPINFOW startup{sizeof(startup)};
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
PROCESS_INFORMATION process{};
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
nullptr, helper.parent_path().c_str(), &startup, &process))
throw std::runtime_error("Cannot start clipboard snapshot helper");
CloseHandle(process.hThread);
auto wait = WaitForSingleObject(process.hProcess, 10000);
DWORD result = ERROR_GEN_FAILURE;
helper_.reset();
clip_ = {};
if (!clipboardHasImage())
{
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence, &sequence);
return sequence;
}
auto helper = std::make_unique<Helper>();
auto &channel = helper->channel;
channel.open();
channel.view.control->sequence = sequence;
// Let the helper discard its private copy if the resident exits unexpectedly.
ImageWorkerHandle parent;
const auto self = GetCurrentProcess();
if (!DuplicateHandle(self, self, self, &parent.value, SYNCHRONIZE, TRUE, 0))
throw std::runtime_error("Cannot pass resident lifetime to clipboard helper");
channel.start(L"--clipboard-snapshot", parent.value);
const auto wait = channel.waitForResponse(10000);
if (wait == WAIT_TIMEOUT)
throw std::runtime_error("Clipboard snapshot helper timed out during capture");
if (wait == WAIT_FAILED)
throw std::runtime_error(utf8(lastError(L"Cannot wait for clipboard snapshot helper")));
if (wait != WAIT_OBJECT_0)
{
TerminateProcess(process.hProcess, ERROR_TIMEOUT);
WaitForSingleObject(process.hProcess, INFINITE);
const auto &error = channel.view.control->captureError;
if (error[0]) throw std::runtime_error(std::string("Clipboard snapshot capture: ") + error);
DWORD exitCode{};
if (GetExitCodeProcess(channel.process.value, &exitCode))
throw std::runtime_error("Clipboard snapshot helper exited during capture (code " +
std::to_string(exitCode) + ")");
throw std::runtime_error(utf8(lastError(L"Cannot read clipboard snapshot helper exit code")));
}
GetExitCodeProcess(process.hProcess, &result);
CloseHandle(process.hProcess);
if (wait != WAIT_OBJECT_0 || result) throw std::runtime_error("Clipboard snapshot helper failed");
return parse(unprotect(readFile(request_.wstring() + L".result", 4096))).at("sequence").get<DWORD>();
}
void ClipboardSnapshot::capture(HWND window, DWORD sequence)
{
cleanup();
clip_ = {};
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
!IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")))
{
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence);
return;
}
request_ = std::filesystem::temp_directory_path() / (L"ks-clipboard-" + newSnippetId() + L".request");
try { run(false, sequence); }
catch (...) { cleanup(); throw; }
sequence = channel.view.control->sequence;
helper_ = std::move(helper);
return sequence;
}
DWORD ClipboardSnapshot::restore(HWND window, DWORD sequence)
{
return request_.empty() ? writeClipboardGuarded(window, clip_, sequence) : run(true, sequence);
if (!helper_) return writeClipboardGuarded(window, clip_, sequence);
auto &channel = helper_->channel;
if (!channel.process.value)
throw std::runtime_error("Clipboard snapshot helper is unavailable");
channel.view.control->sequence = sequence;
DWORD result{};
if (!SetEvent(channel.requestReady.value) || WaitForSingleObject(channel.process.value, 10000) != WAIT_OBJECT_0 ||
!GetExitCodeProcess(channel.process.value, &result) || result != 0)
{
channel.stop();
throw std::runtime_error("Clipboard snapshot helper failed to restore");
}
return channel.view.control->sequence;
}
int runClipboardSnapshot(const std::filesystem::path &request)
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent)
{
ImageWorkerView<ClipboardSnapshotControl> view{static_cast<ClipboardSnapshotControl *>(
MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(ClipboardSnapshotControl)))};
if (!view.control) return 1;
try
{
if (!request.is_absolute() || !request.filename().wstring().starts_with(L"ks-clipboard-") ||
request.extension() != L".request") return 1;
auto job = parse(unprotect(readFile(request, 4096)));
if (job.at("schema") != 1) return 1;
auto sequence = job.at("sequence").get<DWORD>();
const auto snapshot = request.wstring() + L".snapshot";
if (job.at("restore").get<bool>())
{
auto clip = decodeClip(unprotect(readFile(snapshot, 70 * 1024 * 1024)));
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
if (!window) return 1;
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
sequence = writeClipboardGuarded(window, clip, sequence);
}
else
{
auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
if (sequence != GetClipboardSequenceNumber()) return 2;
atomicWrite(snapshot, protect(encodeClip(clip)));
}
atomicWrite(request.wstring() + L".result", protect(jsonBytes(Json{{"sequence", sequence}})));
auto &sequence = view.control->sequence;
const auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence, &sequence);
if (!SetEvent(responseReady)) return 1;
// The captured formats stay in this process.
HANDLE signals[]{parent, requestReady};
if (WaitForMultipleObjects(2, signals, FALSE, INFINITE) != WAIT_OBJECT_0 + 1) return 1;
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
if (!window) return 1;
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
view.control->sequence = writeClipboardGuarded(window, clip, view.control->sequence);
return 0;
}
catch (const std::exception &error)
{
auto &message = view.control->captureError;
strncpy_s(message, error.what(), _TRUNCATE);
return 1;
}
catch (...) { return 1; }
}
bool History::captureImage(DWORD sequence, const std::wstring &app, const Settings &settings)
@@ -917,9 +997,7 @@ int runImageHistoryCapture(const std::filesystem::path &request)
!IsClipboardFormatAvailable(RegisterClipboardFormatW(L"Clipboard Viewer Ignore"));
};
if (!valid()) return 2;
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
!IsClipboardFormatAvailable(CF_BITMAP) &&
!IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))) return 2;
if (!clipboardHasImage()) return 2;
auto clip = readClipboard(nullptr, size_t(settings.maxImageMiB) * 1024 * 1024);
if (!valid()) return 2;
for (const auto &format : clip.formats)
@@ -1163,61 +1241,6 @@ void History::clear()
}
namespace
{
void HistoryImageWorker::stop()
{
if(process.value && WaitForSingleObject(process.value,0)==WAIT_TIMEOUT)
{
TerminateProcess(process.value,ERROR_CANCELLED);
WaitForSingleObject(process.value,INFINITE);
}
process.reset();
view.reset();
mapping.reset();
requestReady.reset();
responseReady.reset();
}
void HistoryImageWorker::start()
{
SECURITY_ATTRIBUTES security{sizeof(security),nullptr,TRUE};
mapping.value=CreateFileMappingW(INVALID_HANDLE_VALUE,&security,PAGE_READWRITE,0,sizeof(ImageWorkerControl),nullptr);
requestReady.value=CreateEventW(&security,FALSE,FALSE,nullptr);
responseReady.value=CreateEventW(&security,FALSE,FALSE,nullptr);
if(!mapping.value || !requestReady.value || !responseReady.value)
throw std::runtime_error("Cannot create history OCR worker channel");
view.control=static_cast<ImageWorkerControl *>(MapViewOfFile(mapping.value,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)));
if(!view.control) throw std::runtime_error("Cannot map history OCR worker channel");
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
Bytes storage(bytes);
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes))
throw std::runtime_error("Cannot initialize history OCR worker startup");
struct Attributes
{
LPPROC_THREAD_ATTRIBUTE_LIST value;
~Attributes() { DeleteProcThreadAttributeList(value); }
} cleanup{attributes};
HANDLE inherited[]{mapping.value,requestReady.value,responseReady.value};
if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr))
throw std::runtime_error("Cannot configure history OCR worker startup");
const auto helper=std::filesystem::path(executable()).parent_path()/L"KSwitcher.Screenshot.exe";
auto command=L"\""+helper.wstring()+L"\" --history-image-worker";
for(auto handle:inherited) command+=L" "+std::to_wstring(reinterpret_cast<uintptr_t>(handle));
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.lpAttributeList=attributes;
PROCESS_INFORMATION child{};
if(!CreateProcessW(helper.c_str(),command.data(),nullptr,nullptr,TRUE,
CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,nullptr,helper.parent_path().c_str(),&startup.StartupInfo,&child))
throw std::runtime_error(utf8(lastError(L"Cannot start history OCR helper")));
process.value=child.hProcess;
CloseHandle(child.hThread);
for(const auto handle:inherited) SetHandleInformation(handle,HANDLE_FLAG_INHERIT,0);
}
int HistoryImageWorker::perform(const std::filesystem::path &request,const std::function<bool()> &cancelled)
{
std::unique_lock lock(mutex,std::defer_lock);
@@ -1234,42 +1257,42 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
{
for(int attempt=0;attempt<2;++attempt)
{
if(!process.value || WaitForSingleObject(process.value,0)!=WAIT_TIMEOUT)
if(!channel.process.value || WaitForSingleObject(channel.process.value,0)!=WAIT_TIMEOUT)
{
stop();
start();
channel.stop();
channel.open();
channel.start(L"--history-image-worker");
}
checkCancelled();
std::copy(path.begin(),path.end(),view.control->request);
view.control->request[path.size()]=L'\0';
if(!SetEvent(requestReady.value)) throw std::runtime_error("Cannot request history OCR");
HANDLE signals[]{responseReady.value,process.value};
std::copy(path.begin(),path.end(),channel.view.control->request);
channel.view.control->request[path.size()]=L'\0';
if(!SetEvent(channel.requestReady.value)) throw std::runtime_error("Cannot request history OCR");
const auto deadline=GetTickCount64()+60000;
for(;;)
{
const auto wait=WaitForMultipleObjects(2,signals,FALSE,100);
const auto wait=channel.waitForResponse(100);
if(wait==WAIT_OBJECT_0)
{
checkCancelled();
return view.control->result;
return channel.view.control->result;
}
if(wait==WAIT_OBJECT_0+1)
{
DWORD code{};
if(GetExitCodeProcess(process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
if(GetExitCodeProcess(channel.process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
throw std::runtime_error("History OCR helper exited before responding");
}
if(wait!=WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper");
checkCancelled();
if(GetTickCount64()>=deadline) throw std::runtime_error("History OCR helper timed out");
}
stop();
channel.stop();
}
}
catch(...)
{
// The child must stop writing before the request and response files are cleaned up.
stop();
channel.stop();
throw;
}
throw std::runtime_error("History OCR helper did not accept the request");
@@ -1278,7 +1301,7 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
int runHistoryImageWorker(HANDLE mapping,HANDLE requestReady,HANDLE responseReady)
{
ImageWorkerView view{static_cast<ImageWorkerControl *>(
ImageWorkerView<ImageWorkerControl> view{static_cast<ImageWorkerControl *>(
MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)))};
if(!view.control) return 1;
for(;;)
+6 -7
View File
@@ -58,20 +58,19 @@ bool sameClipboardImage(const Clip &, const Clip &);
int runImageHistoryCapture(const std::filesystem::path &request);
int runHistoryOcr(const std::filesystem::path &request);
int runHistoryImageWorker(HANDLE mapping, HANDLE requestReady, HANDLE responseReady);
// Image backups stay encrypted on disk and are read/written only by a short-lived helper.
// Image backups are held in memory by a helper for the lifetime of the transaction.
class ClipboardSnapshot
{
struct Helper;
Clip clip_;
std::filesystem::path request_;
void cleanup() noexcept;
DWORD run(bool restore, DWORD sequence);
std::unique_ptr<Helper> helper_;
public:
ClipboardSnapshot() = default;
ClipboardSnapshot();
ClipboardSnapshot(const ClipboardSnapshot &) = delete;
ClipboardSnapshot &operator=(const ClipboardSnapshot &) = delete;
~ClipboardSnapshot();
void capture(HWND, DWORD sequence);
DWORD capture(HWND, DWORD sequence);
DWORD restore(HWND, DWORD sequence);
};
int runClipboardSnapshot(const std::filesystem::path &request);
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent);
} // namespace ks
+1820 -469
View File
File diff suppressed because it is too large. Load diff
+21 -6
View File
@@ -14,7 +14,6 @@ struct AppLanguagesView
bool dirty{};
HWND pickerOutline{};
};
constexpr UINT AppWindowPicked = WM_APP + 78;
void showAppLanguageStatus(HWND w, const AppLanguagesView &v)
{
if (v.selection < 0)
@@ -130,7 +129,7 @@ void updatePickerOutline(HWND dialog, HWND &outline, HWND target)
}
LRESULT CALLBACK appWindowPickerProc(HWND button, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR data)
{
HWND dialog = GetParent(button);
HWND dialog = GetAncestor(button, GA_ROOT);
auto &outline = *reinterpret_cast<HWND *>(data);
if (msg == WM_LBUTTONDOWN)
{
@@ -177,11 +176,27 @@ LRESULT CALLBACK appWindowPickerProc(HWND button, UINT msg, WPARAM wp, LPARAM lp
if (msg == WM_NCDESTROY) RemoveWindowSubclass(button, appWindowPickerProc, id);
return DefSubclassProc(button, msg, wp, lp);
}
void createAppWindowPicker(HWND w, int id, int x, int y, int width, HWND &outline)
HWND createButtonTooltips(HWND owner)
{
control(w, L"BUTTON", L" ⊕ Drag to window", WS_TABSTOP | BS_PUSHBUTTON | BS_LEFT,
id, x, y, width, 28);
SetWindowSubclass(GetDlgItem(w, id), appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&outline));
return CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, owner, nullptr,
GetModuleHandleW(nullptr), nullptr);
}
void addButtonTooltip(HWND tips, HWND owner, int id, const wchar_t *text)
{
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, owner,
reinterpret_cast<UINT_PTR>(GetDlgItem(owner, id))};
tool.lpszText = const_cast<wchar_t *>(text);
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
}
constexpr int AppWindowPickerIcon = 753;
void createAppWindowPicker(HWND w, int id, int x, int y, int width, HWND &outline, HWND tips = nullptr)
{
const bool icon = id == AppWindowPickerIcon;
HWND picker = control(w, L"BUTTON", icon ? L"Drag to application window" : L" ⊕ Drag to window",
WS_TABSTOP | (icon ? BS_OWNERDRAW : BS_PUSHBUTTON | BS_LEFT), id, x, y, width, 28);
SetWindowSubclass(picker, appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&outline));
if (tips) addButtonTooltip(tips, w, id, L"Drag to an application window");
}
LRESULT CALLBACK appLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
+226 -94
View File
@@ -1,7 +1,7 @@
// Uses the resident service; the configurator never opens a discovery socket.
struct LanView
{
HWND parent{};
HWND owner{};
App *app{};
nlohmann::json snapshot=nlohmann::json::object();
std::vector<std::string> ids;
@@ -11,7 +11,7 @@ struct LanView
std::vector<std::wstring> rows;
std::string logRequest;
std::filesystem::path logDestination;
std::wstring transferMessage;
std::wstring logMessage;
};
nlohmann::json lanRequest(App &app,const nlohmann::json &request)
{
@@ -23,19 +23,116 @@ std::string selectedLan(HWND w,LanView &v)
auto index=SendDlgItemMessageW(w,702,LB_GETCURSEL,0,0);
return index>=0 && size_t(index)<v.ids.size() ? v.ids[size_t(index)] : "";
}
std::filesystem::path pickLanFile(HWND owner, bool save, const wchar_t *suggestion=L"")
std::filesystem::path pickLanFile(HWND owner, bool save, const wchar_t *suggestion=L"",
const wchar_t *filter=L"All files\0*.*\0")
{
wchar_t path[32768]{};
wcsncpy_s(path,suggestion,_TRUNCATE);
OPENFILENAMEW dialog{sizeof(dialog)};
dialog.hwndOwner=owner;
dialog.lpstrFilter=L"All files\0*.*\0";
dialog.lpstrFilter=filter;
dialog.lpstrFile=path;
dialog.nMaxFile=std::size(path);
dialog.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|(save?OFN_OVERWRITEPROMPT:OFN_FILEMUSTEXIST);
if(save?GetSaveFileNameW(&dialog):GetOpenFileNameW(&dialog))return path;
return {};
}
struct LanClientsView
{
App *app{};
nlohmann::json entries;
};
void refreshLanClients(HWND window, LanClientsView &view)
{
view.entries = lanRequest(*view.app, {{"action", "trustedClients"}});
SendDlgItemMessageW(window, 732, LB_RESETCONTENT, 0, 0);
for (const auto &entry : view.entries)
{
auto path = wide(entry.at("path").get<std::string>());
if (path.starts_with(L"\\\\?\\UNC\\")) path = L"\\\\" + path.substr(8);
else if (path.starts_with(L"\\\\?\\")) path.erase(0, 4);
SendDlgItemMessageW(window, 732, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(path.c_str()));
const auto width = scale(window, int(path.size()) * 9);
if (width > SendDlgItemMessageW(window, 732, LB_GETHORIZONTALEXTENT, 0, 0))
SendDlgItemMessageW(window, 732, LB_SETHORIZONTALEXTENT, width, 0);
}
EnableWindow(GetDlgItem(window, 734), FALSE);
}
LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
{
auto *view = reinterpret_cast<LanClientsView *>(GetWindowLongPtrW(window, GWLP_USERDATA));
if (msg == WM_DPICHANGED) { resizeForDpi(window, wp, lp); return 0; }
if (msg == WM_CLOSE || (msg == WM_COMMAND && LOWORD(wp) == IDCANCEL))
{
DestroyWindow(window);
return 0;
}
if (msg == WM_DESTROY)
{
const auto parent = GetWindow(window, GW_OWNER);
EnableWindow(parent, TRUE);
SetForegroundWindow(parent);
delete view;
return 0;
}
if (view && msg == WM_COMMAND)
{
const auto id = LOWORD(wp);
const auto index = SendDlgItemMessageW(window, 732, LB_GETCURSEL, 0, 0);
if (id == 732 && HIWORD(wp) == LBN_SELCHANGE)
{
EnableWindow(GetDlgItem(window, 734), index != LB_ERR);
return 0;
}
try
{
if (id == 733)
{
const auto path = pickLanFile(window, false, L"", L"Windows executables (*.exe)\0*.exe\0");
if (!path.empty() && MessageBoxW(window,
(L"Allow this application to browse and download files from paired computers?\n\n" + path.wstring()).c_str(),
L"Trust a LAN client", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) == IDYES)
{
lanRequest(*view->app, {{"action", "trustClient"}, {"path", utf8(path.wstring())}});
refreshLanClients(window, *view);
}
return 0;
}
if (id == 734 && index >= 0 && size_t(index) < view->entries.size())
{
lanRequest(*view->app, {{"action", "removeClient"}, {"path", view->entries[size_t(index)].at("path")}});
refreshLanClients(window, *view);
return 0;
}
}
catch (const std::exception &error)
{
MessageBoxW(window, wide(error.what()).c_str(), L"Trusted clients", MB_OK | MB_ICONERROR);
return 0;
}
}
return DefWindowProcW(window, msg, wp, lp);
}
void showLanClients(HWND parent, App &app)
{
auto window = makeWindow(app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 280, 0, false);
SetWindowLongPtrW(window, GWLP_HWNDPARENT, reinterpret_cast<LONG_PTR>(parent));
auto view = new LanClientsView{&app};
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(view));
label(window, L"Trusted executables can browse and download files from paired computers.", 16, 14, 578);
control(window, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | WS_BORDER | LBS_NOTIFY |
LBS_NOINTEGRALHEIGHT, 732, 16, 42, 578, 152);
label(window, L"Add the executable again after updating it.", 16, 202, 578);
button(window, L"&Add client…", 733, 16, 236, 126);
button(window, L"&Remove", 734, 150, 236, 110);
button(window, L"&Close", IDCANCEL, 494, 236, 100);
try { refreshLanClients(window, *view); }
catch (...) { DestroyWindow(window); throw; }
EnableWindow(parent, FALSE);
showRequestedWindow(window);
SetForegroundWindow(window);
}
LRESULT CALLBACK lanHelpProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
{
if(msg==WM_DPICHANGED){resizeForDpi(w,wp,lp);return 0;}
@@ -67,13 +164,13 @@ void refreshLan(HWND w,LanView &v)
if(state=="ready")
{
v.logRequest.clear();
v.transferMessage.clear();
v.logMessage.clear();
atomicWrite(v.logDestination,decodeLanLog(reply.at("logHex")));
v.transferMessage=L"Diagnostic log saved.";
v.logMessage=L"Diagnostic log saved.";
}
else if(state=="denied")v.transferMessage=L"Remote diagnostic downloads are disabled on that PC.";
else if(state=="unavailable")v.transferMessage=L"The selected log is unavailable on that PC.";
else v.transferMessage=L"The remote log download timed out.";
else if(state=="denied")v.logMessage=L"Remote diagnostic downloads are disabled on that PC.";
else if(state=="unavailable")v.logMessage=L"The selected log is unavailable on that PC.";
else v.logMessage=L"The remote log download timed out.";
v.logRequest.clear();
}
}
@@ -143,18 +240,19 @@ void refreshLan(HWND w,LanView &v)
EnableWindow(GetDlgItem(w,705),enabled&&online&&!pending&&!paired);
EnableWindow(GetDlgItem(w,706),pending);
EnableWindow(GetDlgItem(w,707),paired);
bool canTransfer=false;
bool canDownloadLogs=false;
for(const auto &peer:v.snapshot["peers"])
if(peer.at("id")==selected)canTransfer=paired&&peer.value("verified",false)&&peer.value("fileTransfer",false);
EnableWindow(GetDlgItem(w,726),canTransfer);
EnableWindow(GetDlgItem(w,727),canTransfer&&v.logRequest.empty());
EnableWindow(GetDlgItem(w,728),canTransfer&&v.logRequest.empty());
EnableWindow(GetDlgItem(w,730),!v.snapshot["files"].empty());
if(peer.at("id")==selected)canDownloadLogs=paired&&peer.value("verified",false)&&peer.value("fileTransfer",false);
EnableWindow(GetDlgItem(w,727),canDownloadLogs&&v.logRequest.empty());
EnableWindow(GetDlgItem(w,728),canDownloadLogs&&v.logRequest.empty());
CheckDlgButton(w,729,v.snapshot.value("shareLogs",false)?BST_CHECKED:BST_UNCHECKED);
auto fileCount=v.snapshot["files"].size();
auto transferStatus=v.transferMessage;
if(transferStatus.empty())transferStatus=wide(v.snapshot.value("transferStatus",std::string{}));
value(w,731,fileCount?L"Incoming files: "+std::to_wstring(fileCount):transferStatus);
if (value(w, 731) != v.logMessage)
{
value(w, 731, v.logMessage);
ShowWindow(GetDlgItem(w, 731), v.logMessage.empty() ? SW_HIDE : SW_SHOWNA);
arrangeWindow(GetParent(w));
arrangeWindow(w);
}
for(int id:{703,704}) EnableWindow(GetDlgItem(w,id),enabled&&!pending&&!paired);
auto positions=v.snapshot.value("positions",nlohmann::json::object());
EnableWindow(GetDlgItem(w,715),enabled&&!positions.empty()&&!v.snapshot.value("shareInput",false));
@@ -166,7 +264,7 @@ void refreshLan(HWND w,LanView &v)
auto inputStatus=wide(v.snapshot.value("inputStatus",std::string("Input sharing disabled.")));
if(!v.snapshot.value("shareInput",false))
inputStatus=!enabled ? L"Enable discovery to set up mouse and keyboard sharing." :
selected.empty() ? L"Select a computer in the list above to enable input." :
selected.empty() ? L"Select a computer in the pairing list to enable input." :
!paired ? L"Pair the selected computer first." :
L"Arrange the monitors, then enable input sharing on all PCs.";
auto mode=v.snapshot.value("controlMode",0);
@@ -178,14 +276,43 @@ void refreshLan(HWND w,LanView &v)
#include "ui_lan_layout.inl"
LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
{
if(msg==WM_DPICHANGED) {resizeForDpi(w,wp,lp);return 0;}
if (msg == WM_SIZE) arrangeWindow(w);
auto v=(LanView*)GetWindowLongPtrW(w,GWLP_USERDATA);
if(!v) return DefWindowProcW(w,msg,wp,lp);
if(msg==WM_DESTROY) {DestroyWindow(GetDlgItem(w,721));KillTimer(w,1);EnableWindow(v->parent,TRUE);SetForegroundWindow(v->parent);delete v;SetWindowLongPtrW(w,GWLP_USERDATA,0);return 0;}
if(msg==WM_CLOSE||(msg==WM_COMMAND&&LOWORD(wp)==IDCANCEL)) {DestroyWindow(w);return 0;}
if (msg == WM_NCDESTROY)
{
KillTimer(w, 1);
delete windowLayoutState(w);
RemovePropW(w, L"WindowLayout");
delete v;
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
return DefWindowProcW(w, msg, wp, lp);
}
if (msg == WM_CTLCOLORSTATIC)
return SendMessageW(GetParent(w), msg, wp, lp);
if (msg == WM_PAINT)
{
paintSettingsMatches(w);
return 0;
}
try
{
if(msg==WM_TIMER) {refreshLan(w,*v);return 0;}
if (msg == WM_SHOWWINDOW)
{
if (wp)
{
SetTimer(w, 1, 1000, nullptr);
refreshLan(w, *v);
}
else if (v->logRequest.empty()) KillTimer(w, 1);
return 0;
}
if (msg == WM_TIMER && wp == 1)
{
if (IsWindowVisible(w) || !v->logRequest.empty()) refreshLan(w, *v);
else KillTimer(w, 1);
return 0;
}
if(msg==WM_COMMAND)
{
int id=LOWORD(wp); auto peer=selectedLan(w,*v);
@@ -193,7 +320,8 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
if(HIWORD(wp)!=BN_CLICKED) return DefWindowProcW(w,msg,wp,lp);
if(!IsWindowEnabled(GetDlgItem(w,id)))return 0;
v->error.clear();
if(id==722){showLanHelp(w,*v->app);return 0;}
if(id==722){showLanHelp(v->owner,*v->app);return 0;}
if(id==735){showLanClients(v->owner,*v->app);return 0;}
if(id==701) lanRequest(*v->app,{{"action","enable"},{"enabled",!v->snapshot.value("enabled",false)}});
if(id==704)
{
@@ -204,49 +332,18 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
if(id==705) lanRequest(*v->app,{{"action","pair"},{"peer",peer},{"code",utf8(value(w,703))}});
if(id==706) lanRequest(*v->app,{{"action","cancel"}});
if(id==707) lanRequest(*v->app,{{"action","forget"},{"peer",peer}});
if(id==726)
{
auto file=pickLanFile(w,false);
if(!file.empty())
{
lanRequest(*v->app,{{"action","sendFile"},{"peer",peer},{"path",utf8(file.wstring())}});
v->transferMessage.clear();
}
}
if(id==727||id==728)
{
auto destination=pickLanFile(w,true,id==728?L"kswitcher-previous.log":L"kswitcher-remote.log");
auto destination=pickLanFile(v->owner,true,id==728?L"kswitcher-previous.log":L"kswitcher-remote.log");
if(!destination.empty())
{
auto reply=lanRequest(*v->app,{{"action","requestLog"},{"peer",peer},{"previous",id==728}});
v->logDestination=std::move(destination);
v->logRequest=reply.at("request").get<std::string>();
v->transferMessage=L"Downloading diagnostic log...";
v->logMessage=L"Downloading diagnostic log...";
}
}
if(id==729)lanRequest(*v->app,{{"action","shareLogs"},{"enabled",IsDlgButtonChecked(w,729)==BST_CHECKED}});
if(id==730 && !v->snapshot["files"].empty())
{
const auto file=v->snapshot["files"].front();
auto name=wide(file.at("name").get<std::string>());
auto question=wide(file.at("sender").get<std::string>())+L" sent "+name+L" ("+
std::to_wstring(file.at("size").get<size_t>())+L" bytes).\n\nSave this file? Choose No to discard it.";
auto answer=MessageBoxW(w,question.c_str(),L"Incoming file",MB_YESNOCANCEL|MB_ICONQUESTION);
if(answer==IDYES || answer==IDNO)
{
// A peer supplies the display name. Only offer it as a plain Windows filename.
const bool validName = !name.empty() && name.size() <= 255 &&
name.find_first_of(L"<>:\"/\\|?*") == name.npos &&
name.back() != L'.' && name.back() != L' ' &&
std::none_of(name.begin(), name.end(), [](wchar_t c) { return c < L' '; });
auto destination=answer==IDYES?pickLanFile(w,true,validName?name.c_str():L"received-file"):
std::filesystem::path{};
if(answer==IDNO||!destination.empty())
lanRequest(*v->app,{{"action",answer==IDYES?"saveFile":"discardFile"},{"id",file.at("id")},
{"peer",file.at("peer")},{"path",utf8(destination.wstring())}});
}
v->transferMessage.clear();
}
if(id==715)
{
lanRequest(*v->app,{{"action","input"},{"enabled",true}});
@@ -258,47 +355,82 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
catch(const std::exception &e) {v->error=wide(e.what());value(w,708,v->error);}
return DefWindowProcW(w,msg,wp,lp);
}
void showLan(HWND parent,App &app)
constexpr int LanPadding = 16, LanPairingWidth = 332, LanLayoutLeft = 366, LanLayoutWidth = 348;
constexpr int LanDiagnosticsTop = 364;
constexpr int LanSettingsWidth = LanLayoutLeft + LanLayoutWidth + LanPadding, LanSettingsHeight = 506;
HWND createLanSettings(HWND pane, App &app)
{
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,730,498,0,false);
windowLayoutState(w)->fixedClient=true;
SetWindowLongPtrW(w,GWLP_HWNDPARENT,(LONG_PTR)parent);
auto v=new LanView{parent,&app};SetWindowLongPtrW(w,GWLP_USERDATA,(LONG_PTR)v);
label(w,L"Changes save automatically.",16,12,698);
control(w,L"STATIC",L"",0,709,16,35,698,22);
WNDCLASSW panel{};
panel.hInstance = app.instance;
panel.lpfnWndProc = lanProc;
panel.lpszClassName = L"KSwitcher.LAN.Settings";
panel.hCursor = LoadCursorW(nullptr, IDC_ARROW);
panel.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
RegisterClassW(&panel);
HWND w = CreateWindowExW(WS_EX_CONTROLPARENT, panel.lpszClassName, L"",
WS_CHILD | WS_CLIPCHILDREN, 0, 0, scale(pane, LanSettingsWidth),
scale(pane, LanSettingsHeight), pane, reinterpret_cast<HMENU>(262), app.instance, nullptr);
if (!w) throw std::runtime_error("Cannot create computer settings.");
auto v = new LanView{GetAncestor(pane, GA_ROOT), &app};
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(v));
SetPropW(w, L"Font", GetPropW(pane, L"Font"));
auto layout = new WindowLayout{LanSettingsWidth, LanSettingsHeight, 0, 0, true, true};
SetPropW(w, L"WindowLayout", layout);
constexpr int left = LanPadding, pairingWidth = LanPairingWidth, right = LanLayoutLeft, rightWidth = LanLayoutWidth;
constexpr int gap = 10, rowHeight = 28;
constexpr int discoveryWidth = (pairingWidth - gap) / 2;
settingsGroupLabel(w, L"Pairing", left, 14, pairingWidth);
control(w, L"STATIC", L"", 0, 709, left, 39, pairingWidth, 22);
button(w, L"&Enable discovery", 701, left, 65, discoveryWidth);
button(w, L"&Trusted clients…", 735, left + discoveryWidth + gap, 65, discoveryWidth);
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | WS_BORDER | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT,
702, left, 98, pairingWidth, 70);
control(w, L"STATIC", L"", 0, 710, left, 173, pairingWidth, 33);
constexpr int codeTop = 235, actionTop = codeTop + rowHeight + 8;
constexpr int generateWidth = 135, codeWidth = pairingWidth - gap - generateWidth;
constexpr int actionWidth = (pairingWidth - 2 * gap) / 3, actionStep = actionWidth + gap;
label(w, L"Same pairing c&ode on both PCs", left, 211, pairingWidth);
edit(w, 703, left, codeTop, codeWidth, rowHeight);
SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
button(w, L"&Generate code", 704, left + codeWidth + gap, codeTop, generateWidth);
button(w, L"&Pair", 705, left, actionTop, actionWidth);
button(w, L"Ca&ncel", 706, left + actionStep, actionTop, actionWidth);
button(w, L"&Forget pair", 707, left + 2 * actionStep, actionTop, actionWidth);
control(w, L"STATIC", L"", 0, 708, left, actionTop + rowHeight + 5, pairingWidth, 42);
button(w,L"&Enable discovery",701,16,62,164);
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,16,98,332,70);
control(w,L"STATIC",L"",0,710,16,173,332,36);
label(w,L"Same pairing c&ode on both computers",16,211,332);
edit(w,703,16,234,189);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
button(w,L"&Generate code",704,213,234,135);
button(w,L"&Pair",705,16,268,76);
button(w,L"Cancel &pairing",706,100,268,125);
button(w,L"&Forget pair",707,233,268,115);
control(w,L"STATIC",L"Use one code on both PCs. Select each other and click Pair on both.",0,0,16,302,332,37);
control(w,L"STATIC",L"",0,708,16,344,332,53);
constexpr int right=366,rightWidth=348,gridTop=92,gridHeight=185;
label(w,L"Arrange your computers",right,65,rightWidth);
constexpr int gridTop = 43, gridHeight = 151, inputButtonWidth = (rightWidth - gap) / 2;
settingsGroupLabel(w, L"Input sharing", right, 14, rightWidth);
WNDCLASSW gridClass{};gridClass.lpfnWndProc=lanGridProc;gridClass.hInstance=app.instance;gridClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);gridClass.lpszClassName=L"KSwitcher.LAN.Layout";RegisterClassW(&gridClass);
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer in the list, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
scale(w,right),scale(w,gridTop),scale(w,rightWidth),scale(w,gridHeight),w,reinterpret_cast<HMENU>(721),app.instance,v);
windowLayoutState(w)->controls.push_back({grid,{right,gridTop,right+rightWidth,gridTop+gridHeight}});
control(w,L"STATIC",L"",0,719,right,283,rightWidth,37);
button(w,L"Enable &input sharing",715,right,323,172);
button(w,L"&Stop input sharing",716,546,323,168);
control(w,L"STATIC",L"",0,718,right,357,rightWidth,40);
control(w, L"STATIC", L"", 0, 719, right, 200, rightWidth, 35);
button(w, L"Enable &input sharing", 715, right, 240, inputButtonWidth);
button(w, L"&Stop input sharing", 716, right + inputButtonWidth + gap, 240, inputButtonWidth);
control(w, L"STATIC", L"", 0, 718, right, 274, rightWidth, 38);
button(w, L"Connection &help", 722, right, 317, 232);
button(w,L"Send file…",726,16,403,168);
button(w,L"Incoming files…",730,192,403,168);
button(w,L"Download log…",727,368,403,168);
button(w,L"Previous log…",728,544,403,170);
control(w,L"STATIC",L"",0,731,16,436,698,20);
checkbox(w,L"Allow paired computers to download diagnostic logs",729,16,464,418);
button(w,L"Connection &help",722,444,460,162);
button(w,L"&Close",IDCANCEL,614,460,100);
EnableWindow(parent,FALSE);showRequestedWindow(w);SetForegroundWindow(w);
SetTimer(w,1,1000,nullptr);
try {refreshLan(w,*v);} catch(const std::exception &e){v->error=wide(e.what());value(w,708,v->error);}
constexpr int fullWidth = right + rightWidth - left;
constexpr int logButtonWidth = (fullWidth - gap) / 2;
settingsGroupLabel(w, L"Diagnostic logs", left, LanDiagnosticsTop, fullWidth);
checkbox(w, L"Allow paired computers to download logs", 729, left, LanDiagnosticsTop + 28, fullWidth);
button(w, L"Current log…", 727, left, LanDiagnosticsTop + 62, logButtonWidth);
button(w, L"Previous log…", 728, left + logButtonWidth + gap, LanDiagnosticsTop + 62, logButtonWidth);
ShowWindow(control(w, L"STATIC", L"", 0, 731, left, LanDiagnosticsTop + 96, fullWidth, 22), SW_HIDE);
SetWindowSubclass(grid, scrollChildProc, 2, 0);
captureSettingsGeometry(*layout, 0, w);
layout->arranging = false;
return w;
}
int fitLanSettings(HWND panel, int width)
{
auto &layout = *windowLayoutState(panel);
layout.width = 1;
// The final control is feedback for the diagnostic log actions.
const auto end = layout.controls.size() - (GetWindowTextLengthW(GetDlgItem(panel, 731)) ? 0 : 1);
layout.height = fitSettingsColumns(layout, 0, end, width,
{LanPadding, LanLayoutLeft + LanLayoutWidth, LanLayoutLeft, LanPadding + LanPairingWidth,
LanDiagnosticsTop, 640});
return layout.height;
}
+150 -52
View File
@@ -1,12 +1,96 @@
std::wstring selectedMouseProfile(HWND w, const SettingsView &view)
{
const auto row = ListView_GetNextItem(GetDlgItem(w, 731), -1, LVNI_SELECTED);
const auto row = ListView_GetNextItem(GetDlgItem(settingsPage(w), 731), -1, LVNI_SELECTED);
return row < 0 || static_cast<size_t>(row) >= view.mouseProfiles.size() ? GlobalMouseProfile : view.mouseProfiles[row];
}
constexpr int RenameMouseProfile = 757, DeleteMouseProfile = 758;
constexpr int AddMouseEvent = 762, MouseEventCapture = 763, MouseEventNameField = 764, MouseEventStatus = 765;
void prepareMouseProfileChecks(HWND list, SettingsView &view)
{
const auto native = ListView_GetImageList(list, LVSIL_STATE);
int width{}, height{};
if (!native || !ImageList_GetIconSize(native, &width, &height)) return;
const auto checked = ImageList_GetIcon(native, 1, ILD_TRANSPARENT);
const auto unchecked = ImageList_GetIcon(native, 0, ILD_TRANSPARENT);
// Keep the native checked states and keyboard handling. Use transparent state
// images so only the glyph we place at the center of the column is visible.
const auto blank = ImageList_Create(1, height, ILC_COLOR32 | ILC_MASK, 2, 0);
const std::vector<WORD> white(height, 0xFFFF);
const auto mask = CreateBitmap(1, height, 1, 1, white.data());
const bool ready = blank && checked && unchecked && mask &&
ImageList_Add(blank, mask, mask) == 0 && ImageList_Add(blank, mask, mask) == 1;
if (mask) DeleteObject(mask);
if (!ready)
{
if (blank) ImageList_Destroy(blank);
if (checked) DestroyIcon(checked);
if (unchecked) DestroyIcon(unchecked);
return;
}
if (const auto previous = ListView_SetImageList(list, blank, LVSIL_STATE)) ImageList_Destroy(previous);
view.mouseProfileChecks = {unchecked, checked};
const auto dpi = GetDpiForWindow(list);
view.mouseProfileCheckSize = {MulDiv(width, 96, dpi), MulDiv(height, 96, dpi)};
}
bool mouseProfileCheckBounds(HWND list, const SettingsView &view, int row, RECT &glyph, RECT &cell)
{
if (row < 0 || !view.mouseProfileChecks.front()) return false;
const auto header = ListView_GetHeader(list);
RECT column{}, item{};
if (!Header_GetItemRect(header, 0, &column) || !ListView_GetItemRect(list, row, &item, LVIR_BOUNDS))
return false;
MapWindowPoints(header, list, reinterpret_cast<POINT *>(&column), 2);
const int width = scale(list, view.mouseProfileCheckSize.cx), height = scale(list, view.mouseProfileCheckSize.cy);
const LONG left = column.left + (column.right - column.left - width) / 2;
const LONG top = item.top + (item.bottom - item.top - height) / 2;
glyph = {left, top, left + width, top + height};
cell = {column.left, item.top, column.right, item.bottom};
return true;
}
LRESULT drawMouseProfileChecks(const SettingsView &view, const NMLVCUSTOMDRAW &draw)
{
if (!view.mouseProfileChecks.front()) return CDRF_DODEFAULT;
if (draw.nmcd.dwDrawStage == CDDS_PREPAINT) return CDRF_NOTIFYITEMDRAW;
if (draw.nmcd.dwDrawStage == CDDS_ITEMPREPAINT) return CDRF_NOTIFYPOSTPAINT;
if (draw.nmcd.dwDrawStage == CDDS_ITEMPOSTPAINT)
{
const auto list = draw.nmcd.hdr.hwndFrom;
const auto row = static_cast<int>(draw.nmcd.dwItemSpec);
RECT glyph{}, cell{};
if (mouseProfileCheckBounds(list, view, row, glyph, cell))
{
const auto saved = SaveDC(draw.nmcd.hdc);
IntersectClipRect(draw.nmcd.hdc, cell.left, cell.top, cell.right, cell.bottom);
// The list view reserves a small strip for its native state image and
// paints it separately from the selected row. Blend that strip back in.
const int strip = scale(list, 4);
if (cell.right - cell.left > 2 * strip)
{
RECT client{};
GetClientRect(list, &client);
const int sample = std::min<int>(cell.right - strip, client.right - 1);
if (sample > cell.left + strip)
{
const auto background = GetPixel(draw.nmcd.hdc, sample, (cell.top + cell.bottom) / 2);
if (background != CLR_INVALID)
{
SetDCBrushColor(draw.nmcd.hdc, background);
RECT nativeStrip{cell.left, cell.top + 1, cell.left + strip, cell.bottom - 1};
FillRect(draw.nmcd.hdc, &nativeStrip, reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
}
}
const auto icon = view.mouseProfileChecks[ListView_GetCheckState(list, row) != FALSE];
DrawIconEx(draw.nmcd.hdc, glyph.left, glyph.top, icon, glyph.right - glyph.left,
glyph.bottom - glyph.top, 0, nullptr, DI_NORMAL);
RestoreDC(draw.nmcd.hdc, saved);
}
}
return CDRF_DODEFAULT;
}
std::wstring mouseActionLabel(const MouseAction &action)
{
if (action.type == MouseActionType::Shortcut) return action.shortcut.format();
@@ -25,7 +109,7 @@ int mouseEventAtRow(HWND list, int row)
void selectMouseEvent(HWND w, int event)
{
HWND list = GetDlgItem(w, 733);
HWND list = GetDlgItem(settingsPage(w), 733);
LVFINDINFOW search{LVFI_PARAM};
search.lParam = event;
const int row = ListView_FindItem(list, -1, &search);
@@ -37,9 +121,9 @@ void selectMouseEvent(HWND w, int event)
void fillMouseEvents(HWND w, SettingsView &view, int selection = 0)
{
const auto profile = selectedMouseProfile(w, view);
EnableWindow(GetDlgItem(w, RenameMouseProfile), isNamedMouseProfile(profile));
EnableWindow(GetDlgItem(w, DeleteMouseProfile), isNamedMouseProfile(profile));
HWND list = GetDlgItem(w, 733);
EnableWindow(GetDlgItem(settingsPage(w), RenameMouseProfile), isNamedMouseProfile(profile));
EnableWindow(GetDlgItem(settingsPage(w), DeleteMouseProfile), isNamedMouseProfile(profile));
HWND list = GetDlgItem(settingsPage(w), 733);
ListView_DeleteAllItems(list);
for (int event = 0; event < static_cast<int>(std::size(MouseEvents)); ++event)
{
@@ -79,14 +163,14 @@ std::set<std::wstring> profileApplications(const Settings &settings, const std::
void selectMouseProfile(HWND w, int row)
{
auto list = GetDlgItem(w, 731);
auto list = GetDlgItem(settingsPage(w), 731);
ListView_SetItemState(list, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
ListView_EnsureVisible(list, row, FALSE);
}
void appendMouseProfile(HWND w, SettingsView &view, const std::wstring &profile)
{
auto list = GetDlgItem(w, 731);
auto list = GetDlgItem(settingsPage(w), 731);
std::wstring text;
for (const auto &app : profile == GlobalMouseProfile ? std::set<std::wstring>{} : profileApplications(view.draft, profile))
{
@@ -135,7 +219,7 @@ bool blockMouseProfileStateChange(HWND w, SettingsView &view, const NMLISTVIEW &
void fillMouseProfiles(HWND w, SettingsView &view)
{
const auto previous = selectedMouseProfile(w, view);
ListView_DeleteAllItems(GetDlgItem(w, 731));
ListView_DeleteAllItems(GetDlgItem(settingsPage(w), 731));
view.mouseProfiles.clear();
appendMouseProfile(w, view, GlobalMouseProfile);
for (const auto &[app, bindings] : view.draft.mouseBindings)
@@ -163,12 +247,12 @@ LRESULT CALLBACK mouseButtonCaptureProc(HWND field, UINT msg, WPARAM wp, LPARAM
{
SetFocus(field);
SetCapture(field);
HWND settings = GetParent(field);
HWND settings = GetAncestor(field, GA_ROOT);
auto *view = reinterpret_cast<SettingsView *>(GetWindowLongPtrW(settings, GWLP_USERDATA));
if (view)
selectMouseEvent(settings, doubleClick && button < 3 ? button + 5 : button);
if (view)
value(settings, 738, std::wstring(L"Window event: ") + MouseButtonNames[button] +
value(settingsPage(settings), 738, std::wstring(L"Window event: ") + MouseButtonNames[button] +
L" | Presses: " + std::to_wstring(++view->mouseEvents));
}
else if (GetCapture() == field)
@@ -187,7 +271,7 @@ bool registerMouseTestInput(HWND w)
void readMouseTestInput(HWND w, SettingsView &view, HRAWINPUT handle)
{
HWND capture = GetDlgItem(w, 737);
HWND capture = GetDlgItem(settingsPage(w), 737);
if (!IsWindowVisible(capture)) return;
RAWINPUT input{};
UINT size = sizeof(input);
@@ -203,7 +287,7 @@ void readMouseTestInput(HWND w, SettingsView &view, HRAWINPUT handle)
{
if (!(input.data.mouse.usButtonFlags & downFlags[i])) continue;
value(w, 739, std::wstring(L"Raw Input: ") + MouseButtonNames[i] +
value(settingsPage(w), 739, std::wstring(L"Raw Input: ") + MouseButtonNames[i] +
L" | Presses: " + std::to_wstring(++view.rawMouseEvents));
}
}
@@ -272,7 +356,6 @@ struct MouseProfileEditor
constexpr int ActionApplications = 748, ActionApplicationName = 749, AddActionApp = 750, RemoveActionApp = 751;
constexpr int BrowseActionApp = 752;
constexpr int PickActionApp = 753;
constexpr int AddMouseProfile = 754, MouseProfileName = 755;
void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
@@ -295,7 +378,7 @@ void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
FrameRect(item.hDC, &folder, ink);
FillRect(item.hDC, &tab, ink);
}
else if (item.CtlID == PickActionApp)
else if (item.CtlID == AppWindowPickerIcon)
{
RECT target{x - half, y - half, x + half + 1, y + half + 1};
RECT horizontal{x - half - weight, y, x + half + weight + 1, y + 1};
@@ -344,14 +427,6 @@ void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
}
}
void addActionApplicationTooltip(HWND tips, HWND editor, int id, const wchar_t *text)
{
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, editor,
reinterpret_cast<UINT_PTR>(GetDlgItem(editor, id))};
tool.lpszText = const_cast<wchar_t *>(text);
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
}
void fillActionApplications(HWND w, const MouseProfileEditor &editor)
{
SendDlgItemMessageW(w, ActionApplications, LB_RESETCONTENT, 0, 0);
@@ -501,7 +576,7 @@ LRESULT CALLBACK mouseActionEditorProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
EnableWindow(parent, TRUE);
SetForegroundWindow(parent);
SetFocus(GetDlgItem(parent, 733));
SetFocus(GetDlgItem(settingsPage(parent), 733));
}
}
}
@@ -586,7 +661,7 @@ int mouseProfileRowAt(HWND list, POINT point)
void showMouseListMenu(HWND list, POINT point, bool profiles)
{
HWND w = GetParent(list);
HWND w = GetAncestor(list, GA_ROOT);
int event;
if (point.x == -1 && point.y == -1)
{
@@ -629,15 +704,36 @@ void showMouseListMenu(HWND list, POINT point, bool profiles)
if (command) SendMessageW(w, WM_COMMAND, command, 0);
}
LRESULT CALLBACK mouseEventListProc(HWND list, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR)
LRESULT CALLBACK mouseEventListProc(HWND list, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR data)
{
const bool profiles = GetDlgCtrlID(list) == 731;
if (profiles && (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK))
{
const auto &view = *reinterpret_cast<SettingsView *>(data);
POINT pt{GET_X_LPARAM(lp), GET_Y_LPARAM(lp)};
LVHITTESTINFO hit{pt};
ListView_HitTest(list, &hit);
const int row = mouseProfileRowAt(list, pt);
RECT glyph{}, cell{};
if (mouseProfileCheckBounds(list, view, row, glyph, cell))
{
const bool onGlyph = PtInRect(&glyph, pt) && PtInRect(&cell, pt);
if (onGlyph || (msg == WM_LBUTTONDOWN && (hit.flags & LVHT_ONITEMSTATEICON)))
{
SetFocus(list);
selectMouseProfile(GetAncestor(list, GA_ROOT), row);
if (onGlyph && msg == WM_LBUTTONDOWN)
ListView_SetCheckState(list, row, !ListView_GetCheckState(list, row));
return 0;
}
}
}
if (profiles && msg == WM_LBUTTONDBLCLK)
{
const int row = mouseProfileRowAt(list, {GET_X_LPARAM(lp), GET_Y_LPARAM(lp)});
if (row >= 0)
{
const auto owner = GetParent(list);
const auto owner = GetAncestor(list, GA_ROOT);
selectMouseProfile(owner, row);
SendMessageW(owner, WM_COMMAND, RenameMouseProfile, 0);
}
@@ -676,7 +772,7 @@ LRESULT CALLBACK mouseProfileNameProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
return 0;
}
if (msg == WM_DRAWITEM && (wp == AddActionApp || wp == RemoveActionApp || wp == BrowseActionApp || wp == PickActionApp))
if (msg == WM_DRAWITEM && (wp == AddActionApp || wp == RemoveActionApp || wp == BrowseActionApp || wp == AppWindowPickerIcon))
{
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
@@ -775,18 +871,13 @@ void showMouseProfileName(HWND owner, SettingsView &view, bool renaming)
control(w, L"BUTTON", L"&Remove application", WS_TABSTOP | BS_OWNERDRAW, RemoveActionApp, 430, 100, 32, 28);
HWND appName = edit(w, ActionApplicationName, 18, 207, 324);
SendMessageW(appName, EM_SETCUEBANNER, FALSE, reinterpret_cast<LPARAM>(L"Application executable (e.g. chrome.exe)"));
HWND picker = control(w, L"BUTTON", L"Drag to application window", WS_TABSTOP | BS_OWNERDRAW,
PickActionApp, 350, 205, 32, 28);
SetWindowSubclass(picker, appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&editor->pickerOutline));
HWND tips = createButtonTooltips(w);
createAppWindowPicker(w, AppWindowPickerIcon, 350, 205, 32, editor->pickerOutline, tips);
control(w, L"BUTTON", L"&Browse for application", WS_TABSTOP | BS_OWNERDRAW, BrowseActionApp, 390, 205, 32, 28);
control(w, L"BUTTON", L"Add a&pplication", WS_TABSTOP | BS_OWNERDRAW, AddActionApp, 430, 205, 32, 28);
HWND tips = CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, w, nullptr,
view.app->instance, nullptr);
addActionApplicationTooltip(tips, w, RemoveActionApp, L"Remove application");
addActionApplicationTooltip(tips, w, AddActionApp, L"Add application");
addActionApplicationTooltip(tips, w, BrowseActionApp, L"Browse for an executable or shortcut");
addActionApplicationTooltip(tips, w, PickActionApp, L"Drag to an application window");
addButtonTooltip(tips, w, RemoveActionApp, L"Remove application");
addButtonTooltip(tips, w, AddActionApp, L"Add application");
addButtonTooltip(tips, w, BrowseActionApp, L"Browse for an executable or shortcut");
fillActionApplications(w, *editor);
control(w, L"BUTTON", renaming ? L"&Apply" : L"&Add", WS_TABSTOP | BS_DEFPUSHBUTTON, IDOK, 248, 251, 100, 28);
button(w, L"Cancel", IDCANCEL, 362, 251, 100);
@@ -956,7 +1047,7 @@ LRESULT CALLBACK addMouseEventProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
EnableWindow(parent, TRUE);
SetForegroundWindow(parent);
SetFocus(GetDlgItem(parent, 733));
SetFocus(GetDlgItem(settingsPage(parent), 733));
}
}
}
@@ -1010,7 +1101,7 @@ bool handleMouseBindings(HWND w, SettingsView &view, WPARAM wp)
return true;
}
if (id != EditMouseEvent && id != ResetMouseEvent) return false;
const HWND list = GetDlgItem(w, 733);
const HWND list = GetDlgItem(settingsPage(w), 733);
const int event = mouseEventAtRow(list, ListView_GetNextItem(list, -1, LVNI_SELECTED));
if (event < 0) return true;
if (id == EditMouseEvent) showMouseActionEditor(w, view, event);
@@ -1028,38 +1119,38 @@ void scaleMouseTableColumns(HWND w, int previousDpi, int nextDpi)
{
for (int id : {731, 733})
{
const auto list = GetDlgItem(w, id);
const auto list = GetDlgItem(settingsPage(w), id);
const int count = Header_GetItemCount(ListView_GetHeader(list));
for (int column = 0; column < count; ++column)
ListView_SetColumnWidth(list, column, MulDiv(ListView_GetColumnWidth(list, column), nextDpi, previousDpi));
}
}
void createMousePage(HWND w, SettingsView &view)
void createMousePage(HWND root, SettingsView &view)
{
HWND w = view.viewport;
constexpr int profilesLeft = 18, actionsLeft = 369, tableWidth = 333;
constexpr int profilesRight = profilesLeft + tableWidth;
label(w, L"Profiles", 18, 64, 120);
label(w, L"Mouse events", actionsLeft, 64, tableWidth - 30);
settingsGroupLabel(w, L"Profiles", profilesLeft, 64, 120);
settingsGroupLabel(w, L"Mouse events", actionsLeft, 64, tableWidth - 30);
control(w, L"BUTTON", L"Add mouse event", WS_TABSTOP | BS_OWNERDRAW, AddMouseEvent,
actionsLeft + tableWidth - 24, 61, 24, 24);
control(w, L"BUTTON", L"Delete profile", WS_TABSTOP | BS_OWNERDRAW, DeleteMouseProfile, profilesRight - 80, 61, 24, 24);
control(w, L"BUTTON", L"Edit profile", WS_TABSTOP | BS_OWNERDRAW, RenameMouseProfile, profilesRight - 52, 61, 24, 24);
control(w, L"BUTTON", L"Add profile", WS_TABSTOP | BS_OWNERDRAW, AddMouseProfile, profilesRight - 24, 61, 24, 24);
HWND tips = CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, w, nullptr,
view.app->instance, nullptr);
addActionApplicationTooltip(tips, w, AddMouseProfile, L"Add profile");
addActionApplicationTooltip(tips, w, RenameMouseProfile, L"Edit profile");
addActionApplicationTooltip(tips, w, DeleteMouseProfile, L"Delete profile");
addActionApplicationTooltip(tips, w, AddMouseEvent, L"Add mouse event");
HWND tips = createButtonTooltips(w);
addButtonTooltip(tips, w, AddMouseProfile, L"Add profile");
addButtonTooltip(tips, w, RenameMouseProfile, L"Edit profile");
addButtonTooltip(tips, w, DeleteMouseProfile, L"Delete profile");
addButtonTooltip(tips, w, AddMouseEvent, L"Add mouse event");
constexpr int listTop = 90, listHeight = 224;
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES};
InitCommonControlsEx(&controls);
constexpr DWORD listStyle = WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER;
HWND profiles = control(w, WC_LISTVIEWW, L"", listStyle, 731, profilesLeft, listTop, tableWidth, listHeight);
SetWindowSubclass(profiles, mouseEventListProc, 3, 0);
SetWindowSubclass(profiles, mouseEventListProc, 3, reinterpret_cast<DWORD_PTR>(&view));
ListView_SetExtendedListViewStyle(profiles, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP | LVS_EX_CHECKBOXES);
prepareMouseProfileChecks(profiles, view);
wchar_t nameTitle[] = L"Name", activeTitle[] = L"Active", applicationsTitle[] = L"Applications";
LVCOLUMNW profileColumn{LVCF_TEXT | LVCF_WIDTH};
profileColumn.pszText = activeTitle;
@@ -1073,6 +1164,13 @@ void createMousePage(HWND w, SettingsView &view)
ListView_InsertColumn(profiles, 2, &profileColumn);
int order[]{1, 0, 2};
ListView_SetColumnOrderArray(profiles, 3, order);
HDITEMW alignment{HDI_FORMAT};
const auto header = ListView_GetHeader(profiles);
if (Header_GetItem(header, 0, &alignment))
{
alignment.fmt = (alignment.fmt & ~HDF_JUSTIFYMASK) | HDF_CENTER;
Header_SetItem(header, 0, &alignment);
}
HWND list = control(w, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT |
LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 733, actionsLeft, listTop, tableWidth, listHeight);
SetWindowSubclass(list, mouseEventListProc, 3, 0);
@@ -1090,7 +1188,7 @@ void createMousePage(HWND w, SettingsView &view)
737, profilesLeft, listTop + listHeight + 10, tableWidth, 56);
SetWindowSubclass(GetDlgItem(w, 737), mouseButtonCaptureProc, 1, 0);
control(w, L"STATIC", L"Window event: waiting for a press", 0, 738, actionsLeft, 370, tableWidth, 20);
view.rawMouseRegistered = registerMouseTestInput(w);
view.rawMouseRegistered = registerMouseTestInput(root);
control(w, L"STATIC", view.rawMouseRegistered ? L"Raw Input: waiting for a press" : L"Raw Input: unavailable",
0, 739, actionsLeft, 394, tableWidth, 20);
}
+93 -44
View File
@@ -1,5 +1,6 @@
#include "ui_sync_conflicts.inl"
struct SyncView { HWND parent; App *app; bool actionError{}; };
constexpr int SyncSave = 614;
struct SyncView { App *app; bool initialized{}, actionError{}; };
void updateSyncControls(HWND w, App &app)
{
bool enabled = checked(w, 601);
@@ -7,14 +8,14 @@ void updateSyncControls(HWND w, App &app)
for (int id : {602, 603, 604, 605, 606, 607, 610, 611, 613})
EnableWindow(GetDlgItem(w, id), enabled);
EnableWindow(GetDlgItem(w, 612), enabled && savedEnabled);
EnableWindow(GetDlgItem(w, IDOK), enabled || savedEnabled);
value(w, IDOK, enabled ? L"&Save / Sign in / Sync" : L"&Save");
EnableWindow(GetDlgItem(w, SyncSave), enabled || savedEnabled);
value(w, SyncSave, enabled ? L"Save and s&ync" : L"S&ave connection");
std::wstring status;
if (!enabled)
status = savedEnabled ? L"Click Save to disable synchronization." :
status = savedEnabled ? L"Click Save connection to disable synchronization." :
L"Synchronization is disabled. Enable it above to configure and sync.";
else if (!savedEnabled)
status = L"Configure the connection, then click Save / Sign in / Sync to enable synchronization.";
status = L"Configure the connection, then click Save and sync to enable synchronization.";
else
status = app.syncCommand();
auto *view = reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
@@ -33,11 +34,30 @@ SyncConfig syncFields(HWND w)
}
LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
if (msg == WM_DPICHANGED) { resizeForDpi(w, wp, lp); return 0; }
if (msg == WM_SIZE) arrangeWindow(w);
auto *v = reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
if (!v) return DefWindowProcW(w, msg, wp, lp);
try
{
if (msg == WM_PAINT) { paintSettingsMatches(w); return 0; }
if (msg == WM_CTLCOLORSTATIC) return SendMessageW(GetParent(w), msg, wp, lp);
if (msg == WM_SHOWWINDOW)
{
if (!wp) KillTimer(w, 1);
else
{
if (!v->initialized)
{
const auto c = loadSyncConfig(v->app->data);
check(w, 601, c.enabled); check(w, 613, c.keepLocalLayouts);
value(w, 602, c.server); value(w, 603, c.username);
value(w, 605, c.mount); value(w, 606, c.path); value(w, 607, c.authMount);
v->initialized = true;
}
updateSyncControls(w, *v->app);
SetTimer(w, 1, 1000, nullptr);
}
}
if (msg == WM_TIMER)
{
updateSyncControls(w, *v->app);
@@ -52,10 +72,9 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
updateSyncControls(w, *v->app);
return 0;
}
if ((id == IDOK || id == 610 || id == 611 || id == 612) &&
if ((id == SyncSave || id == 610 || id == 611 || id == 612) &&
!IsWindowEnabled(GetDlgItem(w, id))) return 0;
if (id == 612) { showSyncConflicts(w, *v->app); return 0; }
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
if (id == 609)
{
v->actionError = false;
@@ -70,12 +89,12 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
KillTimer(w, 1);
return 0;
}
if (id == IDOK || id == 610 || id == 611)
if (id == SyncSave || id == 610 || id == 611)
{
v->actionError = false;
if (!checked(w, 601))
{
if (id != IDOK) return 0;
if (id != SyncSave) return 0;
auto c = loadSyncConfig(v->app->data);
c.enabled = false;
saveSyncConfig(v->app->data, c);
@@ -83,7 +102,7 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
updateSyncControls(w, *v->app);
return 0;
}
if (id != IDOK && MessageBoxW(w, id == 610 ?
if (id != SyncSave && MessageBoxW(GetAncestor(w, GA_ROOT), id == 610 ?
L"Replace this PC's shared settings with the remote profile? A local backup will be saved. The open Settings window will refresh automatically; its unsaved edits will be discarded." :
L"Replace the remote profile with this PC's saved settings? OpenBao retains older versions according to its retention policy. Unsaved edits are not included.",
L"Resolve synchronization", MB_YESNO | MB_ICONWARNING) != IDYES) return 0;
@@ -111,44 +130,74 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
value(w, 608, wide(e.what()));
return 0;
}
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
if (msg == WM_NCDESTROY)
{
KillTimer(w, 1);
EnableWindow(v->parent, TRUE); SetForegroundWindow(v->parent);
disposeFont(w); delete v; SetWindowLongPtrW(w, GWLP_USERDATA, 0);
delete windowLayoutState(w);
RemovePropW(w, L"WindowLayout");
RemovePropW(w, L"Font");
delete v;
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
}
return DefWindowProcW(w, msg, wp, lp);
}
void showSyncOptions(HWND parent, App &app)
constexpr int SyncSettingsWidth = 660, SyncSettingsHeight = 550;
constexpr int SyncSettingsMargin = 16, SyncSettingsGap = 16, SyncFieldsTop = 78, SyncActionsTop = 294;
constexpr int SyncColumnWidth = (SyncSettingsWidth - 2 * SyncSettingsMargin - SyncSettingsGap) / 2;
constexpr int SyncRightColumn = SyncSettingsMargin + SyncColumnWidth + SyncSettingsGap;
HWND createSyncSettings(HWND pane, App &app)
{
auto c = loadSyncConfig(app.data);
HWND w = makeWindow(app, L"KSwitcher.Sync", L"Settings synchronization - OpenBao", syncProc, 660, 672);
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)new SyncView{parent, &app});
checkbox(w, L"&Enable synchronization with your OpenBao (KV v2)", 601, 18, 18, 620);
check(w, 601, c.enabled);
label(w, L"Se&rver (HTTPS)", 18, 60, 160); edit(w, 602, 190, 56, 450); value(w, 602, c.server);
label(w, L"User&name", 18, 100, 160); edit(w, 603, 190, 96, 450); value(w, 603, c.username);
label(w, L"&Password", 18, 140, 160); edit(w, 604, 190, 136, 450, 25, ES_AUTOHSCROLL | ES_PASSWORD);
label(w, L"Leave password blank to use the saved Windows credential.", 190, 166, 450);
label(w, L"KV v2 &mount", 18, 210, 160); edit(w, 605, 190, 206, 450); value(w, 605, c.mount);
label(w, L"Profile pa&th", 18, 250, 160); edit(w, 606, 190, 246, 450); value(w, 606, c.path);
label(w, L"&Login mount", 18, 290, 160); edit(w, 607, 190, 286, 450); value(w, 607, c.authMount);
label(w, L"Sync uses saved settings. Download remote refreshes the open Settings window.", 18, 330, 622);
edit(w, 608, 18, 362, 622, 76, ES_MULTILINE | ES_READONLY | WS_VSCROLL | ES_AUTOVSCROLL);
value(w, 608, app.syncCommand());
checkbox(w, L"&Keep this PC's layouts and layout shortcuts (sync other settings)", 613, 18, 446, 622);
check(w, 613, c.keepLocalLayouts);
button(w, L"&Save / Sign in / Sync", IDOK, 18, 484, 200);
button(w, L"&Download remote", 610, 230, 484, 195);
button(w, L"&Upload local", 611, 437, 484, 203);
button(w, L"Resolve &individual conflicts...", 612, 18, 530, 300);
label(w, L"Background check: every 10 minutes", 330, 534, 310);
button(w, L"Disconnect / &forget password", 609, 18, 582, 290);
button(w, L"&Close", IDCANCEL, 540, 582, 100);
updateSyncControls(w, app);
EnableWindow(parent, FALSE);
SetTimer(w, 1, 1000, nullptr);
showRequestedWindow(w); SetForegroundWindow(w);
WNDCLASSW panel{};
panel.hInstance = app.instance;
panel.lpfnWndProc = syncProc;
panel.lpszClassName = L"KSwitcher.Sync";
panel.hCursor = LoadCursorW(nullptr, IDC_ARROW);
panel.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
RegisterClassW(&panel);
HWND w = CreateWindowExW(WS_EX_CONTROLPARENT, panel.lpszClassName, L"", WS_CHILD | WS_CLIPCHILDREN,
0, 0, scale(pane, SyncSettingsWidth), scale(pane, SyncSettingsHeight),
pane, reinterpret_cast<HMENU>(SettingsSyncPanel), app.instance, nullptr);
if (!w) throw std::runtime_error("Cannot create OpenBao settings.");
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(new SyncView{&app}));
SetPropW(w, L"Font", GetPropW(pane, L"Font"));
auto *layout = new WindowLayout{SyncSettingsWidth, SyncSettingsHeight, 0, 0, true, true};
SetPropW(w, L"WindowLayout", layout);
constexpr int left = SyncSettingsMargin, width = SyncSettingsWidth - 2 * left;
settingsGroupLabel(w, L"Connection", left, 14, width);
checkbox(w, L"&Enable synchronization with OpenBao", 601, left, 42, width);
auto field = [&](int id, const wchar_t *name, int x, int y, DWORD style = ES_AUTOHSCROLL)
{
label(w, name, x, y, SyncColumnWidth);
edit(w, id, x, y + 24, SyncColumnWidth, 25, style);
};
field(602, L"Se&rver (HTTPS)", left, SyncFieldsTop);
field(603, L"User&name", left, SyncFieldsTop + 59);
field(604, L"&Password", left, SyncFieldsTop + 118, ES_AUTOHSCROLL | ES_PASSWORD);
label(w, L"Leave blank to use the saved Windows credential.", left, 250, SyncColumnWidth);
field(605, L"KV v2 &mount", SyncRightColumn, SyncFieldsTop);
field(606, L"Profile pa&th", SyncRightColumn, SyncFieldsTop + 59);
field(607, L"&Login mount", SyncRightColumn, SyncFieldsTop + 118);
checkbox(w, L"&Keep this PC's layouts and layout shortcuts", 613, left, SyncActionsTop, width);
settingsGroupLabel(w, L"Synchronization", left, SyncActionsTop + 38, width);
label(w, L"Sync uses saved settings. Download remote refreshes the open Settings window.", left, 360, width);
button(w, L"Save and s&ync", SyncSave, left, 387, 196);
button(w, L"&Download remote", 610, 222, 387, 200);
button(w, L"&Upload local", 611, 432, 387, 212);
edit(w, 608, left, 423, width, 66, ES_MULTILINE | ES_READONLY | WS_VSCROLL | ES_AUTOVSCROLL);
button(w, L"Resolve &individual conflicts…", 612, left, 499, SyncColumnWidth);
button(w, L"Disconnect / &forget password", 609, SyncRightColumn, 499, SyncColumnWidth);
for (int id : {602, 603, 604, 605, 606, 607, 610, 611, 612, 613, SyncSave})
EnableWindow(GetDlgItem(w, id), FALSE);
captureSettingsGeometry(*layout, 0, w);
layout->arranging = false;
return w;
}
int fitSyncSettings(HWND panel, int width)
{
auto &layout = *windowLayoutState(panel);
layout.width = 1;
layout.height = fitSettingsColumns(layout, 0, layout.controls.size(), width,
{SyncSettingsMargin, SyncSettingsWidth - SyncSettingsMargin, SyncRightColumn,
SyncSettingsMargin + SyncColumnWidth, SyncActionsTop, 610, 0, SyncFieldsTop});
return layout.height;
}
+5 -3
View File
@@ -51,7 +51,8 @@ LRESULT CALLBACK syncConflictsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
if (msg == WM_NCDESTROY)
{
EnableWindow(v->parent, TRUE); SetForegroundWindow(v->parent);
const auto owner = GetAncestor(v->parent, GA_ROOT);
EnableWindow(owner, TRUE); SetForegroundWindow(owner);
disposeFont(w); delete v; SetWindowLongPtrW(w, GWLP_USERDATA, 0);
}
return DefWindowProcW(w, msg, wp, lp);
@@ -60,8 +61,9 @@ void showSyncConflicts(HWND parent, App &app)
{
auto conflicts = decodeSyncConflicts(app.syncConflictData());
if (conflicts.empty()) { value(parent, 608, L"No pending conflicts. Run Sync to check for changes."); return; }
const auto owner = GetAncestor(parent, GA_ROOT);
HWND w = makeWindow(app, L"KSwitcher.SyncConflicts", L"Resolve individual settings", syncConflictsProc, 800, 560);
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
SetWindowLongPtrW(w, GWLP_HWNDPARENT, reinterpret_cast<LONG_PTR>(owner));
auto *v = new SyncConflictView{parent, &app, std::move(conflicts), {}};
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
label(w, L"Choose a value for each conflicting setting. Other changes are already synchronized.", 18, 16, 760);
@@ -76,5 +78,5 @@ void showSyncConflicts(HWND parent, App &app)
button(w, L"&Apply choices", IDOK, 526, 488, 140);
button(w, L"&Cancel", IDCANCEL, 678, 488, 100);
SendDlgItemMessageW(w, 620, LB_SETCURSEL, 0, 0); showConflictValues(w, v);
EnableWindow(parent, FALSE); showRequestedWindow(w); SetForegroundWindow(w);
EnableWindow(owner, FALSE); showRequestedWindow(w); SetForegroundWindow(w);
}
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.119";
inline constexpr wchar_t AppVersion[] = L"0.7.2";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+583 -125
View File
@@ -2,6 +2,7 @@
#include "ocr.h"
#include "screenshot.h"
#include "lan_pairing.h"
#include "settings_ui.h"
#include <iostream>
#include <commctrl.h>
@@ -22,6 +23,102 @@ 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');
@@ -33,21 +130,17 @@ void lanWindowLayoutChecks(const std::filesystem::path &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);
SendMessageW(app.settingsWindow,WM_COMMAND,262,0);
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
require(lan!=nullptr,"Computers window opens");
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 room{0,0,MulDiv(750,dpi,96),MulDiv(510,dpi,96)};
AdjustWindowRectExForDpi(&room,GetWindowLongPtrW(lan,GWL_STYLE)&~(WS_HSCROLL|WS_VSCROLL),
FALSE,GetWindowLongPtrW(lan,GWL_EXSTYLE),dpi);
RECT frame{};GetWindowRect(lan,&frame);
SetWindowPos(lan,nullptr,0,0,std::min(frame.right-frame.left,room.right-room.left),
std::min(frame.bottom-frame.top,room.bottom-room.top),SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
require(!(GetWindowLongPtrW(lan,GWL_STYLE)&(WS_HSCROLL|WS_VSCROLL)),"Computers window fits without scrollbars");
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,
@@ -62,13 +155,37 @@ void lanWindowLayoutChecks(const std::filesystem::path &root)
}
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 &&
pair.right - pair.left == cancel.right - cancel.left &&
cancel.right - cancel.left == forget.right - forget.left &&
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(lan,WM_COMMAND,IDCANCEL,0);
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
std::cout<<"Computers layout verified at "<<dpi<<" DPI.\n";
}
@@ -163,6 +280,187 @@ void contextChecks()
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)
{
@@ -177,7 +475,25 @@ int main(int argc,char **argv)
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");
@@ -194,17 +510,17 @@ int main(int argc,char **argv)
require(!saveEnabled() && status()==L"No unsaved settings.","new Settings shows clean state with Save disabled");
SendMessageW(parent,WM_COMMAND,IDOK,0);
require(IsWindow(parent),"Save command with no changes does not apply or close Settings");
bool originalLog=IsDlgButtonChecked(parent,208)==BST_CHECKED;
CheckDlgButton(parent,208,originalLog?BST_UNCHECKED:BST_CHECKED);
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() && status().find(L"Unsaved settings") == 0,"checkbox edit immediately marks Settings dirty");
CheckDlgButton(parent,208,originalLog?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(settingsViewport(parent),208,originalLog?BST_CHECKED:BST_UNCHECKED);
SendMessageW(parent,WM_COMMAND,MAKEWPARAM(208,BN_CLICKED),0);
require(!saveEnabled(),"reverting checkbox disables Save again");
wchar_t originalLimit[32]{}; GetDlgItemTextW(parent,240,originalLimit,32);
SetDlgItemTextW(parent,240,L"invalid");
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(parent,240,originalLimit);
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);
@@ -223,33 +539,41 @@ int main(int argc,char **argv)
SetDlgItemTextW(ocr,503,languages);
SendMessageW(ocr,WM_COMMAND,IDOK,0);
require(!saveEnabled(),"reverting OCR draft in child clears parent dirty state");
SendMessageW(parent,WM_COMMAND,255,0);
HWND automatic=findTestWindow(L"KSwitcher.AutoOptions",nullptr);
require(automatic!=nullptr,"automatic correction preferences open");
bool replace=IsDlgButtonChecked(automatic,414)==BST_CHECKED;
CheckDlgButton(automatic,414,replace?BST_UNCHECKED:BST_CHECKED);
SendMessageW(automatic,WM_COMMAND,IDOK,0);
require(!IsWindow(automatic) && saveEnabled(),"accepted auto-correction edits enable Save");
SendMessageW(parent,WM_COMMAND,255,0);
automatic=findTestWindow(L"KSwitcher.AutoOptions",nullptr);
CheckDlgButton(automatic,414,replace?BST_CHECKED:BST_UNCHECKED);
SendMessageW(automatic,WM_COMMAND,IDOK,0);
require(!saveEnabled(),"reverting auto-correction draft disables Save");
HWND tabs = GetDlgItem(parent, 260);
require(tabs && TabCtrl_GetItemCount(tabs) == 10, "ten settings categories");
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(parent, 281, mcpConfig, std::size(mcpConfig));
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 tab shows a Codex stdio configuration");
for (int page = 0; page < TabCtrl_GetItemCount(tabs); ++page)
"MCP section shows a Codex stdio configuration");
for (int page = 0; page < sections; ++page)
{
TabCtrl_SetCurSel(tabs, page);
NMHDR notification{tabs, 260, TCN_SELCHANGE};
SendMessageW(parent, WM_NOTIFY, 260, (LPARAM)&notification);
selectSettingsPage(parent, page);
std::vector<RECT> boxes;
for (HWND child = GetWindow(parent, GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
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);
@@ -265,13 +589,208 @@ int main(int argc,char **argv)
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-tab-" + std::to_wstring(page) + L".png"),
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / (L"settings-section-" + std::to_wstring(page) + L".png"),
ks::encodePng(ks::decodeImage(clip)));
}
TabCtrl_SetCurSel(tabs, 1);
NMHDR notification{tabs, 260, TCN_SELCHANGE};
SendMessageW(parent, WM_NOTIFY, 260, (LPARAM)&notification);
require(!saveEnabled(),"changing tabs leaves Settings clean");
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 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);
HIGHCONTRASTW contrast{sizeof(contrast)};
SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0);
if (!(contrast.dwFlags & HCF_HIGHCONTRASTON))
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 (!(contrast.dwFlags & HCF_HIGHCONTRASTON))
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");
@@ -309,9 +828,15 @@ int main(int argc,char **argv)
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");
require(ks::loadSettings(root / L"settings.json", app.layouts).chatCycles == app.settings.chatCycles, "profile saved to disk");
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");
@@ -347,36 +872,8 @@ int main(int argc,char **argv)
SendDlgItemMessageW(dialog, 722, LB_SETSEL, TRUE, -1);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(722, LBN_SELCHANGE), 0);
HWND picker = GetDlgItem(dialog, 728);
RECT dialogBounds{};
GetWindowRect(dialog, &dialogBounds);
MONITORINFO monitor{sizeof(monitor)};
require(GetMonitorInfoW(MonitorFromWindow(dialog, 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");
SendMessageW(picker, WM_KEYDOWN, VK_ESCAPE, 0);
require(!IsWindow(outline) && GetCapture() != picker, "Escape clears the outline and releases capture");
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
SendMessageW(picker, WM_LBUTTONUP, 0, MAKELPARAM(drop.x, drop.y));
require(!IsWindow(outline), "dropping clears the outline");
auto pickedApp = ks::applicationName(ks::processName(target));
DestroyWindow(target);
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");
@@ -425,60 +922,24 @@ int main(int argc,char **argv)
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");
app.settings.snippets = {{L";scope", L"Example", L"scope-fixture"}};
ks::showSettings(app); parent=app.settingsWindow;
require(!saveEnabled(),"Settings starts clean before separately saved snippet edit");
ks::showSnippets(app);
HWND snippets = 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(IsDlgButtonChecked(snippets,314)==BST_UNCHECKED, "old snippet shows everywhere");
CheckDlgButton(snippets,314,BST_CHECKED);
SendMessageW(snippets,WM_COMMAND,314,0);
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");
SendMessageW(snippets,WM_COMMAND,318,0);
require(IsWindow(snippets) && app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "inline snippet editor saves selected applications");
require(!saveEnabled() && status()==L"No unsaved settings.","separately saved snippet edit leaves Settings clean");
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)));
SendMessageW(parent,WM_COMMAND,IDCANCEL,0);
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");
SendMessageW(snippets,WM_COMMAND,IDCANCEL,0);
require(app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "cancel preserves existing scope");
snippetEditorChecks(app, root);
ks::showSettings(app);parent=app.settingsWindow;
SendMessageW(parent,WM_COMMAND,262,0);
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
require(lan && !IsWindowEnabled(parent),"LAN pairing opens a native child window");
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_THICKFRAME|WS_MAXIMIZEBOX)),"LAN window has a fixed size");
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(lan),"connection help opens without changing network settings");
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&&
@@ -490,13 +951,12 @@ int main(int argc,char **argv)
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(lan),"closing connection help returns to LAN setup");
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)));
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);
require(IsWindowEnabled(parent)&&!saveEnabled(),"closing discovery restores Settings without false unsaved state");
require(IsWindowEnabled(parent)&&!saveEnabled(),"opening discovery leaves Settings clean");
require(status().find(L"Network changes save automatically")!=std::wstring::npos,"Settings explains why network actions do not enable Save");
SendMessageW(parent,WM_COMMAND,IDCANCEL,0);
}
@@ -505,8 +965,7 @@ int main(int argc,char **argv)
{"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);ks::showSettings(pairedApp);
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,262,0);
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
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");
@@ -532,8 +991,7 @@ int main(int argc,char **argv)
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)));
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
}
{
using J=ks::lan::Json;const std::string b(32,'b'),c(32,'c');
@@ -542,7 +1000,7 @@ int main(int argc,char **argv)
{"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);
SendMessageW(layoutApp.settingsWindow,WM_COMMAND,262,0);auto lan=findTestWindow(L"KSwitcher.LAN",nullptr);auto grid=GetDlgItem(lan,721);
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));
@@ -551,7 +1009,7 @@ int main(int argc,char **argv)
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)));
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);SendMessageW(layoutApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
SendMessageW(layoutApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
}
std::filesystem::remove_all(root);
std::cout << "Passed " << passed << " chat profile checks\n";
+79 -4
View File
@@ -4,6 +4,8 @@
#include <psapi.h>
#include <iostream>
#include <algorithm>
#include <future>
#include <thread>
static void require(bool ok, const char *name) {
if (!ok) throw std::runtime_error(name);
std::cout << "PASS " << name << '\n';
@@ -39,12 +41,66 @@ static void verifyImage(HWND w) {
}
require(c.text()==L"Snapshot mixed text","preserves accompanying text");
}
static LRESULT CALLBACK delayedImageOwner(HWND window, UINT message, WPARAM format, LPARAM param) {
if (message == WM_RENDERFORMAT && format == CF_DIB) {
const auto dib = ks::imageDib(ks::Pixels{1, 1, ks::Bytes{77, 0, 0, 255}});
if (auto data = GlobalAlloc(GMEM_MOVEABLE, dib.data.size())) {
if (auto bytes = GlobalLock(data)) {
memcpy(bytes, dib.data.data(), dib.data.size());
GlobalUnlock(data);
if (SetClipboardData(CF_DIB, data)) return 0;
}
GlobalFree(data);
}
return 0;
}
return DefWindowProcW(window, message, format, param);
}
static void verifyDelayedImageSnapshot(HWND window) {
std::promise<HWND> ready;
auto owner = ready.get_future();
std::jthread publisher([&] {
WNDCLASSW wc{};
wc.lpfnWndProc = delayedImageOwner;
wc.hInstance = GetModuleHandleW(nullptr);
wc.lpszClassName = L"KSwitcher.DelayedClipboardFixture";
HWND delayed = RegisterClassW(&wc) ? CreateWindowExW(0, wc.lpszClassName, L"", 0, 0, 0, 0, 0,
HWND_MESSAGE, nullptr, wc.hInstance, nullptr) : nullptr;
bool published = false;
if (delayed && OpenClipboard(delayed)) {
if (EmptyClipboard()) SetClipboardData(CF_DIB, nullptr);
published = IsClipboardFormatAvailable(CF_DIB) && GetClipboardOwner() == delayed;
CloseClipboard();
}
ready.set_value(published ? delayed : nullptr);
if (published) {
MSG message{};
while (GetMessageW(&message, delayed, 0, 0) > 0 && message.message != WM_CLOSE)
DispatchMessageW(&message);
}
if (delayed) DestroyWindow(delayed);
});
const auto delayed = owner.get();
require(delayed != nullptr, "publishes a delayed image format");
struct CloseOwner { HWND window; ~CloseOwner() { PostMessageW(window, WM_CLOSE, 0, 0); } } close{delayed};
const auto before = GetClipboardSequenceNumber();
ks::ClipboardSnapshot snapshot;
const auto captured = snapshot.capture(window, before);
require(captured == GetClipboardSequenceNumber(), "snapshot reports the sequence after delayed rendering");
const auto temporary = ks::writeClipboard(window, ks::textClip(L"temporary"));
snapshot.restore(window, temporary);
const auto clip = ks::readClipboard(window);
const auto image = ks::decodeImage(clip);
require(image.width == 1 && image.height == 1 && image.bgra.front() == 77, "restores the delayed image");
}
int main(int argc,char**argv) {
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
HWND w=owner(); int result=0; ks::Clip original; bool saved=false;
try {
std::string mode=argc>1?argv[1]:"suite";
if(mode=="publish") {
if(mode=="temporary") {
ks::writeClipboard(w,ks::textClip(L"temporary"));
} else if(mode=="publish") {
ks::Pixels p{1566,1068,ks::Bytes(1566*1068*4,255)}; p.bgra[0]=77;
auto dib=ks::imageDib(p); auto v5=dib;
BITMAPV5HEADER h{}; h.bV5Size=sizeof(h); h.bV5Width=p.width; h.bV5Height=-p.height;
@@ -60,9 +116,17 @@ int main(int argc,char**argv) {
auto clip=ks::readClipboard(w,64*1024*1024);
ks::writeClipboard(w,ks::textClip(L"temporary")); ks::writeClipboard(w,clip);
} else {
ks::ClipboardSnapshot snapshot; snapshot.capture(w,GetClipboardSequenceNumber());
auto seq=ks::writeClipboard(w,ks::textClip(L"temporary"));
require(snapshot.restore(w,seq)==GetClipboardSequenceNumber(),"helper returns current sequence");
ks::ClipboardSnapshot snapshot;
auto started=GetTickCount64();
snapshot.capture(w,GetClipboardSequenceNumber());
std::cout<<"Image snapshot capture: "<<GetTickCount64()-started<<" ms\n";
// A separate publisher avoids blocking clipboard notifications on this waiting test thread.
child(L"temporary");
const auto seq=GetClipboardSequenceNumber();
started=GetTickCount64();
const auto restored=snapshot.restore(w,seq);
std::cout<<"Image snapshot restore: "<<GetTickCount64()-started<<" ms\n";
require(restored==GetClipboardSequenceNumber(),"helper returns current sequence");
}
auto after=resident();
auto report="baseline="+std::to_string(baseline)+" after="+std::to_string(after)+" delta="+std::to_string(int64_t(after)-int64_t(baseline))+"\n";
@@ -78,6 +142,16 @@ int main(int argc,char**argv) {
bool rejected=false;
try {ks::readClipboard(w,32*1024*1024,ks::ClipboardRead::WithoutImages,seq);} catch(...) {rejected=true;}
require(rejected,"resident rejects images before reading their data");
{
ks::ClipboardSnapshot snapshot;
try {snapshot.capture(w,seq-1); rejected=false;}
catch(const std::runtime_error &error) {
rejected=std::string_view(error.what()).find("Clipboard changed while taking snapshot") != std::string_view::npos;
}
require(rejected,"stale image snapshot reports the sequence mismatch");
snapshot.capture(w,seq);
}
require(GetClipboardSequenceNumber()==seq,"discarding an image snapshot leaves the clipboard untouched");
{
ks::ClipboardSnapshot snapshot; snapshot.capture(w,seq);
auto stale=ks::writeClipboard(w,ks::textClip(L"temporary"));
@@ -100,6 +174,7 @@ int main(int argc,char**argv) {
auto marked=ks::textClip(L"line"); marked.formats.push_back({0,L"MSDEVLineSelect",ks::Bytes{1}});
ks::writeClipboard(w,marked);
require(ks::readClipboard(w,1024,ks::ClipboardRead::Selection).formats.size()==2,"selection reader preserves editor guard metadata");
verifyDelayedImageSnapshot(w);
std::cout<<"PASS clipboard snapshot suite\n";
}
} catch(const std::exception &e) {std::cerr<<"FAIL "<<e.what()<<'\n';result=1;}
+32 -8
View File
@@ -19,6 +19,7 @@ public static class ConfigurationTestUi {
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindow(string cls,string title);
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr w,int id);
[DllImport("user32.dll")] public static extern bool IsWindowEnabled(IntPtr w);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr w);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr w,uint msg,IntPtr wp,IntPtr lp);
[DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr w,uint msg,IntPtr wp,IntPtr lp);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SetText(IntPtr w,uint msg,IntPtr wp,string text);
@@ -41,7 +42,8 @@ function Window($class) {
for($i=0;$i -lt 100;$i++) {
$title=switch($class){'KSwitcher.Main'{'KSwitcher'};'KSwitcher.Settings'{'KSwitcher settings'};'KSwitcher.Snippets'{'Text snippets'};'KSwitcher.Logs'{'KSwitcher diagnostic operations'}}
$window=[ConfigurationTestUi]::FindWindow($class,$title)
if($window -ne [IntPtr]::Zero){return $window}
if($window -ne [IntPtr]::Zero -and
($class -eq 'KSwitcher.Main' -or [ConfigurationTestUi]::IsWindowVisible($window))) { return $window }
Start-Sleep -Milliseconds 50
}
foreach($process in $processes){$process.Refresh(); Write-Host ("Diagnostic process {0}: exited={1} title={2}" -f $process.Id,$process.HasExited,$process.MainWindowTitle)}
@@ -57,6 +59,14 @@ function Launch($file,$argument) {
function Click($window,$id) {
$null=[ConfigurationTestUi]::PostMessage($window,0x111,[IntPtr]$id,[IntPtr]::Zero)
}
function SelectSection($settings,$index) {
$navigation=[ConfigurationTestUi]::GetDlgItem($settings,260)
$node=[ConfigurationTestUi]::SendMessage($navigation,0x110a,[IntPtr]::Zero,[IntPtr]::Zero)
for($i=0;$i -lt $index;$i++) {
$node=[ConfigurationTestUi]::SendMessage($navigation,0x110a,[IntPtr]1,$node)
}
$null=[ConfigurationTestUi]::SendMessage($navigation,0x110b,[IntPtr]9,$node)
}
function TestLogs {
'test-marker' | Set-Content -LiteralPath (Join-Path $root 'data/kswitcher.log')
$config=Launch 'KSwitcher.Config.exe' '--logs'
@@ -101,9 +111,15 @@ try {
$second=Launch 'KSwitcher.Config.exe' ''
Assert ($second.WaitForExit(6000) -and $second.ExitCode -eq 0) 'second launch forwards to existing instance'
Assert ((Window 'KSwitcher.Settings') -eq $settings) 'existing settings window reused'
$pane=[ConfigurationTestUi]::GetDlgItem($settings,264)
$null=[ConfigurationTestUi]::PostMessage($main,0x312,[IntPtr]21,[IntPtr]::Zero)
$editor=[ConfigurationTestUi]::GetDlgItem($pane,301)
for($i=0;$i -lt 100 -and ![ConfigurationTestUi]::IsWindowVisible($editor);$i++) { Start-Sleep -Milliseconds 50 }
Assert ([ConfigurationTestUi]::IsWindowVisible($editor)) 'resident Snippets command selects the inline editor'
# Only inject into the isolated fixture window, never another foreground app.
Assert ([ConfigurationTestUi]::GetForegroundWindow() -eq $settings) 'fixture owns foreground before shortcut capture test'
$field=[ConfigurationTestUi]::GetDlgItem($settings,210)
SelectSection $settings 2
$field=[ConfigurationTestUi]::GetDlgItem($pane,210)
Assert ([ConfigurationTestUi]::FocusControl($field)) 'shortcut field receives actual focus'
Assert ([ConfigurationTestUi]::PressF24() -eq 2) 'test F24 events accepted'
$text=[Text.StringBuilder]::new(128)
@@ -114,7 +130,7 @@ try {
Start-Sleep -Milliseconds 20
}
Assert ($text.ToString() -eq 'F24') 'resident hook forwards shortcut capture to configurator'
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($settings,240),0x0c,[IntPtr]::Zero,'321')
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($pane,240),0x0c,[IntPtr]::Zero,'321')
Click $settings 1
Assert ($config.WaitForExit(6000) -and $config.ExitCode -eq 0) 'save exits configurator'
Assert ((Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json).maxItems -eq 321) 'save committed through resident process'
@@ -122,27 +138,35 @@ try {
$resident.Refresh(); Assert (!$resident.HasExited) 'resident survives settings save'
$config=Launch 'KSwitcher.Config.exe' ''
$settings=Window 'KSwitcher.Settings'
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($settings,240),0x0c,[IntPtr]::Zero,'456')
$pane=[ConfigurationTestUi]::GetDlgItem($settings,264)
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($pane,240),0x0c,[IntPtr]::Zero,'456')
Click $settings 2
$prompt=[IntPtr]::Zero
for($i=0;$i -lt 100 -and $prompt -eq [IntPtr]::Zero;$i++) {
$prompt=[ConfigurationTestUi]::FindWindow('#32770',('KSwitcher {0} Unsaved settings' -f [char]0x2014))
if($prompt -eq [IntPtr]::Zero) { Start-Sleep -Milliseconds 50 }
}
Assert ($prompt -ne [IntPtr]::Zero) 'cancel asks about unsaved changes'
Click $prompt 7
Assert ($config.WaitForExit(6000)) 'cancel exits configurator'
Assert ((Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json).maxItems -eq 321) 'cancel preserves saved settings'
$config=Launch 'KSwitcher.Config.exe' '--snippets'
$snippets=Window 'KSwitcher.Snippets'
$null=[ConfigurationTestUi]::SendMessage($snippets,0,[IntPtr]::Zero,[IntPtr]::Zero)
foreach($id in @(302,303,311,312,313)) {
foreach($id in @(302,303,311,320)) {
Assert (![ConfigurationTestUi]::IsWindowEnabled([ConfigurationTestUi]::GetDlgItem($snippets,$id))) "snippet control $id disabled without selection"
}
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]310,[IntPtr]::Zero)
foreach($id in @(302,303,311,312,313)) {
foreach($id in @(302,303,311,320)) {
Assert ([ConfigurationTestUi]::IsWindowEnabled([ConfigurationTestUi]::GetDlgItem($snippets,$id))) 'Add enables snippet editing'
}
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($snippets,303),0x0c,[IntPtr]::Zero,'preserved snippet')
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]310,[IntPtr]::Zero)
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]311,[IntPtr]::Zero)
foreach($id in @(302,303,311,312,313)) {
foreach($id in @(302,303,311,320)) {
Assert (![ConfigurationTestUi]::IsWindowEnabled([ConfigurationTestUi]::GetDlgItem($snippets,$id))) 'deleting selection disables snippet editing'
}
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]312,[IntPtr]::Zero)
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]320,[IntPtr]::Zero)
$snippetText=[Text.StringBuilder]::new(128)
$null=[ConfigurationTestUi]::GetText([ConfigurationTestUi]::GetDlgItem($snippets,303),0x0d,[IntPtr]128,$snippetText)
Assert ($snippetText.Length -eq 0) 'marker command cannot edit an unselected snippet'
+9 -2
View File
@@ -84,9 +84,11 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) {
{
ks::App app(instance,false,folder/L"data");app.window=owner;
app.settings.history=false;app.settings.autoCorrect=false;app.settings.writeLog=true;
auto prepare=[&](wchar_t last=L'r') {
auto prepare=[&](wchar_t last=L'r', wchar_t prefix=0) {
if(!ks::activateWindow(target))throw std::runtime_error("isolated Far lost foreground");
key(VK_ESCAPE);key('Y',0,LEFT_CTRL_PRESSED);key(VK_OEM_1,L':',SHIFT_PRESSED);key(WORD(towupper(last)),last);
key(VK_ESCAPE);key('Y',0,LEFT_CTRL_PRESSED);
if(prefix)key(prefix==L' '?VK_SPACE:WORD(towupper(prefix)),prefix);
key(VK_OEM_1,L':',SHIFT_PRESSED);key(WORD(towupper(last)),last);
app.run.reset();app.run.window=target;app.run.layout=ks::windowLayout(target);
app.run.at=GetTickCount64();app.run.keys=L":r";
};
@@ -103,6 +105,11 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) {
require(ks::readClipboard(owner).text()==sentinel.text(),"snippet restores original clipboard");
prepare(L'x');before=position();original=row();expand(L"rider .{enter}");
require(row()==original && position().X==before.X,"mismatched trigger restores original caret and never executes Enter");
prepare(L'r',L'x');before=position();original=row();expand(L"rider .");
require(row()==original && position().X==before.X,"trigger inside a word restores original caret");
prepare(L'r',L' ');before=position();expand(L"rider .");
require(row().substr(before.X-3,8)==L" rider ." && position().X==before.X+5,
"trigger after a space preserves the separator");
prepare();before=position();original=row();expand(L"left{cursor}right");
require(row().substr(before.X-2,9)==L"leftright" && position().X==before.X+2,"cursor marker uses Far selection semantics");
prepare();before=position();original=row();expand(L"first\nsecond{enter}");
+38
View File
@@ -117,6 +117,18 @@ function Scintilla($Window) {
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
}
function Assert-ReopenedMarkdown($Window, $File) {
try { Browser 'reopen' '' $File }
finally {
if ([MarkdownUi]::IsWindowVisible((Scintilla $Window))) { throw "$File opened as raw text." }
}
}
function Close-Preview($Window) {
Post $Window 0x10 0
[void](Wait-For 'the Markdown preview to close' { ![MarkdownUi]::IsWindowVisible($Window) })
}
function Assert-TextWindowAppearance($Window, [string]$Mode) {
$identity = "HrynCo.KSwitcher.Files.$Mode"
$resource = if($Mode -eq 'Editor') { ',-104' } else { ',-103' }
@@ -204,6 +216,8 @@ const value = 42;
'@
$original = Join-Path $docs 'Preview.md'
[IO.File]::WriteAllText($original,$fixture)
[IO.File]::WriteAllText("$docs\Reopen.md",'# Reopened Markdown')
[IO.File]::WriteAllText("$docs\Second.md",'# Second Markdown')
$childText = '# Linked Markdown' + "`n`n" + (("Filler paragraph.`n`n") * 60) + '## Target heading'
[IO.File]::WriteAllText("$docs\child\Other.md",$childText)
[IO.File]::WriteAllText("$docs\Plain.txt",'Plain text')
@@ -235,6 +249,30 @@ const value = 42;
[MarkdownUi]::Activate($main)
$panel = [MarkdownUi]::GetDlgItem($main,102)
$previewScript = Join-Path $app 'terminal\markdown.js'
$originalScript = [IO.File]::ReadAllText($previewScript)
try {
# Let the page load without sending the ready message until Files starts a new WebView.
[IO.File]::WriteAllText($previewScript,"document.documentElement.dataset.startup = 'stalled';")
Open-File 'Reopen.md' 0x72
$window = Wait-For 'the stalled Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Reopen.md' }
Browser 'startup-stalled'
} finally { [IO.File]::WriteAllText($previewScript,$originalScript) }
Assert-ReopenedMarkdown $window 'Reopen.md'
Close-Preview $window
Write-Output 'Verified that the same viewer renders Markdown after a stalled WebView2 startup.'
Open-File 'Reopen.md' 0x72
$window = Wait-For 'the Markdown viewer before early close' { Find-Window 'KSwitcher.Files.Text' 'Reopen.md' }
Close-Preview $window
foreach ($file in 'Reopen.md','Second.md','Reopen.md','Second.md','Reopen.md','Second.md') {
Open-File $file 0x72
$window = Wait-For "the reopened $file viewer" { Find-Window 'KSwitcher.Files.Text' $file }
Assert-ReopenedMarkdown $window $file
Close-Preview $window
}
Write-Output 'Verified six immediate Markdown reopens after closing the initial preview during startup.'
Open-File 'Preview.md' 0x72
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
+11 -2
View File
@@ -139,9 +139,18 @@ try {
clip: { x:0, y:0, width:cssContentSize.width, height:Math.min(cssContentSize.height, 620), scale:1 } });
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} else if (scenario === 'startup-stalled') {
await waitFor(() => evaluate(`document.documentElement?.dataset.startup === 'stalled'`),
'the preview page to load without announcing readiness');
} else if (scenario === 'reopen') {
const heading = title === 'Reopen.md' ? 'Reopened Markdown' : 'Second Markdown';
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
document.querySelector('h1')?.textContent === ${JSON.stringify(heading)}`), heading);
assert.equal(await evaluate(`performance.getEntriesByName(new URL('mermaid.js', location.href).href).length`),
0, 'Reopening a document without diagrams must not load Mermaid');
} else if (scenario === 'external-replacement') {
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
document.querySelector('main').textContent.trim() === 'An external replacement'`),
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
document.querySelector('main')?.textContent.trim() === 'An external replacement'`),
'the replacement file rendered after discarding edits');
} else if (scenario === 'diagram-reference') {
await waitFor(() => evaluate("document.documentElement.classList.contains('rendered')"), 'rendered diagram page');
+294 -182
View File
@@ -7,6 +7,8 @@
#include <commctrl.h>
#include <iostream>
#include <cmath>
#include "input_pause.h"
#include "settings_ui.h"
static int settingsCloseChoice = IDCANCEL;
static int settingsClosePrompts = 0;
static void CALLBACK answerSettingsClose(HWND, UINT, UINT_PTR, DWORD)
@@ -27,6 +29,45 @@ LRESULT CALLBACK countControlMoves(HWND w, UINT message, WPARAM wp, LPARAM lp, U
}
namespace ks {
struct InputRegressionAccess {
static LRESULT CALLBACK probeInput(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR context) {
auto &app = *reinterpret_cast<App *>(context);
static bool queuedSnippet = false;
// Queue a real expansion just before TrackPopupMenu returns the pause command.
if (msg == WM_EXITMENULOOP && app.inputState == App::InputState::Active)
queuedSnippet = app.queueSnippet(w, 0, 2, w);
if (msg == ProbeTrayIcon) return trayIconMatchesInput(app.trayBaseIcon(16, 16), wp != 0);
if (msg != ProbeInputState) return DefSubclassProc(w, msg, wp, lp);
// Also exercise settings/layout updates that would normally re-register shortcuts.
if (wp && app.inputState == App::InputState::Paused) {
app.applySettings(app.settings);
app.reloadLayouts();
app.dispatch(Toggle);
app.pasteEntry(L"fixture", false);
const auto version = app.inputVersion.load();
KBDLLHOOKSTRUCT key{};
key.vkCode = 'A';
if (app.handleKeyboard(key, true, 0) || app.inputVersion != version) return 0;
const std::string status = R"({"action":"status"})";
const auto response = app.lanCommand(Bytes(status.begin(), status.end()));
if (std::string(response.begin(), response.end()).find("Input processing paused") == std::string::npos)
return 0;
}
const bool bound = app.isHotkey(VK_F22, MOD_CONTROL | MOD_SHIFT);
if (app.inputState == App::InputState::Active && app.keyboardHook && app.mouseHook &&
app.filesHotkeyId && bound) return 1;
if (app.inputState == App::InputState::Paused && !app.keyboardHook && !app.mouseHook &&
!app.filesHotkeyId && !bound && !app.busy && app.snippetPending == -1 &&
!app.snippetTyping && queuedSnippet && !app.transformAttempt) return 2;
return 0;
}
static void CALLBACK installProbe(HWND, UINT, UINT_PTR timer, DWORD) {
auto app = App::current;
if (app && app->window && SetWindowSubclass(app->window, probeInput, 1, reinterpret_cast<DWORD_PTR>(app))) {
KillTimer(app->window, 5); // Keep the input fixture independent of update checks.
SetTimer(app->window, 2, 60000, nullptr);
KillTimer(nullptr, timer);
}
}
static int snippetChoice(App &a, const std::vector<Snippet> &snippets) {
a.settings.snippets=snippets; a.settings.autoCorrect=false; a.busy=false;
a.snippetPending=-1; a.typingTarget=nullptr; a.snippetTyping=false;
@@ -169,6 +210,20 @@ struct InputRegressionAccess {
};
}
int main(int argc, char **argv) {
if (argc == 2 && std::string(argv[1]) == "--input-pause") return testInputPause();
if (argc == 2 && std::string(argv[1]) == "--input-pause-resident") {
// The driver copies this binary alone into a fresh fixture folder.
auto folder = std::filesystem::path(ks::executable()).parent_path();
if (!folder.filename().wstring().starts_with(L"KSwitcher-input-pause-")) return 1;
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
ks::App app(GetModuleHandleW(nullptr), false, folder / L"data");
app.settings.toggle = L"Ctrl+Shift+F22";
app.settings.filesHotkey = L"Ctrl+Shift+F23";
app.settings.snippets = {{L";t", L"fixture"}};
app.settings.history = app.settings.autoCorrect = app.settings.autostart = false;
SetTimer(nullptr, 0, 10, ks::InputRegressionAccess::installProbe);
return app.execute();
}
if (argc == 2 && std::string(argv[1]) == "--update-check") {
try {
auto result = ks::runUpdate(false, {});
@@ -807,50 +862,44 @@ int main(int argc, char **argv) {
ks::showSettings(app,false);
{
auto settings = app.settingsWindow;
auto tabs = GetDlgItem(settings, 260);
auto capture = GetDlgItem(settings, 737);
auto events = GetDlgItem(settings, 733);
auto visible = [&](int id) { return (GetWindowLongPtrW(GetDlgItem(settings, id), GWL_STYLE) & WS_VISIBLE) != 0; };
auto selectPage = [&](int index) {
TabCtrl_SetCurSel(tabs, index);
NMHDR changed{tabs, 260, TCN_SELCHANGE};
SendMessageW(settings, WM_NOTIFY, 260, reinterpret_cast<LPARAM>(&changed));
};
RECT lastTab{}, tabClient{};
GetClientRect(tabs, &tabClient);
require(TabCtrl_GetItemCount(tabs) == 10 && TabCtrl_GetItemRect(tabs, 9, &lastTab) &&
lastTab.right <= tabClient.right, "all Settings tabs fit in one row");
auto navigation = settingsNavigation(settings);
auto pane = settingsViewport(settings);
auto capture = GetDlgItem(pane, 737);
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) == 18, "all Settings sections are listed");
selectPage(3);
require(visible(257) && !visible(301), "OCR options are in Clipboard");
selectPage(6);
require(visible(258) && !visible(262), "Sync has its own tab");
require(visible(271) && !visible(262), "Sync opens the embedded OpenBao page");
selectPage(7);
require(visible(262) && !visible(258), "Computers has its own tab");
require(!visible(262) && !visible(271), "Computers parent hides embedded controls");
selectPage(10);
require(visible(262), "Manage computers shows the embedded panel");
selectPage(8);
require(visible(208) && visible(256), "logging controls are in Diagnostics");
selectPage(4);
require(visible(301) && visible(303) && visible(318), "Snippets has an inline editor and its own Save button");
require(visible(301) && visible(303) && visible(320) && !GetDlgItem(pane, 318),
"Snippets uses the inline editor and the shared Save button");
const bool awake = app.settings.awake;
SendDlgItemMessageW(settings, 205, BM_SETCHECK, awake ? BST_UNCHECKED : BST_CHECKED, 0);
SendDlgItemMessageW(pane, 205, BM_SETCHECK, awake ? BST_UNCHECKED : BST_CHECKED, 0);
SendMessageW(settings, WM_COMMAND, 310, 0);
SetDlgItemTextW(settings, 302, L";inline-fixture");
SetDlgItemTextW(settings, 303, L"inline snippet");
SetDlgItemTextW(pane, 302, L";inline-fixture");
SetDlgItemTextW(pane, 303, L"inline snippet");
selectPage(0);
selectPage(4);
SendMessageW(settings, WM_COMMAND, 318, 0);
wchar_t replacement[64]{};
GetDlgItemTextW(pane, 303, replacement, std::size(replacement));
require(app.settings.awake == awake && IsWindowEnabled(GetDlgItem(settings, IDOK)) &&
std::any_of(app.settings.snippets.begin(), app.settings.snippets.end(), [](const ks::Snippet &snippet) {
return snippet.trigger == L";inline-fixture" && snippet.text == L"inline snippet";
}), "saving inline snippets preserves the unsaved settings draft across tab changes");
SendDlgItemMessageW(settings, 205, BM_SETCHECK, awake ? BST_CHECKED : BST_UNCHECKED, 0);
std::wstring(replacement) == L"inline snippet",
"changing sections preserves the unsaved settings and snippet drafts");
SendDlgItemMessageW(pane, 205, BM_SETCHECK, awake ? BST_CHECKED : BST_UNCHECKED, 0);
SendMessageW(settings, WM_COMMAND, 311, 0);
SendMessageW(settings, WM_COMMAND, 318, 0);
selectPage(0);
require(!(GetWindowLongPtrW(capture, GWL_STYLE) & WS_VISIBLE),
"mouse detection is hidden on General");
TabCtrl_SetCurSel(tabs, 5);
NMHDR changed{tabs, 260, TCN_SELCHANGE};
SendMessageW(settings, WM_NOTIFY, 260, reinterpret_cast<LPARAM>(&changed));
selectPage(5);
require(GetWindowLongPtrW(capture, GWL_STYLE) & WS_VISIBLE,
"mouse detection is visible on Mouse");
RECT suggestedSettings{};
@@ -864,7 +913,7 @@ int main(int argc, char **argv) {
!(GetWindowLongPtrW(events, GWL_STYLE) & WS_HSCROLL),
"a DPI resize keeps both settings and the action table free of unnecessary scrollbars");
RECT profilesBounds{}, eventsBounds{};
require(GetWindowRect(GetDlgItem(settings, 731), &profilesBounds) &&
require(GetWindowRect(GetDlgItem(pane, 731), &profilesBounds) &&
GetWindowRect(events, &eventsBounds) &&
profilesBounds.top == eventsBounds.top && profilesBounds.bottom == eventsBounds.bottom &&
profilesBounds.right - profilesBounds.left == eventsBounds.right - eventsBounds.left,
@@ -874,14 +923,14 @@ int main(int argc, char **argv) {
require(editor && SendDlgItemMessageW(editor, 734, CB_GETCOUNT, 0, 0) == 8,
"Global actions do not include inheritance");
SendMessageW(editor, WM_COMMAND, IDCANCEL, 0);
require(!GetDlgItem(settings, 741) && !GetDlgItem(settings, 732) && !GetDlgItem(settings, 745),
require(!GetDlgItem(pane, 741) && !GetDlgItem(pane, 732) && !GetDlgItem(pane, 745),
"applications are chosen in the action editor only");
for (auto message : {WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_XBUTTONUP})
SendMessageW(capture, message, MAKEWPARAM(0, XBUTTON2), 0);
require(ListView_GetNextItem(events, -1, LVNI_SELECTED) == 4,
"mouse button capture selects the second side button");
wchar_t detected[100]{};
GetDlgItemTextW(settings, 738, detected, 100);
GetDlgItemTextW(pane, 738, detected, 100);
require(std::wstring(detected) == L"Window event: XButton2 | Presses: 2",
"detection shows the last button and counts repeated presses");
SendMessageW(capture, WM_MBUTTONDBLCLK, 0, 0);
@@ -911,7 +960,7 @@ int main(int argc, char **argv) {
SendDlgItemMessageW(editor, 747, ks::CaptureHotkeyMessage, VK_TAB, MOD_CONTROL);
require(!GetDlgItem(editor, 748), "the action editor has no application list");
SendMessageW(editor, WM_COMMAND, IDOK, 0);
const auto profiles = GetDlgItem(settings, 731);
const auto profiles = GetDlgItem(pane, 731);
require(ListView_GetItemCount(profiles) == 1 &&
IsWindowEnabled(GetDlgItem(settings, IDOK)), "adding a mouse binding enables Save");
wchar_t action[80]{};
@@ -1001,23 +1050,15 @@ int main(int argc, char **argv) {
"profile row bounds are available");
const int nameWidth = ListView_GetColumnWidth(profiles, 1);
const int rowCenter = (profileRow.top + profileRow.bottom) / 2;
int checkboxX = -1;
for (int x = nameWidth; x < profileRow.right; ++x)
{
LVHITTESTINFO hit{};
hit.pt = {x, rowCenter};
if (ListView_HitTest(profiles, &hit) == 1 && (hit.flags & LVHT_ONITEMSTATEICON))
{
checkboxX = x;
break;
}
}
require(checkboxX >= nameWidth && checkboxX < nameWidth + ListView_GetColumnWidth(profiles, 0) &&
ListView_GetCheckState(profiles, 1),
"the enabled checkbox is hit-testable in the second column");
const int checkboxX = nameWidth + ListView_GetColumnWidth(profiles, 0) / 2;
require(ListView_GetCheckState(profiles, 1), "the new profile is enabled");
SendMessageW(profiles, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(checkboxX, rowCenter));
SendMessageW(profiles, WM_LBUTTONUP, 0, MAKELPARAM(checkboxX, rowCenter));
require(!ListView_GetCheckState(profiles, 1), "clicking the row checkbox disables its profile");
require(!ListView_GetCheckState(profiles, 1), "clicking the centered checkbox disables its profile");
SendMessageW(profiles, WM_KEYDOWN, VK_SPACE, 0);
require(ListView_GetCheckState(profiles, 1), "Space toggles the focused profile");
SendMessageW(profiles, WM_KEYDOWN, VK_SPACE, 0);
require(!ListView_GetCheckState(profiles, 1), "Space restores the disabled profile");
ListView_SetItemState(profiles, 0, LVIS_SELECTED, LVIS_SELECTED);
SendMessageW(profiles, WM_LBUTTONDBLCLK, MK_LBUTTON, MAKELPARAM(nameWidth / 2, rowCenter));
profileDialog = FindWindowW(L"KSwitcher.MouseProfileName", nullptr);
@@ -1050,19 +1091,19 @@ int main(int argc, char **argv) {
{
auto window = app.settingsWindow;
auto previous = app.settings;
TabCtrl_SetCurSel(GetDlgItem(window,260),3);
selectSettingsPage(window, 3);
app.settings.awake = !previous.awake;
app.settings.maxItems = previous.maxItems + 1;
SendMessageW(window,ks::ConfigSettingsDownloaded,0,0);
wchar_t count[32]{};
GetDlgItemTextW(window,240,count,32);
GetDlgItemTextW(settingsViewport(window), 240,count,32);
require(app.settingsWindow == window &&
SendDlgItemMessageW(window,205,BM_GETCHECK,0,0) == (app.settings.awake ? BST_CHECKED : BST_UNCHECKED) &&
std::stoi(count) == app.settings.maxItems && TabCtrl_GetCurSel(GetDlgItem(window,260)) == 3,
SendDlgItemMessageW(settingsViewport(window), 205,BM_GETCHECK,0,0) == (app.settings.awake ? BST_CHECKED : BST_UNCHECKED) &&
std::stoi(count) == app.settings.maxItems && TreeView_GetSelection(settingsNavigation(window)) == settingsSection(settingsNavigation(window), 3),
"download refreshes existing settings controls while preserving window and active tab");
app.settings = previous;
SendMessageW(window,ks::ConfigSettingsDownloaded,0,0);
TabCtrl_SetCurSel(GetDlgItem(window,260),0);
selectSettingsPage(window, 0);
auto timer = SetTimer(nullptr, 0, 10, answerSettingsClose);
require(timer != 0, "settings close prompt responder");
SendMessageW(app.settingsWindow, WM_CLOSE, 0, 0);
@@ -1070,17 +1111,17 @@ int main(int argc, char **argv) {
"unchanged settings close without prompting");
ks::showSettings(app,false);
auto settingsWindow = app.settingsWindow;
auto initial = SendDlgItemMessageW(settingsWindow,205,BM_GETCHECK,0,0);
SendDlgItemMessageW(settingsWindow,205,BM_SETCHECK,!initial,0);
auto initial = SendDlgItemMessageW(settingsViewport(settingsWindow), 205,BM_GETCHECK,0,0);
SendDlgItemMessageW(settingsViewport(settingsWindow), 205,BM_SETCHECK,!initial,0);
SendMessageW(settingsWindow, WM_CLOSE, 0, 0);
require(IsWindow(settingsWindow) && settingsClosePrompts == 1,
"cancel close preserves changed settings");
SendDlgItemMessageW(settingsWindow,205,BM_SETCHECK,initial,0);
SendDlgItemMessageW(settingsViewport(settingsWindow), 205,BM_SETCHECK,initial,0);
SendMessageW(settingsWindow, WM_CLOSE, 0, 0);
require(!app.settingsWindow && settingsClosePrompts == 1,
"reverted settings close without prompting");
ks::showSettings(app,false);
SetDlgItemTextW(app.settingsWindow,240,L"invalid");
SetDlgItemTextW(settingsViewport(app.settingsWindow), 240,L"invalid");
settingsCloseChoice = IDNO;
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
require(!app.settingsWindow && settingsClosePrompts == 2,
@@ -1091,7 +1132,7 @@ int main(int argc, char **argv) {
app.settings.undo = app.settings.clipboard = app.settings.screenshot = L"";
app.settings.direct.assign(app.layouts.size(), L"");
ks::showSettings(app,false);
SendDlgItemMessageW(app.settingsWindow,208,BM_SETCHECK,
SendDlgItemMessageW(settingsViewport(app.settingsWindow), 208,BM_SETCHECK,
originalSettings.writeLog ? BST_UNCHECKED : BST_CHECKED,0);
settingsCloseChoice = IDYES;
SendMessageW(app.settingsWindow,WM_CLOSE,0,0);
@@ -1105,21 +1146,21 @@ int main(int argc, char **argv) {
settingsCloseChoice = IDCANCEL;
ks::showSettings(app,false);
}
require(GetDlgItem(app.settingsWindow,258)!=nullptr,"sync available without local opt-in");
require(GetDlgItem(settingsViewport(app.settingsWindow), 271)!=nullptr,"OpenBao available without local opt-in");
// Mnemonics only target visible controls; show without taking foreground focus.
ShowWindow(app.settingsWindow,SW_SHOWNOACTIVATE);
auto previousActive=SetActiveWindow(app.settingsWindow);
auto awakeBefore=SendDlgItemMessageW(app.settingsWindow,205,BM_GETCHECK,0,0);
MSG accessKey{}; accessKey.hwnd=GetDlgItem(app.settingsWindow,201);
auto awakeBefore=SendDlgItemMessageW(settingsViewport(app.settingsWindow), 205,BM_GETCHECK,0,0);
MSG accessKey{}; accessKey.hwnd=GetDlgItem(settingsViewport(app.settingsWindow), 201);
accessKey.message=WM_SYSCHAR; accessKey.wParam=L'k'; accessKey.lParam=1LL<<29;
require(IsDialogMessageW(app.settingsWindow,&accessKey),"Alt+K is handled as a dialog access key");
MSG dispatched{};
while(PeekMessageW(&dispatched,nullptr,0,0,PM_REMOVE)) { TranslateMessage(&dispatched); DispatchMessageW(&dispatched); }
require(SendDlgItemMessageW(app.settingsWindow,205,BM_GETCHECK,0,0)!=awakeBefore,
require(SendDlgItemMessageW(settingsViewport(app.settingsWindow), 205,BM_GETCHECK,0,0)!=awakeBefore,
"Alt+K toggles Keep screen awake");
IsDialogMessageW(app.settingsWindow,&accessKey);
while(PeekMessageW(&dispatched,nullptr,0,0,PM_REMOVE)) { TranslateMessage(&dispatched); DispatchMessageW(&dispatched); }
require(SendDlgItemMessageW(app.settingsWindow,205,BM_GETCHECK,0,0)==awakeBefore,
require(SendDlgItemMessageW(settingsViewport(app.settingsWindow), 205,BM_GETCHECK,0,0)==awakeBefore,
"repeated access key restores checkbox state");
ShowWindow(app.settingsWindow,SW_HIDE);
SetActiveWindow(previousActive);
@@ -1127,25 +1168,33 @@ int main(int argc, char **argv) {
DestroyWindow(app.settingsWindow);
ks::saveSyncConfig(app.data,ks::SyncConfig{});
ks::showSettings(app,false);
require(GetDlgItem(app.settingsWindow,258)!=nullptr,"sync button available after local opt-in");
SendMessageW(app.settingsWindow,WM_COMMAND,258,0);
auto syncWindow=FindWindowW(L"KSwitcher.Sync",nullptr);
require(syncWindow!=nullptr,"private sync dialog opens");
ShowWindow(syncWindow,SW_HIDE);
selectSettingsPage(app.settingsWindow, 6);
const auto tree = settingsNavigation(app.settingsWindow);
require(TreeView_GetSelection(tree) == settingsSection(tree, 17), "Sync opens its OpenBao child");
auto syncWindow = GetDlgItem(settingsViewport(app.settingsWindow), 271);
require(syncWindow && (GetWindowLongPtrW(syncWindow,GWL_STYLE)&WS_VISIBLE) &&
!FindWindowW(L"KSwitcher.Sync",nullptr), "OpenBao is embedded in the Settings window");
require((GetWindowLongPtrW(GetDlgItem(syncWindow,604),GWL_STYLE)&ES_PASSWORD)!=0,
"sync password is masked");
require(!IsWindowEnabled(app.settingsWindow),"sync dialog owns settings interaction");
for(int id:{602,603,604,605,606,607,610,611,612,613,IDOK})
require(IsWindowEnabled(app.settingsWindow),"OpenBao allows switching to other settings pages");
for(int id:{602,603,604,605,606,607,610,611,612,613,614})
require(!IsWindowEnabled(GetDlgItem(syncWindow,id)),"disabled synchronization disables dependent controls");
require(IsWindowEnabled(GetDlgItem(syncWindow,601)) && IsWindowEnabled(GetDlgItem(syncWindow,609)) &&
IsWindowEnabled(GetDlgItem(syncWindow,IDCANCEL)),"enable, forget password and close remain available");
require(IsWindowEnabled(GetDlgItem(syncWindow,601)) && IsWindowEnabled(GetDlgItem(syncWindow,609)),
"enable and forget password remain available");
SendMessageW(syncWindow,WM_COMMAND,612,0);
require(!FindWindowW(L"KSwitcher.SyncConflicts",nullptr),"disabled conflict action is ignored");
SendDlgItemMessageW(syncWindow,601,BM_SETCHECK,BST_CHECKED,0);
SendMessageW(syncWindow,WM_COMMAND,MAKEWPARAM(601,BN_CLICKED),0);
for(int id:{602,603,604,605,606,607,610,611,613,IDOK})
for(int id:{602,603,604,605,606,607,610,611,613,614})
require(IsWindowEnabled(GetDlgItem(syncWindow,id)),"enabling synchronization immediately enables connection controls");
require(!ks::loadSyncConfig(app.data).enabled,"checking enable alone does not connect or persist");
SetDlgItemTextW(syncWindow, 602, L"https://draft.example.test");
selectSettingsPage(app.settingsWindow, 0);
selectSettingsPage(app.settingsWindow, 17);
wchar_t draftServer[64]{};
GetDlgItemTextW(syncWindow, 602, draftServer, std::size(draftServer));
require(std::wstring_view(draftServer) == L"https://draft.example.test",
"switching sections preserves the OpenBao draft");
auto enabledSync=ks::loadSyncConfig(app.data);
enabledSync.enabled=true;
enabledSync.server=L"https://sync.example.test";
@@ -1171,10 +1220,10 @@ int main(int argc, char **argv) {
"conflict controls fit dialog");
}
SendMessageW(conflictsWindow,WM_COMMAND,623,0);
require(!IsWindowEnabled(syncWindow),"conflict dialog owns sync interaction");
require(!IsWindowEnabled(app.settingsWindow),"conflict dialog owns settings interaction");
SendMessageW(conflictsWindow,WM_COMMAND,IDCANCEL,0);
require(IsWindowEnabled(syncWindow),"closing conflict dialog restores sync window");
for(int id:{601,602,603,604,605,606,607,608,609,610,611,612,613,IDOK,IDCANCEL}) {
require(IsWindowEnabled(app.settingsWindow),"closing conflict dialog restores Settings");
for(int id:{601,602,603,604,605,606,607,608,609,610,611,612,613,614}) {
RECT control{},client{};
GetWindowRect(GetDlgItem(syncWindow,id),&control);
MapWindowPoints(nullptr,syncWindow,reinterpret_cast<POINT*>(&control),2);
@@ -1184,12 +1233,11 @@ int main(int argc, char **argv) {
}
SendDlgItemMessageW(syncWindow,601,BM_SETCHECK,BST_UNCHECKED,0);
SendMessageW(syncWindow,WM_COMMAND,MAKEWPARAM(601,BN_CLICKED),0);
require(IsWindowEnabled(GetDlgItem(syncWindow,IDOK)),"Save remains available to persist disabling sync");
SendMessageW(syncWindow,WM_COMMAND,IDOK,0);
require(IsWindowEnabled(GetDlgItem(syncWindow,614)),"Save remains available to persist disabling sync");
SendMessageW(syncWindow,WM_COMMAND,614,0);
require(!ks::loadSyncConfig(app.data).enabled,"saving disabled sync does not enable network access");
require(!IsWindowEnabled(GetDlgItem(syncWindow,IDOK)),"Save disables after disabled state is persisted");
SendMessageW(syncWindow,WM_COMMAND,IDCANCEL,0);
require(IsWindowEnabled(app.settingsWindow),"closing sync restores parent");
require(!IsWindowEnabled(GetDlgItem(syncWindow,614)),"Save disables after disabled state is persisted");
selectSettingsPage(app.settingsWindow, 0);
require(ks::InputRegressionAccess::staleSync(app,false),"in-flight sync cannot overwrite newer local edits");
require(ks::InputRegressionAccess::staleSync(app,true),"disconnect discards in-flight downloaded profile");
require(ks::InputRegressionAccess::idleUndo(app),"idle cleanup retains available/busy Undo and frees expired Undo");
@@ -1197,85 +1245,36 @@ int main(int argc, char **argv) {
require(ks::InputRegressionAccess::completedSync(app,mode),
"completed, failed and invalid sync release buffers but preserve conflict choices");
require(ks::InputRegressionAccess::syncBackoff(app),"saving settings preserves authentication error backoff");
SendMessageW(app.settingsWindow,WM_COMMAND,255,0);
auto autoOptions=FindWindowW(L"KSwitcher.AutoOptions",nullptr);
require(autoOptions!=nullptr,"auto-correction options open");
ShowWindow(autoOptions,SW_HIDE);
selectSettingsPage(app.settingsWindow, 14);
auto autoOptions = settingsViewport(app.settingsWindow);
for (int id : {411, 412, 413})
{
require((GetWindowLongPtrW(autoOptions,GWL_STYLE)&WS_THICKFRAME)!=0,
"auto-correction dialog supports resizing");
RECT original{}, before[3]{}, after[3]{}, buttonBefore{}, buttonAfter{};
GetWindowRect(autoOptions,&original);
// Use a client size above the scrolling baseline at every DPI.
UINT dpi=GetDpiForWindow(autoOptions);
SetWindowPos(autoOptions,nullptr,0,0,MulDiv(800,dpi,96),MulDiv(1100,dpi,96),
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
RECT baseline{}; GetWindowRect(autoOptions,&baseline);
RECT clientBefore{}; GetClientRect(autoOptions,&clientBefore);
for(int i=0;i<3;++i) GetWindowRect(GetDlgItem(autoOptions,411+i),&before[i]);
GetWindowRect(GetDlgItem(autoOptions,IDOK),&buttonBefore);
SetWindowPos(autoOptions,nullptr,0,0,baseline.right-baseline.left+240,
baseline.bottom-baseline.top+120,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
RECT clientAfter{}; GetClientRect(autoOptions,&clientAfter);
// Windows can constrain oversized windows to the current desktop.
// Check layout against the actual available client space.
int extraBeforeX=std::max(0,int(clientBefore.right)-MulDiv(560,dpi,96));
int extraAfterX=std::max(0,int(clientAfter.right)-MulDiv(560,dpi,96));
int extraY=std::max(0,int(clientAfter.bottom)-MulDiv(880,dpi,96))-
std::max(0,int(clientBefore.bottom)-MulDiv(880,dpi,96));
for(int i=0;i<3;++i) {
GetWindowRect(GetDlgItem(autoOptions,411+i),&after[i]);
int extraX=(extraAfterX*(i+1)/3-extraAfterX*i/3)-
(extraBeforeX*(i+1)/3-extraBeforeX*i/3);
require(after[i].right-after[i].left==before[i].right-before[i].left+extraX &&
after[i].bottom-after[i].top==before[i].bottom-before[i].top+extraY,
"dictionary columns share extra width and receive extra height");
}
GetWindowRect(GetDlgItem(autoOptions,IDOK),&buttonAfter);
require(buttonAfter.left-buttonBefore.left==extraAfterX-extraBeforeX && buttonAfter.top-buttonBefore.top==extraY,
"auto-correction buttons follow bottom-right corner");
require(after[0].right<after[1].left && after[1].right<after[2].left &&
after[2].bottom<buttonAfter.top,
"resized dictionary fields and footer do not overlap");
SetWindowPos(autoOptions,nullptr,0,0,original.right-original.left,original.bottom-original.top,
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
}
for(int id:{411,412,413}) {
RECT control{},client{};
GetWindowRect(GetDlgItem(autoOptions,id),&control);
MapWindowPoints(nullptr,autoOptions,reinterpret_cast<POINT*>(&control),2);
GetClientRect(autoOptions,&client);
require(control.left>=0&&control.top>=0&&control.right<=client.right&&control.bottom<=client.bottom,
"personal dictionary field fits options window");
const auto field = GetDlgItem(autoOptions, id);
RECT bounds{};
GetWindowRect(field, &bounds);
require((GetWindowLongPtrW(field, GWL_STYLE) & WS_VISIBLE) &&
bounds.bottom - bounds.top >= MulDiv(72, GetDpiForWindow(field), 96),
"all personal dictionary fields use tall editors on their own page");
}
SetDlgItemTextW(autoOptions,412,L"Релізик\r\nрелізик, словечко");
SetDlgItemTextW(autoOptions,416,L" Првиіт = Привіт\r\nhelo=hello\r\n Мамамила = Мама мила ");
SendDlgItemMessageW(autoOptions,414,BM_SETCHECK,BST_CHECKED,0);
SendDlgItemMessageW(autoOptions,415,BM_SETCHECK,BST_CHECKED,0);
SendMessageW(autoOptions,WM_COMMAND,IDOK,0);
require(!IsWindow(autoOptions),"personal words accepted without file editing");
{
auto timer = SetTimer(nullptr,0,10,answerSettingsClose);
auto before = settingsClosePrompts;
SendMessageW(app.settingsWindow,WM_CLOSE,0,0);
KillTimer(nullptr,timer);
require(app.settingsWindow && settingsClosePrompts == before + 1,
"accepted personal dictionary edits trigger unsaved settings warning");
}
SendMessageW(app.settingsWindow,WM_COMMAND,255,0);
autoOptions=FindWindowW(L"KSwitcher.AutoOptions",nullptr);
ShowWindow(autoOptions,SW_HIDE);
selectSettingsPage(app.settingsWindow, 0);
selectSettingsPage(app.settingsWindow, 14);
wchar_t personalWords[128]{};
GetDlgItemTextW(autoOptions,412,personalWords,128);
require(std::wstring(personalWords)==L"релізик, словечко",
"personal dictionary normalizes case, newlines and duplicate words");
wchar_t pairs[128]{};
GetDlgItemTextW(autoOptions,416,pairs,128);
require(std::wstring(pairs)==L"helo=hello\r\nмамамила=мама мила\r\nпрвиіт=привіт\r\n" &&
SendDlgItemMessageW(autoOptions,414,BM_GETCHECK,0,0)==BST_CHECKED &&
SendDlgItemMessageW(autoOptions,415,BM_GETCHECK,0,0)==BST_CHECKED,
"typo options and normalized replacement pairs survive reopening");
SendMessageW(autoOptions,WM_COMMAND,IDCANCEL,0);
GetDlgItemTextW(autoOptions, 412, personalWords, std::size(personalWords));
require(std::wstring(personalWords) == L"Релізик\r\nрелізик, словечко",
"personal dictionary draft survives switching pages");
{
auto timer = SetTimer(nullptr, 0, 10, answerSettingsClose);
auto before = settingsClosePrompts;
SendMessageW(app.settingsWindow, WM_CLOSE, 0, 0);
KillTimer(nullptr, timer);
require(app.settingsWindow && settingsClosePrompts == before + 1,
"inline correction edits trigger the unsaved settings warning");
}
selectSettingsPage(app.settingsWindow, 0);
if (!app.history) app.history=std::make_unique<ks::History>(temp/L"history-layout");
ks::showHistory(app,false);
auto history=app.historyWindow;
@@ -1366,14 +1365,14 @@ int main(int argc, char **argv) {
require(EqualRect(&listBefore,&(listAfter=childRect(102))),"DPI refresh preserves history list geometry");
}
auto settings=app.settingsWindow;
require(SendDlgItemMessageW(settings,209,BM_GETCHECK,0,0)==BST_UNCHECKED,"automatic screenshot editor checkbox defaults off");
require(SendDlgItemMessageW(settingsViewport(settings), 209,BM_GETCHECK,0,0)==BST_UNCHECKED,"automatic screenshot editor checkbox defaults off");
require(settings&&!IsWindowVisible(settings),"settings layout tested without changing user focus");
for(auto pair:{std::pair{209,215},std::pair{209,207},std::pair{209,220},std::pair{209,232},std::pair{207,215},std::pair{207,232},std::pair{207,220},std::pair{232,230},std::pair{230,231},std::pair{231,253}}) {
// Controls on different settings tabs intentionally share the page area.
if (!(GetWindowLongPtrW(GetDlgItem(settings,pair.first),GWL_STYLE)&WS_VISIBLE) ||
!(GetWindowLongPtrW(GetDlgItem(settings,pair.second),GWL_STYLE)&WS_VISIBLE)) continue;
if (!(GetWindowLongPtrW(GetDlgItem(settingsViewport(settings),pair.first),GWL_STYLE)&WS_VISIBLE) ||
!(GetWindowLongPtrW(GetDlgItem(settingsViewport(settings),pair.second),GWL_STYLE)&WS_VISIBLE)) continue;
RECT first{},second{},overlap{};
GetWindowRect(GetDlgItem(settings,pair.first),&first); GetWindowRect(GetDlgItem(settings,pair.second),&second);
GetWindowRect(GetDlgItem(settingsViewport(settings),pair.first),&first); GetWindowRect(GetDlgItem(settingsViewport(settings),pair.second),&second);
require(!IntersectRect(&overlap,&first,&second),"capture hotkey and layout controls do not overlap");
}
RECT frame{},client{},cancel{};
@@ -1385,48 +1384,161 @@ int main(int argc, char **argv) {
std::cout << "Hidden Settings layout checked at " << dpi << " DPI\n";
GetWindowRect(GetDlgItem(settings,IDCANCEL),&cancel);
require(cancel.right-cancel.left==MulDiv(100,dpi,96),"controls use actual window DPI");
auto pane = settingsViewport(settings);
selectSettingsPage(settings, 2);
for (int width : {800, 620, 800})
{
SetWindowPos(settings, nullptr, 0, 0, MulDiv(width, dpi, 96), MulDiv(540, dpi, 96),
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
RECT viewport{};
GetClientRect(pane, &viewport);
const int margin = MulDiv(24, dpi, 96);
for (int id = 210; id <= 216; ++id)
{
RECT field{};
GetWindowRect(GetDlgItem(pane, id), &field);
MapWindowPoints(nullptr, pane, reinterpret_cast<POINT *>(&field), 2);
require(field.left == MulDiv(width == 620 ? 24 : 230, dpi, 96) &&
field.right <= viewport.right - margin + 1 && field.right > field.left,
"shortcut fields fit inside the viewport in both layouts");
}
require(!(GetWindowLongPtrW(pane, GWL_STYLE) & WS_HSCROLL),
"shortcut fields do not require horizontal scrolling");
}
auto fieldBounds = [&](int id)
{
RECT rect{};
GetWindowRect(GetDlgItem(pane, id), &rect);
MapWindowPoints(nullptr, pane, reinterpret_cast<POINT *>(&rect), 2);
return rect;
};
auto fitsPane = [&](const RECT &rect)
{
RECT viewport{};
GetClientRect(pane, &viewport);
return rect.left >= 0 && rect.left < rect.right && rect.right <= viewport.right &&
!(GetWindowLongPtrW(pane, GWL_STYLE) & WS_HSCROLL);
};
for (int width : {800, 620})
{
SetWindowPos(settings, nullptr, 0, 0, MulDiv(width, dpi, 96), MulDiv(600, dpi, 96),
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
selectSettingsPage(settings, 3);
for (int id : {240, 241, 242, 243})
require(fitsPane(fieldBounds(id)), "clipboard fields fit inside the pane");
selectSettingsPage(settings, 13);
const auto first = fieldBounds(404), second = fieldBounds(405);
require(fitsPane(first) && fitsPane(second) && first.bottom < second.top &&
std::abs((first.bottom - first.top) - (second.bottom - second.top)) <= MulDiv(1, dpi, 96) &&
second.bottom >= MulDiv(320, dpi, 96),
"exception lists equally fill the available height");
LOGFONTW captionFont{}, editFont{};
const auto edit = GetDlgItem(pane, 404);
const auto caption = GetWindow(edit, GW_HWNDPREV);
GetObjectW(reinterpret_cast<HFONT>(SendMessageW(caption, WM_GETFONT, 0, 0)), sizeof(captionFont), &captionFont);
GetObjectW(reinterpret_cast<HFONT>(SendMessageW(edit, WM_GETFONT, 0, 0)), sizeof(editFont), &editFont);
require(captionFont.lfWeight == FW_SEMIBOLD && editFont.lfWeight == FW_NORMAL,
"field captions use semibold while input text stays regular");
}
selectSettingsPage(settings, 14);
for (int height : {470, 600, 700})
{
SetWindowPos(settings, nullptr, 0, 0, MulDiv(700, dpi, 96), MulDiv(height, dpi, 96),
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
const auto english = fieldBounds(411), ukrainian = fieldBounds(412), russian = fieldBounds(413);
const LONG heights[] = {english.bottom - english.top, ukrainian.bottom - ukrainian.top,
russian.bottom - russian.top};
const auto [minHeight, maxHeight] = std::minmax_element(std::begin(heights), std::end(heights));
RECT viewport{};
GetClientRect(pane, &viewport);
require(fitsPane(english) && fitsPane(ukrainian) && fitsPane(russian) &&
*minHeight >= MulDiv(72, dpi, 96) && *maxHeight - *minHeight <= MulDiv(1, dpi, 96),
"personal dictionary fields share the viewport height equally");
if (height == 470)
require(GetWindowLongPtrW(pane, GWL_STYLE) & WS_VSCROLL,
"personal dictionary fields keep their minimum height in a short viewport");
else
require(std::abs(viewport.bottom - russian.bottom - MulDiv(24, dpi, 96)) <= MulDiv(1, dpi, 96) &&
!(GetWindowLongPtrW(pane, GWL_STYLE) & WS_VSCROLL),
"personal dictionary fields fill the viewport down to the bottom margin");
}
auto controlsFit = [&](HWND parent)
{
RECT viewport{};
GetClientRect(parent, &viewport);
require(!(GetWindowLongPtrW(parent, GWL_STYLE) & WS_HSCROLL),
"settings page does not need horizontal scrolling");
for (HWND child = GetWindow(parent, GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
{
if (!(GetWindowLongPtrW(child, GWL_STYLE) & WS_VISIBLE)) continue;
RECT bounds{};
GetWindowRect(child, &bounds);
MapWindowPoints(nullptr, parent, reinterpret_cast<POINT *>(&bounds), 2);
require(bounds.left >= 0 && bounds.right <= viewport.right,
"settings control fits the visible pane width");
}
};
for (const auto &[width, widenSidebar] : {std::pair{800, false}, {620, false}, {620, true}})
{
SetWindowPos(settings, nullptr, 0, 0, MulDiv(width, dpi, 96), MulDiv(540, dpi, 96),
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
if (widenSidebar)
for (int step = 0; step < 24; ++step)
SendMessageW(GetDlgItem(settings, 270), WM_KEYDOWN, VK_RIGHT, 0);
for (int page = 0; page < 18; ++page)
{
selectSettingsPage(settings, page);
controlsFit(pane);
if (page == 10) controlsFit(GetDlgItem(pane, 262));
if (page == 17) controlsFit(GetDlgItem(pane, 271));
}
}
selectSettingsPage(settings, 0);
SetWindowPos(settings,nullptr,0,0,480,360,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
GetWindowRect(GetDlgItem(settings, IDCANCEL), &cancel);
SCROLLINFO scroll{sizeof(scroll),SIF_ALL};
GetScrollInfo(settings,SB_VERT,&scroll);
GetScrollInfo(pane,SB_VERT,&scroll);
require(scroll.nMax+1>(int)scroll.nPage,"small settings window has vertical scrolling");
GetScrollInfo(settings,SB_HORZ,&scroll);
require(scroll.nMax+1>(int)scroll.nPage,"small settings window has horizontal scrolling");
require(!(GetWindowLongPtrW(pane, GWL_STYLE) & WS_HSCROLL),
"small settings window needs only vertical scrolling");
int controlMoves = 0;
auto trackedControl = GetDlgItem(settings,201);
auto trackedControl = GetDlgItem(pane, 201);
SetWindowSubclass(trackedControl,countControlMoves,99,(DWORD_PTR)&controlMoves);
SendMessageW(settings,WM_VSCROLL,SB_TOP,0);
SendMessageW(settings,WM_HSCROLL,SB_LEFT,0);
SendMessageW(pane,WM_VSCROLL,SB_TOP,0);
SendMessageW(pane,WM_HSCROLL,SB_LEFT,0);
controlMoves=0;
ValidateRect(settings,nullptr);
SendMessageW(settings,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA),0);
SendMessageW(settings,WM_TIMER,ks::ScrollFrameTimer,0);
require(controlMoves==0 && !GetUpdateRect(settings,nullptr,FALSE),"wheel at top does not move controls or erase the window");
SendMessageW(settings,WM_MOUSEWHEEL,MAKEWPARAM(0,WORD(short(-WHEEL_DELTA/2))),0);
SendMessageW(settings,WM_TIMER,ks::ScrollFrameTimer,0);
ValidateRect(pane,nullptr);
SendMessageW(pane,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA),0);
SendMessageW(pane,WM_TIMER,ks::ScrollFrameTimer,0);
require(controlMoves==0 && !GetUpdateRect(pane,nullptr,FALSE),"wheel at top does not move controls or erase the window");
SendMessageW(pane,WM_MOUSEWHEEL,MAKEWPARAM(0,WORD(short(-WHEEL_DELTA/2))),0);
SendMessageW(pane,WM_TIMER,ks::ScrollFrameTimer,0);
require(controlMoves==0,"partial wheel step does not rearrange controls");
SendMessageW(settings,WM_MOUSEWHEEL,MAKEWPARAM(0,WORD(short(-WHEEL_DELTA/2))),0);
SendMessageW(pane,WM_MOUSEWHEEL,MAKEWPARAM(0,WORD(short(-WHEEL_DELTA/2))),0);
require(controlMoves==0,"wheel changes wait for the shared frame timer");
SendMessageW(settings,WM_TIMER,ks::ScrollFrameTimer,0);
SendMessageW(pane,WM_TIMER,ks::ScrollFrameTimer,0);
require(controlMoves==1,"wheel scroll batches each control movement once");
SendMessageW(settings,WM_VSCROLL,SB_BOTTOM,0);
SendMessageW(settings,WM_HSCROLL,SB_RIGHT,0);
SendMessageW(pane,WM_VSCROLL,SB_BOTTOM,0);
SendMessageW(pane,WM_HSCROLL,SB_RIGHT,0);
controlMoves=0;
SendMessageW(settings,WM_MOUSEWHEEL,MAKEWPARAM(0,-WHEEL_DELTA),0);
SendMessageW(settings,WM_MOUSEHWHEEL,MAKEWPARAM(0,WHEEL_DELTA),0);
SendMessageW(settings,WM_TIMER,ks::ScrollFrameTimer,0);
SendMessageW(pane,WM_MOUSEWHEEL,MAKEWPARAM(0,-WHEEL_DELTA),0);
SendMessageW(pane,WM_MOUSEHWHEEL,MAKEWPARAM(0,WHEEL_DELTA),0);
SendMessageW(pane,WM_TIMER,ks::ScrollFrameTimer,0);
require(controlMoves==0,"wheel at bottom and right boundaries does not rearrange controls");
require((GetWindowLongPtrW(settings,GWL_STYLE)&WS_CLIPCHILDREN)!=0,"parent background excludes child controls");
RemoveWindowSubclass(trackedControl,countControlMoves,99);
RECT cancelAfterScroll{};
GetWindowRect(GetDlgItem(settings, IDCANCEL), &cancelAfterScroll);
require(EqualRect(&cancel, &cancelAfterScroll), "the footer stays anchored while the page scrolls");
GetClientRect(settings,&client);
GetWindowRect(GetDlgItem(settings,IDCANCEL),&cancel);
MapWindowPoints(nullptr,settings,(POINT*)&cancel,2);
require(cancel.left>=0&&cancel.top>=0&&cancel.right<=client.right&&cancel.bottom<=client.bottom,"bottom actions reachable by scrolling");
SendMessageW(settings,WM_VSCROLL,SB_TOP,0);
SendMessageW(settings,WM_HSCROLL,SB_LEFT,0);
SendMessageW(GetDlgItem(settings,IDCANCEL),WM_SETFOCUS,0,0);
GetWindowRect(GetDlgItem(settings,IDCANCEL),&cancel);
MapWindowPoints(nullptr,settings,(POINT*)&cancel,2);
require(cancel.left>=0&&cancel.top>=0&&cancel.right<=client.right&&cancel.bottom<=client.bottom,"keyboard focus reveals off-screen action");
require(cancel.left>=0&&cancel.top>=0&&cancel.right<=client.right&&cancel.bottom<=client.bottom,"footer actions stay reachable while the page scrolls");
SendMessageW(pane,WM_VSCROLL,SB_TOP,0);
SendMessageW(pane,WM_HSCROLL,SB_LEFT,0);
SendMessageW(GetDlgItem(pane, 205), WM_SETFOCUS, 0, 0);
GetScrollInfo(pane, SB_VERT, &scroll);
require(scroll.nPos > 0, "keyboard focus reveals an off-screen setting");
SetWindowPos(settings,nullptr,-20000,-20000,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
SendMessageW(settings,WM_DISPLAYCHANGE,0,0);
GetWindowRect(settings,&frame);
+147
View File
@@ -0,0 +1,147 @@
#include "app.h"
#include "input_pause.h"
#include <iostream>
namespace {
void require(bool result, const char *message)
{
if (!result) throw std::runtime_error(message);
}
template<class Predicate> void until(Predicate ready, const char *message)
{
auto deadline = GetTickCount64() + 4000;
while (!ready()) {
require(GetTickCount64() < deadline, message);
Sleep(10);
}
}
HWND childWindow(DWORD pid, const wchar_t *type)
{
HWND w{};
while ((w = FindWindowExW(nullptr, w, type, nullptr))) {
DWORD owner{};
GetWindowThreadProcessId(w, &owner);
if (owner == pid) return w;
}
return nullptr;
}
DWORD_PTR query(HWND w, UINT msg, WPARAM wp = 0)
{
DWORD_PTR result{};
require(SendMessageTimeoutW(w, msg, wp, 0, SMTO_ABORTIFHUNG | SMTO_ERRORONEXIT, 2000, &result),
"test resident did not respond");
return result;
}
void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected)
{
require(PostMessageW(resident, ks::TrayMessage, 0, WM_CONTEXTMENU), "cannot open tray menu");
HWND popup{};
until([&] { popup = childWindow(pid, L"#32768"); return popup && IsWindowVisible(popup); },
"tray menu did not open");
const auto menu = reinterpret_cast<HMENU>(query(popup, MN_GETHMENU));
wchar_t label[100]{};
require(GetMenuStringW(menu, 0, label, std::size(label), MF_BYPOSITION) &&
std::wstring_view(label).starts_with(expected), "incorrect input state in tray menu");
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);
}
}
bool trayIconMatchesInput(HICON icon, bool active)
{
HDC dc = CreateCompatibleDC(nullptr);
HBITMAP bitmap = CreateBitmap(16, 16, 1, 32, nullptr);
bool matches = false;
if (dc && bitmap) {
const auto previous = SelectObject(dc, bitmap);
if (icon && DrawIconEx(dc, 0, 0, icon, 16, 16, 0, nullptr, DI_NORMAL)) {
const auto tile = GetPixel(dc, 2, 8);
const auto white = RGB(255, 255, 255);
const auto gap = GetPixel(dc, 8, 8);
// The active keycap is purple. The pause glyph has two white strokes with a gap.
matches = active ? GetBValue(tile) > GetRValue(tile) + 70 :
GetPixel(dc, 5, 8) == white && GetPixel(dc, 10, 8) == white &&
GetRValue(gap) < 160 && std::abs(GetBValue(gap) - GetRValue(gap)) < 32;
}
SelectObject(dc, previous);
}
if (bitmap) DeleteObject(bitmap);
if (dc) DeleteDC(dc);
return matches;
}
int testInputPause()
{
auto name = L"KSwitcher-input-pause-" + ks::newSnippetId();
const auto folder = std::filesystem::temp_directory_path() / name;
PROCESS_INFORMATION child{};
HWND resident{};
int result = 1;
bool created = false;
try {
// Never switch the user's visible desktop or direct a command at their resident.
const auto desktop = CreateDesktopW(name.c_str(), nullptr, nullptr, 0, GENERIC_ALL, nullptr);
require(desktop && SetThreadDesktop(desktop), "cannot use private desktop");
created = std::filesystem::create_directory(folder);
require(created, "cannot create fixture directory");
const auto fixture = folder / L"KSwitcherInputTests.exe";
std::filesystem::copy_file(ks::executable(), fixture);
auto command = L"\"" + fixture.wstring() + L"\" --input-pause-resident";
STARTUPINFOW startup{sizeof(startup)};
startup.lpDesktop = name.data();
require(CreateProcessW(fixture.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
nullptr, folder.c_str(), &startup, &child), "cannot start test resident");
until([&] {
resident = childWindow(child.dwProcessId, L"KSwitcher.Main");
return resident && query(resident, ProbeInputState) == 1;
}, "resident did not start with both hooks and shortcuts");
require(query(resident, ProbeTrayIcon, TRUE), "active tray icon missing at startup");
constexpr UINT mods = MOD_CONTROL | MOD_SHIFT;
require(!RegisterHotKey(nullptr, 1, mods, VK_F23) && GetLastError() == ERROR_HOTKEY_ALREADY_REGISTERED,
"Files shortcut should be owned by resident before pause");
chooseInputAction(resident, child.dwProcessId, L"Pause &input processing");
until([&] { return query(resident, ProbeInputState) == 2; },
"pause did not release both hooks and bindings and cancel the queued snippet");
require(query(resident, ProbeTrayIcon), "pause bars missing after pause");
require(RegisterHotKey(nullptr, 1, mods, VK_F23), "another process could not acquire Files shortcut");
require(query(resident, ProbeInputState, 1) == 2, "settings, layout reload or IPC restarted input");
chooseInputAction(resident, child.dwProcessId, L"Resume &input processing");
require(query(resident, ProbeInputState) == 2, "Files conflict partially resumed input");
require(query(resident, ProbeTrayIcon), "Files shortcut conflict cleared the pause icon");
require(UnregisterHotKey(nullptr, 1), "cannot release Files shortcut");
require(RegisterHotKey(nullptr, 2, mods, VK_F22), "cannot occupy hook shortcut during pause");
chooseInputAction(resident, child.dwProcessId, L"Resume &input processing");
require(query(resident, ProbeInputState) == 2, "hook shortcut conflict partially resumed input");
require(query(resident, ProbeTrayIcon), "hook shortcut conflict cleared the pause icon");
require(RegisterHotKey(nullptr, 1, mods, VK_F23), "failed resume leaked Files registration");
UnregisterHotKey(nullptr, 1);
UnregisterHotKey(nullptr, 2);
chooseInputAction(resident, child.dwProcessId, L"Resume &input processing");
require(query(resident, ProbeInputState) == 1, "resume did not restore both hooks and shortcuts");
require(query(resident, ProbeTrayIcon, TRUE), "active tray icon missing after resume");
require(!RegisterHotKey(nullptr, 1, mods, VK_F23) && GetLastError() == ERROR_HOTKEY_ALREADY_REGISTERED,
"resident did not reclaim Files shortcut");
std::cout << "Tray pause/resume, hooks, settings reload, cross-process ownership and conflict rollback passed.\n";
result = 0;
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
}
if (child.hProcess) {
if (resident) PostMessageW(resident, WM_CLOSE, 0, 0);
if (WaitForSingleObject(child.hProcess, 2000) != WAIT_OBJECT_0) {
TerminateProcess(child.hProcess, 1);
WaitForSingleObject(child.hProcess, 2000);
result = 1;
}
CloseHandle(child.hThread);
CloseHandle(child.hProcess);
}
std::error_code error;
if (created) std::filesystem::remove_all(folder, error);
return result;
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include <windows.h>
inline constexpr UINT ProbeInputState = WM_APP + 200;
inline constexpr UINT ProbeTrayIcon = WM_APP + 201;
bool trayIconMatchesInput(HICON icon, bool active);
int testInputPause();
+187 -3
View File
@@ -14,6 +14,7 @@ struct InputRegressionAccess
{
return app.snippetPopup && IsWindowVisible(app.snippetPopup);
}
static size_t suggestionCount(const App &app) { return app.snippetMatches.size(); }
static bool suggestionsNearCaret(const App &app)
{
GUITHREADINFO info{sizeof(info)};
@@ -42,6 +43,10 @@ struct InputRegressionAccess
++*reinterpret_cast<int *>(context);
return DefSubclassProc(window, message, wp, lp);
}, 1, reinterpret_cast<DWORD_PTR>(&hideCount));
expireRun(app);
}
static void expireRun(App &app)
{
std::lock_guard lock(app.stateMutex);
app.run.at = GetTickCount64() - 2500;
}
@@ -65,6 +70,13 @@ bool conversionOnly = false;
bool typosOnly = false;
int pasteBehavior = 0;
int enterPresses = 0;
bool observeLiteralSequence = false;
ULONGLONG literalTextAt{}, literalEnterAt{};
std::wstring literalTextBeforeEnter;
bool observeMacros = false, moveFocusOnMacro = false;
bool rightAltAndCtrl = false, rightShift = false;
bool typeDuringMacros = false;
ULONGLONG macroStart{}, macroEnd{};
int copyFailuresRemaining = 0, copyRequests = 0;
int droppedSelectionKeys = 0;
bool trimCopiedSpaces = false;
@@ -84,6 +96,18 @@ LRESULT CALLBACK forwardingHook(int code, WPARAM wp, LPARAM lp)
}
LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
if (observeMacros && (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) && wp == VK_F8)
{
macroStart = GetTickCount64();
rightAltAndCtrl = (GetKeyState(VK_RMENU) & 0x8000) && (GetKeyState(VK_RCONTROL) & 0x8000);
if (moveFocusOnMacro) SetFocus(host);
return 0;
}
if (observeMacros && macroStart && message == WM_KEYDOWN && wp == VK_LEFT)
{
macroEnd = GetTickCount64();
rightShift = (GetKeyState(VK_RSHIFT) & 0x8000) != 0;
}
if (message == WM_KEYDOWN && wp == VK_LEFT && droppedSelectionKeys > 0 &&
(GetKeyState(VK_SHIFT) & 0x8000))
{
@@ -167,7 +191,19 @@ LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_P
if (pasteBehavior == 2) SendMessageW(w, EM_REPLACESEL, TRUE, (LPARAM)L"other!");
return 0;
}
if (message == WM_KEYDOWN && wp == VK_RETURN) ++enterPresses;
if (observeLiteralSequence && message == WM_CHAR && wp == L'l' && !enterPresses)
literalTextAt = GetTickCount64();
if (message == WM_KEYDOWN && wp == VK_RETURN)
{
if (observeLiteralSequence && !enterPresses)
{
literalEnterAt = GetTickCount64();
wchar_t before[128]{};
GetWindowTextW(w, before, std::size(before));
literalTextBeforeEnter = before;
}
++enterPresses;
}
return DefSubclassProc(w, message, wp, lp);
}
int stage = 0, ru = -1, en = -1;
@@ -233,7 +269,14 @@ void typeKeys(std::initializer_list<WORD> keys)
inputs.push_back(input);
}
require(SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT)) == inputs.size(),
"snippet autocomplete keyboard input submitted");
"snippet keyboard input submitted");
}
void expandMacroSnippet(const wchar_t *replacement)
{
app->settings.snippets = {{L";zmtest", replacement}};
prepare(L"prefix ;zmtest", false);
record(L";zmtest");
app->transform(0, 0, 0, field);
}
void finish()
{
@@ -268,6 +311,11 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
throw std::runtime_error("Native integration timed out");
if (app->busy)
{
if (typeDuringMacros && ks::InputRegressionAccess::deferring(*app))
{
typeDuringMacros = false;
typeKeys({VK_SPACE, 'X'});
}
if (typeDuringCorrection && ks::InputRegressionAccess::deferring(*app))
{
typeDuringCorrection = false;
@@ -693,10 +741,28 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
case 73:
require(enterPresses == 1 && text() == L"prefix ;qz\r\n" &&
!ks::InputRegressionAccess::suggestionsVisible(*app),
"Enter without arrow navigation reaches the editor");
"Enter reaches the editor while multiple suggestions await navigation");
prepare(L"prefix ", false);
typeKeys({VK_OEM_1, 'Q', 'Z', VK_OEM_MINUS, 'S'});
stage = 75;
break;
case 75:
require(ks::InputRegressionAccess::suggestionsVisible(*app) &&
ks::InputRegressionAccess::suggestionCount(*app) == 1,
"a filtered prefix leaves one visible suggestion");
enterPresses = 0;
typeKeys({VK_RETURN});
break;
case 76:
require(text() == L"prefix second" && enterPresses == 0 &&
!ks::InputRegressionAccess::suggestionsVisible(*app),
"Enter accepts the only suggestion without arrows or forwarding the key");
require(ks::readClipboard(app->window).text() == sentinel,
"accepting a single suggestion restores the clipboard");
app->resetInput();
SetFocus(host);
typeKeys({VK_OEM_1});
stage = 74;
break;
case 74:
if (ks::InputRegressionAccess::findingSuggestionCaret(*app))
@@ -865,6 +931,118 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
require(enterPresses == 0, "unverified snippet never submits Enter even without logging");
require(ks::readClipboard(app->window).text() == sentinel, "rejected snippet restores clipboard");
pasteBehavior = 0;
stage = 80;
break;
case 80:
if (!captured) saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
app->settings.autoCorrect = false;
ActivateKeyboardLayout(app->layouts[en].handle, 0);
observeMacros = true;
typeDuringMacros = true;
expandMacroSnippet(L"left{cursor}right{{ctrlr}}+{{altr}}+{{F8}}{pause:150}{{shiftr}}+{{left}}{enter}");
break;
case 81:
require(rightAltAndCtrl && rightShift && ks::modifiersReleased(),
"snippet chords press the specified right modifiers and release them");
require(macroStart && macroEnd >= macroStart + 140, "snippet pause separates actual keyboard events");
require(text() == L"prefix lef\r\n xright",
"snippet macros start at the cursor marker and finish before buffered typing");
require(ks::readClipboard(app->window).text() == sentinel, "snippet macros restore the clipboard");
expandMacroSnippet(L"left{cursor}right{{ctrl}}+{{V}}");
break;
case 82:
require(text() == L"prefix left" + sentinel + L"right", "a snippet paste chord uses the user's clipboard");
enterPresses = 0;
macroStart = 0;
moveFocusOnMacro = true;
expandMacroSnippet(L"done{{F8}}{pause:250}{enter}");
break;
case 83:
require(macroStart && GetFocus() == host && text() == L"prefix done" && enterPresses == 0,
"snippet macros stop when focus moves to a different control");
observeMacros = false;
moveFocusOnMacro = false;
expandMacroSnippet(L"left{pause:50}{enter}{enter}right{cursor}!");
stage = 92;
break;
case 92:
require(text() == L"prefix left\r\n\r\nright!" && enterPresses == 2,
"actions between text segments run before the next segment");
require(LOWORD(SendMessageW(field, EM_GETSEL, 0, 0)) == GetWindowTextLengthW(field) - 1,
"the cursor marker works in the final text segment");
require(ks::readClipboard(app->window).text() == sentinel,
"each verified snippet segment restores the clipboard");
finish();
break;
case 93:
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
app->settings.autoCorrect = false;
ActivateKeyboardLayout(app->layouts[en].handle, 0);
require(ks::lower(ks::processName(host)) == L"chatgpt",
"literal macro fixture runs under the Codex executable name");
observeLiteralSequence = true;
expandMacroSnippet(L"$example-skill{pause:500}{enter}{enter}{enter} Draft text{cursor}");
break;
case 94:
require(text() == L"prefix $example-skill\r\n\r\n\r\n Draft text" && enterPresses == 3,
"three Enter markers send three keys before the tail without requiring a suggestion");
require(literalTextBeforeEnter == L"prefix $example-skill" && literalTextAt &&
literalEnterAt >= literalTextAt + 475,
"the first Enter follows the typed prefix and the configured 500 ms pause");
require(ks::readClipboard(app->window).text() == sentinel,
"literal snippet actions restore the clipboard");
finish();
break;
case 84:
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
app->settings.snippets = {{L";r", L"rider ."}, {L"[g", L"expanded"}};
app->settings.autoCorrect = false;
ActivateKeyboardLayout(app->layouts[ru].handle, 0);
prepare(L"", false);
typeKeys({'G', 'J', 'L', 'L', 'T', VK_OEM_1, 'R'});
break;
case 85:
require(text() == L"поддежк", "layout variant does not expand at the end of a word");
prepare(L"поддека", false);
SendMessageW(field, EM_SETSEL, 5, 5);
typeKeys({VK_OEM_1, 'R'});
break;
case 86:
require(text() == L"поддежкка", "layout variant does not expand at a caret inside existing text");
require(LOWORD(SendMessageW(field, EM_GETSEL, 0, 0)) == 7,
"skipping expansion restores the caret before the rest of the word");
prepare(L"", false);
typeKeys({'G', 'J', 'L', 'L', 'T'});
break;
case 87:
require(text() == L"подде", "editor received the first part of the word");
ks::InputRegressionAccess::expireRun(*app);
typeKeys({VK_OEM_1, 'R'});
break;
case 88:
require(text() == L"поддежк", "layout variant does not expand after the typing buffer expires");
prepare(L"prefix (", false);
typeKeys({VK_OEM_1, 'R'});
break;
case 89:
require(text() == L"prefix (rider .", "layout variant expands after punctuation");
prepare(L"token_", false);
typeKeys({VK_OEM_4, 'G'});
break;
case 90:
require(text() == L"token_хп", "word boundary also applies to other trigger prefixes");
prepare(L"", false);
typeKeys({VK_OEM_4, 'G'});
break;
case 91:
require(text() == L"expanded", "another layout variant expands at the start of the field");
require(ks::readClipboard(app->window).text() == sentinel, "word boundary check restores the clipboard");
finish();
break;
case 20:
@@ -1182,6 +1360,12 @@ int main(int argc, char **argv)
stage = 64;
if (argc > 1 && std::string(argv[1]) == "--snippet-autocomplete")
stage = 66;
if (argc > 1 && std::string(argv[1]) == "--snippet-macros")
stage = 80;
if (argc > 1 && std::string(argv[1]) == "--snippet-literal-keys")
stage = 93;
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
stage = 84;
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");
+14 -1
View File
@@ -131,7 +131,7 @@ int main(int argc,char **argv)
{
const auto folder=root/L"wake";
std::filesystem::create_directory(folder);
const auto saved=Json{{"version",1},{"id",a},{"enabled",true},{"trusted",{
const auto saved=Json{{"version",1},{"id",a},{"enabled",true},{"shareInput",true},{"trusted",{
{b,{{"name","Wake peer"},{"key",left.derived},{"wakeMac","02468ace1357"}}},
{c,{{"name","Legacy peer"},{"key",left.derived}}}}}}.dump();
atomicWrite(folder/L"lan-pairing.bin",protect(Bytes(saved.begin(),saved.end())));
@@ -140,6 +140,19 @@ int main(int argc,char **argv)
check(peers.size()==2 && peers[0].at("id")==b && peers[0].at("address")=="" &&
peers[1].at("id")==c,"offline PCs remain selectable in Files with or without a saved MAC address");
check(peers.dump().find("02468ace1357")==std::string::npos,"Files snapshot omits the stored MAC address");
const auto pairing = readFile(folder/L"lan-pairing.bin",256*1024);
check(restored.inputEnabled(), "paired LAN input starts enabled");
restored.setInputPaused(true);
const auto state = request(restored,{{"action","status"}});
check(!restored.inputEnabled() && state.at("enabled")==true && state.at("shareInput")==true &&
state.at("controlMode")==0 && state.at("inputReady").empty() &&
state.at("inputStatus")=="Input processing paused in the tray.",
"tray pause disables LAN input while keeping discovery and the saved permission");
check(!restored.tickInput() && !restored.keyboard(KBDLLHOOKSTRUCT{},true) &&
!restored.mouse(WM_MOUSEMOVE,MSLLHOOKSTRUCT{},true), "paused LAN router ignores input and queued ticks");
restored.setInputPaused(false);
check(restored.inputEnabled() && readFile(folder/L"lan-pairing.bin",256*1024)==pairing,
"LAN input resumes from the original pairing without rewriting it");
}
if(argc>1&&std::string(argv[1])=="--network")
{
+91
View File
@@ -0,0 +1,91 @@
#include "lan_clients.h"
#include <iostream>
namespace
{
using ks::lan::Json;
void require(bool value, const char *message)
{
if (!value) throw std::runtime_error(message);
}
Json request(const std::wstring &name)
{
require(WaitNamedPipeW(name.c_str(), 3000) != FALSE, "LAN client pipe did not start");
struct Pipe
{
HANDLE value;
~Pipe() { if (value != INVALID_HANDLE_VALUE) CloseHandle(value); }
} pipe{CreateFileW(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, nullptr)};
require(pipe.value != INVALID_HANDLE_VALUE, "could not open LAN client pipe");
auto transfer = [&](void *buffer, DWORD length, bool write) {
auto *cursor = static_cast<char *>(buffer);
while (length)
{
DWORD count{};
require((write ? WriteFile(pipe.value, cursor, length, &count, nullptr) :
ReadFile(pipe.value, cursor, length, &count, nullptr)) && count, "pipe transfer failed");
cursor += count;
length -= count;
}
};
auto payload = Json{{"action", "peers"}}.dump();
DWORD length = DWORD(payload.size());
transfer(&length, sizeof(length), true);
transfer(payload.data(), length, true);
transfer(&length, sizeof(length), false);
require(length > 0 && length < 4096, "unexpected reply size");
payload.resize(length);
transfer(payload.data(), length, false);
char ack{};
transfer(&ack, 1, true);
return Json::parse(payload);
}
}
int main()
{
const auto suffix = L".test." + std::to_wstring(GetCurrentProcessId());
const auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-LAN" + suffix);
try
{
require(std::filesystem::create_directory(root), "could not create test directory");
DWORD session{};
require(ProcessIdToSessionId(GetCurrentProcessId(), &session) != FALSE, "no Windows session");
const auto pipe = L"\\\\.\\pipe\\KSwitcher.LAN.Clients.v1." + std::to_wstring(session) + suffix;
{
ks::lan::LanClients clients(root);
clients.start([](const Json &request, const auto &, const auto &send) {
require(request.at("action") == "peers", "unexpected request");
constexpr std::string_view reply = R"([{"id":"fixture","name":"Paired PC","online":true}])";
send(reply.data(), DWORD(reply.size()));
}, suffix);
// WaitNamedPipe returns immediately if the instance has not been created yet.
for (int n = 0; n < 100 && !WaitNamedPipeW(pipe.c_str(), 20); ++n) Sleep(20);
require(request(pipe).contains("error"), "an untrusted executable was accepted");
const auto path = ks::utf8(ks::executable());
const auto trusted = clients.settings("trustClient", {{"path", path}});
require(trusted.size() == 1, "the program must be enrolled exactly once");
require(request(pipe).at(0).at("name") == "Paired PC", "the trusted program was rejected");
auto changed = trusted;
changed.at(0)["sha256"] = std::string(64, '0');
const auto store = root / L"lan-clients.bin";
const auto differentHash = changed.dump();
ks::atomicWrite(store, ks::protect(ks::Bytes(differentHash.begin(), differentHash.end())));
require(request(pipe).contains("error"), "an executable with a different fingerprint was accepted");
clients.settings("trustClient", {{"path", path}});
clients.settings("removeClient", {{"path", trusted.at(0).at("path")}});
require(request(pipe).contains("error"), "revocation must reject the next request");
}
std::filesystem::remove(root / L"lan-clients.bin");
std::filesystem::remove(root);
std::cout << "Verified executable approval, resident pipe access and revocation.\n";
return 0;
}
catch (const std::exception &error)
{
std::cerr << error.what() << '\n';
return 1;
}
}
+64 -4
View File
@@ -319,10 +319,10 @@ void hubChecks()
while((hubs[0]->ready().size()!=2||hubs[1]->ready().size()!=2||hubs[2]->ready().size()!=2)&&GetTickCount64()<deadline)pump();
check(hubs[0]->ready().size()==2&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"three TCP hubs authenticate all independent pair channels on one listener per PC");
auto generation=hubs[0]->ready();
for(auto &list:endpoints)for(auto &e:list)e.address=0;
for(auto &list:endpoints)for(auto &e:list){e.address=0;e.discovered=false;}
for(int n=0;n<20;++n)pump();
check(hubs[0]->ready()==generation&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"expired discovery does not destroy authenticated channels");
for(auto &list:endpoints)for(auto &e:list)e.address=htonl(INADDR_LOOPBACK);
for(auto &list:endpoints)for(auto &e:list){e.address=htonl(INADDR_LOOPBACK);e.discovered=true;}
InputFrame keyFrame{InputType::Key,7,'A',0,1},cross{InputType::Cross,8,2,30000};
hubs[0]->poll(endpoints[0],{{ids[1],keyFrame},{ids[2],cross}},incoming[0],GetTickCount64());
for(int n=0;n<100&&(incoming[1].empty()||incoming[2].empty());++n)pump();
@@ -340,16 +340,76 @@ void hubChecks()
for(int n=0;n<300&&(server.ready().empty()||client.ready().empty());++n){
server.poll(unknown,{},a,GetTickCount64());client.poll(known,{},b,GetTickCount64());Sleep(1);
}
check(server.ready().size()==1&&client.ready().size()==1,"saved pair listens and authenticates without receiving a discovery announcement");
check(server.ready().size()==1&&client.ready().size()==1,"available peer can accept inbound TCP without dialing");
}
endpoints[0].erase(endpoints[0].begin());hubs[0]->poll(endpoints[0],{},incoming[0],GetTickCount64()+1800);
check(!hubs[0]->ready().contains(ids[1])&&hubs[0]->ready().contains(ids[2]),"forgetting one pair revokes only its channel");
}
void offlineDiscoveryChecks()
{
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
struct Close{~Close(){WSACleanup();}} close;
std::string a(32,'a'),b(32,'b'),key(64,'f');
const auto pa=freePort(),pb=freePort();
InputHub left(a,pa),right(b,pb);
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),pb,false}},eb{{a,key,htonl(INADDR_LOOPBACK),pa,false}};
std::vector<RoutedInput> ia,ib;
int datagrams=0;
left.datagrams([&](const auto &,const auto &){++datagrams;});
auto now=GetTickCount64();
auto pump=[&](uint64_t step=1){now+=step;right.poll(eb,{},ib,now);left.poll(ea,{},ia,now);};
auto checkIdle=[&]{
check(left.onlinePeers()==0&&left.ready().empty()&&!left.needsHelp()&&datagrams==0,
"offline saved peer does not trigger input retries or connection help");
SOCKET probe=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
sockaddr_in addr{};addr.sin_family=AF_INET;addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);addr.sin_port=htons(pa);
int result=connect(probe,(sockaddr*)&addr,sizeof(addr));
const auto error=WSAGetLastError();closesocket(probe);
check(result==SOCKET_ERROR&&error==WSAECONNREFUSED,"input TCP listener is closed while all peers are offline");
};
pump();pump(20000);checkIdle();
auto rediscover=[&]{
ea.front().discovered=eb.front().discovered=true;
for(int n=0;n<200&&(left.ready().empty()||right.ready().empty());++n){pump(20);Sleep(1);}
check(left.onlinePeers()==1&&left.ready().contains(b)&&right.ready().contains(a),
"input TCP connects when the saved peer reappears in discovery");
};
rediscover();
const auto oldEpoch=left.ready().at(b);
ea.front().discovered=false;
eb.clear(); // The other instance stops while discovery is already stale.
for(int n=0;n<30;++n){pump(20);Sleep(1);}
pump(20000);checkIdle();
eb={{a,key,htonl(INADDR_LOOPBACK),pa,false}};
rediscover();
check(left.ready().at(b)!=oldEpoch,"rediscovery replaces the disconnected input generation");
}
void fallbackChecks()
{
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
struct Close{~Close(){WSACleanup();}} close;
std::string a(32,'a'),b(32,'b'),key(64,'f');
{
auto pa=freePort(),pb=freePort();InputHub left(a,pa),right(b,pb);
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),pb}},eb{{a,key,0}};
std::vector<RoutedInput> ia,ib;
int datagrams=0;
left.datagrams([&](const auto &,const auto &){++datagrams;});
auto now=GetTickCount64();
right.poll(eb,{},ib,now); // Listen, but delay reading and authenticating the TCP connection.
left.poll(ea,{},ia,now);
for(int n=0;n<100&&left.status().find("authenticating")==std::string::npos;++n){
Sleep(1);left.poll(ea,{},ia,now+1);
}
check(left.status().find("authenticating")!=std::string::npos,"TCP connection is waiting for the peer handshake");
now+=6000;
left.poll(ea,{},ia,now);
for(int n=0;n<100&&(left.ready().empty()||right.ready().empty());++n){
++now;right.poll(eb,{},ib,now);left.poll(ea,{},ia,now);Sleep(1);
}
check(left.ready().contains(b)&&right.ready().contains(a)&&datagrams==0,
"UDP fallback does not cancel a TCP handshake within its deadline");
}
for(bool udp:{false,true}){
auto pa=freePort(),pb=freePort(),blocked=freePort();InputHub left(a,pa),right(b,pb);
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),blocked}},eb{{a,key,htonl(INADDR_LOOPBACK),udp?blocked:pa}};
@@ -507,6 +567,6 @@ void channelChecks()
}
int main()
{
try{channelChecks();hubChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
try{channelChecks();hubChecks();offlineDiscoveryChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
catch(const std::exception &e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}
}
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include <windows.h>
#include <commctrl.h>
inline HWND settingsViewport(HWND settings)
{
return GetDlgItem(settings, 264);
}
inline HWND settingsNavigation(HWND settings)
{
return GetDlgItem(settings, 260);
}
inline HTREEITEM settingsSection(HWND navigation, int page)
{
const auto find = [&](auto &&self, HTREEITEM first) -> HTREEITEM
{
for (auto item = first; item; item = TreeView_GetNextSibling(navigation, item))
{
TVITEMW data{};
data.mask = TVIF_PARAM;
data.hItem = item;
if (TreeView_GetItem(navigation, &data) && data.lParam == page) return item;
if (const auto match = self(self, TreeView_GetChild(navigation, item))) return match;
}
return nullptr;
};
return find(find, TreeView_GetRoot(navigation));
}
inline void selectSettingsPage(HWND settings, int page)
{
const auto navigation = settingsNavigation(settings);
const auto item = settingsSection(navigation, page);
TreeView_EnsureVisible(navigation, item);
TreeView_SelectItem(navigation, item);
}
inline HWND showComputerSettings(HWND settings)
{
selectSettingsPage(settings, 10);
return GetDlgItem(settingsViewport(settings), 262);
}
+27 -6
View File
@@ -459,12 +459,33 @@ int main(int argc, char **argv)
require(ks::transliterate(L"Shchuka") == L"Щука", "reverse transliteration");
require(ks::parseTemplate(L"a{cursor}b").suffix == L"b", "snippet suffix");
require(ks::parseTemplate(L"{{cursor}}").text == L"{cursor}", "escaped cursor");
require(ks::parseTemplate(L"rider .{enter}").text == L"rider ." &&
ks::parseTemplate(L"rider .{enter}").enters == 1, "Enter is an action, not inserted text");
require(ks::parseTemplate(L"a{cursor}b{enter}{enter}").suffix == L"b" &&
ks::parseTemplate(L"a{cursor}b{enter}{enter}").enters == 2, "Enter actions preserve cursor suffix");
require(ks::parseTemplate(L"{{enter}}").text == L"{enter}" &&
ks::parseTemplate(L"{{enter}}").enters == 0, "escaped Enter is literal");
const auto enters = ks::parseTemplate(L"a{cursor}b{enter}{enter}");
require(enters.text == L"ab" && enters.suffix == L"b" &&
enters.actions == std::vector<ks::SnippetAction>{{2, std::vector<WORD>{VK_RETURN}},
{2, std::vector<WORD>{VK_RETURN}}},
"Enter actions preserve the inserted text and cursor suffix");
const auto escaped = ks::parseTemplate(L"before {{cursor}} {{enter}} {{{shift}}} {{pause:50}} after");
require(escaped.text == L"before {cursor} {enter} {{shift}} {pause:50} after" && escaped.actions.empty(),
"escaped snippet markers are literal even inside text");
const auto macros = ks::parseTemplate(L"a{{SHIFT}}{cursor}b{pause:50}{{altr}}+{{ctrl}}+{{F5}}{{tab}}{{ctrl}}+{{return}}");
require(macros.text == L"ab" && macros.suffix == L"b" &&
macros.actions == std::vector<ks::SnippetAction>{{1, std::vector<WORD>{VK_LSHIFT}}, {2, DWORD{50}},
{2, std::vector<WORD>{VK_RMENU, VK_LCONTROL, VK_F5}}, {2, std::vector<WORD>{VK_TAB}},
{2, std::vector<WORD>{VK_LCONTROL, VK_RETURN}}},
"snippet macros preserve key chords, tap order, pauses and cursor placement");
const std::wstring literal = L"{{unknown}} + {pause:-1} {pause:10001} {pause:99999999999999} {pause:}";
const auto unrecognized = ks::parseTemplate(literal);
require(unrecognized.text == literal && unrecognized.actions.empty(),
"unknown keys and invalid pause durations remain literal");
const auto plus = ks::parseTemplate(L"2+{{left}}+1{pause:0}{pause:10000}");
require(plus.text == L"2++1" && plus.actions == std::vector<ks::SnippetAction>{
{2, std::vector<WORD>{VK_LEFT}}, {4, DWORD{0}}, {4, DWORD{10000}}},
"only a plus between key markers forms a chord and pause bounds are inclusive");
const auto prompt = ks::parseTemplate(L"$example-skill{pause:500}{enter}{enter}{enter} Draft text{cursor}");
require(prompt.text == L"$example-skill Draft text" && prompt.suffix.empty() &&
prompt.actions == std::vector<ks::SnippetAction>{{14, DWORD{500}}, {14, std::vector<WORD>{VK_RETURN}},
{14, std::vector<WORD>{VK_RETURN}}, {14, std::vector<WORD>{VK_RETURN}}},
"all three Enter markers stay before the tail text");
require(ks::parseTemplate(L"{cursor}{cursor}").cursors == 2, "duplicate cursor detection");
require(ks::Hotkey::parse(L"Ctrl+Alt+Shift+Space")->key == VK_SPACE, "hotkey parse");
require(!ks::Hotkey::parse(L"Ctrl+F25"), "invalid function key");
+20
View File
@@ -45,6 +45,26 @@ frames[-1].save(root / 'kswitcher-files.ico', sizes=icon_sizes, append_images=fr
if args.files_only:
raise SystemExit
# Keep the two pause bars aligned to whole pixels at each tray size.
def draw_paused_icon(size):
scale = 8
tile = Image.new('RGBA', (size * scale, size * scale))
unit = size * scale / 32
ImageDraw.Draw(tile).rounded_rectangle(
(unit, unit, 31 * unit - 1, 31 * unit - 1), radius=7 * unit, fill='#575E68')
tile = tile.resize((size, size), Image.Resampling.LANCZOS)
draw = ImageDraw.Draw(tile)
top = round(size / 4)
left = round(size / 4)
width = round(size * 3 / 16)
for x in (left, size - left - width):
draw.rectangle((x, top, x + width - 1, size - top - 1), fill='white')
return tile
paused_frames = [draw_paused_icon(size) for size, _ in icon_sizes]
paused_frames[-1].save(root / 'kswitcher-paused.ico', sizes=icon_sizes, append_images=paused_frames[:-1])
# Geometric K: white stem/upper arm, mint lower arm on an indigo keycap.
polygons = [('#FFFFFF', [(8, 7), (12, 7), (12, 25), (8, 25)]),
('#FFFFFF', [(11, 15), (22, 6), (25, 9), (14, 18)]),