Compare commits

...
Author SHA1 Message Date
agrynco 211a6bdb33 Prepare KSwitcher v0.8.12 for stable delivery
Refs #227
2026-12-01 20:46:12 +02:00
agrynco 240cc535ba Report and reset held input blocking LAN handoffs
Refs #227
2026-12-01 20:38:02 +02:00
agrynco 92b72c2e7b Merge pull request 'Prepare KSwitcher v0.8.11 with Open URL shortcuts' (#225) from codex/shortcut-open-url into prerelease 2026-11-30 12:59:06 +02:00
agrynco 59d01375ff Ship Open URL shortcuts in KSwitcher v0.8.11
Refs #219
2026-11-30 12:59:02 +02:00
agrynco 2ffee2f880 Merge pull request 'Promote prerelease to main for KSwitcher v0.8.10' (#224) from prerelease into main 2026-11-30 12:07:58 +02:00
agrynco e5987dee22 Merge pull request 'Prepare KSwitcher v0.8.10 with the Explorer launch fix' (#223) from codex/settings-close-after-apply into prerelease 2026-11-30 12:07:43 +02:00
agrynco 890d869f8f Fix Explorer app launching from the elevated resident
Refs #219
2026-11-30 12:07:38 +02:00
agrynco 77aa5b7894 Merge pull request 'Prepare KSwitcher v0.8.10 with corrected Settings save controls' (#222) from codex/settings-close-after-apply into prerelease 2026-11-30 12:01:42 +02:00
agrynco d95f521c77 Disable Settings Save after Apply in v0.8.10 2026-11-30 12:01:38 +02:00
agrynco fd4ba1b69f Merge pull request 'Promote prerelease to main for KSwitcher v0.8.9' (#221) from prerelease into main 2026-11-30 11:50:47 +02:00
agrynco 2a6dfc92ba Merge pull request 'Prepare KSwitcher v0.8.9 with custom shortcuts' (#220) from codex/219-custom-shortcuts into prerelease 2026-11-30 11:49:21 +02:00
agrynco 418b262c2a Prepare KSwitcher v0.8.9 release
Refs #219
2026-11-30 11:49:16 +02:00
agrynco ee9bcf98a7 Add configurable global application shortcuts
Refs #219
2026-11-30 11:19:34 +02:00
agrynco bc086873ba Merge pull request 'Promote prerelease to main for KSwitcher v0.8.8' (#218) from prerelease into main 2026-11-28 15:16:43 +02:00
agrynco a1aa432355 Merge pull request 'Prepare KSwitcher v0.8.8 with contrasting Lavender popups' (#217) from codex/deliver-v0.8.8 into prerelease 2026-11-28 15:16:29 +02:00
agrynco 919f8e9c7c Ship contrasting Lavender popup frames in v0.8.8
Refs #9
2026-11-28 15:16:17 +02:00
agrynco e852da8fcd Merge pull request 'Promote prerelease to main for KSwitcher v0.8.7' (#216) from prerelease into main 2026-11-28 15:04:14 +02:00
agrynco 79aeff1c8b Merge pull request 'Prepare KSwitcher v0.8.7 with Change drive fixes' (#215) from codex/deliver-v0.8.7 into prerelease 2026-11-28 15:04:04 +02:00
agrynco 03f5a8db7c Ship Change drive shortcuts and complete disk capacity values in v0.8.7
Refs #9
2026-11-28 15:03:53 +02:00
agrynco 99c8b6191f Merge pull request 'Promote prerelease to main for KSwitcher v0.8.6' (#214) from prerelease into main 2026-11-28 14:52:09 +02:00
agrynco 50804185f4 Merge pull request 'Prepare KSwitcher v0.8.6 for stable delivery' (#213) from codex/deliver-v0.8.6 into prerelease 2026-11-28 14:51:08 +02:00
agrynco a9866d6973 Record KSwitcher v0.8.6 package manifest and checksum 2026-11-28 14:49:16 +02:00
agrynco 7b70105168 Use current pane source checks for Space Analyzer
Refs #94
2026-11-28 14:46:55 +02:00
agrynco b076dcb303 Open Space Analyzer directly in a Files pane
Refs #94
2026-11-28 14:44:26 +02:00
agrynco 8bedb9ffbd Set KSwitcher version to v0.8.6 2026-11-28 14:44:25 +02:00
agrynco 8f52bf2a8f Preserve fallback when the fast scan cannot read the root 2026-11-28 14:44:04 +02:00
agrynco 359b9ce284 Batch local NTFS folder-size scans 2026-11-28 14:38:46 +02:00
agrynco 160cece79d Prefer the tracked layout when recent input matches several layouts 2026-11-28 14:38:30 +02:00
agrynco 2869d584d8 Check the latest stable release without fetching release history 2026-11-28 14:37:05 +02:00
agrynco 2db1d79c1d Run delayed selection regression independently
Refs #135
2026-11-28 14:36:34 +02:00
agrynco fb27ad8843 Recover recent text selection in Claude and verify hosted editors
Refs #135

Refs #137
2026-11-28 14:36:18 +02:00
agrynco c910fc32d8 Merge pull request 'Promote prerelease to main for KSwitcher v0.8.5' (#212) from prerelease into main 2026-11-28 01:43:52 +02:00
agrynco 879d2adcce Merge pull request 'Prepare KSwitcher v0.8.5 for stable delivery' (#211) from codex/deliver-v0.8.5 into prerelease 2026-11-28 01:43:41 +02:00
agrynco 356f472fd2 Prepare KSwitcher v0.8.5 for stable delivery
Refs #209
2026-11-28 01:43:04 +02:00
agrynco 203d9ec68d Merge pull request 'Show KSwitcher snippet suggestions in Dirlume' (#210) from codex/issue-209 into prerelease 2026-11-28 01:33:00 +02:00
agrynco f9cbb29c07 Insert selected KSwitcher snippets in Dirlume terminals
Refs #209
2026-11-27 17:39:11 +02:00
agrynco 187334aed2 Show KSwitcher snippet suggestions in WebView2 text fields
Refs #209
2026-11-27 16:06:50 +02:00
agrynco ae7939eca5 Merge pull request 'Promote prerelease to main for KSwitcher v0.8.4' (#208) from prerelease into main 2026-11-27 10:56:56 +02:00
agrynco f7620d164f Merge pull request 'Prepare KSwitcher v0.8.4 for stable delivery' (#207) from codex/deliver-v0.8.4 into prerelease 2026-11-27 10:55:14 +02:00
agrynco 47e10477e1 Prepare KSwitcher v0.8.4 for stable delivery
Refs #204

Refs #122

Refs #196
2026-11-27 10:53:35 +02:00
agrynco f2e403dd39 Merge pull request 'Allow trusted LAN clients to resolve transfer conflicts' (#206) from codex/dirlume-transfer-conflicts into prerelease 2026-11-27 10:00:16 +02:00
agrynco 85cdce1b01 Allow trusted LAN clients to resolve transfer conflicts
Refs #122
2026-11-27 09:57:45 +02:00
agrynco 4acff70e49 Merge pull request 'Move chat language profiles into Settings' (#205) from codex/issue-204-chat-languages into prerelease 2026-11-27 03:27:33 +02:00
55 changed files with 3052 additions and 411 deletions

No files matched your search

+28 -2
View File
@@ -1,17 +1,18 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.8.3 LANGUAGES C CXX RC)
project(KSwitcher VERSION 0.8.12 LANGUAGES C CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_folder_size.cpp src/files_text_window.cpp
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp
src/files_mcp.cpp resources/files.rc)
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/files-space-analyzer-controls.inc"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-compare.ico")
include(cmake/FilesTextLibraries.cmake)
include(cmake/FilesArchiveLibraries.cmake)
@@ -150,6 +151,14 @@ else()
target_link_options(KSwitcherOcrTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
enable_testing()
add_executable(KSwitcherFilesFolderSizeTests tests/files_folder_size.cpp src/files_folder_size.cpp)
target_include_directories(KSwitcherFilesFolderSizeTests PRIVATE src)
target_compile_definitions(KSwitcherFilesFolderSizeTests PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
if(NOT MSVC)
target_link_options(KSwitcherFilesFolderSizeTests PRIVATE -static)
endif()
add_test(NAME files-folder-size COMMAND KSwitcherFilesFolderSizeTests)
set_tests_properties(files-folder-size PROPERTIES SKIP_RETURN_CODE 77)
add_executable(KSwitcherFilesTextTests tests/files_text_document.cpp src/files_text_document.cpp)
target_include_directories(KSwitcherFilesTextTests PRIVATE src)
target_compile_definitions(KSwitcherFilesTextTests PRIVATE UNICODE _UNICODE NOMINMAX WIN32_LEAN_AND_MEAN)
@@ -245,6 +254,16 @@ add_test(NAME files-recent-folders-panel
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_recent_folders_panel.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-recent-folders-panel PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
add_test(NAME files-drive-picker
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_drive_shortcuts.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -FtpProfiles)
set_tests_properties(files-drive-picker PROPERTIES RUN_SERIAL TRUE TIMEOUT 45)
add_test(NAME files-lavender-drive-picker
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_lavender.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -DrivePickerOnly)
set_tests_properties(files-lavender-drive-picker PROPERTIES RUN_SERIAL TRUE TIMEOUT 25)
add_test(NAME files-lavender
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_lavender.ps1"
@@ -255,6 +274,11 @@ add_test(NAME files-space-analyzer-layout
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-space-analyzer-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 25)
add_test(NAME files-space-analyzer-pane
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_pane.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-space-analyzer-pane PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
find_program(KSWITCHER_NODE NAMES node)
if(KSWITCHER_NODE)
add_test(NAME files-terminal-enter
@@ -358,6 +382,8 @@ 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_dependencies(KSwitcherInputTests KSwitcherFilesActivationFixture)
add_test(NAME custom-shortcut-layout COMMAND KSwitcherInputTests --custom-shortcut-layout $<TARGET_FILE:KSwitcherFilesActivationFixture>)
add_dependencies(KSwitcherInputTests KSwitcherScreenshot)
add_test(NAME clipboard-history-layout COMMAND KSwitcherInputTests --history-layout)
set_tests_properties(clipboard-history-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
+21 -14
View File
@@ -5,6 +5,8 @@
власних діалогів та налаштувань. Діалоги файлових операцій мають темний
заголовок, помітну рамку й білі поля на лавандовому тлі. Попередження мають
червоний заголовок. За замовчуванням увімкнено Far. Гарячі клавіші діють в обох стилях.
У Lavender меню вибору диска, меню команд, пошук панелі та підказки команд мають
світло-лавандове тло та контрастну фіолетову рамку завтовшки 2 пікселі за масштабу 100%.
Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far.
Іконка головного вікна показує дві сині панелі з бірюзовою рамкою та виділеним рядком.
@@ -181,9 +183,10 @@ Warning і початковий фокус на No.
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP, SFTP і SMB.
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
до закриття меню, навіть коли оновлюється список LAN.
Літера відкриває локальний диск. Цифри **1**, **2**, **3** і **4** відкривають
FTP, SFTP, SMB і Recent folders відповідно. Для LAN-дисків і Wake доступні
цифри 5–9 і 0. У меню лише для LAN доступні цифри 2–9 і 0.
Призначена цифра зберігається до закриття меню, навіть коли оновлюється список LAN.
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
документ — у програмі, призначеній для його типу у Windows. EXE запускається
@@ -465,6 +468,8 @@ Warning і початковий фокус на No.
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
На локальному NTFS підрахунок читає записи каталогів пакетами та паралельно
обходить підпапки. Для інших файлових систем діє звичайний обхід.
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
позначених папок в інших рядках рахує позначені папки. Без позначок
F3 рахує папку під курсором або відкриває файл. Папки обробляються по черзі,
@@ -601,23 +606,24 @@ Warning і початковий фокус на No.
коли вимірювання недоступне. Якщо попереднє число є, позначка ! відрізняє
його від свіжого результату.
- **Commands → Space Analyzer** показує місткість і вільне місце за даними
Windows перед скануванням. Volume вибирає корінь тому, Folder повертає
поточну локальну папку, Start запускає фоновий аналіз тим самим обходом,
що й підрахунок розмірів F3. Посилання на каталоги всередині області
сканування позначаються як link. Stop залишає часткові результати, а
Rescan повторює аналіз із початку.
- Дерево показує логічний розмір, зайняті байти та частку логічного розміру
від батьківської папки. Знак + позначає частковий підрахунок. Зайняті байти
- **Left → Space Analyzer** або **Right → Space Analyzer** відкриває аналіз
локальної папки в цій панелі та запускає сканування. **Close** або Esc
повертає список файлів. **Commands → Space Analyzer** відкриває діалог,
де **Start** запускає аналіз після показу місткості та вільного простору.
**Volume** вибирає корінь тому, а **Folder** повертає поточну локальну папку.
**Stop** залишає часткові результати. **Rescan** запускає аналіз заново.
- **Logical size** і **Size on disk** перемикають метрику дерева, часток
від батьківської папки та обох графіків. Посилання позначаються як link.
Знак + позначає частковий підрахунок. Зайняті байти
підсумовуються за файловими записами, включно з окремими іменами для
жорстких посилань. Службові дані файлової системи в цей підсумок не входять.
Відсутні дані про зайняті байти позначаються в рядку стану.
- Treemap показує дочірні елементи вибраної папки прямокутниками,
пропорційними до їхнього логічного розміру. Дрібні елементи доступні в
пропорційними до їхнього розміру за вибраною метрикою. Дрібні елементи доступні в
дереві. Клік по плитці відкриває точний елемент у сусідній панелі. Стрілки
переводять фокус між плитками, Enter відкриває плитку у фокусі.
- Sunburst показує до трьох рівнів вкладеності секторами за логічним
розміром. Клік по сектору та Enter у відповідному рядку списку ведуть
- Sunburst показує до трьох рівнів вкладеності секторами за вибраною метрикою.
Клік по сектору та Enter у відповідному рядку списку ведуть
до одного елемента. Обраний рядок підсвічує відповідний сектор.
- Під час аналізу всього NTFS-тому Files використовує індекс MFT за
наявності доступу Windows. Звичайний обхід працює без такого доступу.
@@ -642,6 +648,7 @@ Warning і початковий фокус на No.
- Коли список LAN-дисків змінює розмір меню Change drive, рамка й список
змінюють позицію разом. Рамка повністю перемальовується після зміни
розміру, а список має однаковий внутрішній відступ зліва і справа.
Смуга прокрутки має окреме місце, щоб не обрізати значення вільного місця.
- Тайм-аут запиту дисків відображається як Connection timed out. Якщо
ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. Commands → Files log відкриває до 200 останніх записів поточного або попереднього журналу. Refresh оновлює список. Copy selected або Ctrl+C копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано.
+17 -2
View File
@@ -35,7 +35,8 @@ retain their original reply formats.
- `capabilities` optionally takes a `peer`. It returns the broker `protocol`
(2), `hostRevision`, and boolean `write`, `delete`, `move`,
`revisionRead`, `onHostTransfer`, and `localEndpoint` fields. With no peer,
`revisionRead`, `onHostTransfer`, `localEndpoint`, and optional
`conflictPrompt` fields. With no peer,
the fields describe the local broker and its grants. With a peer, the flags
also account for its supported protocol. A peer with revision 0 still
supports legacy browsing and downloading.
@@ -57,7 +58,8 @@ retain their original reply formats.
The recycle bin is subject to Windows availability on the paired host.
- `transfer` takes `source` and `target` objects with a `peer` and `path`
each, optional `move` (default false), and a `conflict` policy of `fail`
(default), `skip`, or `replace`. Replace merges directories and replaces
(default), `skip`, `replace`, or `ask` when `conflictPrompt` is available.
Replace merges directories and replaces
regular files after validating the destination revision. The broker
allows at most one local endpoint, represented by `"peer": null`. For a
local endpoint the client must open the pipe with Windows impersonation
@@ -69,6 +71,12 @@ retain their original reply formats.
final frame has `type: "complete"` and counts, or an error. Transfers
on one paired computer use its own file service even across drives. The
local pipe exchanges only control and status for transfers.
- Ask merges directories and reports individual collisions in a JSON frame
with `type: "conflict"`, target `path`, `incoming` and `existing` metadata
(as in `stat`), and boolean `replaceable`. Respond with a JSON frame
containing `decision: "replace"`, `"skip"`, or `"cancel"`. Send
`decision: "wait"` at least once every five seconds while a prompt is open.
Access is checked again after each reply and before publishing the file.
- For a move, the copy phase finishes before source deletion begins.
Skipped items remain at the source. Cancellation or failure can leave
previously completed destination items. Failure during source cleanup
@@ -131,6 +139,13 @@ 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.
If a held key or button blocks a handoff, the tray and **Settings → Computers**
identify the PC and name the input when available. The hint clears when the
input is released or a handoff succeeds. If Windows still sees an input as held,
choose **Reset held keys and mouse buttons** in the tray menu on the PC named
in the hint. Both computers need v0.8.12 or later for the source PC to display
which input is held on the destination.
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.
+32 -2
View File
@@ -46,6 +46,26 @@ Saving Settings now merges independent resident/editor changes. If the same fiel
changed on both sides, choose whether to retain your draft without closing the
window. Declining preserves all draft edits. No export/import workaround is needed.
## Custom shortcuts
In **Settings → Shortcuts → Custom shortcuts**, choose **Add shortcut…** and
record a global key combination. **Launch app** can start the program each time
or activate its last-used window and start it if closed. **Send text to app**
inserts text into an editable Windows **Edit** or **RichEdit** field selected
with the KSwitcher crosshair. **Open URL** opens an HTTP or HTTPS address in the
default browser, Chrome, or a browser executable you choose. For Chrome, you can
pick a profile from its standard data folder. Use **Apply** or **Save** to activate the rule.
Custom shortcuts are stored on this PC.
**Українською.** У **Settings → Shortcuts → Custom shortcuts** натисніть
**Add shortcut…** і запишіть глобальну комбінацію клавіш. **Launch app** запускає
програму щоразу або активує її останнє використане вікно й запускає програму,
якщо вона закрита. **Send text to app** вставляє текст у поле Windows **Edit**
або **RichEdit**, вибране прицілом KSwitcher. **Open URL** відкриває адресу HTTP
або HTTPS у типовому браузері, Chrome чи іншому вказаному браузері. Для Chrome
можна вибрати профіль зі стандартної папки даних. Застосуйте зміни кнопкою **Apply**
або **Save**. Власні шорткати зберігаються на цьому ПК.
## Mouse buttons for applications
In **Settings → Mouse**, put the pointer over **Test mouse buttons here** and
@@ -119,7 +139,7 @@ including Mouse, Manage computers and OpenBao. **Apply** keeps the current page
**Save** closes Settings. With pending edits, **Cancel** or closing the window asks whether
to discard them or keep editing. When there are no pending edits, **Close** exits without a prompt.
If saving fails, the window stays open with your edits intact.
Settings displays **No unsaved settings** when the draft matches the saved settings. If **Start with Windows** is enabled, **Save** remains available to recheck the autostart path.
Settings displays **No unsaved settings** when the draft matches the saved settings. **Apply** and **Save** are disabled until you make another edit.
Enable discovery and click **Save** on each PC before looking for peers. Enter the same code and
click **Pair**, then **Apply** or **Save**, on both PCs. Use **Apply** to watch the target and
remaining wait time without closing Settings.
@@ -170,7 +190,7 @@ the task runs in the signed-in user's interactive session, including on battery
With both options enabled, opening the regular `KSwitcher.exe` after exiting a development
build requests administrator approval if needed. Development builds keep their current launch privileges.
Disabling the administrator option restores ordinary per-user startup. Disabling startup stops
future automatic launches. On launch and after clicking **Save** in Settings, KSwitcher checks whether the
future automatic launches. On launch and after committing edits with **Apply** or **Save**, KSwitcher checks whether the
enabled autostart entry still points to its current location. If the previous file is missing and
KSwitcher has the required privileges, it updates the path automatically. If the previous path may
still be in use or the repair requires administrator approval, KSwitcher shows both paths and asks
@@ -1044,6 +1064,16 @@ embedded in KSwitcher.Files.exe.
.\tests\configuration.ps1 # Separate-process settings tests; close KSwitcher first
```
To check snippet suggestions in a WebView2 app, focus a blank editable field and
run `KSwitcherIntegration.exe --snippet-external-editor` without changing the
foreground window. The test types `;`, checks that the popup opens without
stealing focus, dismisses it, and removes the test character. In Dirlume, repeat
in the Command line, the terminal at an idle prompt, and the text editor. Use
`--insert` as the second argument to test Tab insertion in a blank text field.
With a Dirlume build that supports KSwitcher terminal insertion, use
`--terminal-insert` at a blank shell prompt and check that `snippet test`
appears as an editable draft. Clear that draft without submitting it.
`-Test` also checks remote/own input separation, hidden Settings layout and scrolling, and updater
package validation, file preservation and rollback in temporary fixture directories. It does not
replace a running installation. Optional read-only network checks:
+74
View File
@@ -1,5 +1,79 @@
# Latest Windows release
## v0.8.12 — 2026-12-01
**LAN cursor handoff.** The tray and **Settings → Computers** identify the computer and, when known, the key or mouse button holding up the handoff. If Windows still sees an input as held after you release it, choose **Reset held keys and mouse buttons** from the tray menu on that PC. Update both computers to see which input on the other PC is blocking the handoff.
**Українською.** Трей і **Налаштування → Комп’ютери** показують, на якому ПК заблоковано перехід курсора та яка клавіша або кнопка миші його блокує, якщо її вдалося визначити. Якщо Windows продовжує вважати ввід затиснутим після відпускання, виберіть **«Скинути затиснуті клавіші й кнопки миші»** у треї на цьому ПК. Оновіть обидва комп’ютери, щоб бачити, який ввід на іншому ПК блокує перехід.
## v0.8.11 — 2026-11-30
**Open URL** is a new action in **Settings → Shortcuts → Custom shortcuts**. Open an HTTP or HTTPS address in the default browser, Google Chrome, or another browser by picking its executable. Choose a Chrome profile from its standard data folder if needed. The shortcut editor uses a white content area and the same tinted footer style as Settings.
**Українською.** У **Settings → Shortcuts → Custom shortcuts** з’явилася дія **Open URL**. Відкривайте адреси HTTP або HTTPS у типовому браузері, Google Chrome або іншому браузері, вказавши його `.exe`. Для Chrome за потреби виберіть профіль зі стандартної папки даних. Редактор шорткатів має білу область вмісту й тонований футер у стилі Settings.
## v0.8.10 — 2026-11-30
After **Apply** saves your changes, Settings disables **Apply** and **Save** and offers **Close**, including when **Start with Windows** is enabled. A new edit enables the saving controls again.
Application launch actions work through Windows Explorer when KSwitcher runs as administrator. Launched programs open with their executable folder as the working directory.
**Українською.** Після збереження змін через **Apply** у налаштуваннях доступна кнопка **Close**, а **Apply** і **Save** вимкнені навіть за ввімкненого автозапуску Windows. Наступна зміна знову робить кнопки збереження доступними.
Дії запуску програм працюють через Провідник Windows, коли KSwitcher запущено від адміністратора. Робоча папка запущеної програми відповідає папці її виконуваного файлу.
## v0.8.9 — 2026-11-30
- **Custom shortcuts.** Open **Settings → Shortcuts → Custom shortcuts** to add global shortcuts. Launch an executable each time or activate its last-used window and launch it if closed. Select an open program with the KSwitcher crosshair or use **Browse**.
- **Text insertion.** Drag the same crosshair onto an editable Windows **Edit** or **RichEdit** field and enter the text to insert. Multiline fields accept multiline text. Custom shortcuts are saved on this PC.
**Українською.**
- **Власні шорткати.** Відкрийте **Settings → Shortcuts → Custom shortcuts**, щоб додати глобальні комбінації. Шорткат може щоразу запускати програму або активувати її останнє використане вікно й запускати програму, якщо вона закрита. Виберіть відкриту програму прицілом KSwitcher або скористайтеся кнопкою **Browse**.
- **Вставлення тексту.** Перетягніть той самий приціл на доступне для редагування поле Windows **Edit** або **RichEdit** і введіть текст. Багаторядкові поля приймають багаторядковий текст. Власні шорткати зберігаються на цьому ПК.
## v0.8.8 — 2026-11-28
In Lavender, **Change drive**, command menus, panel search and command suggestions use a light lavender background and a contrasting purple outline, 2 pixels thick at 100% scaling.
**Українською.** У Lavender меню **Change drive**, меню команд, пошук панелі й підказки команд мають світло-лавандове тло та контрастну фіолетову рамку завтовшки 2 пікселі за масштабу 100%.
## v0.8.7 — 2026-11-28
In **Change drive** (Alt+F1 or Alt+F2), press **1** for FTP, **2** for SFTP, **3** for SMB or **4** for Recent folders. The scroll bar has its own space so it does not clip the free-space column.
**Українською.** У **Change drive** (Alt+F1 або Alt+F2) клавіші **1**, **2**, **3** і **4** відкривають FTP, SFTP, SMB і нещодавні папки відповідно. Для смуги прокрутки відведено окреме місце, щоб не обрізати значення вільного місця.
## v0.8.6 — 2026-11-28
- **Updater.** Checking for updates requests only the latest stable Gitea release, avoiding timeouts while loading the release history. If the older updater still times out, install this release using the complete portable ZIP.
- **Layout conversion.** Recent text selection can recover after delayed editor selection in apps such as Claude. When several layouts produce the same recent text, KSwitcher prefers the layout used to type it.
- **Files.** Open **Space Analyzer** from **Left** or **Right** to scan in that pane. **Logical size** and **Size on disk** apply to the tree and charts. Local NTFS folder sizes use batched directory reads and parallel traversal.
**Українською.**
- **Оновлення.** KSwitcher запитує в Gitea лише останній стабільний реліз. Це усуває тайм-аут під час завантаження історії релізів. Якщо старий оновлювач і далі не відповідає, встановіть цей реліз із повного портативного ZIP.
- **Перетворення розкладки.** KSwitcher може відновити виділення нещодавнього тексту в редакторах із затримкою виділення, зокрема в Claude. Якщо кілька розкладок дають той самий набраний текст, KSwitcher віддає перевагу розкладці, у якій його набрано.
- **Files.** **Space Analyzer** у меню **Left** або **Right** запускає аналіз у вибраній панелі. **Logical size** і **Size on disk** діють у дереві й на графіках. Підрахунок розміру папок на NTFS використовує пакетне читання й паралельний обхід.
## v0.8.5 — 2026-11-28
- **Snippets in Dirlume.** Type `;` to see matching KSwitcher snippets in the command line, editor, other editable fields and embedded terminal. A compatible Dirlume build accepts a single-line snippet with **Tab** at a supported shell prompt and leaves the command editable. Terminal insertion excludes key actions and pauses.
**Українською.**
- **Сніпети в Dirlume.** Введіть `;`, щоб побачити підказки KSwitcher у командному рядку, редакторі, інших текстових полях і вбудованому терміналі. У сумісній збірці Dirlume клавіша **Tab** вставляє однорядковий сніпет у рядок підтримуваної оболонки й залишає команду доступною для редагування. Термінал не вставляє сніпети з клавіатурними діями або паузами.
## v0.8.4 — 2026-11-27
- **Settings.** Open **Languages → Languages for a chat** in the Settings tree to search for a chat and choose its keyboard layouts. Save changes with **Apply** or **Save**.
- **Trusted LAN clients.** Clients such as Dirlume can ask how to handle individual file conflicts during copy or move. When supported, choose to replace, skip or cancel.
**Українською.**
- **Налаштування.** Відкрийте **Languages → Languages for a chat** у дереві Settings, щоб знайти чат і вибрати його розкладки. Застосуйте зміни кнопкою **Apply** або **Save**.
- **Довірені клієнти LAN.** Клієнти на кшталт Dirlume можуть запитувати, як обробити окремі конфлікти файлів під час копіювання або переміщення. Якщо клієнт підтримує цю можливість, виберіть заміну, пропуск або скасування.
## v0.8.3 — 2026-11-26
- **Files.** Lavender now shows compact path segments with chevrons above both panes. The current folder has a rounded highlight. Click an ancestor to open it, the current folder to edit the path, or an ellipsis to reveal hidden folders.
+1 -1
View File
@@ -1 +1 @@
0726c819b43cd1508c4fa22b717ab13b0da826f5a48bbc3a4b0f10e6418d207a KSwitcher-win-x64.zip
f21c0f10aeb188f688bf4f3cfec8020d9ffbf92d86f15ad09efbb507dcbe7c49 KSwitcher-win-x64.zip
+73 -73
View File
@@ -1,181 +1,181 @@
{
"version": "0.8.3",
"schema": 1,
"files": [
{
"sha256": "134aff7d86cdba13eecf9e32a0556e0267c0900800bd6dc1e9b005729190eb7a",
"path": "KSwitcher.exe",
"size": 3247616
"size": 3311104,
"sha256": "a5454e72ec1dc0acfebd8ed713b8ca9a124cf501ef7ae7ee28e66a865b3e821f"
},
{
"sha256": "7f90f6af18c9ac7f9e0f8255bfd339c49c9ea28e2da88d6b6e3443f6a867a1dd",
"path": "KSwitcher.Config.exe",
"size": 2849792
"size": 2897408,
"sha256": "3695f4c1f02fdf9aa27230b22f855685e028c82402c1d05f1198e01c28e023aa"
},
{
"sha256": "f010f82aba8ace45abf0b90db991804964c1ec18f783a4169add56f478c96344",
"path": "KSwitcher.Screenshot.exe",
"size": 3193344
"size": 3209216,
"sha256": "cc0bb2b9bfab49d1c639a97b6ca55aca1bc502f6ca3cc03525f84ff646b7bfd3"
},
{
"sha256": "caa66e3d8cddd094f1de317fb1a6410d4413f30034cdb61f130d7fcee21004bb",
"path": "KSwitcher.Files.exe",
"size": 6000640
"size": 6039040,
"sha256": "2ccbd71bff0dd09f3f00aa063c33307dcfb7bf94811a9cd5f15213af73499f2a"
},
{
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"path": "WebView2Loader.dll",
"size": 194912
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"path": "terminal/addon-fit.js",
"size": 1521
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"path": "terminal/index.html",
"size": 527
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"path": "terminal/markdown-it.js",
"size": 100786
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2",
"path": "terminal/markdown.html",
"size": 3800
"size": 3800,
"sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2"
},
{
"sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96",
"path": "terminal/markdown.js",
"size": 18721
"size": 18721,
"sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96"
},
{
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"path": "terminal/mermaid.js",
"size": 5537838
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7",
"path": "terminal/terminal.js",
"size": 6627
"size": 6627,
"sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7"
},
{
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"path": "terminal/xterm-LICENSE.txt",
"size": 1261
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"path": "terminal/xterm.css",
"size": 7112
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"path": "terminal/xterm.js",
"size": 488663
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"path": "LICENSE",
"size": 4401
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
},
{
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"path": "json-LICENSE.txt",
"size": 1096
"size": 1096,
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
},
{
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"path": "files-text-license.txt",
"size": 883
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d",
"path": "files-archive-license.txt",
"size": 4990
"size": 4990,
"sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d"
},
{
"sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4",
"path": "files-image-license.txt",
"size": 3044
"size": 3044,
"sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4"
},
{
"sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594",
"path": "files-sftp-license.txt",
"size": 2064
"size": 2064,
"sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594"
},
{
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01",
"path": "README.md",
"size": 105515
"size": 108205,
"sha256": "d9a53cb9190dfde2415df54c131b8bd293efbd627014a4e0976cea717ae855ae"
},
{
"sha256": "917c2f41b3943647fdfafa911d93f72b8c6fb0d08592016ce1a698d256e038bb",
"path": "LAN-PREVIEW.md",
"size": 16722
"size": 17689,
"sha256": "d8418e72fe7d78862bc101fe7df6de44a185a49d6001afee1a20bd8d98cffcd5"
},
{
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"path": "dictionaries/en.txt",
"size": 732485
"size": 732485,
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
},
{
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20566
"size": 20566,
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
},
{
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"path": "dictionaries/README.md",
"size": 2265
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"path": "dictionaries/ru.txt",
"size": 1109134
"size": 1109134,
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
},
{
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"path": "dictionaries/sources.json",
"size": 1280
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"path": "dictionaries/uk.txt",
"size": 940799
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"path": "tools/README.txt",
"size": 993
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
},
{
"sha256": "b6a36bcdc26fc6bb55083e023e2fafb60236e541e9b1b7e598c66816a3089175",
"path": "tools/StayHere.exe",
"size": 133120
"size": 133120,
"sha256": "ad8fa1e781e817f9b04c5148be484d757913941387ffedd4b73fffeb1d119f6a"
},
{
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"path": "tools/StayHere-README.md",
"size": 2796
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
]
],
"schema": 1,
"version": "0.8.12"
}
+3 -3
View File
@@ -14,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,8,3,0
PRODUCTVERSION 0,8,3,0
FILEVERSION 0,8,12,0
PRODUCTVERSION 0,8,12,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -25,7 +25,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.8.3"
VALUE "FileVersion", "0.8.12"
END
END
BLOCK "VarFileInfo"
@@ -0,0 +1,18 @@
LTEXT "", 488, 16, 15, 353, 13, SS_PATHELLIPSIS
LTEXT "", 495, 16, 28, 353, 13, SS_ENDELLIPSIS
CONTROL "&Tree", 502, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 44, 16
COMBOBOX 503, 16, 59, 132, 64, CBS_DROPDOWNLIST | WS_TABSTOP
CONTROL "Vo&lume", 496, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 64, 16
CONTROL "Tree&map", 497, "Button", BS_OWNERDRAW | WS_TABSTOP, 84, 43, 64, 16
CONTROL "S&unburst", 499, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 43, 64, 16
LTEXT "Sunburst items", 501, 171, 43, 201, 16, NOT WS_VISIBLE
LISTBOX 500, 171, 60, 201, 105, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | NOT WS_VISIBLE
CONTROL "", 498, "Static", SS_OWNERDRAW | SS_NOTIFY | WS_TABSTOP | NOT WS_VISIBLE, 16, 60, 353, 105
CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131
LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS
LTEXT "", 491, 12, 184, 1, 1, NOT WS_VISIBLE
CONTROL "S&top", 492, "Button", BS_OWNERDRAW | WS_TABSTOP, 22, 189, 46, 16
CONTROL "St&art", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16
CONTROL "&View", 494, "Button", BS_OWNERDRAW | WS_TABSTOP, 126, 189, 46, 16
CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16
+9 -16
View File
@@ -577,22 +577,15 @@ STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Space Analyzer"
FONT 10, "Consolas"
BEGIN
LTEXT "", 488, 16, 15, 353, 13, SS_PATHELLIPSIS
LTEXT "", 495, 16, 28, 353, 13, SS_ENDELLIPSIS
CONTROL "Vo&lume", 496, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 64, 16
CONTROL "Tree&map", 497, "Button", BS_OWNERDRAW | WS_TABSTOP, 84, 43, 64, 16
CONTROL "S&unburst", 499, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 43, 64, 16
LTEXT "Sunburst items", 501, 171, 43, 201, 16, NOT WS_VISIBLE
LISTBOX 500, 171, 60, 201, 105, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | NOT WS_VISIBLE
CONTROL "", 498, "Static", SS_OWNERDRAW | SS_NOTIFY | WS_TABSTOP | NOT WS_VISIBLE, 16, 60, 353, 105
CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131
LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS
LTEXT "", 491, 12, 184, 1, 1, NOT WS_VISIBLE
CONTROL "S&top", 492, "Button", BS_OWNERDRAW | WS_TABSTOP, 22, 189, 46, 16
CONTROL "St&art", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16
CONTROL "&View", 494, "Button", BS_OWNERDRAW | WS_TABSTOP, 126, 189, 46, 16
CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16
#include "files-space-analyzer-controls.inc"
END
621 DIALOGEX 0, 0, 420, 209
STYLE DS_SETFONT | DS_CONTROL | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
EXSTYLE WS_EX_CONTROLPARENT
FONT 10, "Consolas"
BEGIN
#include "files-space-analyzer-controls.inc"
END
119 DIALOGEX 0, 0, 260, 197
+8 -1
View File
@@ -239,6 +239,13 @@ function Receive-File([string]$Url,[string]$Path,[long]$Limit,[string]$ProgressL
if ($response) { $response.Dispose() }
}
}
function Receive-ReleaseMetadata([string]$Path,[string]$ProgressLabel = '') {
try {
Receive-File 'https://gitea.hrynco.com/api/v1/repos/hrynco/hrynco-kswitcher/releases/latest' $Path 2MB $ProgressLabel
} catch {
throw "Could not check the latest KSwitcher release on Gitea. $($_.Exception.GetBaseException().Message)"
}
}
function Select-Release($Releases,[version]$Current) {
$candidates = @($Releases | Where-Object { !$_.draft -and !$_.prerelease -and (Get-StableVersion $_.tag_name) } |
Sort-Object { Get-StableVersion $_.tag_name } -Descending)
@@ -473,7 +480,7 @@ try {
$ready = [Threading.EventWaitHandle]::OpenExisting($ReadyEvent)
}
$metadata = Join-Path $WorkDirectory 'releases.json'
Receive-File 'https://gitea.hrynco.com/api/v1/repos/hrynco/hrynco-kswitcher/releases?limit=100' $metadata 2MB
Receive-ReleaseMetadata $metadata
$release = Select-Release (Get-Content -LiteralPath $metadata -Raw | ConvertFrom-Json) $current
if (!$release) {
if ($Unattended) { Write-UpdateJournal "No newer stable release is available ($CurrentVersion)." }
+356 -62
View File
@@ -4,6 +4,7 @@
#include "../resources/resource.h"
#include "ocr.h"
#include "lan_clipboard_image.h"
#include "lan_input.h"
#include "lan_files.h"
#include "configuration.h"
#include "google_drive.h"
@@ -45,26 +46,107 @@ GUITHREADINFO snippetGuiInfo(HWND target)
return info;
}
std::optional<RECT> accessibleSnippetCaret(HWND target)
using Microsoft::WRL::ComPtr;
constexpr std::wstring_view terminalSnippetTicketPrefix = L"dirlume-terminal-snippet-v1:";
bool snippetElementClass(IUIAutomationElement *element, std::wstring_view name)
{
BSTR className{};
const bool matches = SUCCEEDED(element->get_CurrentClassName(&className)) && className && className == name;
SysFreeString(className);
return matches;
}
ComPtr<IUIAutomationElement> focusedSnippetElement(IUIAutomation2 *automation, HWND target)
{
using Microsoft::WRL::ComPtr;
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER,
IID_IUIAutomation2, reinterpret_cast<void **>(automation.GetAddressOf()))))
return {};
automation->put_ConnectionTimeout(150);
automation->put_TransactionTimeout(150);
ComPtr<IUIAutomationElement> focused;
if (FAILED(automation->GetFocusedElement(&focused)) || !focused)
return {};
DWORD process{};
GetWindowThreadProcessId(target, &process);
int focusedProcess{};
BOOL password = TRUE;
if (!process || FAILED(focused->get_CurrentProcessId(&focusedProcess)) ||
process != static_cast<DWORD>(focusedProcess) ||
FAILED(focused->get_CurrentIsPassword(&password)) || password)
if (FAILED(focused->get_CurrentIsPassword(&password)) || password ||
!focusedTextBelongsToWindow(automation, focused.Get(), target))
return {};
return focused;
}
ComPtr<IUIAutomation2> snippetAutomation()
{
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&automation))))
return {};
automation->put_ConnectionTimeout(150);
automation->put_TransactionTimeout(150);
return automation;
}
ComPtr<IUIAutomationValuePattern> terminalSnippetInput(IUIAutomation *automation, IUIAutomationElement *focused)
{
// The receiver is a sibling of this terminal's focused xterm input.
ComPtr<IUIAutomationTreeWalker> walker;
ComPtr<IUIAutomationElement> parent, input;
ComPtr<IUIAutomationCondition> condition;
if (FAILED(automation->get_RawViewWalker(&walker)) || !walker ||
FAILED(walker->GetParentElement(focused, &parent)) || !parent)
return {};
VARIANT className{};
className.vt = VT_BSTR;
className.bstrVal = SysAllocString(L"dirlume-terminal-snippet-input");
const auto result = automation->CreatePropertyCondition(UIA_ClassNamePropertyId, className, &condition);
VariantClear(&className);
if (FAILED(result) || !condition ||
FAILED(parent->FindFirst(TreeScope_Children, condition.Get(), &input)) || !input)
return {};
ComPtr<IUIAutomationValuePattern> value;
input->GetCurrentPatternAs(UIA_ValuePatternId, IID_PPV_ARGS(&value));
return value;
}
std::wstring terminalSnippetTicket(IUIAutomationValuePattern *value)
{
if (!value) return {};
BSTR ticket{};
const auto result = value->get_CurrentValue(&ticket);
const std::wstring_view text(ticket ? ticket : L"", SysStringLen(ticket));
auto accepted = SUCCEEDED(result) && text.size() == terminalSnippetTicketPrefix.size() + 36 &&
text.starts_with(terminalSnippetTicketPrefix) ? std::wstring(text) : std::wstring();
SysFreeString(ticket);
return accepted;
}
std::optional<Template> terminalSnippetTemplate(const Snippet &snippet)
{
auto value = parseTemplate(snippet.text);
if (value.text.empty() || value.text.size() > 8192 || !value.actions.empty() ||
std::any_of(value.text.begin(), value.text.end(), [](wchar_t c) {
return c < 0x20 || (c >= 0x7f && c <= 0x9f) || c == 0x2028 || c == 0x2029;
})) return {};
return value;
}
std::optional<SnippetAnchor> accessibleSnippetCaret(HWND target)
{
const auto automation = snippetAutomation();
if (!automation) return {};
const auto focused = focusedSnippetElement(automation.Get(), target);
if (!focused) return {};
// The xterm.js input follows the terminal cursor for IME. Dirlume
// handles replacement in the active shell draft through a separate input.
if (snippetElementClass(focused.Get(), L"xterm-helper-textarea"))
{
RECT cell{};
BOOL offscreen = TRUE;
if (SUCCEEDED(focused->get_CurrentIsOffscreen(&offscreen)) && !offscreen &&
SUCCEEDED(focused->get_CurrentBoundingRectangle(&cell)) && cell.right > cell.left &&
cell.bottom > cell.top)
{
auto ticket = lower(processName(target)) == L"dirlume" ?
terminalSnippetTicket(terminalSnippetInput(automation.Get(), focused.Get()).Get()) : std::wstring();
return SnippetAnchor{{cell.left, cell.top, cell.left, cell.bottom}, true, std::move(ticket)};
}
return {};
}
ComPtr<IUIAutomationTextPattern2> pattern;
ComPtr<IUIAutomationTextRange> range;
BOOL active{};
@@ -121,7 +203,7 @@ std::optional<RECT> accessibleSnippetCaret(HWND target)
}
}
SafeArrayDestroy(rectangles);
if (anchor && anchor->bottom > anchor->top) return anchor;
if (anchor && anchor->bottom > anchor->top) return SnippetAnchor{*anchor};
}
return {};
}
@@ -145,8 +227,10 @@ ULONG_PTR snippetReplayMarker()
}
constexpr int OpenFiles = 25, FilesHotkeyFirst = 0x4B10, FilesHotkeySecond = 0x4B11;
constexpr int ToggleInputProcessing = 26, DonateViaMonobank = 27, OpenHelp = 28, OpenWhatsNew = 29, OpenAbout = 16;
constexpr int ResetHeldInput = 30;
constexpr wchar_t MonobankDonationUrl[] = L"https://send.monobank.ua/jar/88h2TddKfS";
constexpr int ShortcutProbeId = FilesHotkeySecond + 1;
constexpr int FirstCustomShortcut = 0x5000;
constexpr UINT_PTR PauseDrainTimer = 23;
bool shortcutAvailable(HWND window, Hotkey key)
@@ -178,6 +262,30 @@ bool activateFilesWindow()
return true;
}
HWND shortcutAppWindow(const std::wstring &executable, const std::deque<std::pair<HWND, DWORD>> &recent)
{
const auto path = std::filesystem::path(executable).lexically_normal().make_preferred().wstring();
auto matches = [&path](HWND candidate) {
if (!IsWindowVisible(candidate) || (GetWindowLongPtrW(candidate, GWL_EXSTYLE) & WS_EX_TOOLWINDOW)) return false;
const auto image = processImagePath(candidate);
return CompareStringOrdinal(path.c_str(), -1, image.c_str(), -1, TRUE) == CSTR_EQUAL;
};
if (const auto foreground = GetAncestor(GetForegroundWindow(), GA_ROOT); matches(foreground)) return foreground;
for (const auto &[candidate, expectedProcess] : recent)
{
DWORD process{};
if (GetWindowThreadProcessId(candidate, &process) && process == expectedProcess && matches(candidate)) return candidate;
}
struct Search { decltype(matches) &match; HWND result{}; } search{matches};
EnumWindows([](HWND candidate, LPARAM context) -> BOOL {
auto &state = *reinterpret_cast<Search *>(context);
if (!state.match(candidate)) return TRUE;
state.result = candidate;
return FALSE;
}, reinterpret_cast<LPARAM>(&search));
return search.result;
}
std::vector<std::pair<int, std::wstring>> shortcuts(const Settings &s)
{
std::vector<std::pair<int, std::wstring>> out{{Toggle, s.toggle},
@@ -188,6 +296,9 @@ std::vector<std::pair<int, std::wstring>> shortcuts(const Settings &s)
{Screenshot, s.screenshot}};
for (size_t i = 0; i < s.direct.size(); ++i)
out.emplace_back(Direct + (int)i, s.direct[i]);
for (size_t i = 0; i < s.customShortcuts.size(); ++i)
if (s.customShortcuts[i].enabled)
out.emplace_back(FirstCustomShortcut + static_cast<int>(i), s.customShortcuts[i].shortcut);
return out;
}
std::vector<std::wstring> buildSnippetVariants(const std::wstring &trigger, const std::vector<Layout> &layouts)
@@ -660,21 +771,18 @@ class Transaction
}
auto text = select(count) ? copy() : std::wstring{};
diagnosticEvent(L"Selection initial match=" + std::to_wstring(matches(text)) + L" copied=" + diagnosticText(text));
// Chromium editors can apply only part of a burst of Shift+Left events.
// Extend only a verified suffix; never replace a partial or unrelated range.
// The editor may finish applying queued Shift+Left events after copying
// the suffix. Collapse to its right edge before trying the full range again.
if (valid() && !matches(text) && !text.empty() &&
(suffixMatches ? suffixMatches(text) : newlines(wordCandidate).ends_with(newlines(text))) &&
caretSteps(text) < count)
{
const auto missing = count - caretSteps(text);
diagnosticEvent(L"Selection: extending verified suffix by " + std::to_wstring(missing));
for (size_t i = 0; i < missing; ++i)
{
if (!valid() || !chord(VK_LEFT, MOD_SHIFT))
return {};
diagnosticEvent(L"Selection recovery Shift+Left sent=" + std::to_wstring(i + 1) + L" total=" + std::to_wstring(missing));
Sleep(25);
}
diagnosticEvent(L"Selection: reselecting full range after verified suffix");
if (!finishSelection(false))
return {};
Sleep(25);
if (!selectPrevious(count, [&] { return valid(); }, true))
return {};
text = copy();
diagnosticEvent(L"Selection: suffix recovery match=" + std::to_wstring(matches(text)) + L" copied=" + diagnosticText(text));
}
@@ -1041,6 +1149,7 @@ bool App::updateTray(DWORD action)
std::to_wstring(trayInput.paired) + L" PCs connected)";
}
}
if (state == InputState::Active && !trayInputBlock.empty()) tip = trayInputBlock;
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
const bool updated = Shell_NotifyIconW(action, &icon) != FALSE;
if (badge) DestroyIcon(badge);
@@ -1049,6 +1158,7 @@ bool App::updateTray(DWORD action)
void App::refreshTrayInput()
{
refreshTrayInputBlock();
const auto state = lanService ? lanService->inputConnections() : LanInputConnections{};
if (state == trayInput) return;
trayInput = state;
@@ -1060,6 +1170,41 @@ void App::refreshTrayInput()
updateTray(NIM_MODIFY);
}
namespace
{
bool trayNotice(HWND window, const std::wstring &text)
{
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = window;
icon.uID = 1;
icon.uFlags = NIF_INFO;
wcsncpy_s(icon.szInfo, text.c_str(), _TRUNCATE);
wcscpy_s(icon.szInfoTitle, L"KSwitcher");
icon.dwInfoFlags = NIIF_WARNING;
return Shell_NotifyIconW(NIM_MODIFY, &icon) != FALSE;
}
}
void App::refreshTrayInputBlock()
{
auto block = lanService ? lanService->inputBlockText() : std::wstring{};
if (block == trayInputBlock) return;
const bool newlyBlocked = trayInputBlock.empty();
trayInputBlock = std::move(block);
updateTray(NIM_MODIFY);
const auto now = GetTickCount64();
if (newlyBlocked && now >= nextInputBlockNotice)
{
inputBlockNoticeVisible = trayNotice(window, trayInputBlock);
nextInputBlockNotice = now + 4000;
}
else if (inputBlockNoticeVisible)
{
trayNotice(window, {});
inputBlockNoticeVisible = false;
}
}
void App::addTray()
{
if (updateTray(NIM_ADD))
@@ -1128,13 +1273,18 @@ bool App::registerHotkeys(const Settings &s, bool rollback)
return true;
}
void App::startLanService()
{
lanService = std::make_unique<LanService>(data, window, inputState != InputState::Active, [this] {
// Mouse actions may consume a button press before it reaches Windows.
const auto held = std::find_if(mousePresses.begin(), mousePresses.end(), [](const auto &press) { return press.held; });
return held == mousePresses.end() ? 0 : lan::MouseInputKeys[size_t(held - mousePresses.begin())];
});
if (!smoke) lanService->startClients();
}
Bytes App::lanCommand(const Bytes &command)
{
if (!lanService)
{
lanService = std::make_unique<LanService>(data,window,inputState != InputState::Active);
if (!smoke) lanService->startClients();
}
if (!lanService) startLanService();
auto reply = lanService->command(command);
updateLanInputTimer();
if (lanService->takeInputChange()) resetLanInput();
@@ -1151,6 +1301,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();
refreshTrayInputBlock();
}
void App::applySettings(const Settings &requested, const Bytes &supplement)
{
@@ -1485,6 +1636,12 @@ void App::matchSnippets(HWND fg, bool expandExact)
!snippetWordCharacter(layout->at(physicalLayout().code(previous)));
}))
{
if (snippetPopupAnchor.terminal && snippetTarget == fg && snippetPopup &&
IsWindowVisible(snippetPopup) && snippetFocus == snippetGuiInfo(fg).hwndFocus)
{
hideSnippetPopup();
return;
}
queueSnippet(fg, i, sn.trigger.size());
return;
}
@@ -1559,11 +1716,11 @@ void App::showSnippetPopup()
if ((info.rcCaret.left || info.rcCaret.top || anchor.bottom - anchor.top >= 4) &&
snippetCaretInside(anchor, bounds))
{
placeSnippetPopup(anchor);
placeSnippetPopup({anchor});
return;
}
}
if (snippetPopup && IsWindowVisible(snippetPopup) && snippetCaretInside(snippetPopupAnchor, bounds))
if (snippetPopup && IsWindowVisible(snippetPopup) && snippetCaretInside(snippetPopupAnchor.bounds, bounds))
placeSnippetPopup(snippetPopupAnchor);
if (snippetCaretPending) return;
snippetCaretPending = true;
@@ -1572,6 +1729,14 @@ void App::showSnippetPopup()
const auto receiver = window;
enqueue([this, version, target, receiver] {
auto caret = GetForegroundWindow() == target ? accessibleSnippetCaret(target) : std::nullopt;
if (!caret && inputVersion == version && GetForegroundWindow() == target)
{
// A WebView can expose the old, empty field while the keystroke
// that requested suggestions is still reaching its renderer.
Sleep(45);
if (inputVersion == version && GetForegroundWindow() == target)
caret = accessibleSnippetCaret(target);
}
{
std::lock_guard lock(stateMutex);
snippetCaret = caret;
@@ -1579,9 +1744,22 @@ void App::showSnippetPopup()
PostMessageW(receiver, SnippetCaretMessage, static_cast<WPARAM>(version), 0);
});
}
void App::placeSnippetPopup(RECT anchor)
void App::placeSnippetPopup(SnippetAnchor placement)
{
snippetPopupAnchor = anchor;
if (placement.terminal && placement.canInsert())
{
const auto previous = snippetMatches[snippetSelection];
std::erase_if(snippetMatches, [&](size_t index) { return !terminalSnippetTemplate(settings.snippets[index]); });
if (snippetMatches.empty())
{
hideSnippetPopup();
return;
}
const auto selected = std::find(snippetMatches.begin(), snippetMatches.end(), previous);
snippetSelection = selected == snippetMatches.end() ? 0 : static_cast<size_t>(selected - snippetMatches.begin());
}
snippetPopupAnchor = std::move(placement);
const auto &anchor = snippetPopupAnchor.bounds;
if (!snippetPopup)
{
WNDCLASSW cls{};
@@ -1630,24 +1808,83 @@ void App::placeSnippetPopup(RECT anchor)
InvalidateRect(snippetPopup, nullptr, FALSE);
SetTimer(window, SnippetPopupTimer, 100, nullptr);
}
void App::selectSnippet(size_t row)
bool App::selectSnippet(size_t row)
{
if (row >= snippetMatches.size() || !snippetPopupCurrent()) return;
if (!snippetPopupAnchor.canInsert() || row >= snippetMatches.size() || !snippetPopupCurrent()) return false;
const auto index = snippetMatches[row];
const auto length = snippetPrefixLength;
hideSnippetPopup();
std::lock_guard lock(stateMutex);
if (snippetPopupVersion == inputVersion && !busy)
queueSnippet(snippetTarget, index, length, snippetFocus);
if (!snippetPopupCurrent()) return false;
if (!snippetPopupAnchor.terminal)
{
hideSnippetPopup();
return queueSnippet(snippetTarget, index, length, snippetFocus);
}
const auto layout = std::find_if(layouts.begin(), layouts.end(), [&](const auto &item) {
return item.handle == run.layout && item.convertible;
});
if (layout == layouts.end() || run.window != snippetTarget || run.keys.size() < length)
return false;
const auto replacement = terminalSnippetTemplate(settings.snippets[index]);
if (!replacement) return false;
std::wstring prefix;
for (wchar_t key : std::wstring_view(run.keys).substr(run.keys.size() - length))
prefix += layout->at(physicalLayout().code(key));
if (prefix.empty() || prefix.find(L'\0') != prefix.npos) return false;
const auto ticket = snippetPopupAnchor.terminalTicket;
const auto target = snippetTarget;
const auto editor = snippetFocus;
const auto request = wide(DiagnosticJson::array({utf8(ticket), utf8(prefix), utf8(replacement->text),
replacement->text.size() - replacement->suffix.size()}).dump(-1, ' ', true, DiagnosticJson::error_handler_t::replace));
hideSnippetPopup();
run.reset();
const auto version = ++inputVersion;
typingTarget = target;
snippetTyping = true;
busy = true;
enqueue([this, target, editor, version, ticket, request] {
struct Replay
{
HWND window;
~Replay() { PostMessageW(window, ReplayTypingMessage, 0, 0); }
} replay{window};
const auto current = [&] {
return inputVersion == version && GetForegroundWindow() == target && snippetGuiInfo(target).hwndFocus == editor;
};
if (!current()) return;
const auto automation = snippetAutomation();
if (!automation) return;
const auto focused = focusedSnippetElement(automation.Get(), target);
if (!focused || !snippetElementClass(focused.Get(), L"xterm-helper-textarea")) return;
const auto input = terminalSnippetInput(automation.Get(), focused.Get());
if (terminalSnippetTicket(input.Get()) != ticket || !current()) return;
BSTR payload = SysAllocStringLen(request.data(), static_cast<UINT>(request.size()));
if (!payload) return;
const auto sent = input->SetValue(payload);
SysFreeString(payload);
if (FAILED(sent)) return;
// Keep subsequent keystrokes ordered behind the renderer's draft edit.
const auto until = GetTickCount64() + 200;
while (current() && GetTickCount64() < until)
{
const auto reply = terminalSnippetTicket(input.Get());
if (!reply.empty() && reply != ticket) return;
Sleep(10);
}
});
return true;
}
bool App::handleSnippetKey(DWORD vk, UINT mods)
{
if (!snippetPopupAnchor.canInsert() && vk != VK_ESCAPE) return false;
const bool accept = vk == VK_TAB ||
(vk == VK_RETURN && (snippetNavigated || snippetMatches.size() == 1));
(!snippetPopupAnchor.terminal && vk == VK_RETURN && (snippetNavigated || snippetMatches.size() == 1));
if (mods || (!accept && vk != VK_UP && vk != VK_DOWN && vk != VK_ESCAPE) ||
!snippetPopup || !IsWindowVisible(snippetPopup) || !snippetPopupCurrent())
return false;
if (accept) selectSnippet(snippetSelection);
if (accept) return selectSnippet(snippetSelection);
else if (vk == VK_ESCAPE) hideSnippetPopup();
else
{
@@ -1690,7 +1927,7 @@ LRESULT CALLBACK App::snippetPopupProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
const LONG top = static_cast<LONG>(i - first) * app->snippetRowHeight;
RECT row{0, top, bounds.right, top + app->snippetRowHeight};
const bool selected = i == app->snippetSelection;
const bool selected = app->snippetPopupAnchor.canInsert() && i == app->snippetSelection;
if (selected) FillRect(dc, &row, GetSysColorBrush(COLOR_HIGHLIGHT));
SetTextColor(dc, GetSysColor(selected ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT));
row.left += MulDiv(8, dpi, 96);
@@ -1815,7 +2052,7 @@ bool App::handleKeyboard(const KBDLLHOOKSTRUCT &key, bool down, UINT mods)
// from opening on Win-up after we consumed V. 0xE8 is unassigned.
if (mods & (MOD_WIN | MOD_ALT))
chord(0xE8);
PostMessageW(window, WM_HOTKEY, action, 0);
PostMessageW(window, WM_HOTKEY, action, MAKELPARAM(mods, key.vkCode));
}
if (action != 0)
{
@@ -2138,6 +2375,8 @@ LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp)
{
auto &app = *current;
const auto &mouse = *reinterpret_cast<const MSLLHOOKSTRUCT *>(lp);
if ((mouse.flags & LLMHF_INJECTED) && mouse.dwExtraInfo == inputMarker())
return CallNextHookEx(nullptr, code, wp, lp);
// Forwarded mouse events use the same bindings as local events on this PC.
const int button = mouseButton(UINT(wp), HIWORD(mouse.mouseData));
const auto wheelDelta = static_cast<SHORT>(HIWORD(mouse.mouseData));
@@ -2166,10 +2405,8 @@ LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp)
}
if (app.lanService)
{
const bool mouseActionHeld = std::any_of(app.mousePresses.begin(), app.mousePresses.end(),
[](const MousePress &press) { return press.held; });
bool consumed = app.lanService->mouse(UINT(wp), mouse,
!app.busy && !app.suspended && !app.hotkeyCapture && !mouseActionHeld);
!app.busy && !app.suspended && !app.hotkeyCapture);
if (app.lanService->takeInputChange()) app.resetLanInput();
if (consumed) return 1;
}
@@ -3157,6 +3394,15 @@ void App::recognizeEntry(std::wstring id)
}
});
}
void App::clearMousePresses()
{
mousePresses = {};
pendingMouseClicks = {};
KillTimer(window, MouseClickTimer);
for (size_t i = 0; i < mousePresses.size(); ++i) KillTimer(window, FirstMouseVolumeTimer + i);
PostMessageW(window, MouseVolumeReleasedMessage, 0, 0);
}
void App::toggleInputProcessing()
{
if (inputState == InputState::Pausing) return;
@@ -3170,10 +3416,7 @@ void App::toggleInputProcessing()
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);
clearMousePresses();
hideSnippetPopup();
if (lanService) lanService->setInputPaused(true);
KillTimer(window, 8);
@@ -3226,6 +3469,8 @@ void App::trayMenu()
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_STRING, ResetHeldInput, PRIMARYLANGID(GetThreadUILanguage()) == LANG_UKRAINIAN ?
L"Скинути затиснуті клавіші й кнопки миші" : L"Reset held keys and mouse buttons");
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
AppendMenuW(menu, MF_STRING, 10, L"Clipboard &history");
AppendMenuW(menu, MF_STRING, 24, L"&Capture screen region…");
@@ -3303,6 +3548,14 @@ void App::trayMenu()
case ToggleInputProcessing:
toggleInputProcessing();
break;
case ResetHeldInput:
if (lan::resetWindowsHeldInput())
{
if (lanService) lanService->forgetHeldInput();
clearMousePresses();
}
else report(L"Windows could not release all held keys or mouse buttons.");
break;
case OpenFiles:
dispatch(OpenFiles);
break;
@@ -3533,6 +3786,42 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
case WM_HOTKEY:
if (app->inputState != InputState::Active || wp == ShortcutProbeId) return 0;
if (wp >= FirstCustomShortcut)
{
const size_t index = wp - FirstCustomShortcut;
if (app->installingUpdate || app->busy || app->hotkeyCapture || index >= app->settings.customShortcuts.size()) return 0;
const auto &rule = app->settings.customShortcuts[index];
if (!rule.enabled || Hotkey::parse(rule.shortcut) != Hotkey{LOWORD(lp), HIWORD(lp)}) return 0;
if (rule.action == CustomShortcutAction::OpenUrl)
{
if (!openShortcutUrl(rule))
app->report(L"Could not open the URL for " + rule.name + L". Check the configured browser and profile.");
return 0;
}
if (rule.action == CustomShortcutAction::SendText)
{
const auto target = shortcutAppWindow(rule.executable, app->recentForegroundWindows);
const auto control = findShortcutTextControl(target, rule.controlClass, rule.controlId);
if (control && rule.text.find_first_of(L"\r\n") != std::wstring::npos &&
!(GetWindowLongPtrW(control, GWL_STYLE) & ES_MULTILINE))
app->report(L"The target field for " + rule.name + L" accepts a single line of text.");
else if (!control || !SendMessageTimeoutW(control, EM_REPLACESEL, TRUE, reinterpret_cast<LPARAM>(rule.text.c_str()),
SMTO_ABORTIFHUNG | SMTO_BLOCK | SMTO_ERRORONEXIT, 300, nullptr))
app->report(L"Could not insert text for " + rule.name + L". Check that its target field is open.");
return 0;
}
if (!rule.newInstance)
{
if (const auto target = shortcutAppWindow(rule.executable, app->recentForegroundWindows))
{
if (IsIconic(target)) ShowWindowAsync(target, SW_RESTORE);
if (!activateWindow(target)) app->report(L"Could not activate the window for " + rule.name + L".");
return 0;
}
}
if (!launchThroughExplorer(rule.executable)) app->report(L"Could not launch the program for " + rule.name + L".");
return 0;
}
if (app->filesHotkeyId && wp == static_cast<WPARAM>(app->filesHotkeyId))
{
if(!activateFilesWindow()) app->dispatch(OpenFiles);
@@ -3603,13 +3892,13 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
app->showSnippetPopup();
return 0;
}
std::optional<RECT> caret;
std::optional<SnippetAnchor> caret;
{
std::lock_guard lock(app->stateMutex);
caret = app->snippetCaret;
}
RECT bounds{};
if (caret && GetWindowRect(app->snippetTarget, &bounds) && snippetCaretInside(*caret, bounds))
if (caret && GetWindowRect(app->snippetTarget, &bounds) && snippetCaretInside(caret->bounds, bounds))
{
app->placeSnippetPopup(*caret);
return 0;
@@ -3624,14 +3913,8 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case ErrorMessage:
{
std::unique_ptr<std::wstring> text((std::wstring *)lp);
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = hwnd;
icon.uID = 1;
icon.uFlags = NIF_INFO;
wcsncpy_s(icon.szInfo, text->c_str(), _TRUNCATE);
wcscpy_s(icon.szInfoTitle, L"KSwitcher");
icon.dwInfoFlags = NIIF_WARNING;
Shell_NotifyIconW(NIM_MODIFY, &icon);
app->inputBlockNoticeVisible = false;
trayNotice(hwnd, *text);
return 0;
}
case LanInputStatusMessage:
@@ -3884,7 +4167,7 @@ int App::execute()
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(); }
try { startLanService(); }
catch (const std::exception &e) { report(L"LAN module: " + wide(e.what())); }
updateLanInputTimer();
refreshTrayInput();
@@ -3906,6 +4189,16 @@ int App::execute()
try { notificationRegistration = startScreenshotNotificationRegistration(); }
catch(const std::exception &e) { log(L"Screenshot notification registration: "+wide(e.what())); }
auto screenshotActivation=startScreenshotActivationListener();
const auto foregroundHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr,
[](HWINEVENTHOOK, DWORD, HWND target, LONG, LONG, DWORD, DWORD) {
target = GetAncestor(target, GA_ROOT);
DWORD process{};
if (!current || !GetWindowThreadProcessId(target, &process)) return;
auto &recent = current->recentForegroundWindows;
std::erase_if(recent, [target](const auto &entry) { return entry.first == target || !IsWindow(entry.first); });
recent.emplace_front(target, process);
if (recent.size() > 256) recent.pop_back();
}, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
if (keyboardHook && mouseHook) showWhatsNewAfterUpdate();
MSG msg;
while (GetMessageW(&msg, nullptr, 0, 0) > 0)
@@ -3931,6 +4224,7 @@ int App::execute()
DispatchMessageW(&msg);
}
if(screenshotActivation) CoRevokeClassObject(screenshotActivation);
if (foregroundHook) UnhookWinEvent(foregroundHook);
return (int)msg.wParam;
}
} // namespace ks
+18 -4
View File
@@ -23,6 +23,13 @@ inline constexpr int Toggle = 1, Case = 2, Translit = 3, Undo = 4, ShowHistory =
inline constexpr UINT AutoCorrectMessage = WM_APP + 6;
inline constexpr UINT ReplayTypingMessage = WM_APP + 30;
inline constexpr UINT CaptureHotkeyMessage = WM_APP + 5;
struct SnippetAnchor
{
RECT bounds{};
bool terminal{};
std::wstring terminalTicket;
bool canInsert() const { return !terminal || !terminalTicket.empty(); }
};
struct LastTransform
{
HWND window{};
@@ -119,6 +126,7 @@ class App
void toggleInputProcessing();
void updateLanInputTimer();
void pollLanInput();
void startLanService();
struct MousePress
{
HWND target{};
@@ -173,15 +181,21 @@ class App
bool trayRetryPending{};
LanInputConnections trayInput;
bool trayInputPulse{};
std::wstring trayInputBlock;
ULONGLONG nextInputBlockNotice{};
bool inputBlockNoticeVisible{};
HICON trayBaseIcon(int width, int height) const;
bool updateTray(DWORD action);
void refreshTrayInput();
void refreshTrayInputBlock();
void clearMousePresses();
uint64_t transformAttempt{}, previousAttemptVersion{};
std::atomic<uint64_t> activeTransformAttempt{};
ULONGLONG previousAttemptAt{};
HWND previousAttemptWindow{};
int previousAttemptCommand{}, repeatAttempts{};
std::vector<std::pair<int, Hotkey>> hookBindings;
std::deque<std::pair<HWND, DWORD>> recentForegroundWindows;
std::vector<Hotkey> availableBeforePause;
Hotkey registeredFilesHotkey{};
int filesHotkeyId{};
@@ -203,20 +217,20 @@ class App
bool snippetNavigated{};
int snippetRowHeight{};
UINT snippetDpi{96};
RECT snippetPopupAnchor{};
SnippetAnchor snippetPopupAnchor{};
bool snippetCaretPending{};
std::optional<RECT> snippetCaret;
std::optional<SnippetAnchor> snippetCaret;
std::vector<std::pair<std::wstring, std::vector<std::wstring>>> snippetTriggers;
std::vector<size_t> snippetMatches;
std::array<bool, 256> snippetKeys{};
void matchSnippets(HWND, bool expandExact);
bool queueSnippet(HWND, size_t index, size_t length, HWND editor = nullptr);
void showSnippetPopup();
void placeSnippetPopup(RECT);
void placeSnippetPopup(SnippetAnchor);
void hideSnippetPopup();
bool snippetPopupCurrent() const;
bool handleSnippetKey(DWORD, UINT);
void selectSnippet(size_t);
bool selectSnippet(size_t);
static LRESULT CALLBACK snippetPopupProc(HWND, UINT, WPARAM, LPARAM);
std::vector<INPUT> deferredTyping;
bool beginTypingDeferral(HWND, uint64_t, bool snippet = false);
+16 -6
View File
@@ -645,15 +645,25 @@ int Run::match(const std::wstring &text, const std::vector<Layout> &layouts, con
{
if (text.size() != keys.size() || overflow)
return -1;
const auto normalized = lower(text);
int fallback = -1;
for (int i = 0; i < (int)layouts.size(); ++i)
if (layouts[i].convertible)
{
const auto &candidate = layouts[i];
const bool tracked = layout && candidate.handle == layout;
if (!candidate.convertible || (!tracked && fallback >= 0))
continue;
std::wstring expected;
for (wchar_t c : keys)
expected += c == L' ' ? L' ' : candidate.at(physical.code(c));
if (lower(expected) == normalized)
{
std::wstring expected;
for (wchar_t c : keys)
expected += c == L' ' ? L' ' : layouts[i].at(physical.code(c));
if (lower(expected) == lower(text))
if (tracked)
return i;
fallback = i;
}
return -1;
}
return fallback;
}
} // namespace ks
+16
View File
@@ -82,6 +82,21 @@ struct MouseAction
int volumeStep = DefaultMouseVolumeStep;
bool operator==(const MouseAction &) const = default;
};
enum class CustomShortcutAction { LaunchApp, SendText, OpenUrl };
enum class ShortcutBrowser { Default, Chrome, Other };
struct CustomShortcut
{
std::wstring name, shortcut, executable;
bool enabled = true;
bool newInstance = false;
CustomShortcutAction action = CustomShortcutAction::LaunchApp;
std::wstring controlClass, text;
int controlId = 0;
std::wstring url;
ShortcutBrowser browser = ShortcutBrowser::Default;
std::wstring chromeProfile;
bool operator==(const CustomShortcut &) const = default;
};
struct Settings
{
bool recent = true, switchLayout = true, history = true, autostart = false, awake = false;
@@ -109,6 +124,7 @@ struct Settings
translit = L"Ctrl+Alt+Shift+T", undo = L"Ctrl+Alt+Shift+Z", clipboard = L"Win+V",
screenshot = L"Win+Shift+S";
std::optional<std::wstring> filesHotkey;
std::vector<CustomShortcut> customShortcuts;
std::vector<std::wstring> cycle, direct, directIds;
// Exact application + visible chat name; an absent entry uses the global cycle.
std::map<std::wstring, std::vector<std::wstring>> chatCycles;
+223
View File
@@ -0,0 +1,223 @@
#include "files_folder_size.h"
#include <windows.h>
#include <algorithm>
#include <array>
#include <condition_variable>
#include <cstddef>
#include <cstring>
#include <exception>
#include <mutex>
#include <string_view>
#include <thread>
#include <vector>
namespace ks::files
{
namespace
{
namespace fs=std::filesystem;
struct Directory
{
HANDLE handle;
explicit Directory(const fs::path &path):handle(CreateFileW(path.c_str(),
FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)) {}
~Directory() {if(handle!=INVALID_HANDLE_VALUE) CloseHandle(handle);}
Directory(const Directory &)=delete;
Directory &operator=(const Directory &)=delete;
};
uint64_t directoryId(const BY_HANDLE_FILE_INFORMATION &info)
{
return (uint64_t(info.nFileIndexHigh)<<32)|info.nFileIndexLow;
}
bool ordinaryDirectory(const BY_HANDLE_FILE_INFORMATION &info)
{
return (info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))==
FILE_ATTRIBUTE_DIRECTORY;
}
struct ScanDirectory
{
fs::path path;
uint64_t id;
};
constexpr size_t pageBytes=64*1024;
using DirectoryPage=std::array<std::byte,pageBytes>;
// Directory records are variable length. Read the fixed fields and name only
// after checking that both stay within the current record.
bool readPage(const DirectoryPage &page,const fs::path &parent,FolderSize &size,
std::vector<ScanDirectory> &children)
{
constexpr size_t nameOffset=offsetof(FILE_ID_EXTD_DIR_INFO,FileName);
std::wstring name;
for(size_t offset=0;offset<page.size();)
{
const auto remaining=page.size()-offset;
if(remaining<nameOffset) return false;
FILE_ID_EXTD_DIR_INFO entry{};
std::memcpy(&entry,page.data()+offset,nameOffset);
const size_t next=entry.NextEntryOffset;
const size_t recordBytes=next?next:remaining;
const size_t nameBytes=entry.FileNameLength;
if(recordBytes>remaining || recordBytes<nameOffset || next%8 ||
nameBytes%sizeof(wchar_t) || nameBytes>recordBytes-nameOffset || entry.EndOfFile.QuadPart<0)
return false;
if(!(entry.FileAttributes&FILE_ATTRIBUTE_REPARSE_POINT))
{
name.resize(nameBytes/sizeof(wchar_t));
std::memcpy(name.data(),page.data()+offset+nameOffset,nameBytes);
if(name!=L"." && name!=L"..")
{
if(name.empty() || name.find_first_of(L"\\/:")!=name.npos || name.find(L'\0')!=name.npos)
size.partial=true;
else if(entry.FileAttributes&FILE_ATTRIBUTE_DIRECTORY)
{
uint64_t id{};
std::memcpy(&id,entry.FileId.Identifier,sizeof(id));
children.push_back({parent/name,id});
}
else size.add(static_cast<uint64_t>(entry.EndOfFile.QuadPart));
}
}
if(!next) return true;
offset+=next;
}
return false;
}
template<class PublishPage>
DWORD enumerate(const ScanDirectory &job,DWORD volume,DirectoryPage &page,
std::stop_token stop,const PublishPage &publish)
{
Directory directory(job.path);
if(directory.handle==INVALID_HANDLE_VALUE) return GetLastError();
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(directory.handle,&info)) return GetLastError();
if(!ordinaryDirectory(info) || info.dwVolumeSerialNumber!=volume || directoryId(info)!=job.id)
return ERROR_PATH_NOT_FOUND;
while(!stop.stop_requested())
{
if(!GetFileInformationByHandleEx(directory.handle,FileIdExtdDirectoryInfo,
page.data(),static_cast<DWORD>(page.size())))
{
const auto error=GetLastError();
return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error;
}
FolderSize size;
std::vector<ScanDirectory> children;
if(!readPage(page,job.path,size,children)) return ERROR_INVALID_DATA;
publish(size,children);
}
return ERROR_CANCELLED;
}
bool unsupported(DWORD error)
{
return error==ERROR_INVALID_FUNCTION || error==ERROR_INVALID_PARAMETER || error==ERROR_NOT_SUPPORTED;
}
}
std::optional<FolderSize> measureNtfsFolder(const fs::path &root,std::stop_token stop)
{
if(stop.stop_requested()) return FolderSize{};
const auto drive=GetDriveTypeW(root.root_path().c_str());
if(drive!=DRIVE_FIXED && drive!=DRIVE_REMOVABLE) return std::nullopt;
// The extended path also lets descendants cross MAX_PATH while scanning.
const auto normalized=root.lexically_normal();
const fs::path scanPath=L"\\\\?\\"+normalized.native();
Directory directory(scanPath);
if(directory.handle==INVALID_HANDLE_VALUE) return std::nullopt;
wchar_t filesystem[32]{};
if(!GetVolumeInformationByHandleW(directory.handle,nullptr,0,nullptr,nullptr,nullptr,
filesystem,static_cast<DWORD>(std::size(filesystem))) || std::wstring_view(filesystem)!=L"NTFS")
return std::nullopt;
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(directory.handle,&info)) return std::nullopt;
if(!ordinaryDirectory(info)) return std::nullopt;
// Dirlume Space Analyzer (space_analyzer/windows_walk.rs) reads NTFS
// directory pages with a smaller worker pool on seek-sensitive storage.
constexpr DWORD noSeekPenalty=0x04;
FILE_STORAGE_INFO storage{};
const unsigned limit=GetFileInformationByHandleEx(directory.handle,FileStorageInfo,&storage,sizeof(storage)) &&
(storage.Flags&noSeekPenalty)?16:4;
const unsigned workers=std::min(limit,std::max(1u,std::thread::hardware_concurrency()));
std::stop_source scanning;
std::stop_callback cancel(stop,[&]{scanning.request_stop();});
const auto scanStop=scanning.get_token();
std::mutex mutex;
std::condition_variable_any changed;
std::vector<ScanDirectory> pending{{scanPath,directoryId(info)}};
unsigned active{};
bool fallback{};
FolderSize result;
std::exception_ptr failure;
const auto work=[&]
{
try
{
alignas(FILE_ID_EXTD_DIR_INFO) DirectoryPage page;
for(;;)
{
std::unique_lock lock(mutex);
changed.wait(lock,scanStop,[&]{return !pending.empty() || !active;});
if(scanStop.stop_requested() || pending.empty()) return;
auto job=std::move(pending.back());
pending.pop_back();
++active;
lock.unlock();
bool readPage=false;
const auto error=enumerate(job,info.dwVolumeSerialNumber,page,scanStop,
[&](FolderSize size,std::vector<ScanDirectory> &children)
{
readPage=true;
std::lock_guard publishLock(mutex);
result.add(size.bytes);
result.partial|=size.partial;
for(auto &child:children) pending.push_back(std::move(child));
if(!children.empty()) changed.notify_all();
});
lock.lock();
--active;
if(unsupported(error) ||
(error!=ERROR_SUCCESS && error!=ERROR_CANCELLED && job.path==scanPath && !readPage))
{
fallback=true;
scanning.request_stop();
}
else if(error!=ERROR_SUCCESS) result.partial=true;
if(!active) changed.notify_all();
}
}
catch(...)
{
std::lock_guard lock(mutex);
failure=std::current_exception();
scanning.request_stop();
}
};
std::vector<std::jthread> pool;
pool.reserve(workers-1);
try
{
for(unsigned worker=1;worker<workers;++worker) pool.emplace_back(work);
}
catch(const std::system_error &)
{
// The workers already started can finish the scan.
}
work();
for(auto &worker:pool) worker.join();
if(failure) std::rethrow_exception(failure);
if(fallback) return std::nullopt;
return result;
}
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <optional>
#include <stop_token>
namespace ks::files
{
struct FolderSize
{
uint64_t bytes{};
bool partial{}, failed{}, previous{};
void add(uint64_t amount)
{
if(amount>UINT64_MAX-bytes)
{
bytes=UINT64_MAX;
partial=true;
}
else bytes+=amount;
}
};
// No result means the caller should use its ordinary directory listing.
std::optional<FolderSize> measureNtfsFolder(const std::filesystem::path &,std::stop_token);
}
+3 -2
View File
@@ -12,6 +12,7 @@ constexpr struct
L"Press F1 on a menu item for its topic. Commands → Keyboard shortcuts lists the active scheme and lets you assign extra bindings."},
{L"Locations and navigation",L"folder path history breadcrumbs drives recent bookmark directory unc",
L"Use the breadcrumb in a local or remote pane to jump to an ancestor. The folder history keeps earlier locations for that pane. Choose Recent folders in Change drive to see recent locations in that panel. Enter opens the selected folder, Delete removes it from recent folders, and Esc restores the previous folder.\r\n\r\n"
L"In Change drive, press 1 for FTP, 2 for SFTP, 3 for SMB, or 4 for Recent folders. Use the digit shown beside a LAN drive or Wake action.\r\n\r\n"
L"Folder shortcuts open frequently used locations. In the default scheme Ctrl+0–9 recalls a digit and Ctrl+Shift+0–9 adds the current folder."},
{L"Find files",L"search filter mask results alt f7 paths subfolders",
L"Find files searches from the active folder, including subfolders. Supply a filename mask such as *.md. The results show their locations and can be opened or used in file operations.\r\n\r\n"
@@ -26,8 +27,8 @@ constexpr struct
L"Open a ZIP or 7z archive from a local pane to browse its entries. Copy entries out to extract them. Back out through the parent entry or Esc.\r\n\r\n"
L"Use Pack files to create or update a ZIP or 7z archive. Review the destination, compression and conflict choices before saving."},
{L"Space Analyzer",L"storage folder size allocation disk tree treemap sunburst",
L"Open Space Analyzer from Commands for a local folder. The tree and charts show which folders consume space. Select an item to inspect its contribution and choose the display you need.\r\n\r\n"
L"Logical size describes file data. Allocated size describes disk allocation where it can be measured."},
L"Open Space Analyzer from the Left or Right menu to scan a local folder in its pane. Use Close or Esc to return to the file list. The Commands menu opens a separate analyzer window.\r\n\r\n"
L"Choose Logical size for file data or Size on disk for measured disk allocation. The selected metric is used in Tree, Treemap and Sunburst."},
{L"Properties and locking processes",L"context menu windows owner attributes filesystem locks handle",
L"Properties shows available file details and Windows attributes. The Windows context menu exposes actions supplied by the file type and the operating system.\r\n\r\n"
L"Use Locking processes for selected local items to see processes with open handles. Save any work in the owning program before closing it."},
+29 -18
View File
@@ -307,7 +307,8 @@ INT_PTR lavenderDialogColors(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return reinterpret_cast<INT_PTR>(GetStockObject(DC_BRUSH));
}
RECT paintLavenderDialogFrame(HWND dialog,HDC dc,RECT client,const wchar_t *title,const wchar_t *hints=nullptr)
RECT paintLavenderDialogFrame(HWND dialog,HDC dc,RECT client,const wchar_t *title,
const wchar_t *hints=nullptr,bool popup=false)
{
using namespace lavender;
const LavenderMetrics metrics(dialog);
@@ -315,30 +316,35 @@ RECT paintLavenderDialogFrame(HWND dialog,HDC dc,RECT client,const wchar_t *titl
const bool operation=isLavenderFileOperation(dialog);
const auto edge=dialogEdge(dialog);
LONG headerBottom=client.top+metrics.px(operationHeaderHeight);
if(operation)
if(operation || popup)
{
for(auto control=GetWindow(dialog,GW_CHILD);control;control=GetWindow(control,GW_HWNDNEXT))
{
if(!IsWindowVisible(control)) continue;
RECT bounds{};
GetWindowRect(control,&bounds);
MapWindowPoints(nullptr,dialog,reinterpret_cast<POINT*>(&bounds),2);
headerBottom=std::min(headerBottom,bounds.top);
}
rounded(dc,client,metrics.px(9),edge,edge);
const int stroke=metrics.px(2);
auto inner=client;
InflateRect(&inner,-stroke,-stroke);
const int diameter=metrics.px(14);
const auto clip=CreateRoundRectRgn(inner.left,inner.top,inner.right+1,inner.bottom+1,diameter,diameter);
const auto saved=SaveDC(dc);
if(clip && saved)
if(popup)
rounded(dc,inner,metrics.px(7),operationSurface,operationSurface);
else
{
ExtSelectClipRgn(dc,clip,RGN_AND);
fill(dc,{inner.left,std::max(inner.top,headerBottom),inner.right,inner.bottom},operationSurface);
for(auto control=GetWindow(dialog,GW_CHILD);control;control=GetWindow(control,GW_HWNDNEXT))
{
if(!IsWindowVisible(control)) continue;
RECT bounds{};
GetWindowRect(control,&bounds);
MapWindowPoints(nullptr,dialog,reinterpret_cast<POINT*>(&bounds),2);
headerBottom=std::min(headerBottom,bounds.top);
}
const int diameter=metrics.px(14);
const auto clip=CreateRoundRectRgn(inner.left,inner.top,inner.right+1,inner.bottom+1,diameter,diameter);
const auto saved=SaveDC(dc);
if(clip && saved)
{
ExtSelectClipRgn(dc,clip,RGN_AND);
fill(dc,{inner.left,std::max(inner.top,headerBottom),inner.right,inner.bottom},operationSurface);
}
if(saved) RestoreDC(dc,saved);
if(clip) DeleteObject(clip);
}
if(saved) RestoreDC(dc,saved);
if(clip) DeleteObject(clip);
}
else rounded(dc,client,metrics.px(9),surface,line);
auto content=client;
@@ -357,3 +363,8 @@ RECT paintLavenderDialogFrame(HWND dialog,HDC dc,RECT client,const wchar_t *titl
if(hints) text(dc,{content.left,client.bottom-metrics.px(21),content.right,client.bottom},hints,muted,DT_CENTER);
return content;
}
void paintLavenderPopupFrame(HWND popup,HDC dc,RECT bounds,const wchar_t *title)
{
paintLavenderDialogFrame(popup,dc,bounds,title,nullptr,true);
}
+67 -38
View File
@@ -40,6 +40,7 @@
#include <libssh2.h>
#include <libssh2_sftp.h>
#include "files_terminal.h"
#include "files_folder_size.h"
#include "files_archive.h"
#include "files_git_changes.h"
#include "files_compare_text.h"
@@ -309,17 +310,7 @@ DWORD readElevatedFolder(const ElevatedHelper &session,const fs::path &directory
}
return stop.stop_requested()?ERROR_CANCELLED:ERROR_TIMEOUT;
}
struct FolderSize
{
uint64_t bytes{};
bool partial{}, failed{}, previous{};
void add(uint64_t amount)
{
if(amount>UINT64_MAX-bytes) partial=true;
else bytes+=amount;
}
};
using ks::files::FolderSize;
using FolderSizes=std::map<fs::path,FolderSize>;
constexpr ULONGLONG folderSpinnerDelay=2000;
@@ -808,6 +799,11 @@ std::wstring panelCaption(const Panel &panel)
Panel panels[2];
HWND quickViewWindow{};
HWND spacePaneWindow{};
int spacePaneSide=-1;
void closeSpacePane(HWND owner,bool restorePane=true);
void toggleSpacePane(HWND owner,int side);
void focusSpacePane();
HWND quickImageWindow{};
bool quickViewDisplaysImage{};
int quickViewSource{};
@@ -929,7 +925,6 @@ ks::files::InlineListAction driveWakeAction(driveWakeLabel);
std::vector<DriveQuery> driveQueries;
std::map<LRESULT,DriveChoice> remoteDriveRows;
std::map<std::pair<std::string,std::optional<fs::path>>,wchar_t> driveDigits;
constexpr wchar_t ftpDriveDigit=L'1';
constexpr UINT_PTR driveQueryTimer=3;
ULONGLONG nextDriveRefresh{},driveRefreshDeadline{};
int drivePickerWidth{};
@@ -1714,6 +1709,7 @@ void swapPanels(HWND window)
std::swap(panels[0],panels[1]);
active=1-active;
if(quickViewWindow) quickViewSource=1-quickViewSource;
if(spacePaneWindow) spacePaneSide=1-spacePaneSide;
if(sshPrompt) sshPrompt->panel=1-sshPrompt->panel;
for(auto &command:terminalCommands)
if(command.panel>=0) command.panel=1-command.panel;
@@ -1829,7 +1825,7 @@ void layout(HWND window,bool activeOnly)
place(panels[i].path,x+inset,panelTop,std::max(0,end-x-2*inset),pathHeight);
const int headingHeight=detailedPanel(panels[i])?rowHeight:0;
const int listWidth=std::max(0,end-x-(lavender?2*inset:panelMargin+3)-scrollBarWidth(panels[i].list));
const bool panelVisible=!gitMode && !terminalVisible && (!quickViewWindow || i==quickViewSource);
const bool panelVisible=!gitMode && !terminalVisible && i!=spacePaneSide && (!quickViewWindow || i==quickViewSource);
ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE);
ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE);
SendMessageW(panels[i].selectionSummary,WM_SETFONT,panelFont,FALSE);
@@ -1921,6 +1917,15 @@ void layout(HWND window,bool activeOnly)
ShowWindow(preview,!gitMode && !terminalVisible && current?SW_SHOWNA:SW_HIDE);
}
}
if(spacePaneWindow)
{
const int left=spacePaneSide?middle+2:0;
const int right=spacePaneSide?width:middle-2;
const int bottom=panelBottom+summaryHeight+textHeight+detailsInset;
SetWindowPos(spacePaneWindow,nullptr,left+panelMargin,pathTop,std::max(0,right-left-2*panelMargin),
std::max(0,bottom-pathTop),SWP_NOZORDER|SWP_NOACTIVATE);
ShowWindow(spacePaneWindow,!gitMode && !terminalVisible?SW_SHOWNA:SW_HIDE);
}
if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window);
layoutGitChanges(window);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
@@ -2012,6 +2017,11 @@ void invalidatePanelCursorChange(HWND list,LRESULT previous)
void activatePanel(int index)
{
if(index==spacePaneSide)
{
focusSpacePane();
return;
}
if(quickViewWindow && index!=quickViewSource) return;
const auto previous=active;
active=index;
@@ -3862,7 +3872,7 @@ bool queueFolderMeasurements(Panel &panel,const std::vector<fs::path> &folders,b
const auto stop=job->stop.get_token();
try
{
const auto measure=[&](const auto &listDirectory)
const auto measure=[&](const auto &listDirectory,bool local=false)
{
for(;;)
{
@@ -3882,7 +3892,8 @@ bool queueFolderMeasurements(Panel &panel,const std::vector<fs::path> &folders,b
job->started=GetTickCount64();
}
}
const auto size=measureFolder(folder,stop,listDirectory);
auto native=local?ks::files::measureNtfsFolder(folder,stop):std::nullopt;
const auto size=native?*native:measureFolder(folder,stop,listDirectory);
if(stop.stop_requested()) continue;
std::lock_guard lock(job->mutex);
job->completed.emplace(folder,size);
@@ -3903,7 +3914,7 @@ bool queueFolderMeasurements(Panel &panel,const std::vector<fs::path> &folders,b
measure([&](const fs::path &directory,const FileVisitor &visit)
{
return listMeasuredDirectory(host,directory,visit,stop);
});
},!peer);
}
}
catch(const std::exception &)
@@ -4085,16 +4096,23 @@ void runActivePeerAction(HWND owner,bool update)
(update?L"Requesting a KSwitcher update on ":L"Requesting hibernation for ")+peer.name+L"...");
}
constexpr std::array driveSourceLabels{L"FTP",L"SFTP",L"SMB",L"Recent folders"};
constexpr std::wstring_view driveShortcutDigits=L"1234567890";
LRESULT ftpDriveRow() {return lanDrivePicker?-1:static_cast<LRESULT>(drivePaths.size())+1;}
LRESULT sftpDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;}
LRESULT smbDriveRow() {return lanDrivePicker?-1:sftpDriveRow()+1;}
LRESULT recentDriveRow() {return lanDrivePicker?-1:smbDriveRow()+1;}
LRESULT lanHeaderRow() {return recentDriveRow()+1;}
bool builtInDriveSource(LRESULT row)
{
return !lanDrivePicker && row>=ftpDriveRow() && row<lanHeaderRow();
}
bool driveSourceRow(LRESULT row)
{
return row>=0 && (row<static_cast<LRESULT>(drivePaths.size()) || row==ftpDriveRow() ||
row==sftpDriveRow() || row==smbDriveRow() || row==recentDriveRow());
return (row>=0 && row<static_cast<LRESULT>(drivePaths.size())) || builtInDriveSource(row);
}
bool panelItemPropertiesAvailable(const Panel &panel);
@@ -4143,7 +4161,8 @@ void selectDrive()
if(menuIndex==0 || menuIndex==4)
{
const int index=menuIndex==4;
if(row>4) panelViewAction(owner,panels[index],static_cast<int>(row)-5);
if(row>5) panelViewAction(owner,panels[index],static_cast<int>(row)-6);
else if(row==5) toggleSpacePane(owner,index);
else if(row==4) chooseDrive(index);
else setMode(index,static_cast<PanelMode>(row));
}
@@ -4279,12 +4298,17 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
{ return path.native().front()==key; });
if(disk!=drivePaths.end()) row=disk-drivePaths.begin();
}
else if(key==ftpDriveDigit) row=ftpDriveRow();
else if(key>=L'0' && key<=L'9')
{
const auto choice=std::find_if(remoteDriveRows.begin(),remoteDriveRows.end(),
[key](const auto &entry){return entry.second.digit==key;});
if(choice!=remoteDriveRows.end()) row=choice->first;
const auto digit=driveShortcutDigits.find(key);
if(!lanDrivePicker && digit<driveSourceLabels.size())
row=ftpDriveRow()+static_cast<LRESULT>(digit);
else
{
const auto choice=std::find_if(remoteDriveRows.begin(),remoteDriveRows.end(),
[key](const auto &entry){return entry.second.digit==key;});
if(choice!=remoteDriveRows.end()) row=choice->first;
}
}
if(row!=LB_ERR)
{
@@ -4409,8 +4433,9 @@ void layoutDrivePicker(int selected,bool focus)
const int panelWidth=panel.right-panel.left;
const auto frame=dialogFrameMetrics(GetDpiForWindow(owner));
const int inset=frame.content(),vertical=dialogListInset(frame,textHeight);
const int limit=lanDrivePicker?panelWidth:panelWidth*4/5;
const int width=std::clamp(drivePickerWidth,90,std::max(90,limit-2*inset));
const int scrollWidth=scrollBarWidth(picker);
const int width=std::clamp(drivePickerWidth+scrollWidth,90,std::max(90,panelWidth-2*inset));
const int listWidth=std::max(1,width-scrollWidth);
const int height=std::min(std::max(1,(static_cast<int>(panel.bottom-panel.top)-2*vertical)/textHeight),
static_cast<int>(SendMessageW(picker,LB_GETCOUNT,0,0)))*textHeight;
const int x=panel.left+(panel.right-panel.left-width)/2;
@@ -4420,11 +4445,11 @@ void layoutDrivePicker(int selected,bool focus)
if(layout) layout=DeferWindowPos(layout,pickerFrame,HWND_TOP,
x-inset,y-vertical,width+2*inset,height+2*vertical,flags);
if(layout) layout=DeferWindowPos(layout,picker,HWND_TOP,x,y,
std::max(1,width-scrollBarWidth(picker)),height,flags);
listWidth,height,flags);
if(!layout || !EndDeferWindowPos(layout))
{
SetWindowPos(pickerFrame,HWND_TOP,x-inset,y-vertical,width+2*inset,height+2*vertical,flags);
SetWindowPos(picker,HWND_TOP,x,y,std::max(1,width-scrollBarWidth(picker)),height,flags);
SetWindowPos(picker,HWND_TOP,x,y,listWidth,height,flags);
}
RedrawWindow(pickerFrame,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW);
SendMessageW(picker,LB_SETCURSEL,selected,0);
@@ -4442,18 +4467,15 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
for(auto count=SendMessageW(picker,LB_GETCOUNT,0,0);count>static_cast<LRESULT>(drivePaths.size());--count)
SendMessageW(picker,LB_DELETESTRING,count-1,0);
remoteDriveRows.clear();
const auto add=[](const std::wstring &label)
const auto add=[](const std::wstring &label,int shortcutColumns=0)
{
drivePickerWidth=std::max(drivePickerWidth,static_cast<int>(label.size()+2)*cellWidth);
drivePickerWidth=std::max(drivePickerWidth,(static_cast<int>(label.size())+2+shortcutColumns)*cellWidth);
return SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
};
if(!lanDrivePicker)
{
add(L"");
add(L"FTP");
add(L"SFTP");
add(L"SMB");
add(L"Recent folders");
for(const auto label:driveSourceLabels) add(label,2);
}
add(L"KSwitcher LAN");
if(!drivePeerLookupError.empty()) add(L" "+drivePeerLookupError);
@@ -4472,7 +4494,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
if(current.peer && current.peer->id==query.peer.id && path==current.directory.root_path())
matchingDrive=row;
const auto id=std::pair{query.peer.id,path};
constexpr std::wstring_view available=L"234567890";
const auto available=driveShortcutDigits.substr(lanDrivePicker?1:driveSourceLabels.size());
auto digit=driveDigits.find(id);
if(digit==driveDigits.end() && driveDigits.size()<available.size())
digit=driveDigits.emplace(id,available[driveDigits.size()]).first;
@@ -4571,6 +4593,7 @@ void pollDriveQueries(HWND owner)
void chooseDrive(int index,bool fromMenu,bool lanOnly)
{
if(index==spacePaneSide) closeSpacePane(GetParent(picker));
lanDrivePicker=lanOnly;
if(quickViewWindow && index!=quickViewSource) toggleQuickView(GetParent(picker));
folderPicker.reset();
@@ -4783,6 +4806,7 @@ void toggleQuickView(HWND owner)
setStatus(L"Could not open Quick View.");
return;
}
if(spacePaneWindow) closeSpacePane(owner,false);
quickViewSource=active;
refreshQuickView(panel);
layout(owner);
@@ -8559,6 +8583,7 @@ void openMenu(HWND window, int index)
rows.push_back(std::move(label));
}
rows.push_back(index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2");
rows.push_back(index/4==spacePaneSide?L" Close Space Analyzer":L" Space Analyzer");
if(panelViewAvailable(panel))
{
constexpr const wchar_t *sortLabels[]{L"Sort by name\tCtrl+F3",L"Sort by extension\tCtrl+F4",
@@ -8834,7 +8859,9 @@ void restoreCommandFocus()
if(focus==GetParent(terminalInput)) SetFocus(gitChangesView->list);
return;
}
if(GetFocus()!=terminalInput && !GetCapture() && commandLineAvailable(GetParent(terminalInput)))
const auto focus=GetFocus();
if(spacePaneWindow && (focus==spacePaneWindow || IsChild(spacePaneWindow,focus))) return;
if(focus!=terminalInput && !GetCapture() && commandLineAvailable(GetParent(terminalInput)))
SetFocus(terminalInput);
}
@@ -9243,7 +9270,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
const auto start=panelSearchPrefix.size()>cells?panelSearchPrefix.size()-cells:0;
if(lavenderFiles())
{
paintLavenderDialogFrame(window,item.hDC,item.rcItem,L"Search");
paintLavenderPopupFrame(item.hwndItem,item.hDC,item.rcItem,L"Search");
lavender::rounded(item.hDC,field,LavenderMetrics(window).px(5),lavender::path,lavender::line);
field.left+=LavenderMetrics(window).px(6);
lavender::text(item.hDC,field,panelSearchPrefix.c_str()+start,lavender::ink);
@@ -9355,7 +9382,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
if(lavenderFiles())
{
const auto title=driveFrame?L"Change drive":folderPicker?folderPicker->caption:L"";
paintLavenderDialogFrame(window,item.hDC,item.rcItem,title);
paintLavenderPopupFrame(item.hwndItem,item.hDC,item.rcItem,title);
paintScrollPosition(item.hwndItem,item.hDC,item.hwndItem==pickerFrame?picker:completionList,lavender::path);
return TRUE;
}
@@ -9600,7 +9627,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
RECT button{};
const auto choice=remoteDriveRows.find(item.itemID);
const bool wake=choice!=remoteDriveRows.end() && !choice->second.path;
const auto digit=item.itemID==ftpDriveRow()?ftpDriveDigit:
const auto digit=builtInDriveSource(item.itemID)?driveShortcutDigits[item.itemID-ftpDriveRow()]:
choice==remoteDriveRows.end()?L'\0':choice->second.digit;
SelectObject(item.hDC,mono);
SetTextColor(item.hDC,foreground);
@@ -9847,6 +9874,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
return 0;
case WM_DESTROY:
filesMcp.stop();
closeSpacePane(window,false);
pendingPanelDrop.reset();
closeGitChanges(window,false);
for(auto &panel:panels)
@@ -9950,6 +9978,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
if(GetForegroundWindow()==window || IsChild(window,GetFocus())) restoreCommandFocus();
if(GetMessageW(&message,nullptr,0,0)<=0) break;
if(handleFilesHelpMessage(message) || handleComparisonMessage(message)) continue;
if(handleSpacePaneMessage(window,message)) continue;
if(message.message==WM_KEYDOWN && message.wParam==VK_TAB &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
ks::files::cycleTextWindows(GetAncestor(message.hwnd,GA_ROOT),(GetKeyState(VK_SHIFT)&0x8000)!=0))
+201 -42
View File
@@ -2,6 +2,7 @@ constexpr int spacePath=488,spaceTree=489,spaceStatus=490,spaceFooter=491;
constexpr int spaceStop=492,spaceRescan=493,spaceView=494;
constexpr int spaceCapacity=495,spaceScope=496,spaceMapButton=497,spaceMap=498;
constexpr int spaceSunburstButton=499,spaceSunburstList=500,spaceSunburstLabel=501;
constexpr int spaceTreeButton=502,spaceMetric=503;
constexpr UINT_PTR spaceUpdateTimer=1;
constexpr UINT_PTR spaceVolumeTimer=2;
constexpr size_t spaceBatchSize=256;
@@ -151,7 +152,7 @@ struct SpaceAnalyzer
fs::path folder, root, selected;
SpaceVolume volume;
std::future<SpaceVolume> pendingVolume;
bool selectedFolder{}, volumeScope{};
bool selectedFolder{}, volumeScope{}, embedded{}, onDisk{};
SpaceDisplay display{SpaceDisplay::tree};
std::shared_ptr<SpaceRun> run;
std::vector<SpaceNode> nodes;
@@ -163,6 +164,13 @@ struct SpaceAnalyzer
bool scanning{}, hasResults{};
};
void showSpaceSelection(HWND owner,const SpaceAnalyzer &state,int origin,int answer);
uint64_t spaceBytes(const SpaceAnalyzer &state,const SpaceNode &node)
{
return state.onDisk?node.allocated.known.bytes:node.size.bytes;
}
void layoutSpaceAnalyzer(HWND dialog)
{
RECT bounds{};
@@ -173,39 +181,61 @@ void layoutSpaceAnalyzer(HWND dialog)
const auto place=[&](int id,int top,int height) {
SetWindowPos(GetDlgItem(dialog,id),nullptr,inset,top,width,height,SWP_NOZORDER|SWP_NOACTIVATE);
};
const auto state=reinterpret_cast<const SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
const bool embedded=state && state->embedded;
const auto gap=dialogColumnGap();
const auto buttonHeight=textHeight;
const auto buttonRows=[&](std::initializer_list<int> ids,int y,bool position)
{
const auto start=y;
int x=inset;
for(const auto id:ids)
{
const auto button=GetDlgItem(dialog,id);
const auto buttonWidth=std::min(width,farDialogButtonWidth(button));
if(x>inset && x+buttonWidth>inset+width)
{
y+=buttonHeight+dialogRowGap();
x=inset;
}
if(position) SetWindowPos(button,nullptr,x,y,buttonWidth,buttonHeight,SWP_NOZORDER|SWP_NOACTIVATE);
x+=buttonWidth+gap;
}
return y-start+buttonHeight;
};
auto top=dialogListInset(frame,textHeight);
place(spacePath,top,textHeight);
top+=textHeight;
place(spaceCapacity,top,textHeight);
top+=textHeight+dialogRowGap();
const auto buttonHeight=textHeight;
auto x=inset;
for(const auto id:{spaceScope,spaceMapButton,spaceSunburstButton})
{
const auto button=GetDlgItem(dialog,id);
const auto width=std::max(12L*cellWidth,farDialogButtonWidth(button));
SetWindowPos(button,nullptr,x,top,width,buttonHeight,SWP_NOZORDER|SWP_NOACTIVATE);
x+=width+dialogColumnGap();
}
top+=buttonHeight+dialogRowGap();
place(spaceTree,top,9*textHeight);
const auto state=reinterpret_cast<const SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
top+=buttonRows({spaceScope,spaceTreeButton,spaceMapButton,spaceSunburstButton},top,true)+dialogRowGap();
const auto metric=GetDlgItem(dialog,spaceMetric);
SetWindowPos(metric,nullptr,inset,top,std::min(width,20L*cellWidth),5*textHeight,
SWP_NOZORDER|SWP_NOACTIVATE);
RECT metricBounds{};
GetWindowRect(metric,&metricBounds);
top+=std::max<LONG>(textHeight,metricBounds.bottom-metricBounds.top)+dialogRowGap();
const auto footerHeight=embedded?buttonRows(spaceFooterButtons,0,false):0;
const auto treeHeight=embedded?std::max(1L,bounds.bottom-top-inset-footerHeight-textHeight-3*dialogRowGap()):
9*static_cast<LONG>(textHeight);
place(spaceTree,top,treeHeight);
if(state && state->display==SpaceDisplay::sunburst)
{
const auto graphWidth=width*3/5;
const auto gap=dialogColumnGap();
SetWindowPos(GetDlgItem(dialog,spaceSunburstLabel),nullptr,inset+graphWidth,top-textHeight-dialogRowGap(),
SetWindowPos(GetDlgItem(dialog,spaceSunburstLabel),nullptr,inset+graphWidth,top,
width-graphWidth,textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(GetDlgItem(dialog,spaceMap),nullptr,inset,top,graphWidth-gap,9*textHeight,
SetWindowPos(GetDlgItem(dialog,spaceMap),nullptr,inset,top,std::max(1L,graphWidth-gap),treeHeight,
SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(GetDlgItem(dialog,spaceSunburstList),nullptr,inset+graphWidth,top,width-graphWidth,
9*textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(GetDlgItem(dialog,spaceSunburstList),nullptr,inset+graphWidth,top+textHeight,width-graphWidth,
std::max(1L,treeHeight-textHeight),SWP_NOZORDER|SWP_NOACTIVATE);
}
else place(spaceMap,top,9*textHeight);
top+=9*textHeight+dialogRowGap();
else place(spaceMap,top,treeHeight);
top+=treeHeight+dialogRowGap();
place(spaceStatus,top,textHeight);
place(spaceFooter,top+textHeight+dialogRowGap(),1);
layoutDialogButtons(dialog,spaceFooter,spaceFooterButtons);
if(embedded) buttonRows(spaceFooterButtons,top+textHeight+2*dialogRowGap(),true);
else layoutDialogButtons(dialog,spaceFooter,spaceFooterButtons);
}
HTREEITEM insertSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
@@ -230,6 +260,22 @@ void expandSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
for(auto child:node.children) insertSpaceNode(tree,state,child);
}
int CALLBACK compareSpaceNodes(LPARAM left,LPARAM right,LPARAM payload)
{
const auto &state=*reinterpret_cast<const SpaceAnalyzer *>(payload);
const auto &a=state.nodes[left],&b=state.nodes[right];
const auto aSize=spaceBytes(state,a),bSize=spaceBytes(state,b);
if(aSize!=bSize) return aSize>bSize?-1:1;
return a.path.compare(b.path);
}
void sortSpaceChildren(HWND tree,const SpaceAnalyzer &state,const SpaceNode &node)
{
if(!node.item || !node.expanded || node.children.size()<2) return;
TVSORTCB sort{node.item,compareSpaceNodes,reinterpret_cast<LPARAM>(&state)};
TreeView_SortChildrenCB(tree,&sort,FALSE);
}
void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event)
{
if(!event.item)
@@ -283,6 +329,11 @@ std::wstring spaceAllocatedSize(const SpaceNode &node)
return result+L" on disk";
}
std::wstring spaceMetricSize(const SpaceAnalyzer &state,const SpaceNode &node)
{
return state.onDisk?spaceAllocatedSize(node):spaceLogicalSize(node);
}
std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index)
{
const auto &node=state.nodes[index];
@@ -297,11 +348,12 @@ std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index)
}
if(!state.hasResults) return name;
if(node.link) return name+L" [link]";
auto result=name+L" — "+spaceLogicalSize(node)+L" · "+spaceAllocatedSize(node);
if(parent.size.bytes)
auto result=name+L" — "+spaceMetricSize(state,node);
const auto parentBytes=spaceBytes(state,parent);
if(parentBytes && (!state.onDisk || node.allocated.measured || !node.allocated.unavailable))
{
wchar_t share[48]{};
swprintf_s(share,L" (%.1f%%)",100.0*static_cast<double>(node.size.bytes)/static_cast<double>(parent.size.bytes));
swprintf_s(share,L" (%.1f%%)",100.0*static_cast<double>(spaceBytes(state,node))/static_cast<double>(parentBytes));
result+=share;
}
return result;
@@ -359,12 +411,12 @@ void updateSpaceTree(HWND dialog,SpaceAnalyzer &state)
const auto &allocation=state.nodes[0].allocated;
auto label=std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files";
if(indexed) label+=L" · NTFS index";
if(allocation.unavailable || allocation.known.partial) label+=L" · on-disk sizes partial";
else label+=state.display==SpaceDisplay::treemap?L" · logical size by area":
state.display==SpaceDisplay::sunburst?L" · logical size by angle":L" · logical shares of parent";
label+=state.onDisk?L" · Size on disk":L" · Logical size";
if(state.onDisk && (allocation.unavailable || allocation.known.partial)) label+=L" (partial)";
SetDlgItemTextW(dialog,spaceStatus,label.c_str());
if(finished)
{
for(const auto &node:state.nodes) sortSpaceChildren(tree,state,node);
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
@@ -409,6 +461,8 @@ void prepareSpaceScope(HWND dialog,SpaceAnalyzer &state)
layoutSpaceAnalyzer(dialog);
}
void rescanSpace(HWND dialog,SpaceAnalyzer &state);
void updateSpaceVolume(HWND dialog,SpaceAnalyzer &state)
{
if(!state.pendingVolume.valid() ||
@@ -426,6 +480,7 @@ void updateSpaceVolume(HWND dialog,SpaceAnalyzer &state)
EnableWindow(GetDlgItem(dialog,spaceScope),
!state.volume.root.empty() && !sameVolumeRoot(state.folder,state.volume.root));
prepareSpaceScope(dialog,state);
if(state.embedded) rescanSpace(dialog,state);
}
void rescanSpace(HWND dialog,SpaceAnalyzer &state)
@@ -467,6 +522,10 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
SetWindowSubclass(GetDlgItem(dialog,spaceSunburstList),spaceSunburstListKeys,1,reinterpret_cast<DWORD_PTR>(&state));
TreeView_SetBkColor(tree,RGB(255,255,255));
TreeView_SetTextColor(tree,RGB(0,0,0));
for(const auto label:{L"Logical size",L"Size on disk"})
SendDlgItemMessageW(dialog,spaceMetric,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
SendDlgItemMessageW(dialog,spaceMetric,CB_SETCURSEL,0,0);
EnableWindow(GetDlgItem(dialog,spaceTreeButton),FALSE);
layoutSpaceAnalyzer(dialog);
const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content();
// Rescan is one character wider than the initial Start label.
@@ -487,6 +546,7 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
{
SetDlgItemTextW(dialog,spaceCapacity,L"Volume capacity unavailable");
prepareSpaceScope(dialog,state);
if(state.embedded) rescanSpace(dialog,state);
}
SetFocus(tree);
return FALSE;
@@ -494,6 +554,11 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
const auto state=reinterpret_cast<SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!state) return FALSE;
const auto tree=GetDlgItem(dialog,spaceTree);
if(message==WM_SIZE && state->embedded)
{
layoutSpaceAnalyzer(dialog);
return TRUE;
}
if(message==WM_DRAWITEM && wp==spaceMap)
{
const auto &paint=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
@@ -535,7 +600,11 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
{
const auto &item=*reinterpret_cast<const NMTREEVIEWW *>(lp);
const auto index=static_cast<size_t>(item.itemNew.lParam);
if(item.action==TVE_EXPAND && index<state->nodes.size()) expandSpaceNode(tree,*state,index);
if(item.action==TVE_EXPAND && index<state->nodes.size())
{
expandSpaceNode(tree,*state,index);
sortSpaceChildren(tree,*state,state->nodes[index]);
}
}
if(notification->code==TVN_SELCHANGEDW)
{
@@ -562,12 +631,23 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
{
state->volumeScope=!state->volumeScope;
prepareSpaceScope(dialog,*state);
if(state->embedded) rescanSpace(dialog,*state);
return TRUE;
}
if(command==spaceMapButton || command==spaceSunburstButton)
if(command==spaceMetric && HIWORD(wp)==CBN_SELCHANGE)
{
const auto chart=command==spaceMapButton?SpaceDisplay::treemap:SpaceDisplay::sunburst;
setSpaceDisplay(dialog,*state,state->display==chart?SpaceDisplay::tree:chart);
state->onDisk=SendDlgItemMessageW(dialog,spaceMetric,CB_GETCURSEL,0,0)==1;
for(const auto &node:state->nodes) sortSpaceChildren(tree,*state,node);
InvalidateRect(tree,nullptr,FALSE);
if(state->display!=SpaceDisplay::tree) refreshSpaceChart(GetDlgItem(dialog,spaceMap),*state);
if(state->run) updateSpaceTree(dialog,*state);
return TRUE;
}
if(command==spaceTreeButton || command==spaceMapButton || command==spaceSunburstButton)
{
const auto display=command==spaceTreeButton?SpaceDisplay::tree:
command==spaceMapButton?SpaceDisplay::treemap:SpaceDisplay::sunburst;
setSpaceDisplay(dialog,*state,display);
if(state->run) updateSpaceTree(dialog,*state);
return TRUE;
}
@@ -594,7 +674,8 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
if(state->embedded) closeSpacePane(GetParent(dialog));
else FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message==WM_DESTROY)
@@ -606,17 +687,8 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
return paintCopyDialog(dialog,message,wp,lp,L" Space Analyzer ",false,{spaceFooter});
}
void openSpaceAnalyzer(HWND owner,Panel &panel)
void showSpaceSelection(HWND owner,const SpaceAnalyzer &state,int origin,int answer)
{
if(panel.peer || panel.ftp || panel.archive || panel.directory.empty())
{
setStatus(L"Space Analyzer requires an open local folder.");
return;
}
const auto origin=static_cast<int>(&panel-panels);
SpaceAnalyzer state{.folder=folderPathWithoutSeparator(panel.directory),.root=folderPathWithoutSeparator(panel.directory)};
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner,
spaceAnalyzerDialog,reinterpret_cast<LPARAM>(&state));
if(answer==spaceView)
{
ks::files::openTextWindow(owner,state.selected,false,textWindowDialogs(),nullptr);
@@ -633,3 +705,90 @@ void openSpaceAnalyzer(HWND owner,Panel &panel)
if(state.selectedFolder) openOn(other,state.selected,true,{});
else revealLocalFile(other,state.selected);
}
bool spaceAnalyzerAvailable(const Panel &panel)
{
return !panel.peer && !panel.ftp && !panel.archive && !panelListsLocations(panel) && !panel.directory.empty();
}
void openSpaceAnalyzer(HWND owner,Panel &panel)
{
if(!spaceAnalyzerAvailable(panel))
{
setStatus(L"Space Analyzer requires an open local folder.");
return;
}
const auto folder=folderPathWithoutSeparator(panel.directory);
SpaceAnalyzer state{.folder=folder,.root=folder};
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner,
spaceAnalyzerDialog,reinterpret_cast<LPARAM>(&state));
showSpaceSelection(owner,state,static_cast<int>(&panel-panels),static_cast<int>(answer));
}
std::unique_ptr<SpaceAnalyzer> spacePane;
void focusSpacePane()
{
if(spacePaneWindow && IsWindowVisible(spacePaneWindow)) SetFocus(GetDlgItem(spacePaneWindow,spaceTree));
}
void closeSpacePane(HWND owner,bool restorePane)
{
if(!spacePaneWindow) return;
const auto side=std::exchange(spacePaneSide,-1);
DestroyWindow(std::exchange(spacePaneWindow,nullptr));
spacePane.reset();
if(restorePane)
{
activatePanel(side);
layout(owner);
restoreCommandFocus();
}
}
void toggleSpacePane(HWND owner,int side)
{
if(spacePaneSide==side)
{
closeSpacePane(owner);
return;
}
const auto &panel=panels[side];
if(!spaceAnalyzerAvailable(panel) || terminalVisible)
{
setStatus(L"Space Analyzer requires a visible local file pane.");
return;
}
const auto folder=folderPathWithoutSeparator(panel.directory);
auto state=std::make_unique<SpaceAnalyzer>();
state->folder=state->root=folder;
state->embedded=true;
const auto window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(621),owner,
spaceAnalyzerDialog,reinterpret_cast<LPARAM>(state.get()));
if(!window)
{
setStatus(L"Could not open Space Analyzer in this pane.");
return;
}
closeQuickViews();
closeSpacePane(owner,false);
spacePane=std::move(state);
spacePaneWindow=window;
spacePaneSide=side;
activatePanel(1-side);
layout(owner);
focusSpacePane();
}
bool handleSpacePaneMessage(HWND owner,MSG &message)
{
if(!spacePaneWindow || (message.hwnd!=spacePaneWindow && !IsChild(spacePaneWindow,message.hwnd))) return false;
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
{
if(SendDlgItemMessageW(spacePaneWindow,spaceMetric,CB_GETDROPPEDSTATE,0,0))
SendDlgItemMessageW(spacePaneWindow,spaceMetric,CB_SHOWDROPDOWN,FALSE,0);
else closeSpacePane(owner);
return true;
}
return IsDialogMessageW(spacePaneWindow,&message)!=FALSE;
}
+10 -14
View File
@@ -5,7 +5,8 @@ void finishSpaceSelection(HWND dialog,SpaceAnalyzer &state,size_t selected,int a
if(action==spaceView && node.folder) return;
state.selected=node.path;
state.selectedFolder=node.folder;
FilesModalDialog::finish(dialog,action);
if(state.embedded) showSpaceSelection(GetParent(dialog),state,spacePaneSide,action);
else FilesModalDialog::finish(dialog,action);
}
void divideSpaceTiles(std::span<const size_t> nodes,std::span<const long double> prefix,RECT bounds,
@@ -51,14 +52,14 @@ void layoutSpaceMap(HWND map,SpaceAnalyzer &state)
if(state.mapFolder>=state.nodes.size()) return;
std::vector<size_t> items;
for(auto index:state.nodes[state.mapFolder].children)
if(state.nodes[index].size.bytes) items.push_back(index);
if(spaceBytes(state,state.nodes[index])) items.push_back(index);
std::sort(items.begin(),items.end(),[&](size_t left,size_t right) {
const auto a=state.nodes[left].size.bytes, b=state.nodes[right].size.bytes;
const auto a=spaceBytes(state,state.nodes[left]), b=spaceBytes(state,state.nodes[right]);
return a!=b?a>b:left<right;
});
std::vector<long double> prefix{0};
prefix.reserve(items.size()+1);
for(auto index:items) prefix.push_back(prefix.back()+state.nodes[index].size.bytes);
for(auto index:items) prefix.push_back(prefix.back()+spaceBytes(state,state.nodes[index]));
RECT bounds{};
GetClientRect(map,&bounds);
const auto minimum=std::max(4,MulDiv(8,GetDpiForWindow(map),96));
@@ -120,14 +121,8 @@ void paintSpaceMap(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state)
bounds.top+=textHeight;
if(bounds.bottom-bounds.top>=textHeight)
{
const auto logical=spaceLogicalSize(node);
DrawTextW(paint.hDC,logical.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
bounds.top+=textHeight;
if(bounds.bottom-bounds.top>=textHeight)
{
const auto allocated=spaceAllocatedSize(node);
DrawTextW(paint.hDC,allocated.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
}
const auto value=spaceMetricSize(state,node);
DrawTextW(paint.hDC,value.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
}
}
}
@@ -219,8 +214,9 @@ void setSpaceDisplay(HWND dialog,SpaceAnalyzer &state,SpaceDisplay display)
state.mapFolder=node.folder && !node.link?index:node.parent;
}
state.display=display;
SetDlgItemTextW(dialog,spaceMapButton,display==SpaceDisplay::treemap?L"Tr&ee":L"Tree&map");
SetDlgItemTextW(dialog,spaceSunburstButton,showSunburst?L"Tr&ee":L"S&unburst");
EnableWindow(GetDlgItem(dialog,spaceTreeButton),!showTree);
EnableWindow(GetDlgItem(dialog,spaceMapButton),display!=SpaceDisplay::treemap);
EnableWindow(GetDlgItem(dialog,spaceSunburstButton),!showSunburst);
layoutSpaceAnalyzer(dialog);
ShowWindow(tree,showTree?SW_SHOW:SW_HIDE);
ShowWindow(map,showTree?SW_HIDE:SW_SHOW);
+5 -4
View File
@@ -12,15 +12,16 @@ void addSunburstRing(SpaceAnalyzer &state,size_t folder,unsigned ring,double sta
if(ring>=sunburstRings || end-start<0.02) return;
const auto &parent=state.nodes[folder];
double total=0;
for(auto index:parent.children) total+=static_cast<double>(state.nodes[index].size.bytes);
for(auto index:parent.children) total+=static_cast<double>(spaceBytes(state,state.nodes[index]));
if(total<=0) return;
const auto span=end-start;
auto cursor=start;
for(auto index:parent.children)
{
const auto &item=state.nodes[index];
if(!item.size.bytes) continue;
const auto next=std::min(end,cursor+span*static_cast<double>(item.size.bytes)/total);
const auto size=spaceBytes(state,item);
if(!size) continue;
const auto next=std::min(end,cursor+span*static_cast<double>(size)/total);
if(next-cursor>=0.02)
{
state.sectors.push_back({index,ring,cursor,next});
@@ -75,7 +76,7 @@ void layoutSunburst(HWND map,SpaceAnalyzer &state)
const auto &node=state.nodes[sector.node];
const auto &root=state.nodes[state.mapFolder];
const auto name=node.path.lexically_relative(root.path).native();
const auto line=name+L" — "+spaceLogicalSize(node);
const auto line=name+L" — "+spaceMetricSize(state,node);
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(line.c_str()));
if(row>=0)
{
+36 -4
View File
@@ -148,6 +148,7 @@ struct LanService::Impl
std::mutex inputMutex;
std::vector<lan::RoutedInput> inputOut,inputIn;
std::map<std::string,uint64_t> inputReady;
std::function<int()> additionalHeldKey;
std::unique_ptr<lan::InputMesh> router;
std::string inputStatus="Input sharing disabled.";
size_t inputConnectedPeers{}, inputOnlinePeers{};
@@ -155,8 +156,8 @@ struct LanService::Impl
bool inputNeedsHelp{};
HWND inputWindow{};std::atomic<bool> inputNotification{false};
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)
explicit Impl(const std::filesystem::path &root,HWND window,bool paused,std::function<int()> heldKey)
: path(root/L"lan-pairing.bin"),inputPaused(paused),additionalHeldKey(std::move(heldKey)),inputWindow(window),clients(root)
{
if(std::filesystem::exists(path))
{
@@ -239,7 +240,8 @@ struct LanService::Impl
router.reset();++inputConfiguration;
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);});
router=std::make_unique<lan::InputMesh>(id,lan::windowsInputEnvironment(additionalHeldKey),std::move(layout),
[this](const auto &peer,auto f){return queue(peer,f);});
}
inputStatus=enabled&&shareInput?"Connecting input channels...":"Input sharing disabled.";
observedRevision=0;
@@ -282,6 +284,26 @@ struct LanService::Impl
router->receive(frame.peer,frame.frame,GetTickCount64(),allowEnter);
return takeChange();
}
std::wstring inputBlockText(const lan::HandoffBlock &block) const
{
if(!block.key)return {};
std::wstring location=L"this PC";
if(!block.peer.empty())
{
auto paired=trusted.find(block.peer);
if(paired==trusted.end())return {};
location=wide(paired->value("name",block.peer.substr(0,8)));
if(location.size()>50)
{
const bool highSurrogate=location[48]>=0xd800&&location[48]<=0xdbff;
location.resize(highSurrogate?48:49);
location+=L"…";
}
}
auto input=lan::heldInputName(block.key);
return L"Cursor handoff blocked on "+location+L": "+
(input.empty()?L"a key or mouse button is held.":input+L" is held.");
}
void start()
{
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
@@ -827,6 +849,7 @@ struct LanService::Impl
{"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["inputBlock"]=router?utf8(inputBlockText(router->handoffBlock())):std::string{};
result["shareLogs"]=shareLogs;
result["files"]=Json::array();
result["transferStatus"]=transfers->status;
@@ -853,7 +876,8 @@ struct LanService::Impl
return encoded(result);
}
};
LanService::LanService(const std::filesystem::path &path,HWND window,bool paused) : impl(std::make_unique<Impl>(path,window,paused)) {}
LanService::LanService(const std::filesystem::path &path,HWND window,bool paused,std::function<int()> heldKey)
:impl(std::make_unique<Impl>(path,window,paused,std::move(heldKey))) {}
LanService::~LanService()=default;
Bytes LanService::command(const Bytes &command) { return impl->command(command); }
void LanService::startClients() { impl->startClients(); }
@@ -888,6 +912,14 @@ LanInputConnections LanService::inputConnections()const
return {std::min(impl->inputConnectedPeers,paired),std::min(impl->inputOnlinePeers,paired),paired,impl->inputWorkerStopped};
}
bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);}
std::wstring LanService::inputBlockText()const
{
const auto block=impl->router?impl->router->handoffBlock():lan::HandoffBlock{};
if(!block.key)return {};
std::lock_guard lock(impl->mutex);
return impl->inputBlockText(block);
}
void LanService::forgetHeldInput(){if(impl->router)impl->router->forgetHeldKeys();}
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);}
bool LanService::takeInputChange(){return impl->takeChange();}
+4 -1
View File
@@ -21,7 +21,8 @@ class LanService
struct Impl;
std::unique_ptr<Impl> impl;
public:
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr, bool inputPaused=false);
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr, bool inputPaused=false,
std::function<int()> additionalHeldKey={});
~LanService();
Bytes command(const Bytes &);
void startClients();
@@ -31,6 +32,8 @@ class LanService
bool inputEnabled() const;
void setInputPaused(bool);
LanInputConnections inputConnections() const;
std::wstring inputBlockText() const;
void forgetHeldInput();
bool tickInput(bool allowEnter = true);
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
bool mouse(UINT, const MSLLHOOKSTRUCT &, bool allowEnter);
+25 -5
View File
@@ -48,7 +48,8 @@ Json capabilities(bool write, bool erase, unsigned host)
{
return {{"protocol", 2}, {"hostRevision", host}, {"write", write && host},
{"delete", erase && host}, {"move", write && erase && host},
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0}};
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0},
{"conflictPrompt", host != 0}};
}
fs::path itemPath(const Json &value)
{
@@ -128,6 +129,27 @@ class ClientTransfer
if (!result.at("continue").get<bool>()) throw std::system_error(ERROR_CANCELLED, std::system_category());
guard();
}
bool resolveConflict(const fs::path &path, const Json &incoming, const Json &existing)
{
if (conflict == "skip") return false;
const bool replaceable = directory(incoming) == directory(existing) && !reparse(existing);
if (conflict == "replace" && replaceable) return true;
if (conflict != "ask") throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
if (replaceable && directory(existing)) return true;
sendJson(send, {{"type", "conflict"}, {"path", utf8(path.native())},
{"incoming", incoming}, {"existing", existing}, {"replaceable", replaceable}});
for (;;)
{
const auto answer = Json::parse(receive(256)).at("decision").get<std::string>();
guard();
if (answer == "wait") continue;
if (answer == "skip") return false;
if (answer == "replace" && replaceable) return true;
if (answer == "cancel") throw std::system_error(ERROR_CANCELLED, std::system_category());
throw std::runtime_error("Invalid transfer conflict decision.");
}
}
bool copy(const fs::path &from, const fs::path &to, unsigned depth)
{
if (depth > 256) throw std::runtime_error("The file tree is too deep.");
@@ -139,9 +161,7 @@ class ClientTransfer
if (found)
{
checkFileReply(existing);
if (conflict == "skip") { ++skipped; return false; }
if (conflict != "replace" || directory(original) != directory(existing))
throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
if (!resolveConflict(to, original, existing)) { ++skipped; return false; }
requireRegular(existing);
}
@@ -199,7 +219,7 @@ public:
void run(const fs::path &from, const fs::path &to)
{
if (conflict != "fail" && conflict != "skip" && conflict != "replace")
if (conflict != "fail" && conflict != "skip" && conflict != "replace" && conflict != "ask")
throw std::runtime_error("Unknown conflict policy.");
if (sameHost)
{
+85 -11
View File
@@ -82,8 +82,11 @@ INPUT button(unsigned index,bool down)
{MOUSEEVENTF_MIDDLEUP,MOUSEEVENTF_MIDDLEDOWN},{MOUSEEVENTF_XUP,MOUSEEVENTF_XDOWN},{MOUSEEVENTF_XUP,MOUSEEVENTF_XDOWN}};
input.mi.dwFlags=flags[index][down];if(index>=3)input.mi.mouseData=index==3?XBUTTON1:XBUTTON2;return input;
}
bool windowsKeyDown(int key){return (GetAsyncKeyState(key)&0x8000)!=0;}
UINT keyScan(int key){return MapVirtualKeyW(UINT(key),MAPVK_VK_TO_VSC_EX);}
bool extendedKey(UINT scan){return (scan&0xff00)==0xe000;}
}
InputEnvironment windowsInputEnvironment()
InputEnvironment windowsInputEnvironment(std::function<int()> additionalHeldKey)
{
auto overlay=std::make_shared<ControlOverlay>();
return {
@@ -91,7 +94,10 @@ InputEnvironment windowsInputEnvironment()
[]{POINT p{};GetCursorPos(&p);return p;},
[](const INPUT &i){INPUT input=i;return SendInput(1,&input,sizeof(input))==1;},
ordinaryDesktop,
[]{for(int key=1;key<256;++key)if(GetAsyncKeyState(key)&0x8000)return true;return false;},
[additionalHeldKey=std::move(additionalHeldKey)]{
if(additionalHeldKey)if(const int key=additionalHeldKey())return key;
for(int key=1;key<256;++key)if(windowsKeyDown(key))return key;
return 0;},
[]{POINT p{};GetCursorPos(&p);MONITORINFO info{sizeof(info)};
if(GetMonitorInfoW(MonitorFromPoint(p,MONITOR_DEFAULTTONEAREST),&info))p={(info.rcMonitor.left+info.rcMonitor.right)/2,(info.rcMonitor.top+info.rcMonitor.bottom)/2};
return p;},
@@ -99,6 +105,55 @@ InputEnvironment windowsInputEnvironment()
monitorDpi
};
}
std::wstring heldInputName(int key)
{
switch(key)
{
case VK_LBUTTON:return L"Left mouse button";
case VK_RBUTTON:return L"Right mouse button";
case VK_MBUTTON:return L"Middle mouse button";
case VK_XBUTTON1:return L"Mouse button 4";
case VK_XBUTTON2:return L"Mouse button 5";
case VK_MEDIA_PLAY_PAUSE:return L"Play/Pause";
}
if(key>0&&key<UnknownHeldInput)
{
if(auto name=Hotkey{0,UINT(key)}.format();!name.empty())return name;
const auto scan=keyScan(key);
wchar_t name[64]{};
if(scan&&GetKeyNameTextW(LONG(((scan&0xff)<<16)|(extendedKey(scan)?1u<<24:0u)),name,int(std::size(name))))
return name;
}
return {};
}
std::vector<INPUT> heldInputReleases(const std::function<bool(int)> &isDown)
{
std::vector<INPUT> releases;
for(int key=1;key<256;++key)
{
if(!isDown(key))continue;
// Windows reports a generic modifier along with its left/right key.
if((key==VK_SHIFT&&(isDown(VK_LSHIFT)||isDown(VK_RSHIFT)))||
(key==VK_CONTROL&&(isDown(VK_LCONTROL)||isDown(VK_RCONTROL)))||
(key==VK_MENU&&(isDown(VK_LMENU)||isDown(VK_RMENU))))continue;
const auto mouse=std::find(MouseInputKeys.begin(),MouseInputKeys.end(),key);
if(mouse!=MouseInputKeys.end())
{
auto release=button(unsigned(mouse-MouseInputKeys.begin()),false);
release.mi.dwExtraInfo=inputMarker();
releases.push_back(release);
}
else releases.push_back(keyboardInput(WORD(key),KEYEVENTF_KEYUP|
(extendedKey(keyScan(key))||key==VK_MEDIA_PLAY_PAUSE?KEYEVENTF_EXTENDEDKEY:0)));
}
return releases;
}
bool resetWindowsHeldInput()
{
if(!ordinaryDesktop())return false;
auto releases=heldInputReleases(windowsKeyDown);
return releases.empty()||SendInput(UINT(releases.size()),releases.data(),sizeof(INPUT))==releases.size();
}
bool atEdge(POINT p,RECT r,int side)
{return side==0?p.x<=r.left:side==1?p.x>=r.right-1:side==2?p.y<=r.top:p.y>=r.bottom-1;}
int edgePosition(POINT p,RECT r,int side)
@@ -140,9 +195,15 @@ bool InputRouter::move(POINT p,bool warp)
return ok;
}
bool InputRouter::post(InputFrame f){return connected&&send(f);}
bool InputRouter::held()const
int InputRouter::heldKey()const
{
return std::any_of(physical.begin(),physical.end(),[](bool b){return b;})||env.held();
const auto key=std::find(physical.begin(),physical.end(),true);
return key!=physical.end()?int(key-physical.begin()):env.heldKey();
}
void InputRouter::noteHeldInput(int key)
{
if(!blockedKey_)log(L"LAN input: cursor handoff blocked by local input (VK "+std::to_wstring(key)+L")");
blockedKey_=key;
}
void InputRouter::release()
{
@@ -159,7 +220,7 @@ void InputRouter::local(uint64_t now,int position)
}
bool InputRouter::handoff(int side,int position,uint64_t now)
{
if(!multi||mode_!=ControlMode::Sending||held()||side<0||side>3)return false;
if(!multi||mode_!=ControlMode::Sending||heldKey()||side<0||side>3)return false;
edge=side;transit=true;token=ownershipToken();
requested=now;mode(ControlMode::Requesting);
if(!post({InputType::Enter,token,edge,std::clamp(position,0,65535)})){cancel(now,"next computer unavailable");return false;}
@@ -185,8 +246,10 @@ void InputRouter::tick(bool ready,uint64_t now)
{returning=false;if(env.modeChanged)env.modeChanged(ControlMode::Local);}
}
connected=ready;
const bool desktop=ready&&env.desktop();
if(blockedKey_)blockedKey_=desktop?heldKey():0;
if(!ready)cancel(now,"channel unavailable");
else if(!env.desktop())cancel(now,"input desktop unavailable");
else if(!desktop)cancel(now,"input desktop unavailable");
else if(mode_==ControlMode::Requesting&&now-requested>1000)cancel(now,"handoff acknowledgement timed out");
if(mode_==ControlMode::Sending&&awaitingWarp)
{
@@ -212,9 +275,14 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
if(f.type==InputType::Enter)
{
const wchar_t *declined=nullptr;
int blocked=0;
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((blocked=heldKey())!=0)
{
noteHeldInput(blocked);
post({InputType::Return,f.token,32768,blocked});return;
}
else if(returning||mode_==ControlMode::Sending||mode_==ControlMode::Receiving||
(mode_==ControlMode::Requesting&&preferLocal))
declined=L"another handoff is active";
@@ -225,7 +293,7 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
}
if(mode_==ControlMode::Requesting)cancel(now);
if(multi)edge=f.a^1;
crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
blockedKey_=0;crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
receivedPoint=edgePoint(env.bounds(),edge,f.b);
awaitingEntry=true;entryStarted=now;
if(!move(receivedPoint))cancel(now,"destination cursor injection failed");
@@ -233,8 +301,13 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
}
if(f.type==InputType::Accept)
{
if(mode_!=ControlMode::Requesting||f.token!=token||held()||(!transit&&!atEdge(env.cursor(),env.bounds(),edge))){post({InputType::Return,f.token,32768});if(f.token==token)cancel(now);return;}
transit=false;auto r=env.bounds();anchor=env.anchor?env.anchor():POINT{(r.left+r.right)/2,(r.top+r.bottom)/2};mode(ControlMode::Sending);
const int blocked=mode_==ControlMode::Requesting&&f.token==token?heldKey():0;
if(mode_!=ControlMode::Requesting||f.token!=token||blocked||(!transit&&!atEdge(env.cursor(),env.bounds(),edge)))
{
if(blocked)noteHeldInput(blocked);
post({InputType::Return,f.token,32768});if(f.token==token)cancel(now);return;
}
blockedKey_=0;transit=false;auto r=env.bounds();anchor=env.anchor?env.anchor():POINT{(r.left+r.right)/2,(r.top+r.bottom)/2};mode(ControlMode::Sending);
warpStarted=now;
if(!move(anchor,true))cancel(now,"source cursor parking failed");
return;
@@ -358,8 +431,9 @@ bool InputRouter::mouse(UINT message,const MSLLHOOKSTRUCT &m,uint64_t now,bool a
}
if(index>=0&&outButtons[size_t(index)]){if(!down)outButtons[size_t(index)]=false;return true;}
if(mode_==ControlMode::Local&&connected&&allowEnter&&message==WM_MOUSEMOVE&&now>=cooldown&&
env.desktop()&&!held()&&atEdge(m.pt,env.bounds(),edge))
env.desktop()&&atEdge(m.pt,env.bounds(),edge))
{
if(const int blocked=heldKey()){noteHeldInput(blocked);return false;}
token=ownershipToken();
returnPoint=m.pt;requested=now;mode(ControlMode::Requesting);
if(!post({InputType::Enter,token,edge,edgePosition(m.pt,env.bounds(),edge)}))cancel(now);
+15 -4
View File
@@ -4,18 +4,25 @@
namespace ks::lan
{
enum class ControlMode { Local, Requesting, Sending, Receiving };
// The Return frame's second field was unused. Older peers still return control.
inline constexpr int UnknownHeldInput = 256;
inline constexpr int HeldInputCleared = -1;
struct InputEnvironment
{
std::function<RECT()> bounds;
std::function<POINT()> cursor;
std::function<bool(const INPUT &)> inject;
std::function<bool()> desktop;
std::function<bool()> held;
std::function<int()> heldKey;
std::function<POINT()> anchor;
std::function<void(ControlMode)> modeChanged;
std::function<int(POINT)> dpi;
};
InputEnvironment windowsInputEnvironment();
inline constexpr std::array MouseInputKeys{VK_LBUTTON,VK_RBUTTON,VK_MBUTTON,VK_XBUTTON1,VK_XBUTTON2};
InputEnvironment windowsInputEnvironment(std::function<int()> additionalHeldKey={});
std::wstring heldInputName(int key);
std::vector<INPUT> heldInputReleases(const std::function<bool(int)> &isDown);
bool resetWindowsHeldInput();
ULONG_PTR remoteInputMarker();
ULONG_PTR cursorWarpMarker();
bool atEdge(POINT,RECT,int edge);
@@ -34,6 +41,7 @@ class InputRouter
bool awaitingWarp{},awaitingEntry{};
uint64_t warpStarted{},entryStarted{};
bool returning{};POINT returnTarget{};uint64_t returnStarted{};
int blockedKey_{};
double remainderX{},remainderY{};
std::array<bool,256> physical{},outKeys{},remoteKeys{};
std::array<INPUT,256> releases{};
@@ -42,7 +50,8 @@ class InputRouter
bool emit(INPUT);
bool move(POINT,bool warp=false);
bool post(InputFrame);
bool held() const;
int heldKey() const;
void noteHeldInput(int key);
void release();
void local(uint64_t now,int position=-1);
public:
@@ -50,7 +59,9 @@ class InputRouter
~InputRouter();
void selectEdge(int side,bool prefer){edge=side;preferLocal=prefer;}
uint32_t sessionToken()const{return token;}
bool canHandoff()const{return mode_==ControlMode::Sending&&!held();}
bool canHandoff()const{return mode_==ControlMode::Sending&&!heldKey();}
int blockedKey()const{return blockedKey_;}
void forgetHeldKeys(){physical.fill(false);}
bool handoff(int side,int position,uint64_t now);
void returnAt(int side,int position,uint64_t now);
ControlMode mode()const{return mode_;}
+53 -1
View File
@@ -1,8 +1,14 @@
#pragma once
#include "lan_input.h"
#include <map>
#include <optional>
namespace ks::lan
{
struct HandoffBlock
{
std::string peer; // Empty for this PC.
int key{};
};
// The physical input source routes directly to the current destination. A
// destination only reports edge crossings; it never relays injected key events.
class InputMesh
@@ -13,7 +19,17 @@ class InputMesh
std::map<std::string,uint64_t> ready;
std::function<bool(const std::string &,InputFrame)> send;
uint64_t activeGeneration{},routeRevision{};
struct Rejection {uint32_t token;uint64_t generation;int key;};
std::map<std::string,Rejection> rejectedPeers;
std::optional<std::pair<std::string,Rejection>> remoteBlock;
InputRouter router;
bool sendActive(InputFrame frame)
{
if(active.empty()||!ready.contains(active)||!send(active,frame))return false;
if(frame.type==InputType::Return&&frame.b>0)
rejectedPeers.insert_or_assign(active,Rejection{frame.token,ready.at(active),frame.b});
return true;
}
std::string neighbor(const std::string &from,int side)const
{
POINT p{};if(from!=local){auto found=positions.find(from);if(found==positions.end())return {};p=found->second;}
@@ -31,10 +47,17 @@ class InputMesh
InputMesh(std::string id,InputEnvironment environment,std::map<std::string,POINT> layout,
std::function<bool(const std::string &,InputFrame)> sender)
:local(std::move(id)),env(std::move(environment)),positions(std::move(layout)),send(std::move(sender)),
router(env,[this](InputFrame f){return !active.empty()&&ready.contains(active)&&send(active,f);},1,true,true){}
router(env,[this](InputFrame f){return sendActive(f);},1,true,true){}
ControlMode mode()const{return router.mode();}
uint64_t revision()const{return router.revision()+routeRevision;}
const std::string &peer()const{return active;}
HandoffBlock handoffBlock()const
{
if(router.blockedKey())return {{},router.blockedKey()};
if(remoteBlock)return {remoteBlock->first,remoteBlock->second.key};
return {};
}
void forgetHeldKeys(){router.forgetHeldKeys();}
void cancel(uint64_t now){router.cancel(now);}
void tick(std::map<std::string,uint64_t> connections,uint64_t now)
{
@@ -44,10 +67,38 @@ class InputMesh
if(connected&&activeGeneration!=ready.at(active)){router.cancel(now,"peer reconnected");activeGeneration=ready.at(active);}
router.tick(connected,now);
}
const auto sameConnection=[this](const std::string &peer,const Rejection &rejection){
auto connection=ready.find(peer);
return connection!=ready.end()&&connection->second==rejection.generation;
};
if(remoteBlock&&!sameConnection(remoteBlock->first,remoteBlock->second))remoteBlock.reset();
const int held=router.blockedKey();
for(auto it=rejectedPeers.begin();it!=rejectedPeers.end();)
{
auto &[peer,rejection]=*it;
if(!sameConnection(peer,rejection)){it=rejectedPeers.erase(it);continue;}
if(held!=rejection.key&&send(peer,{InputType::Return,rejection.token,32768,held?held:HeldInputCleared}))
rejection.key=held;
if(!rejection.key)it=rejectedPeers.erase(it);
else ++it;
}
}
void receive(const std::string &peer,const InputFrame &f,uint64_t now,bool allowEnter=true)
{
if(!ready.contains(peer)||!positions.contains(peer))return;
if(f.type==InputType::Return)
{
const bool held=f.b>0&&f.b<=UnknownHeldInput;
if(remoteBlock&&remoteBlock->first==peer&&remoteBlock->second.token==f.token)
{
// These updates belong to a completed request, never the current owner.
if(f.b==HeldInputCleared)remoteBlock.reset();
else if(held)remoteBlock->second.key=f.b;
return;
}
if(held&&active==peer&&router.mode()==ControlMode::Requesting&&router.sessionToken()==f.token)
remoteBlock=std::pair{peer,Rejection{f.token,ready.at(peer),f.b}};
}
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");
@@ -66,6 +117,7 @@ class InputMesh
router.handoff(f.a,f.b,now);return;
}
router.receive(f,now);
if(router.mode()==ControlMode::Sending||router.mode()==ControlMode::Receiving)remoteBlock.reset();
}
bool keyboard(const KBDLLHOOKSTRUCT &key,bool down,uint64_t now){return router.keyboard(key,down,now);}
bool mouse(UINT message,const MSLLHOOKSTRUCT &mouse,uint64_t now,bool allowEnter=true)
+52 -11
View File
@@ -1,15 +1,53 @@
#pragma once
#include "platform.h"
#include <uiautomation.h>
#include <wrl/client.h>
namespace ks
{
inline bool focusedTextBelongsToWindow(IUIAutomation *automation, IUIAutomationElement *focused, HWND target)
{
using Microsoft::WRL::ComPtr;
DWORD process{};
GetWindowThreadProcessId(target, &process);
int focusedProcess{};
if (!process || FAILED(focused->get_CurrentProcessId(&focusedProcess))) return false;
if (process == static_cast<DWORD>(focusedProcess)) return true;
BOOL hasFocus{}, readOnly = TRUE;
ComPtr<IUIAutomationValuePattern> value;
if (FAILED(focused->get_CurrentHasKeyboardFocus(&hasFocus)) || !hasFocus ||
FAILED(focused->GetCurrentPatternAs(UIA_ValuePatternId, IID_PPV_ARGS(&value))) || !value ||
FAILED(value->get_CurrentIsReadOnly(&readOnly)) || readOnly)
return false;
// WebView2 exposes text through a different process. Its accessibility
// ancestors lead back to a native child window of the foreground app.
ComPtr<IUIAutomationTreeWalker> walker;
if (FAILED(automation->get_RawViewWalker(&walker)) || !walker)
return false;
ComPtr<IUIAutomationElement> element = focused;
for (int depth = 0; element && depth < 32; ++depth)
{
UIA_HWND native{};
if (SUCCEEDED(element->get_CurrentNativeWindowHandle(&native)) && native)
{
const auto hwnd = reinterpret_cast<HWND>(native);
return hwnd == target || IsChild(target, hwnd);
}
ComPtr<IUIAutomationElement> parent;
if (FAILED(walker->GetParentElement(element.Get(), &parent))) return false;
element = std::move(parent);
}
return false;
}
// Read-only UI Automation: never select, move the caret, or touch the clipboard.
class PasteProbe
{
IUIAutomation2 *automation{};
IUIAutomationElement *element{};
IUIAutomationTextPattern *pattern{};
HWND targetWindow{};
static std::optional<std::wstring> rangeText(IUIAutomationTextRange *range)
{
@@ -24,7 +62,7 @@ class PasteProbe
public:
std::wstring status = L"not-requested";
std::optional<std::wstring> precedingCharacter;
PasteProbe(bool enabled, HWND target)
PasteProbe(bool enabled, HWND target) : targetWindow(target)
{
if (!enabled)
return;
@@ -36,17 +74,15 @@ class PasteProbe
automation->put_TransactionTimeout(200);
if (FAILED(automation->GetFocusedElement(&element)) || !element)
return;
if (target)
if (target && GetForegroundWindow() != target)
{
DWORD process{};
GetWindowThreadProcessId(target, &process);
int focusedProcess{};
if (!process || FAILED(element->get_CurrentProcessId(&focusedProcess)) ||
process != static_cast<DWORD>(focusedProcess) || GetForegroundWindow() != target)
{
status = L"focused-control-changed";
return;
}
status = L"focused-window-changed";
return;
}
if (target && !focusedTextBelongsToWindow(automation, element, target))
{
status = L"focused-control-outside-target";
return;
}
BOOL password = TRUE;
if (FAILED(element->get_CurrentIsPassword(&password)) || password)
@@ -95,6 +131,11 @@ class PasteProbe
{
if (!pattern)
return {};
if (targetWindow && GetForegroundWindow() != targetWindow)
{
status = L"focused-window-changed";
return {};
}
if (characters <= 0 || characters > 4096)
{
status = L"readback-size-limit";
+170 -13
View File
@@ -1,4 +1,5 @@
#include "platform.h"
#include "windows_command_line.h"
#include "../vendor/json.hpp"
#include <algorithm>
#include <fstream>
@@ -17,6 +18,7 @@
#include <shldisp.h>
#include <tlhelp32.h>
#include <wincrypt.h>
#include <winhttp.h>
#include <wrl/client.h>
namespace ks
@@ -289,7 +291,7 @@ bool ownsClipboard(HWND window)
return it->second;
});
}
std::wstring processName(HWND window)
std::wstring processImagePath(HWND window)
{
DWORD pid{};
GetWindowThreadProcessId(window, &pid);
@@ -300,7 +302,38 @@ std::wstring processName(HWND window)
DWORD n = 32768;
BOOL ok = QueryFullProcessImageNameW(h, 0, path, &n);
CloseHandle(h);
return ok ? std::filesystem::path(std::wstring(path, n)).stem().wstring() : L"";
return ok ? std::wstring(path, n) : L"";
}
std::wstring processName(HWND window)
{
return std::filesystem::path(processImagePath(window)).stem().wstring();
}
std::wstring shortcutTextControlClass(HWND window)
{
wchar_t name[256]{};
if (!GetClassNameW(window, name, std::size(name))) return {};
const auto kind = lower(name);
if ((kind != L"edit" && !kind.starts_with(L"richedit")) || !IsWindowEnabled(window) ||
(GetWindowLongPtrW(window, GWL_STYLE) & (ES_READONLY | ES_PASSWORD))) return {};
return name;
}
HWND findShortcutTextControl(HWND window, std::wstring_view controlClass, int controlId)
{
if (!window) return nullptr;
struct Search { std::wstring_view kind; int id; HWND target{}; } search{controlClass, controlId};
EnumChildWindows(window, [](HWND candidate, LPARAM context) -> BOOL {
auto &state = *reinterpret_cast<Search *>(context);
if (!IsWindowVisible(candidate) || GetDlgCtrlID(candidate) != state.id || shortcutTextControlClass(candidate) != state.kind)
return TRUE;
if (state.target)
{
state.target = nullptr;
return FALSE;
}
state.target = candidate;
return TRUE;
}, reinterpret_cast<LPARAM>(&search));
return search.target;
}
std::wstring mouseApplicationName(HWND window)
{
@@ -317,7 +350,9 @@ std::wstring mouseApplicationName(HWND window)
}, reinterpret_cast<LPARAM>(&hosted));
return hosted.empty() ? name : hosted;
}
bool launchThroughExplorer(const std::wstring &path)
namespace
{
bool shellOpenThroughExplorer(const std::wstring &target, const std::wstring &arguments, const std::wstring &directory)
{
HANDLE token{};
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return false;
@@ -330,7 +365,9 @@ bool launchThroughExplorer(const std::wstring &path)
{
SHELLEXECUTEINFOW launch{sizeof(launch)};
launch.fMask = SEE_MASK_FLAG_NO_UI;
launch.lpFile = path.c_str();
launch.lpFile = target.c_str();
launch.lpParameters = arguments.empty() ? nullptr : arguments.c_str();
launch.lpDirectory = directory.empty() ? nullptr : directory.c_str();
launch.nShow = SW_SHOWNORMAL;
return ShellExecuteExW(&launch) != FALSE;
}
@@ -361,8 +398,12 @@ bool launchThroughExplorer(const std::wstring &path)
hr = browser->QueryActiveShellView(&viewRaw);
std::unique_ptr<IShellView, decltype(release)> view(viewRaw, release);
if (FAILED(hr) || !view) return false;
IDispatch *backgroundRaw{};
hr = view->GetItemObject(SVGIO_BACKGROUND, IID_IDispatch, reinterpret_cast<void **>(&backgroundRaw));
std::unique_ptr<IDispatch, decltype(release)> background(backgroundRaw, release);
if (FAILED(hr) || !background) return false;
IShellFolderViewDual *folderRaw{};
hr = view->GetItemObject(SVGIO_BACKGROUND, IID_IShellFolderViewDual, reinterpret_cast<void **>(&folderRaw));
hr = background->QueryInterface(IID_IShellFolderViewDual, reinterpret_cast<void **>(&folderRaw));
std::unique_ptr<IShellFolderViewDual, decltype(release)> folder(folderRaw, release);
if (FAILED(hr) || !folder) return false;
IDispatch *applicationRaw{};
@@ -373,12 +414,126 @@ bool launchThroughExplorer(const std::wstring &path)
hr = application->QueryInterface(IID_IShellDispatch2, reinterpret_cast<void **>(&shellRaw));
std::unique_ptr<IShellDispatch2, decltype(release)> shell(shellRaw, release);
if (FAILED(hr) || !shell) return false;
BSTR executable = SysAllocString(path.c_str());
if (!executable) return false;
hr = shell->ShellExecute(executable, empty, empty, empty, empty);
SysFreeString(executable);
std::unique_ptr<OLECHAR, decltype(&SysFreeString)> executable(SysAllocString(target.c_str()), SysFreeString);
std::unique_ptr<OLECHAR, decltype(&SysFreeString)> workingDirectory(SysAllocString(directory.c_str()), SysFreeString);
std::unique_ptr<OLECHAR, decltype(&SysFreeString)> parameters(SysAllocString(arguments.c_str()), SysFreeString);
if (!executable || !workingDirectory || !parameters) return false;
VARIANT location{}, shown{}, args{};
location.vt = VT_BSTR;
location.bstrVal = workingDirectory.get();
shown.vt = VT_I4;
shown.lVal = SW_SHOWNORMAL;
args.vt = VT_BSTR;
args.bstrVal = parameters.get();
hr = shell->ShellExecute(executable.get(), args, location, empty, shown);
return SUCCEEDED(hr);
}
std::filesystem::path shortcutKnownFolder(REFKNOWNFOLDERID folder)
{
PWSTR raw{};
if (FAILED(SHGetKnownFolderPath(folder, 0, nullptr, &raw))) return {};
std::unique_ptr<wchar_t, decltype(&CoTaskMemFree)> path(raw, CoTaskMemFree);
return std::filesystem::path(path.get());
}
std::filesystem::path chromeUserData()
{
const auto local = shortcutKnownFolder(FOLDERID_LocalAppData);
return local.empty() ? local : local / L"Google/Chrome/User Data";
}
std::filesystem::path chromeExecutable()
{
constexpr wchar_t key[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe";
std::error_code ec;
for (const auto hive : {HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE})
{
wchar_t path[32768]{};
DWORD bytes = sizeof(path);
if (RegGetValueW(hive, key, nullptr, RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ, nullptr, path, &bytes) == ERROR_SUCCESS)
{
const std::filesystem::path candidate(path);
if (candidate.is_absolute() && lower(candidate.filename().wstring()) == L"chrome.exe" &&
std::filesystem::is_regular_file(candidate, ec)) return candidate;
}
}
for (const auto *folder : {&FOLDERID_LocalAppData, &FOLDERID_ProgramFiles, &FOLDERID_ProgramFilesX86})
{
const auto base = shortcutKnownFolder(*folder);
if (base.empty()) continue;
const auto candidate = (base / L"Google/Chrome/Application/chrome.exe").make_preferred();
if (std::filesystem::is_regular_file(candidate, ec)) return candidate;
}
return {};
}
} // namespace
bool launchThroughExplorer(const std::wstring &path)
{
return shellOpenThroughExplorer(path, {}, std::filesystem::path(path).parent_path().wstring());
}
bool validShortcutUrl(const std::wstring &url)
{
if (url.empty() || url.size() > 16384 || std::any_of(url.begin(), url.end(), [](wchar_t ch) {
return ch <= L' ' || ch == L'\x7f' || ch == L'\\' || ch == L'"';
})) return false;
URL_COMPONENTSW parts{};
parts.dwStructSize = sizeof(parts);
parts.dwHostNameLength = static_cast<DWORD>(-1);
return WinHttpCrackUrl(url.c_str(), static_cast<DWORD>(url.size()), 0, &parts) &&
(parts.nScheme == INTERNET_SCHEME_HTTP || parts.nScheme == INTERNET_SCHEME_HTTPS) && parts.dwHostNameLength;
}
bool validChromeProfileName(std::wstring_view name)
{
return !name.empty() && name.size() <= 255 && name.back() != L'.' && name.back() != L' ' &&
name.find_first_of(L"<>:\"/\\|?*") == name.npos && std::none_of(name.begin(), name.end(), [](wchar_t ch) {
return ch < L' ';
});
}
std::vector<std::pair<std::wstring, std::wstring>> chromeShortcutProfiles()
{
std::vector<std::pair<std::wstring, std::wstring>> profiles;
const auto root = chromeUserData();
if (root.empty()) return profiles;
try
{
const auto state = nlohmann::json::parse(readFile(root / L"Local State", 16 * 1024 * 1024));
const auto &cache = state.at("profile").at("info_cache");
if (!cache.is_object()) return profiles;
for (const auto &[id, entry] : cache.items())
{
const auto directory = wide(id);
std::error_code ec;
if (!validChromeProfileName(directory) || !entry.is_object() ||
!std::filesystem::is_directory(root / directory, ec)) continue;
auto display = entry.find("name");
const auto name = display != entry.end() && display->is_string() ? wide(display->get<std::string>()) : directory;
profiles.emplace_back(directory, name.empty() ? directory : name);
}
}
catch (const std::exception &) {} // Chrome may be uninstalled or may be rewriting Local State.
return profiles;
}
bool openShortcutUrl(const CustomShortcut &rule)
{
if (rule.browser == ShortcutBrowser::Default) return shellOpenThroughExplorer(rule.url, {}, {});
const auto path = rule.browser == ShortcutBrowser::Chrome ? chromeExecutable() : std::filesystem::path(rule.executable);
if (path.empty()) return false;
auto arguments = quoteWindowsArgument(rule.url);
if (rule.browser == ShortcutBrowser::Chrome && !rule.chromeProfile.empty())
{
const auto root = chromeUserData();
std::error_code ec;
if (root.empty() || !std::filesystem::is_directory(root / rule.chromeProfile, ec)) return false;
arguments = quoteWindowsArgument(L"--profile-directory=" + rule.chromeProfile) + L" " + arguments;
}
return shellOpenThroughExplorer(path.wstring(), arguments, path.parent_path().wstring());
}
bool clipboardHasImage()
{
return IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
@@ -676,9 +831,10 @@ bool needsSelectionDelay(HWND target)
{
const auto name = lower(processName(target));
return name == L"ms-teams" || name == L"msedgewebview2" ||
name == L"chrome" || name == L"msedge" || name == L"chatgpt" || name == L"codex";
name == L"chrome" || name == L"msedge" || name == L"chatgpt" ||
name == L"codex" || name == L"claude";
}
bool selectPrevious(size_t count, const std::function<bool()> &valid)
bool selectPrevious(size_t count, const std::function<bool()> &valid, bool forcePacing)
{
if (count > 100000)
return false;
@@ -686,9 +842,10 @@ bool selectPrevious(size_t count, const std::function<bool()> &valid)
// Shift+Left events can all use the same caret position and select only one
// character. Give each change time to settle before sending the next one.
const auto target = GetForegroundWindow();
const bool paced = forcePacing || needsSelectionDelay(target);
diagnosticEvent(L"SelectPrevious requested=" + std::to_wstring(count) +
L" mode=" + (needsSelectionDelay(target) ? std::wstring(L"paced-25ms") : std::wstring(L"batch")));
if (needsSelectionDelay(target))
(paced ? L" mode=paced-25ms" : L" mode=batch"));
if (paced)
{
for (size_t i = 0; i < count; ++i)
{
+8 -1
View File
@@ -49,8 +49,15 @@ bool ownsClipboard(HWND);
bool webViewDescendant(DWORD owner, DWORD host,
const std::function<std::optional<std::pair<DWORD, std::wstring>>(DWORD)> &read);
std::wstring processName(HWND);
std::wstring processImagePath(HWND);
std::wstring shortcutTextControlClass(HWND);
HWND findShortcutTextControl(HWND, std::wstring_view controlClass, int controlId);
std::wstring mouseApplicationName(HWND);
bool launchThroughExplorer(const std::wstring &);
bool validShortcutUrl(const std::wstring &);
bool validChromeProfileName(std::wstring_view);
std::vector<std::pair<std::wstring, std::wstring>> chromeShortcutProfiles();
bool openShortcutUrl(const CustomShortcut &);
enum class ClipboardRead { All, Selection, WithoutImages };
bool clipboardHasImage();
Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024,
@@ -75,7 +82,7 @@ ULONG_PTR inputMarker();
bool ownKeyboardInput(const KBDLLHOOKSTRUCT &);
INPUT keyboardInput(WORD key, DWORD flags = 0);
bool needsSelectionDelay(HWND);
bool selectPrevious(size_t count, const std::function<bool()> &valid);
bool selectPrevious(size_t count, const std::function<bool()> &valid, bool forcePacing = false);
bool modifiersReleased();
void releaseModifiers();
std::filesystem::path dataDirectory();
+95
View File
@@ -207,6 +207,36 @@ void validateSettings(const Settings &s)
std::vector<std::wstring> keys{s.toggle, s.casing, s.translit, s.undo, s.clipboard, s.screenshot};
if (s.filesHotkey) keys.push_back(*s.filesHotkey);
keys.insert(keys.end(), s.direct.begin(), s.direct.end());
if (s.customShortcuts.size() > 100)
throw std::runtime_error("You can configure up to 100 custom shortcuts.");
for (const auto &rule : s.customShortcuts)
{
if (rule.name.size() > 128 || rule.name.find_first_not_of(L" \t\r\n") == std::wstring::npos)
throw std::runtime_error("Enter a name of up to 128 characters for the custom shortcut.");
const auto key = Hotkey::parse(rule.shortcut);
if (!key || !key->key)
throw std::runtime_error("Enter a key combination for the custom shortcut.");
if (rule.action != CustomShortcutAction::OpenUrl || rule.browser == ShortcutBrowser::Other)
{
const std::filesystem::path path(rule.executable);
if (rule.executable.size() > 32700 || rule.executable.find_first_of(L"\r\n\"") != std::wstring::npos ||
rule.executable.find(L'\0') != std::wstring::npos || !path.is_absolute() || lower(path.extension().wstring()) != L".exe")
throw std::runtime_error("Choose a program executable (.exe) for the custom shortcut.");
}
if (rule.action == CustomShortcutAction::OpenUrl)
{
if (!validShortcutUrl(rule.url)) throw std::runtime_error("Enter a valid HTTP or HTTPS URL.");
if (rule.browser != ShortcutBrowser::Default && rule.browser != ShortcutBrowser::Chrome && rule.browser != ShortcutBrowser::Other)
throw std::runtime_error("Choose a browser for the URL shortcut.");
if (rule.browser == ShortcutBrowser::Chrome && !rule.chromeProfile.empty() && !validChromeProfileName(rule.chromeProfile))
throw std::runtime_error("Choose a valid Chrome profile.");
}
if (rule.action == CustomShortcutAction::SendText &&
(rule.controlClass.empty() || rule.controlClass.size() > 255 || rule.text.empty() ||
rule.text.size() > 32768 || rule.text.find(L'\0') != std::wstring::npos))
throw std::runtime_error("Choose a target text field and enter up to 32,768 characters to insert.");
if (rule.enabled) keys.push_back(rule.shortcut);
}
for (auto &text : keys)
{
auto key = Hotkey::parse(text);
@@ -373,6 +403,40 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
s.clipboard = str(j, "clipboardHotkey", s.clipboard);
s.screenshot = str(j, "screenshotHotkey", s.screenshot);
if (j.contains("filesHotkey")) s.filesHotkey = wide(j.at("filesHotkey").get<std::string>());
if (j.contains("customShortcuts"))
{
const auto &rules = j.at("customShortcuts");
if (!rules.is_array()) throw std::runtime_error("Invalid custom shortcut list.");
for (const auto &rule : rules)
{
const auto action = rule.value("action", "launchApp");
CustomShortcut shortcut{str(rule, "name", L""), str(rule, "shortcut", L""),
str(rule, "executable", L""), rule.value("enabled", true)};
if (action == "sendText")
{
shortcut.action = CustomShortcutAction::SendText;
shortcut.controlClass = str(rule, "controlClass", L"");
shortcut.text = str(rule, "text", L"");
shortcut.controlId = rule.value("controlId", 0);
}
else if (action == "openUrl")
{
shortcut.action = CustomShortcutAction::OpenUrl;
shortcut.url = str(rule, "url", L"");
const auto browser = rule.value("browser", "default");
if (browser == "chrome")
{
shortcut.browser = ShortcutBrowser::Chrome;
shortcut.chromeProfile = str(rule, "chromeProfile", L"");
}
else if (browser == "other") shortcut.browser = ShortcutBrowser::Other;
else if (browser != "default") throw std::runtime_error("Unknown shortcut browser.");
}
else if (action == "launchApp") shortcut.newInstance = rule.value("newInstance", false);
else throw std::runtime_error("Unknown custom shortcut action.");
s.customShortcuts.push_back(std::move(shortcut));
}
}
s.screenshotAutoOpenEditor = j.value("screenshotAutoOpenEditor", false);
if (j.contains("layouts"))
{
@@ -533,6 +597,37 @@ Bytes encodeSettings(const Settings &s)
{"screenshotHotkey", utf8(s.screenshot)},
{"screenshotAutoOpenEditor", s.screenshotAutoOpenEditor}};
if (s.filesHotkey) j["filesHotkey"] = utf8(*s.filesHotkey);
if (!s.customShortcuts.empty())
{
auto &rules = j["customShortcuts"] = Json::array();
for (const auto &rule : s.customShortcuts)
{
rules.push_back({{"name", utf8(rule.name)}, {"shortcut", utf8(rule.shortcut)},
{"executable", utf8(rule.executable)}, {"enabled", rule.enabled}});
auto &item = rules.back();
if (rule.action == CustomShortcutAction::SendText)
{
item["action"] = "sendText";
item["controlClass"] = utf8(rule.controlClass);
item["controlId"] = rule.controlId;
item["text"] = utf8(rule.text);
}
else if (rule.action == CustomShortcutAction::OpenUrl)
{
item["action"] = "openUrl";
item["url"] = utf8(rule.url);
item["browser"] = rule.browser == ShortcutBrowser::Chrome ? "chrome" :
rule.browser == ShortcutBrowser::Other ? "other" : "default";
if (rule.browser == ShortcutBrowser::Chrome && !rule.chromeProfile.empty())
item["chromeProfile"] = utf8(rule.chromeProfile);
}
else
{
item["action"] = "launchApp";
item["newInstance"] = rule.newInstance;
}
}
}
j["layouts"] = Json::array();
j["appLanguageSets"] = Json::object();
for (const auto &[name, set] : s.appLanguageSets)
+1
View File
@@ -313,6 +313,7 @@ void preserveMissingSettings(Json &profile, const Json &fallback)
Bytes sharedSyncSettings(const Settings &s)
{
auto j = parse(encodeSettings(s));
j.erase("customShortcuts"); // Executable paths and target control identifiers belong to this PC.
// Windows may enumerate the same installed layouts in a different order on
// another PC. Binding order is not user intent (unlike the layout cycle).
auto &bindings = j["layoutHotkeys"];
+83 -2
View File
@@ -481,6 +481,62 @@ HWND makeWindow(App &app, const wchar_t *cls, const wchar_t *title, WNDPROC proc
SetPropW(w, L"Dpi", (HANDLE)(UINT_PTR)GetDpiForWindow(w));
return w;
}
#ifndef KS_RESIDENT_APP
constexpr int ModalFooterHeight = 50;
LRESULT CALLBACK settingsModalPaletteProc(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR data)
{
auto *palette = reinterpret_cast<WindowPalette *>(data);
if (msg == WM_ERASEBKGND)
{
const auto dc = reinterpret_cast<HDC>(wp);
RECT area{};
GetClientRect(w, &area);
FillRect(dc, &area, GetSysColorBrush(COLOR_WINDOW));
area.top = std::max(0L, area.bottom - scale(w, ModalFooterHeight));
FillRect(dc, &area, palette->brush());
fillSurface(dc, {area.left, area.top, area.right, area.top + 1}, palette->edge());
return 1;
}
if (msg == WM_CTLCOLORSTATIC)
{
const auto dc = reinterpret_cast<HDC>(wp);
SetBkColor(dc, GetSysColor(COLOR_WINDOW));
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_WINDOW));
}
if (msg == WM_SYSCOLORCHANGE || msg == WM_THEMECHANGED || msg == WM_SETTINGCHANGE || msg == WM_DWMCOLORIZATIONCOLORCHANGED)
{
palette->refresh();
RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN);
}
if (msg == WM_NCDESTROY)
{
RemoveWindowSubclass(w, settingsModalPaletteProc, id);
delete palette;
}
return DefSubclassProc(w, msg, wp, lp);
}
HWND makeSettingsModal(App &app, HWND owner, const wchar_t *cls, const wchar_t *title, WNDPROC proc, int width, int height)
{
auto palette = std::make_unique<WindowPalette>();
palette->refresh();
const auto w = makeWindow(app, cls, title, proc, width, height, 0, false, owner);
windowLayoutState(w)->fixedClient = true;
if (SetWindowSubclass(w, settingsModalPaletteProc, 1, reinterpret_cast<DWORD_PTR>(palette.get()))) palette.release();
return w;
}
void settingsModalActions(HWND w, int width, int height, const wchar_t *accept, int extraId = 0, const wchar_t *extra = nullptr)
{
constexpr int margin = 22, acceptWidth = 120, cancelWidth = 90, gap = 12;
const int y = height - (ModalFooterHeight + 28) / 2;
const int x = width - margin - acceptWidth;
if (extra) button(w, extra, extraId, margin, y, cancelWidth);
button(w, L"Cancel", IDCANCEL, x - gap - cancelWidth, y, cancelWidth);
control(w, L"BUTTON", accept, WS_TABSTOP | WS_GROUP | BS_DEFPUSHBUTTON, IDOK, x, y, acceptWidth, 28);
}
#endif
void resizeForDpi(HWND w, WPARAM wp, LPARAM lp)
{
// Creation may send WM_DPICHANGED before controls and the original font exist.
@@ -1211,6 +1267,8 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
constexpr int LanguagesPage = 1, ShortcutsPage = 2, ClipboardPage = 3, SnippetsPage = 4, MousePage = 5;
constexpr int ExceptionsPage = 13, PersonalDictionariesPage = 14, WordBoundariesPage = 15, SnippetMacros = 320;
constexpr int CustomReplacementsPage = 16, ChatLanguagesPage = 20;
constexpr int CustomShortcutsPage = 21;
constexpr int CustomShortcutList = 780, CustomShortcutAdd = 781, CustomShortcutEdit = 782;
constexpr int ChatContacts = 710, ChatLayouts = 711, ChatProfileStatus = 712, ChatRemoveProfile = 713, ChatSearch = 714;
constexpr int ClipboardExcludedApps = 243, ClipboardAppName = 244, ClipboardAddApp = 245,
ClipboardRemoveApp = 246, ClipboardAppPicker = 247;
@@ -1256,6 +1314,7 @@ constexpr struct SettingsSection
{"google-drive", L"Google Drive", L"Synchronize settings across PCs or manage manual backups.", SyncPage},
{"ocr", L"Image text recognition", L"Choose Windows OCR or Tesseract. Recognition runs on this computer.", ClipboardPage},
{"chat-languages", L"Languages for a chat", L"Choose which keyboard layouts to cycle through in a chat.", LanguagesPage},
{"custom-shortcuts", L"Custom shortcuts", L"Assign global keyboard shortcuts to actions in other apps.", ShortcutsPage},
};
constexpr wchar_t SettingsWindowFile[] = L"configurator-window.json";
struct SettingsWindowState
@@ -1399,6 +1458,7 @@ bool mergeSnippetDraft(HWND, SnippetView *, Settings &);
void refreshSnippetDraft(HWND, SnippetView *);
void fillSnippets(HWND, SnippetView *);
void updateSettingsState(HWND w, SettingsView *v);
Settings collectSettings(SettingsView *v, std::vector<CustomShortcut> *rules = nullptr);
bool matchesSettingsSearch(const SettingsView &v, const std::wstring &text)
{
if (!v.searching) return false;
@@ -1868,6 +1928,15 @@ void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height)
}
layout.height = fitSettingsColumns(layout, page.first, page.end, available, grid);
const int extra = height * 96 / static_cast<int>(dpi) - layout.height;
if (v.selectedPage == CustomShortcutsPage)
{
auto &[list, bounds] = layout.controls[page.end - 1];
const int columnWidth = scale(pane, bounds.right - bounds.left) -
GetSystemMetricsForDpi(SM_CXVSCROLL, dpi) - 2;
ListView_SetColumnWidth(list, 0, columnWidth * 36 / 100);
ListView_SetColumnWidth(list, 1, columnWidth * 38 / 100);
ListView_SetColumnWidth(list, 2, columnWidth - columnWidth * 36 / 100 - columnWidth * 38 / 100);
}
if (v.selectedPage == ChatLanguagesPage)
stretchSettingsEditors(layout, page.first, page.end, std::min(extra, 160), {ChatContacts, ChatLayouts}, true);
if (v.selectedPage == SnippetsPage)
@@ -2424,6 +2493,7 @@ void createChatLanguages(HWND pane)
}
#include "ui_app_languages.inl"
#include "ui_mouse_buttons.inl"
#include "ui_custom_shortcuts.inl"
void resizeSettingsForDpi(HWND w, int previousDpi, int nextDpi)
{
auto &v = *reinterpret_cast<SettingsView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
@@ -2544,6 +2614,7 @@ void fillSettings(HWND root, SettingsView *v)
value(w, 214, s.clipboard);
value(w, 215, s.screenshot);
value(w, 216, s.filesHotkey.value_or(L""));
fillCustomShortcuts(*v);
value(w, 240, std::to_wstring(s.maxItems));
value(w, 241, std::to_wstring(s.maxMiB));
value(w, 242, std::to_wstring(s.maxImageMiB));
@@ -2578,11 +2649,12 @@ int integer(HWND w, int id)
throw std::runtime_error("Enter a whole number for history limits");
return v;
}
Settings collectSettings(SettingsView *v)
Settings collectSettings(SettingsView *v, std::vector<CustomShortcut> *rules)
{
HWND w = v->viewport;
collectLayout(v);
auto s = v->draft;
if (rules) s.customShortcuts = std::move(*rules);
s.recent = checked(w, 201);
s.switchLayout = checked(w, 202);
s.writeLog = checked(w, 208);
@@ -2817,7 +2889,7 @@ void updateSettingsState(HWND w, SettingsView *v)
EnableWindow(GetDlgItem(w, SettingsApply), dirty);
const auto closeLabel = dirty ? L"&Cancel" : L"&Close";
if (value(w, IDCANCEL) != closeLabel) value(w, IDCANCEL, closeLabel);
EnableWindow(GetDlgItem(w, IDOK), dirty || (v->app->settings.autostart && !isLocalBuild()));
EnableWindow(GetDlgItem(w, IDOK), dirty);
const wchar_t *text = changed ? L"Unsaved settings — click Apply or Save." :
snippetsChanged ? L"Unsaved snippets — click Apply or Save." : L"No unsaved settings.";
if (value(w, SettingsStatus) != text) value(w, SettingsStatus, text);
@@ -2974,6 +3046,7 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (LOWORD(wp) != WA_INACTIVE) updateSettingsState(w, v);
break;
case WM_NOTIFY:
if (handleCustomShortcutList(w, *v, *reinterpret_cast<NMHDR *>(lp))) return 0;
if (reinterpret_cast<const NMHDR *>(lp)->idFrom == ChatContacts &&
reinterpret_cast<const NMHDR *>(lp)->code == LVN_ITEMCHANGED)
{
@@ -3066,6 +3139,11 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
SettingsStateRefresh refresh{w};
HWND pane = v->viewport;
if ((id == CustomShortcutAdd || id == CustomShortcutEdit) && HIWORD(wp) == BN_CLICKED)
{
showCustomShortcut(w, *v, id == CustomShortcutEdit);
return 0;
}
if ((id == OcrUseTesseract && HIWORD(wp) == BN_CLICKED) ||
((id == OcrExecutable || id == OcrLanguages) && HIWORD(wp) == EN_CHANGE))
{
@@ -4062,6 +4140,9 @@ void showSettings(App &app, bool visible)
createChatLanguages(pane);
page();
createCustomShortcuts(pane);
page();
v->splitter = control(w, L"STATIC", L"Resize navigation pane", SS_NOTIFY | WS_TABSTOP,
SettingsSplitter, 0, 0, 0, 0);
SetWindowSubclass(v->splitter, settingsSplitterProc, 1, reinterpret_cast<DWORD_PTR>(v));
+10 -2
View File
@@ -75,9 +75,17 @@ HWND appPickerTarget(HWND button, LPARAM position)
{
POINT point{(short)LOWORD(position), (short)HIWORD(position)};
ClientToScreen(button, &point);
auto target = GetAncestor(WindowFromPoint(point), GA_ROOT);
auto child = WindowFromPoint(point);
auto target = GetAncestor(child, GA_ROOT);
auto dialog = GetParent(button);
return target && target != dialog && target != GetWindow(dialog, GW_OWNER) ? target : nullptr;
if (!target || target == dialog || target == GetWindow(dialog, GW_OWNER)) return nullptr;
if (!GetPropW(button, L"PickShortcutControl")) return target;
while (child && child != target)
{
if (!shortcutTextControlClass(child).empty()) return child;
child = GetParent(child);
}
return nullptr;
}
void updatePickerOutline(HWND dialog, HWND &outline, HWND target)
{
+362
View File
@@ -0,0 +1,362 @@
constexpr int RuleName = 783, RuleHotkey = 784, RuleExecutable = 785, RuleBrowse = 786;
constexpr int RuleReuseWindow = 787, RuleNewInstance = 788, RuleRemove = 789;
constexpr int RuleAction = 790, RuleControl = 791, RuleText = 792, RuleModeLabel = 793, RuleTextLabel = 794;
constexpr int RulePickerHelp = 795;
constexpr int RuleProgramLabel = 796, RuleUrl = 797, RuleUrlLabel = 798, RuleBrowser = 799, RuleBrowserLabel = 800;
constexpr int RuleChromeProfile = 801, RuleChromeProfileLabel = 802, RuleBrowserPath = 803,
RuleBrowserBrowse = 804, RuleBrowserPathLabel = 805;
constexpr int ShortcutDialogWidth = 620, ShortcutDialogHeight = 425;
void fillCustomShortcuts(SettingsView &view, int selected = -1)
{
const auto list = GetDlgItem(view.viewport, CustomShortcutList);
const bool filling = std::exchange(view.filling, true);
ListView_DeleteAllItems(list);
int row = 0;
for (const auto &rule : view.draft.customShortcuts)
{
LVITEMW item{LVIF_TEXT};
item.iItem = row;
item.pszText = const_cast<wchar_t *>(rule.name.c_str());
ListView_InsertItem(list, &item);
const wchar_t *action = rule.action == CustomShortcutAction::OpenUrl ? L"Open URL" :
rule.action == CustomShortcutAction::SendText ? L"Send text to app" :
rule.newInstance ? L"Launch new instance" : L"Activate last used or launch";
ListView_SetItemText(list, row, 1, const_cast<wchar_t *>(action));
ListView_SetItemText(list, row, 2, const_cast<wchar_t *>(rule.shortcut.c_str()));
ListView_SetCheckState(list, row, rule.enabled);
++row;
}
if (selected >= 0 && selected < row)
{
ListView_SetItemState(list, selected, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
ListView_EnsureVisible(list, selected, FALSE);
}
EnableWindow(GetDlgItem(view.viewport, CustomShortcutEdit), selected >= 0 && selected < row);
view.filling = filling;
}
struct CustomShortcutEditor
{
SettingsView &view;
int row;
std::optional<CustomShortcut> previous;
HWND pickerOutline{};
std::wstring controlClass;
std::wstring targetExecutable;
std::wstring launchExecutable;
int controlId = 0;
CustomShortcutAction action = CustomShortcutAction::LaunchApp;
std::vector<std::pair<std::wstring, std::wstring>> chromeProfiles;
bool profilesLoaded = false;
};
void stageCustomShortcuts(SettingsView &view, std::vector<CustomShortcut> rules)
{
auto proposed = collectSettings(&view, &rules);
view.draft.customShortcuts = std::move(proposed.customShortcuts);
}
CustomShortcutAction selectedShortcutAction(HWND w)
{
return static_cast<CustomShortcutAction>(SendDlgItemMessageW(w, RuleAction, CB_GETCURSEL, 0, 0));
}
ShortcutBrowser selectedShortcutBrowser(HWND w)
{
return static_cast<ShortcutBrowser>(SendDlgItemMessageW(w, RuleBrowser, CB_GETCURSEL, 0, 0));
}
void refreshCustomShortcutEditor(HWND w, CustomShortcutEditor &editor)
{
const bool sendsText = editor.action == CustomShortcutAction::SendText;
const bool opensUrl = editor.action == CustomShortcutAction::OpenUrl;
const bool chrome = opensUrl && selectedShortcutBrowser(w) == ShortcutBrowser::Chrome;
const bool other = opensUrl && selectedShortcutBrowser(w) == ShortcutBrowser::Other;
const auto picker = GetDlgItem(w, AppWindowPickerIcon);
if (sendsText) SetPropW(picker, L"PickShortcutControl", reinterpret_cast<HANDLE>(1));
else RemovePropW(picker, L"PickShortcutControl");
for (const int id : {RuleProgramLabel, RuleExecutable, AppWindowPickerIcon, RulePickerHelp})
ShowWindow(GetDlgItem(w, id), opensUrl ? SW_HIDE : SW_SHOWNA);
for (const int id : {RuleControl, RuleTextLabel, RuleText}) ShowWindow(GetDlgItem(w, id), sendsText ? SW_SHOWNA : SW_HIDE);
for (const int id : {RuleBrowse, RuleModeLabel, RuleReuseWindow, RuleNewInstance})
ShowWindow(GetDlgItem(w, id), sendsText || opensUrl ? SW_HIDE : SW_SHOWNA);
for (const int id : {RuleUrl, RuleUrlLabel, RuleBrowser, RuleBrowserLabel})
ShowWindow(GetDlgItem(w, id), opensUrl ? SW_SHOWNA : SW_HIDE);
for (const int id : {RuleChromeProfile, RuleChromeProfileLabel})
ShowWindow(GetDlgItem(w, id), chrome ? SW_SHOWNA : SW_HIDE);
for (const int id : {RuleBrowserPath, RuleBrowserBrowse, RuleBrowserPathLabel})
ShowWindow(GetDlgItem(w, id), other ? SW_SHOWNA : SW_HIDE);
const auto browser = GetDlgItem(w, RuleBrowser);
for (auto &[control, bounds] : windowLayoutState(w)->controls)
if (control == browser) bounds.right = chrome ? 298 : 598;
arrangeWindow(w);
if (chrome && !editor.profilesLoaded)
{
editor.profilesLoaded = true;
editor.chromeProfiles = chromeShortcutProfiles();
const auto saved = editor.previous ? editor.previous->chromeProfile : std::wstring{};
if (!saved.empty() && std::none_of(editor.chromeProfiles.begin(), editor.chromeProfiles.end(),
[&](const auto &profile) { return profile.first == saved; }))
editor.chromeProfiles.emplace_back(saved, saved + L" (unavailable)");
int selected = 0, index = 0;
for (const auto &[directory, name] : editor.chromeProfiles)
{
const bool duplicate = std::count_if(editor.chromeProfiles.begin(), editor.chromeProfiles.end(),
[&](const auto &profile) { return profile.second == name; }) > 1;
const auto caption = duplicate ? name + L" (" + directory + L")" : name;
SendDlgItemMessageW(w, RuleChromeProfile, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(caption.c_str()));
++index;
if (directory == saved) selected = index;
}
SendDlgItemMessageW(w, RuleChromeProfile, CB_SETCURSEL, selected, 0);
}
SendDlgItemMessageW(w, RuleExecutable, EM_SETREADONLY, sendsText, 0);
value(w, RulePickerHelp, sendsText ? L"Drag the crosshair onto the text field you want to fill." :
L"Drag the crosshair to an open window to select its program.");
}
LRESULT CALLBACK customShortcutProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
auto *editor = reinterpret_cast<CustomShortcutEditor *>(GetWindowLongPtrW(w, GWLP_USERDATA));
if (!editor) return DefWindowProcW(w, msg, wp, lp);
const HWND owner = GetWindow(w, GW_OWNER);
try
{
if (msg == AppWindowPicked)
{
if (lp == 1)
{
const auto picked = reinterpret_cast<HWND>(wp);
const auto root = GetAncestor(picked, GA_ROOT);
const auto path = processImagePath(root);
if (editor->action == CustomShortcutAction::SendText)
{
const auto kind = shortcutTextControlClass(picked);
const auto id = GetDlgCtrlID(picked);
if (kind.empty() || path.empty() || findShortcutTextControl(root, kind, id) != picked)
throw std::runtime_error("Pick a uniquely identifiable, editable Windows text field.");
editor->controlClass = kind;
editor->controlId = id;
editor->targetExecutable = path;
value(w, RuleControl, L"Target control: " + kind + L" (ID " + std::to_wstring(id) + L")");
}
if (path.empty()) throw std::runtime_error("Drop the crosshair onto a program window.");
value(w, RuleExecutable, path);
}
return 0;
}
if (msg == WM_DRAWITEM && wp == AppWindowPickerIcon)
{
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if (msg == WM_COMMAND)
{
const auto id = LOWORD(wp);
if (id == RuleAction && HIWORD(wp) == CBN_SELCHANGE)
{
if (editor->action == CustomShortcutAction::LaunchApp) editor->launchExecutable = value(w, RuleExecutable);
editor->action = selectedShortcutAction(w);
refreshCustomShortcutEditor(w, *editor);
value(w, RuleExecutable, editor->action == CustomShortcutAction::SendText ? editor->targetExecutable : editor->launchExecutable);
return 0;
}
if (id == RuleBrowser && HIWORD(wp) == CBN_SELCHANGE)
{
refreshCustomShortcutEditor(w, *editor);
return 0;
}
if (id == RuleBrowse || id == RuleBrowserBrowse)
{
const auto path = chooseApplicationFile(w, L"Programs (*.exe)\0*.exe\0");
if (!path.empty()) value(w, id == RuleBrowse ? RuleExecutable : RuleBrowserPath, path);
return 0;
}
if (id == IDOK || id == RuleRemove)
{
auto rules = editor->view.draft.customShortcuts;
const int row = editor->row;
if (row >= 0 && (static_cast<size_t>(row) >= rules.size() || rules[row] != editor->previous))
throw std::runtime_error("This shortcut changed while you were editing. Close and reopen the editor.");
if (id == RuleRemove)
rules.erase(rules.begin() + row);
else
{
CustomShortcut rule{value(w, RuleName), value(w, RuleHotkey), value(w, RuleExecutable),
row < 0 || rules[row].enabled, checked(w, RuleNewInstance)};
if (editor->action == CustomShortcutAction::SendText)
{
rule.action = CustomShortcutAction::SendText;
rule.controlClass = editor->controlClass;
rule.controlId = editor->controlId;
rule.text = value(w, RuleText);
rule.executable = editor->targetExecutable;
rule.newInstance = false;
if (rule.controlClass.empty() || rule.text.empty())
throw std::runtime_error("Choose a target text field and enter the text to insert.");
}
else if (editor->action == CustomShortcutAction::OpenUrl)
{
rule.action = CustomShortcutAction::OpenUrl;
rule.url = trimApplicationText(value(w, RuleUrl));
rule.browser = selectedShortcutBrowser(w);
rule.executable = rule.browser == ShortcutBrowser::Other ? trimApplicationText(value(w, RuleBrowserPath)) : L"";
rule.newInstance = false;
if (rule.browser == ShortcutBrowser::Chrome)
{
const auto profile = SendDlgItemMessageW(w, RuleChromeProfile, CB_GETCURSEL, 0, 0);
if (profile > 0 && static_cast<size_t>(profile) <= editor->chromeProfiles.size())
rule.chromeProfile = editor->chromeProfiles[profile - 1].first;
}
}
if (row < 0) rules.push_back(std::move(rule));
else rules[row] = std::move(rule);
}
const int selection = row < 0 ? static_cast<int>(rules.size()) - 1 : row;
stageCustomShortcuts(editor->view, std::move(rules));
fillCustomShortcuts(editor->view, selection);
updateSettingsState(owner, &editor->view);
DestroyWindow(w);
return 0;
}
if (id == IDCANCEL)
{
DestroyWindow(w);
return 0;
}
}
if (msg == WM_CLOSE)
{
DestroyWindow(w);
return 0;
}
if (msg == WM_NCDESTROY)
{
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
delete editor;
disposeFont(w);
EnableWindow(owner, TRUE);
SetForegroundWindow(owner);
}
}
catch (const std::exception &e) { error(w, e); return 0; }
return DefWindowProcW(w, msg, wp, lp);
}
void showCustomShortcut(HWND owner, SettingsView &view, bool editing)
{
const auto list = GetDlgItem(view.viewport, CustomShortcutList);
const int row = editing ? ListView_GetNextItem(list, -1, LVNI_SELECTED) : -1;
if (editing && row < 0) return;
const auto rule = editing ? view.draft.customShortcuts.at(row) : CustomShortcut{};
const HWND w = makeSettingsModal(*view.app, owner, L"KSwitcher.CustomShortcut", editing ? L"Edit shortcut" : L"Add shortcut",
customShortcutProc, ShortcutDialogWidth, ShortcutDialogHeight);
const bool sendsText = rule.action == CustomShortcutAction::SendText;
auto *editor = new CustomShortcutEditor{view, row, editing ? std::optional(rule) : std::nullopt, nullptr, rule.controlClass,
sendsText ? rule.executable : L"", rule.action == CustomShortcutAction::LaunchApp ? rule.executable : L"",
rule.controlId, rule.action};
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(editor));
label(w, L"&Name", 22, 16, 340);
edit(w, RuleName, 22, 40, 340);
label(w, L"&Shortcut", 378, 16, 220);
hotkeyEdit(*view.app, w, RuleHotkey, 378, 40, 220);
label(w, L"&Action", 22, 80, 576);
control(w, WC_COMBOBOXW, L"", WS_TABSTOP | CBS_DROPDOWNLIST, RuleAction, 22, 101, 576, 110);
for (const auto *action : {L"Launch app", L"Send text to app", L"Open URL"})
SendDlgItemMessageW(w, RuleAction, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(action));
SendDlgItemMessageW(w, RuleAction, CB_SETCURSEL, static_cast<WPARAM>(rule.action), 0);
control(w, L"STATIC", L"&Program", 0, RuleProgramLabel, 22, 137, 576, 22);
edit(w, RuleExecutable, 22, 160, 440);
button(w, L"&Browse...", RuleBrowse, 472, 158, 84);
createAppWindowPicker(w, AppWindowPickerIcon, 566, 158, 32, editor->pickerOutline, createButtonTooltips(w));
control(w, L"STATIC", L"", SS_NOPREFIX, RulePickerHelp, 22, 194, 576, 22);
control(w, L"STATIC", L"When you press the shortcut", SS_NOPREFIX, RuleModeLabel, 22, 229, 576, 22);
control(w, L"STATIC", L"", SS_NOPREFIX, RuleControl, 22, 223, 576, 22);
control(w, L"STATIC", L"Text to insert", SS_NOPREFIX, RuleTextLabel, 22, 251, 576, 22);
edit(w, RuleText, 22, 274, 576, 76, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL);
SendDlgItemMessageW(w, RuleText, EM_SETLIMITTEXT, 32768, 0);
control(w, L"BUTTON", L"Activate the last-used window, or launch the app if it is closed",
WS_TABSTOP | WS_GROUP | BS_AUTORADIOBUTTON, RuleReuseWindow, 22, 252, 576, 24);
control(w, L"BUTTON", L"Always launch a new instance", BS_AUTORADIOBUTTON, RuleNewInstance, 22, 281, 576, 24);
control(w, L"STATIC", L"&URL", 0, RuleUrlLabel, 22, 137, 576, 22);
edit(w, RuleUrl, 22, 160, 576);
SendDlgItemMessageW(w, RuleUrl, EM_SETLIMITTEXT, 16384, 0);
control(w, L"STATIC", L"&Browser", 0, RuleBrowserLabel, 22, 201, 276, 22);
control(w, WC_COMBOBOXW, L"", WS_TABSTOP | CBS_DROPDOWNLIST, RuleBrowser, 22, 224, 576, 115);
for (const auto *browser : {L"Default browser", L"Google Chrome", L"Other browser"})
SendDlgItemMessageW(w, RuleBrowser, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(browser));
SendDlgItemMessageW(w, RuleBrowser, CB_SETCURSEL, static_cast<WPARAM>(rule.browser), 0);
control(w, L"STATIC", L"Chrome &profile", 0, RuleChromeProfileLabel, 319, 201, 279, 22);
control(w, WC_COMBOBOXW, L"", WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWNLIST, RuleChromeProfile, 319, 224, 279, 122);
SendDlgItemMessageW(w, RuleChromeProfile, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Use Chrome's default profile"));
SendDlgItemMessageW(w, RuleChromeProfile, CB_SETCURSEL, 0, 0);
control(w, L"STATIC", L"Browser executable", 0, RuleBrowserPathLabel, 22, 265, 576, 22);
edit(w, RuleBrowserPath, 22, 288, 478);
button(w, L"Browse...", RuleBrowserBrowse, 510, 286, 88);
settingsModalActions(w, ShortcutDialogWidth, ShortcutDialogHeight, editing ? L"Save shortcut" : L"Add shortcut",
RuleRemove, editing ? L"&Remove" : nullptr);
value(w, RuleName, rule.name);
value(w, RuleHotkey, rule.shortcut);
value(w, RuleExecutable, rule.executable);
value(w, RuleControl, rule.controlClass.empty() ? L"No target field selected" :
L"Target control: " + rule.controlClass + L" (ID " + std::to_wstring(rule.controlId) + L")");
value(w, RuleText, rule.text);
value(w, RuleUrl, rule.url);
if (rule.action == CustomShortcutAction::OpenUrl && rule.browser == ShortcutBrowser::Other)
value(w, RuleBrowserPath, rule.executable);
CheckRadioButton(w, RuleReuseWindow, RuleNewInstance, rule.newInstance ? RuleNewInstance : RuleReuseWindow);
refreshCustomShortcutEditor(w, *editor);
EnableWindow(owner, FALSE);
showRequestedWindow(w);
SetFocus(GetDlgItem(w, RuleName));
}
bool handleCustomShortcutList(HWND w, SettingsView &view, const NMHDR &header)
{
if (header.idFrom != CustomShortcutList || view.filling) return false;
if (header.code == NM_DBLCLK)
{
showCustomShortcut(w, view, true);
return true;
}
if (header.code != LVN_ITEMCHANGED) return false;
const auto &change = reinterpret_cast<const NMLISTVIEW &>(header);
const auto list = header.hwndFrom;
EnableWindow(GetDlgItem(view.viewport, CustomShortcutEdit), ListView_GetNextItem(list, -1, LVNI_SELECTED) >= 0);
if (change.iItem < 0 || static_cast<size_t>(change.iItem) >= view.draft.customShortcuts.size() ||
!(change.uOldState & LVIS_STATEIMAGEMASK) || !((change.uNewState ^ change.uOldState) & LVIS_STATEIMAGEMASK))
return true;
try
{
auto rules = view.draft.customShortcuts;
rules[change.iItem].enabled = ListView_GetCheckState(list, change.iItem);
stageCustomShortcuts(view, std::move(rules));
updateSettingsState(w, &view);
}
catch (const std::exception &e)
{
view.filling = true;
ListView_SetCheckState(list, change.iItem, view.draft.customShortcuts[change.iItem].enabled);
view.filling = false;
error(w, e);
}
return true;
}
void createCustomShortcuts(HWND pane)
{
button(pane, L"&Add shortcut...", CustomShortcutAdd, 24, 64, 138);
button(pane, L"&Edit...", CustomShortcutEdit, 170, 64, 90);
const auto list = control(pane, WC_LISTVIEWW, L"Custom shortcuts", WS_TABSTOP | WS_BORDER | LVS_REPORT |
LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, CustomShortcutList, 24, 106, 660, 242);
ListView_SetExtendedListViewStyle(list, LVS_EX_FULLROWSELECT | LVS_EX_CHECKBOXES | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP);
const std::pair<const wchar_t *, int> columns[]{{L"Name", 235}, {L"Action", 255}, {L"Shortcut", 150}};
for (const auto &[title, width] : columns)
{
LVCOLUMNW column{LVCF_TEXT | LVCF_WIDTH};
column.pszText = const_cast<wchar_t *>(title);
column.cx = scale(pane, width);
ListView_InsertColumn(list, Header_GetItemCount(ListView_GetHeader(list)), &column);
}
}
+2
View File
@@ -364,6 +364,8 @@ void refreshLan(HWND w,LanView &v)
auto mode=v.snapshot.value("controlMode",0);
if(mode==2)inputStatus=L"Mouse and keyboard control the OTHER PC. Ctrl+Alt+Esc returns here.";
else if(mode==3)inputStatus=L"This PC is controlled remotely. Local physical input takes control back.";
const auto inputBlock=v.snapshot.value("inputBlock",std::string{});
if(!inputBlock.empty()&&v.snapshot.value("shareInput",false))inputStatus=wide(inputBlock);
if (v.draft.contains("shareInput"))
inputStatus = L"Click Apply or Save to apply input sharing changes.";
setStatus(718,v.layoutError.empty() ? inputStatus : v.layoutError);
+11 -4
View File
@@ -466,16 +466,23 @@ std::wstring actionApplicationExecutable(std::filesystem::path path)
return path.filename().wstring();
}
void browseActionApplication(HWND w, MouseProfileEditor &editor)
std::wstring chooseApplicationFile(HWND w, const wchar_t *filter, DWORD flags = 0)
{
wchar_t path[32768]{};
OPENFILENAMEW picker{sizeof(picker)};
picker.hwndOwner = w;
picker.lpstrFilter = L"Applications and shortcuts (*.exe;*.lnk)\0*.exe;*.lnk\0";
picker.lpstrFilter = filter;
picker.lpstrFile = path;
picker.nMaxFile = static_cast<DWORD>(std::size(path));
picker.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_NODEREFERENCELINKS;
if (!GetOpenFileNameW(&picker)) return;
picker.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | flags;
return GetOpenFileNameW(&picker) ? path : L"";
}
void browseActionApplication(HWND w, MouseProfileEditor &editor)
{
const auto path = chooseApplicationFile(w, L"Applications and shortcuts (*.exe;*.lnk)\0*.exe;*.lnk\0",
OFN_NODEREFERENCELINKS);
if (path.empty()) return;
value(w, ActionApplicationName, actionApplicationExecutable(path));
addActionApplication(w, editor);
}
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.8.3";
inline constexpr wchar_t AppVersion[] = L"0.8.12";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+1 -1
View File
@@ -855,7 +855,7 @@ int main(int argc,char **argv)
require(!saveEnabled(), "reverting an inline correction edit disables Save");
HWND navigation = settingsNavigation(parent);
constexpr int chatLanguagesPage = 20;
constexpr int sections = 21;
constexpr int sections = 22;
require(navigation && TreeView_GetCount(navigation) == sections &&
TreeView_GetParent(navigation, settingsSection(navigation, 10)) == settingsSection(navigation, 7) &&
TreeView_GetParent(navigation, settingsSection(navigation, 11)) == settingsSection(navigation, 0),
+6 -2
View File
@@ -23,10 +23,14 @@ int wmain(int argc,wchar_t **argv)
wchar_t executable[32768]{};
const auto length=GetModuleFileNameW(nullptr,executable,static_cast<DWORD>(std::size(executable)));
if(!length || length>=std::size(executable)) return 1;
const std::filesystem::path target=argc==2?argv[1]:executable;
const bool browserFixture=argc==2 && std::filesystem::path(executable).filename()==L"browser-fixture.exe";
const std::filesystem::path target=argc==2 && !browserFixture?argv[1]:executable;
auto report=target;
report+=L".opened";
std::ofstream result(report,std::ios::binary);
result<<"opened";
if(browserFixture) {
const std::wstring_view url(argv[1]);
for(const auto ch:url) result.put(static_cast<char>(ch));
} else result<<"opened";
return result?0:1;
}
+2 -2
View File
@@ -81,8 +81,8 @@ function Open-FilesSource([IntPtr]$Window, [int]$Side, [string]$Source) {
[void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr](0x20000 + 121), $picker)
}
function Invoke-FilesCommand([IntPtr]$Window, [string]$LabelPattern) {
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr]132, [IntPtr]::Zero)
function Invoke-FilesCommand([IntPtr]$Window, [string]$LabelPattern, [int]$Menu = 132) {
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr]$Menu, [IntPtr]::Zero)
$picker = [FilesCommandsUi]::GetDlgItem($Window, 121)
[void](Wait-For 'the Commands menu' { [FilesCommandsUi]::IsWindowVisible($picker) })
$count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
+66 -16
View File
@@ -2,10 +2,12 @@ param(
[string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe",
[switch]$OfflineWake,
[switch]$FtpProfiles,
[switch]$Far,
[string]$Screenshot
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
. "$PSScriptRoot/files_commands_ui.ps1"
Add-Type @'
using System;
@@ -45,8 +47,9 @@ $previousDpi = [FilesDriveShortcutTest]::SetThreadDpiAwarenessContext([IntPtr](-
try {
if ($FtpProfiles) {
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$preferenceNames = 'FtpProfiles', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor',
'LeftFtpLocation', 'RightFtpLocation', 'FontPoints', 'WindowPlacement'
$preferenceNames = 'FtpProfiles', 'SftpProfiles', 'RecentFolders', 'LeftWide', 'RightWide',
'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftFtpLocation', 'RightFtpLocation',
'FontPoints', 'WindowPlacement', 'AppearanceMode', 'PanelScale', 'DisplayFont', 'RestoreLocalDocuments'
foreach ($name in $preferenceNames) {
if ($name -in $preferences.GetValueNames()) {
$savedPreferences[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
@@ -54,8 +57,17 @@ try {
}
$profile = '[{"name":"Test FTP profile","host":"localhost","user":"","port":21,"secret":[]}]'
$preferences.SetValue('FtpProfiles', [Text.Encoding]::UTF8.GetBytes($profile), 'Binary')
$profile = '[{"name":"Test SFTP profile","host":"localhost","user":"","port":22,"secret":[]}]'
$preferences.SetValue('SftpProfiles', [Text.Encoding]::UTF8.GetBytes($profile), 'Binary')
$recentFolder = [IO.Path]::GetFullPath($env:TEMP)
$recentJson = ConvertTo-Json -InputObject @($recentFolder) -Compress
$preferences.SetValue('RecentFolders', [Text.Encoding]::UTF8.GetBytes($recentJson), 'Binary')
foreach ($name in 'LeftWide', 'RightWide') { $preferences.SetValue($name, 1, 'DWord') }
$preferences.SetValue('FontPoints', 80, 'DWord')
$preferences.SetValue('PanelScale', 100, 'DWord')
$preferences.SetValue('AppearanceMode', [int]!$Far, 'DWord')
$preferences.SetValue('RestoreLocalDocuments', 0, 'DWord')
$preferences.DeleteValue('DisplayFont', $false)
foreach ($name in 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement') {
$preferences.DeleteValue($name, $false)
}
@@ -74,17 +86,18 @@ try {
$picker = [FilesDriveShortcutTest]::GetDlgItem($window, 121)
$path = [FilesDriveShortcutTest]::GetDlgItem($window, 142)
function Open-Picker([int]$Side = 0) {
[void][FilesDriveShortcutTest]::PostMessage($window, 260, [IntPtr](112 + $Side), [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::IsWindowVisible($picker) }
Invoke-FilesCommand $window '*Change drive*' (130 + 4 * $Side)
Wait-Until { (Read-Picker) -contains 'KSwitcher LAN' }
}
function Read-Picker {
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i }
}
function Render-Picker {
function Render-Picker([int]$Height = 0) {
$client = [FilesDriveShortcutTest+Rect]::new()
[void][FilesDriveShortcutTest]::GetClientRect($picker, [ref]$client)
$bitmap = [Drawing.Bitmap]::new($client.Right, $client.Bottom)
$captureHeight = if ($Height -gt 0) { [Math]::Min($Height, $client.Bottom) } else { $client.Bottom }
$bitmap = [Drawing.Bitmap]::new($client.Right, $captureHeight)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
@@ -137,17 +150,43 @@ try {
$line -ne $bitmap.GetPixel($bitmap.Width - 5, $y).ToArgb()) {
throw "The local disks and FTP divider did not render in panel $side."
}
$ftpBounds = [FilesDriveShortcutTest+Rect]::new()
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]$row, [ref]$ftpBounds)
$yellow = [Drawing.Color]::Yellow.ToArgb()
$hasDigit = $false
for ($lineY = $ftpBounds.Top; $lineY -lt $ftpBounds.Bottom -and $lineY -lt $bitmap.Height -and !$hasDigit; $lineY++) {
for ($x = 0; $x -lt [Math]::Min(128,$bitmap.Width); $x++) {
if ($bitmap.GetPixel($x,$lineY).ToArgb() -eq $yellow) { $hasDigit = $true; break }
$accent = if ($Far) { [Drawing.Color]::Yellow.ToArgb() } else { [Drawing.Color]::FromArgb(70, 72, 187).ToArgb() }
$dpi = [FilesCommandsUi]::GetDpiForWindow($picker)
$pixels = [Math]::Round(8 * $dpi / 72)
$font = [Drawing.Font]::new('Consolas', $pixels, [Drawing.FontStyle]::Regular, [Drawing.GraphicsUnit]::Pixel)
try {
$columns = @(0, 0, 0)
$flags = [Windows.Forms.TextFormatFlags]::NoPadding -bor [Windows.Forms.TextFormatFlags]::SingleLine
$layout = [Drawing.Size]::new(10000, 1000)
for ($disk = 0; $disk -lt $row - 1; ++$disk) {
$parts = $rows[$disk] -split [char]9
for ($column = 0; $column -lt 3; ++$column) {
$width = [Windows.Forms.TextRenderer]::MeasureText($parts[$column], $font, $layout, $flags).Width
$columns[$column] = [Math]::Max($columns[$column], $width)
}
}
$space = [Windows.Forms.TextRenderer]::MeasureText(' ', $font, $layout, $flags).Width
$lastColumnEnd = $columns[0] + $columns[1] + $columns[2] + 5 * $space + 2
if ($bitmap.Width -lt $lastColumnEnd) {
throw "Free-space values are clipped in panel $side (end $lastColumnEnd, width $($bitmap.Width))."
}
} finally { $font.Dispose() }
for ($offset = 0; $offset -lt 4; $offset++) {
$bounds = [FilesDriveShortcutTest+Rect]::new()
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]($row + $offset), [ref]$bounds)
$hasDigit = $false
for ($lineY = $bounds.Top; $lineY -lt $bounds.Bottom -and $lineY -lt $bitmap.Height -and !$hasDigit; $lineY++) {
for ($x = 0; $x -lt [Math]::Min(128,$bitmap.Width); $x++) {
if ($bitmap.GetPixel($x,$lineY).ToArgb() -eq $accent) { $hasDigit = $true; break }
}
}
if (!$hasDigit) { throw "The $($rows[$row + $offset]) shortcut digit did not render in panel $side." }
}
if ($Screenshot -and $side -eq 0) {
$sources = Render-Picker $bounds.Bottom
try { $sources.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png) }
finally { $sources.Dispose() }
}
if (!$hasDigit) { throw "The FTP shortcut digit did not render in panel $side." }
if ($Screenshot -and $side -eq 0) { $bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png) }
} finally { $bitmap.Dispose() }
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]($row - 2), $null)
Press-Shortcut '1'
@@ -163,8 +202,19 @@ try {
} finally { $graphics.ReleaseHdc($dc) }
} finally { $graphics.Dispose() }
if ($process.HasExited) { throw "Files exited while rendering the FTP profile in panel $side." }
Open-Picker $side
Press-Shortcut '2'
Wait-Until { (Read-Text $panelPath) -ceq 'SFTP' }
if ((Read-Text $list 393 0) -cne 'Test SFTP profile') { throw "Saved SFTP profile missing from panel $side." }
Open-Picker $side
Press-Shortcut '3'
Wait-Until { (Read-Text $panelPath) -ceq 'SMB' }
Open-Picker $side
Press-Shortcut '4'
Wait-Until { (Read-Text $panelPath) -ceq 'Recent folders' }
Wait-Until { (Read-FilesList $list) -contains $recentFolder }
}
Write-Output 'Both source menus rendered the FTP shortcut, skipped group dividers, and opened FTP with 1.'
Write-Output 'Both source menus rendered shortcuts 1–4 and opened FTP, SFTP, SMB, and Recent folders.'
return
}
if ($OfflineWake) {
+77
View File
@@ -0,0 +1,77 @@
#include "files_folder_size.h"
#include <windows.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
namespace fs=std::filesystem;
using ks::files::measureNtfsFolder;
namespace
{
struct Fixture
{
fs::path path=fs::temp_directory_path()/
(L"ks-files-size-"+std::to_wstring(GetCurrentProcessId())+L"-"+std::to_wstring(GetTickCount64()));
Fixture() {fs::create_directory(path);}
~Fixture() {std::error_code error;fs::remove_all(path,error);}
};
void write(const fs::path &path,const char *data)
{
std::ofstream file(path,std::ios::binary);
if(!(file<<data)) throw std::runtime_error("Could not create scan fixture.");
}
}
int main()
{
try
{
Fixture fixture;
wchar_t filesystem[32]{};
if(!GetVolumeInformationW(fixture.path.root_path().c_str(),nullptr,0,nullptr,nullptr,nullptr,
filesystem,static_cast<DWORD>(std::size(filesystem))) || std::wstring_view(filesystem)!=L"NTFS")
{
std::cout<<"Native NTFS scan unavailable on the temporary volume.\n";
return 77;
}
const auto root=fixture.path/L"selected";
const auto empty=root/L"empty";
fs::create_directories(empty);
const auto emptySize=measureNtfsFolder(empty,{});
if(!emptySize || emptySize->bytes || emptySize->partial) throw std::runtime_error("Empty NTFS folder.");
const auto source=root/L"source.bin";
write(source,"abc");
const auto branch=root/L"nested";
fs::create_directory(branch);
fs::create_hard_link(source,branch/L"alias.bin");
// Force more than one NTFS page and several concurrent directory jobs.
for(int i=0;i<600;++i)
{
const auto suffix=std::to_wstring(i);
write(branch/(L"long-filename-0123456789-"+suffix+L".txt"),"x");
if(i<8)
{
const auto sibling=root/(L"sibling-"+suffix);
fs::create_directory(sibling);
write(sibling/L"payload","12");
}
}
const auto total=measureNtfsFolder(root,{});
if(!total || total->partial || total->bytes!=622)
throw std::runtime_error("NTFS scan must sum all pages, branches and hard-link names.");
std::stop_source canceled;
canceled.request_stop();
const auto stopped=measureNtfsFolder(root,canceled.get_token());
if(!stopped || stopped->bytes) throw std::runtime_error("Canceled scan counted files.");
std::cout<<"NTFS folder sizes passed.\n";
return 0;
}
catch(const std::exception &error)
{
std::cerr<<error.what()<<'\n';
return 1;
}
}
+49 -12
View File
@@ -1,6 +1,7 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$Screenshot,
[switch]$DrivePickerOnly,
[string]$DialogScreenshotDirectory
)
$ErrorActionPreference = 'Stop'
@@ -118,6 +119,45 @@ function Set-Style($Window, [int]$Style) {
Wait-Until { [LavenderWindow]::Activate($Window) }
}
function Save-DialogScreenshot($Window, $Bounds, [string]$Name) {
$owner = Get-Bounds $Window
$horizontal = [int](105 * $scale)
$vertical = [int](88 * $scale)
$context = [LavenderWindow+Rect]::new()
$context.Left = [Math]::Max($owner.Left, $Bounds.Left - $horizontal)
$context.Right = [Math]::Min($owner.Right, $Bounds.Right + $horizontal)
$context.Top = [Math]::Max($owner.Top, $Bounds.Top - $vertical)
$context.Bottom = [Math]::Min($owner.Bottom, $Bounds.Bottom + $vertical)
$scene = Read-Window $context
try { $scene.Save((Join-Path $DialogScreenshotDirectory $Name), [Drawing.Imaging.ImageFormat]::Png) }
finally { $scene.Dispose() }
}
function Test-LavenderDrivePicker($Window) {
Invoke-FilesCommand $Window '*Change drive*' 134
$frame = [LavenderWindow]::GetDlgItem($Window, 122)
Wait-Until { [LavenderWindow]::IsWindowVisible($frame) }
Start-Sleep -Milliseconds 160
$bounds = Get-Bounds $frame
$image = Read-Window $bounds
try {
$x = $bounds.Left + [int](($bounds.Right - $bounds.Left) / 2)
$y = $bounds.Top + [int](($bounds.Bottom - $bounds.Top) / 2)
$stroke = [Math]::Round(2 * $scale, [MidpointRounding]::AwayFromZero)
Test-Pixel $image $bounds $x ($bounds.Top + $stroke - 1) '#4648BB' 'Drive picker top outline'
Test-Pixel $image $bounds $x ($bounds.Bottom - $stroke) '#4648BB' 'Drive picker bottom outline'
Test-Pixel $image $bounds ($bounds.Left + $stroke - 1) $y '#4648BB' 'Drive picker left outline'
Test-Pixel $image $bounds ($bounds.Right - $stroke) $y '#4648BB' 'Drive picker right outline'
Test-Pixel $image $bounds $x ($bounds.Bottom - $stroke - 1) '#F2EFFB' 'Drive picker surface'
if ($DialogScreenshotDirectory) {
Save-DialogScreenshot $Window $bounds 'files-lavender-drive.png'
}
} finally { $image.Dispose() }
$picker = [LavenderWindow]::GetDlgItem($Window, 121)
[void][LavenderWindow]::Post($picker, 0x100, [IntPtr]27, [IntPtr]::Zero)
Wait-Until { ![LavenderWindow]::IsWindowVisible($frame) }
}
function Test-LavenderDialog($Window, [string]$Keys, [int]$ControlId, [string]$Name) {
$keyboard.SendKeys($Keys)
try {
@@ -137,23 +177,14 @@ function Test-LavenderDialog($Window, [string]$Keys, [int]$ControlId, [string]$N
([int](($field.Top + $field.Bottom) / 2)) '#FFFFFF' 'Copy destination field'
}
if ($DialogScreenshotDirectory -and $Name -eq 'Copy') {
$owner = Get-Bounds $Window
$horizontal = [int](105 * $scale)
$vertical = [int](88 * $scale)
$context = [LavenderWindow+Rect]::new()
$context.Left = [Math]::Max($owner.Left, $bounds.Left - $horizontal)
$context.Right = [Math]::Min($owner.Right, $bounds.Right + $horizontal)
$context.Top = [Math]::Max($owner.Top, $bounds.Top - $vertical)
$context.Bottom = [Math]::Min($owner.Bottom, $bounds.Bottom + $vertical)
$scene = Read-Window $context
try { $scene.Save((Join-Path $DialogScreenshotDirectory 'files-lavender-copy.png'), [Drawing.Imaging.ImageFormat]::Png) }
finally { $scene.Dispose() }
Save-DialogScreenshot $Window $bounds 'files-lavender-copy.png'
}
} finally { $image.Dispose() }
$keyboard.SendKeys('{ESC}')
Wait-Until { ![LavenderWindow]::IsWindow($dialog) -and [LavenderWindow]::Activate($Window) }
}
. "$PSScriptRoot/files_commands_ui.ps1"
$exe = (Resolve-Path $Executable).Path
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$names = 'AppearanceMode', 'LeftPanelMode', 'RightPanelMode', 'LeftViewOrder', 'RightViewOrder', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'OptionsLocation'
@@ -179,7 +210,7 @@ try {
foreach ($name in '.gitignore', 'CMakeLists.txt', 'FILES-UI.md', 'LICENSE', 'README.md') {
[IO.File]::WriteAllText((Join-Path $right.FullName $name), ('Example content' * (40 + 54 * $name.Length)))
}
$key.SetValue('AppearanceMode', 0, 'DWord')
$key.SetValue('AppearanceMode', [int]$DrivePickerOnly.IsPresent, 'DWord')
$key.SetValue('LeftPanelMode', 1, 'DWord')
$key.SetValue('RightPanelMode', 1, 'DWord')
$key.SetValue('LeftViewOrder', 0, 'DWord')
@@ -203,6 +234,12 @@ try {
$rightList = [LavenderWindow]::GetDlgItem($window, 103)
Wait-Until { [LavenderWindow]::Send($leftList, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq 6 -and
[LavenderWindow]::Send($rightList, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq 12 }
if ($DrivePickerOnly) {
if ($DialogScreenshotDirectory) { [void][IO.Directory]::CreateDirectory($DialogScreenshotDirectory) }
Test-LavenderDrivePicker $window
'Verified the lavender drive picker surface and the outline on all four edges.'
return
}
$farRow = [LavenderWindow]::Send($leftList, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
Set-Style $window 1
$rowHeight = [LavenderWindow]::Send($leftList, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
+123
View File
@@ -0,0 +1,123 @@
param([Parameter(Mandatory)][string]$Executable,[string]$Screenshot)
$ErrorActionPreference='Stop'
. "$PSScriptRoot/files_commands_ui.ps1"
function Read-Label([IntPtr]$control,[uint32]$message=13) {
$text=[Text.StringBuilder]::new(1024)
[void][FilesCommandsUi]::Read($control,$message,[IntPtr]$(if($message -eq 13){$text.Capacity}else{0}),$text)
$text.ToString()
}
function Click([IntPtr]$panel,[int]$id) {
[void][FilesCommandsUi]::Send($panel,273,$id,[FilesCommandsUi]::GetDlgItem($panel,$id))
}
function Set-Metric([IntPtr]$panel,[int]$row) {
$select=[FilesCommandsUi]::GetDlgItem($panel,503)
if(!$select) {throw 'The analyzer metric selector is missing.'}
[void][FilesCommandsUi]::Send($select,334,$row,0)
[void][FilesCommandsUi]::Send($panel,273,(65536+503),$select)
}
$exe=(Resolve-Path -LiteralPath $Executable).Path
$fixture=[IO.Directory]::CreateTempSubdirectory('ks-space-pane-').FullName
$preferences=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$keys='LeftPath','RightPath','LeftFtpLocation','RightFtpLocation','WindowPlacement',
'LeftCursor','RightCursor','RestoreLocalDocuments'
$saved=@{}
foreach($key in $keys) {
if($key -in $preferences.GetValueNames()) {$saved[$key]=@($preferences.GetValue($key),$preferences.GetValueKind($key))}
}
$app=$null
$dpi=[FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
try {
$left=[IO.Directory]::CreateDirectory((Join-Path $fixture 'left')).FullName
$right=[IO.Directory]::CreateDirectory((Join-Path $fixture 'right')).FullName
[IO.File]::WriteAllBytes((Join-Path $left 'allocated.bin'),[byte[]]::new(5307))
$preferences.SetValue('LeftPath',$left,'String')
$preferences.SetValue('RightPath',$right,'String')
$preferences.SetValue('RestoreLocalDocuments',0,'DWord')
foreach($key in 'LeftFtpLocation','RightFtpLocation','WindowPlacement') {$preferences.DeleteValue($key,$false)}
$app=Start-Process -FilePath $exe -WindowStyle Hidden -PassThru
$main=Wait-For 'Files main window' {
$candidate=[IntPtr]::Zero
while(($candidate=[FilesCommandsUi]::FindWindowEx(0,$candidate,'KSwitcher.Files',[NullString]::Value)) -ne 0) {
[uint32]$owner=0
[void][FilesCommandsUi]::GetWindowThreadProcessId($candidate,[ref]$owner)
if($owner -eq $app.Id) {return $candidate}
}
}
[void][FilesCommandsUi]::ShowWindow($main,4)
[void][FilesCommandsUi]::SetWindowPos($main,0,24,24,1240,710,20)
$leftList=[FilesCommandsUi]::GetDlgItem($main,102)
$rightList=[FilesCommandsUi]::GetDlgItem($main,103)
[void](Wait-For 'fixture folder' {(Read-Label ([FilesCommandsUi]::GetDlgItem($main,142))) -eq $left})
Invoke-FilesCommand $main '*Space Analyzer' 130
$analyzer=Wait-For 'Space Analyzer child pane' {
$candidate=[FilesCommandsUi]::FindWindowEx($main,0,'#32770',[NullString]::Value)
if($candidate -and [FilesCommandsUi]::IsWindowVisible($candidate) -and
[FilesCommandsUi]::GetDlgItem($candidate,489)) {return $candidate}
}
if([FilesCommandsUi]::IsWindowVisible($leftList) -or ![FilesCommandsUi]::IsWindowVisible($rightList)) {
throw 'The analyzer should replace only the selected pane.'
}
$state=[FilesCommandsUi]::GetDlgItem($analyzer,490)
[void](Wait-For 'automatic fixture scan' {(Read-Label $state) -like 'Complete*Logical size'})
Set-Metric $analyzer 1
[void](Wait-For 'allocated tree metric' {(Read-Label $state) -like '*Size on disk'})
Click $analyzer 499
$sunburst=[FilesCommandsUi]::GetDlgItem($analyzer,500)
[void](Wait-For 'allocated chart item' {(Read-Label $sunburst 393) -like 'allocated.bin*on disk'})
Set-Metric $analyzer 0
[void](Wait-For 'logical chart metric' {(Read-Label $sunburst 393) -like 'allocated.bin*logical'})
Click $analyzer 497
if(![FilesCommandsUi]::IsWindowVisible([FilesCommandsUi]::GetDlgItem($analyzer,498))) {
throw 'Treemap did not show in the analyzer pane.'
}
Click $analyzer 502
Set-Metric $analyzer 1
if($Screenshot) {
Add-Type -AssemblyName System.Drawing
$bounds=[FilesCommandsUi+Rect]::new()
[void][FilesCommandsUi]::GetClientRect($main,[ref]$bounds)
$image=[Drawing.Bitmap]::new($bounds.Right,$bounds.Bottom)
try {
$graphics=[Drawing.Graphics]::FromImage($image)
try {
$dc=$graphics.GetHdc()
try {if(![FilesCommandsUi]::PrintWindow($main,$dc,3)) {throw 'Cannot render Space Analyzer.'}}
finally {$graphics.ReleaseHdc($dc)}
} finally {$graphics.Dispose()}
$image.Save($Screenshot,[Drawing.Imaging.ImageFormat]::Png)
} finally {$image.Dispose()}
}
Click $analyzer 1
[void](Wait-For 'selection opened in the other pane' {
[FilesCommandsUi]::IsWindowVisible($analyzer) -and
(Read-Label ([FilesCommandsUi]::GetDlgItem($main,143))) -eq $left
})
Click $analyzer 2
[void](Wait-For 'restored file pane' {
[FilesCommandsUi]::IsWindowVisible($leftList) -and (Read-Label ([FilesCommandsUi]::GetDlgItem($main,142))) -eq $left
})
Invoke-FilesCommand $main '*Space Analyzer' 134
$analyzer=Wait-For 'analyzer in the right pane' {
$candidate=[FilesCommandsUi]::FindWindowEx($main,0,'#32770',[NullString]::Value)
if($candidate -and [FilesCommandsUi]::IsWindowVisible($candidate) -and
[FilesCommandsUi]::GetDlgItem($candidate,489) -and ![FilesCommandsUi]::IsWindowVisible($rightList)) {
return $candidate
}
}
[void][FilesCommandsUi]::Post([FilesCommandsUi]::GetDlgItem($analyzer,489),256,27,0)
[void](Wait-For 'right file pane restored with Esc' {[FilesCommandsUi]::IsWindowVisible($rightList)})
'Verified in-pane analysis on both sides, size selection in tree and charts, and return to files.'
} finally {
if($app -and !$app.HasExited) {$app.Kill();$app.WaitForExit()}
foreach($key in $keys) {
if($saved.ContainsKey($key)) {$preferences.SetValue($key,$saved[$key][0],$saved[$key][1])}
else {$preferences.DeleteValue($key,$false)}
}
$preferences.Dispose()
if($dpi) {[void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi)}
$resolved=(Resolve-Path -LiteralPath $fixture).Path
if($resolved -ne [IO.Path]::GetFullPath($fixture)) {throw 'Unexpected fixture path.'}
[IO.Directory]::Delete($resolved,$true)
}
+138 -1
View File
@@ -30,6 +30,10 @@ LRESULT CALLBACK countControlMoves(HWND w, UINT message, WPARAM wp, LPARAM lp, U
}
namespace ks {
struct InputRegressionAccess {
static void invokeCustomShortcut(App &app, unsigned row, WORD key)
{
app.windowProc(app.window, WM_HOTKEY, 0x5000 + row, MAKELPARAM(MOD_CONTROL | MOD_ALT, key));
}
static void finishHistoryPreviews(App &app)
{
std::deque<std::function<void()>> jobs;
@@ -375,6 +379,139 @@ int main(int argc, char **argv) {
try {
INITCOMMONCONTROLSEX controls{sizeof(controls),ICC_STANDARD_CLASSES|ICC_LISTVIEW_CLASSES};
InitCommonControlsEx(&controls);
if (argc == 3 && std::string_view(argv[1]) == "--custom-shortcut-layout")
{
{
ks::App app(GetModuleHandleW(nullptr), true, temp);
app.settings.autostart = true;
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.customShortcuts = {{L"Open editor", L"Ctrl+Alt+F9", L"C:\\Apps\\Editor.exe"}};
ks::showSettings(app);
const auto settings = app.settingsWindow;
const auto nav = settingsNavigation(settings);
require(TreeView_GetParent(nav, settingsSection(nav, 21)) == settingsSection(nav, 2),
"custom shortcuts sit under the built-in shortcuts page");
selectSettingsPage(settings, 21);
const auto pane = settingsViewport(settings);
const auto list = GetDlgItem(pane, 780);
require(IsWindowVisible(list) && ListView_GetItemCount(list) == 1 && IsWindowVisible(GetDlgItem(pane, 781)),
"the custom shortcuts page shows saved shortcuts and the Add button");
ListView_SetCheckState(list, 0, FALSE);
require(IsWindowEnabled(GetDlgItem(settings, 272)) && IsWindowEnabled(GetDlgItem(settings, IDOK)),
"editing a shortcut enables Apply and Save");
SendMessageW(settings, WM_COMMAND, 272, 0);
require(!app.settings.customShortcuts.at(0).enabled, "Apply commits the shortcut change");
wchar_t closeLabel[24]{};
GetDlgItemTextW(settings, IDCANCEL, closeLabel, std::size(closeLabel));
require(IsWindow(settings) && !IsWindowEnabled(GetDlgItem(settings, 272)) &&
!IsWindowEnabled(GetDlgItem(settings, IDOK)) && IsWindowEnabled(GetDlgItem(settings, IDCANCEL)) &&
std::wstring_view(closeLabel) == L"&Close",
"Apply leaves only Close enabled for saved settings when Windows autostart is on");
require(!ks::loadSettings(temp / L"settings.json", app.layouts).customShortcuts.at(0).enabled,
"Apply saves the shortcut change to disk");
SendMessageW(settings, WM_COMMAND, 781, 0);
const auto dialog = GetWindow(settings, GW_ENABLEDPOPUP);
require(dialog != settings && IsWindowVisible(GetDlgItem(dialog, 753)),
"the launch action offers the shared crosshair");
require(IsWindowVisible(GetDlgItem(dialog, 787)) && IsWindowVisible(GetDlgItem(dialog, 788)) &&
SendDlgItemMessageW(dialog, 787, BM_GETCHECK, 0, 0) == BST_CHECKED,
"both launch modes are visible and activating a window is the default");
SendDlgItemMessageW(dialog, 790, CB_SETCURSEL, 1, 0);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(790, CBN_SELCHANGE), 0);
require(IsWindowVisible(GetDlgItem(dialog, 753)) && IsWindowVisible(GetDlgItem(dialog, 792)) &&
!IsWindowVisible(GetDlgItem(dialog, 787)),
"text insertion uses the crosshair and shows a multiline text editor");
auto select = [&](int id, int row) {
SendDlgItemMessageW(dialog, id, CB_SETCURSEL, row, 0);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(id, CBN_SELCHANGE), 0);
};
select(790, 2);
require(IsWindowVisible(GetDlgItem(dialog, 797)) && IsWindowVisible(GetDlgItem(dialog, 799)) &&
!IsWindowVisible(GetDlgItem(dialog, 753)) && !IsWindowVisible(GetDlgItem(dialog, 801)),
"Open URL shows an address and browser without an unrelated crosshair or profile picker");
select(799, 2);
require(IsWindowVisible(GetDlgItem(dialog, 803)), "choosing another browser exposes the browser executable");
select(799, 1);
require(IsWindowVisible(GetDlgItem(dialog, 801)) && !IsWindowVisible(GetDlgItem(dialog, 803)),
"choosing Chrome exposes the profile picker");
SetDlgItemTextW(dialog, 783, L"Open project board");
SetDlgItemTextW(dialog, 784, L"Ctrl+Alt+F10");
SetDlgItemTextW(dialog, 797, L"https://example.com/board");
SendMessageW(dialog, WM_COMMAND, IDOK, 0);
require(!IsWindow(dialog) && ListView_GetItemCount(list) == 2, "adding Open URL updates the shortcut list");
ListView_SetCheckState(list, 1, FALSE);
SendMessageW(settings, WM_COMMAND, 272, 0);
const auto persisted = ks::loadSettings(temp / L"settings.json", app.layouts).customShortcuts;
require(persisted.size() == 2 && persisted[1].action == ks::CustomShortcutAction::OpenUrl &&
persisted[1].url == L"https://example.com/board" && persisted[1].browser == ks::ShortcutBrowser::Chrome,
"Apply persists the Open URL action and browser from the editor");
DestroyWindow(settings);
const auto target = CreateWindowExW(0, L"STATIC", L"Shortcut target", WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, 320, 180, nullptr, nullptr, app.instance, nullptr);
const auto text = CreateWindowExW(0, L"Edit", L"Before after", WS_CHILD | WS_VISIBLE | ES_MULTILINE,
10, 10, 270, 100, target, reinterpret_cast<HMENU>(101), app.instance, nullptr);
require(target && text, "the target window and native multiline edit are available");
SendMessageW(text, EM_SETSEL, 7, 7);
app.settings.customShortcuts = {{L"Insert text", L"Ctrl+Alt+F9", ks::processImagePath(target), true, false,
ks::CustomShortcutAction::SendText, L"Edit", L"first\r\nsecond ", 101}};
ks::InputRegressionAccess::invokeCustomShortcut(app, 0, VK_F9);
wchar_t inserted[80]{};
GetWindowTextW(text, inserted, std::size(inserted));
require(std::wstring_view(inserted) == L"Before first\r\nsecond after", "shortcut inserts text at the target selection");
app.settings.customShortcuts[0].enabled = false;
ks::InputRegressionAccess::invokeCustomShortcut(app, 0, VK_F9);
GetWindowTextW(text, inserted, std::size(inserted));
require(std::wstring_view(inserted) == L"Before first\r\nsecond after", "disabled shortcut cannot insert text");
const auto targetExe = ks::processImagePath(target);
app.settings.customShortcuts[0] = {L"Activate target", L"Ctrl+Alt+F9", targetExe};
ShowWindow(target, SW_MINIMIZE);
ks::InputRegressionAccess::invokeCustomShortcut(app, 0, VK_F9);
for (const auto deadline = GetTickCount64() + 1500; IsIconic(target) && GetTickCount64() < deadline;)
{
MSG message{};
while (PeekMessageW(&message, target, 0, 0, PM_REMOVE)) DispatchMessageW(&message);
Sleep(10);
}
require(!IsIconic(target), "activate mode restores an existing minimized window");
DestroyWindow(target);
for (const bool newInstance : {false, true})
{
const auto fixture = temp / (newInstance ? L"start-new.exe" : L"start-if-closed.exe");
std::filesystem::copy_file(std::filesystem::path(argv[2]), fixture);
auto marker = fixture;
marker += L".opened";
app.settings.customShortcuts[0] = {L"Start fixture", L"Ctrl+Alt+F9", fixture.wstring(), true, newInstance};
ks::InputRegressionAccess::invokeCustomShortcut(app, 0, VK_F9);
for (const auto deadline = GetTickCount64() + 5000;
!std::filesystem::exists(marker) && GetTickCount64() < deadline;) Sleep(25);
require(std::filesystem::exists(marker), newInstance ? "new-instance mode starts the program" :
"activate mode starts the program if there is no matching window");
}
const auto browser = temp / L"browser-fixture.exe";
std::filesystem::copy_file(std::filesystem::path(argv[2]), browser);
const std::wstring url = L"https://example.com/board?view=a%20b&filter=active#notes";
app.settings.customShortcuts[0] = {L"Open board", L"Ctrl+Alt+F9", browser.wstring(), true, false,
ks::CustomShortcutAction::OpenUrl, L"", L"", 0, url, ks::ShortcutBrowser::Other};
ks::InputRegressionAccess::invokeCustomShortcut(app, 0, VK_F9);
const auto marker = temp / L"browser-fixture.exe.opened";
for (const auto deadline = GetTickCount64() + 5000; GetTickCount64() < deadline;)
{
std::error_code ec;
if (std::filesystem::file_size(marker, ec) == url.size()) break;
Sleep(25);
}
const auto recorded = ks::readFile(marker, 1024);
require(std::string(recorded.begin(), recorded.end()) == ks::utf8(url),
"URL shortcut starts the chosen browser with the complete address as one argument");
}
std::filesystem::remove_all(temp);
std::cout << "Passed " << checks << " custom shortcuts layout checks\n";
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--help-layout")
{
{
@@ -1138,7 +1275,7 @@ int main(int argc, char **argv) {
auto events = GetDlgItem(pane, 733);
auto visible = [&](int id) { return (GetWindowLongPtrW(GetDlgItem(pane, id), GWL_STYLE) & WS_VISIBLE) != 0; };
auto selectPage = [&](int index) { selectSettingsPage(settings, index); };
require(TreeView_GetCount(navigation) == 20, "all Settings sections are listed");
require(TreeView_GetCount(navigation) == 22, "all Settings sections are listed");
selectPage(3);
require(visible(243) && !visible(501), "Clipboard lists excluded apps separately from OCR");
require(TreeView_GetParent(navigation, settingsSection(navigation, 19)) == settingsSection(navigation, 3),
+8 -4
View File
@@ -48,7 +48,7 @@ void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected)
std::wstring_view(label).starts_with(expected), "incorrect input state in tray menu");
HMENU help{};
MENUITEMINFOW donation{sizeof(donation), MIIM_BITMAP};
bool donationSeparated = false;
bool donationSeparated = false, resetAvailable = false;
const auto menuTitle = [&](HMENU source, int index) {
if (!GetMenuStringW(source, index, label, std::size(label), MF_BYPOSITION)) return std::wstring_view{};
const std::wstring_view text(label);
@@ -56,6 +56,8 @@ void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected)
};
for (int i = 0, count = GetMenuItemCount(menu); i < count; ++i) {
const auto title = menuTitle(menu, i);
if (title == L"Reset held keys and mouse buttons" || title == L"Скинути затиснуті клавіші й кнопки миші")
resetAvailable = (GetMenuState(menu, i, MF_BYPOSITION) & (MF_GRAYED | MF_DISABLED)) == 0;
if (title == L"&Donate via Monobank" && i > 0 && i + 1 < count) {
donationSeparated = (GetMenuState(menu, i - 1, MF_BYPOSITION) & MF_SEPARATOR) &&
(GetMenuState(menu, i + 1, MF_BYPOSITION) & MF_SEPARATOR);
@@ -66,10 +68,12 @@ void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected)
break;
}
}
require(resetAvailable, "the tray offers manual input reset while active or paused");
require(donationSeparated && donation.hbmpItem, "tray donation item has an icon and both separators");
require(help && GetMenuItemCount(help) == 2 && menuTitle(help, 0) == L"&User guide" &&
menuTitle(help, 1) == L"&About KSwitcher",
"tray Help submenu contains User guide and About KSwitcher");
require(help && GetMenuItemCount(help) == 3 && menuTitle(help, 0) == L"&User guide" &&
menuTitle(help, 1) == ks::whatsNewTitle(GetThreadUILanguage()) &&
menuTitle(help, 2) == L"&About KSwitcher",
"tray Help submenu contains User guide, release notes and About KSwitcher");
require(PostMessageW(popup, WM_CHAR, L'i', 0), "cannot select input menu item");
until([&] { return !IsWindow(popup); }, "tray action did not close menu");
query(resident, WM_NULL);
+158 -2
View File
@@ -1,5 +1,6 @@
#include "app.h"
#include "diagnostics.h"
#include "paste_probe.h"
#include <algorithm>
#include <iostream>
#include <fstream>
@@ -61,6 +62,11 @@ namespace
{
ks::App *app{};
HWND host{}, field{};
HWND externalEditor{};
ULONGLONG externalPopupUntil{};
bool insertExternalSnippet{};
bool insertTerminalSnippet{};
constexpr wchar_t externalSnippetText[] = L"snippet test";
ks::Clip saved;
bool snippetRecoveryOnly = false;
LONG unfilteredSnippetWidth{};
@@ -79,6 +85,7 @@ bool typeDuringMacros = false;
ULONGLONG macroStart{}, macroEnd{};
int copyFailuresRemaining = 0, copyRequests = 0;
int droppedSelectionKeys = 0;
int delayedSelectionKeys = 0;
bool trimCopiedSpaces = false;
int trimmedCopies = 0;
bool temporaryClipboardExcluded = true;
@@ -152,6 +159,16 @@ LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_P
--copyFailuresRemaining;
return 0;
}
if (delayedSelectionKeys)
{
DWORD start{}, end{};
SendMessageW(w, EM_GETSEL, reinterpret_cast<WPARAM>(&start), reinterpret_cast<LPARAM>(&end));
auto result = DefSubclassProc(w, message, wp, lp);
// Apply the remaining Shift+Left moves after publishing the partial selection.
SendMessageW(w, EM_SETSEL, end, start - std::min<DWORD>(start, delayedSelectionKeys));
delayedSelectionKeys = 0;
return result;
}
if (trimCopiedSpaces)
{
auto result = DefSubclassProc(w, message, wp, lp);
@@ -278,6 +295,53 @@ void expandMacroSnippet(const wchar_t *replacement)
record(L";zmtest");
app->transform(0, 0, 0, field);
}
bool terminalShowsTestDraft()
{
using Microsoft::WRL::ComPtr;
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&automation))))
return false;
automation->put_TransactionTimeout(150);
ComPtr<IUIAutomationElement> element;
ComPtr<IUIAutomationTreeWalker> walker;
if (FAILED(automation->GetFocusedElement(&element)) || !element ||
!ks::focusedTextBelongsToWindow(automation.Get(), element.Get(), externalEditor) ||
FAILED(automation->get_RawViewWalker(&walker)) || !walker)
return false;
// The xterm accessibility tree is beside the input's screen element.
for (int depth = 0; element && depth < 3; ++depth)
{
ComPtr<IUIAutomationElement> parent;
walker->GetParentElement(element.Get(), &parent);
element = std::move(parent);
}
if (!element) return false;
VARIANT className{};
className.vt = VT_BSTR;
className.bstrVal = SysAllocString(L"xterm-accessibility-tree");
ComPtr<IUIAutomationCondition> condition;
const auto hr = automation->CreatePropertyCondition(UIA_ClassNamePropertyId, className, &condition);
VariantClear(&className);
ComPtr<IUIAutomationElement> tree, row;
if (FAILED(hr) || !condition || FAILED(element->FindFirst(TreeScope_Descendants, condition.Get(), &tree)) ||
!tree || FAILED(walker->GetLastChildElement(tree.Get(), &row))) return false;
while (row)
{
BSTR name{};
row->get_CurrentName(&name);
std::wstring_view line(name ? name : L"", SysStringLen(name));
const auto end = line.find_last_not_of(L" \t\r\n\u00a0");
const bool matches = end != line.npos && line.substr(0, end + 1).ends_with(externalSnippetText);
SysFreeString(name);
if (end != line.npos) return matches;
ComPtr<IUIAutomationElement> previous;
walker->GetPreviousSiblingElement(row.Get(), &previous);
row = std::move(previous);
}
return false;
}
void finish()
{
KillTimer(host, 1);
@@ -337,7 +401,65 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
switch (stage++)
{
case 101:
require(GetForegroundWindow() == externalEditor, "external editor retains foreground before typing");
app->settings.snippets = {{L";ksw-regression", externalSnippetText}};
app->resetInput();
externalPopupUntil = GetTickCount64() + 2000;
typeKeys({VK_OEM_1});
break;
case 102:
{
if (GetForegroundWindow() != externalEditor)
throw std::runtime_error("External editor lost foreground while typing");
const bool visible = ks::InputRegressionAccess::suggestionsVisible(*app);
if (!visible && GetTickCount64() < externalPopupUntil)
{
stage = 102;
break;
}
if (!visible) typeKeys({VK_BACK});
else if (insertExternalSnippet || insertTerminalSnippet)
{
externalPopupUntil = GetTickCount64() + 3000;
typeKeys({VK_TAB});
}
else typeKeys({VK_ESCAPE, VK_BACK});
require(visible, "semicolon shows suggestions in the external editor");
break;
}
case 103:
if (insertExternalSnippet)
{
require(GetForegroundWindow() == externalEditor, "insertion leaves the external editor focused");
ks::PasteProbe probe(true, externalEditor);
const auto text = probe.read(static_cast<int>(std::size(externalSnippetText) - 1));
const bool inserted = text && *text == externalSnippetText;
if (inserted)
{
ks::chord('A', MOD_CONTROL);
typeKeys({VK_BACK});
}
require(inserted, "Tab inserts the selected snippet in the external editor");
}
else if (insertTerminalSnippet)
{
const bool inserted = GetForegroundWindow() == externalEditor &&
!ks::InputRegressionAccess::suggestionsVisible(*app) && terminalShowsTestDraft();
if (!inserted && GetTickCount64() < externalPopupUntil)
{
stage = 103;
break;
}
require(inserted, "Tab replaces the prefix in the live shell prompt");
}
else
require(!ks::InputRegressionAccess::suggestionsVisible(*app), "Escape dismisses external suggestions");
finish();
break;
case 0:
app->settings.writeLog = true;
ks::setLoggingEnabled(true);
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
@@ -685,6 +807,26 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
case 59:
require(text() == L"OLDghbdtn NEXT", "hotkey without selection reconverts only the previous middle range");
require(ks::readClipboard(app->window).text() == sentinel, "selected and repeated conversions restore clipboard");
[[fallthrough]];
case 95:
if (!captured)
{
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
}
prepare(L" nen NEXT", false);
SendMessageW(field, EM_SETSEL, 6, 6);
record(L"nen ");
droppedSelectionKeys = delayedSelectionKeys = 2;
app->transform(ks::Direct + ru);
stage = 96;
break;
case 96:
require(text() == L" " + ks::convertTo(L"nen ", app->layouts, ru, en) + L"NEXT",
"delayed selection preserves the older prefix and text after the caret");
require(!droppedSelectionKeys && !delayedSelectionKeys, "fixture applied the delayed selection moves");
require(ks::readClipboard(app->window).text() == sentinel, "delayed selection restores clipboard");
finish();
break;
case 66:
@@ -1196,6 +1338,15 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
} // namespace
int main(int argc, char **argv)
{
const bool externalEditorTest = argc > 1 && std::string_view(argv[1]) == "--snippet-external-editor";
if (externalEditorTest)
{
insertExternalSnippet = argc > 2 && std::string_view(argv[2]) == "--insert";
insertTerminalSnippet = argc > 2 && std::string_view(argv[2]) == "--terminal-insert";
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
externalEditor = GetForegroundWindow();
if (!externalEditor) return 1;
}
conversionOnly = argc > 1 && std::string(argv[1]) == "--conversion-only";
typosOnly = argc > 1 && std::string(argv[1]) == "--typos-only";
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
@@ -1362,7 +1513,7 @@ int main(int argc, char **argv)
if (language == 0x419)
ru = i;
}
if (en < 0 || ru < 0)
if (!externalEditorTest && (en < 0 || ru < 0))
throw std::runtime_error(
"Integration test requires installed English US and Russian layouts");
WNDCLASSW cls{};
@@ -1372,7 +1523,8 @@ int main(int argc, char **argv)
cls.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
RegisterClassW(&cls);
host = CreateWindowW(cls.lpszClassName, L"KSwitcher — automated test editor",
WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 650, 320, nullptr, nullptr,
WS_OVERLAPPEDWINDOW | (externalEditorTest ? 0 : WS_VISIBLE),
100, 100, 650, 320, nullptr, nullptr,
cls.hInstance, nullptr);
field =
CreateWindowW(L"EDIT", L"", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_MULTILINE | ES_WANTRETURN,
@@ -1392,6 +1544,10 @@ int main(int argc, char **argv)
stage = 93;
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
stage = 84;
if (externalEditorTest)
stage = 101;
if (argc > 1 && std::string(argv[1]) == "--delayed-selection-only")
stage = 95;
SetTimer(host, 1, 100, nullptr);
auto forwarding = SetWindowsHookExW(WH_KEYBOARD_LL,forwardingHook,GetModuleHandleW(nullptr),0);
require(forwarding!=nullptr,"downstream forwarding fixture installed before application hook");
+36
View File
@@ -228,6 +228,42 @@ void verifyFiles(LanClients &clients, const Json &trusted, const std::wstring &p
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "replace")).at("type") == "complete" &&
read(to / L"content.txt") == content, "replace conflict policy failed");
const auto ask = [&](const char *decision, bool replaceable) {
Pipe client(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "ask"));
unsigned prompts = 0;
for (;;)
{
auto result = client.reply();
const auto type = result.value("type", "");
if (type == "progress") client.sendJson({{"continue", true}});
else if (type == "conflict")
{
++prompts;
require(result.at("path") == utf8((to / L"content.txt").native()) &&
result.at("replaceable") == replaceable &&
result.at("incoming").at("size") == content.size(), "incorrect conflict prompt");
client.sendJson({{"decision", "wait"}});
client.sendJson({{"decision", decision}});
}
else
{
client.ack();
require(prompts == 1, "ask did not report the nested collision exactly once");
return result;
}
}
};
save(to / L"content.txt", "keep me");
require(ask("skip", true).at("skipped") == 1 && read(to / L"content.txt") == "keep me",
"skipping a prompted collision changed its destination");
require(ask("replace", true).at("type") == "complete" && read(to / L"content.txt") == content,
"confirming a prompted collision did not replace its destination");
fs::remove(to / L"content.txt");
fs::create_directory(to / L"content.txt");
require(ask("replace", false).contains("error") && fs::is_directory(to / L"content.txt"),
"a prompted type mismatch allowed replacement");
fs::remove(to / L"content.txt");
const auto localCopy = root / L"local.txt";
const auto fromLocal = transfer(endpoint(nullptr, file), endpoint(b, dst / L"from-local.txt"), false);
require(runTransfer(pipe, fromLocal).contains("error"), "identification-only pipe accessed local files");
+75 -5
View File
@@ -13,7 +13,8 @@ void check(bool value,const char *text){if(!value)throw std::runtime_error(text)
template<class F>void rejects(F f,const char *text){bool failed=false;try{f();}catch(...){failed=true;}check(failed,text);}
struct Desktop
{
RECT rect{-1920,-200,0,880};POINT point{-1000,300};bool available=true,physicalHeld=false,allow=true;
RECT rect{-1920,-200,0,880};POINT point{-1000,300};bool available=true,allow=true;
int heldKey{};
std::vector<INPUT> events;int dpi=96;bool delayed=false;InputRouter *router{};
InputEnvironment environment()
{
@@ -26,7 +27,7 @@ struct Desktop
if(router){MSLLHOOKSTRUCT m{};m.pt=point;m.flags=LLMHF_INJECTED;m.dwExtraInfo=i.mi.dwExtraInfo;router->mouse(WM_MOUSEMOVE,m,1000);}
}
return true;
},[this]{return available;},[this]{return physicalHeld;},{},{},[this](POINT){return dpi;}};
},[this]{return available;},[this]{return heldKey;},{},{},[this](POINT){return dpi;}};
}
unsigned keyEvents(bool down)const
{return unsigned(std::count_if(events.begin(),events.end(),[down](auto &i){return i.type==INPUT_KEYBOARD&&bool(i.ki.dwFlags&KEYEVENTF_KEYUP)!=down;}));}
@@ -205,9 +206,9 @@ void routerChecks()
p.b.available=true;p.right.tick(true,1400);check(p.b.keyEvents(false)==1,"blocked release retried when normal desktop returns");
}
{
Pair p(1);p.a.physicalHeld=true;motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1000);
Pair p(1);p.a.heldKey=VK_TAB;motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1000);
check(p.left.mode()==ControlMode::Local,"no cross-screen handoff with physically held key/button");
p.a.physicalHeld=false;motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1100);
p.a.heldKey=0;motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1100);
p.left.keyboard(key('X'),true,1101);p.deliver(1200);
check(p.left.mode()==ControlMode::Local&&p.right.mode()==ControlMode::Local,"typing during handoff cancels stale accept");
}
@@ -298,6 +299,75 @@ void meshChecks()
f.connections[0]["2"]=2;f.pump();check(f.meshes[0]->mode()==ControlMode::Local,"new connection generation does not continue stale ownership");
}
}
void handoffBlockChecks()
{
for(int blockedPc:{0,1})
for(int heldKey:{VK_TAB,VK_LBUTTON,UnknownHeldInput})
{
MeshFixture f;
f.desktops[blockedPc].heldKey=heldKey;
f.desktops[0].point={798,300};
f.move(1,0);
const auto sourceBlock=f.meshes[0]->handoffBlock();
const auto blockedPcBlock=f.meshes[blockedPc]->handoffBlock();
check(f.meshes[0]->mode()==ControlMode::Local&&sourceBlock.key==heldKey&&
sourceBlock.peer==(blockedPc==0?"":"1")&&blockedPcBlock.key==heldKey&&blockedPcBlock.peer.empty(),
"held input blocks the handoff and names the PC that is holding it");
f.desktops[blockedPc].heldKey=0;
f.pump();
check(!f.meshes[0]->handoffBlock().key&&!f.meshes[blockedPc]->handoffBlock().key,
"release clears both notices without another crossing attempt");
f.now+=650;
f.enter();
}
{
MeshFixture f;
f.meshes[1]->keyboard(key(VK_MEDIA_PLAY_PAUSE),true,f.now);
f.desktops[1].heldKey=VK_MEDIA_PLAY_PAUSE;
f.desktops[0].point={798,300};
f.move(1,0);
check(f.meshes[0]->handoffBlock().key==VK_MEDIA_PLAY_PAUSE,"tracked media key reports the Windows key identity");
f.desktops[1].heldKey=0;
f.meshes[1]->forgetHeldKeys();
f.pump();
check(!f.meshes[0]->handoffBlock().key&&!f.meshes[1]->handoffBlock().key,
"manual reset also clears previously tracked held keys");
f.now+=650;
f.enter();
}
{
MeshFixture f;
f.desktops[1].heldKey=VK_TAB;
f.desktops[0].point={798,300};
f.move(1,0);
f.desktops[1].heldKey=VK_XBUTTON2;
f.pump();
check(f.meshes[0]->handoffBlock().key==VK_XBUTTON2,"source notice updates when the destination blocker changes");
f.connections[0]["1"]=2;
f.pump();
check(!f.meshes[0]->handoffBlock().key,"a reconnect discards notices from the prior connection generation");
}
}
void heldInputReleaseChecks()
{
const auto releases=heldInputReleases([](int key){
return key==VK_MEDIA_PLAY_PAUSE||key==VK_LBUTTON||key==VK_XBUTTON2||key==VK_CONTROL||key==VK_RCONTROL;
});
check(releases.size()==4,"reset includes only down inputs and does not duplicate a generic modifier");
check(releases[0].type==INPUT_MOUSE&&releases[0].mi.dwFlags==MOUSEEVENTF_LEFTUP&&
releases[0].mi.dwExtraInfo==inputMarker(),"reset releases the left mouse button without running mouse bindings");
check(releases[1].type==INPUT_MOUSE&&releases[1].mi.dwFlags==MOUSEEVENTF_XUP&&
releases[1].mi.mouseData==XBUTTON2,"reset releases the correct extra mouse button");
check(releases[2].type==INPUT_KEYBOARD&&releases[2].ki.wVk==VK_RCONTROL&&
(releases[2].ki.dwFlags&KEYEVENTF_KEYUP),"reset releases the specific modifier");
check(releases[3].type==INPUT_KEYBOARD&&releases[3].ki.wVk==VK_MEDIA_PLAY_PAUSE&&
releases[3].ki.dwFlags==(KEYEVENTF_KEYUP|KEYEVENTF_EXTENDEDKEY)&&releases[3].ki.dwExtraInfo==inputMarker(),
"reset releases Play/Pause without generating a media key press");
check(heldInputName(VK_TAB)==L"Tab"&&heldInputName(VK_MEDIA_PLAY_PAUSE)==L"Play/Pause"&&
heldInputName(VK_LBUTTON)==L"Left mouse button"&&heldInputName(UnknownHeldInput).empty(),
"known blockers have readable names and unknown ones use the general message");
check(heldInputReleases([](int){return false;}).empty(),"reset with no down inputs is a no-op");
}
uint16_t freePort()
{
SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(s==INVALID_SOCKET)throw std::runtime_error("test socket");
@@ -567,6 +637,6 @@ void channelChecks()
}
int main()
{
try{channelChecks();hubChecks();offlineDiscoveryChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
try{channelChecks();hubChecks();offlineDiscoveryChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();handoffBlockChecks();heldInputReleaseChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
catch(const std::exception &e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}
}
+42
View File
@@ -449,6 +449,18 @@ int main(int argc, char **argv)
"cycle does not use disabled English when all candidates are unchanged");
require(ks::nextConversionLayout(L"123 ", layouts, {0, 1, 2}, 0) == 1,
"unchanged digits finish after a bounded cycle");
auto digitLayouts = layouts;
digitLayouts[2].handle = reinterpret_cast<HKL>(static_cast<ULONG_PTR>(0xf0a80422));
ks::Run digitRun;
digitRun.layout = digitLayouts[2].handle;
digitRun.keys = L"4732";
const int digitSource = digitRun.match(L"4732", digitLayouts, en);
require(digitSource == 2 && ks::nextConversionLayout(L"4732", digitLayouts, {1, 0, 2}, digitSource) == 1 &&
ks::convertTo(L"4732", digitLayouts, 1, digitSource) == L"4732",
"shared digits advance from the tracked Ukrainian layout to Russian without changing text");
digitRun.keys = L"ghbdtn";
require(digitRun.match(L"ghbdtn", digitLayouts, en) == 0,
"recent input falls back when the tracked layout does not reproduce the selection");
require(ks::nextConversionLayout(L"рф", layouts, {2, 0}, 1) == 0,
"source outside cycle still skips unchanged candidates");
require(ks::cycleCase(L"hello world") == L"Hello World", "title case");
@@ -865,6 +877,36 @@ int main(int argc, char **argv)
rejects([&] { ks::validateSettings(captureSettings); }, "screen capture shortcut duplicates rejected");
captureSettings.screenshot.clear();
ks::validateSettings(captureSettings);
ks::Settings custom;
custom.customShortcuts = {
{L"Activate editor", L"Ctrl+Alt+F9", L"C:\\Apps\\Editor.exe"},
{L"New editor", L"Ctrl+Alt+F10", L"C:\\Apps\\Editor.exe", false, true},
{L"Insert note", L"Ctrl+Alt+F11", L"C:\\Apps\\Editor.exe", true, false,
ks::CustomShortcutAction::SendText, L"Edit", L"First line\r\nSecond line", 101},
{L"Open board", L"Ctrl+Alt+F12", L"", true, false, ks::CustomShortcutAction::OpenUrl,
L"", L"", 0, L"https://example.com/board", ks::ShortcutBrowser::Chrome, L"Profile 1"},
};
require(ks::decodeSettings(ks::encodeSettings(custom), {}).customShortcuts == custom.customShortcuts,
"custom shortcut actions, launch modes, text and enabled state roundtrip");
custom.customShortcuts[0].shortcut = custom.toggle;
rejects([&] { ks::validateSettings(custom); }, "custom shortcuts cannot shadow built-in shortcuts");
custom.customShortcuts[0].enabled = false;
ks::validateSettings(custom);
auto &web = custom.customShortcuts.back();
web.url = L"file:///C:/Windows/notepad.exe";
rejects([&] { ks::validateSettings(custom); }, "URL shortcut requires HTTP or HTTPS");
web.url = L"https://example.com/a%20b?q=one%20two#result";
web.chromeProfile = L"..\\Other";
rejects([&] { ks::validateSettings(custom); }, "Chrome profile must be a single directory name");
web.chromeProfile.clear();
web.browser = ks::ShortcutBrowser::Other;
rejects([&] { ks::validateSettings(custom); }, "specific browser requires an executable");
web.executable = L"C:\\Apps\\Browser.exe";
require(ks::decodeSettings(ks::encodeSettings(custom), {}).customShortcuts == custom.customShortcuts,
"URL shortcut and specific browser roundtrip");
custom.customShortcuts[2].controlClass.clear();
rejects([&] { ks::validateSettings(custom); }, "text shortcuts require a target control");
require(ks::loadSettings(temp / L"defaults.json", {}).screenshot == L"Win+Shift+S",
"screen capture default for existing settings");
invalid.undo = invalid.toggle;
+1 -1
View File
@@ -178,7 +178,7 @@ try {
Assert ([IO.File]::ReadAllText((Join-Path $target 'KSwitcher.exe')) -eq 'old binary fixture') 'partial install rollback'
if ($Network) {
$metadata=Join-Path $root 'live-releases.json'
Receive-File 'https://gitea.hrynco.com/api/v1/repos/hrynco/hrynco-kswitcher/releases?limit=100' $metadata 2MB
Receive-ReleaseMetadata $metadata
$live=Select-Release (Get-Content -LiteralPath $metadata -Raw | ConvertFrom-Json) ([version]'0.0.0')
Assert ($null -ne $live) 'live repository exposes a complete stable release'
$liveZip=Join-Path $root 'live.zip'; $liveSum=Join-Path $root 'live-sums.txt'
+1 -1
View File
@@ -9,7 +9,7 @@ try {
if ($script:progressWindow.Percent -ne 42) { throw 'Determinate download progress missing' }
$script:progressWindow.SavePreview((Join-Path $PreviewDirectory 'download.png'))
if ($Network) {
Receive-File 'https://gitea.hrynco.com/api/v1/repos/hrynco/hrynco-kswitcher/releases?limit=100' (Join-Path $PreviewDirectory 'releases.json') 2MB 'Downloading update'
Receive-ReleaseMetadata (Join-Path $PreviewDirectory 'releases.json') 'Downloading update'
if ($script:progressWindow.Percent -ne 100) { throw 'Real download did not finish at 100 percent' }
}
foreach ($stage in @('Verifying download','Preparing installation','Closing KSwitcher','Installing update','Restarting KSwitcher','Restoring previous version')) {