Compare commits

...
Author SHA1 Message Date
agrynco bc086873ba Merge pull request 'Promote prerelease to main for KSwitcher v0.8.8' (#218) from prerelease into main 2026-11-28 15:16:43 +02:00
agrynco a1aa432355 Merge pull request 'Prepare KSwitcher v0.8.8 with contrasting Lavender popups' (#217) from codex/deliver-v0.8.8 into prerelease 2026-11-28 15:16:29 +02:00
agrynco 919f8e9c7c Ship contrasting Lavender popup frames in v0.8.8
Refs #9
2026-11-28 15:16:17 +02:00
agrynco e852da8fcd Merge pull request 'Promote prerelease to main for KSwitcher v0.8.7' (#216) from prerelease into main 2026-11-28 15:04:14 +02:00
agrynco 79aeff1c8b Merge pull request 'Prepare KSwitcher v0.8.7 with Change drive fixes' (#215) from codex/deliver-v0.8.7 into prerelease 2026-11-28 15:04:04 +02:00
agrynco 03f5a8db7c Ship Change drive shortcuts and complete disk capacity values in v0.8.7
Refs #9
2026-11-28 15:03:53 +02:00
agrynco 99c8b6191f Merge pull request 'Promote prerelease to main for KSwitcher v0.8.6' (#214) from prerelease into main 2026-11-28 14:52:09 +02:00
agrynco 50804185f4 Merge pull request 'Prepare KSwitcher v0.8.6 for stable delivery' (#213) from codex/deliver-v0.8.6 into prerelease 2026-11-28 14:51:08 +02:00
agrynco a9866d6973 Record KSwitcher v0.8.6 package manifest and checksum 2026-11-28 14:49:16 +02:00
agrynco 7b70105168 Use current pane source checks for Space Analyzer
Refs #94
2026-11-28 14:46:55 +02:00
agrynco b076dcb303 Open Space Analyzer directly in a Files pane
Refs #94
2026-11-28 14:44:26 +02:00
agrynco 8bedb9ffbd Set KSwitcher version to v0.8.6 2026-11-28 14:44:25 +02:00
agrynco 8f52bf2a8f Preserve fallback when the fast scan cannot read the root 2026-11-28 14:44:04 +02:00
agrynco 359b9ce284 Batch local NTFS folder-size scans 2026-11-28 14:38:46 +02:00
agrynco 160cece79d Prefer the tracked layout when recent input matches several layouts 2026-11-28 14:38:30 +02:00
agrynco 2869d584d8 Check the latest stable release without fetching release history 2026-11-28 14:37:05 +02:00
agrynco 2db1d79c1d Run delayed selection regression independently
Refs #135
2026-11-28 14:36:34 +02:00
agrynco fb27ad8843 Recover recent text selection in Claude and verify hosted editors
Refs #135

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

Refs #122

Refs #196
2026-11-27 10:53:35 +02:00
agrynco f2e403dd39 Merge pull request 'Allow trusted LAN clients to resolve transfer conflicts' (#206) from codex/dirlume-transfer-conflicts into prerelease 2026-11-27 10:00:16 +02:00
agrynco 85cdce1b01 Allow trusted LAN clients to resolve transfer conflicts
Refs #122
2026-11-27 09:57:45 +02:00
agrynco 4acff70e49 Merge pull request 'Move chat language profiles into Settings' (#205) from codex/issue-204-chat-languages into prerelease 2026-11-27 03:27:33 +02:00
agrynco 20bd93b76b Move chat language profiles into Settings
Refs #204
2026-11-27 03:26:54 +02:00
agrynco a63e3534c1 Release KSwitcher v0.8.3 with compact Files breadcrumbs (#203)
Refs #201
2026-11-26 22:02:06 +02:00
agrynco e2b9a65237 Prepare KSwitcher v0.8.3 for delivery
Refs #201
2026-11-26 22:00:30 +02:00
agrynco e7ef2e600b Use compact breadcrumbs above Files panels in Lavender
Refs #201
2026-11-26 21:18:21 +02:00
agrynco 211a5e0b59 Merge pull request 'Release KSwitcher v0.8.2' (#200) from codex/release-v0.8.2 into prerelease 2026-11-26 12:32:47 +02:00
agrynco 0ad8d7f6aa Release KSwitcher v0.8.2 with Lavender Files appearance
Port the optional Lavender style to the current Files panels and dialogs while retaining the 0.8 navigation and transfer features.
2026-11-26 12:31:22 +02:00
agrynco ce36d73b66 Merge pull request 'Show release notes after updating and in Help' (#197) from codex/issue-196-whats-new into prerelease
Show release notes after updating and in Help
2026-11-26 08:20:09 +02:00
agrynco aa90645c98 Show release notes after updating and in Help
Refs #196
2026-11-26 08:18:46 +02:00
agrynco 07646d3642 Merge pull request 'Release KSwitcher v0.8.1' (#195) from codex/release-v0.8.1 into prerelease
Release KSwitcher v0.8.1
2026-11-26 07:52:02 +02:00
agrynco 9a5479b8f9 Release KSwitcher v0.8.1 2026-11-26 07:51:19 +02:00
agrynco 9edb27c765 Merge pull request 'Open Recent folders in the selected file panel' (#194) from codex/recent-folders-in-panel into prerelease
Open Recent folders in the selected file panel
2026-11-26 00:39:09 +02:00
agrynco 5194e2b621 Keep long recent folder names readable and stabilize UI checks
Refs #88
2026-11-26 00:37:46 +02:00
agrynco da914168e8 Open Recent folders in the selected file panel
Refs #88
2026-11-26 00:34:53 +02:00
agrynco 15bf006a19 Merge pull request 'Show SMB connections and shares in the file panel' (#193) from codex/smb-profiles-in-panel into prerelease
Show SMB connections and shares in the file panel
2026-11-26 00:26:50 +02:00
agrynco 9b5cff122d Show SMB connections and shares in the file panel
Refs #109
2026-11-26 00:25:22 +02:00
agrynco 7670616dc4 Merge pull request 'Release KSwitcher v0.8.0' (#192) from codex/release-v0.8.0 into prerelease
Release KSwitcher v0.8.0
2026-11-26 00:02:28 +02:00
61 changed files with 4300 additions and 1116 deletions

No files matched your search

+39 -4
View File
@@ -1,17 +1,18 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.8.0 LANGUAGES C CXX RC)
project(KSwitcher VERSION 0.8.8 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)
@@ -36,7 +37,7 @@ add_custom_target(check-files-quick-view
DEPENDS KSwitcherFiles
VERBATIM)
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr userenv KSwitcherFilesImage libssh2::libssh2)
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr userenv dwmapi KSwitcherFilesImage libssh2::libssh2)
if(MSVC)
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
else()
@@ -81,7 +82,8 @@ set_property(SOURCE resources/help.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/help-guide.md"
"${CMAKE_CURRENT_SOURCE_DIR}/README.md"
"${CMAKE_CURRENT_SOURCE_DIR}/FILES-UI.md"
"${CMAKE_CURRENT_SOURCE_DIR}/LAN-PREVIEW.md")
"${CMAKE_CURRENT_SOURCE_DIR}/LAN-PREVIEW.md"
"${CMAKE_CURRENT_SOURCE_DIR}/Release/README.md")
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc resources/help.rc)
target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
target_link_libraries(KSwitcher PRIVATE kscore)
@@ -149,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)
@@ -239,11 +249,36 @@ add_test(NAME files-smb-password
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_smb_password.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-smb-password PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_test(NAME files-recent-folders-panel
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-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"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-lavender PROPERTIES RUN_SERIAL TRUE TIMEOUT 55)
add_test(NAME files-space-analyzer-layout
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-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
+46 -26
View File
@@ -1,5 +1,13 @@
# Оформлення KSwitcher Files
**F9 → Options → Appearance → Window style → Lavender** вмикає світлі
заокруглені панелі, виділення поточного рядка, смугу команд і оформлення
власних діалогів та налаштувань. Діалоги файлових операцій мають темний
заголовок, помітну рамку й білі поля на лавандовому тлі. Попередження мають
червоний заголовок. За замовчуванням увімкнено Far. Гарячі клавіші діють в обох стилях.
У Lavender меню вибору диска, меню команд, пошук панелі та підказки команд мають
світло-лавандове тло та контрастну фіолетову рамку завтовшки 2 пікселі за масштабу 100%.
Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far.
Іконка головного вікна показує дві сині панелі з бірюзовою рамкою та виділеним рядком.
@@ -111,12 +119,15 @@ Warning і початковий фокус на No.
підтримувати атомарне перейменування OpenSSH. Якщо сервер відмовляє
в заміні, Files показує причину й зберігає попередній файл.
- **SMB** у меню джерел обох панелей відкриває збережені підключення.
**New** додає назву й сервер або повний UNC-шлях. **Open** для сервера
показує видимі дискові шари. Відомий прихований шар можна додати як
повний UNC-шлях. Вибір шару або відкриття профілю з UNC-папкою переходить
до цієї папки в панелі, з якої викликали меню.
- Для SMB діють дозволи Windows. **Sign in** використовує вказаний
- **SMB** у меню джерел показує збережені підключення у вибраній панелі.
**Shift+F4** додає профіль із сервером або повним UNC-шляхом.
**F4** редагує профіль, **F8** запитує підтвердження видалення.
**Enter** або подвійний клік відкриває профіль. Сервер показує видимі
дискові шари в тій самій панелі, а шар або профіль із повним UNC-шляхом
відкриває папку. Відомий прихований шар можна додати як повний UNC-шлях.
**Esc** або рядок `..` повертає зі списку шарів до профілів.
**Esc** зі списку профілів повертає попередню папку.
- Для SMB діють дозволи Windows. **Sign in** у контекстному меню профілю використовує вказаний
обліковий запис. Прапорець **Remember in Windows Credential Manager**
типово вимкнений. Коли його ввімкнено, після успішного підключення Windows
зберігає облікові дані для цього профілю. **Remove** видаляє профіль і
@@ -172,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 запускається
@@ -456,6 +468,8 @@ Warning і початковий фокус на No.
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
На локальному NTFS підрахунок читає записи каталогів пакетами та паралельно
обходить підпапки. Для інших файлових систем діє звичайний обхід.
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
позначених папок в інших рядках рахує позначені папки. Без позначок
F3 рахує папку під курсором або відкриває файл. Папки обробляються по черзі,
@@ -592,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. Звичайний обхід працює без такого доступу.
@@ -633,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 копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано.
@@ -706,12 +722,13 @@ Warning і початковий фокус на No.
показують перший кадр. Пошкоджені та надто великі файли показують повідомлення.
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
останні відвідані локальні, FTP, SFTP та LAN-папки. Повторний візит підіймає
один запис угору, порядок зберігається після перезапуску. Enter або клік
відкриває шлях у панелі, з якої викликали меню. Віддалені записи містять
шлях і ідентифікатор збереженого FTP- чи SFTP-профілю або спареного ПК. Паролі
зберігаються в захищених налаштуваннях профілів. Delete прибирає вибраний
запис із недавніх.
останні відвідані локальні, FTP, SFTP та LAN-папки у вибраній панелі.
**Enter** або подвійний клік відкриває папку в тій самій панелі.
**Delete** прибирає запис із недавніх. **Esc** повертає попередню папку.
Повторний візит підіймає один запис угору, порядок зберігається після
перезапуску. Віддалені записи містять шлях і ідентифікатор збереженого
FTP- чи SFTP-профілю або спареного ПК. Паролі зберігаються в захищених
налаштуваннях профілів.
- Кнопки ← та → переходять назад і вперед в історії відповідної панелі,
зокрема між локальними, FTP, SFTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..`
@@ -722,6 +739,9 @@ Warning і початковий фокус на No.
попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
а Esc повертає до тих самих панелей і курсора.
- Над обома панелями працює спільний компонент рядка шляху. У Lavender кнопки
навігації стоять ліворуч, а сегменти за шириною підпису розділяються знаком `›`.
Назва поточної папки виділена напівжирним шрифтом і заокругленим фоном.
- У заголовку FTP- чи SFTP-папки клік по назві профілю відкриває збережені
підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери
+10 -2
View File
@@ -35,7 +35,8 @@ retain their original reply formats.
- `capabilities` optionally takes a `peer`. It returns the broker `protocol`
(2), `hostRevision`, and boolean `write`, `delete`, `move`,
`revisionRead`, `onHostTransfer`, and `localEndpoint` fields. With no peer,
`revisionRead`, `onHostTransfer`, `localEndpoint`, and optional
`conflictPrompt` fields. With no peer,
the fields describe the local broker and its grants. With a peer, the flags
also account for its supported protocol. A peer with revision 0 still
supports legacy browsing and downloading.
@@ -57,7 +58,8 @@ retain their original reply formats.
The recycle bin is subject to Windows availability on the paired host.
- `transfer` takes `source` and `target` objects with a `peer` and `path`
each, optional `move` (default false), and a `conflict` policy of `fail`
(default), `skip`, or `replace`. Replace merges directories and replaces
(default), `skip`, `replace`, or `ask` when `conflictPrompt` is available.
Replace merges directories and replaces
regular files after validating the destination revision. The broker
allows at most one local endpoint, represented by `"peer": null`. For a
local endpoint the client must open the pipe with Windows impersonation
@@ -69,6 +71,12 @@ retain their original reply formats.
final frame has `type: "complete"` and counts, or an error. Transfers
on one paired computer use its own file service even across drives. The
local pipe exchanges only control and status for transfers.
- Ask merges directories and reports individual collisions in a JSON frame
with `type: "conflict"`, target `path`, `incoming` and `existing` metadata
(as in `stat`), and boolean `replaceable`. Respond with a JSON frame
containing `decision: "replace"`, `"skip"`, or `"cancel"`. Send
`decision: "wait"` at least once every five seconds while a prompt is open.
Access is checked again after each reply and before publishing the file.
- For a move, the copy phase finishes before source deletion begins.
Skipped items remain at the source. Cancellation or failure can leave
previously completed destination items. Failure during source cleanup
+20 -8
View File
@@ -440,9 +440,10 @@ Drag the divider to resize navigation. The window remembers its size, position,
Switching sections preserves your edits. Save, Cancel, Import and Export stay below every page.
Open the desired chat in Telegram Desktop or Microsoft Teams, then open Settings → Languages →
**Languages for a chat…**. Select the chat and click the languages to include. Choose
**Use languages**, then **Save** in Settings. The subset order is saved from the main
layout list when editing the profile; one-language profiles are supported. **Remove profile** restores default behavior.
**Languages for a chat** in the navigation tree. Find the contact, select the chat and
choose the layouts to include. Click **Apply** to keep Settings open or **Save** to close it.
A profile can contain a single layout and cycles through its layouts in the order shown.
Use **Remove profile** and apply or save the change to restore default behavior.
For a matching chat, **Alt+Shift**, **Win+Space** (and reverse **Win+Shift+Space**) cycle
through that subset. KSwitcher's **Next layout** conversion uses the same subset.
@@ -461,10 +462,11 @@ From v0.6.53, chat profiles (application, visible chat name and ordered language
**Українською.** Вибирайте розділ у дереві Settings або шукайте окремий параметр через **Search settings**.
Перетягніть розділювач, щоб змінити ширину дерева. Settings запам’ятовує розмір і положення вікна
та активний розділ. Перехід між розділами зберігає чернетку. Save, Cancel, Import і Export доступні знизу. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages
for a chat…**. Вибери чат і потрібні мови, натисни **Use languages**, а потім **Save**.
for a chat** у дереві налаштувань. Знайдіть контакт, виберіть чат і потрібні розкладки.
Натисніть **Apply**, щоб залишити Settings відкритим, або **Save**, щоб закрити його.
Набір діє для **Alt+Shift**, **Win+Space**, **Win+Shift+Space** та **Next layout** KSwitcher.
Можна вибрати й одну мову; порядок зберігається із загального списку під час редагування профілю. **Remove profile**
повертає звичайну поведінку. Без профілю системні комбінації працюють як раніше,
Можна вибрати одну розкладку. Розкладки перемикаються в порядку, показаному в списку.
Натисніть **Remove profile** і застосуйте або збережіть зміни, щоб повернути звичайну поведінку. Без профілю системні комбінації працюють як раніше,
а Next layout використовує загальний набір. Видалені з Windows розкладки пропускаються;
якщо доступних мов профілю не залишилося, використовується загальний набір.
Прямі комбінації мов не змінюються; явно задані комбінації KSwitcher мають пріоритет.
@@ -478,11 +480,11 @@ Telegram ігнорується. Teams підтримує зазначений
### Telegram Web in Chrome — v0.6.51
Open a chat in Telegram Web K (`https://web.telegram.org/k/`) in Chrome, then use **Settings → Languages → Languages for a chat...** and select **Telegram Web: name**. Choose languages, then **Use languages → Save**. The same subset applies to Alt+Shift, Win+Space, Win+Shift+Space and Next layout. Web profiles are separate from desktop Telegram profiles. Same-name chats across browser profiles/accounts share a web profile.
Open a chat in Telegram Web K (`https://web.telegram.org/k/`) in Chrome, then use **Settings → Languages → Languages for a chat** and select the contact with **Telegram Web** in the App column. Choose layouts and click **Apply** or **Save**. The same subset applies to Alt+Shift, Win+Space, Win+Shift+Space and Next layout. Web profiles are separate from desktop Telegram profiles. Same-name chats across browser profiles/accounts share a web profile.
Recognition uses Chrome accessibility: the address bar and active document must both identify a Telegram chat, then the visible header supplies the name. The app watches foreground/focus and address/header-change events; it does not use OCR, a polling timer, an extension, or message-history extraction. The address bar, home page and unsupported URLs do not match. Web A and other browsers have not been validated and are not advertised as supported. Page or accessibility changes can make a chat unavailable instead of guessing.
**Українською.** З v0.6.51 підтримано Telegram Web K у Chrome. Відкрий чат, потім **Settings → Languages → Languages for a chat...**, вибери **Telegram Web: ім’я**, мови та **Use languages → Save**. Набір діє для Alt+Shift, Win+Space, Win+Shift+Space і Next layout. Вебпрофілі окремі від Telegram Desktop; однакові назви в різних акаунтах/профілях браузера мають спільний вебпрофіль. Адреса й назва беруться через accessibility, без OCR, таймера, розширення та читання історії повідомлень. В адресному рядку, на головній сторінці й для непідтримуваних адрес профіль не діє. Web A та інші браузери не перевірені й не заявлені як підтримувані.
**Українською.** З v0.6.51 підтримано Telegram Web K у Chrome. Відкрий чат, потім **Settings → Languages → Languages for a chat**, вибери контакт із **Telegram Web** у колонці App та потрібні розкладки, а потім натисни **Apply** або **Save**. Набір діє для Alt+Shift, Win+Space, Win+Shift+Space і Next layout. Вебпрофілі окремі від Telegram Desktop; однакові назви в різних акаунтах/профілях браузера мають спільний вебпрофіль. Адреса й назва беруться через accessibility, без OCR, таймера, розширення та читання історії повідомлень. В адресному рядку, на головній сторінці й для непідтримуваних адрес профіль не діє. Web A та інші браузери не перевірені й не заявлені як підтримувані.
### Snippet autocomplete — v0.6.69
@@ -1042,6 +1044,16 @@ embedded in KSwitcher.Files.exe.
.\tests\configuration.ps1 # Separate-process settings tests; close KSwitcher first
```
To check snippet suggestions in a WebView2 app, focus a blank editable field and
run `KSwitcherIntegration.exe --snippet-external-editor` without changing the
foreground window. The test types `;`, checks that the popup opens without
stealing focus, dismisses it, and removes the test character. In Dirlume, repeat
in the Command line, the terminal at an idle prompt, and the text editor. Use
`--insert` as the second argument to test Tab insertion in a blank text field.
With a Dirlume build that supports KSwitcher terminal insertion, use
`--terminal-insert` at a blank shell prompt and check that `snippet test`
appears as an editable draft. Clear that draft without submitting it.
`-Test` also checks remote/own input separation, hidden Settings layout and scrolling, and updater
package validation, file preservation and rollback in temporary fixture directories. It does not
replace a running installation. Optional read-only network checks:
+70
View File
@@ -1,5 +1,75 @@
# Latest Windows release
## v0.8.8 — 2026-11-28
In Lavender, **Change drive**, command menus, panel search and command suggestions use a light lavender background and a contrasting purple outline, 2 pixels thick at 100% scaling.
**Українською.** У Lavender меню **Change drive**, меню команд, пошук панелі й підказки команд мають світло-лавандове тло та контрастну фіолетову рамку завтовшки 2 пікселі за масштабу 100%.
## v0.8.7 — 2026-11-28
In **Change drive** (Alt+F1 or Alt+F2), press **1** for FTP, **2** for SFTP, **3** for SMB or **4** for Recent folders. The scroll bar has its own space so it does not clip the free-space column.
**Українською.** У **Change drive** (Alt+F1 або Alt+F2) клавіші **1**, **2**, **3** і **4** відкривають FTP, SFTP, SMB і нещодавні папки відповідно. Для смуги прокрутки відведено окреме місце, щоб не обрізати значення вільного місця.
## v0.8.6 — 2026-11-28
- **Updater.** Checking for updates requests only the latest stable Gitea release, avoiding timeouts while loading the release history. If the older updater still times out, install this release using the complete portable ZIP.
- **Layout conversion.** Recent text selection can recover after delayed editor selection in apps such as Claude. When several layouts produce the same recent text, KSwitcher prefers the layout used to type it.
- **Files.** Open **Space Analyzer** from **Left** or **Right** to scan in that pane. **Logical size** and **Size on disk** apply to the tree and charts. Local NTFS folder sizes use batched directory reads and parallel traversal.
**Українською.**
- **Оновлення.** KSwitcher запитує в Gitea лише останній стабільний реліз. Це усуває тайм-аут під час завантаження історії релізів. Якщо старий оновлювач і далі не відповідає, встановіть цей реліз із повного портативного ZIP.
- **Перетворення розкладки.** KSwitcher може відновити виділення нещодавнього тексту в редакторах із затримкою виділення, зокрема в Claude. Якщо кілька розкладок дають той самий набраний текст, KSwitcher віддає перевагу розкладці, у якій його набрано.
- **Files.** **Space Analyzer** у меню **Left** або **Right** запускає аналіз у вибраній панелі. **Logical size** і **Size on disk** діють у дереві й на графіках. Підрахунок розміру папок на NTFS використовує пакетне читання й паралельний обхід.
## v0.8.5 — 2026-11-28
- **Snippets in Dirlume.** Type `;` to see matching KSwitcher snippets in the command line, editor, other editable fields and embedded terminal. A compatible Dirlume build accepts a single-line snippet with **Tab** at a supported shell prompt and leaves the command editable. Terminal insertion excludes key actions and pauses.
**Українською.**
- **Сніпети в Dirlume.** Введіть `;`, щоб побачити підказки KSwitcher у командному рядку, редакторі, інших текстових полях і вбудованому терміналі. У сумісній збірці Dirlume клавіша **Tab** вставляє однорядковий сніпет у рядок підтримуваної оболонки й залишає команду доступною для редагування. Термінал не вставляє сніпети з клавіатурними діями або паузами.
## v0.8.4 — 2026-11-27
- **Settings.** Open **Languages → Languages for a chat** in the Settings tree to search for a chat and choose its keyboard layouts. Save changes with **Apply** or **Save**.
- **Trusted LAN clients.** Clients such as Dirlume can ask how to handle individual file conflicts during copy or move. When supported, choose to replace, skip or cancel.
**Українською.**
- **Налаштування.** Відкрийте **Languages → Languages for a chat** у дереві Settings, щоб знайти чат і вибрати його розкладки. Застосуйте зміни кнопкою **Apply** або **Save**.
- **Довірені клієнти LAN.** Клієнти на кшталт Dirlume можуть запитувати, як обробити окремі конфлікти файлів під час копіювання або переміщення. Якщо клієнт підтримує цю можливість, виберіть заміну, пропуск або скасування.
## v0.8.3 — 2026-11-26
- **Files.** Lavender now shows compact path segments with chevrons above both panes. The current folder has a rounded highlight. Click an ancestor to open it, the current folder to edit the path, or an ellipsis to reveal hidden folders.
**Українською.**
- **Files.** У Lavender над обома панелями тепер видно компактні сегменти шляху з роздільниками `›`. Поточна папка має заокруглене виділення. Клік на батьківській папці відкриває її, клік на поточній відкриває введення шляху, а трикрапка показує приховані папки.
## v0.8.2 — 2026-11-26
- **Files.** Choose **F9 → Options → Appearance → Window style → Lavender** for light panes, clearer selection and a redesigned command bar. File operation dialogs have a dark title band, with a red band for warnings. Far remains the default, and keyboard shortcuts work in both styles.
- **What’s new.** KSwitcher shows release notes after an update. Reopen them from **Help → What’s new** in the tray.
**Українською.**
- **Files.** Виберіть **F9 → Options → Appearance → Window style → Lavender**, щоб увімкнути світлі панелі, виразніше виділення й оновлену смугу команд. Діалоги файлових операцій мають темний заголовок, а попередження — червоний. Far лишається стандартним режимом, в обох стилях працюють ті самі гарячі клавіші.
- **Що нового.** KSwitcher показує нотатки після оновлення. Повторно відкрийте їх через **Help → What’s new** у треї.
## v0.8.1 — 2026-11-26
- **SMB.** Saved connections and a server’s shares open in the selected Files panel. Press **Enter** to open a connection or share. **Esc** returns to the previous list or folder. Profile editing and sign-in use their existing dialogs.
- **Recent folders.** The selected panel shows recent local and remote folders. **Enter** opens the entry in that panel, **Delete** removes the history entry, and **Esc** restores the previous folder and cursor.
**Українською.**
- **SMB.** Збережені підключення та спільні ресурси сервера відкриваються у вибраній панелі Files. **Enter** відкриває підключення чи ресурс. **Esc** повертає до попереднього списку або папки. Для редагування профілю та входу використовуються окремі діалоги.
- **Recent folders.** Вибрана панель показує нещодавні локальні й віддалені папки. **Enter** відкриває запис у цій панелі, **Delete** прибирає його з історії, а **Esc** відновлює попередню папку й курсор.
## v0.8.0 — 2026-11-26
- **Files panels and search.** Find files recursively on local, FTP, SFTP and paired LAN panes. Work with results directly, navigate with breadcrumbs and history, recall recent folders, and configure sorting, filters, columns and panel layout. File clipboard and drag and drop integrate with Windows.
+1 -1
View File
@@ -1 +1 @@
3d1d0d0a1c9ad671c949e0744987c94642125ccb2f479d3126509250c1fca541 KSwitcher-win-x64.zip
c0efa5d6ea85b408439d6879968f6f667a3a537c7d6ff8ced9b5c5d98e7de6e2 KSwitcher-win-x64.zip
+23 -23
View File
@@ -1,23 +1,23 @@
{
"files": [
{
"sha256": "48fb46c472b1a3e689ff7a594f2ba728abee1b0ae2163333901179b624c23fe1",
"size": 3192832,
"sha256": "e40a89e8af4f783d76d38de7e77847727938813d5421d103e60469b83a3b9be4",
"size": 3265536,
"path": "KSwitcher.exe"
},
{
"sha256": "cf6f71169c79bb915c633765a4d56e6048e9a2c84ff877226158e9a27c8183ee",
"size": 2892800,
"sha256": "1e86f3b6e94b619715201b30cf27b9a1db41f25cb73f7defbc1b7eccf77bb16f",
"size": 2850304,
"path": "KSwitcher.Config.exe"
},
{
"sha256": "79ec0555f9a2668fd284dd73663e2a2aecbc5833dba39e2b02a45b88ad1cae3d",
"sha256": "56f1f0cd70bc6089b8964fea8ae3b25461648ae7481404283878810ded39279b",
"size": 3193344,
"path": "KSwitcher.Screenshot.exe"
},
{
"sha256": "ebe481402fadc09f60afef4dc7ece293d2709c0f3931154d474fbc9a12c7d6a6",
"size": 5967872,
"sha256": "12007fa59dbdc0cb2354a993cd7f64a482605a3a8a91705d6030efcc6c373f12",
"size": 6018048,
"path": "KSwitcher.Files.exe"
},
{
@@ -51,13 +51,13 @@
"path": "terminal/markdown-it.js"
},
{
"sha256": "2576d0c897ffa7e78eb73fc065cd438af164b5dd332cc59083a53ac692fd575f",
"size": 3740,
"sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2",
"size": 3800,
"path": "terminal/markdown.html"
},
{
"sha256": "1eaf9a8a63ec5a62eb4e710cd413bf6893dbc9eaf7dbf4898927fb44afa08bbc",
"size": 18318,
"sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96",
"size": 18721,
"path": "terminal/markdown.js"
},
{
@@ -106,28 +106,28 @@
"path": "files-text-license.txt"
},
{
"sha256": "0b1d38528f1da5acccfb02634a91e3aa753547e137ccd1eebd0873fef2a9dd74",
"size": 4880,
"sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d",
"size": 4990,
"path": "files-archive-license.txt"
},
{
"sha256": "c94d49ba533db63c368a49a7e630ac7e947634cb6dc87cfaab7627272cc3e3e7",
"size": 2994,
"sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4",
"size": 3044,
"path": "files-image-license.txt"
},
{
"sha256": "05894358228417bb0c524b5c800119b1d47ac0de3477e7cd1abe7a6b41580809",
"size": 2024,
"sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594",
"size": 2064,
"path": "files-sftp-license.txt"
},
{
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01",
"size": 105515,
"sha256": "7d727e102fc77ea6942c3a68cf3564709807cafc32431505469289a1e9b7fb99",
"size": 106600,
"path": "README.md"
},
{
"sha256": "435ace9c718e14e4c391462ffea3a893c9b6622e9a8b861a7dab0492faf61469",
"size": 16474,
"sha256": "4eac1f410e6b544aa45756e24f4fdfe9193c6f732410656160be54ab27a0d7e4",
"size": 17245,
"path": "LAN-PREVIEW.md"
},
{
@@ -166,7 +166,7 @@
"path": "tools/README.txt"
},
{
"sha256": "d4de0a3606267a1c2585412e1288d3be782786720ff1f2ccd9b2217e053bc11b",
"sha256": "a7cb5eb8d8aeccfb477f4238c6c4c274b57772069f4afb074e2c96579b51c39f",
"size": 133120,
"path": "tools/StayHere.exe"
},
@@ -177,5 +177,5 @@
}
],
"schema": 1,
"version": "0.8.0"
"version": "0.8.8"
}
+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,0,0
PRODUCTVERSION 0,8,0,0
FILEVERSION 0,8,8,0
PRODUCTVERSION 0,8,8,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.0"
VALUE "FileVersion", "0.8.8"
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
+12 -34
View File
@@ -250,7 +250,7 @@ STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMEN
CAPTION "KSwitcher Files Options"
FONT 9, "Segoe UI"
BEGIN
LTEXT "&Search settings", -1, 8, 8, 113, 10
LTEXT "&Search settings", 418, 8, 8, 113, 10
EDITTEXT 270, 8, 21, 113, 14, ES_AUTOHSCROLL
CONTROL "", 271, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 8, 40, 113, 240
LTEXT "", 272, 131, 8, 253, 12
@@ -276,6 +276,8 @@ BEGIN
PUSHBUTTON "Change &color…", 279, 131, 48, 82, 15
LTEXT "", 280, 222, 50, 155, 12
LTEXT "", 281, 131, 30, 254, 14
LTEXT "Interface style", 416, 131, 30, 105, 14
COMBOBOX 417, 245, 28, 132, 65, CBS_DROPDOWNLIST | WS_TABSTOP
PUSHBUTTON "Change &font…", 282, 131, 52, 82, 15
LTEXT "&Outer padding (px at 96 DPI)", 302, 131, 31, 173, 12
COMBOBOX 303, 311, 28, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
@@ -575,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
@@ -623,23 +618,6 @@ BEGIN
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
END
121 DIALOGEX 0, 0, 430, 192
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB connections"
FONT 10, "Consolas"
BEGIN
LTEXT "", 540, 16, 16, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 541, "ListBox", LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP, 16, 31, 398, 103
LTEXT "", 542, 16, 140, 398, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 543, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 19, 166, 56, 17
CONTROL "&New", 544, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 166, 56, 17
CONTROL "&Edit", 545, "Button", BS_OWNERDRAW | WS_TABSTOP, 145, 166, 56, 17
CONTROL "Re&move", 546, "Button", BS_OWNERDRAW | WS_TABSTOP, 208, 166, 56, 17
CONTROL "&Sign in", 547, "Button", BS_OWNERDRAW | WS_TABSTOP, 271, 166, 60, 17
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 338, 166, 56, 17
END
122 DIALOGEX 0, 0, 355, 113
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB connection"
+2
View File
@@ -58,6 +58,8 @@ Choose Files from the tray. Use the two file panels to browse, move and copy fil
Use the tray menu to pause or resume input processing, keep the display awake, pause clipboard history, open the data folder, check for updates or exit. Tools lists supported portable utilities placed in the tools folder.
After a successful update, What's new shows the installed release notes once. Open Help → What's new from the tray to read current and earlier releases offline or open the full release page in Gitea.
If a shortcut stops working, check whether input processing is paused and whether another application owns the binding. If a paired PC is missing, check discovery and access on both computers. Settings → Diagnostics and View log in the tray provide logs. Settings → MCP displays management integration settings.
Donate via Monobank opens the project's donation jar in the browser. Choose Help → About KSwitcher to see the running version.
+1
View File
@@ -4,3 +4,4 @@ IDR_HELP_GUIDE RCDATA "help-guide.md"
IDR_HELP_MANUAL RCDATA "../README.md"
IDR_HELP_FILES RCDATA "../FILES-UI.md"
IDR_HELP_COMPUTERS RCDATA "../LAN-PREVIEW.md"
IDR_HELP_RELEASES RCDATA "../Release/README.md"
+1
View File
@@ -14,3 +14,4 @@
#define IDR_HELP_MANUAL 601
#define IDR_HELP_FILES 602
#define IDR_HELP_COMPUTERS 603
#define IDR_HELP_RELEASES 604
+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)." }
+229 -43
View File
@@ -45,26 +45,107 @@ GUITHREADINFO snippetGuiInfo(HWND target)
return info;
}
std::optional<RECT> accessibleSnippetCaret(HWND target)
using Microsoft::WRL::ComPtr;
constexpr std::wstring_view terminalSnippetTicketPrefix = L"dirlume-terminal-snippet-v1:";
bool snippetElementClass(IUIAutomationElement *element, std::wstring_view name)
{
BSTR className{};
const bool matches = SUCCEEDED(element->get_CurrentClassName(&className)) && className && className == name;
SysFreeString(className);
return matches;
}
ComPtr<IUIAutomationElement> focusedSnippetElement(IUIAutomation2 *automation, HWND target)
{
using Microsoft::WRL::ComPtr;
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER,
IID_IUIAutomation2, reinterpret_cast<void **>(automation.GetAddressOf()))))
return {};
automation->put_ConnectionTimeout(150);
automation->put_TransactionTimeout(150);
ComPtr<IUIAutomationElement> focused;
if (FAILED(automation->GetFocusedElement(&focused)) || !focused)
return {};
DWORD process{};
GetWindowThreadProcessId(target, &process);
int focusedProcess{};
BOOL password = TRUE;
if (!process || FAILED(focused->get_CurrentProcessId(&focusedProcess)) ||
process != static_cast<DWORD>(focusedProcess) ||
FAILED(focused->get_CurrentIsPassword(&password)) || password)
if (FAILED(focused->get_CurrentIsPassword(&password)) || password ||
!focusedTextBelongsToWindow(automation, focused.Get(), target))
return {};
return focused;
}
ComPtr<IUIAutomation2> snippetAutomation()
{
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&automation))))
return {};
automation->put_ConnectionTimeout(150);
automation->put_TransactionTimeout(150);
return automation;
}
ComPtr<IUIAutomationValuePattern> terminalSnippetInput(IUIAutomation *automation, IUIAutomationElement *focused)
{
// The receiver is a sibling of this terminal's focused xterm input.
ComPtr<IUIAutomationTreeWalker> walker;
ComPtr<IUIAutomationElement> parent, input;
ComPtr<IUIAutomationCondition> condition;
if (FAILED(automation->get_RawViewWalker(&walker)) || !walker ||
FAILED(walker->GetParentElement(focused, &parent)) || !parent)
return {};
VARIANT className{};
className.vt = VT_BSTR;
className.bstrVal = SysAllocString(L"dirlume-terminal-snippet-input");
const auto result = automation->CreatePropertyCondition(UIA_ClassNamePropertyId, className, &condition);
VariantClear(&className);
if (FAILED(result) || !condition ||
FAILED(parent->FindFirst(TreeScope_Children, condition.Get(), &input)) || !input)
return {};
ComPtr<IUIAutomationValuePattern> value;
input->GetCurrentPatternAs(UIA_ValuePatternId, IID_PPV_ARGS(&value));
return value;
}
std::wstring terminalSnippetTicket(IUIAutomationValuePattern *value)
{
if (!value) return {};
BSTR ticket{};
const auto result = value->get_CurrentValue(&ticket);
const std::wstring_view text(ticket ? ticket : L"", SysStringLen(ticket));
auto accepted = SUCCEEDED(result) && text.size() == terminalSnippetTicketPrefix.size() + 36 &&
text.starts_with(terminalSnippetTicketPrefix) ? std::wstring(text) : std::wstring();
SysFreeString(ticket);
return accepted;
}
std::optional<Template> terminalSnippetTemplate(const Snippet &snippet)
{
auto value = parseTemplate(snippet.text);
if (value.text.empty() || value.text.size() > 8192 || !value.actions.empty() ||
std::any_of(value.text.begin(), value.text.end(), [](wchar_t c) {
return c < 0x20 || (c >= 0x7f && c <= 0x9f) || c == 0x2028 || c == 0x2029;
})) return {};
return value;
}
std::optional<SnippetAnchor> accessibleSnippetCaret(HWND target)
{
const auto automation = snippetAutomation();
if (!automation) return {};
const auto focused = focusedSnippetElement(automation.Get(), target);
if (!focused) return {};
// The xterm.js input follows the terminal cursor for IME. Dirlume
// handles replacement in the active shell draft through a separate input.
if (snippetElementClass(focused.Get(), L"xterm-helper-textarea"))
{
RECT cell{};
BOOL offscreen = TRUE;
if (SUCCEEDED(focused->get_CurrentIsOffscreen(&offscreen)) && !offscreen &&
SUCCEEDED(focused->get_CurrentBoundingRectangle(&cell)) && cell.right > cell.left &&
cell.bottom > cell.top)
{
auto ticket = lower(processName(target)) == L"dirlume" ?
terminalSnippetTicket(terminalSnippetInput(automation.Get(), focused.Get()).Get()) : std::wstring();
return SnippetAnchor{{cell.left, cell.top, cell.left, cell.bottom}, true, std::move(ticket)};
}
return {};
}
ComPtr<IUIAutomationTextPattern2> pattern;
ComPtr<IUIAutomationTextRange> range;
BOOL active{};
@@ -121,7 +202,7 @@ std::optional<RECT> accessibleSnippetCaret(HWND target)
}
}
SafeArrayDestroy(rectangles);
if (anchor && anchor->bottom > anchor->top) return anchor;
if (anchor && anchor->bottom > anchor->top) return SnippetAnchor{*anchor};
}
return {};
}
@@ -144,7 +225,7 @@ ULONG_PTR snippetReplayMarker()
return reinterpret_cast<ULONG_PTR>(&marker);
}
constexpr int OpenFiles = 25, FilesHotkeyFirst = 0x4B10, FilesHotkeySecond = 0x4B11;
constexpr int ToggleInputProcessing = 26, DonateViaMonobank = 27, OpenHelp = 28, OpenAbout = 16;
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 UINT_PTR PauseDrainTimer = 23;
@@ -660,21 +741,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));
}
@@ -1485,6 +1563,12 @@ void App::matchSnippets(HWND fg, bool expandExact)
!snippetWordCharacter(layout->at(physicalLayout().code(previous)));
}))
{
if (snippetPopupAnchor.terminal && snippetTarget == fg && snippetPopup &&
IsWindowVisible(snippetPopup) && snippetFocus == snippetGuiInfo(fg).hwndFocus)
{
hideSnippetPopup();
return;
}
queueSnippet(fg, i, sn.trigger.size());
return;
}
@@ -1559,11 +1643,11 @@ void App::showSnippetPopup()
if ((info.rcCaret.left || info.rcCaret.top || anchor.bottom - anchor.top >= 4) &&
snippetCaretInside(anchor, bounds))
{
placeSnippetPopup(anchor);
placeSnippetPopup({anchor});
return;
}
}
if (snippetPopup && IsWindowVisible(snippetPopup) && snippetCaretInside(snippetPopupAnchor, bounds))
if (snippetPopup && IsWindowVisible(snippetPopup) && snippetCaretInside(snippetPopupAnchor.bounds, bounds))
placeSnippetPopup(snippetPopupAnchor);
if (snippetCaretPending) return;
snippetCaretPending = true;
@@ -1572,6 +1656,14 @@ void App::showSnippetPopup()
const auto receiver = window;
enqueue([this, version, target, receiver] {
auto caret = GetForegroundWindow() == target ? accessibleSnippetCaret(target) : std::nullopt;
if (!caret && inputVersion == version && GetForegroundWindow() == target)
{
// A WebView can expose the old, empty field while the keystroke
// that requested suggestions is still reaching its renderer.
Sleep(45);
if (inputVersion == version && GetForegroundWindow() == target)
caret = accessibleSnippetCaret(target);
}
{
std::lock_guard lock(stateMutex);
snippetCaret = caret;
@@ -1579,9 +1671,22 @@ void App::showSnippetPopup()
PostMessageW(receiver, SnippetCaretMessage, static_cast<WPARAM>(version), 0);
});
}
void App::placeSnippetPopup(RECT anchor)
void App::placeSnippetPopup(SnippetAnchor placement)
{
snippetPopupAnchor = anchor;
if (placement.terminal && placement.canInsert())
{
const auto previous = snippetMatches[snippetSelection];
std::erase_if(snippetMatches, [&](size_t index) { return !terminalSnippetTemplate(settings.snippets[index]); });
if (snippetMatches.empty())
{
hideSnippetPopup();
return;
}
const auto selected = std::find(snippetMatches.begin(), snippetMatches.end(), previous);
snippetSelection = selected == snippetMatches.end() ? 0 : static_cast<size_t>(selected - snippetMatches.begin());
}
snippetPopupAnchor = std::move(placement);
const auto &anchor = snippetPopupAnchor.bounds;
if (!snippetPopup)
{
WNDCLASSW cls{};
@@ -1630,24 +1735,83 @@ void App::placeSnippetPopup(RECT anchor)
InvalidateRect(snippetPopup, nullptr, FALSE);
SetTimer(window, SnippetPopupTimer, 100, nullptr);
}
void App::selectSnippet(size_t row)
bool App::selectSnippet(size_t row)
{
if (row >= snippetMatches.size() || !snippetPopupCurrent()) return;
if (!snippetPopupAnchor.canInsert() || row >= snippetMatches.size() || !snippetPopupCurrent()) return false;
const auto index = snippetMatches[row];
const auto length = snippetPrefixLength;
hideSnippetPopup();
std::lock_guard lock(stateMutex);
if (snippetPopupVersion == inputVersion && !busy)
queueSnippet(snippetTarget, index, length, snippetFocus);
if (!snippetPopupCurrent()) return false;
if (!snippetPopupAnchor.terminal)
{
hideSnippetPopup();
return queueSnippet(snippetTarget, index, length, snippetFocus);
}
const auto layout = std::find_if(layouts.begin(), layouts.end(), [&](const auto &item) {
return item.handle == run.layout && item.convertible;
});
if (layout == layouts.end() || run.window != snippetTarget || run.keys.size() < length)
return false;
const auto replacement = terminalSnippetTemplate(settings.snippets[index]);
if (!replacement) return false;
std::wstring prefix;
for (wchar_t key : std::wstring_view(run.keys).substr(run.keys.size() - length))
prefix += layout->at(physicalLayout().code(key));
if (prefix.empty() || prefix.find(L'\0') != prefix.npos) return false;
const auto ticket = snippetPopupAnchor.terminalTicket;
const auto target = snippetTarget;
const auto editor = snippetFocus;
const auto request = wide(DiagnosticJson::array({utf8(ticket), utf8(prefix), utf8(replacement->text),
replacement->text.size() - replacement->suffix.size()}).dump(-1, ' ', true, DiagnosticJson::error_handler_t::replace));
hideSnippetPopup();
run.reset();
const auto version = ++inputVersion;
typingTarget = target;
snippetTyping = true;
busy = true;
enqueue([this, target, editor, version, ticket, request] {
struct Replay
{
HWND window;
~Replay() { PostMessageW(window, ReplayTypingMessage, 0, 0); }
} replay{window};
const auto current = [&] {
return inputVersion == version && GetForegroundWindow() == target && snippetGuiInfo(target).hwndFocus == editor;
};
if (!current()) return;
const auto automation = snippetAutomation();
if (!automation) return;
const auto focused = focusedSnippetElement(automation.Get(), target);
if (!focused || !snippetElementClass(focused.Get(), L"xterm-helper-textarea")) return;
const auto input = terminalSnippetInput(automation.Get(), focused.Get());
if (terminalSnippetTicket(input.Get()) != ticket || !current()) return;
BSTR payload = SysAllocStringLen(request.data(), static_cast<UINT>(request.size()));
if (!payload) return;
const auto sent = input->SetValue(payload);
SysFreeString(payload);
if (FAILED(sent)) return;
// Keep subsequent keystrokes ordered behind the renderer's draft edit.
const auto until = GetTickCount64() + 200;
while (current() && GetTickCount64() < until)
{
const auto reply = terminalSnippetTicket(input.Get());
if (!reply.empty() && reply != ticket) return;
Sleep(10);
}
});
return true;
}
bool App::handleSnippetKey(DWORD vk, UINT mods)
{
if (!snippetPopupAnchor.canInsert() && vk != VK_ESCAPE) return false;
const bool accept = vk == VK_TAB ||
(vk == VK_RETURN && (snippetNavigated || snippetMatches.size() == 1));
(!snippetPopupAnchor.terminal && vk == VK_RETURN && (snippetNavigated || snippetMatches.size() == 1));
if (mods || (!accept && vk != VK_UP && vk != VK_DOWN && vk != VK_ESCAPE) ||
!snippetPopup || !IsWindowVisible(snippetPopup) || !snippetPopupCurrent())
return false;
if (accept) selectSnippet(snippetSelection);
if (accept) return selectSnippet(snippetSelection);
else if (vk == VK_ESCAPE) hideSnippetPopup();
else
{
@@ -1690,7 +1854,7 @@ LRESULT CALLBACK App::snippetPopupProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
const LONG top = static_cast<LONG>(i - first) * app->snippetRowHeight;
RECT row{0, top, bounds.right, top + app->snippetRowHeight};
const bool selected = i == app->snippetSelection;
const bool selected = app->snippetPopupAnchor.canInsert() && i == app->snippetSelection;
if (selected) FillRect(dc, &row, GetSysColorBrush(COLOR_HIGHLIGHT));
SetTextColor(dc, GetSysColor(selected ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT));
row.left += MulDiv(8, dpi, 96);
@@ -3269,6 +3433,7 @@ void App::trayMenu()
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
HMENU help = CreatePopupMenu();
AppendMenuW(help, MF_STRING, OpenHelp, L"&User guide");
AppendMenuW(help, MF_STRING, OpenWhatsNew, whatsNewTitle(GetThreadUILanguage()));
AppendMenuW(help, MF_STRING, OpenAbout, L"&About KSwitcher");
AppendMenuW(menu, MF_POPUP, reinterpret_cast<UINT_PTR>(help), L"H&elp");
AppendMenuW(menu, MF_STRING, 17, L"E&xit");
@@ -3333,6 +3498,9 @@ void App::trayMenu()
case OpenHelp:
showHelp(*this);
break;
case OpenWhatsNew:
showWhatsNew(*this, GetThreadUILanguage());
break;
case DonateViaMonobank:
if (reinterpret_cast<INT_PTR>(ShellExecuteW(window, L"open", MonobankDonationUrl, nullptr, nullptr, SW_SHOWNORMAL)) <= 32)
throw std::runtime_error("Could not open the Monobank donation page.");
@@ -3372,6 +3540,25 @@ void App::trayMenu()
report(wide(e.what()));
}
}
void App::showWhatsNewAfterUpdate()
{
if (!confirmUpdatedStartup(updateStartupEvent)) return;
log(std::wstring(L"Update completed; running version ") + AppVersion);
try
{
const auto seen = data / L"whats-new-seen.txt";
const auto version = utf8(AppVersion);
if (std::filesystem::exists(seen) && readFile(seen, 64) == Bytes(version.begin(), version.end()))
return;
showWhatsNew(*this, GetThreadUILanguage());
atomicWrite(seen, Bytes(version.begin(), version.end()));
}
catch (const std::exception &error)
{
log(L"Could not show release notes: " + wide(error.what()));
}
}
void App::checkUpdate(bool interactive, bool install, const std::wstring &version)
{
if (updateRunning) return;
@@ -3580,13 +3767,13 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
app->showSnippetPopup();
return 0;
}
std::optional<RECT> caret;
std::optional<SnippetAnchor> caret;
{
std::lock_guard lock(app->stateMutex);
caret = app->snippetCaret;
}
RECT bounds{};
if (caret && GetWindowRect(app->snippetTarget, &bounds) && snippetCaretInside(*caret, bounds))
if (caret && GetWindowRect(app->snippetTarget, &bounds) && snippetCaretInside(caret->bounds, bounds))
{
app->placeSnippetPopup(*caret);
return 0;
@@ -3876,8 +4063,6 @@ int App::execute()
SetTimer(window, 2, 10000, nullptr);
else
SetTimer(window, 5, 5000, nullptr);
if (keyboardHook && mouseHook && confirmUpdatedStartup(updateStartupEvent))
log(std::wstring(L"Update completed; running version ") + AppVersion);
if (startCommand)
PostMessageW(window, WM_HOTKEY, startCommand, 0);
if (!smoke && !isLocalBuild() && settings.autostart)
@@ -3885,6 +4070,7 @@ int App::execute()
try { notificationRegistration = startScreenshotNotificationRegistration(); }
catch(const std::exception &e) { log(L"Screenshot notification registration: "+wide(e.what())); }
auto screenshotActivation=startScreenshotActivationListener();
if (keyboardHook && mouseHook) showWhatsNewAfterUpdate();
MSG msg;
while (GetMessageW(&msg, nullptr, 0, 0) > 0)
{
+14 -4
View File
@@ -23,6 +23,13 @@ inline constexpr int Toggle = 1, Case = 2, Translit = 3, Undo = 4, ShowHistory =
inline constexpr UINT AutoCorrectMessage = WM_APP + 6;
inline constexpr UINT ReplayTypingMessage = WM_APP + 30;
inline constexpr UINT CaptureHotkeyMessage = WM_APP + 5;
struct SnippetAnchor
{
RECT bounds{};
bool terminal{};
std::wstring terminalTicket;
bool canInsert() const { return !terminal || !terminalTicket.empty(); }
};
struct LastTransform
{
HWND window{};
@@ -78,6 +85,7 @@ class App
void enqueue(std::function<void()>);
void enqueueHistorySearch(std::function<void()>);
void report(const std::wstring &);
void showWhatsNewAfterUpdate();
void trayMenu();
void addTray();
bool registerHotkeys(const Settings &, bool rollback = false);
@@ -202,20 +210,20 @@ class App
bool snippetNavigated{};
int snippetRowHeight{};
UINT snippetDpi{96};
RECT snippetPopupAnchor{};
SnippetAnchor snippetPopupAnchor{};
bool snippetCaretPending{};
std::optional<RECT> snippetCaret;
std::optional<SnippetAnchor> snippetCaret;
std::vector<std::pair<std::wstring, std::vector<std::wstring>>> snippetTriggers;
std::vector<size_t> snippetMatches;
std::array<bool, 256> snippetKeys{};
void matchSnippets(HWND, bool expandExact);
bool queueSnippet(HWND, size_t index, size_t length, HWND editor = nullptr);
void showSnippetPopup();
void placeSnippetPopup(RECT);
void placeSnippetPopup(SnippetAnchor);
void hideSnippetPopup();
bool snippetPopupCurrent() const;
bool handleSnippetKey(DWORD, UINT);
void selectSnippet(size_t);
bool selectSnippet(size_t);
static LRESULT CALLBACK snippetPopupProc(HWND, UINT, WPARAM, LPARAM);
std::vector<INPUT> deferredTyping;
bool beginTypingDeferral(HWND, uint64_t, bool snippet = false);
@@ -234,5 +242,7 @@ void showLogs(App &);
void showSnippets(App &);
void showShortcuts(App &);
void showHelp(App &);
const wchar_t *whatsNewTitle(LANGID language);
void showWhatsNew(App &, LANGID language);
void showEntry(App &, const std::wstring &);
} // namespace ks
+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
+4 -3
View File
@@ -259,14 +259,15 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM
SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()));
label.resize(count);
const bool selected=(item.itemState&ODS_SELECTED)!=0 && item.itemData<terminalHistory.size();
const auto background=colors[selected?Selection:Dialog];
const auto ink=colors[Text];
const auto palette=farDropDownPalette();
const auto background=selected?palette.selection:palette.surface;
const auto ink=palette.text;
if(item.itemData==static_cast<ULONG_PTR>(-1))
{
auto bounds=item.rcItem;
InflateRect(&bounds,-historyRowInset(GetDpiForWindow(dialog)),0);
const auto saved=SaveDC(item.hDC);
SelectObject(item.hDC,mono);
SelectObject(item.hDC,dialogUiFont());
SetBkColor(item.hDC,background);
SetTextColor(item.hDC,ink);
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&bounds,nullptr,0,nullptr);
+4 -2
View File
@@ -1051,6 +1051,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
SendMessageW(dialog,WM_SETICON,ICON_SMALL,reinterpret_cast<LPARAM>(small));
SendMessageW(dialog,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(large));
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,L"HrynCo.KSwitcher.Files.Compare");
if(lavenderFiles()) styleLavenderDialogControls(dialog);
initializeComparisonToolbar(toolbar);
const auto actions=GetDlgItem(dialog,408);
initializeComparisonActions(actions);
@@ -1070,6 +1071,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
applyComparisonAppearance(dialog,*comparison);
layoutComparisonHeaders(dialog,*comparison);
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
return TRUE;
}
if(message==WM_CLOSE && comparison)
@@ -1195,7 +1197,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
}
return FALSE;
return lavenderDialogColors(dialog,message,wp,lp);
}
INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
@@ -1230,7 +1232,7 @@ bool selectedComparisonFiles(CompareFile (&files)[2])
const auto pick=[](const Panel &panel,const fs::path &path,CompareFile &file)
{
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
if(panel.archive || transferProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder")
if(panel.archive || panelListsLocations(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder")
return false;
const auto directory=path.parent_path();
const auto tail=(directory.filename()/path.filename()).native();
+31 -2
View File
@@ -94,7 +94,32 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
if(!popup.handle) return;
constexpr UINT openItem=1,findItems=2,newProfile=3,properties=4;
const auto add=[&](UINT id,const wchar_t *label){AppendMenuW(popup.handle,MF_STRING,id,label);};
if(transferProfileList(panel))
if(recentFolderList(panel))
{
if(row!=LB_ERR)
{
add(openItem,L"Open folder");
add(117,L"Remove from recent");
}
add(110,L"Refresh panel");
}
else if(panel.listing)
{
if(panel.listing->smb->server.empty())
{
if(row!=LB_ERR)
{
add(openItem,L"Connect");
add(112,L"Edit connection");
add(smbSignInCommand,L"Sign in");
add(117,L"Remove connection");
}
add(newProfile,L"New connection");
}
else if(row!=LB_ERR) add(openItem,L"Open share");
add(110,L"Refresh panel");
}
else if(transferProfileList(panel))
{
if(row!=LB_ERR)
{
@@ -129,7 +154,11 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
screen.x,screen.y,owner,nullptr));
if(command==openItem) enter(panel);
else if(command==findItems) findPanelFiles(owner,panel);
else if(command==newProfile) editTransferProfile(panel,true);
else if(command==newProfile)
{
if(panel.listing) editSmbProfile(panel,true);
else editTransferProfile(panel,true);
}
else if(command==properties) showPanelItemProperties(owner,panel);
else if(command) SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0);
}
+5
View File
@@ -54,6 +54,8 @@ LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data)
class FilesModalDialog
{
public:
inline static void (*styleControls)(HWND){};
inline static INT_PTR (*styleBackground)(HWND,UINT,WPARAM,LPARAM){};
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument,
bool watchOutsideClicks=true,bool fitToOwner=true)
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
@@ -347,7 +349,10 @@ private:
lp=state->argument_;
}
if(!state) return FALSE;
if(styleBackground)
if(const auto styled=styleBackground(dialog,message,wp,lp)) return styled;
const auto handled=state->procedure_(dialog,message,wp,lp);
if(message==WM_INITDIALOG && styleControls) styleControls(dialog);
if(message==WM_NCDESTROY) RemovePropW(dialog,stateProperty_);
if(!handled && message==WM_CLOSE)
{
+10 -6
View File
@@ -309,12 +309,16 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto dc=BeginPaint(dialog,&ps);
RECT client{};
GetClientRect(dialog,&client);
const auto frame=CreateSolidBrush(colors[Text]);
const auto bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),teal,frame);
DeleteObject(frame);
paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono,
view->digit<0?L"Enter Esc":quickFolderHints);
paintScrollPosition(dialog,dc,GetDlgItem(dialog,shortcutList),colors[Dialog]);
const auto hints=view->digit<0?L"Enter Esc":quickFolderHints;
if(lavenderFiles()) paintLavenderDialogFrame(dialog,dc,client,L"Folder shortcuts",hints);
else
{
const auto frame=CreateSolidBrush(colors[Text]);
const auto bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),teal,frame);
DeleteObject(frame);
paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono,hints);
}
paintScrollPosition(dialog,dc,GetDlgItem(dialog,shortcutList),lavenderFiles()?lavender::surface:colors[Dialog]);
EndPaint(dialog,&ps);
return TRUE;
}
+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);
}
+5 -4
View File
@@ -11,7 +11,8 @@ constexpr struct
L"Press F9 to show the menu bar. Use the arrow keys to move between categories and entries. Press Enter to run the highlighted command.\r\n\r\n"
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. Recent folders are available from the drive picker.\r\n\r\n"
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,13 +27,13 @@ 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."},
{L"Network connections",L"ftp sftp smb lan ssh host authentication credentials password remote",
L"The drive picker opens FTP, SFTP and SMB connection profiles, as well as paired LAN computers. Create a profile with its protocol, host and starting folder.\r\n\r\n"
L"The drive picker opens FTP, SFTP and SMB connection profiles, as well as paired LAN computers. SMB profiles and server shares appear in the selected file panel. Press Shift+F4 to add a profile or Enter to open the selected profile or share. Press Esc to go back. Sign in is in the profile context menu.\r\n\r\n"
L"Check the remote server identity when connecting. If a listing is interrupted, use the Refresh command shown in the pane's status line to retry."},
{L"Command line and terminal",L"powershell ssh console history windows command f1",
L"Type a PowerShell command and press Enter to run it in the active pane's context. Ctrl+O switches between the file panes and terminal output. Previous command and Command history use the active keyboard scheme.\r\n\r\n"
+122
View File
@@ -0,0 +1,122 @@
namespace lavender
{
constexpr COLORREF canvas=RGB(238,240,250), surface=RGB(255,255,255), line=RGB(218,221,241);
constexpr COLORREF ink=RGB(29,33,64), muted=RGB(91,97,133), accent=RGB(70,72,187);
constexpr COLORREF activeEdge=RGB(151,151,244), selection=RGB(231,227,253), idleSelection=RGB(240,241,249);
constexpr COLORREF folder=RGB(124,133,227), key=RGB(231,230,252), path=RGB(247,247,253);
constexpr COLORREF marked=RGB(105,52,170), markedSelection=RGB(219,209,250);
HFONT font{}, emphasis{};
void setFont(UINT dpi)
{
if(font) DeleteObject(font);
if(emphasis) DeleteObject(emphasis);
const auto create=[&](int weight)
{
return CreateFontW(-MulDiv(14,dpi,96),0,0,0,weight,FALSE,FALSE,FALSE,DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI");
};
font=create(FW_NORMAL);
emphasis=create(FW_SEMIBOLD);
}
void fill(HDC dc,const RECT &rect,COLORREF color)
{
SetDCBrushColor(dc,color);
FillRect(dc,&rect,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
void rounded(HDC dc,RECT rect,int radius,COLORREF color,COLORREF border)
{
if(rect.right<=rect.left || rect.bottom<=rect.top) return;
const auto brush=SelectObject(dc,GetStockObject(DC_BRUSH));
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
SetDCBrushColor(dc,color);
SetDCPenColor(dc,border);
RoundRect(dc,rect.left,rect.top,rect.right,rect.bottom,2*radius,2*radius);
SelectObject(dc,pen);
SelectObject(dc,brush);
}
void text(HDC dc,RECT rect,const wchar_t *label,COLORREF color,UINT alignment=DT_LEFT,
UINT ellipsis=DT_END_ELLIPSIS,HFONT textFont=nullptr)
{
if(rect.right<=rect.left) return;
if(!textFont) textFont=font;
const auto previous=SelectObject(dc,textFont?textFont:GetStockObject(DEFAULT_GUI_FONT));
const auto background=SetBkMode(dc,TRANSPARENT);
const auto inkColor=SetTextColor(dc,color);
DrawTextW(dc,label,-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|alignment|ellipsis);
SetTextColor(dc,inkColor);
SetBkMode(dc,background);
SelectObject(dc,previous);
}
}
struct LavenderMetrics
{
UINT dpi;
int px(int value) const { return MulDiv(value,dpi,96); }
int row;
explicit LavenderMetrics(HWND window): dpi(GetDpiForWindow(window)),row(px(25)) {}
};
void styleLavenderCaption(HWND window,bool enabled)
{
const COLORREF surface=enabled?lavender::path:DWMWA_COLOR_DEFAULT;
const COLORREF text=enabled?lavender::ink:DWMWA_COLOR_DEFAULT;
DwmSetWindowAttribute(window,DWMWA_CAPTION_COLOR,&surface,sizeof(surface));
DwmSetWindowAttribute(window,DWMWA_TEXT_COLOR,&text,sizeof(text));
}
void paintLavenderFileIcon(HDC dc,RECT row,const LavenderMetrics &metrics,bool folder)
{
using namespace lavender;
const int x=row.left+metrics.px(9), y=(row.top+row.bottom-metrics.px(12))/2;
const int stroke=metrics.px(1);
if(folder)
{
const auto edge=RGB(104,114,205);
rounded(dc,{x,y,x+metrics.px(8),y+metrics.px(8)},stroke,lavender::folder,edge);
rounded(dc,{x,y+metrics.px(3),x+metrics.px(14),y+metrics.px(12)},2*stroke,lavender::folder,edge);
}
else
{
const int left=x+metrics.px(2), right=x+metrics.px(12), bottom=y+metrics.px(13);
rounded(dc,{left,y,right,bottom},stroke,path,RGB(157,164,198));
for(int offset:{5,8}) fill(dc,{left+2*stroke,y+metrics.px(offset),right-2*stroke,
y+metrics.px(offset)+stroke},RGB(185,190,215));
}
}
void paintLavenderCommand(const DRAWITEMSTRUCT &item,const std::wstring &label,const LavenderMetrics &metrics,bool compact)
{
using namespace lavender;
const auto &box=item.rcItem;
fill(item.hDC,box,canvas);
const bool pressed=item.itemState&ODS_SELECTED;
rounded(item.hDC,box,metrics.px(8),pressed?selection:path,pressed?activeEdge:line);
const auto separator=label.find(L' ');
const auto shortcut=label.substr(0,separator);
const int width=metrics.px(shortcut.size()>3?48:27);
const int padding=metrics.px(5);
if(compact)
{
const LONG left=std::max(box.left,(box.left+box.right-width)/2);
const LONG top=box.top+metrics.px(2);
const RECT badge{left,top,std::min(box.right,left+width),top+metrics.px(17)};
rounded(item.hDC,badge,metrics.px(4),key,key);
text(item.hDC,badge,shortcut.c_str(),accent,DT_CENTER);
if(separator!=label.npos)
text(item.hDC,{box.left+1,badge.bottom,box.right-1,box.bottom-1},
label.c_str()+separator+1,ink,DT_CENTER);
return;
}
const LONG top=(box.top+box.bottom-metrics.px(18))/2;
const RECT badge{box.left+padding,top,std::min(box.left+padding+width,box.right-padding),top+metrics.px(18)};
rounded(item.hDC,badge,metrics.px(4),key,key);
text(item.hDC,badge,shortcut.c_str(),accent,DT_CENTER);
if(separator!=label.npos)
text(item.hDC,{badge.right+padding,box.top,box.right-padding,box.bottom},label.c_str()+separator+1,ink);
}
+370
View File
@@ -0,0 +1,370 @@
constexpr auto lavenderDialogWarning=L"KSwitcher.Files.Lavender.Warning";
constexpr auto lavenderFileOperation=L"KSwitcher.Files.Lavender.FileOperation";
constexpr int lavenderSidebarLabel=418;
constexpr int operationHeaderHeight=27;
constexpr COLORREF operationSurface=RGB(242,239,251), operationBorder=RGB(111,96,166);
bool isLavenderFileOperation(HWND dialog) { return GetPropW(dialog,lavenderFileOperation)!=nullptr; }
void markLavenderFileOperation(HWND dialog)
{
if(lavenderFiles()) SetPropW(dialog,lavenderFileOperation,reinterpret_cast<HANDLE>(1));
}
COLORREF lavenderDialogSurface(HWND dialog)
{
return isLavenderFileOperation(dialog)?operationSurface:lavender::surface;
}
HFONT dialogUiFont() { return lavenderFiles() && lavender::font?lavender::font:mono; }
bool dialogClass(HWND control,const wchar_t *name)
{
wchar_t type[64]{};
GetClassNameW(control,type,static_cast<int>(std::size(type)));
return _wcsicmp(type,name)==0;
}
COLORREF dialogEdge(HWND dialog)
{
return GetPropW(dialog,lavenderDialogWarning)?RGB(161,43,72):lavender::accent;
}
void paintLavenderDialogButton(HWND control,HDC dc,RECT bounds,bool pressed,bool focused,bool primary)
{
using namespace lavender;
const LavenderMetrics metrics(control);
const bool enabled=IsWindowEnabled(control)!=FALSE;
const auto id=GetDlgCtrlID(control);
const auto dialog=GetParent(control);
const bool operation=isLavenderFileOperation(dialog);
const auto accentColor=id==IDCANCEL || id==IDNO?accent:dialogEdge(dialog);
const auto bg=!enabled?canvas:primary?accentColor:pressed?selection:operation?surface:path;
fill(dc,bounds,lavenderDialogSurface(dialog));
InflateRect(&bounds,-metrics.px(1),-metrics.px(1));
rounded(dc,bounds,metrics.px(6),bg,focused?accentColor:primary?bg:enabled && operation?operationBorder:line);
wchar_t label[128]{};
GetWindowTextW(control,label,static_cast<int>(std::size(label)));
const auto previous=SelectObject(dc,reinterpret_cast<HFONT>(SendMessageW(control,WM_GETFONT,0,0)));
const auto mode=SetBkMode(dc,TRANSPARENT);
const auto color=SetTextColor(dc,!enabled?muted:primary?surface:ink);
InflateRect(&bounds,-metrics.px(3),0);
DrawTextW(dc,label,-1,&bounds,DT_CENTER|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS);
if(focused && primary)
{
InflateRect(&bounds,0,-metrics.px(3));
DrawFocusRect(dc,&bounds);
}
SetTextColor(dc,color);
SetBkMode(dc,mode);
SelectObject(dc,previous);
}
void paintLavenderToggle(HWND control,HDC dc,RECT bounds,bool radio)
{
using namespace lavender;
const LavenderMetrics metrics(control);
const int side=std::min(metrics.px(14),static_cast<int>(bounds.bottom-bounds.top));
const LONG x=bounds.left+metrics.px(1), y=(bounds.top+bounds.bottom-side)/2;
const bool checked=SendMessageW(control,BM_GETCHECK,0,0)==BST_CHECKED;
const bool enabled=IsWindowEnabled(control)!=FALSE;
const RECT indicator{x,y,x+side,y+side};
fill(dc,bounds,lavenderDialogSurface(GetParent(control)));
rounded(dc,indicator,radio?side/2:metrics.px(3),checked?accent:path,enabled?accent:line);
if(checked && radio)
{
auto dot=indicator;
InflateRect(&dot,-side/3,-side/3);
rounded(dc,dot,side/4,surface,surface);
}
else if(checked)
{
const auto old=SelectObject(dc,GetStockObject(DC_PEN));
SetDCPenColor(dc,surface);
const POINT check[]{{x+side/4,y+side/2},{x+side*2/5,y+side*2/3},{x+side*3/4,y+side/3}};
Polyline(dc,check,static_cast<int>(std::size(check)));
SelectObject(dc,old);
}
bounds.left=x+side+metrics.px(6);
wchar_t label[128]{};
GetWindowTextW(control,label,static_cast<int>(std::size(label)));
const auto previous=SelectObject(dc,reinterpret_cast<HFONT>(SendMessageW(control,WM_GETFONT,0,0)));
SetBkMode(dc,TRANSPARENT);
SetTextColor(dc,enabled?ink:muted);
DrawTextW(dc,label,-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS);
if(GetFocus()==control)
{
RECT extent{};
DrawTextW(dc,label,-1,&extent,DT_SINGLELINE|DT_CALCRECT);
bounds.right=std::min(bounds.right,bounds.left+extent.right+metrics.px(3));
DrawFocusRect(dc,&bounds);
}
SelectObject(dc,previous);
}
LRESULT CALLBACK lavenderNativeButton(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(!lavenderFiles()) return DefSubclassProc(control,message,wp,lp);
const auto style=GetWindowLongPtrW(control,GWL_STYLE)&BS_TYPEMASK;
if(message==WM_PAINT || message==WM_PRINTCLIENT)
{
PAINTSTRUCT paint{};
const auto dc=message==WM_PAINT?BeginPaint(control,&paint):reinterpret_cast<HDC>(wp);
RECT bounds{};
GetClientRect(control,&bounds);
if(style==BS_GROUPBOX)
{
const LavenderMetrics metrics(control);
auto frame=bounds;
frame.top+=metrics.px(7);
lavender::fill(dc,bounds,lavender::surface);
lavender::rounded(dc,frame,metrics.px(7),lavender::surface,lavender::line);
wchar_t label[96]{};
GetWindowTextW(control,label,static_cast<int>(std::size(label)));
paintDialogCaption(dc,{bounds.left,bounds.top,bounds.right,bounds.top+metrics.px(15)},label,
static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)),lavender::muted,
reinterpret_cast<HFONT>(SendMessageW(control,WM_GETFONT,0,0)));
}
else if(style==BS_AUTOCHECKBOX || style==BS_AUTORADIOBUTTON)
paintLavenderToggle(control,dc,bounds,style==BS_AUTORADIOBUTTON);
else paintLavenderDialogButton(control,dc,bounds,(SendMessageW(control,BM_GETSTATE,0,0)&BST_PUSHED)!=0,
GetFocus()==control,style==BS_DEFPUSHBUTTON);
if(message==WM_PAINT) EndPaint(control,&paint);
return 0;
}
const auto result=DefSubclassProc(control,message,wp,lp);
if(message==WM_SETFOCUS || message==WM_KILLFOCUS || message==WM_ENABLE || message==BM_SETSTATE ||
message==BM_SETCHECK || message==BM_SETSTYLE || message==WM_SETTEXT ||
message==WM_LBUTTONUP || message==WM_KEYUP)
InvalidateRect(control,nullptr,FALSE);
return result;
}
LRESULT CALLBACK lavenderEditEdge(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_NCCALCSIZE && lavenderFiles())
{
const auto result=DefSubclassProc(control,message,wp,lp);
auto &client=*reinterpret_cast<RECT*>(lp);
const auto inset=LavenderMetrics(control).px(2);
InflateRect(&client,-inset,-inset);
return result;
}
if(message==WM_NCPAINT && lavenderFiles())
{
const auto dc=GetWindowDC(control);
if(!dc) return DefSubclassProc(control,message,wp,lp);
RECT bounds{}, client{};
GetWindowRect(control,&bounds);
GetClientRect(control,&client);
MapWindowPoints(control,nullptr,reinterpret_cast<POINT*>(&client),2);
OffsetRect(&client,-bounds.left,-bounds.top);
OffsetRect(&bounds,-bounds.left,-bounds.top);
ExcludeClipRect(dc,client.left,client.top,client.right,client.bottom);
const auto dialog=GetParent(control);
const bool operation=isLavenderFileOperation(dialog);
lavender::fill(dc,bounds,lavenderDialogSurface(dialog));
lavender::rounded(dc,bounds,LavenderMetrics(control).px(4),operation?lavender::surface:lavender::path,
GetFocus()==control?(operation?dialogEdge(dialog):lavender::activeEdge):operation?operationBorder:lavender::line);
ReleaseDC(control,dc);
return 0;
}
const auto result=DefSubclassProc(control,message,wp,lp);
if((message==WM_SETFOCUS || message==WM_KILLFOCUS) && lavenderFiles())
RedrawWindow(control,nullptr,nullptr,RDW_INVALIDATE|RDW_FRAME);
return result;
}
void paintLavenderComboFace(HWND control,HDC dc,RECT bounds,const wchar_t *label)
{
using namespace lavender;
const LavenderMetrics metrics(control);
const bool focused=GetFocus()==control;
const auto dialog=GetParent(control);
const bool operation=isLavenderFileOperation(dialog);
fill(dc,bounds,lavenderDialogSurface(dialog));
rounded(dc,bounds,metrics.px(5),operation?surface:path,
focused?(operation?dialogEdge(dialog):activeEdge):operation?operationBorder:line);
const LONG center=label[0]?bounds.right-metrics.px(10):(bounds.left+bounds.right)/2;
const LONG middle=(bounds.top+bounds.bottom)/2;
const int arm=metrics.px(3);
const auto previous=SelectObject(dc,GetStockObject(DC_PEN));
SetDCPenColor(dc,IsWindowEnabled(control)?accent:muted);
const POINT arrow[]{{center-arm,middle-arm/2},{center,middle+arm/2},{center+arm,middle-arm/2}};
Polyline(dc,arrow,static_cast<int>(std::size(arrow)));
SelectObject(dc,previous);
bounds.left+=metrics.px(7);
bounds.right-=metrics.px(20);
const auto oldFont=SelectObject(dc,reinterpret_cast<HFONT>(SendMessageW(control,WM_GETFONT,0,0)));
SetTextColor(dc,IsWindowEnabled(control)?ink:muted);
SetBkMode(dc,TRANSPARENT);
DrawTextW(dc,label,-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
SelectObject(dc,oldFont);
}
LRESULT CALLBACK lavenderNativeCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(lavenderFiles() && (message==WM_PAINT || message==WM_PRINTCLIENT))
{
PAINTSTRUCT paint{};
const auto dc=message==WM_PAINT?BeginPaint(control,&paint):reinterpret_cast<HDC>(wp);
RECT bounds{};
GetClientRect(control,&bounds);
const auto length=GetWindowTextLengthW(control);
std::wstring label(length+1,L'\0');
GetWindowTextW(control,label.data(),static_cast<int>(label.size()));
paintLavenderComboFace(control,dc,bounds,label.c_str());
if(message==WM_PAINT) EndPaint(control,&paint);
return 0;
}
const auto result=DefSubclassProc(control,message,wp,lp);
if(message==WM_SETFOCUS || message==WM_KILLFOCUS || message==CB_SETCURSEL || message==WM_ENABLE)
InvalidateRect(control,nullptr,FALSE);
return result;
}
void styleLavenderDialogControls(HWND dialog)
{
const bool modern=lavenderFiles();
const bool custom=(GetWindowLongPtrW(dialog,GWL_STYLE)&WS_CAPTION)==0;
if(!custom) styleLavenderCaption(dialog,modern);
for(auto control=GetWindow(dialog,GW_CHILD);control;control=GetWindow(control,GW_HWNDNEXT))
{
DWORD_PTR oldEdge{};
if(!modern)
{
if(GetWindowSubclass(control,lavenderEditEdge,1,&oldEdge))
{
RemoveWindowSubclass(control,lavenderEditEdge,1);
SetWindowLongPtrW(control,GWL_EXSTYLE,GetWindowLongPtrW(control,GWL_EXSTYLE)|oldEdge);
SendMessageW(control,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,
MAKELPARAM(EC_USEFONTINFO,EC_USEFONTINFO));
SetWindowPos(control,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
}
if(dialogClass(control,WC_TREEVIEWW))
{
const auto style=GetWindowLongPtrW(control,GWL_STYLE);
SetWindowLongPtrW(control,GWL_STYLE,(style&~TVS_FULLROWSELECT)|WS_BORDER|TVS_HASLINES);
TreeView_SetBkColor(control,CLR_NONE);
TreeView_SetTextColor(control,CLR_NONE);
TreeView_SetLineColor(control,CLR_DEFAULT);
SetWindowPos(control,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
}
continue;
}
if(custom) SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(dialogUiFont()),FALSE);
if(dialogClass(control,L"Button"))
{
const auto type=GetWindowLongPtrW(control,GWL_STYLE)&BS_TYPEMASK;
DWORD_PTR existing{};
if(type!=BS_OWNERDRAW && !GetWindowSubclass(control,lavenderNativeButton,2,&existing))
SetWindowSubclass(control,lavenderNativeButton,2,0);
}
else if(dialogClass(control,WC_TREEVIEWW))
{
const auto style=GetWindowLongPtrW(control,GWL_STYLE);
SetWindowLongPtrW(control,GWL_STYLE,(style&~(WS_BORDER|TVS_HASLINES))|TVS_FULLROWSELECT);
TreeView_SetBkColor(control,lavender::path);
TreeView_SetTextColor(control,lavender::ink);
TreeView_SetLineColor(control,lavender::activeEdge);
SetWindowPos(control,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
}
else if(dialogClass(control,L"ComboBox"))
{
const auto style=GetWindowLongPtrW(control,GWL_STYLE);
if((style&3)==CBS_DROPDOWNLIST && !(style&(CBS_OWNERDRAWFIXED|CBS_OWNERDRAWVARIABLE)))
SetWindowSubclass(control,lavenderNativeCombo,1,0);
}
else if((dialogClass(control,L"KSwitcher.Files.FarEdit") ||
(dialogClass(control,L"Edit") && !(GetWindowLongPtrW(control,GWL_STYLE)&ES_READONLY))) &&
!GetWindowSubclass(control,lavenderEditEdge,1,&oldEdge))
{
const auto style=GetWindowLongPtrW(control,GWL_EXSTYLE);
SetWindowLongPtrW(control,GWL_EXSTYLE,style&~WS_EX_CLIENTEDGE);
SetWindowSubclass(control,lavenderEditEdge,1,style&WS_EX_CLIENTEDGE);
SetWindowPos(control,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
const auto padding=LavenderMetrics(control).px(6);
SendMessageW(control,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,MAKELPARAM(padding,padding));
}
}
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
}
INT_PTR lavenderDialogColors(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_NCDESTROY) RemovePropW(dialog,lavenderFileOperation);
if(!lavenderFiles()) return FALSE;
if(message!=WM_CTLCOLORDLG && message!=WM_CTLCOLORSTATIC && message!=WM_CTLCOLOREDIT && message!=WM_CTLCOLORLISTBOX &&
message!=WM_CTLCOLORBTN) return FALSE;
const auto dc=reinterpret_cast<HDC>(wp);
const auto control=reinterpret_cast<HWND>(lp);
const bool field=message==WM_CTLCOLOREDIT ||
(message==WM_CTLCOLORSTATIC && dialogClass(control,L"KSwitcher.Files.FarEdit"));
const auto background=field?(isLavenderFileOperation(dialog)?lavender::surface:lavender::path):
GetDlgCtrlID(control)==lavenderSidebarLabel && message==WM_CTLCOLORSTATIC?lavender::path:lavenderDialogSurface(dialog);
SetTextColor(dc,IsWindowEnabled(control)?lavender::ink:lavender::muted);
SetBkColor(dc,background);
SetDCBrushColor(dc,background);
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,bool popup=false)
{
using namespace lavender;
const LavenderMetrics metrics(dialog);
fill(dc,client,canvas);
const bool operation=isLavenderFileOperation(dialog);
const auto edge=dialogEdge(dialog);
LONG headerBottom=client.top+metrics.px(operationHeaderHeight);
if(operation || popup)
{
rounded(dc,client,metrics.px(9),edge,edge);
const int stroke=metrics.px(2);
auto inner=client;
InflateRect(&inner,-stroke,-stroke);
if(popup)
rounded(dc,inner,metrics.px(7),operationSurface,operationSurface);
else
{
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);
}
}
else rounded(dc,client,metrics.px(9),surface,line);
auto content=client;
const int inset=metrics.px(10);
InflateRect(&content,-inset,0);
std::wstring_view caption(title);
const auto first=caption.find_first_not_of(L' ');
if(first!=caption.npos)
{
caption=caption.substr(first,caption.find_last_not_of(L' ')-first+1);
const auto titleInset=dialogFrameMetrics(metrics.dpi).content();
auto label=RECT{client.left+titleInset,client.top+metrics.px(4),content.right,client.top+metrics.px(23)};
if(operation) label.bottom=headerBottom;
text(dc,label,std::wstring(caption).c_str(),operation?surface:edge);
}
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);
}
+650 -198
View File
File diff suppressed because it is too large. Load diff
+77 -6
View File
@@ -18,7 +18,9 @@ constexpr int wideColumnControls[]{275,276,201,202,204};
constexpr int statusColumnControls[]{277,203,205,206,207,208};
constexpr int colorOptionControls[]{279,280};
constexpr int appearanceControls[]{281,282};
enum AppearanceSection { Font, DialogFrame, SystemThemes };
enum AppearanceSection { Font, DialogFrame, SystemThemes, WindowStyle };
constexpr int windowStyleChoice=417;
constexpr int windowStyleControls[]{416,windowStyleChoice};
constexpr int terminalScaleSection=1,areaScaleLabel=528,areaScaleControl=529;
constexpr int systemLightChoice=531,systemDarkChoice=533;
constexpr int systemThemeControls[]{530,systemLightChoice,532,systemDarkChoice,535};
@@ -105,6 +107,7 @@ void showPanelModeOptions(HWND dialog)
struct OptionsBaseline
{
FilesAppearance appearance=filesAppearance;
LOGFONTW font=displayFont;
int points=fontPoints;
DialogFramePadding padding=dialogFramePadding;
@@ -127,6 +130,7 @@ struct OptionsBaseline
struct OptionsDraft
{
OptionsBaseline baseline;
FilesAppearance appearance=baseline.appearance;
ks::files::TextSettings text=baseline.text;
ComparisonAppearance comparison=baseline.comparison;
FilesKeySettings keySettings=baseline.keySettings;
@@ -144,7 +148,7 @@ struct OptionsDraft
DWORD location{};
int markdownError{};
HTREEITEM wideColumnsNode{},markdownNode{};
RECT initialClient{};
RECT initialClient{}, resetBounds{};
UINT initialDpi=96;
OptionsControl controls[10]{
{optionsTree,OptionsAnchor::StretchHeight},
@@ -185,7 +189,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives ||
checked(compactLayoutControl)!=base.compact || checked(restoreDocumentsControl)!=base.restoreLocal ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
draft.framePadding!=base.padding || optionsFontChanged(draft) || draft.appearance!=base.appearance ||
checked(optionsRemoteTerminal)!=base.remoteTerminal ||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
@@ -202,7 +206,8 @@ LRESULT CALLBACK optionsGroupBackground(HWND group,UINT message,WPARAM wp,LPARAM
const auto dc=reinterpret_cast<HDC>(wp);
RECT client{};
GetClientRect(group,&client);
FillRect(dc,&client,GetSysColorBrush(COLOR_3DFACE));
if(lavenderFiles()) lavender::fill(dc,client,lavender::surface);
else FillRect(dc,&client,GetSysColorBrush(COLOR_3DFACE));
return TRUE;
}
return DefSubclassProc(group,message,wp,lp);
@@ -221,6 +226,7 @@ void layoutOptionsPreview(HWND dialog)
{
const auto id=GetDlgCtrlID(child);
if(child==preview || id==IDOK || id==IDCANCEL || id==optionsApply ||
(lavenderFiles() && id==optionsReset) ||
!(GetWindowLongPtrW(child,GWL_STYLE)&WS_VISIBLE)) continue;
const auto bounds=dialogControlBounds(dialog,id);
if(id!=-1 && bounds.left>=title.left-4) top=std::max(top,bounds.bottom);
@@ -254,6 +260,13 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft)
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW);
}
groupDialogButtons(dialog,{IDOK,IDCANCEL,optionsApply},true);
const auto reset=draft.resetBounds;
const auto ok=dialogControlBounds(dialog,IDOK);
const auto resetLeft=lavenderFiles()?dialogControlBounds(dialog,optionsTree).left:scale(reset.left);
const auto resetTop=lavenderFiles()?ok.top:scale(reset.top);
const auto resetHeight=lavenderFiles()?ok.bottom-ok.top:scale(reset.bottom-reset.top);
SetWindowPos(GetDlgItem(dialog,optionsReset),nullptr,resetLeft,resetTop,
scale(reset.right-reset.left),resetHeight,SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOREDRAW);
if(draft.page==PanelColors && draft.section==fileStyleSection) layoutFileStyleFields(dialog,false);
layoutOptionsPreview(dialog);
// Paint the final layout together, including the areas vacated by moved controls.
@@ -583,7 +596,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
(section==fileStyleSection?L"File type styles":colorNames[section]):
page==CommandLine?(section==terminalScaleSection?L"Terminal appearance":L"Command history"):
section==SystemThemes?L"System themes":section==DialogFrame?L"Dialog frame":L"Font";
section==WindowStyle?L"Window style":section==SystemThemes?L"System themes":
section==DialogFrame?L"Dialog frame":L"Font";
}
SetDlgItemTextW(dialog,optionsTitle,title);
const auto show=[&](auto &controls,bool visible)
@@ -612,6 +626,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
show(statusColumnControls,page==PanelModes && section==StatusColumns);
show(appearanceControls,page==Appearance && section==Font);
show(systemThemeControls,page==Appearance && section==SystemThemes);
show(windowStyleControls,page==Appearance && section==WindowStyle);
SendDlgItemMessageW(dialog,windowStyleChoice,CB_SETCURSEL,static_cast<WPARAM>(draft.appearance),0);
if(page==Appearance && section==SystemThemes) showSystemThemeRoles(dialog,draft.text);
showAreaScale(dialog,draft,optionsScaleArea(page,section));
show(comparisonControls,page==CompareFiles);
@@ -633,7 +649,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState};
show(fileStyleControls,fileTypes);
const auto preview=GetDlgItem(dialog,fileStylePreview);
const bool panelPreview=page>=0 && page<CommandLine && section>=0 && !(page==Appearance && section==SystemThemes);
const bool panelPreview=page>=0 && page<CommandLine && section>=0 &&
!(page==Appearance && (section==SystemThemes || section==WindowStyle));
ShowWindow(preview,panelPreview?SW_SHOW:SW_HIDE);
layoutOptionsPreview(dialog);
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
@@ -756,6 +773,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
{
addSection(L"Font",Font,matches(L"Display font") || matches(L"Panel scale"));
addSection(L"System themes",SystemThemes,matches(L"Light mode palette") || matches(L"Dark mode palette"));
addSection(L"Window style",WindowStyle,matches(L"Interface style") || matches(L"Lavender") || matches(L"Far"));
addSection(L"Dialog frame",DialogFrame,
matches(L"Outer padding") || matches(L"Inner padding") || matches(L"Row text padding"));
}
@@ -776,6 +794,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
SetWindowLongPtrW(dialog,DWLP_USER,lp);
draft.initialDpi=GetDpiForWindow(dialog);
GetClientRect(dialog,&draft.initialClient);
draft.resetBounds=dialogControlBounds(dialog,optionsReset);
for(auto &control:draft.controls) control.bounds=dialogControlBounds(dialog,control.id);
// Group boxes are behind their sibling controls. Erase their full client
// area on resize while clipping out the controls inside the frame.
@@ -799,6 +818,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_SETCURSEL,0,0);
SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0);
for(const auto label:{L"Far",L"Lavender"})
SendDlgItemMessageW(dialog,windowStyleChoice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
for(const auto &option:frameOptions)
for(DWORD value=0;value<=option.maximum;++value)
SendDlgItemMessageW(dialog,option.id,CB_ADDSTRING,0,
@@ -824,11 +845,30 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
filterOptions(dialog,draft);
if(lavenderFiles()) layoutOptions(dialog,draft);
updateOptionsApply(dialog,draft);
return TRUE;
}
auto *draft=reinterpret_cast<OptionsDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!draft) return FALSE;
if(message==WM_PAINT && lavenderFiles())
{
PAINTSTRUCT paint{};
const auto dc=BeginPaint(dialog,&paint);
RECT client{};
GetClientRect(dialog,&client);
const LavenderMetrics metrics(dialog);
const auto title=dialogControlBounds(dialog,optionsTitle);
const auto tree=dialogControlBounds(dialog,optionsTree);
const auto apply=dialogControlBounds(dialog,optionsApply);
lavender::fill(dc,client,lavender::surface);
lavender::rounded(dc,{tree.left-metrics.px(4),metrics.px(4),tree.right+metrics.px(4),
tree.bottom+metrics.px(4)},metrics.px(7),lavender::path,lavender::line);
lavender::fill(dc,{title.left,title.bottom+metrics.px(3),title.right,title.bottom+metrics.px(3)+1},lavender::line);
lavender::fill(dc,{client.left,apply.top-metrics.px(5),client.right,apply.top-metrics.px(5)+1},lavender::line);
EndPaint(dialog,&paint);
return TRUE;
}
if(message==WM_DRAWITEM && wp==fileStylePreview)
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT*>(lp);
@@ -855,6 +895,22 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
if(message==WM_NOTIFY && wp==optionsTree)
{
if(lavenderFiles() && reinterpret_cast<const NMHDR*>(lp)->code==NM_CUSTOMDRAW)
{
auto &draw=*reinterpret_cast<NMTVCUSTOMDRAW*>(lp);
if(draw.nmcd.dwDrawStage==CDDS_PREPAINT)
{
SetWindowLongPtrW(dialog,DWLP_MSGRESULT,CDRF_NOTIFYITEMDRAW);
return TRUE;
}
if(draw.nmcd.dwDrawStage==CDDS_ITEMPREPAINT)
{
draw.clrText=lavender::ink;
draw.clrTextBk=(draw.nmcd.uItemState&CDIS_SELECTED)?lavender::selection:lavender::path;
SetWindowLongPtrW(dialog,DWLP_MSGRESULT,CDRF_NEWFONT);
return TRUE;
}
}
const auto &change=*reinterpret_cast<const NMTREEVIEWW*>(lp);
if(change.hdr.code==TVN_SELCHANGEDW && change.itemNew.hItem)
{
@@ -874,6 +930,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(changeTextOption(dialog,*draft,wp)) return TRUE;
switch(LOWORD(wp))
{
case windowStyleChoice:
if(HIWORD(wp)==CBN_SELCHANGE)
{
draft->appearance=SendDlgItemMessageW(dialog,windowStyleChoice,CB_GETCURSEL,0,0)==1?
FilesAppearance::Lavender:FilesAppearance::Far;
updateOptionsApply(dialog,*draft);
}
return TRUE;
case optionsSearch:
if(HIWORD(wp)==EN_CHANGE) filterOptions(dialog,*draft);
return TRUE;
@@ -1007,6 +1071,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
return TRUE;
case optionsReset:
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==WindowStyle)))
draft->appearance=FilesAppearance::Far;
if(draft->page==allOptions) draft->scales=ks::files::defaultAppearanceScales;
else if(const auto area=optionsScaleArea(draft->page,draft->section))
draft->scales[ks::files::appearanceIndex(*area)]=100;
@@ -1244,6 +1310,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
saveChanged(dialogFrameOuterKey,draft->framePadding.outer,base.padding.outer);
saveChanged(dialogFrameInnerKey,draft->framePadding.inner,base.padding.inner);
saveChanged(dialogRowTextKey,draft->framePadding.rowText,base.padding.rowText);
saveChanged(filesAppearanceKey,static_cast<DWORD>(draft->appearance),static_cast<DWORD>(base.appearance));
for(size_t i=0;i<draft->scales.size();++i) saveChanged(areaScaleKeys[i],draft->scales[i],base.scales[i]);
if(fontChanged)
{
@@ -1255,13 +1322,16 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto mode=panelModeOption(dialog,index);
if(mode!=base.modes[index]) savePanelMode(index,mode);
}
const bool appearanceChanged=draft->appearance!=base.appearance;
loadFilesPreferences(owner);
if(appearanceChanged) styleLavenderDialogControls(dialog);
refreshFilesKeyBar();
notifyFilesPreferences(owner);
const auto dialogOwner=GetWindow(dialog,GW_OWNER);
if(dialogOwner!=owner)
SendMessageW(dialogOwner,filesPreferencesChanged,reinterpret_cast<WPARAM>(owner),0);
draft->baseline=OptionsBaseline{};
draft->appearance=draft->baseline.appearance;
draft->text=draft->baseline.text;
draft->comparison=draft->baseline.comparison;
draft->keySettings=draft->baseline.keySettings;
@@ -1289,6 +1359,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(draft->page==PanelColors && draft->section==fileStyleSection)
updateFileStyleEditor(dialog,*draft,true);
showOptionsPage(dialog,*draft,draft->page,draft->section);
if(appearanceChanged) layoutOptions(dialog,*draft);
layout(owner);
showFileDetails(panels[active]);
RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW);
+10 -4
View File
@@ -58,20 +58,20 @@ bool retryRemotePanel(Panel &panel,bool automatic,const fs::path &fallback)
return true;
}
void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional<size_t> position={})
void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional<size_t> position={},fs::path selection={})
{
if(location.directory.empty()) return;
if(location.provider==FolderProvider::local)
{
openOn(panel,location.directory,true,{},{},{},{},position);
openOn(panel,location.directory,true,{},std::move(selection),{},{},position);
return;
}
if(location.sameSource(folderLocation(panel,panel.directory)))
{
openOn(panel,location.directory,false,panel.peer,{},{},panel.ftp,position);
openOn(panel,location.directory,false,panel.peer,std::move(selection),{},panel.ftp,position);
return;
}
RemotePanelLocation remote{location.directory,{},{},{},position};
RemotePanelLocation remote{location.directory,std::move(selection),{},{},position};
if(isTransferFolder(location.provider))
{
remote.ftpProfile=location.id;
@@ -124,6 +124,12 @@ void saveFtpPanelLocation(const Panel &panel,int index)
location=panel.remoteRetry->location;
else if(panel.scanRequest && panel.scanRequest->ftp && panel.scanRequest->ftp->protocol==TransferProtocol::ftp)
location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id};
else if(panel.listing && !panel.navigation.history.empty())
{
const auto &previous=panel.navigation.history[panel.navigation.current];
if(previous.provider==FolderProvider::ftp)
location={previous.directory,panel.listing->returnSelection,previous.id};
}
const auto key=ftpPanelLocationKeys[index];
if(location.ftpProfile.empty() || !isFtpFolderPath(location.directory))
+6 -6
View File
@@ -2,7 +2,7 @@ class PanelRowsUpdate
{
public:
PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)),
profiles(transferProfileList(panel))
locationList(panelListsLocations(panel))
{
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
panel.rows.clear();
@@ -33,10 +33,10 @@ public:
}
panel.marked.push_back(!up && marked);
const auto found=panel.metadata.find(path);
const auto entry=up || profiles || found==panel.metadata.end()?FolderEntryMetadata{}:found->second;
const auto entry=up || locationList || found==panel.metadata.end()?FolderEntryMetadata{}:found->second;
panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0);
panel.sizes.push_back(profiles?L"":folder?(up?L"Up":L"Folder"):std::to_wstring(entry.size));
if(!up && !profiles)
panel.sizes.push_back(up?L"Up":locationList?L"":folder?L"Folder":std::to_wstring(entry.size));
if(!up && !locationList)
{
auto &longest=panel.longestColumn;
longest[sizeColumn]=std::max(longest[sizeColumn],panel.sizes.back().size());
@@ -63,7 +63,7 @@ public:
private:
Panel &panel;
bool visible,profiles;
bool visible,locationList;
};
bool treePanelActive(const Panel &panel)
@@ -120,7 +120,7 @@ void visitPanelMarks(const Panel &panel,const Visitor &visit)
}
return;
}
if(transferProfileList(panel)) return;
if(panelListsLocations(panel)) return;
for(size_t i=0;i<panel.rows.size();++i)
{
if(!panel.marked[i] || panel.sizes[i]==L"Up") continue;
+217
View File
@@ -0,0 +1,217 @@
enum class PathAction { back, forward, up, edit, source, ancestors, previous, folder };
struct PathPart
{
PathAction action{};
std::wstring label;
fs::path target;
std::vector<fs::path> hidden;
RECT rect{};
RECT separator{};
bool current{}, dim{}, enabled=true;
};
std::wstring pathSegmentLabel(const fs::path &path,FolderProvider provider,bool compact)
{
if(isTransferFolder(provider) && path==ftpRoot) return L"/";
if(compact && provider==FolderProvider::local && !path.has_relative_path())
{
auto drive=path.root_name().native();
if(drive.size()==2 && drive.back()==L':') return drive;
}
return panelParentPath(path,provider==FolderProvider::local).empty()?path.native():path.filename().native();
}
struct PathBarMetrics
{
bool compact;
LavenderMetrics dpi;
LONG button, padding, separator;
PathBarMetrics(HWND window,RECT bounds): compact(lavenderFiles()),dpi(window),
button(std::max(1L,std::min(compact?static_cast<LONG>(dpi.px(21)):2L*cellWidth,
(bounds.right-bounds.left)/7))),
padding(compact?dpi.px(7):0),separator(compact?dpi.px(9):0) {}
RECT breadcrumbBounds(RECT bounds) const
{
bounds.left=std::min(bounds.right,bounds.left+4*button+dpi.px(2));
return bounds;
}
};
std::vector<PathPart> panelPathParts(HDC dc,const Panel &panel,RECT bounds,const PathBarMetrics &metrics)
{
if(bounds.right<=bounds.left) return {};
const LONG width=metrics.button;
const auto breadcrumb=metrics.breadcrumbBounds(bounds);
const auto font=metrics.compact && dc?SelectObject(dc,lavender::font?lavender::font:GetStockObject(DEFAULT_GUI_FONT)):nullptr;
const auto measure=[&](const std::wstring &label,bool current=false)
{
SIZE size{};
if(font)
{
const auto regular=current && lavender::emphasis?SelectObject(dc,lavender::emphasis):nullptr;
const auto measured=GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.size()),&size);
if(regular) SelectObject(dc,regular);
if(measured) return size.cx+2*metrics.padding;
}
return static_cast<LONG>(label.size()+2)*cellWidth;
};
std::vector<PathPart> parts;
bool hasCrumb=false;
const auto add=[&](PathPart part,LONG length,bool crumb=false)
{
if(length<=0 || bounds.left>=bounds.right) return;
if(crumb && hasCrumb && metrics.separator)
{
const auto end=std::min(bounds.right-1,bounds.left+metrics.separator);
part.separator={bounds.left,bounds.top,end,bounds.bottom};
bounds.left=end;
}
part.rect={bounds.left,bounds.top,std::min(bounds.right,bounds.left+length),bounds.bottom};
bounds.left=part.rect.right;
parts.push_back(std::move(part));
hasCrumb|=crumb;
};
const auto location=folderLocation(panel,panel.directory);
const auto provider=location.provider;
const auto local=provider==FolderProvider::local;
const auto parent=panelParentPath(panel.directory,local);
add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width);
add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width);
add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width);
add({.action=PathAction::edit,.label=L"✎"},width);
if(metrics.compact)
{
bounds.left=std::min(bounds.right,breadcrumb.left+metrics.dpi.px(1));
bounds.right=std::max(bounds.left,bounds.right-metrics.dpi.px(1));
}
if(!local && (!metrics.compact || !location.label.empty()))
{
const auto available=std::max(1L,(bounds.right-bounds.left)/2);
add({.action=PathAction::source,.label=location.label},std::min(available,measure(location.label)),true);
}
std::vector<fs::path> ancestors, previous;
for(auto path=parent;!path.empty();path=panelParentPath(path,local)) ancestors.push_back(path);
std::reverse(ancestors.begin(),ancestors.end());
if(inFolderBranch(panel.directory,panel.navigation.previousBranch,provider))
{
for(auto path=panel.navigation.previousBranch;!sameFolderPath(path,panel.directory,provider);
path=panelParentPath(path,local))
previous.push_back(path);
std::reverse(previous.begin(),previous.end());
}
const LONG room=bounds.right-bounds.left;
const auto label=[&](const fs::path &path) { return pathSegmentLabel(path,provider,metrics.compact); };
const auto segmentWidth=[&](const fs::path &path) { return measure(label(path))+metrics.separator; };
const LONG overflowWidth=width+metrics.separator;
LONG currentWidth=measure(label(panel.directory),true);
LONG required=currentWidth+metrics.separator;
for(const auto &path:ancestors) required+=segmentWidth(path);
for(const auto &path:previous) required+=segmentWidth(path);
if(!hasCrumb) required-=metrics.separator;
size_t firstAncestor=0,visiblePrevious=previous.size();
if(required>room)
{
const LONG reserved=(!ancestors.empty()?overflowWidth:0)+(!previous.empty()?overflowWidth:0)+
(hasCrumb?metrics.separator:0);
currentWidth=std::min(currentWidth,std::max(1L,room-reserved));
LONG remaining=room-currentWidth-reserved;
firstAncestor=ancestors.size();
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1]))
remaining-=segmentWidth(ancestors[--firstAncestor]);
visiblePrevious=0;
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious]))
remaining-=segmentWidth(previous[visiblePrevious++]);
}
if(firstAncestor)
add({.action=PathAction::ancestors,.label=L"…",
.hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width,true);
for(size_t i=firstAncestor;i<ancestors.size();++i)
add({.action=PathAction::folder,.label=label(ancestors[i]),.target=ancestors[i]},
segmentWidth(ancestors[i])-metrics.separator,true);
add({.action=PathAction::edit,.label=label(panel.directory),.current=true},currentWidth,true);
for(size_t i=0;i<visiblePrevious;++i)
add({.action=PathAction::folder,.label=label(previous[i]),.target=previous[i],.dim=true},
segmentWidth(previous[i])-metrics.separator,true);
if(visiblePrevious<previous.size())
add({.action=PathAction::previous,.label=L"…",
.hidden={previous.begin()+visiblePrevious,previous.end()},.dim=true},width,true);
if(font) SelectObject(dc,font);
return parts;
}
void paintPanelPath(HDC dc,HWND window,RECT bounds,const Panel &panel,bool activePanel)
{
const PathBarMetrics metrics(window,bounds);
const int saved=SaveDC(dc);
SelectObject(dc,mono);
SetBkMode(dc,TRANSPARENT);
HPEN separatorPen{};
if(metrics.compact)
{
lavender::rounded(dc,metrics.breadcrumbBounds(bounds),metrics.dpi.px(7),lavender::path,lavender::line);
separatorPen=CreatePen(PS_SOLID,metrics.dpi.px(1),lavender::muted);
}
for(const auto &part:panelPathParts(dc,panel,bounds,metrics))
{
const bool current=activePanel && part.current;
if(metrics.compact)
{
auto label=part.rect;
const auto &gap=part.separator;
const LONG radius=metrics.dpi.px(2);
if(gap.right-gap.left>2*radius)
{
const LONG x=(gap.left+gap.right)/2, y=(gap.top+gap.bottom)/2;
const auto pen=SelectObject(dc,separatorPen?separatorPen:GetStockObject(DC_PEN));
if(!separatorPen) SetDCPenColor(dc,lavender::muted);
MoveToEx(dc,x-1,y-radius,nullptr);
LineTo(dc,x+radius-1,y);
LineTo(dc,x-1,y+radius+1);
SelectObject(dc,pen);
}
if(part.current)
{
auto chip=part.rect;
InflateRect(&chip,0,-metrics.dpi.px(3));
lavender::rounded(dc,chip,metrics.dpi.px(5),lavender::key,lavender::key);
InflateRect(&label,-metrics.dpi.px(4),0);
}
lavender::text(dc,label,part.label.c_str(),!part.enabled || part.dim?lavender::muted:lavender::ink,
DT_CENTER,DT_END_ELLIPSIS,part.current?lavender::emphasis:nullptr);
continue;
}
FillRect(dc,&part.rect,current?teal:blue);
SetTextColor(dc,!part.enabled || part.dim?RGB(160,170,190):colors[current?Text:Frame]);
auto text=part.rect;
DrawTextW(dc,part.label.c_str(),static_cast<int>(part.label.size()),&text,
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
}
if(separatorPen) DeleteObject(separatorPen);
if(saved) RestoreDC(dc,saved);
}
void paintLavenderPanelPath(const DRAWITEMSTRUCT &item,const Panel &panel,bool navigable,bool activePanel)
{
auto bounds=item.rcItem;
lavender::fill(item.hDC,bounds,lavender::surface);
if(navigable)
{
paintPanelPath(item.hDC,item.hwndItem,bounds,panel,activePanel);
return;
}
const LavenderMetrics metrics(item.hwndItem);
lavender::rounded(item.hDC,bounds,metrics.px(7),lavender::path,
activePanel?lavender::activeEdge:lavender::line);
paintLavenderFileIcon(item.hDC,bounds,metrics,true);
bounds.left+=metrics.px(30);
bounds.right-=metrics.px(9);
const auto caption=panelCaption(panel);
lavender::text(item.hDC,bounds,caption.c_str(),lavender::ink,DT_LEFT,DT_PATH_ELLIPSIS);
}
+49 -140
View File
@@ -4,8 +4,6 @@ bool pathNavigationAvailable(const Panel &panel)
return !transferProfileList(panel) && !panel.findOrigin && !panel.archive && !panel.directory.empty();
}
enum class PathAction { back, forward, up, edit, source, ancestors, previous, folder };
void navigatePanelPath(Panel &panel,const fs::path &path)
{
if(path.empty()) return;
@@ -25,119 +23,6 @@ void navigatePanelHistory(Panel &panel,int direction)
}
}
struct PathPart
{
PathAction action{};
std::wstring label;
fs::path target;
std::vector<fs::path> hidden;
RECT rect{};
bool current{}, dim{}, enabled=true;
};
std::wstring pathSegmentLabel(const fs::path &path,FolderProvider provider)
{
if(isTransferFolder(provider) && path==ftpRoot) return L"/";
return panelParentPath(path,provider==FolderProvider::local).empty()?path.native():path.filename().native();
}
LONG segmentWidth(const fs::path &path,FolderProvider provider)
{
return static_cast<LONG>(pathSegmentLabel(path,provider).size()+2)*cellWidth;
}
std::vector<PathPart> panelPathParts(const Panel &panel,RECT bounds)
{
const LONG total=bounds.right-bounds.left;
if(total<=0) return {};
const LONG width=std::max(1L,std::min(2L*cellWidth,total/7));
std::vector<PathPart> parts;
const auto add=[&](PathPart part,LONG length)
{
if(length<=0 || bounds.left>=bounds.right) return;
part.rect={bounds.left,bounds.top,std::min(bounds.right,bounds.left+length),bounds.bottom};
bounds.left=part.rect.right;
parts.push_back(std::move(part));
};
const auto location=folderLocation(panel,panel.directory);
const auto provider=location.provider;
const auto local=provider==FolderProvider::local;
const auto parent=panelParentPath(panel.directory,local);
add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width);
add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width);
add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width);
add({.action=PathAction::edit,.label=L"✎"},width);
if(!local)
{
const auto available=std::max(1L,(bounds.right-bounds.left)/2);
const auto sourceWidth=std::min(available,static_cast<LONG>(location.label.size()+2)*cellWidth);
add({.action=PathAction::source,.label=location.label},sourceWidth);
}
std::vector<fs::path> ancestors, previous;
for(auto path=parent;!path.empty();path=panelParentPath(path,local)) ancestors.push_back(path);
std::reverse(ancestors.begin(),ancestors.end());
if(inFolderBranch(panel.directory,panel.navigation.previousBranch,provider))
{
for(auto path=panel.navigation.previousBranch;!sameFolderPath(path,panel.directory,provider);
path=panelParentPath(path,local))
previous.push_back(path);
std::reverse(previous.begin(),previous.end());
}
const LONG room=bounds.right-bounds.left;
LONG required=segmentWidth(panel.directory,provider);
for(const auto &path:ancestors) required+=segmentWidth(path,provider);
for(const auto &path:previous) required+=segmentWidth(path,provider);
size_t firstAncestor=0,visiblePrevious=previous.size();
LONG currentWidth=segmentWidth(panel.directory,provider);
if(required>room)
{
const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0);
currentWidth=std::min(currentWidth,std::max(1L,room-reserved));
LONG remaining=room-currentWidth-reserved;
firstAncestor=ancestors.size();
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1],provider))
remaining-=segmentWidth(ancestors[--firstAncestor],provider);
visiblePrevious=0;
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious],provider))
remaining-=segmentWidth(previous[visiblePrevious++],provider);
}
if(firstAncestor)
add({.action=PathAction::ancestors,.label=L"…",
.hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width);
for(size_t i=firstAncestor;i<ancestors.size();++i)
add({.action=PathAction::folder,.label=pathSegmentLabel(ancestors[i],provider),.target=ancestors[i]},
segmentWidth(ancestors[i],provider));
add({.action=PathAction::edit,.label=pathSegmentLabel(panel.directory,provider),.current=true},currentWidth);
for(size_t i=0;i<visiblePrevious;++i)
add({.action=PathAction::folder,.label=pathSegmentLabel(previous[i],provider),.target=previous[i],.dim=true},
segmentWidth(previous[i],provider));
if(visiblePrevious<previous.size())
add({.action=PathAction::previous,.label=L"…",
.hidden={previous.begin()+visiblePrevious,previous.end()},.dim=true},width);
return parts;
}
void paintPanelPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel)
{
const int saved=SaveDC(dc);
SelectObject(dc,mono);
SetBkMode(dc,TRANSPARENT);
for(const auto &part:panelPathParts(panel,bounds))
{
const bool current=activePanel && part.current;
FillRect(dc,&part.rect,current?teal:blue);
SetTextColor(dc,!part.enabled || part.dim?RGB(160,170,190):colors[current?Text:Frame]);
auto text=part.rect;
DrawTextW(dc,part.label.c_str(),static_cast<int>(part.label.size()),&text,
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
}
if(saved) RestoreDC(dc,saved);
}
constexpr int addressField=485,addressLabel=486,addressFooter=487;
struct PathPrompt
@@ -318,24 +203,18 @@ void editPanelPath(Panel &panel)
}
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<FolderLocation> locations,
RECT anchor,bool recent=false)
RECT anchor)
{
hidePicker();
showMenu(false);
commandPicker=false;
pickerPanel=side;
folderPicker=FolderPicker{caption,std::move(locations),recent};
folderPicker=FolderPicker{caption,std::move(locations)};
SendMessageW(picker,LB_RESETCONTENT,0,0);
size_t longest=wcslen(caption);
for(const auto &location:folderPicker->locations)
{
auto label=isTransferFolder(location.provider)?ftpPath(location.directory):location.directory.native();
if(recent && location.provider!=FolderProvider::local)
{
const auto &source=location.label;
const auto kind=isTransferFolder(location.provider)?transferProtocolName(folderTransferProtocol(location.provider)):L"LAN";
label=std::wstring(kind)+L" · "+(source.empty()?std::wstring{}:source+L" · ")+label;
}
longest=std::max(longest,label.size());
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
@@ -356,26 +235,52 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<Fol
SetFocus(picker);
}
void showRecentFolders(int side)
void showRecentFolders(Panel &panel)
{
auto locations=readRecentFolders();
if(locations.empty())
PanelListing listing;
listing.recent=readRecentFolders();
listing.rows.reserve(listing.recent.size());
for(size_t i=0;i<listing.recent.size();++i)
{
setStatus(L"No recent folders.");
auto &location=listing.recent[i];
auto label=location.directory.native();
if(location.provider!=FolderProvider::local)
{
const wchar_t *kind=L"LAN";
if(isTransferFolder(location.provider))
{
const auto protocol=folderTransferProtocol(location.provider);
kind=transferProtocolName(protocol);
if(loadTransferProfiles(protocol))
if(const auto *profile=findTransferProfile(location.id,protocol)) location.label=profile->name;
label=ftpPath(location.directory);
}
if(!location.label.empty()) label=location.label+L" · "+label;
label=std::wstring(kind)+L" · "+label;
}
listing.rows.emplace_back(std::to_wstring(i),std::move(label));
}
openPanelListing(panel,std::move(listing));
}
void openRecentFolder(Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row!=LB_ERR && !panel.scan.valid())
openFolderLocation(panel,panel.listing->recent[row]);
}
void removeRecentFolder(Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.scan.valid()) return;
if(!updateRecentFolders(panel.listing->recent[row],false))
{
setStatus(L"Could not remove the recent folder.");
return;
}
const auto owner=GetParent(picker);
RECT anchor{};
GetWindowRect(panels[side].path,&anchor);
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&anchor),2);
for(auto &location:locations)
{
if(!isTransferFolder(location.provider)) continue;
const auto protocol=folderTransferProtocol(location.provider);
if(loadTransferProfiles(protocol))
if(const auto *profile=findTransferProfile(location.id,protocol)) location.label=profile->name;
}
showFolderPicker(owner,side,L"Recent folders",std::move(locations),anchor,true);
for(auto &other:panels)
if(recentFolderList(other) && !other.scan.valid()) showRecentFolders(other);
}
void showHiddenPathParts(HWND window,int side,const PathPart &part)
@@ -413,7 +318,11 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
RECT bounds{};
GetClientRect(window,&bounds);
const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto parts=panelPathParts(panel,bounds);
const PathBarMetrics metrics(window,bounds);
const auto dc=metrics.compact?GetDC(window):nullptr;
if(metrics.compact && !dc) return 0;
const auto parts=panelPathParts(dc,panel,bounds,metrics);
if(dc) ReleaseDC(window,dc);
for(const auto &part:parts)
{
if(!part.enabled || !PtInRect(&part.rect,mouse)) continue;
+1 -1
View File
@@ -129,7 +129,7 @@ void showReadOnlyProperties(HWND owner,const ItemProperties &properties,const st
bool panelItemPropertiesAvailable(const Panel &panel)
{
const auto row=currentPanelRow(panel);
return row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel);
return row!=LB_ERR && panel.sizes[row]!=L"Up" && !panelListsLocations(panel);
}
void showSourceItemProperties(HWND owner,const Panel &panel,const fs::path &path,ItemProperties properties)
+166 -203
View File
@@ -2,7 +2,6 @@ namespace smb
{
constexpr wchar_t profilesKey[]=L"SmbProfiles";
constexpr DWORD shareTypeMask=0xff;
constexpr int summary=540,list=541,status=542,footer=543,newProfile=544,editProfile=545,removeProfile=546,signIn=547;
constexpr int nameLabel=550,nameField=551,addressLabel=552,addressField=553,editFooter=554;
constexpr int loginLabel=555,userLabel=556,userField=557,passwordLabel=558,passwordField=559,rememberField=560,loginFooter=561;
@@ -400,234 +399,198 @@ INT_PTR CALLBACK loginDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
struct Browser
struct PendingConnection
{
std::vector<Profile> profiles;
std::optional<Profile> server;
std::vector<std::wstring> shares;
fs::path chosen;
Profile profile;
std::atomic_bool canceled{};
bool busy{};
std::promise<Connection> result;
std::future<Connection> completion=result.get_future();
};
void browserControls(HWND dialog,const Browser &browser)
std::optional<Profile> findProfile(const fs::path &id)
{
const auto selected=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0)!=LB_ERR;
EnableWindow(GetDlgItem(dialog,list),!browser.busy);
EnableWindow(GetDlgItem(dialog,IDOK),!browser.busy && selected);
EnableWindow(GetDlgItem(dialog,newProfile),!browser.busy);
for(const auto button:{editProfile,removeProfile,signIn})
EnableWindow(GetDlgItem(dialog,button),!browser.busy && selected && !browser.server);
const auto profiles=readProfiles();
const auto match=std::find_if(profiles.begin(),profiles.end(),[&](const auto &profile) {
return ks::wide(profile.id)==id.native();
});
return match==profiles.end()?std::nullopt:std::optional{*match};
}
void showRows(HWND dialog,const Browser &browser,LRESULT selection=0)
std::optional<Profile> selectedProfile(const Panel &panel)
{
const auto rows=GetDlgItem(dialog,list);
SendMessageW(rows,LB_RESETCONTENT,0,0);
const auto add=[&](const std::wstring &label){SendMessageW(rows,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));};
if(browser.server)
{
for(const auto &share:browser.shares) add(share);
SetDlgItemTextW(dialog,summary,(L"Shared folders on "+browser.server->target.server).c_str());
SetDlgItemTextW(dialog,status,browser.shares.empty()?L"No visible disk shares. A known UNC share can be saved as a profile.":L"");
SetDlgItemTextW(dialog,newProfile,L"&Back");
for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_HIDE);
layoutDialogButtons(dialog,footer,{IDOK,newProfile,IDCANCEL});
}
else
{
for(const auto &entry:browser.profiles) add(entry.name+L" · "+profileAddress(entry));
SetDlgItemTextW(dialog,summary,L"Saved SMB connections");
SetDlgItemTextW(dialog,status,browser.profiles.empty()?L"Choose New to add a server or UNC folder.":L"");
SetDlgItemTextW(dialog,newProfile,L"&New");
for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_SHOWNA);
layoutDialogButtons(dialog,footer,{IDOK,newProfile,editProfile,removeProfile,signIn,IDCANCEL});
}
const auto count=SendMessageW(rows,LB_GETCOUNT,0,0);
if(count>0) SendMessageW(rows,LB_SETCURSEL,std::clamp<LRESULT>(selection,0,count-1),0);
browserControls(dialog,browser);
SetFocus(count>0?rows:GetDlgItem(dialog,newProfile));
if(!panel.listing || !panel.listing->smb || !panel.listing->smb->server.empty() || panel.scan.valid() || panel.smbPending) return {};
const auto row=currentPanelRow(panel);
return row==LB_ERR?std::nullopt:findProfile(panel.rows[row]);
}
void openProfile(HWND dialog,Browser &browser,const Profile &profile,bool withLogin)
void showProfiles(Panel &panel,const std::vector<Profile> &profiles,fs::path selection={})
{
Credentials login;
PanelListing listing{SmbListing{}};
listing.rows.reserve(profiles.size());
for(const auto &profile:profiles)
listing.rows.emplace_back(ks::wide(profile.id),profile.name+L" · "+profileAddress(profile));
openPanelListing(panel,std::move(listing),std::move(selection));
}
void refreshProfiles(Panel &panel,const std::vector<Profile> &profiles,fs::path selection={})
{
for(auto &other:panels)
if(other.listing && other.listing->smb && other.listing->smb->server.empty() && !other.smbPending && !other.scan.valid())
showProfiles(other,profiles,&other==&panel?selection:fs::path{});
}
void openProfile(Panel &panel,Profile profile,bool withLogin)
{
if(panel.smbPending || panel.scan.valid()) return;
const auto owner=GetParent(panel.list);
std::shared_ptr<Credentials> login;
if(withLogin)
{
LoginPrompt prompt{profile,login};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(123),dialog,loginDialog,
login=std::make_shared<Credentials>();
LoginPrompt prompt{profile,*login};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(123),owner,loginDialog,
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
}
browser.busy=true;
browser.canceled=false;
browserControls(dialog,browser);
SetFocus(GetDlgItem(dialog,IDCANCEL));
SetDlgItemTextW(dialog,status,(L"Connecting to "+profile.target.server+L"…").c_str());
Connection result;
auto pending=std::make_shared<PendingConnection>();
pending->profile=std::move(profile);
try
{
FileOperationUi worker;
worker.run(dialog,browser.canceled,[&]{result=connect(profile,withLogin?&login:nullptr,browser.canceled);});
std::thread([pending,login=std::move(login),owner] {
Connection connection;
try {connection=connect(pending->profile,login.get(),pending->canceled);}
catch(const std::exception &) {connection.error=ERROR_GEN_FAILURE;}
pending->result.set_value(std::move(connection));
PostMessageW(owner,directoryScanReady,0,0);
}).detach();
}
catch(const std::exception &)
catch(const std::system_error &error)
{
result.error=ERROR_GEN_FAILURE;
}
browser.busy=false;
browserControls(dialog,browser);
if(browser.canceled)
{
SetDlgItemTextW(dialog,status,L"Connection canceled.");
SetFocus(GetDlgItem(dialog,list));
setStatus(L"Could not start SMB connection: "+fileError(error));
return;
}
if(result.error)
{
auto detail=profileAddress(profile)+L"\r\n\r\n"+errorText(result.error);
if(result.error==ERROR_ACCESS_DENIED || result.error==ERROR_LOGON_FAILURE ||
result.error==ERROR_INVALID_PASSWORD || result.error==ERROR_BAD_USERNAME)
detail+=L"\r\n\r\nUse Sign in to try a different account.";
showFilesNotice(dialog,detail.c_str(),L"Could not open SMB connection",{.tone=FilesNoticeTone::warning});
SetDlgItemTextW(dialog,status,L"Connection failed. Open to retry or choose Sign in.");
SetFocus(GetDlgItem(dialog,list));
return;
}
if(result.credentialError)
{
const auto detail=L"Connected, but Windows Credential Manager did not save the account.\r\n\r\n"+
errorText(result.credentialError);
showFilesNotice(dialog,detail.c_str(),L"SMB sign in",{.tone=FilesNoticeTone::warning});
}
if(!result.folder.empty())
{
browser.chosen=std::move(result.folder);
FilesModalDialog::finish(dialog,IDOK);
return;
}
browser.server=profile;
browser.shares=std::move(result.shares);
showRows(dialog,browser);
panel.smbPending=std::move(pending);
if(&panel==&panels[active]) showFileDetails(panel);
}
}
INT_PTR CALLBACK browserDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
void cancelSmbConnection(Panel &panel)
{
auto *browser=reinterpret_cast<Browser*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(message==WM_INITDIALOG)
{
browser=reinterpret_cast<Browser*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,summary);
for(const auto id:{summary,list,status})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendDlgItemMessageW(dialog,list,LB_SETITEMHEIGHT,0,textHeight);
installScrollBar(GetDlgItem(dialog,list),dialog);
showRows(dialog,*browser);
return FALSE;
}
if(message==WM_DRAWITEM && wp==list)
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT*>(lp);
if(item.itemID==UINT(-1)) return TRUE;
const auto length=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
if(length==LB_ERR) return TRUE;
std::wstring label(static_cast<size_t>(length)+1,L'\0');
SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()));
const bool selected=(item.itemState&ODS_SELECTED)!=0;
paintDialogListRow(item.hDC,item.rcItem,label.c_str(),mono,colors[Text],
selected?colors[Selection]:colors[Dialog],dialogRowTextInset(cellWidth),DT_END_ELLIPSIS);
return TRUE;
}
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB ",false,{footer},true,GetDlgItem(dialog,list)))
return painted;
if(!browser) return FALSE;
if(closeRequest(message,wp))
{
if(browser->busy)
{
browser->canceled=true;
SetDlgItemTextW(dialog,status,L"Stopping when Windows returns…");
}
else FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(browser->busy) return TRUE;
const auto command=LOWORD(wp);
const auto row=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0);
if(command==list && HIWORD(wp)==LBN_SELCHANGE)
{
browserControls(dialog,*browser);
return TRUE;
}
const bool open=command==IDOK || (command==list && HIWORD(wp)==LBN_DBLCLK);
if(browser->server)
{
if(command==newProfile)
{
browser->server.reset();
browser->shares.clear();
showRows(dialog,*browser);
}
else if(open && row>=0 && static_cast<size_t>(row)<browser->shares.size())
{
browser->chosen=fs::path(browser->server->target.server+L"\\"+browser->shares[row]);
FilesModalDialog::finish(dialog,IDOK);
}
return TRUE;
}
const auto *selected=row>=0 && static_cast<size_t>(row)<browser->profiles.size()?&browser->profiles[row]:nullptr;
if(command==newProfile || (command==editProfile && selected))
{
EditProfile edit{command==newProfile?Profile{}:*selected};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(122),dialog,editDialog,
reinterpret_cast<LPARAM>(&edit))==IDOK)
{
browser->profiles=std::move(*edit.saved);
const auto profile=std::find_if(browser->profiles.begin(),browser->profiles.end(),[&](const auto &entry) {
return entry.id==edit.profile.id;
});
showRows(dialog,*browser,profile-browser->profiles.begin());
}
return TRUE;
}
if(selected && (open || command==signIn))
{
openProfile(dialog,*browser,*selected,command==signIn);
return TRUE;
}
if(selected && command==removeProfile)
{
const auto detail=L"Remove "+selected->name+L" and its saved credentials?";
if(showFilesNotice(dialog,detail.c_str(),L"Remove SMB connection",{.confirm=true})!=IDYES) return TRUE;
DWORD error=ERROR_SUCCESS;
auto updated=updateProfiles([&](auto &profiles) {
const auto row=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==selected->id;});
if(row==profiles.end()) return true;
if((error=deleteCredential(*row))) return false;
profiles.erase(row);
return true;
});
if(updated)
{
browser->profiles=std::move(*updated);
showRows(dialog,*browser,row);
}
else
{
const auto failure=error?errorText(error):L"Could not remove the saved connection.";
showFilesNotice(dialog,failure.c_str(),L"Remove SMB connection");
}
return TRUE;
}
return FALSE;
}
if(auto pending=std::exchange(panel.smbPending,{})) pending->canceled=true;
}
void showSmbProfiles(Panel &panel)
{
smb::Browser browser{smb::readProfiles()};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(121),GetParent(panel.list),
smb::browserDialog,reinterpret_cast<LPARAM>(&browser))==IDOK)
openOn(panel,browser.chosen,false,{});
smb::showProfiles(panel,smb::readProfiles());
}
void refreshSmbPanel(Panel &panel)
{
if(panel.scan.valid() || panel.smbPending) return;
if(panel.listing->smb->server.empty()) showSmbProfiles(panel);
else if(auto profile=smb::findProfile(ks::wide(panel.listing->smb->serverId));profile && profile->target.folder.empty())
smb::openProfile(panel,std::move(*profile),false);
else showSmbProfiles(panel);
}
void backSmbPanel(Panel &panel)
{
if(panel.smbPending)
{
cancelSmbConnection(panel);
setStatus(L"SMB connection canceled.");
}
else if(!panel.listing->smb->server.empty())
smb::showProfiles(panel,smb::readProfiles(),ks::wide(panel.listing->smb->serverId));
else closePanelListing(panel);
}
void enterSmbPanel(Panel &panel)
{
if(panel.scan.valid() || panel.smbPending) return;
if(panel.listing->smb->server.empty())
{
if(auto profile=smb::selectedProfile(panel)) smb::openProfile(panel,std::move(*profile),false);
return;
}
const auto row=currentPanelRow(panel);
if(row==LB_ERR) return;
const auto &name=panel.rows[row];
if(name==L"..") backSmbPanel(panel);
else openOn(panel,fs::path(panel.listing->smb->server+L"\\"+name.native()),false,{});
}
void editSmbProfile(Panel &panel,bool create)
{
if(!panel.listing || !panel.listing->smb || !panel.listing->smb->server.empty() || panel.smbPending || panel.scan.valid()) return;
const auto profile=create?std::optional{smb::Profile{}}:smb::selectedProfile(panel);
if(!profile) return;
smb::EditProfile edit{*profile};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(122),GetParent(panel.list),smb::editDialog,
reinterpret_cast<LPARAM>(&edit))==IDOK)
smb::refreshProfiles(panel,*edit.saved,ks::wide(edit.profile.id));
}
void removeSmbProfile(Panel &panel)
{
const auto selected=smb::selectedProfile(panel);
if(!selected) return;
const auto owner=GetParent(panel.list);
const auto detail=L"Remove "+selected->name+L" and its saved credentials?";
if(showFilesNotice(owner,detail.c_str(),L"Remove SMB connection",{.confirm=true})!=IDYES) return;
DWORD error=ERROR_SUCCESS;
const auto updated=smb::updateProfiles([&](auto &profiles) {
const auto entry=std::find_if(profiles.begin(),profiles.end(),[&](const auto &profile){return profile.id==selected->id;});
if(entry==profiles.end()) return true;
if((error=smb::deleteCredential(*entry))) return false;
profiles.erase(entry);
return true;
});
if(updated) smb::refreshProfiles(panel,*updated);
else
{
const auto failure=error?smb::errorText(error):L"Could not remove the saved connection.";
showFilesNotice(owner,failure.c_str(),L"Remove SMB connection");
}
}
void signInSmbProfile(Panel &panel)
{
if(auto profile=smb::selectedProfile(panel)) smb::openProfile(panel,std::move(*profile),true);
}
void collectSmbConnections(HWND owner)
{
for(auto &panel:panels)
{
if(!panel.smbPending || panel.smbPending->completion.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
continue;
auto pending=std::exchange(panel.smbPending,{});
const auto result=pending->completion.get();
const auto &profile=pending->profile;
if(result.error)
{
auto detail=smb::profileAddress(profile)+L"\r\n\r\n"+smb::errorText(result.error);
if(result.error==ERROR_ACCESS_DENIED || result.error==ERROR_LOGON_FAILURE ||
result.error==ERROR_INVALID_PASSWORD || result.error==ERROR_BAD_USERNAME)
detail+=L"\r\n\r\nUse Sign in to try a different account.";
showFilesNotice(owner,detail.c_str(),L"Could not open SMB connection",{.tone=FilesNoticeTone::warning});
if(&panel==&panels[active]) showFileDetails(panel);
continue;
}
if(result.credentialError)
{
const auto detail=L"Connected, but Windows Credential Manager did not save the account.\r\n\r\n"+
smb::errorText(result.credentialError);
showFilesNotice(owner,detail.c_str(),L"SMB sign in",{.tone=FilesNoticeTone::warning});
}
if(!result.folder.empty()) openOn(panel,result.folder,false,{});
else
{
PanelListing listing{SmbListing{profile.id,profile.target.server}};
listing.rows.emplace_back(L"..",L"..");
for(const auto &share:result.shares) listing.rows.emplace_back(share,L"["+share+L"]");
const auto selectFirst=profile.id!=panel.listing->smb->serverId && !result.shares.empty();
openPanelListing(panel,std::move(listing),selectFirst?fs::path(result.shares.front()):fs::path{});
}
}
}
+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)
{
+25 -5
View File
@@ -48,7 +48,8 @@ Json capabilities(bool write, bool erase, unsigned host)
{
return {{"protocol", 2}, {"hostRevision", host}, {"write", write && host},
{"delete", erase && host}, {"move", write && erase && host},
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0}};
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0},
{"conflictPrompt", host != 0}};
}
fs::path itemPath(const Json &value)
{
@@ -128,6 +129,27 @@ class ClientTransfer
if (!result.at("continue").get<bool>()) throw std::system_error(ERROR_CANCELLED, std::system_category());
guard();
}
bool resolveConflict(const fs::path &path, const Json &incoming, const Json &existing)
{
if (conflict == "skip") return false;
const bool replaceable = directory(incoming) == directory(existing) && !reparse(existing);
if (conflict == "replace" && replaceable) return true;
if (conflict != "ask") throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
if (replaceable && directory(existing)) return true;
sendJson(send, {{"type", "conflict"}, {"path", utf8(path.native())},
{"incoming", incoming}, {"existing", existing}, {"replaceable", replaceable}});
for (;;)
{
const auto answer = Json::parse(receive(256)).at("decision").get<std::string>();
guard();
if (answer == "wait") continue;
if (answer == "skip") return false;
if (answer == "replace" && replaceable) return true;
if (answer == "cancel") throw std::system_error(ERROR_CANCELLED, std::system_category());
throw std::runtime_error("Invalid transfer conflict decision.");
}
}
bool copy(const fs::path &from, const fs::path &to, unsigned depth)
{
if (depth > 256) throw std::runtime_error("The file tree is too deep.");
@@ -139,9 +161,7 @@ class ClientTransfer
if (found)
{
checkFileReply(existing);
if (conflict == "skip") { ++skipped; return false; }
if (conflict != "replace" || directory(original) != directory(existing))
throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
if (!resolveConflict(to, original, existing)) { ++skipped; return false; }
requireRegular(existing);
}
@@ -199,7 +219,7 @@ public:
void run(const fs::path &from, const fs::path &to)
{
if (conflict != "fail" && conflict != "skip" && conflict != "replace")
if (conflict != "fail" && conflict != "skip" && conflict != "replace" && conflict != "ask")
throw std::runtime_error("Unknown conflict policy.");
if (sameHost)
{
+52 -11
View File
@@ -1,15 +1,53 @@
#pragma once
#include "platform.h"
#include <uiautomation.h>
#include <wrl/client.h>
namespace ks
{
inline bool focusedTextBelongsToWindow(IUIAutomation *automation, IUIAutomationElement *focused, HWND target)
{
using Microsoft::WRL::ComPtr;
DWORD process{};
GetWindowThreadProcessId(target, &process);
int focusedProcess{};
if (!process || FAILED(focused->get_CurrentProcessId(&focusedProcess))) return false;
if (process == static_cast<DWORD>(focusedProcess)) return true;
BOOL hasFocus{}, readOnly = TRUE;
ComPtr<IUIAutomationValuePattern> value;
if (FAILED(focused->get_CurrentHasKeyboardFocus(&hasFocus)) || !hasFocus ||
FAILED(focused->GetCurrentPatternAs(UIA_ValuePatternId, IID_PPV_ARGS(&value))) || !value ||
FAILED(value->get_CurrentIsReadOnly(&readOnly)) || readOnly)
return false;
// WebView2 exposes text through a different process. Its accessibility
// ancestors lead back to a native child window of the foreground app.
ComPtr<IUIAutomationTreeWalker> walker;
if (FAILED(automation->get_RawViewWalker(&walker)) || !walker)
return false;
ComPtr<IUIAutomationElement> element = focused;
for (int depth = 0; element && depth < 32; ++depth)
{
UIA_HWND native{};
if (SUCCEEDED(element->get_CurrentNativeWindowHandle(&native)) && native)
{
const auto hwnd = reinterpret_cast<HWND>(native);
return hwnd == target || IsChild(target, hwnd);
}
ComPtr<IUIAutomationElement> parent;
if (FAILED(walker->GetParentElement(element.Get(), &parent))) return false;
element = std::move(parent);
}
return false;
}
// Read-only UI Automation: never select, move the caret, or touch the clipboard.
class PasteProbe
{
IUIAutomation2 *automation{};
IUIAutomationElement *element{};
IUIAutomationTextPattern *pattern{};
HWND targetWindow{};
static std::optional<std::wstring> rangeText(IUIAutomationTextRange *range)
{
@@ -24,7 +62,7 @@ class PasteProbe
public:
std::wstring status = L"not-requested";
std::optional<std::wstring> precedingCharacter;
PasteProbe(bool enabled, HWND target)
PasteProbe(bool enabled, HWND target) : targetWindow(target)
{
if (!enabled)
return;
@@ -36,17 +74,15 @@ class PasteProbe
automation->put_TransactionTimeout(200);
if (FAILED(automation->GetFocusedElement(&element)) || !element)
return;
if (target)
if (target && GetForegroundWindow() != target)
{
DWORD process{};
GetWindowThreadProcessId(target, &process);
int focusedProcess{};
if (!process || FAILED(element->get_CurrentProcessId(&focusedProcess)) ||
process != static_cast<DWORD>(focusedProcess) || GetForegroundWindow() != target)
{
status = L"focused-control-changed";
return;
}
status = L"focused-window-changed";
return;
}
if (target && !focusedTextBelongsToWindow(automation, element, target))
{
status = L"focused-control-outside-target";
return;
}
BOOL password = TRUE;
if (FAILED(element->get_CurrentIsPassword(&password)) || password)
@@ -95,6 +131,11 @@ class PasteProbe
{
if (!pattern)
return {};
if (targetWindow && GetForegroundWindow() != targetWindow)
{
status = L"focused-window-changed";
return {};
}
if (characters <= 0 || characters > 4096)
{
status = L"readback-size-limit";
+6 -4
View File
@@ -676,9 +676,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 +687,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)
{
+1 -1
View File
@@ -75,7 +75,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();
+145 -193
View File
@@ -10,6 +10,7 @@
#include "ui_geometry.h"
#include "diagnostics.h"
#include "google_drive.h"
#include "update.h"
#include <algorithm>
#include <array>
#include <atomic>
@@ -1209,7 +1210,8 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
#ifndef KS_RESIDENT_APP
constexpr int LanguagesPage = 1, ShortcutsPage = 2, ClipboardPage = 3, SnippetsPage = 4, MousePage = 5;
constexpr int ExceptionsPage = 13, PersonalDictionariesPage = 14, WordBoundariesPage = 15, SnippetMacros = 320;
constexpr int CustomReplacementsPage = 16;
constexpr int CustomReplacementsPage = 16, ChatLanguagesPage = 20;
constexpr int ChatContacts = 710, ChatLayouts = 711, ChatProfileStatus = 712, ChatRemoveProfile = 713, ChatSearch = 714;
constexpr int ClipboardExcludedApps = 243, ClipboardAppName = 244, ClipboardAddApp = 245,
ClipboardRemoveApp = 246, ClipboardAppPicker = 247;
constexpr UINT AppWindowPicked = WM_APP + 78;
@@ -1253,6 +1255,7 @@ constexpr struct SettingsSection
{"openbao", L"OpenBao", L"Connect to OpenBao and synchronize your saved settings.", SyncPage},
{"google-drive", L"Google Drive", L"Synchronize settings across PCs or manage manual backups.", SyncPage},
{"ocr", L"Image text recognition", L"Choose Windows OCR or Tesseract. Recognition runs on this computer.", ClipboardPage},
{"chat-languages", L"Languages for a chat", L"Choose which keyboard layouts to cycle through in a chat.", LanguagesPage},
};
constexpr wchar_t SettingsWindowFile[] = L"configurator-window.json";
struct SettingsWindowState
@@ -1352,6 +1355,9 @@ struct SettingsView
SIZE mouseProfileCheckSize{};
unsigned mouseEvents{}, rawMouseEvents{};
bool rawMouseRegistered{};
std::vector<std::wstring> chatKeys;
int chatSelection = -1;
bool updatingChatContacts{};
SnippetView snippets;
HWND clipboardPickerOutline{};
};
@@ -1862,6 +1868,8 @@ void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height)
}
layout.height = fitSettingsColumns(layout, page.first, page.end, available, grid);
const int extra = height * 96 / static_cast<int>(dpi) - layout.height;
if (v.selectedPage == ChatLanguagesPage)
stretchSettingsEditors(layout, page.first, page.end, std::min(extra, 160), {ChatContacts, ChatLayouts}, true);
if (v.selectedPage == SnippetsPage)
stretchSettingsEditors(layout, page.first, page.end, extra, {301, 303}, available < grid.wrapAt);
if (v.selectedPage == MousePage)
@@ -1953,6 +1961,7 @@ void reflowClipboard(HWND pane, WindowLayout &layout, int width, int height)
if (scale(pane, layout.height) > height)
fit(width - GetSystemMetricsForDpi(SM_CXVSCROLL, dpi));
}
void refreshChatLanguages(SettingsView &v);
void selectSettingsPage(SettingsView &v, int selected)
{
if (selected < 0 || selected >= (int)v.pages.size() || selected == v.selectedPage) return;
@@ -1967,6 +1976,7 @@ void selectSettingsPage(SettingsView &v, int selected)
ShowWindow(layout.controls[i].first, SW_HIDE);
}
v.selectedPage = selected;
if (selected == ChatLanguagesPage) refreshChatLanguages(v);
SetWindowTextW(v.heading, settingsSections[selected].name);
SetWindowTextW(v.description, settingsSections[selected].description);
const auto &page = v.pages[selected];
@@ -2273,81 +2283,42 @@ void indexSettingsControl(SettingsView &v, int page, HWND child)
}
v.searchEntries.push_back({page, child, target, std::move(text), aliases});
}
struct ChatLanguagesView
void fillChatLanguages(SettingsView &v)
{
HWND parent{};
SettingsView *settings{};
std::vector<std::wstring> keys;
Settings draft;
int selection = -1;
bool dirty{};
bool updatingList{};
std::wstring search;
};
void collectChatLanguages(HWND w, ChatLanguagesView *v)
{
if (!v->dirty || v->selection < 0) return;
std::vector<std::wstring> cycle;
for (size_t i = 0; i < v->settings->order.size(); ++i)
if (SendDlgItemMessageW(w, 711, LB_GETSEL, i, 0) > 0)
cycle.push_back(v->settings->app->layouts[v->settings->order[i]].id);
if (cycle.empty()) throw std::runtime_error("Select at least one language.");
v->draft.chatCycles[v->keys[v->selection]] = std::move(cycle);
v->dirty = false;
}
void fillChatLanguages(HWND w, ChatLanguagesView *v)
{
int index = v->selection;
EnableWindow(GetDlgItem(w, 711), index >= 0);
EnableWindow(GetDlgItem(w, IDOK), index >= 0);
if (index < 0)
HWND pane = v.viewport;
const bool selected = v.chatSelection >= 0;
EnableWindow(GetDlgItem(pane, ChatLayouts), selected && !v.order.empty());
if (!selected)
{
SendDlgItemMessageW(w, 711, LB_SETSEL, FALSE, -1);
EnableWindow(GetDlgItem(w, 713), FALSE);
value(w, 712, v->keys.empty() ? L"Open a chat, then reopen this dialog to add it." :
L"No contacts match your search.");
SendDlgItemMessageW(pane, ChatLayouts, LB_SETSEL, FALSE, -1);
EnableWindow(GetDlgItem(pane, ChatRemoveProfile), FALSE);
value(pane, ChatProfileStatus, v.chatKeys.empty() ?
L"Open a chat, then return to this page." : L"No matching chat selected.");
return;
}
const auto &draft = v->draft;
auto saved = draft.chatCycles.find(v->keys[index]);
const auto &cycle = saved == draft.chatCycles.end() ? draft.cycle : saved->second;
for (size_t i = 0; i < v->settings->order.size(); ++i)
const auto saved = v.draft.chatCycles.find(v.chatKeys[v.chatSelection]);
const bool hasProfile = saved != v.draft.chatCycles.end();
const auto &cycle = hasProfile ? saved->second : v.draft.cycle;
for (size_t i = 0; i < v.order.size(); ++i)
{
auto &layout = v->settings->app->layouts[v->settings->order[i]];
SendDlgItemMessageW(w, 711, LB_SETSEL,
std::find(cycle.begin(), cycle.end(), layout.id) != cycle.end(), i);
const auto &layout = v.app->layouts[v.order[i]];
SendDlgItemMessageW(pane, ChatLayouts, LB_SETSEL, std::ranges::find(cycle, layout.id) != cycle.end(), i);
}
value(w, 712, saved == draft.chatCycles.end() ? L"No profile yet. Select the languages for this chat." :
L"Chat profile. Select languages, or remove it to use the defaults.");
EnableWindow(GetDlgItem(w, 713), saved != draft.chatCycles.end());
value(pane, ChatProfileStatus, hasProfile ? L"Chat profile" : L"Using the default language cycle");
EnableWindow(GetDlgItem(pane, ChatRemoveProfile), hasProfile);
}
void selectChatRow(HWND list, int index)
void filterChatRows(SettingsView &v, const std::wstring &previous)
{
int row = -1;
if (index >= 0)
{
LVFINDINFOW find{LVFI_PARAM};
find.lParam = index;
row = ListView_FindItem(list, -1, &find);
}
ListView_SetItemState(list, -1, 0, LVIS_SELECTED | LVIS_FOCUSED);
if (row >= 0)
{
ListView_SetItemState(list, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
ListView_EnsureVisible(list, row, FALSE);
}
}
void filterChatRows(HWND w, ChatLanguagesView *v)
{
auto list = GetDlgItem(w, 710);
auto search = lower(v->search);
int selection = -1;
v->updatingList = true;
auto list = GetDlgItem(v.viewport, ChatContacts);
const auto search = lower(value(v.viewport, ChatSearch));
int selectedRow = -1;
v.chatSelection = -1;
v.updatingChatContacts = true;
SendMessageW(list, WM_SETREDRAW, FALSE, 0);
ListView_DeleteAllItems(list);
for (size_t i = 0; i < v->keys.size(); ++i)
for (size_t i = 0; i < v.chatKeys.size(); ++i)
{
const auto &key = v->keys[i];
const auto &key = v.chatKeys[i];
auto contact = key.substr(key.find(L'\n') + 1);
if (lower(contact).find(search) == std::wstring::npos) continue;
auto app = key.starts_with(L"telegram\n") ? L"Telegram" :
@@ -2357,153 +2328,99 @@ void filterChatRows(HWND w, ChatLanguagesView *v)
item.iItem = ListView_GetItemCount(list);
item.pszText = contact.data();
item.lParam = static_cast<LPARAM>(i);
int row = ListView_InsertItem(list, &item);
const int row = ListView_InsertItem(list, &item);
if (row < 0) continue;
ListView_SetItemText(list, row, 1, const_cast<wchar_t *>(app));
if (selection < 0 || static_cast<int>(i) == v->selection) selection = static_cast<int>(i);
if (selectedRow < 0 || key == previous)
{
selectedRow = row;
v.chatSelection = static_cast<int>(i);
}
}
if (selectedRow >= 0)
{
ListView_SetItemState(list, selectedRow, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
ListView_EnsureVisible(list, selectedRow, FALSE);
}
selectChatRow(list, selection);
SendMessageW(list, WM_SETREDRAW, TRUE, 0);
InvalidateRect(list, nullptr, TRUE);
v->updatingList = false;
v->selection = selection;
fillChatLanguages(w, v);
v.updatingChatContacts = false;
fillChatLanguages(v);
}
LRESULT CALLBACK chatLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
std::wstring selectedChatKey(const SettingsView &v)
{
auto *v = (ChatLanguagesView *)GetWindowLongPtrW(w, GWLP_USERDATA);
if (!v) return DefWindowProcW(w, msg, wp, lp);
try
{
if (msg == WM_NOTIFY && !v->updatingList)
{
auto *change = reinterpret_cast<const NMLISTVIEW *>(lp);
if (change->hdr.idFrom == 710 && change->hdr.code == LVN_ITEMCHANGED &&
(change->uNewState & LVIS_SELECTED) && !(change->uOldState & LVIS_SELECTED))
{
int selected = static_cast<int>(change->lParam);
if (selected == v->selection) return 0;
try { collectChatLanguages(w, v); }
catch (...)
{
v->updatingList = true;
selectChatRow(change->hdr.hwndFrom, v->selection);
v->updatingList = false;
throw;
}
v->selection = selected;
fillChatLanguages(w, v);
return 0;
}
}
if (msg == WM_COMMAND)
{
int id = LOWORD(wp);
if (id == 711 && HIWORD(wp) == LBN_SELCHANGE) { v->dirty = true; return 0; }
if (id == 714 && HIWORD(wp) == EN_CHANGE && !v->updatingList)
{
try { collectChatLanguages(w, v); }
catch (...)
{
v->updatingList = true;
value(w, 714, v->search);
v->updatingList = false;
throw;
}
v->search = value(w, 714);
filterChatRows(w, v);
return 0;
}
if (id == IDOK || id == 713)
{
int selected = v->selection;
if (id == IDOK && selected < 0) return 0;
if (selected < 0 || selected >= (int)v->keys.size())
throw std::runtime_error("Open a Telegram or Teams chat, then reopen this dialog.");
if (id == 713)
{
v->draft.chatCycles.erase(v->keys[selected]);
v->dirty = false;
fillChatLanguages(w, v);
return 0;
}
collectChatLanguages(w, v);
validateSettings(v->draft);
v->settings->draft.chatCycles = std::move(v->draft.chatCycles);
DestroyWindow(w);
return 0;
}
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
}
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
if (msg == WM_DPICHANGED)
{
resizeForDpi(w, wp, lp);
auto list = GetDlgItem(w, 710);
ListView_SetColumnWidth(list, 0, scale(w, 442));
ListView_SetColumnWidth(list, 1, scale(w, 140));
return 0;
}
if (msg == WM_NCDESTROY)
{
EnableWindow(v->parent, TRUE);
SetForegroundWindow(v->parent);
disposeFont(w);
delete v;
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
}
}
catch (const std::exception &e) { error(w, e); }
return DefWindowProcW(w, msg, wp, lp);
return v.chatSelection < 0 ? std::wstring{} : v.chatKeys[v.chatSelection];
}
void showChatLanguages(HWND parent, SettingsView *settings)
void refreshChatLanguages(SettingsView &v)
{
const auto previous = selectedChatKey(v);
std::set<std::wstring> keys;
for (const auto &[key, cycle] : settings->draft.chatCycles) keys.insert(key);
struct Context { std::set<std::wstring> &keys; const Settings &settings; } context{keys, settings->draft};
for (const auto &[key, cycle] : v.draft.chatCycles) keys.insert(key);
EnumWindows([](HWND candidate, LPARAM context) -> BOOL
{
if (!IsWindowVisible(candidate)) return TRUE;
auto &data = *(Context *)context;
auto &contacts = *reinterpret_cast<std::set<std::wstring> *>(context);
auto key = lower(processName(candidate)) == L"chrome" ? readChromeChat(candidate) : windowChatKey(candidate);
if (!key.empty()) data.keys.insert(std::move(key));
if (!key.empty()) contacts.insert(std::move(key));
return TRUE;
}, (LPARAM)&context);
}, reinterpret_cast<LPARAM>(&keys));
v.chatKeys.assign(keys.begin(), keys.end());
SendDlgItemMessageW(v.viewport, ChatLayouts, LB_RESETCONTENT, 0, 0);
for (int index : v.order)
SendDlgItemMessageW(v.viewport, ChatLayouts, LB_ADDSTRING, 0,
reinterpret_cast<LPARAM>(v.app->layouts[index].name.c_str()));
filterChatRows(v, previous);
}
void editChatLanguages(SettingsView &v)
{
if (v.chatSelection < 0) return;
std::vector<std::wstring> cycle;
for (size_t i = 0; i < v.order.size(); ++i)
if (SendDlgItemMessageW(v.viewport, ChatLayouts, LB_GETSEL, i, 0) > 0)
cycle.push_back(v.app->layouts[v.order[i]].id);
const bool hasLayouts = !cycle.empty();
if (hasLayouts) v.draft.chatCycles[v.chatKeys[v.chatSelection]] = std::move(cycle);
fillChatLanguages(v);
if (!hasLayouts) value(v.viewport, ChatProfileStatus, L"Select at least one layout, or remove the profile.");
}
void sizeChatContactColumns(HWND list)
{
RECT bounds{};
GetClientRect(list, &bounds);
const int appWidth = scale(list, 140);
const int scrollWidth = GetSystemMetricsForDpi(SM_CXVSCROLL, GetDpiForWindow(list));
ListView_SetColumnWidth(list, 0, std::max(0L, bounds.right - appWidth - scrollWidth));
ListView_SetColumnWidth(list, 1, appWidth);
}
LRESULT CALLBACK chatContactsProc(HWND list, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
const auto result = DefSubclassProc(list, msg, wp, lp);
if (msg == WM_SIZE) sizeChatContactColumns(list);
return result;
}
void createChatLanguages(HWND pane)
{
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES};
InitCommonControlsEx(&controls);
HWND w = makeWindow(*settings->app, L"KSwitcher.ChatLanguages", L"Languages for a chat", chatLanguagesProc, 640, 524);
auto *v = new ChatLanguagesView{parent, settings, {keys.begin(), keys.end()}};
v->draft = settings->draft;
v->updatingList = true;
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
label(w, L"&Find contact", 18, 19, 106);
edit(w, 714, 130, 14, 492);
auto list = control(w, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL |
LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 710, 18, 48, 604, 136);
label(pane, L"&Find contact", 24, 68, 660);
edit(pane, ChatSearch, 24, 94, 660);
const auto list = control(pane, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL |
LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, ChatContacts, 24, 126, 660, 106);
ListView_SetExtendedListViewStyle(list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP);
for (const auto &[title, width] : {std::pair{L"Contact", 442}, std::pair{L"App", 140}})
for (const auto *title : {L"Contact", L"App"})
{
LVCOLUMNW column{LVCF_TEXT | LVCF_WIDTH};
LVCOLUMNW column{LVCF_TEXT};
column.pszText = const_cast<wchar_t *>(title);
column.cx = scale(w, width);
ListView_InsertColumn(list, Header_GetItemCount(ListView_GetHeader(list)), &column);
}
control(w, L"STATIC", L"Open a chat, then reopen this dialog to add it.", 0, 712, 18, 194, 604, 26);
label(w, L"Click languages to include (saved in the order shown)", 18, 228, 604);
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT | WS_BORDER,
711, 18, 256, 604, 132);
for (int i : settings->order)
SendDlgItemMessageW(w, 711, LB_ADDSTRING, 0, (LPARAM)settings->app->layouts[i].name.c_str());
label(w, L"Applies to Alt+Shift, Win+Space and KSwitcher Next layout.", 18, 402, 604);
label(w, L"Switch chats freely. Use languages, then Save settings.", 18, 430, 604);
button(w, L"&Remove profile", 713, 18, 476, 170);
button(w, L"&Use languages", IDOK, 300, 476, 170);
button(w, L"&Cancel", IDCANCEL, 486, 476, 136);
filterChatRows(w, v);
EnableWindow(parent, FALSE);
showRequestedWindow(w);
SetFocus(GetDlgItem(w, 714));
SetWindowSubclass(list, chatContactsProc, 1, 0);
sizeChatContactColumns(list);
control(pane, L"STATIC", L"", 0, ChatProfileStatus, 24, 242, 660, 24);
label(pane, L"Select layouts to include, in the order shown.", 24, 270, 660);
control(pane, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT |
WS_BORDER, ChatLayouts, 24, 296, 660, 80);
button(pane, L"&Remove profile", ChatRemoveProfile, 24, 388, 170);
label(pane, L"Applies to Alt+Shift, Win+Space, Win+Shift+Space and KSwitcher Next layout.", 24, 424, 660);
}
#include "ui_app_languages.inl"
#include "ui_mouse_buttons.inl"
@@ -2646,6 +2563,7 @@ void fillSettings(HWND root, SettingsView *v)
v->order.push_back(i);
v->selection = 0;
fillLayouts(v);
if (v->selectedPage == ChatLanguagesPage) refreshChatLanguages(*v);
fillMouseProfiles(root, *v);
fillCorrectionOptions(w, s);
v->filling = false;
@@ -3056,6 +2974,20 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (LOWORD(wp) != WA_INACTIVE) updateSettingsState(w, v);
break;
case WM_NOTIFY:
if (reinterpret_cast<const NMHDR *>(lp)->idFrom == ChatContacts &&
reinterpret_cast<const NMHDR *>(lp)->code == LVN_ITEMCHANGED)
{
const auto &change = *reinterpret_cast<const NMLISTVIEW *>(lp);
if (!v->updatingChatContacts && ((change.uNewState ^ change.uOldState) & LVIS_SELECTED))
{
if (change.uNewState & LVIS_SELECTED)
v->chatSelection = static_cast<int>(change.lParam);
else if (!ListView_GetSelectedCount(change.hdr.hwndFrom))
v->chatSelection = -1;
fillChatLanguages(*v);
}
return 0;
}
if (reinterpret_cast<const NMHDR *>(lp)->idFrom == SettingsNavigation)
{
const auto code = reinterpret_cast<const NMHDR *>(lp)->code;
@@ -3188,7 +3120,25 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
if (id == 263) { collectLayout(v); showAppLanguages(w, v); return 0; }
if (handleMouseBindings(w, *v, wp)) return 0;
if (id == 259) { collectLayout(v); showChatLanguages(w, v); return 0; }
if (id == ChatSearch && HIWORD(wp) == EN_CHANGE)
{
if (v->ready) filterChatRows(*v, selectedChatKey(*v));
return 0;
}
if (id == ChatLayouts && HIWORD(wp) == LBN_SELCHANGE)
{
editChatLanguages(*v);
return 0;
}
if (id == ChatRemoveProfile && HIWORD(wp) == BN_CLICKED)
{
if (v->chatSelection >= 0)
{
v->draft.chatCycles.erase(v->chatKeys[v->chatSelection]);
fillChatLanguages(*v);
}
return 0;
}
if (id == 230)
{
collectLayout(v);
@@ -3984,8 +3934,7 @@ void showSettings(App &app, bool visible)
hotkeyEdit(app, pane, 231, 454, 234, 230);
label(pane, L"Backspace / Delete clears it", 454, 270, 230);
button(pane, L"Re&fresh layouts", 253, 454, 322, 230);
button(pane, L"Languages for a &chat...", 259, 24, 378, 230);
button(pane, L"Languages for &applications...", 263, 272, 378, 300);
button(pane, L"Languages for &applications...", 263, 24, 378, 300);
page();
settingsGroupLabel(pane, L"Keyboard shortcuts", 24, 68);
@@ -4110,6 +4059,9 @@ void showSettings(App &app, bool visible)
createOcrSettings(pane);
page();
createChatLanguages(pane);
page();
v->splitter = control(w, L"STATIC", L"Resize navigation pane", SS_NOTIFY | WS_TABSTOP,
SettingsSplitter, 0, 0, 0, 0);
SetWindowSubclass(v->splitter, settingsSplitterProc, 1, reinterpret_cast<DWORD_PTR>(v));
+141 -25
View File
@@ -1,13 +1,16 @@
namespace
{
constexpr int HelpSearch = 810, HelpTopics = 811, HelpTitle = 812, HelpBody = 813;
constexpr int HelpSearch = 810, HelpTopics = 811, HelpTitle = 812, HelpBody = 813, HelpReleaseLink = 814;
constexpr int HelpRail = 268, HelpFooter = 56, HelpHeader = 66;
constexpr int ShortcutTopic = 0, GuideRoot = 1, GettingStarted = 2;
enum class HelpPage { shortcuts, guide, releases };
struct HelpTopic
{
std::wstring title, text;
int parent = -1;
std::wstring releaseVersion;
};
struct HelpView
@@ -19,6 +22,8 @@ struct HelpView
UINT dpi{};
int selected{};
bool rebuilding{};
bool releases{};
bool ukrainian{};
};
std::wstring helpShortcuts(const App &app)
@@ -65,16 +70,19 @@ std::wstring helpText(std::wstring line)
return line;
}
std::wstring helpResourceText(HINSTANCE instance, int resource)
{
HRSRC found = FindResourceW(instance, MAKEINTRESOURCEW(resource), RT_RCDATA);
HGLOBAL loaded = found ? LoadResource(instance, found) : nullptr;
const auto *bytes = loaded ? static_cast<const char *>(LockResource(loaded)) : nullptr;
return bytes ? wide(std::string(bytes, SizeofResource(instance, found))) : std::wstring{};
}
void addHelpDocument(HelpView &view, int resource, std::wstring title, std::wstring introduction)
{
const int root = static_cast<int>(view.topics.size());
view.topics.push_back({std::move(title), std::move(introduction)});
const auto instance = view.app->instance;
HRSRC found = FindResourceW(instance, MAKEINTRESOURCEW(resource), RT_RCDATA);
HGLOBAL loaded = found ? LoadResource(instance, found) : nullptr;
const auto *bytes = loaded ? static_cast<const char *>(LockResource(loaded)) : nullptr;
if (!bytes) return;
std::wistringstream input(wide(std::string(bytes, SizeofResource(instance, found))));
std::wistringstream input(helpResourceText(view.app->instance, resource));
std::array<int, 7> ancestors;
ancestors.fill(root);
int topic = root;
@@ -106,12 +114,74 @@ void addHelpDocument(HelpView &view, int resource, std::wstring title, std::wstr
}
}
int addReleaseTopics(HelpView &view, LANGID language)
{
view.topics.push_back({whatsNewTitle(language), view.ukrainian
? L"Виберіть версію, щоб переглянути зміни."
: L"Select a version to read its release notes."});
std::wistringstream input(helpResourceText(view.app->instance, IDR_HELP_RELEASES));
constexpr std::wstring_view ukrainianMarker = L"**Українською.**";
std::wstring version, english, ukrainian;
bool translated = false, withdrawn = false;
int installed = 0;
const auto add = [&]
{
if (version.empty()) return;
auto &text = view.ukrainian && !ukrainian.empty() ? ukrainian : english;
const auto end = text.find_last_not_of(L" \r\n\t");
if (end == std::wstring::npos) return;
text.resize(end + 1);
if (version == AppVersion) installed = static_cast<int>(view.topics.size());
auto title = L"v" + version;
if (withdrawn) title += view.ukrainian ? L" (відкликано)" : L" (withdrawn)";
view.topics.push_back({std::move(title), std::move(text), 0, withdrawn ? std::wstring{} : version});
};
for (std::wstring line; std::getline(input, line);)
{
if (line.ends_with(L'\r')) line.pop_back();
if (line.starts_with(L"## v"))
{
add();
const auto end = line.find(L' ', 4);
version = line.substr(4, end == line.npos ? line.npos : end - 4);
if (version.empty() || version.find_first_not_of(L"0123456789.") != version.npos)
version.clear();
english.clear();
ukrainian.clear();
translated = false;
withdrawn = line.find(L"(withdrawn") != line.npos;
continue;
}
if (version.empty()) continue;
if (line.starts_with(ukrainianMarker))
{
translated = true;
const auto start = line.find_first_not_of(L" \t", ukrainianMarker.size());
line = start == line.npos ? std::wstring{} : line.substr(start);
}
auto &text = translated ? ukrainian : english;
if (text.empty() && line.empty()) continue;
if (line.starts_with(L"- ")) line.replace(0, 1, L"•");
text += helpText(std::move(line)) + L"\r\n";
}
add();
if (!installed)
{
installed = static_cast<int>(view.topics.size());
view.topics.push_back({std::wstring(L"v") + AppVersion, view.ukrainian
? L"Нотатки для цієї збірки ще недоступні. Попередні випуски можна переглянути у списку."
: L"Notes for this build are unavailable. Earlier releases are in the list.", 0});
}
return installed;
}
void showHelpTopic(HWND w, HelpView &view, int index)
{
view.selected = index;
const auto &topic = view.topics[index];
value(w, HelpTitle, topic.title);
value(w, HelpBody, index == ShortcutTopic ? helpShortcuts(*view.app) : topic.text);
value(w, HelpBody, !view.releases && index == ShortcutTopic ? helpShortcuts(*view.app) : topic.text);
ShowWindow(GetDlgItem(w, HelpReleaseLink), topic.releaseVersion.empty() ? SW_HIDE : SW_SHOWNA);
SendDlgItemMessageW(w, HelpBody, EM_SETSEL, 0, 0);
SendDlgItemMessageW(w, HelpBody, EM_SCROLLCARET, 0, 0);
}
@@ -122,6 +192,7 @@ void fillHelpTopics(HWND w, HelpView &view)
const auto query = lower(value(w, HelpSearch));
std::vector<HTREEITEM> nodes(view.topics.size());
HTREEITEM selected{};
int selectedIndex{};
view.rebuilding = true;
SendMessageW(tree, WM_SETREDRAW, FALSE, 0);
TreeView_DeleteAllItems(tree);
@@ -137,17 +208,27 @@ void fillHelpTopics(HWND w, HelpView &view)
node.item.pszText = const_cast<wchar_t *>(topic.title.c_str());
node.item.lParam = static_cast<LPARAM>(i);
nodes[i] = TreeView_InsertItem(tree, &node);
if (!selected || static_cast<int>(i) == view.selected) selected = nodes[i];
if (nodes[i] && (!selected || static_cast<int>(i) == view.selected))
{
selected = nodes[i];
selectedIndex = static_cast<int>(i);
}
}
if (query.empty()) TreeView_Expand(tree, nodes[GuideRoot], TVE_EXPAND);
if (query.empty()) TreeView_Expand(tree, nodes[view.releases ? 0 : GuideRoot], TVE_EXPAND);
SendMessageW(tree, WM_SETREDRAW, TRUE, 0);
view.rebuilding = false;
if (selected) TreeView_SelectItem(tree, selected);
if (selected)
{
TreeView_SelectItem(tree, selected);
showHelpTopic(w, view, selectedIndex);
}
else
{
value(w, HelpTitle, L"No matching topics");
value(w, HelpBody, L"Try another word or clear the search to see all topics.");
value(w, HelpTitle, view.ukrainian ? L"Нічого не знайдено" : L"No matching topics");
value(w, HelpBody, view.ukrainian ? L"Спробуйте інше слово або очистьте пошук." :
L"Try another word or clear the search to see all topics.");
ShowWindow(GetDlgItem(w, HelpReleaseLink), SW_HIDE);
}
view.rebuilding = false;
InvalidateRect(tree, nullptr, TRUE);
}
@@ -169,6 +250,7 @@ void layoutHelp(HWND w, HelpView &view)
place(HelpTitle, content, scale(w, 13), r.right - pad, scale(w, 55));
place(HelpBody, content, header + pad, r.right - pad, footer - scale(w, 10));
place(IDCANCEL, r.right - pad - scale(w, 100), footer + scale(w, 14), r.right - pad, r.bottom - scale(w, 14));
place(HelpReleaseLink, content, footer + scale(w, 14), content + scale(w, 170), r.bottom - scale(w, 14));
const auto dpi = GetDpiForWindow(w);
if (view.dpi != dpi || !view.heading)
{
@@ -252,6 +334,18 @@ LRESULT CALLBACK helpProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
case WM_COMMAND:
if (LOWORD(wp) == HelpSearch && HIWORD(wp) == EN_CHANGE) fillHelpTopics(w, *view);
if (LOWORD(wp) == HelpReleaseLink && IsWindowVisible(GetDlgItem(w, HelpReleaseLink)))
{
const auto &version = view->topics[view->selected].releaseVersion;
constexpr auto repository = L"https://gitea.hrynco.com/hrynco/hrynco-kswitcher";
// Older release pages can be superseded while the tagged notes remain available.
const auto path = version == AppVersion ? L"/releases/tag/release-v" + version
: L"/src/tag/release-v" + version + L"/Release/README.md";
const auto address = repository + path;
if (reinterpret_cast<INT_PTR>(ShellExecuteW(w, L"open", address.c_str(), nullptr, nullptr, SW_SHOWNORMAL)) <= 32)
MessageBoxW(w, view->ukrainian ? L"Не вдалося відкрити сторінку випуску." :
L"Could not open the release page.", view->ukrainian ? L"Що нового" : L"What's new", MB_OK | MB_ICONWARNING);
}
if (LOWORD(wp) == IDCANCEL) DestroyWindow(w);
return 0;
case WM_NCDESTROY:
@@ -265,7 +359,7 @@ LRESULT CALLBACK helpProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
return DefWindowProcW(w, msg, wp, lp);
}
void openHelp(App &app, int topic)
void openHelp(App &app, HelpPage page, LANGID language = LANG_ENGLISH)
{
if (!app.helpWindow)
{
@@ -273,15 +367,8 @@ void openHelp(App &app, int topic)
app.helpWindow = w;
setWindowTaskbarIdentity(w, IDI_KSWITCHER_HELP, L"HrynCo.KSwitcher.Help");
auto &view = *reinterpret_cast<HelpView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
view.topics = {{L"Keyboard shortcuts", L"Current shortcut bindings and keyboard controls"}};
addHelpDocument(view, IDR_HELP_GUIDE, L"Using KSwitcher", L"Choose an area to learn how to use it.\r\n");
addHelpDocument(view, IDR_HELP_MANUAL, L"KSwitcher manual", L"Detailed documentation for the main application.\r\n");
addHelpDocument(view, IDR_HELP_FILES, L"Files manual (Українська)", L"Докладний посібник з KSwitcher Files.\r\n");
addHelpDocument(view, IDR_HELP_COMPUTERS, L"Paired computers manual", L"Detailed documentation for discovery, pairing and LAN features.\r\n");
auto search = edit(w, HelpSearch, 0, 0, 0);
SendMessageW(search, EM_SETLIMITTEXT, 120, 0);
SendMessageW(search, EM_SETCUEBANNER, TRUE, reinterpret_cast<LPARAM>(L"Search help"));
INITCOMMONCONTROLSEX classes{sizeof(classes), ICC_TREEVIEW_CLASSES};
InitCommonControlsEx(&classes);
control(w, WC_TREEVIEWW, L"Help topics", WS_TABSTOP | TVS_HASBUTTONS | TVS_LINESATROOT |
@@ -289,13 +376,37 @@ void openHelp(App &app, int topic)
control(w, L"STATIC", L"", SS_CENTERIMAGE | SS_ENDELLIPSIS, HelpTitle, 0, 0, 0, 0);
auto body = edit(w, HelpBody, 0, 0, 0, 0, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL);
SendMessageW(body, EM_SETLIMITTEXT, 1024 * 1024, 0);
button(w, L"Open in Gitea", HelpReleaseLink, 0, 0);
button(w, L"&Close", IDCANCEL, 0, 0);
SendMessageW(w, WM_SYSCOLORCHANGE, 0, 0);
layoutHelp(w, view);
}
const auto w = app.helpWindow;
auto &view = *reinterpret_cast<HelpView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
view.selected = topic < static_cast<int>(view.topics.size()) ? topic : GuideRoot;
const bool releases = page == HelpPage::releases;
const bool ukrainian = releases && PRIMARYLANGID(language) == LANG_UKRAINIAN;
int topic = page == HelpPage::shortcuts ? ShortcutTopic : GettingStarted;
if (releases || view.topics.empty() || view.releases)
{
view.topics.clear();
view.releases = releases;
view.ukrainian = ukrainian;
if (releases) topic = addReleaseTopics(view, language);
else
{
view.topics = {{L"Keyboard shortcuts", L"Current shortcut bindings and keyboard controls"}};
addHelpDocument(view, IDR_HELP_GUIDE, L"Using KSwitcher", L"Choose an area to learn how to use it.\r\n");
addHelpDocument(view, IDR_HELP_MANUAL, L"KSwitcher manual", L"Detailed documentation for the main application.\r\n");
addHelpDocument(view, IDR_HELP_FILES, L"Files manual (Українська)", L"Докладний посібник з KSwitcher Files.\r\n");
addHelpDocument(view, IDR_HELP_COMPUTERS, L"Paired computers manual", L"Detailed documentation for discovery, pairing and LAN features.\r\n");
}
}
SetWindowTextW(w, releases ? whatsNewTitle(language) : L"KSwitcher Help");
value(w, IDCANCEL, ukrainian ? L"&Закрити" : L"&Close");
value(w, HelpReleaseLink, ukrainian ? L"Відкрити в Gitea" : L"Open in Gitea");
const auto *searchHint = ukrainian ? L"Пошук випусків" : releases ? L"Search releases" : L"Search help";
SendDlgItemMessageW(w, HelpSearch, EM_SETCUEBANNER, TRUE, reinterpret_cast<LPARAM>(searchHint));
view.selected = topic;
if (value(w, HelpSearch).empty()) fillHelpTopics(w, view);
else value(w, HelpSearch, L"");
if (IsIconic(w)) ShowWindow(w, SW_RESTORE);
@@ -305,5 +416,10 @@ void openHelp(App &app, int topic)
}
} // namespace
void showHelp(App &app) { openHelp(app, GettingStarted); }
void showShortcuts(App &app) { openHelp(app, ShortcutTopic); }
void showHelp(App &app) { openHelp(app, HelpPage::guide); }
void showShortcuts(App &app) { openHelp(app, HelpPage::shortcuts); }
const wchar_t *whatsNewTitle(LANGID language)
{
return PRIMARYLANGID(language) == LANG_UKRAINIAN ? L"Що нового" : L"What's new";
}
void showWhatsNew(App &app, LANGID language) { openHelp(app, HelpPage::releases, language); }
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.8.0";
inline constexpr wchar_t AppVersion[] = L"0.8.8";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+62 -45
View File
@@ -854,13 +854,16 @@ int main(int argc,char **argv)
SendMessageW(GetDlgItem(correction, 414), BM_CLICK, 0, 0);
require(!saveEnabled(), "reverting an inline correction edit disables Save");
HWND navigation = settingsNavigation(parent);
constexpr int sections = 20;
constexpr int chatLanguagesPage = 20;
constexpr int sections = 21;
require(navigation && TreeView_GetCount(navigation) == sections &&
TreeView_GetParent(navigation, settingsSection(navigation, 10)) == settingsSection(navigation, 7) &&
TreeView_GetParent(navigation, settingsSection(navigation, 11)) == settingsSection(navigation, 0),
"correction and computer settings are nested under their sections");
require(TreeView_GetParent(navigation, settingsSection(navigation, 19)) == settingsSection(navigation, 3),
"image text recognition is nested under Clipboard");
require(TreeView_GetParent(navigation, settingsSection(navigation, chatLanguagesPage)) ==
settingsSection(navigation, 1), "chat profiles appear under Languages");
for (int section = 12; section <= 16; ++section)
require(TreeView_GetParent(navigation, settingsSection(navigation, section)) == settingsSection(navigation, 11),
"each correction subsection belongs to the correction branch");
@@ -1124,44 +1127,51 @@ int main(int argc,char **argv)
"search reveals the embedded OpenBao page");
SetWindowTextW(search, L"");
selectSettingsPage(parent, 1);
require(!saveEnabled(),"changing sections leaves Settings clean");
SendMessageW(parent, WM_COMMAND, 259, 0);
HWND dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr);
require(dialog && !IsWindowEnabled(parent), "chat dialog opens with disabled parent");
auto findFixtureChat = [&](HWND chatDialog) {
SetDlgItemTextW(chatDialog, 714, L"! fIXTURE CHAT");
HWND list = GetDlgItem(chatDialog, 710);
require(!saveEnabled() && !GetDlgItem(pane, 259), "Languages uses the tree to open chat profiles");
selectSettingsPage(parent, chatLanguagesPage);
constexpr int contactsId = 710, layoutsId = 711, removeProfileId = 713, searchContactsId = 714;
require(IsWindowVisible(GetDlgItem(pane, contactsId)) && IsWindowEnabled(parent) &&
!findTestWindow(L"KSwitcher.ChatLanguages", nullptr), "chat profiles open within Settings");
auto findFixtureChat = [&] {
const auto chatPage = settingsViewport(parent);
SetDlgItemTextW(chatPage, searchContactsId, L"! fIXTURE CHAT");
const auto list = GetDlgItem(chatPage, contactsId);
require(ListView_GetItemCount(list) == 1, "case-insensitive contact search finds saved chat");
wchar_t appName[32]{};
ListView_GetItemText(list, 0, 1, appName, std::size(appName));
require(std::wstring(appName) == L"Telegram", "chat list shows the source app separately");
};
SetDlgItemTextW(dialog, 714, L"No matching fixture 8031");
require(ListView_GetItemCount(GetDlgItem(dialog, 710)) == 0 &&
!IsWindowEnabled(GetDlgItem(dialog, IDOK)), "empty search results disable profile actions");
findFixtureChat(dialog);
require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "saved single language selected");
RedrawWindow(dialog, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
RECT rect{}; GetClientRect(dialog, &rect);
HDC dc = GetDC(dialog);
auto selectChatLayouts = [&](bool select) {
const auto chatPage = settingsViewport(parent);
SendDlgItemMessageW(chatPage, layoutsId, LB_SETSEL, select, -1);
SendMessageW(chatPage, WM_COMMAND, MAKEWPARAM(layoutsId, LBN_SELCHANGE), 0);
};
SetDlgItemTextW(pane, searchContactsId, L"No matching fixture 8031");
require(ListView_GetItemCount(GetDlgItem(pane, contactsId)) == 0 &&
!IsWindowEnabled(GetDlgItem(pane, layoutsId)) &&
!IsWindowEnabled(GetDlgItem(pane, removeProfileId)), "empty search disables profile editing");
findFixtureChat();
require(SendDlgItemMessageW(pane, layoutsId, LB_GETSELCOUNT, 0, 0) == 1, "saved single language selected");
selectChatLayouts(false);
require(SendDlgItemMessageW(pane, layoutsId, LB_GETSELCOUNT, 0, 0) == 1 && !saveEnabled(),
"deselecting the last layout keeps the profile");
findFixtureChat();
RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
RECT rect{};
GetClientRect(parent, &rect);
HDC dc = GetDC(parent);
auto clip = ks::screenshotClip(dc, rect.right, rect.bottom, {});
ReleaseDC(dialog, dc);
ReleaseDC(parent, dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"chat-languages.png",
ks::encodePng(ks::decodeImage(clip)));
SendDlgItemMessageW(dialog, 711, LB_SETSEL, TRUE, -1);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(711, LBN_SELCHANGE), 0);
SendMessageW(dialog, WM_COMMAND, IDCANCEL, 0);
require(!IsWindow(dialog) && IsWindowEnabled(parent), "cancel closes dialog");
require(!saveEnabled(),"cancelled chat edits do not enable Save");
SendMessageW(parent, WM_COMMAND, 259, 0);
dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr);
findFixtureChat(dialog);
require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "cancel discards language edits");
SendDlgItemMessageW(dialog, 711, LB_SETSEL, TRUE, -1);
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(711, LBN_SELCHANGE), 0);
SendMessageW(dialog, WM_COMMAND, IDOK, 0);
require(!IsWindow(dialog) && IsWindowEnabled(parent), "profile applies to settings draft");
require(saveEnabled() == (app.layouts.size()>1),"accepted chat edits refresh Save immediately");
selectChatLayouts(true);
require(saveEnabled() == (app.layouts.size() > 1) && saveEnabled() == applyEnabled(),
"editing a profile immediately refreshes Apply and Save");
require(app.settings.chatCycles.at(key).size() == 1, "inline editing leaves saved settings untouched");
selectSettingsPage(parent, 1);
selectSettingsPage(parent, chatLanguagesPage);
require(SendDlgItemMessageW(pane, layoutsId, LB_GETSELCOUNT, 0, 0) == static_cast<LRESULT>(app.layouts.size()),
"profile edits survive navigating away and returning");
selectSettingsPage(parent, 16);
SetDlgItemTextW(correction, 412, L"Релізик\r\nрелізик, словечко");
SetDlgItemTextW(correction, 416, L" HeLo = Hello\r\n");
@@ -1174,26 +1184,33 @@ int main(int argc,char **argv)
ks::showSettings(app);
parent = app.settingsWindow;
require(!saveEnabled(),"reopened saved Settings is clean");
SendMessageW(parent, WM_COMMAND, 259, 0);
dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr);
findFixtureChat(dialog);
SendMessageW(dialog, WM_COMMAND, 713, 0);
require(IsWindow(dialog), "chat reset keeps dialog open");
SendMessageW(dialog, WM_COMMAND, IDOK, 0);
require(saveEnabled() && status().find(L"Unsaved settings")==0,"removing child profile immediately marks parent dirty");
RedrawWindow(parent,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
GetClientRect(parent,&rect); dc=GetDC(parent);
clip=ks::screenshotClip(dc,rect.right,rect.bottom,{}); ReleaseDC(parent,dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"settings-unsaved.png",
selectSettingsPage(parent, chatLanguagesPage);
findFixtureChat();
const auto chatPage = settingsViewport(parent);
require(SendDlgItemMessageW(chatPage, layoutsId, LB_GETSELCOUNT, 0, 0) ==
static_cast<LRESULT>(app.layouts.size()), "reopening shows the saved profile");
SendMessageW(GetDlgItem(chatPage, removeProfileId), BM_CLICK, 0, 0);
require(saveEnabled() && applyEnabled() && status().starts_with(L"Unsaved settings"),
"removing a profile immediately marks Settings dirty");
RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
GetClientRect(parent, &rect);
dc = GetDC(parent);
clip = ks::screenshotClip(dc, rect.right, rect.bottom, {});
ReleaseDC(parent, dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"settings-unsaved.png",
ks::encodePng(ks::decodeImage(clip)));
SendMessageW(parent, WM_COMMAND, IDOK, 0);
require(!app.settings.chatCycles.contains(key), "remove profile restores default");
SendMessageW(parent, WM_COMMAND, SettingsApply, 0);
require(IsWindow(parent) && !saveEnabled() && !applyEnabled() &&
!app.settings.chatCycles.contains(key) &&
!ks::loadSettings(root / L"settings.json", app.layouts).chatCycles.contains(key),
"Apply restores the default, saves the removal and keeps Settings open");
SendMessageW(parent, WM_COMMAND, IDCANCEL, 0);
// Existing shared sets become independent application drafts on edit.
app.settings.appLanguageSets[L"Legacy shared"] = {{app.layouts[0].id}, {L"Codex.exe", L"notepad"}};
ks::showSettings(app);
parent = app.settingsWindow;
SendMessageW(parent, WM_COMMAND, 263, 0);
dialog = findTestWindow(L"KSwitcher.AppLanguages", nullptr);
HWND dialog = findTestWindow(L"KSwitcher.AppLanguages", nullptr);
require(dialog && !IsWindowEnabled(parent), "application language editor opens");
auto selectApp = [&](const wchar_t *name) {
int index = (int)SendDlgItemMessageW(dialog, 720, LB_FINDSTRINGEXACT, -1, (LPARAM)name);
+3
View File
@@ -236,6 +236,7 @@ $extension = ".ksfiles$unique"
$progId = "KSwitcher.Files.Test.$unique"
$saved = @{}
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
'LeftPanelMode', 'RightPanelMode', 'LeftViewOrder', 'RightViewOrder', 'AppearanceMode',
'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement', 'FontPoints'
$process = $null
$trace = $null
@@ -275,6 +276,8 @@ try {
$profile.SetValue('RightPath', $rightDir)
foreach ($name in 'LeftCursor', 'RightCursor') { $profile.DeleteValue($name, $false) }
foreach ($name in 'LeftWide', 'RightWide', 'ShowDetails') { $profile.SetValue($name, 1) }
foreach ($name in 'LeftPanelMode', 'RightPanelMode') { $profile.SetValue($name, 1, 'DWord') }
foreach ($name in 'LeftViewOrder', 'RightViewOrder', 'AppearanceMode') { $profile.SetValue($name, 0, 'DWord') }
$profile.SetValue('StatusFields', 3)
if($TerminalOnly){
+35 -2
View File
@@ -48,8 +48,41 @@ function Wait-For([string]$Name, [scriptblock]$Condition) {
throw "Timed out waiting for $Name."
}
function Invoke-FilesCommand([IntPtr]$Window, [string]$LabelPattern) {
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr]132, [IntPtr]::Zero)
function Read-FilesList([IntPtr]$List) {
$count = [FilesCommandsUi]::Send($List, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
for ($row = 0; $row -lt $count; ++$row) {
$label = [Text.StringBuilder]::new(32768)
if ([FilesCommandsUi]::Read($List, 393, [IntPtr]$row, $label).ToInt64() -lt 0) { break }
$label.ToString()
}
}
function Select-FilesListRow([IntPtr]$List, [string]$Label) {
$selection = [array]::IndexOf(@(Read-FilesList $List), $Label)
if ($selection -lt 0) { throw "Missing row '$Label'." }
[void][FilesCommandsUi]::Send($List, 390, [IntPtr]$selection, [IntPtr]::Zero)
}
function Open-FilesSource([IntPtr]$Window, [int]$Side, [string]$Source) {
$menu = if ($Side -eq 0) { 130 } else { 134 }
$picker = [FilesCommandsUi]::GetDlgItem($Window, 121)
[void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr]$menu, [IntPtr]::Zero)
$entry = Wait-For "Change drive in panel ${Side}'s menu" {
if ([FilesCommandsUi]::IsWindowVisible($picker)) {
Read-FilesList $picker | Where-Object { $_ -like '*Change drive*' } | Select-Object -First 1
}
}
Select-FilesListRow $picker $entry
[void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr](0x20000 + 121), $picker)
[void](Wait-For "$Source in panel ${Side}'s source picker" {
[FilesCommandsUi]::IsWindowVisible($picker) -and (Read-FilesList $picker) -contains $Source
})
Select-FilesListRow $picker $Source
[void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr](0x20000 + 121), $picker)
}
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;
}
}
+382
View File
@@ -0,0 +1,382 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$Screenshot,
[switch]$DrivePickerOnly,
[string]$DialogScreenshotDirectory
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
Add-Type @'
using System;
using System.Runtime.InteropServices;
public static class LavenderWindow {
[StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; }
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr window);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetLastActivePopup(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint command);
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(0x12, 0, 0, UIntPtr.Zero);
keybd_event(0x12, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint message, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint message, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)]
public static extern IntPtr SendText(IntPtr window, uint message, IntPtr w, string text);
[DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr window, int attribute, out Rect rect, int size);
}
'@
function Wait-Until([scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 100; $attempt++) {
if (& $Condition) { return }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for $Condition"
}
function Get-Bounds($Window) {
$bounds = [LavenderWindow+Rect]::new()
if (![LavenderWindow]::GetWindowRect($Window, [ref]$bounds)) { throw 'Missing window or control.' }
$bounds
}
function Read-Window($Bounds) {
$image = [Drawing.Bitmap]::new(($Bounds.Right - $Bounds.Left), ($Bounds.Bottom - $Bounds.Top))
$graphics = [Drawing.Graphics]::FromImage($image)
try { $graphics.CopyFromScreen($Bounds.Left, $Bounds.Top, 0, 0, $image.Size) }
finally { $graphics.Dispose() }
$image
}
function Test-Pixel($Image, $Bounds, $X, $Y, $Expected, $Description) {
$actual = $Image.GetPixel($X - $Bounds.Left, $Y - $Bounds.Top)
if ($actual.ToArgb() -ne [Drawing.ColorTranslator]::FromHtml($Expected).ToArgb()) {
throw "$Description expected $Expected, got $($actual.Name)."
}
}
function Test-PathBar($Image, $Bounds, $Path, [double]$Scale, [string]$Name) {
$chip = [Drawing.ColorTranslator]::FromHtml('#E7E6FC').ToArgb()
$separator = [Drawing.ColorTranslator]::FromHtml('#5B6185').ToArgb()
$chipColumns = [Collections.Generic.List[int]]::new()
$chevrons = 0
$chipY = $Path.Top - $Bounds.Top + [int](5 * $Scale)
$centerY = [int][Math]::Floor(($Path.Top + $Path.Bottom) / 2) - $Bounds.Top
for ($x = $Path.Left - $Bounds.Left + [int](85 * $Scale); $x -lt $Path.Right - $Bounds.Left; $x++) {
if ($Image.GetPixel($x, $chipY).ToArgb() -eq $chip) { $chipColumns.Add($x) }
if ($Image.GetPixel($x, $centerY).ToArgb() -eq $separator) { $chevrons++ }
}
if ($chevrons -eq 0) { throw "$Name does not render a breadcrumb chevron." }
if ($chipColumns.Count -lt [int](35 * $Scale) -or $chipColumns.Count -gt [int](93 * $Scale)) {
throw "$Name does not fit the current-folder chip to its label ($($chipColumns.Count) pixels)."
}
$edgeY = $Path.Top - $Bounds.Top + [int][Math]::Floor($Scale)
$chipCenter = $chipColumns[[int][Math]::Floor($chipColumns.Count / 2)]
if ($Image.GetPixel($chipCenter, $edgeY).ToArgb() -eq $chip) {
throw "$Name current-folder chip touches the top edge of the bar."
}
$chipCenter + $Bounds.Left - $Path.Left
}
function Open-LavenderOptions($Window) {
$keyboard.SendKeys('{F9}')
Wait-Until { [LavenderWindow]::IsWindowVisible([LavenderWindow]::GetDlgItem($Window, 133)) }
[void][LavenderWindow]::Post($Window, 0x111, [IntPtr]133, [IntPtr]::Zero)
Wait-Until {
$popup = [LavenderWindow]::GetLastActivePopup($Window)
[LavenderWindow]::IsWindowVisible($popup) -and
[LavenderWindow]::GetDlgItem($popup, 270) -ne [IntPtr]::Zero
}
[LavenderWindow]::GetLastActivePopup($Window)
}
function Set-Style($Window, [int]$Style) {
$dialog = Open-LavenderOptions $Window
$search = [LavenderWindow]::GetDlgItem($dialog, 270)
[void][LavenderWindow]::SendText($search, 0xC, [IntPtr]::Zero, 'Interface style')
$combo = [LavenderWindow]::GetDlgItem($dialog, 417)
Wait-Until { [LavenderWindow]::IsWindowVisible($combo) }
[void][LavenderWindow]::Send($combo, 0x14E, [IntPtr]$Style, [IntPtr]::Zero)
if ([LavenderWindow]::Send($combo, 0x147, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $Style) {
throw "Could not select Files style $Style."
}
[void][LavenderWindow]::Send($dialog, 0x111, [IntPtr](417 + (1 -shl 16)), $combo)
[void][LavenderWindow]::Post($dialog, 0x111, [IntPtr]1, [IntPtr]::Zero)
Wait-Until { ![LavenderWindow]::IsWindow($dialog) }
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 {
Wait-Until { [LavenderWindow]::GetDlgItem([LavenderWindow]::GetLastActivePopup($Window), $ControlId) -ne [IntPtr]::Zero }
} catch { throw "$Name dialog did not open after $Keys. $_" }
$dialog = [LavenderWindow]::GetLastActivePopup($Window)
Start-Sleep -Milliseconds 160
$bounds = Get-Bounds $dialog
$image = Read-Window $bounds
try {
$sampleX = $bounds.Right - [int](8 * $scale)
Test-Pixel $image $bounds $sampleX ($bounds.Top + [int](12 * $scale)) '#4648BB' "$Name title band"
Test-Pixel $image $bounds $sampleX ($bounds.Bottom - [int](12 * $scale)) '#F2EFFB' "$Name surface"
if ($Name -eq 'Copy') {
$field = Get-Bounds ([LavenderWindow]::GetDlgItem($dialog, $ControlId))
Test-Pixel $image $bounds ($field.Right - [int](12 * $scale)) `
([int](($field.Top + $field.Bottom) / 2)) '#FFFFFF' 'Copy destination field'
}
if ($DialogScreenshotDirectory -and $Name -eq 'Copy') {
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'
$saved = @{}
foreach ($name in $names) {
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
}
$fixture = if ($Screenshot) {
$target = [IO.Path]::GetFullPath($Screenshot)
$demoName = 'Demo-' + [Guid]::NewGuid().ToString('N').Substring(0, 6)
[IO.Directory]::CreateDirectory((Join-Path (Split-Path $target) $demoName))
} else { [IO.Directory]::CreateTempSubdirectory('ks-files-lavender-') }
$previousDpi = [LavenderWindow]::SetThreadDpiAwarenessContext([IntPtr](-4))
try {
$left = $fixture.CreateSubdirectory('Projects')
$right = $fixture.CreateSubdirectory('KSwitcher')
foreach ($name in 'Archives', 'Design assets', 'KSwitcher', 'Release notes', 'Screenshots') {
[void]$left.CreateSubdirectory($name)
}
foreach ($name in 'cmake', 'dictionaries', 'resources', 'src', 'tests', 'tools') {
[void]$right.CreateSubdirectory($name)
}
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', [int]$DrivePickerOnly.IsPresent, 'DWord')
$key.SetValue('LeftPanelMode', 1, 'DWord')
$key.SetValue('RightPanelMode', 1, 'DWord')
$key.SetValue('LeftViewOrder', 0, 'DWord')
$key.SetValue('RightViewOrder', 0, 'DWord')
$key.SetValue('LeftPath', $left.FullName, 'String')
$key.SetValue('RightPath', $right.FullName, 'String')
$key.SetValue('LeftCursor', (Join-Path $left.FullName 'KSwitcher'), 'String')
$key.SetValue('RightCursor', (Join-Path $right.FullName 'src'), 'String')
$key.DeleteValue('WindowPlacement', $false)
$keyboard = New-Object -ComObject WScript.Shell
$process = Start-Process -FilePath $exe -PassThru
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero -and [LavenderWindow]::Activate($process.MainWindowHandle) }
$window = $process.MainWindowHandle
$work = [Windows.Forms.Screen]::FromHandle($window).WorkingArea
$scale = [LavenderWindow]::GetDpiForWindow($window) / 96
$width = [Math]::Min($work.Width - 30, [int](1220 * $scale))
$height = [Math]::Min($work.Height - 30, [int](665 * $scale))
[void][LavenderWindow]::SetWindowPos($window, [IntPtr]::Zero, $work.Left + 15, $work.Top + 15, $width, $height, 0x14)
[void][LavenderWindow]::SetForegroundWindow($window)
$leftList = [LavenderWindow]::GetDlgItem($window, 102)
$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()
$expectedHeight = [Math]::Max($farRow, [Math]::Round(25 * $scale, [MidpointRounding]::AwayFromZero))
if ($rowHeight -ne $expectedHeight -or $key.GetValue('AppearanceMode') -ne 1) {
throw "Applying Lavender returned row height $rowHeight at scale $scale and saved mode $($key.GetValue('AppearanceMode'))."
}
$keyboard.SendKeys('{TAB}')
Start-Sleep -Milliseconds 250
$bounds = Get-Bounds $window
$leftBounds = Get-Bounds $leftList
$rightBounds = Get-Bounds $rightList
$leftIndex = [LavenderWindow]::Send($leftList, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
$rightIndex = [LavenderWindow]::Send($rightList, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
if ($leftIndex -lt 0 -or $rightIndex -lt 0) { throw 'Missing current row for the appearance check.' }
$command = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 113))
$leftPath = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 142))
$rightPathWindow = [LavenderWindow]::GetDlgItem($window, 143)
$rightPath = Get-Bounds $rightPathWindow
$pad = [int](8 * $scale)
$image = Read-Window $bounds
try {
Test-Pixel $image $bounds ($leftPath.Left - $pad) ($leftPath.Top - $pad) '#EEF0FA' 'Rounded panel corner'
Test-Pixel $image $bounds ($rightPath.Left + 30) ($rightPath.Top - $pad) '#9797F4' 'Active panel outline'
[void](Test-PathBar $image $bounds $leftPath $scale 'Inactive panel path')
$currentFolderX = Test-PathBar $image $bounds $rightPath $scale 'Active panel path'
Test-Pixel $image $bounds ([int](($leftBounds.Left + $leftBounds.Right) / 2)) ($leftBounds.Top + $leftIndex * $rowHeight + 5) '#F0F1F9' 'Inactive row'
Test-Pixel $image $bounds ([int](($rightBounds.Left + $rightBounds.Right) / 2)) ($rightBounds.Top + $rightIndex * $rowHeight + 5) '#E7E3FD' 'Active row after Tab'
Test-Pixel $image $bounds ($command.Right - 9) ($command.Top + 5) '#F7F7FD' 'Command button surface'
if ($Screenshot) {
$crop = [LavenderWindow+Rect]::new()
if ([LavenderWindow]::DwmGetWindowAttribute($window, 9, [ref]$crop, 16) -ne 0) { $crop = $bounds }
$area = [Drawing.Rectangle]::new(($crop.Left - $bounds.Left), ($crop.Top - $bounds.Top),
($crop.Right - $crop.Left), ($crop.Bottom - $crop.Top))
$visible = $image.Clone($area, [Drawing.Imaging.PixelFormat]::Format24bppRgb)
try { $visible.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png) }
finally { $visible.Dispose() }
}
} finally { $image.Dispose() }
$middleY = [int](($rightPath.Bottom - $rightPath.Top) / 2)
$click = [IntPtr](($middleY -shl 16) + $currentFolderX)
[void][LavenderWindow]::Post($rightPathWindow, 0x201, [IntPtr]1, $click)
[void][LavenderWindow]::Post($rightPathWindow, 0x202, [IntPtr]::Zero, $click)
Wait-Until { [LavenderWindow]::GetDlgItem([LavenderWindow]::GetLastActivePopup($window), 485) -ne [IntPtr]::Zero }
$address = [LavenderWindow]::GetLastActivePopup($window)
[void][LavenderWindow]::Post($address, 0x111, [IntPtr]2, [IntPtr]::Zero)
Wait-Until { ![LavenderWindow]::IsWindow($address) -and [LavenderWindow]::Activate($window) }
if ($DialogScreenshotDirectory) { [void][IO.Directory]::CreateDirectory($DialogScreenshotDirectory) }
Test-LavenderDialog $window '{F5}' 211 'Copy'
Test-LavenderDialog $window '{F6}' 211 'Rename/Move'
Test-LavenderDialog $window '{F7}' 361 'Make folder'
Test-LavenderDialog $window '{F8}' 241 'Delete'
$keyboard.SendKeys('{F5}')
Wait-Until { [LavenderWindow]::GetDlgItem([LavenderWindow]::GetLastActivePopup($window), 211) -ne [IntPtr]::Zero }
$copy = [LavenderWindow]::GetLastActivePopup($window)
[void][LavenderWindow]::SendText([LavenderWindow]::GetDlgItem($copy, 211), 0xC, [IntPtr]::Zero, 'invalid*name')
[void][LavenderWindow]::Post($copy, 0x111, [IntPtr]1, [IntPtr]::Zero)
Wait-Until {
$popup = [LavenderWindow]::GetForegroundWindow()
[LavenderWindow]::GetWindow($popup, 4) -eq $copy -and
[LavenderWindow]::GetDlgItem($popup, 100) -ne [IntPtr]::Zero
}
$warning = [LavenderWindow]::GetForegroundWindow()
Start-Sleep -Milliseconds 160
$warningBounds = Get-Bounds $warning
$warningButton = Get-Bounds ([LavenderWindow]::GetDlgItem($warning, 1))
$warningImage = Read-Window $warningBounds
try {
Test-Pixel $warningImage $warningBounds ($warningBounds.Right - [int](8 * $scale)) `
($warningBounds.Top + [int](8 * $scale)) '#A12B48' 'Nested warning title band'
Test-Pixel $warningImage $warningBounds ($warningButton.Left + [int](9 * $scale)) `
([int](($warningButton.Top + $warningButton.Bottom) / 2)) '#A12B48' 'Nested warning action'
} finally { $warningImage.Dispose() }
$keyboard.SendKeys('{ESC}')
Wait-Until { ![LavenderWindow]::IsWindow($warning) }
$keyboard.SendKeys('{ESC}')
Wait-Until { ![LavenderWindow]::IsWindow($copy) -and [LavenderWindow]::Activate($window) }
$options = Open-LavenderOptions $window
Start-Sleep -Milliseconds 160
$optionsBounds = Get-Bounds $options
$visibleOptions = [LavenderWindow+Rect]::new()
if ([LavenderWindow]::DwmGetWindowAttribute($options, 9, [ref]$visibleOptions, 16) -eq 0) {
$optionsBounds = $visibleOptions
}
$searchBounds = Get-Bounds ([LavenderWindow]::GetDlgItem($options, 270))
$optionsImage = Read-Window $optionsBounds
try {
Test-Pixel $optionsImage $optionsBounds ($searchBounds.Right - [int](12 * $scale)) `
([int](($searchBounds.Top + $searchBounds.Bottom) / 2)) '#F7F7FD' 'Options search field'
if ($DialogScreenshotDirectory) {
$optionsImage.Save((Join-Path $DialogScreenshotDirectory 'files-lavender-options.png'), [Drawing.Imaging.ImageFormat]::Png)
}
} finally { $optionsImage.Dispose() }
[void][LavenderWindow]::Post($options, 0x111, [IntPtr]2, [IntPtr]::Zero)
Wait-Until { ![LavenderWindow]::IsWindow($options) -and [LavenderWindow]::Activate($window) }
$keyboard.SendKeys('{DOWN}')
Wait-Until { [LavenderWindow]::Send($rightList, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq ($rightIndex + 1) }
$keyboard.SendKeys('^{F1}')
Wait-Until { $key.GetValue('RightPanelMode') -eq 0 }
$keyboard.SendKeys('^{F2}')
Wait-Until { $key.GetValue('RightPanelMode') -eq 1 }
[void][LavenderWindow]::SetWindowPos($window, [IntPtr]::Zero, $work.Left + 15, $work.Top + 15,
[int](580 * $scale), [int](420 * $scale), 0x14)
$compact = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 113))
if (($compact.Bottom - $compact.Top) -le ($command.Bottom - $command.Top)) {
throw 'The command bar did not switch to its compact layout.'
}
[void]$process.CloseMainWindow()
if (!$process.WaitForExit(4000)) { throw 'Files did not close.' }
$process = Start-Process -FilePath $exe -PassThru
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero -and [LavenderWindow]::Activate($process.MainWindowHandle) }
$window = $process.MainWindowHandle
$leftList = [LavenderWindow]::GetDlgItem($window, 102)
if ([LavenderWindow]::Send($leftList, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $rowHeight) {
throw 'Lavender did not survive restart.'
}
Set-Style $window 0
if ([LavenderWindow]::Send($leftList, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $farRow) {
throw 'Far did not restore its row geometry.'
}
'Lavender and Far switching, restart, keyboard navigation, Brief/Wide shortcuts, and rendered panels and dialogs verified.'
} finally {
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() }
}
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $key.DeleteValue($name, $false) }
}
$key.Dispose()
$resolvedFixture = (Resolve-Path -LiteralPath $fixture.FullName).Path
if ($resolvedFixture -eq $fixture.FullName) { $fixture.Delete($true) }
if ($previousDpi) { [void][LavenderWindow]::SetThreadDpiAwarenessContext($previousDpi) }
}
+170
View File
@@ -0,0 +1,170 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$PreferenceKey = 'Software\KSwitcher\Files',
[string]$Screenshot,
[int]$FtpPort
)
$ErrorActionPreference = 'Stop'
. "$PSScriptRoot/files_commands_ui.ps1"
function Read-Caption([IntPtr]$Control) {
$label = [Text.StringBuilder]::new(1024)
[void][FilesCommandsUi]::Read($Control, 13, [IntPtr]$label.Capacity, $label)
$label.ToString()
}
function Test-Rows([IntPtr]$List, [string[]]$Expected) {
(@(Read-FilesList $List) -join [char]10) -ceq ($Expected -join [char]10)
}
function Send-PanelKey([IntPtr]$List, [int]$Key) {
[void][FilesCommandsUi]::Post($List, 0x100, [IntPtr]$Key, [IntPtr]::Zero)
}
function Save-FilesWindow([IntPtr]$Window, [string]$Destination) {
Add-Type -AssemblyName System.Drawing
$bounds = [FilesCommandsUi+Rect]::new()
if (![FilesCommandsUi]::GetClientRect($Window, [ref]$bounds)) { throw 'Could not locate the Files window.' }
$bitmap = [Drawing.Bitmap]::new($bounds.Right, $bounds.Bottom)
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try {
if (![FilesCommandsUi]::PrintWindow($Window, $dc, 3)) { throw 'Could not render the Files window.' }
} finally { $graphics.ReleaseHdc($dc) }
} finally { $graphics.Dispose() }
$bitmap.Save($Destination, [Drawing.Imaging.ImageFormat]::Png)
} finally { $bitmap.Dispose() }
}
$exe = (Resolve-Path -LiteralPath $Executable).Path
$root = [IO.Directory]::CreateTempSubdirectory('ks-recent-folders-').FullName
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($PreferenceKey)
$names = 'RecentFolders', 'FtpProfiles', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor',
'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement', 'LeftViewOrder', 'RightViewOrder'
$saved = @{}
foreach ($name in $names) {
if ($name -in $preferences.GetValueNames()) {
$saved[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
}
}
$process = $null
try {
foreach ($folder in 'left', 'right', 'destination', 'remove') {
[void][IO.Directory]::CreateDirectory((Join-Path $root $folder))
}
$leftFolder = Join-Path $root 'left'
$rightFolder = Join-Path $root 'right'
$destinationFolder = Join-Path $root 'destination'
$removeFolder = Join-Path $root 'remove'
[IO.File]::WriteAllText((Join-Path $leftFolder 'left-marker.txt'), 'left file')
[IO.File]::WriteAllText((Join-Path $rightFolder 'right-marker.txt'), 'right file')
[IO.File]::WriteAllText((Join-Path $destinationFolder 'opened-marker.txt'), 'existing folder')
$ftpId = [guid]::NewGuid().ToString('N')
if ($FtpPort) {
$ftpProfile = @(@{id=$ftpId; name='Local FTP'; host='127.0.0.1'; port=$FtpPort; user=''; secret=@()})
$preferences.SetValue('FtpProfiles', [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $ftpProfile -Compress)), 'Binary')
}
$entries = @($destinationFolder, @{source='ftp'; id=$ftpId; label='Local FTP'; path='\documents'}, $removeFolder)
$ftpLabel = 'FTP · Local FTP · /documents'
$preferences.SetValue('RecentFolders', [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $entries -Compress)), 'Binary')
foreach ($name in 'LeftViewOrder', 'RightViewOrder') { $preferences.SetValue($name, 0, 'DWord') }
$preferences.SetValue('LeftPath', $leftFolder, 'String')
$preferences.SetValue('RightPath', $rightFolder, 'String')
$preferences.SetValue('LeftCursor', (Join-Path $leftFolder 'left-marker.txt'), 'String')
foreach ($name in 'RightCursor', 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement') {
$preferences.DeleteValue($name, $false)
}
$process = Start-Process -FilePath $exe -WindowStyle Hidden -PassThru
$window = Wait-For 'the Files window' {
$candidate = [IntPtr]::Zero
while (($candidate = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $candidate, 'KSwitcher.Files', [NullString]::Value)) -ne [IntPtr]::Zero) {
[uint32]$owner = 0
[void][FilesCommandsUi]::GetWindowThreadProcessId($candidate, [ref]$owner)
if ($owner -eq $process.Id) { return $candidate }
}
}
if ($Screenshot) { [void][FilesCommandsUi]::SetWindowPos($window, 0, 80, 60, 1380, 720, 20) }
[void][FilesCommandsUi]::ShowWindow($window, 4)
$picker = [FilesCommandsUi]::GetDlgItem($window, 121)
$left = [FilesCommandsUi]::GetDlgItem($window, 102)
$right = [FilesCommandsUi]::GetDlgItem($window, 103)
$leftPath = [FilesCommandsUi]::GetDlgItem($window, 142)
$rightPath = [FilesCommandsUi]::GetDlgItem($window, 143)
[void](Wait-For 'both initial folders' {
(Read-Caption $leftPath) -eq $leftFolder -and (Read-Caption $rightPath) -eq $rightFolder -and
(Read-FilesList $left) -contains 'left-marker.txt' -and (Read-FilesList $right) -contains 'right-marker.txt'
})
$leftBefore = @(Read-FilesList $left)
Select-FilesListRow $left 'left-marker.txt'
$rightBefore = @(Read-FilesList $right)
Open-FilesSource $window 0 'Recent folders'
[void](Wait-For 'recent folders in the left panel' {
(Read-Caption $leftPath) -ceq 'Recent folders' -and
(Test-Rows $left @($destinationFolder, $ftpLabel, $removeFolder))
})
if ([FilesCommandsUi]::IsWindowVisible($picker) -or !(Test-Rows $right $rightBefore)) {
throw 'Recent folders opened a popup or modified the right panel.'
}
if ($Screenshot) { Save-FilesWindow $window $Screenshot }
Select-FilesListRow $left $removeFolder
Send-PanelKey $left 46
[void](Wait-For 'the recent entry to be removed' { Test-Rows $left @($destinationFolder, $ftpLabel) })
if (!(Test-Path -LiteralPath $removeFolder -PathType Container)) { throw 'Delete removed the underlying folder.' }
Send-PanelKey $left 27
[void](Wait-For 'Escape to restore the left panel' {
$row = [FilesCommandsUi]::Send($left, 392, 0, 0).ToInt32()
(Read-Caption $leftPath) -eq $leftFolder -and (Test-Rows $left $leftBefore) -and
$row -ge 0 -and $leftBefore[$row] -eq 'left-marker.txt'
})
Open-FilesSource $window 1 'Recent folders'
[void](Wait-For 'updated recent folders in the right panel' {
(Read-Caption $rightPath) -ceq 'Recent folders' -and (Test-Rows $right @($destinationFolder, $ftpLabel))
})
if ([FilesCommandsUi]::IsWindowVisible($picker) -or !(Test-Rows $left $leftBefore)) {
throw 'Recent folders opened a popup or modified the left panel.'
}
Select-FilesListRow $right $destinationFolder
Send-PanelKey $right 13
[void](Wait-For 'the local folder to open on the right' {
(Read-Caption $rightPath) -eq $destinationFolder -and (Read-FilesList $right) -contains 'opened-marker.txt'
})
if ($FtpPort) {
Open-FilesSource $window 0 'Recent folders'
[void](Wait-For 'the FTP recent entry' { (Read-FilesList $left) -contains $ftpLabel })
Select-FilesListRow $left $ftpLabel
Send-PanelKey $left 13
[void](Wait-For 'the FTP directory to open on the left' {
(Read-Caption $leftPath) -ceq 'Local FTP · /documents' -and
(Read-FilesList $left) -contains 'ftp-marker.txt'
})
if ((Read-Caption $rightPath) -ne $destinationFolder) { throw 'Opening FTP modified the right panel.' }
}
[void][FilesCommandsUi]::Post($window, 16, 0, 0)
if (!$process.WaitForExit(5000)) { throw 'Files did not close.' }
$recorded = [Text.Encoding]::UTF8.GetString($preferences.GetValue('RecentFolders')) | ConvertFrom-Json
if ($recorded -contains $removeFolder) { throw 'The remove action was not persisted.' }
'Verified in-panel Recent folders, deletion, cursor restoration and folder navigation.'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $preferences.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $preferences.DeleteValue($name, $false) }
}
$preferences.Dispose()
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
$resolved = (Resolve-Path -LiteralPath $root).Path
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-recent-folders-*') {
Remove-Item -LiteralPath $resolved -Recurse -Force
}
}
+23 -15
View File
@@ -61,19 +61,27 @@ try {
}
}
[void][FilesCommandsUi]::ShowWindow($main, 4)
$picker = [FilesCommandsUi]::GetDlgItem($main, 121)
[void][FilesCommandsUi]::Post($main, 0x104, [IntPtr]112, [IntPtr]::Zero)
[void](Wait-For 'Change drive' { [FilesCommandsUi]::IsWindowVisible($picker) })
$count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
$selection = -1
for ($row = 0; $row -lt $count; ++$row) {
$label = [Text.StringBuilder]::new(256)
[void][FilesCommandsUi]::Read($picker, 393, [IntPtr]$row, $label)
if ($label.ToString() -ceq 'SMB') { $selection = $row; break }
function Same-Rows($First, $Second) {
($First -join [char]10) -ceq ($Second -join [char]10)
}
if ($selection -lt 0) { throw 'SMB was missing from Change drive.' }
[void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$selection, [IntPtr]::Zero)
[void][FilesCommandsUi]::Post($picker, 0x100, [IntPtr]13, [IntPtr]::Zero)
$left = [FilesCommandsUi]::GetDlgItem($main, 102)
$right = [FilesCommandsUi]::GetDlgItem($main, 103)
[void](Wait-For 'both local panels' { @(Read-FilesList $left).Count -gt 0 -and @(Read-FilesList $right).Count -gt 0 })
$leftBefore = @(Read-FilesList $left)
$rightBefore = @(Read-FilesList $right)
Open-FilesSource $main 0 'SMB'
[void](Wait-For 'the SMB profile in the left file panel' {
(Read-FilesList $left) -like 'Render fixture*'
})
if (!(Same-Rows $rightBefore @(Read-FilesList $right))) { throw 'Opening SMB on the left changed the right panel.' }
[void][FilesCommandsUi]::Post($left, 0x100, [IntPtr]27, [IntPtr]::Zero)
[void](Wait-For 'Escape to return to the left folder' { Same-Rows $leftBefore @(Read-FilesList $left) })
Open-FilesSource $main 1 'SMB'
[void](Wait-For 'the SMB profile in the right file panel' {
(Read-FilesList $right) -like 'Render fixture*'
})
if (!(Same-Rows $leftBefore @(Read-FilesList $left))) { throw 'Opening SMB on the right changed the left panel.' }
function Find-DialogControl([int]$Id) {
$dialog = [IntPtr]::Zero
while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $dialog, '#32770', [NullString]::Value)) -ne [IntPtr]::Zero) {
@@ -85,8 +93,8 @@ try {
}
}
}
$browser, $signIn = Wait-For 'the SMB Sign in command' { Find-DialogControl 547 }
[void][FilesCommandsUi]::Post($browser, 0x111, [IntPtr]547, $signIn)
if (Find-DialogControl 541) { throw 'SMB displayed a separate browser over the file panels.' }
[void][FilesCommandsUi]::Post($main, 0x111, [IntPtr]547, [IntPtr]::Zero)
$dialog, $password = Wait-For 'the SMB password field' { Find-DialogControl 559 }
$empty = Render-Password $password
Set-Password $password 'WWWWWWWW'
@@ -100,7 +108,7 @@ try {
if ([FilesCommandsUi]::Send($remember, 0xf0, [IntPtr]::Zero, [IntPtr]::Zero) -ne [IntPtr]::Zero) {
throw 'Remember in Windows Credential Manager must be unchecked by default.'
}
'Verified password masking and the default credential-saving choice.'
'Verified SMB in both file panels, Escape navigation, password masking and the default credential-saving choice.'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
foreach ($name in $names) {
+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)
}
+69 -1
View File
@@ -426,6 +426,74 @@ int main(int argc, char **argv) {
ks::encodePng(ks::decodeImage(preview)));
SendMessageW(window, WM_COMMAND, IDCANCEL, 0);
require(!app.helpWindow && !IsWindow(window), "Close releases the help window");
const auto seen = temp / L"whats-new-seen.txt";
app.showWhatsNewAfterUpdate();
require(!app.helpWindow && !std::filesystem::exists(seen), "ordinary startup does not open release notes");
app.updateStartupEvent = L"Local\\KSwitcher.Update.Started." + ks::newSnippetId();
app.showWhatsNewAfterUpdate();
require(!app.helpWindow && !std::filesystem::exists(seen), "an unconfirmed update does not open release notes");
const auto ready = CreateEventW(nullptr, TRUE, FALSE, app.updateStartupEvent.c_str());
require(ready != nullptr, "update test creates a startup handshake");
app.showWhatsNewAfterUpdate();
const auto signaled = WaitForSingleObject(ready, 0);
CloseHandle(ready);
require(signaled == WAIT_OBJECT_0 && IsWindowVisible(app.helpWindow) && std::filesystem::exists(seen),
"successful update signals startup and opens the installed notes once");
DestroyWindow(app.helpWindow);
const auto secondReady = CreateEventW(nullptr, TRUE, FALSE, app.updateStartupEvent.c_str());
require(secondReady != nullptr, "repeat startup can complete its updater handshake");
app.showWhatsNewAfterUpdate();
const auto secondSignal = WaitForSingleObject(secondReady, 0);
CloseHandle(secondReady);
require(secondSignal == WAIT_OBJECT_0 && !app.helpWindow,
"the same version acknowledges the updater without reopening the notes");
const auto language = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
ks::showWhatsNew(app, language);
const auto releases = app.helpWindow;
const auto releaseText = [&](int id) {
wchar_t buffer[32768]{};
GetDlgItemTextW(releases, id, buffer, std::size(buffer));
return std::wstring(buffer);
};
require(std::wstring(ks::whatsNewTitle(language)) == L"What's new" &&
releaseText(812) == std::wstring(L"v") + ks::AppVersion &&
!releaseText(813).empty() && IsWindowVisible(GetDlgItem(releases, 814)),
"manual Help command opens embedded notes for the installed release with a Gitea link");
const auto versions = GetDlgItem(releases, 811);
require(TreeView_GetCount(versions) > 2, "prior releases are available offline");
SetDlgItemTextW(releases, 810, L"v0.6.126");
require(releaseText(812) == L"v0.6.126 (withdrawn)" && !IsWindowVisible(GetDlgItem(releases, 814)),
"withdrawn releases show their archived notes without a dead Gitea release link");
SetDlgItemTextW(releases, 810, L"v0.8.0");
require(releaseText(812) == L"v0.8.0" && releaseText(813).find(L"Find files recursively") != std::wstring::npos,
"release history searches and shows English notes");
const auto ukrainian = MAKELANGID(LANG_UKRAINIAN, SUBLANG_DEFAULT);
ks::showWhatsNew(app, ukrainian);
require(releases == app.helpWindow && std::wstring(ks::whatsNewTitle(ukrainian)) == L"Що нового" &&
releaseText(814) == L"Відкрити в Gitea",
"the same window can display Ukrainian release history");
SetDlgItemTextW(releases, 810, L"v0.8.0");
require(releaseText(812) == L"v0.8.0" && releaseText(813).find(L"Рекурсивний пошук") != std::wstring::npos &&
releaseText(813).find(L"Find files recursively") == std::wstring::npos,
"Ukrainian notes render without the adjacent English section");
SetDlgItemTextW(releases, 810, L"");
require(TreeView_GetCount(versions) > 2 && releaseText(812) == L"v0.8.0",
"clearing the search retains the selected release in the full history");
RECT releaseClient{};
GetClientRect(releases, &releaseClient);
RedrawWindow(releases, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
const auto releaseDc = GetDC(releases);
const auto releasePreview = ks::screenshotClip(releaseDc, releaseClient.right, releaseClient.bottom, {});
ReleaseDC(releases, releaseDc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"whats-new.png",
ks::encodePng(ks::decodeImage(releasePreview)));
ks::showHelp(app);
require(releases == app.helpWindow && releaseText(812) == L"Getting started" &&
!IsWindowVisible(GetDlgItem(releases, 814)),
"returning to the guide restores its topics and actions");
}
std::filesystem::remove_all(temp);
std::cout << "Passed " << checks << " offline help checks\n";
@@ -1070,7 +1138,7 @@ int main(int argc, char **argv) {
auto events = GetDlgItem(pane, 733);
auto visible = [&](int id) { return (GetWindowLongPtrW(GetDlgItem(pane, id), GWL_STYLE) & WS_VISIBLE) != 0; };
auto selectPage = [&](int index) { selectSettingsPage(settings, index); };
require(TreeView_GetCount(navigation) == 20, "all Settings sections are listed");
require(TreeView_GetCount(navigation) == 21, "all Settings sections are listed");
selectPage(3);
require(visible(243) && !visible(501), "Clipboard lists excluded apps separately from OCR");
require(TreeView_GetParent(navigation, settingsSection(navigation, 19)) == settingsSection(navigation, 3),
+4 -3
View File
@@ -67,9 +67,10 @@ void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected)
}
}
require(donationSeparated && donation.hbmpItem, "tray donation item has an icon and both separators");
require(help && GetMenuItemCount(help) == 2 && menuTitle(help, 0) == L"&User guide" &&
menuTitle(help, 1) == L"&About KSwitcher",
"tray Help submenu contains User guide and About KSwitcher");
require(help && GetMenuItemCount(help) == 3 && menuTitle(help, 0) == L"&User guide" &&
menuTitle(help, 1) == ks::whatsNewTitle(GetThreadUILanguage()) &&
menuTitle(help, 2) == L"&About KSwitcher",
"tray Help submenu contains User guide, release notes and About KSwitcher");
require(PostMessageW(popup, WM_CHAR, L'i', 0), "cannot select input menu item");
until([&] { return !IsWindow(popup); }, "tray action did not close menu");
query(resident, WM_NULL);
+158 -2
View File
@@ -1,5 +1,6 @@
#include "app.h"
#include "diagnostics.h"
#include "paste_probe.h"
#include <algorithm>
#include <iostream>
#include <fstream>
@@ -61,6 +62,11 @@ namespace
{
ks::App *app{};
HWND host{}, field{};
HWND externalEditor{};
ULONGLONG externalPopupUntil{};
bool insertExternalSnippet{};
bool insertTerminalSnippet{};
constexpr wchar_t externalSnippetText[] = L"snippet test";
ks::Clip saved;
bool snippetRecoveryOnly = false;
LONG unfilteredSnippetWidth{};
@@ -79,6 +85,7 @@ bool typeDuringMacros = false;
ULONGLONG macroStart{}, macroEnd{};
int copyFailuresRemaining = 0, copyRequests = 0;
int droppedSelectionKeys = 0;
int delayedSelectionKeys = 0;
bool trimCopiedSpaces = false;
int trimmedCopies = 0;
bool temporaryClipboardExcluded = true;
@@ -152,6 +159,16 @@ LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_P
--copyFailuresRemaining;
return 0;
}
if (delayedSelectionKeys)
{
DWORD start{}, end{};
SendMessageW(w, EM_GETSEL, reinterpret_cast<WPARAM>(&start), reinterpret_cast<LPARAM>(&end));
auto result = DefSubclassProc(w, message, wp, lp);
// Apply the remaining Shift+Left moves after publishing the partial selection.
SendMessageW(w, EM_SETSEL, end, start - std::min<DWORD>(start, delayedSelectionKeys));
delayedSelectionKeys = 0;
return result;
}
if (trimCopiedSpaces)
{
auto result = DefSubclassProc(w, message, wp, lp);
@@ -278,6 +295,53 @@ void expandMacroSnippet(const wchar_t *replacement)
record(L";zmtest");
app->transform(0, 0, 0, field);
}
bool terminalShowsTestDraft()
{
using Microsoft::WRL::ComPtr;
ComPtr<IUIAutomation2> automation;
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&automation))))
return false;
automation->put_TransactionTimeout(150);
ComPtr<IUIAutomationElement> element;
ComPtr<IUIAutomationTreeWalker> walker;
if (FAILED(automation->GetFocusedElement(&element)) || !element ||
!ks::focusedTextBelongsToWindow(automation.Get(), element.Get(), externalEditor) ||
FAILED(automation->get_RawViewWalker(&walker)) || !walker)
return false;
// The xterm accessibility tree is beside the input's screen element.
for (int depth = 0; element && depth < 3; ++depth)
{
ComPtr<IUIAutomationElement> parent;
walker->GetParentElement(element.Get(), &parent);
element = std::move(parent);
}
if (!element) return false;
VARIANT className{};
className.vt = VT_BSTR;
className.bstrVal = SysAllocString(L"xterm-accessibility-tree");
ComPtr<IUIAutomationCondition> condition;
const auto hr = automation->CreatePropertyCondition(UIA_ClassNamePropertyId, className, &condition);
VariantClear(&className);
ComPtr<IUIAutomationElement> tree, row;
if (FAILED(hr) || !condition || FAILED(element->FindFirst(TreeScope_Descendants, condition.Get(), &tree)) ||
!tree || FAILED(walker->GetLastChildElement(tree.Get(), &row))) return false;
while (row)
{
BSTR name{};
row->get_CurrentName(&name);
std::wstring_view line(name ? name : L"", SysStringLen(name));
const auto end = line.find_last_not_of(L" \t\r\n\u00a0");
const bool matches = end != line.npos && line.substr(0, end + 1).ends_with(externalSnippetText);
SysFreeString(name);
if (end != line.npos) return matches;
ComPtr<IUIAutomationElement> previous;
walker->GetPreviousSiblingElement(row.Get(), &previous);
row = std::move(previous);
}
return false;
}
void finish()
{
KillTimer(host, 1);
@@ -337,7 +401,65 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
}
switch (stage++)
{
case 101:
require(GetForegroundWindow() == externalEditor, "external editor retains foreground before typing");
app->settings.snippets = {{L";ksw-regression", externalSnippetText}};
app->resetInput();
externalPopupUntil = GetTickCount64() + 2000;
typeKeys({VK_OEM_1});
break;
case 102:
{
if (GetForegroundWindow() != externalEditor)
throw std::runtime_error("External editor lost foreground while typing");
const bool visible = ks::InputRegressionAccess::suggestionsVisible(*app);
if (!visible && GetTickCount64() < externalPopupUntil)
{
stage = 102;
break;
}
if (!visible) typeKeys({VK_BACK});
else if (insertExternalSnippet || insertTerminalSnippet)
{
externalPopupUntil = GetTickCount64() + 3000;
typeKeys({VK_TAB});
}
else typeKeys({VK_ESCAPE, VK_BACK});
require(visible, "semicolon shows suggestions in the external editor");
break;
}
case 103:
if (insertExternalSnippet)
{
require(GetForegroundWindow() == externalEditor, "insertion leaves the external editor focused");
ks::PasteProbe probe(true, externalEditor);
const auto text = probe.read(static_cast<int>(std::size(externalSnippetText) - 1));
const bool inserted = text && *text == externalSnippetText;
if (inserted)
{
ks::chord('A', MOD_CONTROL);
typeKeys({VK_BACK});
}
require(inserted, "Tab inserts the selected snippet in the external editor");
}
else if (insertTerminalSnippet)
{
const bool inserted = GetForegroundWindow() == externalEditor &&
!ks::InputRegressionAccess::suggestionsVisible(*app) && terminalShowsTestDraft();
if (!inserted && GetTickCount64() < externalPopupUntil)
{
stage = 103;
break;
}
require(inserted, "Tab replaces the prefix in the live shell prompt");
}
else
require(!ks::InputRegressionAccess::suggestionsVisible(*app), "Escape dismisses external suggestions");
finish();
break;
case 0:
app->settings.writeLog = true;
ks::setLoggingEnabled(true);
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
@@ -685,6 +807,26 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
case 59:
require(text() == L"OLDghbdtn NEXT", "hotkey without selection reconverts only the previous middle range");
require(ks::readClipboard(app->window).text() == sentinel, "selected and repeated conversions restore clipboard");
[[fallthrough]];
case 95:
if (!captured)
{
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
}
prepare(L" nen NEXT", false);
SendMessageW(field, EM_SETSEL, 6, 6);
record(L"nen ");
droppedSelectionKeys = delayedSelectionKeys = 2;
app->transform(ks::Direct + ru);
stage = 96;
break;
case 96:
require(text() == L" " + ks::convertTo(L"nen ", app->layouts, ru, en) + L"NEXT",
"delayed selection preserves the older prefix and text after the caret");
require(!droppedSelectionKeys && !delayedSelectionKeys, "fixture applied the delayed selection moves");
require(ks::readClipboard(app->window).text() == sentinel, "delayed selection restores clipboard");
finish();
break;
case 66:
@@ -1196,6 +1338,15 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
} // namespace
int main(int argc, char **argv)
{
const bool externalEditorTest = argc > 1 && std::string_view(argv[1]) == "--snippet-external-editor";
if (externalEditorTest)
{
insertExternalSnippet = argc > 2 && std::string_view(argv[2]) == "--insert";
insertTerminalSnippet = argc > 2 && std::string_view(argv[2]) == "--terminal-insert";
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
externalEditor = GetForegroundWindow();
if (!externalEditor) return 1;
}
conversionOnly = argc > 1 && std::string(argv[1]) == "--conversion-only";
typosOnly = argc > 1 && std::string(argv[1]) == "--typos-only";
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
@@ -1362,7 +1513,7 @@ int main(int argc, char **argv)
if (language == 0x419)
ru = i;
}
if (en < 0 || ru < 0)
if (!externalEditorTest && (en < 0 || ru < 0))
throw std::runtime_error(
"Integration test requires installed English US and Russian layouts");
WNDCLASSW cls{};
@@ -1372,7 +1523,8 @@ int main(int argc, char **argv)
cls.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
RegisterClassW(&cls);
host = CreateWindowW(cls.lpszClassName, L"KSwitcher — automated test editor",
WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 650, 320, nullptr, nullptr,
WS_OVERLAPPEDWINDOW | (externalEditorTest ? 0 : WS_VISIBLE),
100, 100, 650, 320, nullptr, nullptr,
cls.hInstance, nullptr);
field =
CreateWindowW(L"EDIT", L"", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_MULTILINE | ES_WANTRETURN,
@@ -1392,6 +1544,10 @@ int main(int argc, char **argv)
stage = 93;
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
stage = 84;
if (externalEditorTest)
stage = 101;
if (argc > 1 && std::string(argv[1]) == "--delayed-selection-only")
stage = 95;
SetTimer(host, 1, 100, nullptr);
auto forwarding = SetWindowsHookExW(WH_KEYBOARD_LL,forwardingHook,GetModuleHandleW(nullptr),0);
require(forwarding!=nullptr,"downstream forwarding fixture installed before application hook");
+36
View File
@@ -228,6 +228,42 @@ void verifyFiles(LanClients &clients, const Json &trusted, const std::wstring &p
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "replace")).at("type") == "complete" &&
read(to / L"content.txt") == content, "replace conflict policy failed");
const auto ask = [&](const char *decision, bool replaceable) {
Pipe client(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "ask"));
unsigned prompts = 0;
for (;;)
{
auto result = client.reply();
const auto type = result.value("type", "");
if (type == "progress") client.sendJson({{"continue", true}});
else if (type == "conflict")
{
++prompts;
require(result.at("path") == utf8((to / L"content.txt").native()) &&
result.at("replaceable") == replaceable &&
result.at("incoming").at("size") == content.size(), "incorrect conflict prompt");
client.sendJson({{"decision", "wait"}});
client.sendJson({{"decision", decision}});
}
else
{
client.ack();
require(prompts == 1, "ask did not report the nested collision exactly once");
return result;
}
}
};
save(to / L"content.txt", "keep me");
require(ask("skip", true).at("skipped") == 1 && read(to / L"content.txt") == "keep me",
"skipping a prompted collision changed its destination");
require(ask("replace", true).at("type") == "complete" && read(to / L"content.txt") == content,
"confirming a prompted collision did not replace its destination");
fs::remove(to / L"content.txt");
fs::create_directory(to / L"content.txt");
require(ask("replace", false).contains("error") && fs::is_directory(to / L"content.txt"),
"a prompted type mismatch allowed replacement");
fs::remove(to / L"content.txt");
const auto localCopy = root / L"local.txt";
const auto fromLocal = transfer(endpoint(nullptr, file), endpoint(b, dst / L"from-local.txt"), false);
require(runTransfer(pipe, fromLocal).contains("error"), "identification-only pipe accessed local files");
+12
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");
+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')) {