Compare commits

..
Author SHA1 Message Date
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 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
43 changed files with 1803 additions and 301 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.4 LANGUAGES C CXX RC)
project(KSwitcher VERSION 0.8.9 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 копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано.
+16
View File
@@ -46,6 +46,22 @@ 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 — v0.8.9
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. 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. Застосуйте зміни кнопкою **Apply**
або **Save**. Власні шорткати зберігаються на цьому ПК.
## Mouse buttons for applications
In **Settings → Mouse**, put the pointer over **Test mouse buttons here** and
+42
View File
@@ -1,5 +1,47 @@
# Latest Windows release
## 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**.
+1 -1
View File
@@ -1 +1 @@
9035578c4aa96533a78dd1830966cf0b2f8d9de623f51ec2d111e62249d1c65d KSwitcher-win-x64.zip
7e84ab435ddf4e5602773cad918669199c40e71796793889ec5b018b2c41075d KSwitcher-win-x64.zip
+72 -72
View File
@@ -1,181 +1,181 @@
{
"schema": 1,
"version": "0.8.9",
"files": [
{
"size": 3281920,
"path": "KSwitcher.exe",
"sha256": "a7ad4db3cb46825c65b851c7e4cbd214f779eb5325a91ca7cdb96a3fe944d8a4",
"size": 3251712
"sha256": "854a5a14abcbe86e0cfafe127a094c16af328bd5f8ddc27e43d7a66b2ebb67dd"
},
{
"size": 2870272,
"path": "KSwitcher.Config.exe",
"sha256": "c9d2dddc6e2a5e14be02680c1177e4813515e207bada399f255fcbf4aef5e884",
"size": 2850304
"sha256": "653b3b015e664c6501782f3278d04600165745a1901420c8a4b1b377195a66c0"
},
{
"size": 3200000,
"path": "KSwitcher.Screenshot.exe",
"sha256": "1112fd25921d49ef20b3f71b0b8234eea3e9df47b1c1d207bfa22a9f7da34028",
"size": 3193344
"sha256": "a67f5ee11cc6f1da2e09661ccd7fdd421d521f98d1fc3dfaefce115cf3cfc668"
},
{
"size": 6018560,
"path": "KSwitcher.Files.exe",
"sha256": "b2843967c9b70839e45ec3b8b48bffde41ff8994ea345317beb1bda28e6d6dff",
"size": 6002688
"sha256": "f0594a10f2176fed1b9755ab72b09a86dd31957af4ad766e101dee185eb91d3c"
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"size": 527,
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"size": 100786,
"path": "terminal/markdown-it.js",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"size": 3800,
"path": "terminal/markdown.html",
"sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2",
"size": 3800
"sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2"
},
{
"size": 18721,
"path": "terminal/markdown.js",
"sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96",
"size": 18721
"sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96"
},
{
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"size": 5537838,
"path": "terminal/mermaid.js",
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"size": 6627,
"path": "terminal/terminal.js",
"sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7",
"size": 6627
"sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7"
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"size": 7112,
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"size": 488663,
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"size": 4401,
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
},
{
"size": 1096,
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
},
{
"size": 883,
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"size": 4990,
"path": "files-archive-license.txt",
"sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d",
"size": 4990
"sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d"
},
{
"size": 3044,
"path": "files-image-license.txt",
"sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4",
"size": 3044
"sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4"
},
{
"size": 2064,
"path": "files-sftp-license.txt",
"sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594",
"size": 2064
"sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594"
},
{
"size": 107782,
"path": "README.md",
"sha256": "7f179b561fab6125f167203a6ae180a7050d876b056c39f62f3be36cf4bad733",
"size": 105904
"sha256": "72202f92d2a28d3467a0aead095557e8638029eb95583073b2ba63f55bed03eb"
},
{
"size": 17245,
"path": "LAN-PREVIEW.md",
"sha256": "4eac1f410e6b544aa45756e24f4fdfe9193c6f732410656160be54ab27a0d7e4",
"size": 17245
"sha256": "4eac1f410e6b544aa45756e24f4fdfe9193c6f732410656160be54ab27a0d7e4"
},
{
"size": 732485,
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
},
{
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
},
{
"size": 2265,
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"size": 1109134,
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"size": 993,
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
},
{
"size": 133120,
"path": "tools/StayHere.exe",
"sha256": "1530796fac99f1542b992e4254fc30c16c24ee7e6c6dc7b6ba41d241e3ea6417",
"size": 133120
"sha256": "48fff08d0010e9319418f777e8009393cd5719a6219e49fa8dd0cb27dea1653c"
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
],
"version": "0.8.4"
]
}
+3 -3
View File
@@ -14,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,8,4,0
PRODUCTVERSION 0,8,4,0
FILEVERSION 0,8,9,0
PRODUCTVERSION 0,8,9,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.4"
VALUE "FileVersion", "0.8.9"
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)." }
+78 -12
View File
@@ -228,6 +228,7 @@ constexpr int OpenFiles = 25, FilesHotkeyFirst = 0x4B10, FilesHotkeySecond = 0x4
constexpr int ToggleInputProcessing = 26, DonateViaMonobank = 27, OpenHelp = 28, OpenWhatsNew = 29, OpenAbout = 16;
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)
@@ -259,6 +260,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},
@@ -269,6 +294,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)
@@ -741,21 +769,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));
}
@@ -1982,7 +2007,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)
{
@@ -3700,6 +3725,36 @@ 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::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);
@@ -4073,6 +4128,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)
@@ -4098,6 +4163,7 @@ int App::execute()
DispatchMessageW(&msg);
}
if(screenshotActivation) CoRevokeClassObject(screenshotActivation);
if (foregroundHook) UnhookWinEvent(foregroundHook);
return (int)msg.wParam;
}
} // namespace ks
+1
View File
@@ -189,6 +189,7 @@ class App
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{};
+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
+12
View File
@@ -82,6 +82,17 @@ struct MouseAction
int volumeStep = DefaultMouseVolumeStep;
bool operator==(const MouseAction &) const = default;
};
enum class CustomShortcutAction { LaunchApp, SendText };
struct CustomShortcut
{
std::wstring name, shortcut, executable;
bool enabled = true;
bool newInstance = false;
CustomShortcutAction action = CustomShortcutAction::LaunchApp;
std::wstring controlClass, text;
int controlId = 0;
bool operator==(const CustomShortcut &) const = default;
};
struct Settings
{
bool recent = true, switchLayout = true, history = true, autostart = false, awake = false;
@@ -109,6 +120,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)
{
+15 -7
View File
@@ -47,6 +47,7 @@ class PasteProbe
IUIAutomation2 *automation{};
IUIAutomationElement *element{};
IUIAutomationTextPattern *pattern{};
HWND targetWindow{};
static std::optional<std::wstring> rangeText(IUIAutomationTextRange *range)
{
@@ -61,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;
@@ -73,13 +74,15 @@ class PasteProbe
automation->put_TransactionTimeout(200);
if (FAILED(automation->GetFocusedElement(&element)) || !element)
return;
if (target)
if (target && GetForegroundWindow() != target)
{
if (GetForegroundWindow() != target || !focusedTextBelongsToWindow(automation, element, 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)
@@ -128,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";
+39 -6
View File
@@ -289,7 +289,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 +300,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)
{
@@ -676,9 +707,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 +718,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)
{
+4 -1
View File
@@ -49,6 +49,9 @@ 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 &);
enum class ClipboardRead { All, Selection, WithoutImages };
@@ -75,7 +78,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();
+62
View File
@@ -207,6 +207,25 @@ 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.");
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::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 +392,27 @@ 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");
if (action != "launchApp" && action != "sendText") throw std::runtime_error("Unknown custom shortcut action.");
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 shortcut.newInstance = rule.value("newInstance", false);
s.customShortcuts.push_back(std::move(shortcut));
}
}
s.screenshotAutoOpenEditor = j.value("screenshotAutoOpenEditor", false);
if (j.contains("layouts"))
{
@@ -533,6 +573,28 @@ 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
{
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"];
+26 -1
View File
@@ -1211,6 +1211,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 +1258,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 +1402,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 +1872,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 +2437,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 +2558,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 +2593,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);
@@ -2974,6 +2990,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 +3083,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 +4084,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)
{
+278
View File
@@ -0,0 +1,278 @@
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;
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::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;
};
void stageCustomShortcuts(SettingsView &view, std::vector<CustomShortcut> rules)
{
auto proposed = collectSettings(&view, &rules);
view.draft.customShortcuts = std::move(proposed.customShortcuts);
}
bool shortcutSendsText(HWND w)
{
return SendDlgItemMessageW(w, RuleAction, CB_GETCURSEL, 0, 0) == 1;
}
void refreshCustomShortcutEditor(HWND w)
{
const bool sendsText = shortcutSendsText(w);
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 : {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 ? SW_HIDE : SW_SHOWNA);
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 (shortcutSendsText(w))
{
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 (shortcutSendsText(w)) editor->launchExecutable = value(w, RuleExecutable);
refreshCustomShortcutEditor(w);
value(w, RuleExecutable, shortcutSendsText(w) ? editor->targetExecutable : editor->launchExecutable);
return 0;
}
if (id == RuleBrowse)
{
const auto path = chooseApplicationFile(w, L"Programs (*.exe)\0*.exe\0");
if (!path.empty()) value(w, RuleExecutable, 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 (shortcutSendsText(w))
{
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.");
}
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 = makeWindow(*view.app, L"KSwitcher.CustomShortcut", editing ? L"Edit shortcut" : L"Add shortcut",
customShortcutProc, 620, 425, 0, false, owner);
windowLayoutState(w)->fixedClient = true;
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"", sendsText ? L"" : rule.executable, rule.controlId};
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"})
SendDlgItemMessageW(w, RuleAction, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(action));
SendDlgItemMessageW(w, RuleAction, CB_SETCURSEL, sendsText, 0);
label(w, L"&Program", 22, 137, 576);
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);
if (editing) button(w, L"&Remove", RuleRemove, 22, 370, 90);
control(w, L"BUTTON", editing ? L"Save shortcut" : L"Add shortcut", WS_TABSTOP | WS_GROUP | BS_DEFPUSHBUTTON,
IDOK, 478, 370, 120, 28);
button(w, L"Cancel", IDCANCEL, 376, 370, 90);
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);
CheckRadioButton(w, RuleReuseWindow, RuleNewInstance, rule.newInstance ? RuleNewInstance : RuleReuseWindow);
refreshCustomShortcutEditor(w);
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);
}
}
+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.4";
inline constexpr wchar_t AppVersion[] = L"0.8.9";
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),
+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)
}
+82 -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,83 @@ 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.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");
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");
DestroyWindow(dialog);
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");
}
}
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 +1219,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) == 21, "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),
+35
View File
@@ -85,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;
@@ -158,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);
@@ -447,6 +458,8 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
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));
@@ -794,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:
@@ -1513,6 +1546,8 @@ int main(int argc, char **argv)
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");
+28
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,22 @@ 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},
};
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);
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')) {