Compare commits
82
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20930dd05c | ||
|
|
f76796c7ea | ||
|
|
86346df08e | ||
|
|
211a6bdb33 | ||
|
|
240cc535ba | ||
|
|
92b72c2e7b | ||
|
|
59d01375ff | ||
|
|
2ffee2f880 | ||
|
|
e5987dee22 | ||
|
|
890d869f8f | ||
|
|
77aa5b7894 | ||
|
|
d95f521c77 | ||
|
|
fd4ba1b69f | ||
|
|
2a6dfc92ba | ||
|
|
418b262c2a | ||
|
|
ee9bcf98a7 | ||
|
|
bc086873ba | ||
|
|
a1aa432355 | ||
|
|
919f8e9c7c | ||
|
|
e852da8fcd | ||
|
|
79aeff1c8b | ||
|
|
03f5a8db7c | ||
|
|
99c8b6191f | ||
|
|
50804185f4 | ||
|
|
a9866d6973 | ||
|
|
7b70105168 | ||
|
|
b076dcb303 | ||
|
|
8bedb9ffbd | ||
|
|
8f52bf2a8f | ||
|
|
359b9ce284 | ||
|
|
160cece79d | ||
|
|
2869d584d8 | ||
|
|
2db1d79c1d | ||
|
|
fb27ad8843 | ||
|
|
c910fc32d8 | ||
|
|
879d2adcce | ||
|
|
356f472fd2 | ||
|
|
203d9ec68d | ||
|
|
f9cbb29c07 | ||
|
|
187334aed2 | ||
|
|
ae7939eca5 | ||
|
|
f7620d164f | ||
|
|
47e10477e1 | ||
|
|
f2e403dd39 | ||
|
|
85cdce1b01 | ||
|
|
4acff70e49 | ||
|
|
20bd93b76b | ||
|
|
a63e3534c1 | ||
|
|
e2b9a65237 | ||
|
|
e7ef2e600b | ||
|
|
211a5e0b59 | ||
|
|
0ad8d7f6aa | ||
|
|
ce36d73b66 | ||
|
|
aa90645c98 | ||
|
|
07646d3642 | ||
|
|
9a5479b8f9 | ||
|
|
9edb27c765 | ||
|
|
5194e2b621 | ||
|
|
da914168e8 | ||
|
|
15bf006a19 | ||
|
|
9b5cff122d | ||
|
|
7670616dc4 | ||
|
|
25acb892d1 | ||
|
|
03a370f445 | ||
|
|
e8bef94474 | ||
|
|
0f400a58a1 | ||
|
|
e852fde4f4 | ||
|
|
e421c17f2a | ||
|
|
f4dcd0efd9 | ||
|
|
a5a5724513 | ||
|
|
040658f350 | ||
|
|
0ac6501b21 | ||
|
|
b6b7164742 | ||
|
|
8870d8c3d9 | ||
|
|
eb0f6ead72 | ||
|
|
d26eec3c98 | ||
|
|
1757450833 | ||
|
|
1066fbeab8 | ||
|
|
f2dc1f0c78 | ||
|
|
64e741f778 | ||
|
|
1edd0343ef | ||
|
|
6c0e8f0736 |
No files matched your search
+53
-5
@@ -1,16 +1,18 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.7.4 LANGUAGES C CXX RC)
|
||||
project(KSwitcher VERSION 0.8.13 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
|
||||
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp resources/files.rc)
|
||||
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)
|
||||
@@ -35,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()
|
||||
@@ -80,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)
|
||||
@@ -148,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)
|
||||
@@ -185,6 +196,16 @@ if(NOT MSVC)
|
||||
target_link_options(KSwitcherFilesModalTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME files-modal-dialog COMMAND KSwitcherFilesModalTests)
|
||||
add_executable(KSwitcherFilesMcpTests tests/files_mcp.cpp src/files_mcp.cpp)
|
||||
target_include_directories(KSwitcherFilesMcpTests PRIVATE src)
|
||||
target_link_libraries(KSwitcherFilesMcpTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesMcpTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherFilesMcpTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME files-mcp COMMAND KSwitcherFilesMcpTests)
|
||||
set_tests_properties(files-mcp PROPERTIES TIMEOUT 30)
|
||||
add_executable(KSwitcherLanTests tests/lan.cpp)
|
||||
target_link_libraries(KSwitcherLanTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
@@ -228,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
|
||||
@@ -336,6 +382,8 @@ add_test(NAME utilities-regressions COMMAND KSwitcherUtilitiesTests)
|
||||
add_test(NAME stayhere-lifecycle COMMAND powershell -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/stayhere.ps1" -Executable "$<TARGET_FILE:StayHereTest>")
|
||||
add_test(NAME scroll-regressions COMMAND KSwitcherScrollTests)
|
||||
add_test(NAME input-regressions COMMAND KSwitcherInputTests)
|
||||
add_dependencies(KSwitcherInputTests KSwitcherFilesActivationFixture)
|
||||
add_test(NAME custom-shortcut-layout COMMAND KSwitcherInputTests --custom-shortcut-layout $<TARGET_FILE:KSwitcherFilesActivationFixture>)
|
||||
add_dependencies(KSwitcherInputTests KSwitcherScreenshot)
|
||||
add_test(NAME clipboard-history-layout COMMAND KSwitcherInputTests --history-layout)
|
||||
set_tests_properties(clipboard-history-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
|
||||
|
||||
+61
-28
@@ -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,9 +648,10 @@ Warning і початковий фокус на No.
|
||||
- Коли список LAN-дисків змінює розмір меню Change drive, рамка й список
|
||||
змінюють позицію разом. Рамка повністю перемальовується після зміни
|
||||
розміру, а список має однаковий внутрішній відступ зліва і справа.
|
||||
Смуга прокрутки має окреме місце, щоб не обрізати значення вільного місця.
|
||||
- Тайм-аут запиту дисків відображається як Connection timed out. Якщо
|
||||
ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий
|
||||
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows.
|
||||
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. Commands → Files log відкриває до 200 останніх записів поточного або попереднього журналу. Refresh оновлює список. Copy selected або Ctrl+C копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано.
|
||||
|
||||
- Застосовані налаштування Files одразу підхоплюють інші відкриті вікна.
|
||||
Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
|
||||
@@ -686,13 +702,19 @@ Warning і початковий фокус на No.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
|
||||
тексту, Markdown і зображень у сусідній панелі. Перегляд слідує за курсором активної
|
||||
тексту, Markdown, HTML, зображень і двійкових файлів у сусідній панелі. Перегляд слідує за курсором активної
|
||||
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
|
||||
Під час перегляду файлові операції з призначенням у сусідній панелі
|
||||
пропонують спершу закрити Quick View.
|
||||
- Для локальних HTML-файлів до 8 МіБ Quick View відкриває **Rendered**. **Show Source** показує початковий текст, **Show Rendered** повертає форматований вигляд. F6 перемикає режими, коли фокус у самому перегляді. Quick View відображає статичне форматування й текст локально. Виконання скриптів, перехід за посиланнями і завантаження ресурсів заблоковані. Для зображень HTML показує їхній альтернативний текст. Більші HTML-файли починаються з першої сторінки вихідного тексту.
|
||||
- Двійковий режим показує до 4096 початкових байтів, зі звичайними символами для друкованих байтів та позначенням `\xNN` для контрольних кодів. Рядки переносяться за шириною панелі. Shift+F3 відкриває повний Hex Viewer.
|
||||
- **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й
|
||||
вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі
|
||||
зображення в порядку вихідної панелі на момент відкриття Viewer.
|
||||
- **Options → Viewer → Restore local Viewer and Editor windows after restart** зберігає відкриті локальні вікна під час закриття Files. Під час наступного запуску наявні документи відкриваються в попередньому режимі й положенні. Текст відновлює сторінку, курсор і прокручування, а зображення — масштаб. Відновлення читає збережені файли з диска.
|
||||
- Локальний Viewer оновлює вміст після зміни файла. Активний Editor пропонує **Reload** або **Keep buffer**. Reload відкриває актуальну версію з диска, Keep buffer залишає відкриті редагування. Збереження після Keep buffer перевіряє початкову версію й зберігає чернетку, якщо файл уже змінився.
|
||||
- **F4** на локальному PNG або JPEG відкриває редактор зображень. Rotate left і Rotate right повертають зображення на 90°. Crop приймає цілі координати X і Y від нуля, ширину й висоту в пікселях поточного зображення. Undo або Ctrl+Z послідовно скасовує зміни.
|
||||
- **Save copy** або Ctrl+Shift+S створює окремий PNG чи JPEG. PNG зберігає прозорість, а JPEG використовує біле тло. **Replace** або Ctrl+S просить підтвердження й звіряє версію оригіналу. Якщо зовнішня зміна або помилка заважає запису, редактор зберігає чернетку. Закриття незбереженої чернетки просить підтвердження.
|
||||
- У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб,
|
||||
перетягування мишею панорамує збільшене зображення, Fit підганяє його
|
||||
під область перегляду, а 100% повертає вихідний масштаб. Клавіші 0 і 1
|
||||
@@ -700,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+↑ та рядок `..`
|
||||
@@ -716,6 +739,9 @@ Warning і початковий фокус на No.
|
||||
попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L
|
||||
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
|
||||
а Esc повертає до тих самих панелей і курсора.
|
||||
- Над обома панелями працює спільний компонент рядка шляху. У Lavender кнопки
|
||||
навігації стоять ліворуч, а сегменти за шириною підпису розділяються знаком `›`.
|
||||
Назва поточної папки виділена напівжирним шрифтом і заокругленим фоном.
|
||||
|
||||
- У заголовку FTP- чи SFTP-папки клік по назві профілю відкриває збережені
|
||||
підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери
|
||||
@@ -735,6 +761,13 @@ Warning і початковий фокус на No.
|
||||
|
||||
- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання.
|
||||
- Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку.
|
||||
- Commands → Files MCP за замовчуванням зупинений. Start запускає MCP Streamable HTTP на `127.0.0.1` з випадковим портом. Клієнту потрібні Endpoint і `Authorization: Bearer <session token>`. Show token показує токен, Copy token копіює його. Stop і вихід із програми Files відкликають токен. Закриття діалогу залишає сервер активним, і меню показує Files MCP (running). Кожен старт створює новий токен.
|
||||
- MCP має три інструменти для читання. `get_panels` повертає стан поточних локальних панелей, курсор і сторінку записів. `search_files` фільтрує назви або відносні шляхи поточного списку чи наявних результатів Find. `get_file_metadata` повертає кешовані атрибути, тип, розмір і час зміни для вже показаного елемента. Для продовження списку клієнт передає `nextOffset` як `offset`. Вміст файлів, віддалені панелі, архіви й операції запису не входять до цього API. Запити з браузерним Origin відхиляються.
|
||||
- F1 відкриває вбудовану офлайн-довідку для панелі, вибраного пункту меню чи поточного діалогу. Пошук фільтрує теми за назвою й текстом. Esc закриває довідку та повертає фокус. У командному рядку з назвою команди F1 зберігає перехід до її довідки Windows. Загальна довідка також доступна через Commands → Help.
|
||||
- Options → Import JSON / Export JSON переносить вибрані групи збережених параметрів Files. Окремо доступні кольори панелей і порівняння разом зі стилями файлів, режими й компонування панелей та іменовані схеми клавіш. Перед заміною відмінних схем з однаковою назвою Files запитує підтвердження. Імпорт спочатку оновлює чернетку Options. Apply або OK зберігає зміни, Cancel відкидає їх. Формат містить лише ці параметри. Невідомі поля і групи пропускаються.
|
||||
- Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings.
|
||||
- Масштаб панелей, текстового Viewer, Editor, Markdown, термінала й порівняння зберігається окремо. У Commands є Panel appearance або Terminal appearance залежно від видимої області. Options у Viewer, Editor та Markdown і кнопка Appearance у порівнянні відкривають відповідну сторінку. Значення 100% використовує обраний базовий розмір шрифту.
|
||||
- Viewer і Editor підтримують колірну схему System (Windows). У Appearance → System themes можна призначити окремі палітри світлому й темному режимам Windows, включно із власними схемами. Rename scheme змінює назву власної схеми у списку, Viewer, Editor і призначеннях світлого та темного режимів.
|
||||
- Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення.
|
||||
- У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок.
|
||||
- Модальні діалоги редактора й переглядача використовують той самий шрифт, що й діалоги операцій Files. Розміри полів і кнопок враховують метрики цього шрифту.
|
||||
|
||||
+18
-2
@@ -35,7 +35,8 @@ retain their original reply formats.
|
||||
|
||||
- `capabilities` optionally takes a `peer`. It returns the broker `protocol`
|
||||
(2), `hostRevision`, and boolean `write`, `delete`, `move`,
|
||||
`revisionRead`, `onHostTransfer`, and `localEndpoint` fields. With no peer,
|
||||
`revisionRead`, `onHostTransfer`, `localEndpoint`, and optional
|
||||
`conflictPrompt` fields. With no peer,
|
||||
the fields describe the local broker and its grants. With a peer, the flags
|
||||
also account for its supported protocol. A peer with revision 0 still
|
||||
supports legacy browsing and downloading.
|
||||
@@ -57,7 +58,8 @@ retain their original reply formats.
|
||||
The recycle bin is subject to Windows availability on the paired host.
|
||||
- `transfer` takes `source` and `target` objects with a `peer` and `path`
|
||||
each, optional `move` (default false), and a `conflict` policy of `fail`
|
||||
(default), `skip`, or `replace`. Replace merges directories and replaces
|
||||
(default), `skip`, `replace`, or `ask` when `conflictPrompt` is available.
|
||||
Replace merges directories and replaces
|
||||
regular files after validating the destination revision. The broker
|
||||
allows at most one local endpoint, represented by `"peer": null`. For a
|
||||
local endpoint the client must open the pipe with Windows impersonation
|
||||
@@ -69,6 +71,12 @@ retain their original reply formats.
|
||||
final frame has `type: "complete"` and counts, or an error. Transfers
|
||||
on one paired computer use its own file service even across drives. The
|
||||
local pipe exchanges only control and status for transfers.
|
||||
- Ask merges directories and reports individual collisions in a JSON frame
|
||||
with `type: "conflict"`, target `path`, `incoming` and `existing` metadata
|
||||
(as in `stat`), and boolean `replaceable`. Respond with a JSON frame
|
||||
containing `decision: "replace"`, `"skip"`, or `"cancel"`. Send
|
||||
`decision: "wait"` at least once every five seconds while a prompt is open.
|
||||
Access is checked again after each reply and before publishing the file.
|
||||
- For a move, the copy phase finishes before source deletion begins.
|
||||
Skipped items remain at the source. Cancellation or failure can leave
|
||||
previously completed destination items. Failure during source cleanup
|
||||
@@ -131,6 +139,14 @@ a green dot when all online paired PCs are connected, and a red dot if the LAN
|
||||
worker stops. Hover over the icon to see the connection status and the connected
|
||||
count when only some paired PCs are connected.
|
||||
|
||||
If a held key or button blocks a handoff, the tray and **Settings → Computers**
|
||||
identify the PC and name the input when available. Starting with v0.8.13, the
|
||||
tray icon shows a steady amber exclamation mark until the input is released or a
|
||||
handoff succeeds.
|
||||
If Windows still sees an input as held, choose **Reset held keys and mouse buttons**
|
||||
in the tray menu on the PC named in the hint. Both computers need v0.8.12 or
|
||||
later for the source PC to display which input is held on the destination.
|
||||
|
||||
The source cursor is parked and hidden beneath a tiny no-activation window. A
|
||||
small banner identifies remote control; no full-screen layered bitmap is retained.
|
||||
The destination uses its own keyboard layout and runs its own hotkeys/snippets.
|
||||
|
||||
@@ -46,6 +46,26 @@ Saving Settings now merges independent resident/editor changes. If the same fiel
|
||||
changed on both sides, choose whether to retain your draft without closing the
|
||||
window. Declining preserves all draft edits. No export/import workaround is needed.
|
||||
|
||||
## Custom shortcuts
|
||||
|
||||
In **Settings → Shortcuts → Custom shortcuts**, choose **Add shortcut…** and
|
||||
record a global key combination. **Launch app** can start the program each time
|
||||
or activate its last-used window and start it if closed. **Send text to app**
|
||||
inserts text into an editable Windows **Edit** or **RichEdit** field selected
|
||||
with the KSwitcher crosshair. **Open URL** opens an HTTP or HTTPS address in the
|
||||
default browser, Chrome, or a browser executable you choose. For Chrome, you can
|
||||
pick a profile from its standard data folder. Use **Apply** or **Save** to activate the rule.
|
||||
Custom shortcuts are stored on this PC.
|
||||
|
||||
**Українською.** У **Settings → Shortcuts → Custom shortcuts** натисніть
|
||||
**Add shortcut…** і запишіть глобальну комбінацію клавіш. **Launch app** запускає
|
||||
програму щоразу або активує її останнє використане вікно й запускає програму,
|
||||
якщо вона закрита. **Send text to app** вставляє текст у поле Windows **Edit**
|
||||
або **RichEdit**, вибране прицілом KSwitcher. **Open URL** відкриває адресу HTTP
|
||||
або HTTPS у типовому браузері, Chrome чи іншому вказаному браузері. Для Chrome
|
||||
можна вибрати профіль зі стандартної папки даних. Застосуйте зміни кнопкою **Apply**
|
||||
або **Save**. Власні шорткати зберігаються на цьому ПК.
|
||||
|
||||
## Mouse buttons for applications
|
||||
|
||||
In **Settings → Mouse**, put the pointer over **Test mouse buttons here** and
|
||||
@@ -119,7 +139,7 @@ including Mouse, Manage computers and OpenBao. **Apply** keeps the current page
|
||||
**Save** closes Settings. With pending edits, **Cancel** or closing the window asks whether
|
||||
to discard them or keep editing. When there are no pending edits, **Close** exits without a prompt.
|
||||
If saving fails, the window stays open with your edits intact.
|
||||
Settings displays **No unsaved settings** when the draft matches the saved settings. If **Start with Windows** is enabled, **Save** remains available to recheck the autostart path.
|
||||
Settings displays **No unsaved settings** when the draft matches the saved settings. **Apply** and **Save** are disabled until you make another edit.
|
||||
Enable discovery and click **Save** on each PC before looking for peers. Enter the same code and
|
||||
click **Pair**, then **Apply** or **Save**, on both PCs. Use **Apply** to watch the target and
|
||||
remaining wait time without closing Settings.
|
||||
@@ -170,7 +190,7 @@ the task runs in the signed-in user's interactive session, including on battery
|
||||
With both options enabled, opening the regular `KSwitcher.exe` after exiting a development
|
||||
build requests administrator approval if needed. Development builds keep their current launch privileges.
|
||||
Disabling the administrator option restores ordinary per-user startup. Disabling startup stops
|
||||
future automatic launches. On launch and after clicking **Save** in Settings, KSwitcher checks whether the
|
||||
future automatic launches. On launch and after committing edits with **Apply** or **Save**, KSwitcher checks whether the
|
||||
enabled autostart entry still points to its current location. If the previous file is missing and
|
||||
KSwitcher has the required privileges, it updates the path automatically. If the previous path may
|
||||
still be in use or the repair requires administrator approval, KSwitcher shows both paths and asks
|
||||
@@ -440,9 +460,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 +482,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 +500,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 +1064,16 @@ embedded in KSwitcher.Files.exe.
|
||||
.\tests\configuration.ps1 # Separate-process settings tests; close KSwitcher first
|
||||
```
|
||||
|
||||
To check snippet suggestions in a WebView2 app, focus a blank editable field and
|
||||
run `KSwitcherIntegration.exe --snippet-external-editor` without changing the
|
||||
foreground window. The test types `;`, checks that the popup opens without
|
||||
stealing focus, dismisses it, and removes the test character. In Dirlume, repeat
|
||||
in the Command line, the terminal at an idle prompt, and the text editor. Use
|
||||
`--insert` as the second argument to test Tab insertion in a blank text field.
|
||||
With a Dirlume build that supports KSwitcher terminal insertion, use
|
||||
`--terminal-insert` at a blank shell prompt and check that `snippet test`
|
||||
appears as an editable draft. Clear that draft without submitting it.
|
||||
|
||||
`-Test` also checks remote/own input separation, hidden Settings layout and scrolling, and updater
|
||||
package validation, file preservation and rollback in temporary fixture directories. It does not
|
||||
replace a running installation. Optional read-only network checks:
|
||||
|
||||
@@ -1,5 +1,129 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.8.13 — 2026-12-01
|
||||
|
||||
**Tray warning for LAN cursor handoff.** A steady amber badge with an exclamation mark appears when a held key or mouse button blocks a cursor handoff. Hover over the tray icon to see the affected PC and, when known, the held key or button. The normal connection indicator returns when the input is released or a handoff succeeds.
|
||||
|
||||
**Українською.** Якщо затиснута клавіша чи кнопка миші блокує перехід курсора між ПК, у треї з’являється сталий бурштиновий індикатор зі знаком оклику. Наведіть курсор на значок, щоб побачити, на якому ПК виникло блокування та що саме затиснуто, якщо це вдалося визначити. Після відпускання вводу або успішного переходу повертається звичайний індикатор з’єднання.
|
||||
|
||||
## v0.8.12 — 2026-12-01
|
||||
|
||||
**LAN cursor handoff.** The tray and **Settings → Computers** identify the computer and, when known, the key or mouse button holding up the handoff. If Windows still sees an input as held after you release it, choose **Reset held keys and mouse buttons** from the tray menu on that PC. Update both computers to see which input on the other PC is blocking the handoff.
|
||||
|
||||
**Українською.** Трей і **Налаштування → Комп’ютери** показують, на якому ПК заблоковано перехід курсора та яка клавіша або кнопка миші його блокує, якщо її вдалося визначити. Якщо Windows продовжує вважати ввід затиснутим після відпускання, виберіть **«Скинути затиснуті клавіші й кнопки миші»** у треї на цьому ПК. Оновіть обидва комп’ютери, щоб бачити, який ввід на іншому ПК блокує перехід.
|
||||
|
||||
## v0.8.11 — 2026-11-30
|
||||
|
||||
**Open URL** is a new action in **Settings → Shortcuts → Custom shortcuts**. Open an HTTP or HTTPS address in the default browser, Google Chrome, or another browser by picking its executable. Choose a Chrome profile from its standard data folder if needed. The shortcut editor uses a white content area and the same tinted footer style as Settings.
|
||||
|
||||
**Українською.** У **Settings → Shortcuts → Custom shortcuts** з’явилася дія **Open URL**. Відкривайте адреси HTTP або HTTPS у типовому браузері, Google Chrome або іншому браузері, вказавши його `.exe`. Для Chrome за потреби виберіть профіль зі стандартної папки даних. Редактор шорткатів має білу область вмісту й тонований футер у стилі Settings.
|
||||
|
||||
## v0.8.10 — 2026-11-30
|
||||
|
||||
After **Apply** saves your changes, Settings disables **Apply** and **Save** and offers **Close**, including when **Start with Windows** is enabled. A new edit enables the saving controls again.
|
||||
|
||||
Application launch actions work through Windows Explorer when KSwitcher runs as administrator. Launched programs open with their executable folder as the working directory.
|
||||
|
||||
**Українською.** Після збереження змін через **Apply** у налаштуваннях доступна кнопка **Close**, а **Apply** і **Save** вимкнені навіть за ввімкненого автозапуску Windows. Наступна зміна знову робить кнопки збереження доступними.
|
||||
|
||||
Дії запуску програм працюють через Провідник Windows, коли KSwitcher запущено від адміністратора. Робоча папка запущеної програми відповідає папці її виконуваного файлу.
|
||||
|
||||
## v0.8.9 — 2026-11-30
|
||||
|
||||
- **Custom shortcuts.** Open **Settings → Shortcuts → Custom shortcuts** to add global shortcuts. Launch an executable each time or activate its last-used window and launch it if closed. Select an open program with the KSwitcher crosshair or use **Browse**.
|
||||
- **Text insertion.** Drag the same crosshair onto an editable Windows **Edit** or **RichEdit** field and enter the text to insert. Multiline fields accept multiline text. Custom shortcuts are saved on this PC.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Власні шорткати.** Відкрийте **Settings → Shortcuts → Custom shortcuts**, щоб додати глобальні комбінації. Шорткат може щоразу запускати програму або активувати її останнє використане вікно й запускати програму, якщо вона закрита. Виберіть відкриту програму прицілом KSwitcher або скористайтеся кнопкою **Browse**.
|
||||
- **Вставлення тексту.** Перетягніть той самий приціл на доступне для редагування поле Windows **Edit** або **RichEdit** і введіть текст. Багаторядкові поля приймають багаторядковий текст. Власні шорткати зберігаються на цьому ПК.
|
||||
|
||||
## v0.8.8 — 2026-11-28
|
||||
|
||||
In Lavender, **Change drive**, command menus, panel search and command suggestions use a light lavender background and a contrasting purple outline, 2 pixels thick at 100% scaling.
|
||||
|
||||
**Українською.** У Lavender меню **Change drive**, меню команд, пошук панелі й підказки команд мають світло-лавандове тло та контрастну фіолетову рамку завтовшки 2 пікселі за масштабу 100%.
|
||||
|
||||
## v0.8.7 — 2026-11-28
|
||||
|
||||
In **Change drive** (Alt+F1 or Alt+F2), press **1** for FTP, **2** for SFTP, **3** for SMB or **4** for Recent folders. The scroll bar has its own space so it does not clip the free-space column.
|
||||
|
||||
**Українською.** У **Change drive** (Alt+F1 або Alt+F2) клавіші **1**, **2**, **3** і **4** відкривають FTP, SFTP, SMB і нещодавні папки відповідно. Для смуги прокрутки відведено окреме місце, щоб не обрізати значення вільного місця.
|
||||
|
||||
## v0.8.6 — 2026-11-28
|
||||
|
||||
- **Updater.** Checking for updates requests only the latest stable Gitea release, avoiding timeouts while loading the release history. If the older updater still times out, install this release using the complete portable ZIP.
|
||||
- **Layout conversion.** Recent text selection can recover after delayed editor selection in apps such as Claude. When several layouts produce the same recent text, KSwitcher prefers the layout used to type it.
|
||||
- **Files.** Open **Space Analyzer** from **Left** or **Right** to scan in that pane. **Logical size** and **Size on disk** apply to the tree and charts. Local NTFS folder sizes use batched directory reads and parallel traversal.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Оновлення.** KSwitcher запитує в Gitea лише останній стабільний реліз. Це усуває тайм-аут під час завантаження історії релізів. Якщо старий оновлювач і далі не відповідає, встановіть цей реліз із повного портативного ZIP.
|
||||
- **Перетворення розкладки.** KSwitcher може відновити виділення нещодавнього тексту в редакторах із затримкою виділення, зокрема в Claude. Якщо кілька розкладок дають той самий набраний текст, KSwitcher віддає перевагу розкладці, у якій його набрано.
|
||||
- **Files.** **Space Analyzer** у меню **Left** або **Right** запускає аналіз у вибраній панелі. **Logical size** і **Size on disk** діють у дереві й на графіках. Підрахунок розміру папок на NTFS використовує пакетне читання й паралельний обхід.
|
||||
|
||||
## v0.8.5 — 2026-11-28
|
||||
|
||||
- **Snippets in Dirlume.** Type `;` to see matching KSwitcher snippets in the command line, editor, other editable fields and embedded terminal. A compatible Dirlume build accepts a single-line snippet with **Tab** at a supported shell prompt and leaves the command editable. Terminal insertion excludes key actions and pauses.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Сніпети в Dirlume.** Введіть `;`, щоб побачити підказки KSwitcher у командному рядку, редакторі, інших текстових полях і вбудованому терміналі. У сумісній збірці Dirlume клавіша **Tab** вставляє однорядковий сніпет у рядок підтримуваної оболонки й залишає команду доступною для редагування. Термінал не вставляє сніпети з клавіатурними діями або паузами.
|
||||
|
||||
## v0.8.4 — 2026-11-27
|
||||
|
||||
- **Settings.** Open **Languages → Languages for a chat** in the Settings tree to search for a chat and choose its keyboard layouts. Save changes with **Apply** or **Save**.
|
||||
- **Trusted LAN clients.** Clients such as Dirlume can ask how to handle individual file conflicts during copy or move. When supported, choose to replace, skip or cancel.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Налаштування.** Відкрийте **Languages → Languages for a chat** у дереві Settings, щоб знайти чат і вибрати його розкладки. Застосуйте зміни кнопкою **Apply** або **Save**.
|
||||
- **Довірені клієнти LAN.** Клієнти на кшталт Dirlume можуть запитувати, як обробити окремі конфлікти файлів під час копіювання або переміщення. Якщо клієнт підтримує цю можливість, виберіть заміну, пропуск або скасування.
|
||||
|
||||
## v0.8.3 — 2026-11-26
|
||||
|
||||
- **Files.** Lavender now shows compact path segments with chevrons above both panes. The current folder has a rounded highlight. Click an ancestor to open it, the current folder to edit the path, or an ellipsis to reveal hidden folders.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **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.
|
||||
- **Storage and transfers.** Inspect folder sizes and disk usage with the tree, treemap and sunburst. Browse, extract, create and update ZIP and 7z archives. Copy and Move provide masks, multiple destinations and preservation options.
|
||||
- **Viewing and editing.** Quick View supports text, Markdown, offline HTML, symbolic binary and images. Use Hex Viewer, line bookmarks, unified comparison, change-block application and Undo. Edit PNG/JPEG images with rotate and crop, and opt in to restoring local document windows after a restart.
|
||||
- **Connections and Windows tools.** Browse saved FTP, SFTP and SMB connections, use the SSH terminal and jump hosts, inspect properties and locking processes, review and stage Git changes, commit the reviewed index, and inspect environment variables.
|
||||
- **Customize and automate.** Use named keyboard schemes, separate area scales, Windows light and dark palettes, selective JSON settings transfer, offline F1 help, and the Files log. The optional loopback MCP exposes pane state, existing Find results and cached metadata with a per-session token.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Панелі та пошук.** Рекурсивний пошук у локальних, FTP, SFTP і спарених LAN-панелях. Результати підтримують файлові операції. Доступні навігаційний шлях, історія, нещодавні папки, сортування, фільтри, колонки й налаштування панелей. Файловий буфер і перетягування працюють із Windows.
|
||||
- **Сховище й перенесення.** Дерево, карта та сонячна діаграма показують використання диска. ZIP і 7z можна переглядати, розпаковувати, створювати й оновлювати. Копіювання й переміщення підтримують маски, кілька папок призначення та збереження атрибутів за вибором.
|
||||
- **Перегляд і редагування.** Quick View підтримує текст, Markdown, офлайн-HTML, символьний перегляд бінарних даних і зображення. Доступні Hex Viewer, закладки рядків, об’єднане порівняння, застосування блоків змін і Undo. PNG/JPEG можна повертати й обрізати. Відновлення локальних вікон після перезапуску вмикається в Options.
|
||||
- **Підключення та інструменти Windows.** Збережені підключення FTP, SFTP і SMB, SSH-термінал і проміжні вузли, властивості файлів, процеси, що їх блокують, Git Changes із підготовкою та комітом змін, перегляд і редагування змінних середовища.
|
||||
- **Налаштування й автоматизація.** Іменовані схеми клавіш, окремий масштаб областей, світла й темна палітри Windows, вибіркове перенесення налаштувань через JSON, офлайн-довідка F1 і журнал Files. Опційний локальний MCP читає стан панелей, наявні результати Find і кешовані метадані за токеном сесії.
|
||||
|
||||
## v0.7.4 — 2026-11-25
|
||||
|
||||
- **Settings → Sync → Google Drive** supports automatic synchronization and a dated list of manual backups. Only one automatic provider is active per PC. Restore a selected backup into the Settings draft and review it before pressing **Apply** or **Save**.
|
||||
|
||||
@@ -1 +1 @@
|
||||
0209951cbe8c5a202dba12a807895ce7146dc6640f96704f6a4aa9afaa4fd3af KSwitcher-win-x64.zip
|
||||
daf147ac8e63db06c9afaa521aa4187e2bae511fae15e117543ac5a8b2b157e9 KSwitcher-win-x64.zip
|
||||
+92
-77
@@ -1,166 +1,181 @@
|
||||
{
|
||||
"version": "0.7.4",
|
||||
"schema": 1,
|
||||
"version": "0.8.13",
|
||||
"files": [
|
||||
{
|
||||
"size": 3082752,
|
||||
"sha256": "31a41c6ecc3387fc9f2b3f228ed64fa916d723654c02dc19bbbb558f94def4b8",
|
||||
"path": "KSwitcher.exe"
|
||||
"sha256": "d261aede51439e4ed185753aea9cbf44764471e7fadf779b666caa624075f665",
|
||||
"path": "KSwitcher.exe",
|
||||
"size": 3312640
|
||||
},
|
||||
{
|
||||
"size": 2832384,
|
||||
"sha256": "b993c050a96215aa63be97e9f05764ead13fcaf4b68fbb99f3d2f9a7d49a629a",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
"sha256": "b26b62a2710ed2e8c714b6bca4e5f2e9ae7d55a15cd85de3b4d19fab1cb77a84",
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"size": 2897408
|
||||
},
|
||||
{
|
||||
"size": 3187712,
|
||||
"sha256": "eff5921b9067e0f4805c83d3cea10ddaa32b0b4e29f408b71b1004f78754afb9",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
"sha256": "631805b3928e921d30ad70e542b0985b0e430006455ece81f64711cfe215d432",
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"size": 3209216
|
||||
},
|
||||
{
|
||||
"size": 4409344,
|
||||
"sha256": "569d016d1eff9519cd33aa848723cea0365cbebe9333ed390245d098c4074d8e",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
"sha256": "9dff79e1891be3e911dff1f06ad7162eba8a1721d93d5e4f96c7f0be41179a55",
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"size": 6039040
|
||||
},
|
||||
{
|
||||
"size": 194912,
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"path": "WebView2Loader.dll"
|
||||
"path": "WebView2Loader.dll",
|
||||
"size": 194912
|
||||
},
|
||||
{
|
||||
"size": 1103,
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"path": "terminal/addon-fit-LICENSE.txt"
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"size": 1103
|
||||
},
|
||||
{
|
||||
"size": 1521,
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"path": "terminal/addon-fit.js"
|
||||
"path": "terminal/addon-fit.js",
|
||||
"size": 1521
|
||||
},
|
||||
{
|
||||
"size": 527,
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"path": "terminal/index.html"
|
||||
"path": "terminal/index.html",
|
||||
"size": 527
|
||||
},
|
||||
{
|
||||
"size": 1073,
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"path": "terminal/markdown-it-LICENSE.txt"
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"size": 1073
|
||||
},
|
||||
{
|
||||
"size": 100786,
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"path": "terminal/markdown-it.js"
|
||||
"path": "terminal/markdown-it.js",
|
||||
"size": 100786
|
||||
},
|
||||
{
|
||||
"size": 3599,
|
||||
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
|
||||
"path": "terminal/markdown.html"
|
||||
"sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2",
|
||||
"path": "terminal/markdown.html",
|
||||
"size": 3800
|
||||
},
|
||||
{
|
||||
"size": 17575,
|
||||
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
|
||||
"path": "terminal/markdown.js"
|
||||
"sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96",
|
||||
"path": "terminal/markdown.js",
|
||||
"size": 18721
|
||||
},
|
||||
{
|
||||
"size": 1089,
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"path": "terminal/mermaid-LICENSE.txt"
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"size": 1089
|
||||
},
|
||||
{
|
||||
"size": 5537838,
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"path": "terminal/mermaid.js"
|
||||
"path": "terminal/mermaid.js",
|
||||
"size": 5537838
|
||||
},
|
||||
{
|
||||
"size": 5065,
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
|
||||
"path": "terminal/terminal.js"
|
||||
"sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7",
|
||||
"path": "terminal/terminal.js",
|
||||
"size": 6627
|
||||
},
|
||||
{
|
||||
"size": 1261,
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"path": "terminal/xterm-LICENSE.txt"
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"size": 1261
|
||||
},
|
||||
{
|
||||
"size": 7112,
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"path": "terminal/xterm.css"
|
||||
"path": "terminal/xterm.css",
|
||||
"size": 7112
|
||||
},
|
||||
{
|
||||
"size": 488663,
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"path": "terminal/xterm.js"
|
||||
"path": "terminal/xterm.js",
|
||||
"size": 488663
|
||||
},
|
||||
{
|
||||
"size": 4401,
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"path": "LICENSE"
|
||||
"path": "LICENSE",
|
||||
"size": 4401
|
||||
},
|
||||
{
|
||||
"size": 1096,
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"path": "json-LICENSE.txt"
|
||||
"path": "json-LICENSE.txt",
|
||||
"size": 1096
|
||||
},
|
||||
{
|
||||
"size": 883,
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"path": "files-text-license.txt"
|
||||
"path": "files-text-license.txt",
|
||||
"size": 883
|
||||
},
|
||||
{
|
||||
"size": 105515,
|
||||
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01",
|
||||
"path": "README.md"
|
||||
"sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d",
|
||||
"path": "files-archive-license.txt",
|
||||
"size": 4990
|
||||
},
|
||||
{
|
||||
"size": 12804,
|
||||
"sha256": "f5bfc48e44af14dd6c45f56f689b4034ef1f7bdaca02f9d15ebc32af387366cf",
|
||||
"path": "LAN-PREVIEW.md"
|
||||
"sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4",
|
||||
"path": "files-image-license.txt",
|
||||
"size": 3044
|
||||
},
|
||||
{
|
||||
"sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594",
|
||||
"path": "files-sftp-license.txt",
|
||||
"size": 2064
|
||||
},
|
||||
{
|
||||
"sha256": "d9a53cb9190dfde2415df54c131b8bd293efbd627014a4e0976cea717ae855ae",
|
||||
"path": "README.md",
|
||||
"size": 108205
|
||||
},
|
||||
{
|
||||
"sha256": "171e48b9a7f1d772a6534700786fef295ead5b1cab6c6792a306723e2d8bf39b",
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"size": 17750
|
||||
},
|
||||
{
|
||||
"size": 732485,
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"path": "dictionaries/en.txt"
|
||||
"path": "dictionaries/en.txt",
|
||||
"size": 732485
|
||||
},
|
||||
{
|
||||
"size": 20566,
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"size": 20566
|
||||
},
|
||||
{
|
||||
"size": 2265,
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"path": "dictionaries/README.md"
|
||||
"path": "dictionaries/README.md",
|
||||
"size": 2265
|
||||
},
|
||||
{
|
||||
"size": 1109134,
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"path": "dictionaries/ru.txt"
|
||||
"path": "dictionaries/ru.txt",
|
||||
"size": 1109134
|
||||
},
|
||||
{
|
||||
"size": 1280,
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"path": "dictionaries/sources.json"
|
||||
"path": "dictionaries/sources.json",
|
||||
"size": 1280
|
||||
},
|
||||
{
|
||||
"size": 940799,
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"path": "dictionaries/uk.txt"
|
||||
"path": "dictionaries/uk.txt",
|
||||
"size": 940799
|
||||
},
|
||||
{
|
||||
"size": 993,
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"path": "tools/README.txt"
|
||||
"path": "tools/README.txt",
|
||||
"size": 993
|
||||
},
|
||||
{
|
||||
"size": 133120,
|
||||
"sha256": "ba891b6cc5d35d26520fa9ad34e136124e90ed10e0cff2f25dedadd0b48fb88e",
|
||||
"path": "tools/StayHere.exe"
|
||||
"sha256": "73b8f40a3b5e9c855f47bd7014b61902ead707c6eb19729903d01edfa546f8cf",
|
||||
"path": "tools/StayHere.exe",
|
||||
"size": 133120
|
||||
},
|
||||
{
|
||||
"size": 2796,
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"path": "tools/StayHere-README.md"
|
||||
"path": "tools/StayHere-README.md",
|
||||
"size": 2796
|
||||
}
|
||||
]
|
||||
],
|
||||
"schema": 1
|
||||
}
|
||||
@@ -16,7 +16,7 @@ function(build_files_webp)
|
||||
endfunction()
|
||||
build_files_webp()
|
||||
|
||||
add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_view.cpp)
|
||||
add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_edit.cpp src/files_image_view.cpp)
|
||||
target_compile_definitions(KSwitcherFilesImage PRIVATE NOMINMAX UNICODE _UNICODE _WIN32_WINNT=0x0A00)
|
||||
target_link_libraries(KSwitcherFilesImage PRIVATE webpdemux windowscodecs msimg32 ole32)
|
||||
if(MSVC)
|
||||
|
||||
+3
-3
@@ -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,7,4,0
|
||||
PRODUCTVERSION 0,7,4,0
|
||||
FILEVERSION 0,8,13,0
|
||||
PRODUCTVERSION 0,8,13,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.7.4"
|
||||
VALUE "FileVersion", "0.8.13"
|
||||
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
|
||||
+133
-40
@@ -156,12 +156,101 @@ BEGIN
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 162, 44, 50, 14
|
||||
END
|
||||
|
||||
615 DIALOGEX 0, 0, 371, 214
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Keyboard shortcuts"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "Active &scheme", -1, 9, 9, 160, 11
|
||||
COMBOBOX 610, 9, 22, 194, 120, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "&Copy as…", 611, 211, 22, 69, 15
|
||||
PUSHBUTTON "Rese&t scheme", 612, 288, 22, 74, 15
|
||||
LTEXT "&Command", -1, 9, 49, 166, 11
|
||||
LISTBOX 613, 9, 63, 166, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
|
||||
LTEXT "", 614, 184, 49, 178, 11
|
||||
LISTBOX 615, 184, 63, 178, 80, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
|
||||
CONTROL "", 616, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 184, 152, 74, 15
|
||||
PUSHBUTTON "&Add", 617, 264, 152, 44, 15
|
||||
PUSHBUTTON "&Remove", 618, 314, 152, 48, 15
|
||||
PUSHBUTTON "Make &primary", 619, 184, 172, 75, 15
|
||||
DEFPUSHBUTTON "OK", IDOK, 250, 192, 52, 15
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 310, 192, 52, 15
|
||||
END
|
||||
|
||||
616 DIALOGEX 0, 0, 233, 73
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Copy keyboard scheme"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "Scheme &name", -1, 9, 9, 214, 11
|
||||
EDITTEXT 620, 9, 23, 215, 15, ES_AUTOHSCROLL
|
||||
DEFPUSHBUTTON "Copy", IDOK, 112, 49, 52, 15
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 172, 49, 52, 15
|
||||
END
|
||||
|
||||
617 DIALOGEX 0, 0, 240, 124
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Files settings"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "", 624, 9, 9, 222, 24
|
||||
AUTOCHECKBOX "Colors and file styles", 621, 9, 39, 222, 13
|
||||
AUTOCHECKBOX "Panel modes and layout", 622, 9, 55, 222, 13
|
||||
AUTOCHECKBOX "Keyboard schemes", 623, 9, 71, 222, 13
|
||||
DEFPUSHBUTTON "Load", IDOK, 118, 99, 52, 15
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 179, 99, 52, 15
|
||||
END
|
||||
|
||||
618 DIALOGEX 0, 0, 468, 242
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "KSwitcher Files Help"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "&Search help", -1, 9, 9, 112, 11
|
||||
EDITTEXT 670, 9, 23, 145, 15, ES_AUTOHSCROLL
|
||||
LISTBOX 671, 9, 45, 145, 160, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
|
||||
LTEXT "", 672, 165, 23, 294, 15
|
||||
EDITTEXT 673, 165, 45, 294, 160, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL
|
||||
DEFPUSHBUTTON "&Close", IDOK, 403, 216, 56, 16
|
||||
END
|
||||
|
||||
619 DIALOGEX 0, 0, 435, 211
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Files log"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "&Log", -1, 9, 12, 40, 11
|
||||
COMBOBOX 680, 51, 9, 115, 70, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "", 681, 9, 31, 415, 28
|
||||
LISTBOX 682, 9, 62, 417, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP
|
||||
PUSHBUTTON "&Copy selected", 683, 9, 187, 90, 15
|
||||
PUSHBUTTON "&Refresh", 684, 107, 187, 66, 15
|
||||
DEFPUSHBUTTON "Close", IDOK, 370, 187, 56, 15
|
||||
END
|
||||
|
||||
620 DIALOGEX 0, 0, 395, 152
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Files MCP"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "", 690, 9, 9, 376, 12
|
||||
LTEXT "Read-only access to local panes, Find results and file metadata.", -1, 9, 26, 376, 13
|
||||
LTEXT "&Endpoint", -1, 9, 49, 72, 12
|
||||
EDITTEXT 691, 83, 46, 302, 15, ES_READONLY | ES_AUTOHSCROLL
|
||||
LTEXT "Session &token", -1, 9, 72, 72, 12
|
||||
EDITTEXT 692, 83, 69, 302, 15, ES_READONLY | ES_AUTOHSCROLL
|
||||
AUTOCHECKBOX "Sho&w token", 694, 83, 94, 81, 13
|
||||
PUSHBUTTON "&Copy token", 695, 169, 91, 72, 16
|
||||
PUSHBUTTON "&Start", 693, 9, 126, 64, 16
|
||||
DEFPUSHBUTTON "Close", IDOK, 329, 126, 56, 16
|
||||
END
|
||||
|
||||
101 DIALOGEX 0, 0, 397, 310
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN
|
||||
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
|
||||
@@ -187,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
|
||||
@@ -194,10 +285,7 @@ BEGIN
|
||||
COMBOBOX 305, 311, 51, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "&Row text padding (characters)", 306, 131, 77, 173, 12
|
||||
COMBOBOX 307, 311, 74, 56, 76, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "Previous command", 320, 131, 30, 120, 12
|
||||
CONTROL "", 321, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 27, 110, 15
|
||||
LTEXT "Open command history", 322, 131, 53, 120, 12
|
||||
CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15
|
||||
PUSHBUTTON "&Keyboard shortcuts…", 321, 131, 30, 127, 15
|
||||
AUTOCHECKBOX "Allow &paired PCs to run PowerShell commands here", 370, 131, 79, 250, 14
|
||||
AUTOCHECKBOX "Allow paired PCs to &hibernate this PC", 371, 131, 95, 250, 14
|
||||
AUTOCHECKBOX "Allow paired PCs to &update KSwitcher here", 372, 131, 111, 250, 14
|
||||
@@ -236,6 +324,8 @@ BEGIN
|
||||
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
|
||||
LTEXT "", 367, 345, 184, 45, 12
|
||||
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
|
||||
PUSHBUTTON "Re&name scheme…", 534, 257, 163, 125, 15
|
||||
AUTOCHECKBOX "Restore local Viewer and Editor windows after restart", 524, 131, 210, 250, 13
|
||||
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
|
||||
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12
|
||||
@@ -249,8 +339,16 @@ BEGIN
|
||||
COMBOBOX 411, 250, 76, 132, 126, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "Change color…", 412, 250, 97, 82, 15
|
||||
LTEXT "", 413, 338, 100, 45, 12
|
||||
LTEXT "Compare files &shortcut", 414, 131, 130, 117, 12
|
||||
CONTROL "", 415, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 250, 127, 132, 15
|
||||
PUSHBUTTON "&Keyboard shortcuts…", 415, 131, 127, 127, 15
|
||||
LTEXT "&Scale", 528, 131, 235, 118, 12
|
||||
COMBOBOX 529, 257, 232, 125, 98, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "&Light mode palette", 530, 131, 32, 118, 12
|
||||
COMBOBOX 531, 250, 29, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "&Dark mode palette", 532, 131, 56, 118, 12
|
||||
COMBOBOX 533, 250, 53, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "Viewer and Editor use these palettes when Color scheme is set to System (Windows).", 535, 131, 80, 250, 28
|
||||
PUSHBUTTON "&Import JSON…", 525, 8, 289, 70, 14
|
||||
PUSHBUTTON "&Export JSON…", 526, 84, 289, 70, 14
|
||||
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
|
||||
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
|
||||
@@ -479,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
|
||||
@@ -527,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"
|
||||
@@ -693,3 +767,22 @@ BEGIN
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 161, 86, 16
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 200, 161, 86, 16
|
||||
END
|
||||
|
||||
130 DIALOGEX 0, 0, 329, 119
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
CAPTION "Crop image"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 650, 14, 15, 301, 12
|
||||
LTEXT "&X", 656, 14, 35, 58, 14, SS_CENTERIMAGE
|
||||
FAR_EDIT(651, ES_NUMBER, 75, 33, 70, 18)
|
||||
LTEXT "&Y", 657, 173, 35, 58, 14, SS_CENTERIMAGE
|
||||
FAR_EDIT(652, ES_NUMBER, 244, 33, 70, 18)
|
||||
LTEXT "&Width", 658, 14, 60, 58, 14, SS_CENTERIMAGE
|
||||
FAR_EDIT(653, ES_NUMBER, 75, 58, 70, 18)
|
||||
LTEXT "&Height", 659, 173, 60, 62, 14, SS_CENTERIMAGE
|
||||
FAR_EDIT(654, ES_NUMBER, 244, 58, 70, 18)
|
||||
LTEXT "", 655, 10, 86, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Crop", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 78, 94, 83, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 168, 94, 83, 17
|
||||
END
|
||||
@@ -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.
|
||||
@@ -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"
|
||||
@@ -14,3 +14,4 @@
|
||||
#define IDR_HELP_MANUAL 601
|
||||
#define IDR_HELP_FILES 602
|
||||
#define IDR_HELP_COMPUTERS 603
|
||||
#define IDR_HELP_RELEASES 604
|
||||
@@ -27,7 +27,7 @@ nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px;
|
||||
::highlight(markdown-search-active) { background: #ffab45; color: #171717; }
|
||||
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
|
||||
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
|
||||
a { color: LinkText; }
|
||||
a[href] { color: LinkText; }
|
||||
pre, table, figure { overflow: auto; }
|
||||
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
|
||||
pre { padding: .75em; }
|
||||
|
||||
@@ -73,7 +73,7 @@ markdown.renderer.rules.image = (tokens, i) => {
|
||||
|
||||
const htmlTags = new Set(`a abbr address article aside b blockquote br caption code col colgroup dd del
|
||||
details div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hr i img input ins kbd li
|
||||
mark ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
|
||||
main mark nav ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
|
||||
tr u ul var wbr`.split(/\s+/));
|
||||
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
|
||||
const tagAttributes = {
|
||||
@@ -88,21 +88,25 @@ function relativeResource(path) {
|
||||
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
|
||||
}
|
||||
|
||||
function renderContent(text, canSave) {
|
||||
function renderContent(text, canSave, html) {
|
||||
// Parse in an inert template and allow only document markup before attaching it to the preview.
|
||||
const template = document.createElement('template');
|
||||
const taskKey = [...crypto.getRandomValues(new Uint32Array(4))].join('-');
|
||||
taskMarkers = new WeakMap();
|
||||
pendingTask = undefined;
|
||||
template.innerHTML = markdown.render(text, { taskKey });
|
||||
template.innerHTML = html ? text : markdown.render(text, { taskKey });
|
||||
for (const element of template.content.querySelectorAll('*')) {
|
||||
const tag = element.localName;
|
||||
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
|
||||
(tag === 'input' && element.type !== 'checkbox')) {
|
||||
(tag === 'input' && (html || element.type !== 'checkbox'))) {
|
||||
element.remove();
|
||||
continue;
|
||||
}
|
||||
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
|
||||
const imagePath = !html && tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
|
||||
if (html && tag === 'img') {
|
||||
element.replaceWith(document.createTextNode(element.getAttribute('alt') ?? ''));
|
||||
continue;
|
||||
}
|
||||
const task = tag === 'input' && element.getAttribute('data-task');
|
||||
if (task && task.startsWith(taskKey + ':')) {
|
||||
const [, line, column] = task.split(':');
|
||||
@@ -112,7 +116,8 @@ function renderContent(text, canSave) {
|
||||
const styles = element.hasAttribute('style')
|
||||
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
|
||||
for (const { name } of [...element.attributes]) {
|
||||
if (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name)) element.removeAttribute(name);
|
||||
const blockedInHtml = html && (name === 'id' || name === 'class' || name === 'href');
|
||||
if (blockedInHtml || (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name))) element.removeAttribute(name);
|
||||
}
|
||||
for (const [name, value] of styles) {
|
||||
if (value) element.style.setProperty(name, value);
|
||||
@@ -247,7 +252,7 @@ searchPrevious.addEventListener('click', () => stepSearch(-1));
|
||||
searchNext.addEventListener('click', () => stepSearch(1));
|
||||
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
|
||||
|
||||
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact }) {
|
||||
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact, html }) {
|
||||
const current = ++generation;
|
||||
if (keepPosition) scroll = window.scrollY;
|
||||
else closeSearch();
|
||||
@@ -255,7 +260,14 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
|
||||
document.title = title;
|
||||
document.documentElement.classList.toggle('quick-view', Boolean(compact));
|
||||
previewRevision = revision;
|
||||
renderContent(text, canSave);
|
||||
renderContent(text, canSave, html);
|
||||
images = [];
|
||||
if (html) {
|
||||
window.scrollTo(0, 0);
|
||||
document.documentElement.classList.add('rendered');
|
||||
send('rendered', { revision });
|
||||
return;
|
||||
}
|
||||
const headings = new Set();
|
||||
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
|
||||
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
||||
@@ -343,6 +355,17 @@ document.addEventListener('keydown', event => {
|
||||
}
|
||||
});
|
||||
|
||||
let scrollTimer;
|
||||
window.addEventListener('scroll', () => {
|
||||
if (document.documentElement.classList.contains('quick-view')) return;
|
||||
clearTimeout(scrollTimer);
|
||||
const revision = previewRevision;
|
||||
scrollTimer = setTimeout(() => {
|
||||
if (revision === previewRevision && document.documentElement.classList.contains('rendered'))
|
||||
send('scroll', { revision, top: Math.round(window.scrollY) });
|
||||
}, 120);
|
||||
}, { passive: true });
|
||||
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
const message = JSON.parse(data);
|
||||
if (message.action === 'clear') {
|
||||
|
||||
@@ -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)." }
|
||||
|
||||
+411
-74
@@ -4,6 +4,7 @@
|
||||
#include "../resources/resource.h"
|
||||
#include "ocr.h"
|
||||
#include "lan_clipboard_image.h"
|
||||
#include "lan_input.h"
|
||||
#include "lan_files.h"
|
||||
#include "configuration.h"
|
||||
#include "google_drive.h"
|
||||
@@ -45,26 +46,107 @@ GUITHREADINFO snippetGuiInfo(HWND target)
|
||||
return info;
|
||||
}
|
||||
|
||||
std::optional<RECT> accessibleSnippetCaret(HWND target)
|
||||
using Microsoft::WRL::ComPtr;
|
||||
constexpr std::wstring_view terminalSnippetTicketPrefix = L"dirlume-terminal-snippet-v1:";
|
||||
|
||||
bool snippetElementClass(IUIAutomationElement *element, std::wstring_view name)
|
||||
{
|
||||
BSTR className{};
|
||||
const bool matches = SUCCEEDED(element->get_CurrentClassName(&className)) && className && className == name;
|
||||
SysFreeString(className);
|
||||
return matches;
|
||||
}
|
||||
|
||||
ComPtr<IUIAutomationElement> focusedSnippetElement(IUIAutomation2 *automation, HWND target)
|
||||
{
|
||||
using Microsoft::WRL::ComPtr;
|
||||
ComPtr<IUIAutomation2> automation;
|
||||
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER,
|
||||
IID_IUIAutomation2, reinterpret_cast<void **>(automation.GetAddressOf()))))
|
||||
return {};
|
||||
automation->put_ConnectionTimeout(150);
|
||||
automation->put_TransactionTimeout(150);
|
||||
ComPtr<IUIAutomationElement> focused;
|
||||
if (FAILED(automation->GetFocusedElement(&focused)) || !focused)
|
||||
return {};
|
||||
DWORD process{};
|
||||
GetWindowThreadProcessId(target, &process);
|
||||
int focusedProcess{};
|
||||
BOOL password = TRUE;
|
||||
if (!process || FAILED(focused->get_CurrentProcessId(&focusedProcess)) ||
|
||||
process != static_cast<DWORD>(focusedProcess) ||
|
||||
FAILED(focused->get_CurrentIsPassword(&password)) || password)
|
||||
if (FAILED(focused->get_CurrentIsPassword(&password)) || password ||
|
||||
!focusedTextBelongsToWindow(automation, focused.Get(), target))
|
||||
return {};
|
||||
return focused;
|
||||
}
|
||||
|
||||
ComPtr<IUIAutomation2> snippetAutomation()
|
||||
{
|
||||
ComPtr<IUIAutomation2> automation;
|
||||
if (FAILED(CoCreateInstance(CLSID_CUIAutomation8, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&automation))))
|
||||
return {};
|
||||
automation->put_ConnectionTimeout(150);
|
||||
automation->put_TransactionTimeout(150);
|
||||
return automation;
|
||||
}
|
||||
|
||||
ComPtr<IUIAutomationValuePattern> terminalSnippetInput(IUIAutomation *automation, IUIAutomationElement *focused)
|
||||
{
|
||||
// The receiver is a sibling of this terminal's focused xterm input.
|
||||
ComPtr<IUIAutomationTreeWalker> walker;
|
||||
ComPtr<IUIAutomationElement> parent, input;
|
||||
ComPtr<IUIAutomationCondition> condition;
|
||||
if (FAILED(automation->get_RawViewWalker(&walker)) || !walker ||
|
||||
FAILED(walker->GetParentElement(focused, &parent)) || !parent)
|
||||
return {};
|
||||
VARIANT className{};
|
||||
className.vt = VT_BSTR;
|
||||
className.bstrVal = SysAllocString(L"dirlume-terminal-snippet-input");
|
||||
const auto result = automation->CreatePropertyCondition(UIA_ClassNamePropertyId, className, &condition);
|
||||
VariantClear(&className);
|
||||
if (FAILED(result) || !condition ||
|
||||
FAILED(parent->FindFirst(TreeScope_Children, condition.Get(), &input)) || !input)
|
||||
return {};
|
||||
ComPtr<IUIAutomationValuePattern> value;
|
||||
input->GetCurrentPatternAs(UIA_ValuePatternId, IID_PPV_ARGS(&value));
|
||||
return value;
|
||||
}
|
||||
|
||||
std::wstring terminalSnippetTicket(IUIAutomationValuePattern *value)
|
||||
{
|
||||
if (!value) return {};
|
||||
BSTR ticket{};
|
||||
const auto result = value->get_CurrentValue(&ticket);
|
||||
const std::wstring_view text(ticket ? ticket : L"", SysStringLen(ticket));
|
||||
auto accepted = SUCCEEDED(result) && text.size() == terminalSnippetTicketPrefix.size() + 36 &&
|
||||
text.starts_with(terminalSnippetTicketPrefix) ? std::wstring(text) : std::wstring();
|
||||
SysFreeString(ticket);
|
||||
return accepted;
|
||||
}
|
||||
|
||||
std::optional<Template> terminalSnippetTemplate(const Snippet &snippet)
|
||||
{
|
||||
auto value = parseTemplate(snippet.text);
|
||||
if (value.text.empty() || value.text.size() > 8192 || !value.actions.empty() ||
|
||||
std::any_of(value.text.begin(), value.text.end(), [](wchar_t c) {
|
||||
return c < 0x20 || (c >= 0x7f && c <= 0x9f) || c == 0x2028 || c == 0x2029;
|
||||
})) return {};
|
||||
return value;
|
||||
}
|
||||
|
||||
std::optional<SnippetAnchor> accessibleSnippetCaret(HWND target)
|
||||
{
|
||||
const auto automation = snippetAutomation();
|
||||
if (!automation) return {};
|
||||
const auto focused = focusedSnippetElement(automation.Get(), target);
|
||||
if (!focused) return {};
|
||||
|
||||
// The xterm.js input follows the terminal cursor for IME. Dirlume
|
||||
// handles replacement in the active shell draft through a separate input.
|
||||
if (snippetElementClass(focused.Get(), L"xterm-helper-textarea"))
|
||||
{
|
||||
RECT cell{};
|
||||
BOOL offscreen = TRUE;
|
||||
if (SUCCEEDED(focused->get_CurrentIsOffscreen(&offscreen)) && !offscreen &&
|
||||
SUCCEEDED(focused->get_CurrentBoundingRectangle(&cell)) && cell.right > cell.left &&
|
||||
cell.bottom > cell.top)
|
||||
{
|
||||
auto ticket = lower(processName(target)) == L"dirlume" ?
|
||||
terminalSnippetTicket(terminalSnippetInput(automation.Get(), focused.Get()).Get()) : std::wstring();
|
||||
return SnippetAnchor{{cell.left, cell.top, cell.left, cell.bottom}, true, std::move(ticket)};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
ComPtr<IUIAutomationTextPattern2> pattern;
|
||||
ComPtr<IUIAutomationTextRange> range;
|
||||
BOOL active{};
|
||||
@@ -121,7 +203,7 @@ std::optional<RECT> accessibleSnippetCaret(HWND target)
|
||||
}
|
||||
}
|
||||
SafeArrayDestroy(rectangles);
|
||||
if (anchor && anchor->bottom > anchor->top) return anchor;
|
||||
if (anchor && anchor->bottom > anchor->top) return SnippetAnchor{*anchor};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
@@ -144,9 +226,11 @@ 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 int ResetHeldInput = 30;
|
||||
constexpr wchar_t MonobankDonationUrl[] = L"https://send.monobank.ua/jar/88h2TddKfS";
|
||||
constexpr int ShortcutProbeId = FilesHotkeySecond + 1;
|
||||
constexpr int FirstCustomShortcut = 0x5000;
|
||||
constexpr UINT_PTR PauseDrainTimer = 23;
|
||||
|
||||
bool shortcutAvailable(HWND window, Hotkey key)
|
||||
@@ -178,6 +262,30 @@ bool activateFilesWindow()
|
||||
return true;
|
||||
}
|
||||
|
||||
HWND shortcutAppWindow(const std::wstring &executable, const std::deque<std::pair<HWND, DWORD>> &recent)
|
||||
{
|
||||
const auto path = std::filesystem::path(executable).lexically_normal().make_preferred().wstring();
|
||||
auto matches = [&path](HWND candidate) {
|
||||
if (!IsWindowVisible(candidate) || (GetWindowLongPtrW(candidate, GWL_EXSTYLE) & WS_EX_TOOLWINDOW)) return false;
|
||||
const auto image = processImagePath(candidate);
|
||||
return CompareStringOrdinal(path.c_str(), -1, image.c_str(), -1, TRUE) == CSTR_EQUAL;
|
||||
};
|
||||
if (const auto foreground = GetAncestor(GetForegroundWindow(), GA_ROOT); matches(foreground)) return foreground;
|
||||
for (const auto &[candidate, expectedProcess] : recent)
|
||||
{
|
||||
DWORD process{};
|
||||
if (GetWindowThreadProcessId(candidate, &process) && process == expectedProcess && matches(candidate)) return candidate;
|
||||
}
|
||||
struct Search { decltype(matches) &match; HWND result{}; } search{matches};
|
||||
EnumWindows([](HWND candidate, LPARAM context) -> BOOL {
|
||||
auto &state = *reinterpret_cast<Search *>(context);
|
||||
if (!state.match(candidate)) return TRUE;
|
||||
state.result = candidate;
|
||||
return FALSE;
|
||||
}, reinterpret_cast<LPARAM>(&search));
|
||||
return search.result;
|
||||
}
|
||||
|
||||
std::vector<std::pair<int, std::wstring>> shortcuts(const Settings &s)
|
||||
{
|
||||
std::vector<std::pair<int, std::wstring>> out{{Toggle, s.toggle},
|
||||
@@ -188,6 +296,9 @@ std::vector<std::pair<int, std::wstring>> shortcuts(const Settings &s)
|
||||
{Screenshot, s.screenshot}};
|
||||
for (size_t i = 0; i < s.direct.size(); ++i)
|
||||
out.emplace_back(Direct + (int)i, s.direct[i]);
|
||||
for (size_t i = 0; i < s.customShortcuts.size(); ++i)
|
||||
if (s.customShortcuts[i].enabled)
|
||||
out.emplace_back(FirstCustomShortcut + static_cast<int>(i), s.customShortcuts[i].shortcut);
|
||||
return out;
|
||||
}
|
||||
std::vector<std::wstring> buildSnippetVariants(const std::wstring &trigger, const std::vector<Layout> &layouts)
|
||||
@@ -660,21 +771,18 @@ class Transaction
|
||||
}
|
||||
auto text = select(count) ? copy() : std::wstring{};
|
||||
diagnosticEvent(L"Selection initial match=" + std::to_wstring(matches(text)) + L" copied=" + diagnosticText(text));
|
||||
// Chromium editors can apply only part of a burst of Shift+Left events.
|
||||
// Extend only a verified suffix; never replace a partial or unrelated range.
|
||||
// The editor may finish applying queued Shift+Left events after copying
|
||||
// the suffix. Collapse to its right edge before trying the full range again.
|
||||
if (valid() && !matches(text) && !text.empty() &&
|
||||
(suffixMatches ? suffixMatches(text) : newlines(wordCandidate).ends_with(newlines(text))) &&
|
||||
caretSteps(text) < count)
|
||||
{
|
||||
const auto missing = count - caretSteps(text);
|
||||
diagnosticEvent(L"Selection: extending verified suffix by " + std::to_wstring(missing));
|
||||
for (size_t i = 0; i < missing; ++i)
|
||||
{
|
||||
if (!valid() || !chord(VK_LEFT, MOD_SHIFT))
|
||||
return {};
|
||||
diagnosticEvent(L"Selection recovery Shift+Left sent=" + std::to_wstring(i + 1) + L" total=" + std::to_wstring(missing));
|
||||
Sleep(25);
|
||||
}
|
||||
diagnosticEvent(L"Selection: reselecting full range after verified suffix");
|
||||
if (!finishSelection(false))
|
||||
return {};
|
||||
Sleep(25);
|
||||
if (!selectPrevious(count, [&] { return valid(); }, true))
|
||||
return {};
|
||||
text = copy();
|
||||
diagnosticEvent(L"Selection: suffix recovery match=" + std::to_wstring(matches(text)) + L" copied=" + diagnosticText(text));
|
||||
}
|
||||
@@ -971,23 +1079,37 @@ HBITMAP trayIconBitmap(HICON base, int width, int height, void **data = nullptr)
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HICON trayInputIcon(HICON base, int width, int height, uint32_t color)
|
||||
HICON trayInputIcon(HICON base, int width, int height, uint32_t color, bool blocked = false)
|
||||
{
|
||||
if (width < 8 || height < 8) return nullptr;
|
||||
void *bits{};
|
||||
const auto bitmap = trayIconBitmap(base, width, height, &bits);
|
||||
if (!bitmap) return nullptr;
|
||||
auto pixels = static_cast<uint32_t *>(bits);
|
||||
const int radius = std::max(3, MulDiv(std::min(width, height), 3, 16));
|
||||
const int minimumRadius = blocked ? 4 : 3;
|
||||
const int radius = std::min((std::min(width, height) - 1) / 2,
|
||||
std::max(minimumRadius, MulDiv(std::min(width, height), minimumRadius, 16)));
|
||||
const int cx = width - 1 - radius, cy = height - 1 - radius;
|
||||
constexpr uint32_t ink = 0xff242424;
|
||||
for (int y = -radius; y <= radius; ++y)
|
||||
for (int x = -radius; x <= radius; ++x)
|
||||
{
|
||||
const int distance = x * x + y * y;
|
||||
if (distance <= radius * radius)
|
||||
pixels[(cy + y) * width + cx + x] = distance <= (radius - 1) * (radius - 1)
|
||||
? color : 0xff242424;
|
||||
? color : ink;
|
||||
}
|
||||
if (blocked)
|
||||
{
|
||||
const int stroke = std::max(1, radius / 4);
|
||||
const int left = cx - (stroke - 1) / 2;
|
||||
const int dot = cy + std::max(2, radius / 2);
|
||||
for (int x = left; x < left + stroke; ++x)
|
||||
{
|
||||
for (int y = cy - radius / 2; y <= cy; ++y) pixels[y * width + x] = ink;
|
||||
for (int y = dot; y < dot + stroke; ++y) pixels[y * width + x] = ink;
|
||||
}
|
||||
}
|
||||
// The 32-bit DIB supplies the transparency. The fallback mask is initialized as well.
|
||||
std::vector<unsigned char> maskBits(size_t((width + 15) / 16) * 2 * height);
|
||||
HICON icon{};
|
||||
@@ -1008,6 +1130,16 @@ HICON App::trayBaseIcon(int width, int height) const
|
||||
return static_cast<HICON>(LoadImageW(instance, MAKEINTRESOURCEW(resource), IMAGE_ICON, width, height, LR_SHARED));
|
||||
}
|
||||
|
||||
HICON App::trayInputBadge(HICON base, int width, int height) const
|
||||
{
|
||||
if (inputState != InputState::Active) return nullptr;
|
||||
if (!trayInputBlock.empty()) return trayInputIcon(base, width, height, 0xffffc457, true);
|
||||
if (!trayInput.paired) return nullptr;
|
||||
const uint32_t color = trayInput.stopped ? 0xfff16b66 : !trayInput.online ? 0xffa0a4ab :
|
||||
!trayInput.reconnecting() ? 0xff45d58c : trayInputPulse ? 0xffffc457 : 0xffac7830;
|
||||
return trayInputIcon(base, width, height, color);
|
||||
}
|
||||
|
||||
bool App::updateTray(DWORD action)
|
||||
{
|
||||
NOTIFYICONDATAW icon{sizeof(icon)};
|
||||
@@ -1018,7 +1150,8 @@ bool App::updateTray(DWORD action)
|
||||
icon.uCallbackMessage = TrayMessage;
|
||||
const int width = GetSystemMetrics(SM_CXSMICON), height = GetSystemMetrics(SM_CYSMICON);
|
||||
icon.hIcon = trayBaseIcon(width, height);
|
||||
HICON badge{};
|
||||
const auto badge = trayInputBadge(icon.hIcon, width, height);
|
||||
if (badge) icon.hIcon = badge;
|
||||
auto tip = localBuildTitle(L"KSwitcher");
|
||||
const auto state = inputState.load();
|
||||
tip += state == InputState::Active ? L" — Input processing active" :
|
||||
@@ -1026,10 +1159,6 @@ bool App::updateTray(DWORD action)
|
||||
if (state == InputState::Active && trayInput.paired)
|
||||
{
|
||||
const bool reconnecting = trayInput.reconnecting();
|
||||
const uint32_t color = trayInput.stopped ? 0xfff16b66 : !trayInput.online ? 0xffa0a4ab :
|
||||
!reconnecting ? 0xff45d58c : trayInputPulse ? 0xffffc457 : 0xffac7830;
|
||||
badge = trayInputIcon(icon.hIcon, width, height, color);
|
||||
if (badge) icon.hIcon = badge;
|
||||
tip += L"\nMouse & keyboard: ";
|
||||
if (trayInput.stopped) tip += L"connection stopped";
|
||||
else if (!trayInput.online) tip += L"all paired PCs offline. Waiting for LAN discovery.";
|
||||
@@ -1041,6 +1170,7 @@ bool App::updateTray(DWORD action)
|
||||
std::to_wstring(trayInput.paired) + L" PCs connected)";
|
||||
}
|
||||
}
|
||||
if (state == InputState::Active && !trayInputBlock.empty()) tip = trayInputBlock;
|
||||
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
|
||||
const bool updated = Shell_NotifyIconW(action, &icon) != FALSE;
|
||||
if (badge) DestroyIcon(badge);
|
||||
@@ -1049,6 +1179,7 @@ bool App::updateTray(DWORD action)
|
||||
|
||||
void App::refreshTrayInput()
|
||||
{
|
||||
refreshTrayInputBlock();
|
||||
const auto state = lanService ? lanService->inputConnections() : LanInputConnections{};
|
||||
if (state == trayInput) return;
|
||||
trayInput = state;
|
||||
@@ -1060,6 +1191,41 @@ void App::refreshTrayInput()
|
||||
updateTray(NIM_MODIFY);
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
bool trayNotice(HWND window, const std::wstring &text)
|
||||
{
|
||||
NOTIFYICONDATAW icon{sizeof(icon)};
|
||||
icon.hWnd = window;
|
||||
icon.uID = 1;
|
||||
icon.uFlags = NIF_INFO;
|
||||
wcsncpy_s(icon.szInfo, text.c_str(), _TRUNCATE);
|
||||
wcscpy_s(icon.szInfoTitle, L"KSwitcher");
|
||||
icon.dwInfoFlags = NIIF_WARNING;
|
||||
return Shell_NotifyIconW(NIM_MODIFY, &icon) != FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
void App::refreshTrayInputBlock()
|
||||
{
|
||||
auto block = lanService ? lanService->inputBlockText() : std::wstring{};
|
||||
if (block == trayInputBlock) return;
|
||||
const bool newlyBlocked = trayInputBlock.empty();
|
||||
trayInputBlock = std::move(block);
|
||||
updateTray(NIM_MODIFY);
|
||||
const auto now = GetTickCount64();
|
||||
if (newlyBlocked && now >= nextInputBlockNotice)
|
||||
{
|
||||
inputBlockNoticeVisible = trayNotice(window, trayInputBlock);
|
||||
nextInputBlockNotice = now + 4000;
|
||||
}
|
||||
else if (inputBlockNoticeVisible)
|
||||
{
|
||||
trayNotice(window, {});
|
||||
inputBlockNoticeVisible = false;
|
||||
}
|
||||
}
|
||||
|
||||
void App::addTray()
|
||||
{
|
||||
if (updateTray(NIM_ADD))
|
||||
@@ -1128,13 +1294,18 @@ bool App::registerHotkeys(const Settings &s, bool rollback)
|
||||
return true;
|
||||
}
|
||||
|
||||
void App::startLanService()
|
||||
{
|
||||
lanService = std::make_unique<LanService>(data, window, inputState != InputState::Active, [this] {
|
||||
// Mouse actions may consume a button press before it reaches Windows.
|
||||
const auto held = std::find_if(mousePresses.begin(), mousePresses.end(), [](const auto &press) { return press.held; });
|
||||
return held == mousePresses.end() ? 0 : lan::MouseInputKeys[size_t(held - mousePresses.begin())];
|
||||
});
|
||||
if (!smoke) lanService->startClients();
|
||||
}
|
||||
Bytes App::lanCommand(const Bytes &command)
|
||||
{
|
||||
if (!lanService)
|
||||
{
|
||||
lanService = std::make_unique<LanService>(data,window,inputState != InputState::Active);
|
||||
if (!smoke) lanService->startClients();
|
||||
}
|
||||
if (!lanService) startLanService();
|
||||
auto reply = lanService->command(command);
|
||||
updateLanInputTimer();
|
||||
if (lanService->takeInputChange()) resetLanInput();
|
||||
@@ -1151,6 +1322,7 @@ void App::pollLanInput()
|
||||
// Temporary text transactions only block new handoffs. A tray pause removes
|
||||
// the router entirely, including for already queued network notifications.
|
||||
if (lanService && lanService->tickInput(!busy && !suspended && !hotkeyCapture)) resetLanInput();
|
||||
refreshTrayInputBlock();
|
||||
}
|
||||
void App::applySettings(const Settings &requested, const Bytes &supplement)
|
||||
{
|
||||
@@ -1485,6 +1657,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 +1737,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 +1750,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 +1765,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 +1829,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 +1948,7 @@ LRESULT CALLBACK App::snippetPopupProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
const LONG top = static_cast<LONG>(i - first) * app->snippetRowHeight;
|
||||
RECT row{0, top, bounds.right, top + app->snippetRowHeight};
|
||||
const bool selected = i == app->snippetSelection;
|
||||
const bool selected = app->snippetPopupAnchor.canInsert() && i == app->snippetSelection;
|
||||
if (selected) FillRect(dc, &row, GetSysColorBrush(COLOR_HIGHLIGHT));
|
||||
SetTextColor(dc, GetSysColor(selected ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT));
|
||||
row.left += MulDiv(8, dpi, 96);
|
||||
@@ -1815,7 +2073,7 @@ bool App::handleKeyboard(const KBDLLHOOKSTRUCT &key, bool down, UINT mods)
|
||||
// from opening on Win-up after we consumed V. 0xE8 is unassigned.
|
||||
if (mods & (MOD_WIN | MOD_ALT))
|
||||
chord(0xE8);
|
||||
PostMessageW(window, WM_HOTKEY, action, 0);
|
||||
PostMessageW(window, WM_HOTKEY, action, MAKELPARAM(mods, key.vkCode));
|
||||
}
|
||||
if (action != 0)
|
||||
{
|
||||
@@ -2138,6 +2396,8 @@ LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
auto &app = *current;
|
||||
const auto &mouse = *reinterpret_cast<const MSLLHOOKSTRUCT *>(lp);
|
||||
if ((mouse.flags & LLMHF_INJECTED) && mouse.dwExtraInfo == inputMarker())
|
||||
return CallNextHookEx(nullptr, code, wp, lp);
|
||||
// Forwarded mouse events use the same bindings as local events on this PC.
|
||||
const int button = mouseButton(UINT(wp), HIWORD(mouse.mouseData));
|
||||
const auto wheelDelta = static_cast<SHORT>(HIWORD(mouse.mouseData));
|
||||
@@ -2166,10 +2426,8 @@ LRESULT CALLBACK App::mouseProc(int code, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
if (app.lanService)
|
||||
{
|
||||
const bool mouseActionHeld = std::any_of(app.mousePresses.begin(), app.mousePresses.end(),
|
||||
[](const MousePress &press) { return press.held; });
|
||||
bool consumed = app.lanService->mouse(UINT(wp), mouse,
|
||||
!app.busy && !app.suspended && !app.hotkeyCapture && !mouseActionHeld);
|
||||
!app.busy && !app.suspended && !app.hotkeyCapture);
|
||||
if (app.lanService->takeInputChange()) app.resetLanInput();
|
||||
if (consumed) return 1;
|
||||
}
|
||||
@@ -3157,6 +3415,15 @@ void App::recognizeEntry(std::wstring id)
|
||||
}
|
||||
});
|
||||
}
|
||||
void App::clearMousePresses()
|
||||
{
|
||||
mousePresses = {};
|
||||
pendingMouseClicks = {};
|
||||
KillTimer(window, MouseClickTimer);
|
||||
for (size_t i = 0; i < mousePresses.size(); ++i) KillTimer(window, FirstMouseVolumeTimer + i);
|
||||
PostMessageW(window, MouseVolumeReleasedMessage, 0, 0);
|
||||
}
|
||||
|
||||
void App::toggleInputProcessing()
|
||||
{
|
||||
if (inputState == InputState::Pausing) return;
|
||||
@@ -3170,10 +3437,7 @@ void App::toggleInputProcessing()
|
||||
if (shortcutAvailable(window, binding.second)) availableBeforePause.push_back(binding.second);
|
||||
releaseInputHooks();
|
||||
resetLanInput();
|
||||
mousePresses = {};
|
||||
KillTimer(window, MouseClickTimer);
|
||||
for (size_t i = 0; i < mousePresses.size(); ++i) KillTimer(window, FirstMouseVolumeTimer + i);
|
||||
PostMessageW(window, MouseVolumeReleasedMessage, 0, 0);
|
||||
clearMousePresses();
|
||||
hideSnippetPopup();
|
||||
if (lanService) lanService->setInputPaused(true);
|
||||
KillTimer(window, 8);
|
||||
@@ -3226,6 +3490,8 @@ void App::trayMenu()
|
||||
AppendMenuW(menu, MF_STRING | (inputState == InputState::Pausing ? MF_GRAYED : 0), ToggleInputProcessing,
|
||||
inputState == InputState::Active ? L"Pause &input processing" :
|
||||
inputState == InputState::Paused ? L"Resume &input processing" : L"Pausing input processing…");
|
||||
AppendMenuW(menu, MF_STRING, ResetHeldInput, PRIMARYLANGID(GetThreadUILanguage()) == LANG_UKRAINIAN ?
|
||||
L"Скинути затиснуті клавіші й кнопки миші" : L"Reset held keys and mouse buttons");
|
||||
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
|
||||
AppendMenuW(menu, MF_STRING, 10, L"Clipboard &history");
|
||||
AppendMenuW(menu, MF_STRING, 24, L"&Capture screen region…");
|
||||
@@ -3269,6 +3535,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");
|
||||
@@ -3302,6 +3569,14 @@ void App::trayMenu()
|
||||
case ToggleInputProcessing:
|
||||
toggleInputProcessing();
|
||||
break;
|
||||
case ResetHeldInput:
|
||||
if (lan::resetWindowsHeldInput())
|
||||
{
|
||||
if (lanService) lanService->forgetHeldInput();
|
||||
clearMousePresses();
|
||||
}
|
||||
else report(L"Windows could not release all held keys or mouse buttons.");
|
||||
break;
|
||||
case OpenFiles:
|
||||
dispatch(OpenFiles);
|
||||
break;
|
||||
@@ -3333,6 +3608,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 +3650,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;
|
||||
@@ -3510,6 +3807,42 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
case WM_HOTKEY:
|
||||
if (app->inputState != InputState::Active || wp == ShortcutProbeId) return 0;
|
||||
if (wp >= FirstCustomShortcut)
|
||||
{
|
||||
const size_t index = wp - FirstCustomShortcut;
|
||||
if (app->installingUpdate || app->busy || app->hotkeyCapture || index >= app->settings.customShortcuts.size()) return 0;
|
||||
const auto &rule = app->settings.customShortcuts[index];
|
||||
if (!rule.enabled || Hotkey::parse(rule.shortcut) != Hotkey{LOWORD(lp), HIWORD(lp)}) return 0;
|
||||
if (rule.action == CustomShortcutAction::OpenUrl)
|
||||
{
|
||||
if (!openShortcutUrl(rule))
|
||||
app->report(L"Could not open the URL for " + rule.name + L". Check the configured browser and profile.");
|
||||
return 0;
|
||||
}
|
||||
if (rule.action == CustomShortcutAction::SendText)
|
||||
{
|
||||
const auto target = shortcutAppWindow(rule.executable, app->recentForegroundWindows);
|
||||
const auto control = findShortcutTextControl(target, rule.controlClass, rule.controlId);
|
||||
if (control && rule.text.find_first_of(L"\r\n") != std::wstring::npos &&
|
||||
!(GetWindowLongPtrW(control, GWL_STYLE) & ES_MULTILINE))
|
||||
app->report(L"The target field for " + rule.name + L" accepts a single line of text.");
|
||||
else if (!control || !SendMessageTimeoutW(control, EM_REPLACESEL, TRUE, reinterpret_cast<LPARAM>(rule.text.c_str()),
|
||||
SMTO_ABORTIFHUNG | SMTO_BLOCK | SMTO_ERRORONEXIT, 300, nullptr))
|
||||
app->report(L"Could not insert text for " + rule.name + L". Check that its target field is open.");
|
||||
return 0;
|
||||
}
|
||||
if (!rule.newInstance)
|
||||
{
|
||||
if (const auto target = shortcutAppWindow(rule.executable, app->recentForegroundWindows))
|
||||
{
|
||||
if (IsIconic(target)) ShowWindowAsync(target, SW_RESTORE);
|
||||
if (!activateWindow(target)) app->report(L"Could not activate the window for " + rule.name + L".");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (!launchThroughExplorer(rule.executable)) app->report(L"Could not launch the program for " + rule.name + L".");
|
||||
return 0;
|
||||
}
|
||||
if (app->filesHotkeyId && wp == static_cast<WPARAM>(app->filesHotkeyId))
|
||||
{
|
||||
if(!activateFilesWindow()) app->dispatch(OpenFiles);
|
||||
@@ -3580,13 +3913,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;
|
||||
@@ -3601,14 +3934,8 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case ErrorMessage:
|
||||
{
|
||||
std::unique_ptr<std::wstring> text((std::wstring *)lp);
|
||||
NOTIFYICONDATAW icon{sizeof(icon)};
|
||||
icon.hWnd = hwnd;
|
||||
icon.uID = 1;
|
||||
icon.uFlags = NIF_INFO;
|
||||
wcsncpy_s(icon.szInfo, text->c_str(), _TRUNCATE);
|
||||
wcscpy_s(icon.szInfoTitle, L"KSwitcher");
|
||||
icon.dwInfoFlags = NIIF_WARNING;
|
||||
Shell_NotifyIconW(NIM_MODIFY, &icon);
|
||||
app->inputBlockNoticeVisible = false;
|
||||
trayNotice(hwnd, *text);
|
||||
return 0;
|
||||
}
|
||||
case LanInputStatusMessage:
|
||||
@@ -3674,7 +4001,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (app->trayInput.reconnecting())
|
||||
{
|
||||
app->trayInputPulse = !app->trayInputPulse;
|
||||
app->updateTray(NIM_MODIFY);
|
||||
if (app->trayInputBlock.empty()) app->updateTray(NIM_MODIFY);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -3861,7 +4188,7 @@ int App::execute()
|
||||
if (!smoke && inputState == InputState::Active) startBrowserChatMonitor();
|
||||
if (!smoke && (std::filesystem::exists(data / L"lan-pairing.bin") ||
|
||||
std::filesystem::exists(data / L"lan-clients.bin")))
|
||||
try { lanService = std::make_unique<LanService>(data,window,inputState != InputState::Active); lanService->startClients(); }
|
||||
try { startLanService(); }
|
||||
catch (const std::exception &e) { report(L"LAN module: " + wide(e.what())); }
|
||||
updateLanInputTimer();
|
||||
refreshTrayInput();
|
||||
@@ -3876,8 +4203,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 +4210,17 @@ int App::execute()
|
||||
try { notificationRegistration = startScreenshotNotificationRegistration(); }
|
||||
catch(const std::exception &e) { log(L"Screenshot notification registration: "+wide(e.what())); }
|
||||
auto screenshotActivation=startScreenshotActivationListener();
|
||||
const auto foregroundHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr,
|
||||
[](HWINEVENTHOOK, DWORD, HWND target, LONG, LONG, DWORD, DWORD) {
|
||||
target = GetAncestor(target, GA_ROOT);
|
||||
DWORD process{};
|
||||
if (!current || !GetWindowThreadProcessId(target, &process)) return;
|
||||
auto &recent = current->recentForegroundWindows;
|
||||
std::erase_if(recent, [target](const auto &entry) { return entry.first == target || !IsWindow(entry.first); });
|
||||
recent.emplace_front(target, process);
|
||||
if (recent.size() > 256) recent.pop_back();
|
||||
}, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
|
||||
if (keyboardHook && mouseHook) showWhatsNewAfterUpdate();
|
||||
MSG msg;
|
||||
while (GetMessageW(&msg, nullptr, 0, 0) > 0)
|
||||
{
|
||||
@@ -3909,6 +4245,7 @@ int App::execute()
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
if(screenshotActivation) CoRevokeClassObject(screenshotActivation);
|
||||
if (foregroundHook) UnhookWinEvent(foregroundHook);
|
||||
return (int)msg.wParam;
|
||||
}
|
||||
} // namespace ks
|
||||
@@ -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);
|
||||
@@ -118,6 +126,7 @@ class App
|
||||
void toggleInputProcessing();
|
||||
void updateLanInputTimer();
|
||||
void pollLanInput();
|
||||
void startLanService();
|
||||
struct MousePress
|
||||
{
|
||||
HWND target{};
|
||||
@@ -172,15 +181,22 @@ class App
|
||||
bool trayRetryPending{};
|
||||
LanInputConnections trayInput;
|
||||
bool trayInputPulse{};
|
||||
std::wstring trayInputBlock;
|
||||
ULONGLONG nextInputBlockNotice{};
|
||||
bool inputBlockNoticeVisible{};
|
||||
HICON trayBaseIcon(int width, int height) const;
|
||||
HICON trayInputBadge(HICON base, int width, int height) const;
|
||||
bool updateTray(DWORD action);
|
||||
void refreshTrayInput();
|
||||
void refreshTrayInputBlock();
|
||||
void clearMousePresses();
|
||||
uint64_t transformAttempt{}, previousAttemptVersion{};
|
||||
std::atomic<uint64_t> activeTransformAttempt{};
|
||||
ULONGLONG previousAttemptAt{};
|
||||
HWND previousAttemptWindow{};
|
||||
int previousAttemptCommand{}, repeatAttempts{};
|
||||
std::vector<std::pair<int, Hotkey>> hookBindings;
|
||||
std::deque<std::pair<HWND, DWORD>> recentForegroundWindows;
|
||||
std::vector<Hotkey> availableBeforePause;
|
||||
Hotkey registeredFilesHotkey{};
|
||||
int filesHotkeyId{};
|
||||
@@ -202,20 +218,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 +250,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
@@ -645,15 +645,25 @@ int Run::match(const std::wstring &text, const std::vector<Layout> &layouts, con
|
||||
{
|
||||
if (text.size() != keys.size() || overflow)
|
||||
return -1;
|
||||
const auto normalized = lower(text);
|
||||
int fallback = -1;
|
||||
for (int i = 0; i < (int)layouts.size(); ++i)
|
||||
if (layouts[i].convertible)
|
||||
{
|
||||
const auto &candidate = layouts[i];
|
||||
const bool tracked = layout && candidate.handle == layout;
|
||||
if (!candidate.convertible || (!tracked && fallback >= 0))
|
||||
continue;
|
||||
|
||||
std::wstring expected;
|
||||
for (wchar_t c : keys)
|
||||
expected += c == L' ' ? L' ' : candidate.at(physical.code(c));
|
||||
if (lower(expected) == normalized)
|
||||
{
|
||||
std::wstring expected;
|
||||
for (wchar_t c : keys)
|
||||
expected += c == L' ' ? L' ' : layouts[i].at(physical.code(c));
|
||||
if (lower(expected) == lower(text))
|
||||
if (tracked)
|
||||
return i;
|
||||
fallback = i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
} // namespace ks
|
||||
+16
@@ -82,6 +82,21 @@ struct MouseAction
|
||||
int volumeStep = DefaultMouseVolumeStep;
|
||||
bool operator==(const MouseAction &) const = default;
|
||||
};
|
||||
enum class CustomShortcutAction { LaunchApp, SendText, OpenUrl };
|
||||
enum class ShortcutBrowser { Default, Chrome, Other };
|
||||
struct CustomShortcut
|
||||
{
|
||||
std::wstring name, shortcut, executable;
|
||||
bool enabled = true;
|
||||
bool newInstance = false;
|
||||
CustomShortcutAction action = CustomShortcutAction::LaunchApp;
|
||||
std::wstring controlClass, text;
|
||||
int controlId = 0;
|
||||
std::wstring url;
|
||||
ShortcutBrowser browser = ShortcutBrowser::Default;
|
||||
std::wstring chromeProfile;
|
||||
bool operator==(const CustomShortcut &) const = default;
|
||||
};
|
||||
struct Settings
|
||||
{
|
||||
bool recent = true, switchLayout = true, history = true, autostart = false, awake = false;
|
||||
@@ -109,6 +124,7 @@ struct Settings
|
||||
translit = L"Ctrl+Alt+Shift+T", undo = L"Ctrl+Alt+Shift+Z", clipboard = L"Win+V",
|
||||
screenshot = L"Win+Shift+S";
|
||||
std::optional<std::wstring> filesHotkey;
|
||||
std::vector<CustomShortcut> customShortcuts;
|
||||
std::vector<std::wstring> cycle, direct, directIds;
|
||||
// Exact application + visible chat name; an absent entry uses the global cycle.
|
||||
std::map<std::wstring, std::vector<std::wstring>> chatCycles;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cwchar>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
enum class AppearanceArea { panels, viewer, editor, markdown, terminal, comparison, count };
|
||||
inline constexpr size_t appearanceIndex(AppearanceArea area) { return static_cast<size_t>(area); }
|
||||
using AppearanceScales=std::array<unsigned,appearanceIndex(AppearanceArea::count)>;
|
||||
inline constexpr AppearanceScales defaultAppearanceScales{100,100,100,100,100,100};
|
||||
inline constexpr unsigned minAppearanceScale=75,maxAppearanceScale=200;
|
||||
|
||||
inline int scaledAppearanceSize(int size,unsigned percent)
|
||||
{
|
||||
return MulDiv(size,static_cast<int>(percent),100);
|
||||
}
|
||||
|
||||
inline bool windowsAppThemeChanged(UINT message,LPARAM parameter)
|
||||
{
|
||||
return message==WM_THEMECHANGED || (message==WM_SETTINGCHANGE && parameter &&
|
||||
std::wcscmp(reinterpret_cast<const wchar_t*>(parameter),L"ImmersiveColorSet")==0);
|
||||
}
|
||||
|
||||
inline bool windowsUsesDarkApps()
|
||||
{
|
||||
DWORD light=1,bytes=sizeof(light);
|
||||
return RegGetValueW(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
|
||||
L"AppsUseLightTheme",RRF_RT_REG_DWORD,nullptr,&light,&bytes)==ERROR_SUCCESS && !light;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)};
|
||||
auto commandHistoryKeys=defaultHistoryKeys;
|
||||
constexpr size_t commandHistoryLimit=1000;
|
||||
|
||||
std::wstring commandHistoryLabel(const std::wstring &command)
|
||||
@@ -19,41 +17,6 @@ std::wstring commandHistoryLabel(const std::wstring &command)
|
||||
return fs::path(path).is_absolute()?path:command;
|
||||
}
|
||||
|
||||
bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
{
|
||||
if(keys[0]==keys[1]) return false;
|
||||
return std::all_of(keys.begin(),keys.end(),[](WORD binding)
|
||||
{
|
||||
const auto key=LOBYTE(binding), modifiers=HIBYTE(binding);
|
||||
const bool letter=key>='A' && key<='Z';
|
||||
const bool function=key>=VK_F1 && key<=VK_F12;
|
||||
if(!letter && !function) return false;
|
||||
if(modifiers==HOTKEYF_CONTROL)
|
||||
return letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y';
|
||||
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
std::array<WORD,2> optionHistoryKeys(HWND dialog)
|
||||
{
|
||||
return {static_cast<WORD>(SendDlgItemMessageW(dialog,321,HKM_GETHOTKEY,0,0)),
|
||||
static_cast<WORD>(SendDlgItemMessageW(dialog,323,HKM_GETHOTKEY,0,0))};
|
||||
}
|
||||
|
||||
void setOptionHistoryKeys(HWND dialog,const std::array<WORD,2> &keys)
|
||||
{
|
||||
SendDlgItemMessageW(dialog,321,HKM_SETHOTKEY,keys[0],0);
|
||||
SendDlgItemMessageW(dialog,323,HKM_SETHOTKEY,keys[1],0);
|
||||
}
|
||||
|
||||
void loadCommandHistoryKeys()
|
||||
{
|
||||
const std::array<WORD,2> keys{static_cast<WORD>(preference(L"PreviousCommandKey",defaultHistoryKeys[0])),
|
||||
static_cast<WORD>(preference(L"CommandHistoryKey",defaultHistoryKeys[1]))};
|
||||
commandHistoryKeys=validHistoryKeys(keys)?keys:defaultHistoryKeys;
|
||||
}
|
||||
|
||||
void loadCommandHistory()
|
||||
{
|
||||
|
||||
@@ -107,23 +70,3 @@ void recallPreviousCommand()
|
||||
if(terminalHistoryIndex==terminalHistory.size()) terminalHistoryDraft=terminalInputText();
|
||||
recallCommand(terminalHistoryIndex-1);
|
||||
}
|
||||
|
||||
void showCommandHistory(HWND owner);
|
||||
|
||||
bool handleCommandHistoryKey(HWND window,const MSG &message)
|
||||
{
|
||||
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
|
||||
if((GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000)) return false;
|
||||
const BYTE modifiers=((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0) |
|
||||
((GetKeyState(VK_MENU)&0x8000)?HOTKEYF_ALT:0) | ((GetKeyState(VK_SHIFT)&0x8000)?HOTKEYF_SHIFT:0);
|
||||
const auto binding=MAKEWORD(message.wParam,modifiers);
|
||||
if(binding==commandHistoryKeys[0] && (message.hwnd==terminalInput ||
|
||||
message.hwnd==panels[0].list || message.hwnd==panels[1].list))
|
||||
{
|
||||
recallPreviousCommand();
|
||||
return true;
|
||||
}
|
||||
if(binding!=commandHistoryKeys[1]) return false;
|
||||
if(!(message.lParam&(1LL<<30))) showCommandHistory(window);
|
||||
return true;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+12
-30
@@ -4,31 +4,8 @@ enum ComparisonColor { CompareBackground, CompareText, CompareInsert, CompareDel
|
||||
constexpr const wchar_t *comparisonColorNames[]{L"Background",L"Text",L"Insertion",L"Deletion",L"Replacement",
|
||||
L"Changed fragment",L"Alignment padding",L"Divider",L"Text on changed lines"};
|
||||
constexpr wchar_t comparisonAppearanceKey[]=L"ComparisonAppearance";
|
||||
constexpr wchar_t comparisonShortcutKey[]=L"ComparisonShortcut";
|
||||
constexpr WORD defaultComparisonShortcut=MAKEWORD(VK_F11,HOTKEYF_SHIFT);
|
||||
WORD comparisonShortcut=defaultComparisonShortcut;
|
||||
constexpr int comparisonSplitScale=10000;
|
||||
|
||||
bool validComparisonShortcut(WORD shortcut)
|
||||
{
|
||||
const auto key=LOBYTE(shortcut),modifiers=HIBYTE(shortcut);
|
||||
return key>=VK_F1 && key<=VK_F12 &&
|
||||
(modifiers==(HOTKEYF_CONTROL|HOTKEYF_SHIFT) ||
|
||||
(modifiers==HOTKEYF_SHIFT && key!=VK_F4 && key!=VK_F8));
|
||||
}
|
||||
|
||||
void loadComparisonShortcut()
|
||||
{
|
||||
const auto shortcut=static_cast<WORD>(preference(comparisonShortcutKey,defaultComparisonShortcut));
|
||||
comparisonShortcut=validComparisonShortcut(shortcut)?shortcut:defaultComparisonShortcut;
|
||||
}
|
||||
|
||||
std::wstring comparisonShortcutLabel()
|
||||
{
|
||||
return std::wstring(HIBYTE(comparisonShortcut)&HOTKEYF_CONTROL?L"Ctrl+Shift+F":L"Shift+F")+
|
||||
std::to_wstring(LOBYTE(comparisonShortcut)-VK_F1+1);
|
||||
}
|
||||
|
||||
struct ComparisonAppearance
|
||||
{
|
||||
LOGFONTW font=defaultFilesFont();
|
||||
@@ -157,8 +134,9 @@ void applyComparisonFont(HWND dialog,FileComparison &comparison)
|
||||
{
|
||||
auto font=comparison.appearance.font;
|
||||
const auto dpi=GetDpiForWindow(dialog);
|
||||
const auto points=std::clamp(comparison.appearance.points+comparison.zoom,80,240);
|
||||
comparison.zoom=points-comparison.appearance.points;
|
||||
const auto base=areaFontPoints(comparison.appearance.points,AppearanceArea::comparison);
|
||||
const auto points=std::clamp(base+comparison.zoom,60,480);
|
||||
comparison.zoom=points-base;
|
||||
font.lfHeight=-MulDiv(points,dpi,720);
|
||||
font.lfWidth=0;
|
||||
if(const auto next=CreateFontIndirectW(&font))
|
||||
@@ -201,8 +179,8 @@ bool zoomComparison(HWND dialog,FileComparison &comparison,WPARAM wheel)
|
||||
comparison.wheelRemainder+=GET_WHEEL_DELTA_WPARAM(wheel);
|
||||
const auto steps=comparison.wheelRemainder/WHEEL_DELTA;
|
||||
comparison.wheelRemainder%=WHEEL_DELTA;
|
||||
const auto base=comparison.appearance.points;
|
||||
const auto zoom=std::clamp(base+comparison.zoom+10*steps,80,240)-base;
|
||||
const auto base=areaFontPoints(comparison.appearance.points,AppearanceArea::comparison);
|
||||
const auto zoom=std::clamp(base+comparison.zoom+10*steps,60,480)-base;
|
||||
if(zoom!=comparison.zoom)
|
||||
{
|
||||
comparison.zoom=zoom;
|
||||
@@ -1023,7 +1001,8 @@ void initializeComparisonToolbar(HWND toolbar)
|
||||
{icon(HIST_BACK),404,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Previous")},
|
||||
{icon(HIST_FORWARD),405,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Next")},
|
||||
{separator,0,0,BTNS_SEP,{},0,0},
|
||||
{I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Show whitespace changes")}
|
||||
{I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Show whitespace changes")},
|
||||
{I_IMAGENONE,527,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Appearance…")}
|
||||
};
|
||||
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
|
||||
}
|
||||
@@ -1072,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);
|
||||
@@ -1091,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)
|
||||
@@ -1130,6 +1111,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto id=LOWORD(wp);
|
||||
if(comparison->working) return TRUE;
|
||||
if(id==IDCANCEL) {closeComparison(dialog,*comparison);return TRUE;}
|
||||
if(id==527) {editFilesAppearance(dialog,AppearanceArea::comparison);return TRUE;}
|
||||
if(id==applyLeft || id==applyRight)
|
||||
{
|
||||
const auto side=id-applyLeft;
|
||||
@@ -1215,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)
|
||||
@@ -1250,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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
bool handleFilesHelpMessage(const MSG &message);
|
||||
|
||||
HWND activeFilesDialog{};
|
||||
HHOOK filesDialogMouseHook{};
|
||||
|
||||
@@ -52,10 +54,13 @@ 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 watchOutsideClicks=true,bool fitToOwner=true)
|
||||
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
|
||||
watchOutsideClicks_(watchOutsideClicks)
|
||||
resource_(IS_INTRESOURCE(resource)?static_cast<unsigned>(reinterpret_cast<ULONG_PTR>(resource)):0),
|
||||
watchOutsideClicks_(watchOutsideClicks),fitToOwner_(fitToOwner)
|
||||
{
|
||||
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
|
||||
}
|
||||
@@ -66,6 +71,12 @@ public:
|
||||
|
||||
HWND window() const { return window_; }
|
||||
|
||||
static unsigned resourceFor(HWND window)
|
||||
{
|
||||
const auto *state=reinterpret_cast<const FilesModalDialog*>(GetPropW(window,stateProperty_));
|
||||
return state?state->resource_:0;
|
||||
}
|
||||
|
||||
static HWND activeFor(HWND owner)
|
||||
{
|
||||
const auto root=GetAncestor(owner,GA_ROOTOWNER);
|
||||
@@ -111,7 +122,7 @@ public:
|
||||
activeFilesDialog=window_;
|
||||
entered_=true;
|
||||
refreshMouseHook();
|
||||
if(GetWindowRect(owner_,&ownerBounds_))
|
||||
if(fitToOwner_ && GetWindowRect(owner_,&ownerBounds_))
|
||||
{
|
||||
if(!layout_) captureLayout();
|
||||
SetWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this),reinterpret_cast<DWORD_PTR>(this));
|
||||
@@ -146,6 +157,7 @@ public:
|
||||
{
|
||||
if(message.hwnd==dialog || IsChild(dialog,message.hwnd))
|
||||
{
|
||||
if(handleFilesHelpMessage(message)) return true;
|
||||
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
|
||||
{
|
||||
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
|
||||
@@ -209,7 +221,8 @@ private:
|
||||
DLGPROC procedure_;
|
||||
LPARAM argument_;
|
||||
INT_PTR result_=IDCANCEL;
|
||||
bool entered_{},finished_{},watchOutsideClicks_;
|
||||
unsigned resource_{};
|
||||
bool entered_{},finished_{},watchOutsideClicks_,fitToOwner_;
|
||||
|
||||
static void refreshMouseHook()
|
||||
{
|
||||
@@ -336,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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline constexpr UINT filesHelpRequest=WM_APP+273;
|
||||
enum class FilesHelpTopic
|
||||
{
|
||||
panels, menus, navigation, find, transfer, deleteFiles, archive, space, properties, connections,
|
||||
terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, log, mcp, count
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
using ks::files::FilesHelpTopic;
|
||||
|
||||
constexpr struct
|
||||
{
|
||||
const wchar_t *title,*keywords,*body;
|
||||
} filesHelpTopics[]{
|
||||
{L"File panels",L"commander left right selection tabs keyboard refresh",
|
||||
L"Use Tab to switch panes. Enter opens the selected folder or file. Insert marks an item and advances to the next row. The selection summary counts marked items.\r\n\r\n"
|
||||
L"The command bar shows the primary keys for common actions. The Left and Right menus switch modes, choose drives, sort items, and filter a pane."},
|
||||
{L"Menus and shortcuts",L"f9 access keys commands actions configuration",
|
||||
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. 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"
|
||||
L"Enter visits a result's folder. Esc stops an active search or returns from the results. Use Quick View for a preview of a local result."},
|
||||
{L"Copy, move and rename",L"transfer destination mask overwrite permissions timestamps clipboard queue",
|
||||
L"Copy and Move use the selection in the active pane. The destination starts with the other pane. Check the destination and the conflict policy before starting the operation.\r\n\r\n"
|
||||
L"Copy/Move options can limit the selection by mask, target several folders, and preserve timestamps or supported permissions. The progress dialog shows the active file and an estimate when enough data has transferred."},
|
||||
{L"Delete and Recycle Bin",L"permanent remove recovery confirmation shift delete",
|
||||
L"Delete respects the selected items and shows a confirmation. Local files are sent to the Recycle Bin when supported. Check the notice for remote locations or permanent deletion.\r\n\r\n"
|
||||
L"Shift+Delete requests permanent deletion. Cancel the confirmation to keep the selection without deleting it."},
|
||||
{L"Archives",L"zip 7z pack extract compression update",
|
||||
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 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. 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"
|
||||
L"With a command name at the caret, F1 can open its Windows command reference. With an empty command line F1 opens the Files guide."},
|
||||
{L"Text Viewer and Quick View",L"preview read file html hex bookmark go to search",
|
||||
L"View opens a separate window. Quick View previews the local selection alongside its pane. View as hex displays binary data. A local Viewer refreshes when its file is changed externally.\r\n\r\n"
|
||||
L"Use the Viewer menus for Find, page navigation and bookmarks. Options opens the Viewer appearance page."},
|
||||
{L"Text Editor",L"edit save encoding f2 f4 f6 external changes buffers",
|
||||
L"Edit opens a text file for changes. The Editor menu provides Save, Find, undo and encoding controls. Switching to Viewer keeps a pending Editor buffer for the open document.\r\n\r\n"
|
||||
L"When the disk version changes, choose Reload or Keep buffer. Saving checks the disk version again and reports a conflict if the file has changed."},
|
||||
{L"Markdown preview",L"markdown rendered source local links images search",
|
||||
L"Open a Markdown file in Viewer to read the rendered document. Use its navigation controls for local links and its search form to find rendered text. Switch back to source for editing.\r\n\r\n"
|
||||
L"Options opens the Markdown page for width, font and scale. Markdown's scale is separate from the text Viewer and Editor."},
|
||||
{L"Image Viewer and Editor",L"png jpeg image zoom rotate crop undo save copy",
|
||||
L"View opens supported images with fit, zoom and navigation controls. Local PNG and JPEG files can be opened with Edit to rotate or crop them.\r\n\r\n"
|
||||
L"Use Undo to reverse edits and Save Copy to create a new file. Replacing the original requires confirmation and checks for external changes."},
|
||||
{L"File comparison",L"diff unified changes left right hunk apply undo whitespace",
|
||||
L"Select the two files and choose Compare files. Previous and Next jump between change blocks. Unified changes the view, and Fold unchanged collapses matching context.\r\n\r\n"
|
||||
L"Apply to left or right changes that side's draft. Use Undo or save the selected side when ready. Appearance opens the comparison font, colors and scale."},
|
||||
{L"Git Changes",L"staged unstaged repository status commit branch diff",
|
||||
L"Open Git Changes in a Git working tree to inspect changes, branches and history. Select an entry to review its diff.\r\n\r\n"
|
||||
L"Stage the changes you want to include. Commit staged changes shows the items currently in the index before writing the commit."},
|
||||
{L"Environment Variables",L"user system process path edit windows variables",
|
||||
L"Environment Variables lists user, system and process scopes. Choose a scope, then review the selected name and value before editing.\r\n\r\n"
|
||||
L"Changes to the system scope require the appropriate Windows permission. Existing applications may need to reopen before using updated values."},
|
||||
{L"Files Options",L"preferences settings search apply reset cancel layout font",
|
||||
L"Search settings by name or choose a section in the tree. Apply saves the draft and refreshes affected windows. Cancel discards the pending changes.\r\n\r\n"
|
||||
L"Reset selected to defaults applies to the displayed section. Import JSON and Export JSON transfer supported settings groups between profiles."},
|
||||
{L"Keyboard schemes",L"keys shortcuts multiple primary named duplicate context conflict",
|
||||
L"Use Commands → Keyboard shortcuts to switch or copy a named scheme. Select a command, enter a key and choose Add. Make primary controls which binding appears in the command bar.\r\n\r\n"
|
||||
L"Keys already assigned in an overlapping context cannot be added to another command in that context. F1 opens this guide."},
|
||||
{L"Appearance and scale",L"theme light dark windows appearance font palette size",
|
||||
L"Panels, Viewer, Editor, Markdown, terminal and comparison each have a saved scale. Use the visible area's Options or Appearance command to open its settings.\r\n\r\n"
|
||||
L"Viewer and Editor can use System (Windows). Assign either a stock or named palette to each Windows mode under Appearance → System themes."},
|
||||
{L"Import and export settings",L"json portable backup restore transfer option groups",
|
||||
L"Select the saved settings groups to include in an export. The supported groups cover colors and file styles, panel layout and keyboard schemes.\r\n\r\n"
|
||||
L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."},
|
||||
{L"Files log",L"diagnostic journal error logging rotate copy record",
|
||||
L"Open Files log from Commands to see recent entries. Switch between the current and previous rotated log, or use Refresh to read newer entries.\r\n\r\n"
|
||||
L"Select an entry to copy its timestamp and summary. The viewer shows only supported diagnostic details."},
|
||||
{L"Files MCP",L"local loopback bearer authorization model context protocol read only search token",
|
||||
L"Open Commands → Files MCP and select Start. Configure the client with the displayed loopback endpoint and use the session token as the bearer credential.\r\n\r\n"
|
||||
L"The client can read current local panes, search their displayed entries and read cached file metadata. Stop revokes the session token."}
|
||||
};
|
||||
static_assert(std::size(filesHelpTopics)==static_cast<size_t>(FilesHelpTopic::count));
|
||||
|
||||
constexpr int helpSearch=670,helpTopics=671,helpTitle=672,helpBody=673;
|
||||
|
||||
void displayFilesHelpTopic(HWND dialog,int topic)
|
||||
{
|
||||
if(topic<0)
|
||||
{
|
||||
SetDlgItemTextW(dialog,helpTitle,L"No matching help topics");
|
||||
SetDlgItemTextW(dialog,helpBody,L"");
|
||||
return;
|
||||
}
|
||||
const auto &entry=filesHelpTopics[topic];
|
||||
SetDlgItemTextW(dialog,helpTitle,entry.title);
|
||||
SetDlgItemTextW(dialog,helpBody,entry.body);
|
||||
SendDlgItemMessageW(dialog,helpBody,EM_SETSEL,0,0);
|
||||
SendDlgItemMessageW(dialog,helpBody,EM_SCROLLCARET,0,0);
|
||||
}
|
||||
|
||||
void filterFilesHelpTopics(HWND dialog,int previous)
|
||||
{
|
||||
wchar_t buffer[129]{};
|
||||
GetDlgItemTextW(dialog,helpSearch,buffer,std::size(buffer));
|
||||
std::wistringstream query(ks::lower(buffer));
|
||||
std::vector<std::wstring> tokens;
|
||||
for(std::wstring term;query>>term;) tokens.push_back(std::move(term));
|
||||
const auto list=GetDlgItem(dialog,helpTopics);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
int displayed=-1;
|
||||
LRESULT selected=LB_ERR;
|
||||
for(size_t i=0;i<std::size(filesHelpTopics);++i)
|
||||
{
|
||||
const auto &topic=filesHelpTopics[i];
|
||||
const auto text=ks::lower(std::wstring(topic.title)+L" "+topic.keywords+L" "+topic.body);
|
||||
if(!std::ranges::all_of(tokens,[&](const auto &word){return text.find(word)!=text.npos;})) continue;
|
||||
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(topic.title));
|
||||
if(row<0) continue;
|
||||
SendMessageW(list,LB_SETITEMDATA,row,i);
|
||||
if(selected==LB_ERR || static_cast<int>(i)==previous)
|
||||
{
|
||||
selected=row;
|
||||
displayed=static_cast<int>(i);
|
||||
}
|
||||
}
|
||||
if(selected!=LB_ERR) SendMessageW(list,LB_SETCURSEL,selected,0);
|
||||
displayFilesHelpTopic(dialog,displayed);
|
||||
}
|
||||
|
||||
int selectedFilesHelpTopic(HWND dialog)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,helpTopics,LB_GETCURSEL,0,0);
|
||||
return row==LB_ERR?-1:static_cast<int>(SendDlgItemMessageW(dialog,helpTopics,LB_GETITEMDATA,row,0));
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK filesHelpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SendDlgItemMessageW(dialog,helpSearch,EM_SETLIMITTEXT,128,0);
|
||||
filterFilesHelpTopics(dialog,static_cast<int>(lp));
|
||||
SetFocus(GetDlgItem(dialog,helpSearch));
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
if(LOWORD(wp)==helpSearch && HIWORD(wp)==EN_CHANGE)
|
||||
filterFilesHelpTopics(dialog,selectedFilesHelpTopic(dialog));
|
||||
if(LOWORD(wp)==helpTopics && HIWORD(wp)==LBN_SELCHANGE)
|
||||
displayFilesHelpTopic(dialog,selectedFilesHelpTopic(dialog));
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void showFilesHelp(HWND owner,FilesHelpTopic topic)
|
||||
{
|
||||
if(!owner || !IsWindow(owner) || FilesModalDialog::resourceFor(owner)==618) return;
|
||||
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(618),owner,filesHelpDialog,
|
||||
static_cast<LPARAM>(topic),false,false);
|
||||
dialog.runModal();
|
||||
}
|
||||
|
||||
FilesHelpTopic filesMenuHelpTopic()
|
||||
{
|
||||
if(folderPicker) return FilesHelpTopic::navigation;
|
||||
if(!commandPicker) return IsWindowVisible(picker)?FilesHelpTopic::connections:FilesHelpTopic::menus;
|
||||
const auto row=SendMessageW(picker,LB_GETCURSEL,0,0);
|
||||
if(!selectablePickerRow(row)) return FilesHelpTopic::menus;
|
||||
const int action=commandActions[row];
|
||||
if(menuIndex==0 || menuIndex==4) return action==4?FilesHelpTopic::navigation:FilesHelpTopic::panels;
|
||||
if(menuIndex==1)
|
||||
{
|
||||
if(action==4) return FilesHelpTopic::archive;
|
||||
if(action==5 || action==6) return FilesHelpTopic::properties;
|
||||
return action<=2?FilesHelpTopic::transfer:FilesHelpTopic::menus;
|
||||
}
|
||||
if(menuIndex!=2) return FilesHelpTopic::menus;
|
||||
switch(action)
|
||||
{
|
||||
case 1: case 4: case 10: case 13: case 14: return FilesHelpTopic::viewer;
|
||||
case 2: case 5: return FilesHelpTopic::editor;
|
||||
case 3: case 11: return FilesHelpTopic::navigation;
|
||||
case 6: case 7: return FilesHelpTopic::connections;
|
||||
case 8: return FilesHelpTopic::comparison;
|
||||
case 9: return FilesHelpTopic::find;
|
||||
case 12: return FilesHelpTopic::space;
|
||||
case 15: return FilesHelpTopic::properties;
|
||||
case 16: return FilesHelpTopic::git;
|
||||
case 17: return FilesHelpTopic::environment;
|
||||
case 19: return FilesHelpTopic::terminal;
|
||||
case 20: return FilesHelpTopic::keys;
|
||||
case 21: return FilesHelpTopic::appearance;
|
||||
case 23: return FilesHelpTopic::log;
|
||||
case 24: return FilesHelpTopic::mcp;
|
||||
default: return FilesHelpTopic::menus;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<FilesHelpTopic> filesHelpForWindow(HWND root,HWND target)
|
||||
{
|
||||
const auto resource=FilesModalDialog::resourceFor(root);
|
||||
switch(resource)
|
||||
{
|
||||
case 618: return {};
|
||||
case 101:
|
||||
{
|
||||
const auto control=GetDlgCtrlID(target);
|
||||
if(control==optionsImport || control==optionsExport) return FilesHelpTopic::portability;
|
||||
if(control==321 || control==comparisonKeySchemesButton) return FilesHelpTopic::keys;
|
||||
if(const auto *option=reinterpret_cast<const OptionsDraft*>(GetWindowLongPtrW(root,DWLP_USER)))
|
||||
{
|
||||
if(option->page==Appearance || control==areaScaleControl) return FilesHelpTopic::appearance;
|
||||
if(option->page==TextViewer && option->section==markdownSection) return FilesHelpTopic::markdown;
|
||||
if(option->page==PanelModes) return FilesHelpTopic::panels;
|
||||
if(option->page==CommandLine) return FilesHelpTopic::terminal;
|
||||
if(option->page==CompareFiles) return FilesHelpTopic::comparison;
|
||||
}
|
||||
return FilesHelpTopic::options;
|
||||
}
|
||||
case 102: case 103: case 104: case 105: case 108: case 113: case 129: return FilesHelpTopic::transfer;
|
||||
case 106: case 107: return FilesHelpTopic::deleteFiles;
|
||||
case 109: case 110: case 117: return FilesHelpTopic::navigation;
|
||||
case 111: return FilesHelpTopic::terminal;
|
||||
case 112: case 121: case 122: case 123: case 124: return FilesHelpTopic::connections;
|
||||
case 114: case 115: return FilesHelpTopic::comparison;
|
||||
case 116: return FilesHelpTopic::find;
|
||||
case 118: return FilesHelpTopic::space;
|
||||
case 119: return FilesHelpTopic::panels;
|
||||
case 120: return FilesHelpTopic::archive;
|
||||
case 125: case 609: return FilesHelpTopic::properties;
|
||||
case 126: return FilesHelpTopic::git;
|
||||
case 127: case 128: return FilesHelpTopic::environment;
|
||||
case 130: return FilesHelpTopic::images;
|
||||
case 602: case 613: case 614: return FilesHelpTopic::viewer;
|
||||
case 603: case 611: case 612: return FilesHelpTopic::editor;
|
||||
case 608: return FilesHelpTopic::appearance;
|
||||
case 615: case 616: return FilesHelpTopic::keys;
|
||||
case 617: return FilesHelpTopic::portability;
|
||||
case 619: return FilesHelpTopic::log;
|
||||
case 620: return FilesHelpTopic::mcp;
|
||||
case 604: case 607:
|
||||
if(const auto owner=GetWindow(root,GW_OWNER);owner && owner!=root)
|
||||
return filesHelpForWindow(owner,owner);
|
||||
break;
|
||||
}
|
||||
if(comparisonWindows.contains(root)) return FilesHelpTopic::comparison;
|
||||
if(const auto area=ks::files::textWindowAppearanceArea(root))
|
||||
return *area==AppearanceArea::markdown?FilesHelpTopic::markdown:
|
||||
*area==AppearanceArea::editor?FilesHelpTopic::editor:FilesHelpTopic::viewer;
|
||||
wchar_t type[64]{};
|
||||
GetClassNameW(root,type,std::size(type));
|
||||
if(std::wstring_view(type)==L"KSwitcherFilesImageViewer") return FilesHelpTopic::images;
|
||||
if(root!=GetParent(terminalInput)) return resource?std::optional(FilesHelpTopic::options):std::nullopt;
|
||||
if(gitChangesView && (target==gitChangesView->host || IsChild(gitChangesView->host,target))) return FilesHelpTopic::git;
|
||||
if(quickImageWindow && (target==quickImageWindow || IsChild(quickImageWindow,target))) return FilesHelpTopic::images;
|
||||
if(quickViewWindow && (target==quickViewWindow || IsChild(quickViewWindow,target))) return FilesHelpTopic::viewer;
|
||||
if(IsWindowVisible(menuBar) || IsWindowVisible(picker)) return filesMenuHelpTopic();
|
||||
if(terminalVisible || target==terminalOutput || IsChild(terminalOutput,target)) return FilesHelpTopic::terminal;
|
||||
if(target==panels[0].path || target==panels[1].path) return FilesHelpTopic::navigation;
|
||||
return panels[active].findOrigin?FilesHelpTopic::find:FilesHelpTopic::panels;
|
||||
}
|
||||
|
||||
bool handleFilesHelpMessage(const MSG &message)
|
||||
{
|
||||
const bool posted=message.message==ks::files::filesHelpRequest;
|
||||
if(!message.hwnd || (!posted && (message.message!=WM_KEYDOWN || message.wParam!=VK_F1 ||
|
||||
((GetKeyState(VK_CONTROL)|GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|
|
||||
GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)))) return false;
|
||||
const auto root=GetAncestor(message.hwnd,GA_ROOT);
|
||||
auto target=message.hwnd;
|
||||
if(root==target)
|
||||
if(const auto focus=GetFocus();focus && IsChild(root,focus)) target=focus;
|
||||
if(FilesModalDialog::resourceFor(root)==618) return true;
|
||||
const auto topic=posted && message.hwnd==GetParent(terminalInput)?
|
||||
std::optional(FilesHelpTopic::terminal):filesHelpForWindow(root,target);
|
||||
if(!topic) return false;
|
||||
if(!posted)
|
||||
{
|
||||
if(message.lParam&(1LL<<30)) return true;
|
||||
if(target==terminalInput && commandLineAvailable(root) && handleCompletionKey(VK_F1,message.lParam))
|
||||
return true;
|
||||
}
|
||||
showFilesHelp(root,*topic);
|
||||
return true;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <wincodec.h>
|
||||
#include <webp/decode.h>
|
||||
#include <webp/demux.h>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
@@ -58,13 +59,14 @@ struct ImagingObject
|
||||
T *operator->() const {return value;}
|
||||
};
|
||||
|
||||
struct Apartment
|
||||
{
|
||||
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
|
||||
};
|
||||
|
||||
ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop)
|
||||
{
|
||||
struct Apartment
|
||||
{
|
||||
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
|
||||
};
|
||||
const Apartment apartment;
|
||||
if(apartment.initialized!=RPC_E_CHANGED_MODE) checkImage(apartment.initialized);
|
||||
ImagingObject<IWICImagingFactory> factory;
|
||||
@@ -141,6 +143,78 @@ bool isImagePath(const std::filesystem::path &path)
|
||||
return imageFormat(path)!=ImageFormat::unknown;
|
||||
}
|
||||
|
||||
bool isEditableImagePath(const std::filesystem::path &path)
|
||||
{
|
||||
const auto format=imageFormat(path);
|
||||
return format==ImageFormat::png || format==ImageFormat::jpeg;
|
||||
}
|
||||
|
||||
void encodeImage(const ImageRaster &raster,const fs::path &contents,const fs::path &name)
|
||||
{
|
||||
const auto format=imageFormat(name);
|
||||
if(format!=ImageFormat::png && format!=ImageFormat::jpeg)
|
||||
throw std::runtime_error("Choose a PNG or JPEG file.");
|
||||
checkImageDimensions(raster.width,raster.height);
|
||||
if(raster.pixels.size()!=size_t(raster.width)*raster.height) throw std::runtime_error(invalidImage);
|
||||
const auto check=[](HRESULT result) {
|
||||
if(FAILED(result)) throw std::system_error(static_cast<int>(result),std::system_category(),"Encode image");
|
||||
};
|
||||
const Apartment apartment;
|
||||
if(apartment.initialized!=RPC_E_CHANGED_MODE) check(apartment.initialized);
|
||||
ImagingObject<IWICImagingFactory> factory;
|
||||
check(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
|
||||
const bool png=format==ImageFormat::png;
|
||||
ImagingObject<IWICStream> stream;
|
||||
check(factory->CreateStream(&stream.value));
|
||||
check(stream->InitializeFromFilename(contents.c_str(),GENERIC_WRITE));
|
||||
ImagingObject<IWICBitmapEncoder> encoder;
|
||||
check(factory->CreateEncoder(png?GUID_ContainerFormatPng:GUID_ContainerFormatJpeg,nullptr,&encoder.value));
|
||||
check(encoder->Initialize(stream.value,WICBitmapEncoderNoCache));
|
||||
ImagingObject<IWICBitmapFrameEncode> frame;
|
||||
ImagingObject<IPropertyBag2> options;
|
||||
check(encoder->CreateNewFrame(&frame.value,&options.value));
|
||||
if(!png)
|
||||
{
|
||||
wchar_t qualityName[]=L"ImageQuality";
|
||||
PROPBAG2 property{};
|
||||
property.pstrName=qualityName;
|
||||
VARIANT quality{};
|
||||
quality.vt=VT_R4;
|
||||
quality.fltVal=0.95f;
|
||||
check(options->Write(1,&property,&quality));
|
||||
}
|
||||
check(frame->Initialize(options.value));
|
||||
check(frame->SetSize(raster.width,raster.height));
|
||||
auto pixelFormat=png?GUID_WICPixelFormat32bppBGRA:GUID_WICPixelFormat24bppBGR;
|
||||
check(frame->SetPixelFormat(&pixelFormat));
|
||||
|
||||
auto *pixels=raster.pixels.data();
|
||||
std::vector<uint32_t> opaque;
|
||||
if(!png && std::any_of(raster.pixels.begin(),raster.pixels.end(),[](uint32_t pixel){return (pixel>>24)!=255;}))
|
||||
{
|
||||
opaque=raster.pixels;
|
||||
for(auto &pixel:opaque)
|
||||
{
|
||||
const auto white=255-(pixel>>24);
|
||||
const auto gray=white|(white<<8)|(white<<16);
|
||||
pixel=0xff000000|((pixel&0x00ffffff)+gray);
|
||||
}
|
||||
pixels=opaque.data();
|
||||
}
|
||||
const auto stride=static_cast<UINT>(raster.width*sizeof(uint32_t));
|
||||
ImagingObject<IWICBitmap> source;
|
||||
check(factory->CreateBitmapFromMemory(raster.width,raster.height,GUID_WICPixelFormat32bppPBGRA,stride,
|
||||
static_cast<UINT>(raster.pixels.size()*sizeof(uint32_t)),
|
||||
reinterpret_cast<BYTE *>(const_cast<uint32_t *>(pixels)),&source.value));
|
||||
ImagingObject<IWICFormatConverter> converter;
|
||||
check(factory->CreateFormatConverter(&converter.value));
|
||||
check(converter->Initialize(source.value,pixelFormat,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom));
|
||||
check(frame->WriteSource(converter.value,nullptr));
|
||||
check(frame->Commit());
|
||||
check(encoder->Commit());
|
||||
check(stream->Commit(STGC_DEFAULT));
|
||||
}
|
||||
|
||||
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop)
|
||||
{
|
||||
const auto format=imageFormat(name);
|
||||
|
||||
@@ -10,10 +10,12 @@ namespace ks::files
|
||||
struct ImageRaster
|
||||
{
|
||||
unsigned width{}, height{};
|
||||
std::vector<uint32_t> pixels;
|
||||
std::vector<uint32_t> pixels; // Premultiplied BGRA.
|
||||
};
|
||||
|
||||
inline constexpr uint64_t imageSourceLimit=96ULL*1024*1024;
|
||||
bool isImagePath(const std::filesystem::path &path);
|
||||
bool isEditableImagePath(const std::filesystem::path &path);
|
||||
void encodeImage(const ImageRaster &raster,const std::filesystem::path &contents,const std::filesystem::path &name);
|
||||
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop={});
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
#include "files_image_edit.h"
|
||||
#include "files_win32_replace.h"
|
||||
#include <system_error>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace
|
||||
{
|
||||
struct ImageFile
|
||||
{
|
||||
HANDLE handle=INVALID_HANDLE_VALUE;
|
||||
~ImageFile() {if(handle!=INVALID_HANDLE_VALUE) CloseHandle(handle);}
|
||||
};
|
||||
|
||||
struct StagedImage
|
||||
{
|
||||
std::filesystem::path path;
|
||||
~StagedImage() {if(!path.empty()) DeleteFileW(path.c_str());}
|
||||
};
|
||||
|
||||
[[noreturn]] void fail(const char *message,DWORD error=GetLastError())
|
||||
{
|
||||
throw std::system_error(static_cast<int>(error),std::system_category(),message);
|
||||
}
|
||||
|
||||
ImageRevision readRevision(HANDLE handle)
|
||||
{
|
||||
const auto revision=fileVersion(handle);
|
||||
if(revision.info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))
|
||||
throw std::runtime_error("Choose a regular local image.");
|
||||
return revision;
|
||||
}
|
||||
|
||||
bool contains(unsigned width,unsigned height,const ImageRegion &area)
|
||||
{
|
||||
return area.width && area.height && area.x<width && area.y<height &&
|
||||
area.width<=width-area.x && area.height<=height-area.y;
|
||||
}
|
||||
}
|
||||
|
||||
ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area)
|
||||
{
|
||||
auto ®ion=geometry.region;
|
||||
const bool sideways=(geometry.turns&1)!=0;
|
||||
if(geometry.turns>=4 || !contains(sideways?region.height:region.width,sideways?region.width:region.height,area))
|
||||
throw std::runtime_error("The crop rectangle must fit inside the image.");
|
||||
const auto width=region.width, height=region.height;
|
||||
switch(geometry.turns)
|
||||
{
|
||||
case 0: region.x+=area.x; region.y+=area.y; break;
|
||||
case 1: region.x+=area.y; region.y+=height-area.x-area.width; break;
|
||||
case 2: region.x+=width-area.x-area.width; region.y+=height-area.y-area.height; break;
|
||||
case 3: region.x+=width-area.y-area.height; region.y+=area.x; break;
|
||||
}
|
||||
region.width=sideways?area.height:area.width;
|
||||
region.height=sideways?area.width:area.height;
|
||||
return geometry;
|
||||
}
|
||||
|
||||
ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry)
|
||||
{
|
||||
const auto ®ion=geometry.region;
|
||||
if(geometry.turns>=4 || !contains(original.width,original.height,region) ||
|
||||
original.pixels.size()!=size_t(original.width)*original.height)
|
||||
throw std::runtime_error("The image edit exceeds the original bounds.");
|
||||
const bool sideways=geometry.turns&1;
|
||||
ImageRaster output{sideways?region.height:region.width,sideways?region.width:region.height,{}};
|
||||
output.pixels.resize(size_t(output.width)*output.height);
|
||||
for(unsigned y=0;y<output.height;++y)
|
||||
{
|
||||
for(unsigned x=0;x<output.width;++x)
|
||||
{
|
||||
unsigned fromX{},fromY{};
|
||||
switch(geometry.turns)
|
||||
{
|
||||
case 0: fromX=x; fromY=y; break;
|
||||
case 1: fromX=y; fromY=region.height-1-x; break;
|
||||
case 2: fromX=region.width-1-x; fromY=region.height-1-y; break;
|
||||
case 3: fromX=region.width-1-y; fromY=x; break;
|
||||
}
|
||||
output.pixels[size_t(y)*output.width+x]=original.pixels[size_t(region.y+fromY)*original.width+region.x+fromX];
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
ImageRevision imageRevision(const std::filesystem::path &path)
|
||||
{
|
||||
ImageFile file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
|
||||
if(file.handle==INVALID_HANDLE_VALUE) fail("Open image revision");
|
||||
return readRevision(file.handle);
|
||||
}
|
||||
|
||||
bool sameImageRevision(const ImageRevision &first,const ImageRevision &second)
|
||||
{
|
||||
return first==second;
|
||||
}
|
||||
|
||||
ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected)
|
||||
{
|
||||
const auto stagedPath=temporaryPath(path.parent_path());
|
||||
{
|
||||
ImageFile reserve{CreateFileW(stagedPath.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,nullptr)};
|
||||
if(reserve.handle==INVALID_HANDLE_VALUE) fail("Create image staging file");
|
||||
}
|
||||
StagedImage pending{stagedPath};
|
||||
encodeImage(raster,pending.path,path);
|
||||
// Keep the saved file's identity through publication, even if the path changes again.
|
||||
ImageFile saved{CreateFileW(pending.path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
|
||||
if(saved.handle==INVALID_HANDLE_VALUE) fail("Track saved image");
|
||||
if(!expected)
|
||||
{
|
||||
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Publish image copy");
|
||||
pending.path.clear();
|
||||
return readRevision(saved.handle);
|
||||
}
|
||||
|
||||
ImageFile current{CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,nullptr,
|
||||
OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
|
||||
if(current.handle==INVALID_HANDLE_VALUE) fail("Verify original image");
|
||||
if(!sameImageRevision(*expected,readRevision(current.handle)))
|
||||
throw std::runtime_error("The original image changed outside Files. Your edits remain open.");
|
||||
const auto backup=temporaryPath(path.parent_path());
|
||||
if(const auto error=replaceFileWithBackup(path,pending.path,backup)) fail("Replace original image",error);
|
||||
pending.path.clear();
|
||||
DeleteFileW(backup.c_str());
|
||||
return readRevision(saved.handle);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "files_image_decode.h"
|
||||
#include "files_win32_replace.h"
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
struct ImageRegion
|
||||
{
|
||||
unsigned x{}, y{}, width{}, height{};
|
||||
bool operator==(const ImageRegion &) const = default;
|
||||
};
|
||||
|
||||
struct ImageGeometry
|
||||
{
|
||||
ImageRegion region;
|
||||
unsigned turns{};
|
||||
bool operator==(const ImageGeometry &) const = default;
|
||||
};
|
||||
|
||||
using ImageRevision=LocalFileVersion;
|
||||
|
||||
ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area);
|
||||
ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry);
|
||||
ImageRevision imageRevision(const std::filesystem::path &path);
|
||||
bool sameImageRevision(const ImageRevision &first,const ImageRevision &second);
|
||||
ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected=nullptr);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
struct ImageCropPrompt
|
||||
{
|
||||
unsigned width,height;
|
||||
ks::files::ImageRegion result;
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK imageCropDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
constexpr int hint=650, x=651, y=652, width=653, height=654, footer=655;
|
||||
if(message==WM_DRAWITEM)
|
||||
{
|
||||
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
|
||||
return TRUE;
|
||||
}
|
||||
if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Crop image ",false,{footer}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<ImageCropPrompt *>(lp);
|
||||
SetWindowLongPtrW(window,DWLP_USER,lp);
|
||||
prepareCopyDialog(window);
|
||||
layoutDialogContent(window,hint);
|
||||
layoutDialogButtons(window,footer,{IDOK,IDCANCEL});
|
||||
const auto description=L"Image: "+std::to_wstring(prompt.width)+L" × "+std::to_wstring(prompt.height)+
|
||||
L" pixels. X and Y start at zero.";
|
||||
SetDlgItemTextW(window,hint,description.c_str());
|
||||
for(const auto id:{x,y,width,height})
|
||||
{
|
||||
fitFarEditToLine(GetDlgItem(window,id));
|
||||
const auto value=id==width?prompt.width:id==height?prompt.height:0;
|
||||
SetDlgItemInt(window,id,value,FALSE);
|
||||
}
|
||||
SetFocus(GetDlgItem(window,x));
|
||||
SendDlgItemMessageW(window,x,EM_SETSEL,0,-1);
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(window,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
|
||||
auto &prompt=*reinterpret_cast<ImageCropPrompt *>(GetWindowLongPtrW(window,DWLP_USER));
|
||||
std::array<unsigned,4> fields{};
|
||||
for(size_t i=0;i<fields.size();++i)
|
||||
{
|
||||
const int id=x+static_cast<int>(i);
|
||||
BOOL valid{};
|
||||
fields[i]=GetDlgItemInt(window,id,&valid,FALSE);
|
||||
if(!valid)
|
||||
{
|
||||
showFilesNotice(window,L"Enter a whole number of pixels.",L"Crop image");
|
||||
SetFocus(GetDlgItem(window,id));
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
const auto [left,top,wide,high]=fields;
|
||||
if(!wide || !high || left>=prompt.width || top>=prompt.height ||
|
||||
wide>prompt.width-left || high>prompt.height-top)
|
||||
{
|
||||
showFilesNotice(window,L"The crop rectangle must fit inside the image.",L"Crop image");
|
||||
return TRUE;
|
||||
}
|
||||
prompt.result={left,top,wide,high};
|
||||
FilesModalDialog::finish(window,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
ks::files::ImageEditDialogs imageEditDialogs()
|
||||
{
|
||||
return {
|
||||
[](HWND owner,unsigned width,unsigned height) -> std::optional<ks::files::ImageRegion>
|
||||
{
|
||||
ImageCropPrompt crop{width,height,{}};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(130),owner,
|
||||
imageCropDialog,reinterpret_cast<LPARAM>(&crop))==IDOK) return crop.result;
|
||||
return {};
|
||||
},
|
||||
[](HWND owner,const fs::path &original) -> fs::path
|
||||
{
|
||||
const auto name=original.stem().native()+L" copy"+original.extension().native();
|
||||
std::array<wchar_t,32768> file{};
|
||||
wcsncpy_s(file.data(),file.size(),name.c_str(),_TRUNCATE);
|
||||
auto initial=original.parent_path().native();
|
||||
OPENFILENAMEW dialog{sizeof(dialog)};
|
||||
dialog.hwndOwner=owner;
|
||||
dialog.lpstrTitle=L"Save an image copy";
|
||||
dialog.lpstrFilter=L"PNG (*.png)\0*.png\0JPEG (*.jpg, *.jpeg)\0*.jpg;*.jpeg\0";
|
||||
dialog.nFilterIndex=ks::lower(original.extension().native())==L".png"?1:2;
|
||||
dialog.lpstrFile=file.data();
|
||||
dialog.nMaxFile=static_cast<DWORD>(file.size());
|
||||
dialog.lpstrInitialDir=initial.c_str();
|
||||
dialog.lpstrDefExt=dialog.nFilterIndex==1?L"png":L"jpg";
|
||||
dialog.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST;
|
||||
if(GetSaveFileNameW(&dialog)) return file.data();
|
||||
if(CommDlgExtendedError()) throw std::runtime_error("Could not open the image save dialog.");
|
||||
return {};
|
||||
},
|
||||
[](HWND owner,const std::wstring &text,const wchar_t *title)
|
||||
{
|
||||
return showFilesNotice(owner,text.c_str(),title,{.confirm=true,.tone=FilesNoticeTone::warning})==IDYES;
|
||||
},
|
||||
[](HWND owner,const wchar_t *text)
|
||||
{
|
||||
showFilesNotice(owner,text,L"Image editor",{.tone=FilesNoticeTone::warning});
|
||||
},
|
||||
FilesModalDialog::dismissOwned,textWindowDialogs().reloadChanged
|
||||
};
|
||||
}
|
||||
+233
-35
@@ -17,8 +17,9 @@ namespace
|
||||
{
|
||||
namespace fs=std::filesystem;
|
||||
constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer";
|
||||
constexpr UINT_PTR imageTimer=1;
|
||||
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize };
|
||||
constexpr UINT_PTR imageTimer=1, externalImageTimer=2;
|
||||
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize,
|
||||
rotateLeft, rotateRight, crop, undoEdit, saveCopy, replaceOriginal };
|
||||
|
||||
void fillImageView(HDC dc,const RECT &rect,COLORREF color)
|
||||
{
|
||||
@@ -37,14 +38,32 @@ struct ImageView
|
||||
ImageLoadRetry retry;
|
||||
bool retried{};
|
||||
std::function<void(HWND)> onClose;
|
||||
std::array<HWND,6> buttons{};
|
||||
std::array<HWND,replaceOriginal> buttons{};
|
||||
struct Draft
|
||||
{
|
||||
ImageEditDialogs dialogs;
|
||||
ImageRaster original;
|
||||
std::optional<ImageRevision> version;
|
||||
ImageGeometry geometry{}, saved{};
|
||||
std::vector<ImageGeometry> undo;
|
||||
bool dirty() const {return geometry!=saved;}
|
||||
};
|
||||
std::optional<Draft> draft;
|
||||
struct Loaded
|
||||
{
|
||||
ImageRaster raster;
|
||||
std::optional<ImageRevision> revision;
|
||||
};
|
||||
bool confirmingClose{};
|
||||
std::optional<ImageRevision> observedVersion;
|
||||
HFONT font{};
|
||||
UINT fontDpi{};
|
||||
int toolbarHeight{};
|
||||
HBITMAP bitmap{};
|
||||
unsigned width{},height{};
|
||||
fs::path requested;
|
||||
std::wstring error;
|
||||
std::future<ImageRaster> reading;
|
||||
std::future<Loaded> reading;
|
||||
std::stop_source stop;
|
||||
uint64_t revision{}, started{};
|
||||
double zoom=1, x{}, y{};
|
||||
@@ -64,7 +83,7 @@ struct ImageView
|
||||
{
|
||||
RECT area{};
|
||||
GetClientRect(window,&area);
|
||||
area.top=std::min(area.bottom,static_cast<LONG>(scale(35)));
|
||||
area.top=std::min(area.bottom,static_cast<LONG>(toolbarHeight));
|
||||
area.bottom=std::max(area.top,area.bottom-scale(27));
|
||||
return area;
|
||||
}
|
||||
@@ -86,45 +105,83 @@ struct ImageView
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
const int left=scale(4), gap=scale(3), height=scale(27);
|
||||
const int count=embedded?4:6;
|
||||
const int available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
|
||||
const int unit=std::min(scale(80),available/count);
|
||||
int x=left;
|
||||
for(auto button:buttons)
|
||||
const auto place=[&](unsigned first,unsigned last,int y,int preferred) {
|
||||
const auto count=static_cast<int>(last-first+1);
|
||||
const auto available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
|
||||
const auto unit=std::min(scale(preferred),available/count);
|
||||
int x=left;
|
||||
for(unsigned id=first;id<=last;++id)
|
||||
{
|
||||
SetWindowPos(buttons[id-1],nullptr,x,scale(y),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
x+=unit+gap;
|
||||
}
|
||||
};
|
||||
place(embedded || draft?zoomOut:previous,actualSize,4,80);
|
||||
int rows=0;
|
||||
if(draft)
|
||||
{
|
||||
if(!button) continue;
|
||||
SetWindowPos(button,nullptr,x,scale(4),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
x+=unit+gap;
|
||||
int buttonWidth=scale(80);
|
||||
if(const auto dc=GetDC(window))
|
||||
{
|
||||
const auto previousFont=font?SelectObject(dc,font):nullptr;
|
||||
for(unsigned id=rotateLeft;id<=replaceOriginal;++id)
|
||||
{
|
||||
wchar_t label[32]{};
|
||||
const auto length=GetWindowTextW(buttons[id-1],label,static_cast<int>(std::size(label)));
|
||||
SIZE extent{};
|
||||
if(GetTextExtentPoint32W(dc,label,length,&extent))
|
||||
buttonWidth=std::max(buttonWidth,static_cast<int>(extent.cx)+scale(8));
|
||||
}
|
||||
if(previousFont) SelectObject(dc,previousFont);
|
||||
ReleaseDC(window,dc);
|
||||
}
|
||||
const auto perRow=static_cast<unsigned>(std::max(1,(static_cast<int>(bounds.right)-left*2+gap)/(buttonWidth+gap)));
|
||||
for(unsigned first=rotateLeft;first<=replaceOriginal;first+=perRow)
|
||||
place(first,std::min<unsigned>(replaceOriginal,first+perRow-1),35+31*rows++,130);
|
||||
}
|
||||
toolbarHeight=scale(35+31*rows);
|
||||
clampOffset();
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void updateButtons() const
|
||||
{
|
||||
if(!embedded)
|
||||
if(!embedded && !draft)
|
||||
{
|
||||
EnableWindow(buttons[previous-1],position>0);
|
||||
EnableWindow(buttons[following-1],position+1<images.size());
|
||||
}
|
||||
for(unsigned id=zoomOut;id<=actualSize;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
|
||||
if(draft)
|
||||
{
|
||||
for(unsigned id=rotateLeft;id<=crop;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
|
||||
EnableWindow(buttons[undoEdit-1],!draft->undo.empty());
|
||||
EnableWindow(buttons[saveCopy-1],bitmap!=nullptr);
|
||||
EnableWindow(buttons[replaceOriginal-1],draft->version && draft->dirty());
|
||||
const auto title=L"Editor — "+requested.filename().wstring()+(draft->dirty()?L" *":L"");
|
||||
SetWindowTextW(window,title.c_str());
|
||||
}
|
||||
for(auto button:buttons)
|
||||
if(button) InvalidateRect(button,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void request(const fs::path &path)
|
||||
void request(const fs::path &path,bool reload=false)
|
||||
{
|
||||
if(requested==path) return;
|
||||
if(requested==path && !reload) return;
|
||||
requested=path;
|
||||
++revision;
|
||||
stop.request_stop();
|
||||
retried=false;
|
||||
error.clear();
|
||||
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
|
||||
width=height=0;
|
||||
fit=true;
|
||||
x=y=0;
|
||||
if(!embedded)
|
||||
if(!reload)
|
||||
{
|
||||
observedVersion.reset();
|
||||
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
|
||||
width=height=0;
|
||||
fit=true;
|
||||
x=y=0;
|
||||
}
|
||||
if(!embedded && !draft)
|
||||
{
|
||||
const auto label=L"Viewer — "+path.filename().wstring();
|
||||
SetWindowTextW(window,label.c_str());
|
||||
@@ -134,7 +191,7 @@ struct ImageView
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void show(ImageRaster image)
|
||||
void show(const ImageRaster &image)
|
||||
{
|
||||
BITMAPINFO info{};
|
||||
info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
|
||||
@@ -144,12 +201,16 @@ struct ImageView
|
||||
info.bmiHeader.biBitCount=32;
|
||||
info.bmiHeader.biCompression=BI_RGB;
|
||||
void *bits=nullptr;
|
||||
bitmap=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
|
||||
if(!bitmap || !bits) throw std::runtime_error("Could not display this image.");
|
||||
const auto next=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
|
||||
if(!next || !bits)
|
||||
{
|
||||
if(next) DeleteObject(next);
|
||||
throw std::runtime_error("Could not display this image.");
|
||||
}
|
||||
std::memcpy(bits,image.pixels.data(),image.pixels.size()*sizeof(uint32_t));
|
||||
if(const auto old=std::exchange(bitmap,next)) DeleteObject(old);
|
||||
width=image.width;
|
||||
height=image.height;
|
||||
updateButtons();
|
||||
}
|
||||
|
||||
void poll()
|
||||
@@ -163,7 +224,20 @@ struct ImageView
|
||||
try
|
||||
{
|
||||
auto image=reading.get();
|
||||
if(current) show(std::move(image));
|
||||
if(current)
|
||||
{
|
||||
show(image.raster);
|
||||
observedVersion=image.revision;
|
||||
if(draft)
|
||||
{
|
||||
draft->undo.clear();
|
||||
draft->version=image.revision;
|
||||
draft->original=std::move(image.raster);
|
||||
draft->geometry=draft->saved={{0,0,width,height},0};
|
||||
}
|
||||
clampOffset();
|
||||
updateButtons();
|
||||
}
|
||||
}
|
||||
catch(const std::exception &failure)
|
||||
{
|
||||
@@ -191,9 +265,17 @@ struct ImageView
|
||||
}
|
||||
stop=std::stop_source{};
|
||||
started=revision;
|
||||
std::packaged_task<ImageRaster()> task([path=requested,decoder=retried?retry.load:load,token=stop.get_token()]
|
||||
std::packaged_task<Loaded()> task([path=requested,decoder=retried?retry.load:load,
|
||||
token=stop.get_token(),watch=!embedded && !load && isLocalDocumentPath(requested),editing=draft.has_value()]
|
||||
{
|
||||
return decoder?decoder(path,token):decodeImage(path,path,token);
|
||||
if(!watch) return Loaded{decoder?decoder(path,token):decodeImage(path,path,token),{}};
|
||||
std::optional<ImageRevision> before;
|
||||
try {before=imageRevision(path);}
|
||||
catch(const std::exception &) {if(editing) throw;}
|
||||
auto raster=decodeImage(path,path,token);
|
||||
if(before && *before!=imageRevision(path))
|
||||
throw std::runtime_error("The image changed while it was opening. Open it again.");
|
||||
return Loaded{std::move(raster),before};
|
||||
});
|
||||
reading=task.get_future();
|
||||
try {std::thread(std::move(task)).detach();}
|
||||
@@ -206,6 +288,18 @@ struct ImageView
|
||||
}
|
||||
}
|
||||
|
||||
void pollExternal()
|
||||
{
|
||||
if(!observedVersion || requested.empty() || reading.valid()) return;
|
||||
std::optional<ImageRevision> revision;
|
||||
try {revision=imageRevision(requested);}
|
||||
catch(const std::exception &) {return;}
|
||||
if(revision==observedVersion) return;
|
||||
if(draft && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !draft->dialogs.reloadChanged)) return;
|
||||
observedVersion=revision;
|
||||
if(!draft || draft->dialogs.reloadChanged(window)) request(requested,true);
|
||||
}
|
||||
|
||||
double factor() const
|
||||
{
|
||||
if(!fit || !width || !height) return zoom;
|
||||
@@ -242,9 +336,70 @@ struct ImageView
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void applyEdit(ImageGeometry next,bool undo)
|
||||
{
|
||||
if(next==draft->geometry) return;
|
||||
auto raster=transformImage(draft->original,next);
|
||||
if(!undo) draft->undo.push_back(draft->geometry);
|
||||
try {show(raster);}
|
||||
catch(...)
|
||||
{
|
||||
if(!undo) draft->undo.pop_back();
|
||||
throw;
|
||||
}
|
||||
if(undo) draft->undo.pop_back();
|
||||
draft->geometry=next;
|
||||
fit=true;
|
||||
zoom=1;
|
||||
x=y=0;
|
||||
updateButtons();
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void editAction(UINT id)
|
||||
{
|
||||
if(!draft || !bitmap) return;
|
||||
try
|
||||
{
|
||||
if(id==rotateLeft || id==rotateRight)
|
||||
{
|
||||
auto next=draft->geometry;
|
||||
next.turns=(next.turns+(id==rotateLeft?3:1))%4;
|
||||
applyEdit(next,false);
|
||||
}
|
||||
else if(id==crop)
|
||||
{
|
||||
if(const auto area=draft->dialogs.crop(window,width,height))
|
||||
applyEdit(cropImage(draft->geometry,*area),false);
|
||||
}
|
||||
else if(id==undoEdit && !draft->undo.empty())
|
||||
applyEdit(draft->undo.back(),true);
|
||||
else if(id==saveCopy)
|
||||
{
|
||||
const auto destination=draft->dialogs.copyPath(window,requested);
|
||||
if(destination.empty()) return;
|
||||
saveImage(transformImage(draft->original,draft->geometry),destination);
|
||||
}
|
||||
else if(id==replaceOriginal && draft->dirty() && draft->version &&
|
||||
draft->dialogs.confirm(window,L"Replace the original image?\r\n\r\n"+requested.native(),L"Replace original"))
|
||||
{
|
||||
draft->version=saveImage(transformImage(draft->original,draft->geometry),requested,&*draft->version);
|
||||
observedVersion=draft->version;
|
||||
draft->saved=draft->geometry;
|
||||
updateButtons();
|
||||
}
|
||||
}
|
||||
catch(const std::exception &failure)
|
||||
{
|
||||
updateButtons();
|
||||
draft->dialogs.report(window,wide(failure.what()).c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void action(UINT id)
|
||||
{
|
||||
if(id==previous && position>0) request(images[--position]);
|
||||
if(id>=rotateLeft && id<=replaceOriginal) editAction(id);
|
||||
else if(id==previous && position>0) request(images[--position]);
|
||||
else if(id==following && position+1<images.size()) request(images[++position]);
|
||||
else if(id==zoomOut || id==zoomIn) changeZoom(id==zoomIn?1.25:0.8);
|
||||
else if(id==fitImage || id==actualSize)
|
||||
@@ -354,12 +509,19 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
case WM_CREATE:
|
||||
{
|
||||
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%"};
|
||||
for(unsigned id=view.embedded?zoomOut:previous;id<=actualSize;++id)
|
||||
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%",
|
||||
L"Rotate left",L"Rotate right",L"Crop…",L"Undo",L"Save copy…",L"Replace…"};
|
||||
const unsigned first=view.embedded || view.draft?zoomOut:previous;
|
||||
const unsigned last=view.draft?replaceOriginal:actualSize;
|
||||
for(unsigned id=first;id<=last;++id)
|
||||
{
|
||||
view.buttons[id-1]=CreateWindowW(L"BUTTON",labels[id-1],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
|
||||
if(!view.buttons[id-1]) return -1;
|
||||
}
|
||||
view.layout();
|
||||
view.updateButtons();
|
||||
if(!view.embedded && !view.load) SetTimer(window,externalImageTimer,500,nullptr);
|
||||
return 0;
|
||||
}
|
||||
case WM_SIZE: view.layout(); return 0;
|
||||
@@ -376,7 +538,10 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
case WM_ERASEBKGND: return 1;
|
||||
case WM_PAINT: view.paint(); return 0;
|
||||
case WM_DRAWITEM: view.paintButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp)); return TRUE;
|
||||
case WM_TIMER: if(wp==imageTimer) view.poll(); return 0;
|
||||
case WM_TIMER:
|
||||
if(wp==imageTimer) view.poll();
|
||||
if(wp==externalImageTimer) view.pollExternal();
|
||||
return 0;
|
||||
case WM_COMMAND:
|
||||
if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);}
|
||||
return 0;
|
||||
@@ -416,15 +581,26 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
return 0;
|
||||
}
|
||||
case WM_KEYDOWN:
|
||||
if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
|
||||
if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='Z') view.action(undoEdit);
|
||||
else if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='S')
|
||||
view.action((GetKeyState(VK_SHIFT)&0x8000)?saveCopy:replaceOriginal);
|
||||
else if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
|
||||
else if(wp==VK_SUBTRACT || wp==VK_OEM_MINUS) view.action(zoomOut);
|
||||
else if(wp=='0') view.action(fitImage);
|
||||
else if(wp=='1') view.action(actualSize);
|
||||
else if(!view.embedded && (wp==VK_LEFT || wp==VK_PRIOR)) view.action(previous);
|
||||
else if(!view.embedded && (wp==VK_RIGHT || wp==VK_NEXT)) view.action(following);
|
||||
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) DestroyWindow(window);
|
||||
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) SendMessageW(window,WM_CLOSE,0,0);
|
||||
else break;
|
||||
return 0;
|
||||
case WM_CLOSE:
|
||||
if(view.confirmingClose || (view.draft && view.draft->dialogs.dismissOwned(window))) return 0;
|
||||
view.confirmingClose=true;
|
||||
if(!view.draft || !view.draft->dirty() ||
|
||||
view.draft->dialogs.confirm(window,L"Discard unsaved image edits?",L"Image editor"))
|
||||
DestroyWindow(window);
|
||||
view.confirmingClose=false;
|
||||
return 0;
|
||||
case WM_NCDESTROY:
|
||||
imageViews.erase(found);
|
||||
if(view.onClose) view.onClose(window);
|
||||
@@ -435,7 +611,8 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
|
||||
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
|
||||
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry)
|
||||
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry,
|
||||
const ImageEditDialogs *editor)
|
||||
{
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
static const bool registered=[instance]
|
||||
@@ -450,6 +627,7 @@ HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<s
|
||||
if(!registered) return nullptr;
|
||||
auto state=std::make_shared<ImageView>();
|
||||
state->embedded=embedded;
|
||||
if(editor) state->draft.emplace(ImageView::Draft{*editor});
|
||||
state->style=style;
|
||||
state->images=std::move(images);
|
||||
state->load=std::move(load);
|
||||
@@ -471,4 +649,24 @@ void showImageViewFile(HWND window,const std::filesystem::path &path)
|
||||
{
|
||||
if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path);
|
||||
}
|
||||
|
||||
std::optional<ImageWindowSession> imageWindowSession(HWND window)
|
||||
{
|
||||
const auto found=imageViews.find(window);
|
||||
if(found==imageViews.end()) return {};
|
||||
const auto &view=*found->second;
|
||||
if(view.embedded || view.load || !isLocalDocumentPath(view.requested)) return {};
|
||||
return ImageWindowSession{view.requested,view.draft.has_value(),view.fit,view.zoom,view.x,view.y};
|
||||
}
|
||||
|
||||
void restoreImageWindowSession(HWND window,const ImageWindowSession &state)
|
||||
{
|
||||
const auto found=imageViews.find(window);
|
||||
if(found==imageViews.end()) return;
|
||||
auto &view=*found->second;
|
||||
view.fit=state.fit;
|
||||
view.zoom=std::isfinite(state.zoom)?std::clamp(state.zoom,0.05,32.0):1.0;
|
||||
view.x=std::isfinite(state.x)?state.x:0;
|
||||
view.y=std::isfinite(state.y)?state.y:0;
|
||||
}
|
||||
}
|
||||
+25
-2
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "files_image_decode.h"
|
||||
#include "files_image_edit.h"
|
||||
#include <optional>
|
||||
#include <windows.h>
|
||||
#include <functional>
|
||||
#include <exception>
|
||||
@@ -22,7 +23,29 @@ struct ImageViewStyle
|
||||
COLORREF background{}, text{}, toolbar{}, toolbarText{}, selection{};
|
||||
};
|
||||
|
||||
struct ImageEditDialogs
|
||||
{
|
||||
std::function<std::optional<ImageRegion>(HWND,unsigned,unsigned)> crop;
|
||||
std::function<std::filesystem::path(HWND,const std::filesystem::path &)> copyPath;
|
||||
std::function<bool(HWND,const std::wstring &,const wchar_t *)> confirm;
|
||||
std::function<void(HWND,const wchar_t *)> report;
|
||||
std::function<bool(HWND)> dismissOwned;
|
||||
std::function<bool(HWND)> reloadChanged;
|
||||
};
|
||||
|
||||
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
|
||||
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={});
|
||||
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={},
|
||||
const ImageEditDialogs *editor=nullptr);
|
||||
void showImageViewFile(HWND window,const std::filesystem::path &path);
|
||||
|
||||
struct ImageWindowSession
|
||||
{
|
||||
std::filesystem::path path;
|
||||
bool editor{}, fit=true;
|
||||
double zoom=1, x{}, y{};
|
||||
RECT bounds{};
|
||||
bool maximized{};
|
||||
};
|
||||
std::optional<ImageWindowSession> imageWindowSession(HWND window);
|
||||
void restoreImageWindowSession(HWND window,const ImageWindowSession &state);
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
enum KeyContext : unsigned { panelKeyContext=1, terminalKeyContext=2 };
|
||||
enum class FilesKey
|
||||
{
|
||||
Refresh, View, Edit, Copy, Move, Mkdir, Delete, Exit, Compare, Previous, History,
|
||||
Pack, Find, ExternalView, ExternalEdit, QuickView, FullPath, HexView, Swap, Properties, Next, Count
|
||||
};
|
||||
constexpr size_t keyIndex(FilesKey command) { return static_cast<size_t>(command); }
|
||||
constexpr unsigned bothKeyContexts=panelKeyContext|terminalKeyContext;
|
||||
constexpr WORD chord(BYTE key,BYTE modifiers=0) { return MAKEWORD(key,modifiers); }
|
||||
constexpr BYTE keyCtrl=HOTKEYF_CONTROL,keyShift=HOTKEYF_SHIFT,keyAlt=HOTKEYF_ALT;
|
||||
constexpr struct
|
||||
{
|
||||
const char *id;
|
||||
const wchar_t *label;
|
||||
unsigned contexts;
|
||||
std::array<WORD,2> defaults;
|
||||
} filesKeyCommands[]{
|
||||
{"refresh",L"Refresh panel",bothKeyContexts,{chord('R',keyCtrl),chord(VK_F2)}},
|
||||
{"view",L"View",panelKeyContext,{chord(VK_F3)}},
|
||||
{"edit",L"Edit",panelKeyContext,{chord(VK_F4)}},
|
||||
{"copy",L"Copy",panelKeyContext,{chord(VK_F5)}},
|
||||
{"move",L"Move",panelKeyContext,{chord(VK_F6)}},
|
||||
{"mkdir",L"Make folder",panelKeyContext,{chord(VK_F7)}},
|
||||
{"delete",L"Delete to Recycle Bin",panelKeyContext,{chord(VK_F8)}},
|
||||
{"exit",L"Exit",bothKeyContexts,{chord(VK_F10)}},
|
||||
{"compare",L"Compare files",panelKeyContext,{chord(VK_F11,keyShift)}},
|
||||
{"previous",L"Previous command",bothKeyContexts,{chord('E',keyCtrl)}},
|
||||
{"history",L"Command history",bothKeyContexts,{chord(VK_F8,keyAlt)}},
|
||||
{"pack",L"Pack files",panelKeyContext,{chord(VK_F5,keyAlt)}},
|
||||
{"find",L"Find files",panelKeyContext,{chord(VK_F7,keyAlt)}},
|
||||
{"externalView",L"View externally",panelKeyContext,{chord(VK_F3,keyAlt)}},
|
||||
{"externalEdit",L"Edit externally",panelKeyContext,{chord(VK_F4,keyAlt)}},
|
||||
{"quickView",L"Quick View",panelKeyContext,{chord('Q',keyCtrl)}},
|
||||
{"fullPath",L"Copy full path",panelKeyContext,{chord('C',keyCtrl|keyShift)}},
|
||||
{"hexView",L"View as hex",panelKeyContext,{chord(VK_F3,keyShift)}},
|
||||
{"swap",L"Swap panels",panelKeyContext,{chord('U',keyCtrl)}},
|
||||
{"properties",L"Properties",panelKeyContext,{chord('A',keyCtrl)}},
|
||||
{"next",L"Next command",terminalKeyContext,{chord(VK_DOWN)}},
|
||||
};
|
||||
static_assert(std::size(filesKeyCommands)==keyIndex(FilesKey::Count));
|
||||
constexpr size_t filesKeySchemeLimit=24,filesKeysPerCommand=8;
|
||||
constexpr wchar_t filesKeySchemePreference[]=L"KeySchemesV1";
|
||||
|
||||
struct FilesKeyScheme
|
||||
{
|
||||
std::wstring name;
|
||||
std::array<std::vector<WORD>,keyIndex(FilesKey::Count)> keys;
|
||||
bool operator==(const FilesKeyScheme &) const=default;
|
||||
};
|
||||
|
||||
struct FilesKeySettings
|
||||
{
|
||||
std::vector<FilesKeyScheme> schemes;
|
||||
size_t active{};
|
||||
bool operator==(const FilesKeySettings &) const=default;
|
||||
};
|
||||
|
||||
std::wstring filesKeyLabel(WORD binding)
|
||||
{
|
||||
if(!binding) return {};
|
||||
std::wstring label;
|
||||
if(HIBYTE(binding)&keyCtrl) label+=L"Ctrl+";
|
||||
if(HIBYTE(binding)&keyAlt) label+=L"Alt+";
|
||||
if(HIBYTE(binding)&keyShift) label+=L"Shift+";
|
||||
const auto key=LOBYTE(binding);
|
||||
if(key>=VK_F1 && key<=VK_F24) label+=L"F"+std::to_wstring(key-VK_F1+1);
|
||||
else if(key==VK_DOWN) label+=L"Down";
|
||||
else label+=static_cast<wchar_t>(key);
|
||||
return label;
|
||||
}
|
||||
|
||||
FilesKeyScheme defaultFilesKeyScheme(std::wstring name=L"Default")
|
||||
{
|
||||
FilesKeyScheme scheme{std::move(name),{}};
|
||||
for(size_t command=0;command<scheme.keys.size();++command)
|
||||
for(const auto binding:filesKeyCommands[command].defaults)
|
||||
if(binding) scheme.keys[command].push_back(binding);
|
||||
return scheme;
|
||||
}
|
||||
|
||||
FilesKeySettings filesKeySettings{{defaultFilesKeyScheme()},0};
|
||||
|
||||
bool sameFilesKeySchemeName(std::wstring_view first,std::wstring_view second)
|
||||
{
|
||||
return CompareStringOrdinal(first.data(),static_cast<int>(first.size()),
|
||||
second.data(),static_cast<int>(second.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
bool validFilesKeySchemeName(std::wstring_view name)
|
||||
{
|
||||
return !name.empty() && name.size()<=48 && !iswspace(name.front()) && !iswspace(name.back()) &&
|
||||
std::ranges::none_of(name,[](wchar_t character){return iswcntrl(character);});
|
||||
}
|
||||
|
||||
unsigned reservedFilesKeyContexts(WORD binding)
|
||||
{
|
||||
const auto key=LOBYTE(binding),mods=HIBYTE(binding);
|
||||
if(key>=VK_F1 && key<=VK_F24)
|
||||
{
|
||||
if(mods==keyAlt && key==VK_F4) return terminalKeyContext;
|
||||
if(!mods && key==VK_F1) return bothKeyContexts;
|
||||
if((!mods && key==VK_F9) || (mods==keyAlt && (key==VK_F1 || key==VK_F2 || key==VK_F10)) ||
|
||||
(mods==keyShift && key==VK_F4) || (mods==keyShift && key==VK_F10) ||
|
||||
(mods==keyCtrl && key<=VK_F12))
|
||||
return panelKeyContext;
|
||||
return 0;
|
||||
}
|
||||
if(key==VK_DOWN && !mods) return panelKeyContext;
|
||||
if(key>='A' && key<='Z' && (mods&keyCtrl) && !(mods&keyAlt))
|
||||
{
|
||||
constexpr std::wstring_view editing=L"CFOPVXYZ";
|
||||
if(mods==keyCtrl && editing.find(key)!=editing.npos) return bothKeyContexts;
|
||||
if((mods==keyCtrl && key=='A') || (mods==(keyCtrl|keyShift) && (key=='C' || key=='V')))
|
||||
return terminalKeyContext;
|
||||
return 0;
|
||||
}
|
||||
return bothKeyContexts;
|
||||
}
|
||||
|
||||
std::wstring filesKeyConflict(const FilesKeyScheme &scheme,size_t command,WORD binding)
|
||||
{
|
||||
if(!binding || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt)))
|
||||
return L"Use a function key or a letter with Ctrl.";
|
||||
const auto contexts=filesKeyCommands[command].contexts;
|
||||
if(reservedFilesKeyContexts(binding)&contexts)
|
||||
return filesKeyLabel(binding)+L" is reserved or unavailable in this context.";
|
||||
for(size_t i=0;i<scheme.keys.size();++i)
|
||||
if((filesKeyCommands[i].contexts&contexts) && std::ranges::find(scheme.keys[i],binding)!=scheme.keys[i].end())
|
||||
return filesKeyLabel(binding)+L" is already assigned to "+filesKeyCommands[i].label+L".";
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<FilesKeySettings> parseFilesKeySettings(const Json &stored)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(stored.at("version")!=1 || !stored.at("schemes").is_array()) return {};
|
||||
const auto &rows=stored.at("schemes");
|
||||
if(rows.empty() || rows.size()>filesKeySchemeLimit) return {};
|
||||
FilesKeySettings settings;
|
||||
const auto active=stored.at("active").get<std::string>();
|
||||
for(const auto &row:rows)
|
||||
{
|
||||
auto name=ks::wide(row.at("name").get<std::string>());
|
||||
if(!validFilesKeySchemeName(name) ||
|
||||
std::ranges::any_of(settings.schemes,[&](const auto &other)
|
||||
{ return sameFilesKeySchemeName(other.name,name); })) return {};
|
||||
FilesKeyScheme scheme{std::move(name),{}};
|
||||
const auto &commands=row.at("commands");
|
||||
if(!commands.is_object()) return {};
|
||||
for(size_t i=0;i<scheme.keys.size();++i)
|
||||
{
|
||||
const auto found=commands.find(filesKeyCommands[i].id);
|
||||
if(found==commands.end()) continue;
|
||||
if(!found->is_array() || found->size()>filesKeysPerCommand) return {};
|
||||
for(const auto &entry:*found)
|
||||
{
|
||||
if(!entry.is_number_unsigned() || entry>0xffff) return {};
|
||||
const auto binding=entry.get<WORD>();
|
||||
if(binding==chord(VK_F1)) continue;
|
||||
if(!filesKeyConflict(scheme,i,binding).empty()) return {};
|
||||
scheme.keys[i].push_back(binding);
|
||||
}
|
||||
}
|
||||
for(size_t i=0;i<scheme.keys.size();++i)
|
||||
if(!commands.contains(filesKeyCommands[i].id))
|
||||
for(const auto binding:filesKeyCommands[i].defaults)
|
||||
if(binding && filesKeyConflict(scheme,i,binding).empty()) scheme.keys[i].push_back(binding);
|
||||
if(active==ks::utf8(scheme.name)) settings.active=settings.schemes.size();
|
||||
settings.schemes.push_back(std::move(scheme));
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
catch(const std::exception &) { return {}; }
|
||||
}
|
||||
|
||||
Json serializeFilesKeySettings(const FilesKeySettings &settings)
|
||||
{
|
||||
Json schemes=Json::array();
|
||||
for(const auto &scheme:settings.schemes)
|
||||
{
|
||||
Json commands=Json::object();
|
||||
for(size_t i=0;i<scheme.keys.size();++i) commands[filesKeyCommands[i].id]=scheme.keys[i];
|
||||
schemes.push_back({{"name",ks::utf8(scheme.name)},{"commands",std::move(commands)}});
|
||||
}
|
||||
return {{"version",1},{"active",ks::utf8(settings.schemes[settings.active].name)},{"schemes",std::move(schemes)}};
|
||||
}
|
||||
|
||||
void loadFilesKeySettings()
|
||||
{
|
||||
if(const auto json=readFilesJsonPreference(filesKeySchemePreference))
|
||||
if(auto settings=parseFilesKeySettings(*json))
|
||||
{
|
||||
filesKeySettings=std::move(*settings);
|
||||
return;
|
||||
}
|
||||
auto migrated=defaultFilesKeyScheme(L"Previous settings");
|
||||
constexpr struct { FilesKey command; const wchar_t *name; } legacy[]{
|
||||
{FilesKey::Previous,L"PreviousCommandKey"},{FilesKey::History,L"CommandHistoryKey"},
|
||||
{FilesKey::Compare,L"ComparisonShortcut"},
|
||||
};
|
||||
for(const auto &item:legacy)
|
||||
{
|
||||
const auto index=keyIndex(item.command);
|
||||
auto &keys=migrated.keys[index];
|
||||
const auto fallback=filesKeyCommands[index].defaults.front();
|
||||
const auto binding=static_cast<WORD>(preference(item.name,fallback));
|
||||
const auto context=filesKeyCommands[index].contexts;
|
||||
if(binding==fallback || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt)) ||
|
||||
(reservedFilesKeyContexts(binding)&context)) continue;
|
||||
for(size_t i=0;i<migrated.keys.size();++i)
|
||||
if(filesKeyCommands[i].contexts&context) std::erase(migrated.keys[i],binding);
|
||||
keys={binding};
|
||||
}
|
||||
filesKeySettings={{defaultFilesKeyScheme()},0};
|
||||
if(migrated.keys!=filesKeySettings.schemes.front().keys)
|
||||
{
|
||||
filesKeySettings.schemes.push_back(std::move(migrated));
|
||||
filesKeySettings.active=1;
|
||||
}
|
||||
}
|
||||
|
||||
WORD currentFilesChord(WPARAM key)
|
||||
{
|
||||
if(key>0xff || ((GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return 0;
|
||||
return chord(static_cast<BYTE>(key),((GetKeyState(VK_CONTROL)&0x8000)?keyCtrl:0) |
|
||||
((GetKeyState(VK_SHIFT)&0x8000)?keyShift:0) | ((GetKeyState(VK_MENU)&0x8000)?keyAlt:0));
|
||||
}
|
||||
|
||||
std::optional<FilesKey> boundFilesCommand(WORD binding,unsigned context)
|
||||
{
|
||||
const auto &keys=filesKeySettings.schemes[filesKeySettings.active].keys;
|
||||
for(size_t i=0;i<keys.size();++i)
|
||||
if((filesKeyCommands[i].contexts&context) && std::ranges::find(keys[i],binding)!=keys[i].end())
|
||||
return static_cast<FilesKey>(i);
|
||||
return {};
|
||||
}
|
||||
|
||||
std::wstring filesKeyHint(FilesKey command,bool all=false)
|
||||
{
|
||||
std::wstring text;
|
||||
for(const auto binding:filesKeySettings.schemes[filesKeySettings.active].keys[keyIndex(command)])
|
||||
{
|
||||
if(!text.empty()) text+=L", ";
|
||||
text+=filesKeyLabel(binding);
|
||||
if(!all) break;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
std::wstring filesKeyMenuLabel(FilesKey command,std::wstring label={})
|
||||
{
|
||||
if(label.empty()) label=filesKeyCommands[keyIndex(command)].label;
|
||||
const auto keys=filesKeyHint(command,true);
|
||||
if(!keys.empty()) label+=L"\t"+keys;
|
||||
return label;
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
constexpr int keySchemeChoice=610,keySchemeCopy=611,keySchemeReset=612,keySchemeCommand=613,
|
||||
keySchemeContext=614,keySchemeBindings=615,keySchemeCapture=616,keySchemeAdd=617,keySchemeRemove=618,
|
||||
keySchemePrimary=619,keySchemeName=620;
|
||||
|
||||
struct FilesKeySchemeDraft
|
||||
{
|
||||
FilesKeySettings base=filesKeySettings,settings=base;
|
||||
FilesKey initial;
|
||||
FilesKeySettings *pending{};
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK copyKeySchemeDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
auto &name=*reinterpret_cast<std::wstring*>(lp);
|
||||
SendDlgItemMessageW(dialog,keySchemeName,EM_SETLIMITTEXT,48,0);
|
||||
SetDlgItemTextW(dialog,keySchemeName,name.c_str());
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
|
||||
auto &name=*reinterpret_cast<std::wstring*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
wchar_t entry[49]{};
|
||||
GetDlgItemTextW(dialog,keySchemeName,entry,std::size(entry));
|
||||
name=entry;
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void refreshFilesKeyBindings(HWND dialog,const FilesKeyScheme &scheme,size_t command,size_t selection=0)
|
||||
{
|
||||
const auto &descriptor=filesKeyCommands[command];
|
||||
SetDlgItemTextW(dialog,keySchemeContext,
|
||||
descriptor.contexts==bothKeyContexts?L"Keys · panels and command output":
|
||||
descriptor.contexts==terminalKeyContext?L"Keys · command output":L"Keys · file panels");
|
||||
const auto list=GetDlgItem(dialog,keySchemeBindings);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
const auto &keys=scheme.keys[command];
|
||||
for(size_t i=0;i<keys.size();++i)
|
||||
{
|
||||
auto label=filesKeyLabel(keys[i]);
|
||||
if(!i) label+=L" (primary)";
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
}
|
||||
if(!keys.empty()) SendMessageW(list,LB_SETCURSEL,std::min(selection,keys.size()-1),0);
|
||||
EnableWindow(GetDlgItem(dialog,keySchemeRemove),!keys.empty());
|
||||
EnableWindow(GetDlgItem(dialog,keySchemePrimary),keys.size()>1 && selection>0 && selection<keys.size());
|
||||
EnableWindow(GetDlgItem(dialog,keySchemeAdd),keys.size()<filesKeysPerCommand);
|
||||
}
|
||||
|
||||
void refreshFilesKeySchemes(HWND dialog,const FilesKeySettings &settings)
|
||||
{
|
||||
const auto choice=GetDlgItem(dialog,keySchemeChoice);
|
||||
SendMessageW(choice,CB_RESETCONTENT,0,0);
|
||||
for(const auto &scheme:settings.schemes)
|
||||
SendMessageW(choice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(scheme.name.c_str()));
|
||||
SendMessageW(choice,CB_SETCURSEL,settings.active,0);
|
||||
EnableWindow(GetDlgItem(dialog,keySchemeCopy),settings.schemes.size()<filesKeySchemeLimit);
|
||||
}
|
||||
|
||||
std::wstring filesKeyBarLabel(FilesKey command,const wchar_t *action)
|
||||
{
|
||||
return filesKeyHint(command)+L" "+action;
|
||||
}
|
||||
|
||||
void refreshFilesKeyBar()
|
||||
{
|
||||
for(size_t i=0;i<std::size(keyBar);++i)
|
||||
{
|
||||
SetWindowTextW(commands[i],filesKeyBarLabel(keyBar[i].command,keyBar[i].label).c_str());
|
||||
InvalidateRect(commands[i],nullptr,FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK filesKeySchemesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &draft=*reinterpret_cast<FilesKeySchemeDraft*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
refreshFilesKeySchemes(dialog,draft.settings);
|
||||
for(const auto &item:filesKeyCommands)
|
||||
SendDlgItemMessageW(dialog,keySchemeCommand,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(item.label));
|
||||
const auto index=keyIndex(draft.initial);
|
||||
SendDlgItemMessageW(dialog,keySchemeCommand,LB_SETCURSEL,index,0);
|
||||
refreshFilesKeyBindings(dialog,draft.settings.schemes[draft.settings.active],index);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
auto &draft=*reinterpret_cast<FilesKeySchemeDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
auto &settings=draft.settings;
|
||||
auto &scheme=settings.schemes[settings.active];
|
||||
const auto row=SendDlgItemMessageW(dialog,keySchemeCommand,LB_GETCURSEL,0,0);
|
||||
if(row==LB_ERR) return FALSE;
|
||||
const auto command=static_cast<size_t>(row);
|
||||
const auto position=static_cast<size_t>(SendDlgItemMessageW(dialog,keySchemeBindings,LB_GETCURSEL,0,0));
|
||||
auto &keys=scheme.keys[command];
|
||||
switch(LOWORD(wp))
|
||||
{
|
||||
case keySchemeChoice:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE)
|
||||
{
|
||||
const auto chosen=SendDlgItemMessageW(dialog,keySchemeChoice,CB_GETCURSEL,0,0);
|
||||
if(chosen!=CB_ERR) settings.active=static_cast<size_t>(chosen);
|
||||
refreshFilesKeyBindings(dialog,settings.schemes[settings.active],command);
|
||||
}
|
||||
return TRUE;
|
||||
case keySchemeCommand:
|
||||
if(HIWORD(wp)==LBN_SELCHANGE) refreshFilesKeyBindings(dialog,scheme,command);
|
||||
return TRUE;
|
||||
case keySchemeBindings:
|
||||
if(HIWORD(wp)==LBN_SELCHANGE)
|
||||
EnableWindow(GetDlgItem(dialog,keySchemePrimary),position>0 && position<keys.size());
|
||||
return TRUE;
|
||||
case keySchemeCopy:
|
||||
{
|
||||
if(settings.schemes.size()>=filesKeySchemeLimit) return TRUE;
|
||||
std::wstring name=scheme.name.substr(0,43)+L" copy";
|
||||
FilesModalDialog copyName(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(616),dialog,
|
||||
copyKeySchemeDialog,reinterpret_cast<LPARAM>(&name),false);
|
||||
if(copyName.runModal()!=IDOK) return TRUE;
|
||||
if(!validFilesKeySchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &other)
|
||||
{ return sameFilesKeySchemeName(other.name,name); }))
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a unique name with no leading or trailing spaces.",L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
auto copy=scheme;
|
||||
copy.name=std::move(name);
|
||||
settings.schemes.push_back(std::move(copy));
|
||||
settings.active=settings.schemes.size()-1;
|
||||
refreshFilesKeySchemes(dialog,settings);
|
||||
refreshFilesKeyBindings(dialog,settings.schemes.back(),command);
|
||||
return TRUE;
|
||||
}
|
||||
case keySchemeReset:
|
||||
{
|
||||
FilesNoticeOptions notice;
|
||||
notice.confirm=true;
|
||||
notice.accept=L"&Reset";
|
||||
const auto prompt=L"Reset all keys in “"+scheme.name+L"” to defaults?";
|
||||
if(showFilesNotice(dialog,prompt.c_str(),L"Keyboard shortcuts",notice)!=IDYES) return TRUE;
|
||||
scheme=defaultFilesKeyScheme(scheme.name);
|
||||
refreshFilesKeyBindings(dialog,scheme,command);
|
||||
return TRUE;
|
||||
}
|
||||
case keySchemeAdd:
|
||||
{
|
||||
if(keys.size()>=filesKeysPerCommand) return TRUE;
|
||||
const auto binding=static_cast<WORD>(SendDlgItemMessageW(dialog,keySchemeCapture,HKM_GETHOTKEY,0,0));
|
||||
if(const auto conflict=filesKeyConflict(scheme,command,binding);!conflict.empty())
|
||||
{
|
||||
showFilesNotice(dialog,conflict.c_str(),L"Keyboard shortcuts");
|
||||
SetFocus(GetDlgItem(dialog,keySchemeCapture));
|
||||
return TRUE;
|
||||
}
|
||||
keys.push_back(binding);
|
||||
SendDlgItemMessageW(dialog,keySchemeCapture,HKM_SETHOTKEY,0,0);
|
||||
refreshFilesKeyBindings(dialog,scheme,command,keys.size()-1);
|
||||
return TRUE;
|
||||
}
|
||||
case keySchemeRemove:
|
||||
if(position<keys.size())
|
||||
{
|
||||
keys.erase(keys.begin()+position);
|
||||
refreshFilesKeyBindings(dialog,scheme,command,position<keys.size()?position:0);
|
||||
}
|
||||
return TRUE;
|
||||
case keySchemePrimary:
|
||||
if(position>0 && position<keys.size())
|
||||
{
|
||||
std::rotate(keys.begin(),keys.begin()+position,keys.begin()+position+1);
|
||||
refreshFilesKeyBindings(dialog,scheme,command);
|
||||
}
|
||||
return TRUE;
|
||||
case IDOK:
|
||||
if(draft.pending) *draft.pending=settings;
|
||||
else if(settings!=draft.base)
|
||||
{
|
||||
const OptionsWriteLock writeLock;
|
||||
if(!writeLock.acquired())
|
||||
{
|
||||
showFilesNotice(dialog,L"Another window is saving Files settings. Try again.",L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
loadFilesKeySettings();
|
||||
if(filesKeySettings!=draft.base && filesKeySettings!=settings)
|
||||
{
|
||||
showFilesNotice(dialog,L"Keyboard schemes were changed in another window. Reopen this dialog.",
|
||||
L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
if(!writeFilesJsonPreference(filesKeySchemePreference,serializeFilesKeySettings(settings)))
|
||||
{
|
||||
showFilesNotice(dialog,L"Could not save the keyboard schemes.",L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
filesKeySettings=settings;
|
||||
refreshFilesKeyBar();
|
||||
showFileDetails(panels[active]);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
}
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending)
|
||||
{
|
||||
if(!pending) loadFilesKeySettings();
|
||||
const auto &base=pending?*pending:filesKeySettings;
|
||||
FilesKeySchemeDraft draft{base,base,initial,pending};
|
||||
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(615),owner,
|
||||
filesKeySchemesDialog,reinterpret_cast<LPARAM>(&draft),false);
|
||||
dialog.runModal();
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
constexpr int filesLogSource=680,filesLogStatus=681,filesLogEntries=682,filesLogCopy=683,filesLogRefresh=684;
|
||||
constexpr size_t filesLogEntryLimit=200,filesLogReadLimit=256*1024;
|
||||
|
||||
std::optional<unsigned> filesLogError(std::string_view message,std::string_view marker)
|
||||
{
|
||||
const auto last=message.rfind(marker);
|
||||
if(last==message.npos) return {};
|
||||
const auto value=message.substr(last+marker.size());
|
||||
unsigned error{};
|
||||
const auto parsed=std::from_chars(value.data(),value.data()+value.size(),error);
|
||||
if(parsed.ec!=std::errc{} || parsed.ptr!=value.data()+value.size()) return {};
|
||||
return error;
|
||||
}
|
||||
|
||||
std::wstring safeFilesLogEntry(std::string_view line)
|
||||
{
|
||||
if(line.ends_with('\r')) line.remove_suffix(1);
|
||||
std::wstring stamp;
|
||||
constexpr std::string_view format="0000-00-00 00:00:00 ";
|
||||
if(line.size()>=format.size())
|
||||
{
|
||||
bool valid=true;
|
||||
for(size_t i=0;i<format.size();++i)
|
||||
valid&=format[i]=='0'?(line[i]>='0' && line[i]<='9'):line[i]==format[i];
|
||||
if(valid)
|
||||
{
|
||||
stamp=ks::wide(std::string(line.substr(0,format.size()-1)))+L" · ";
|
||||
line.remove_prefix(format.size());
|
||||
}
|
||||
}
|
||||
|
||||
// Only fixed descriptions and numeric Windows result codes cross into the UI or clipboard.
|
||||
std::wstring text;
|
||||
std::optional<unsigned> error;
|
||||
if(line=="LAN Files peer lookup failed: local KSwitcher window not found")
|
||||
text=L"LAN peer lookup failed. KSwitcher is unavailable.";
|
||||
else if(line.starts_with("LAN Files peer lookup failed: delivered="))
|
||||
{
|
||||
text=L"LAN peer lookup failed";
|
||||
error=filesLogError(line,", Windows error=");
|
||||
}
|
||||
else if(line=="LAN Files drive query failed: unexpected error")
|
||||
text=L"LAN drive query failed. Unexpected error.";
|
||||
else if(line.starts_with("LAN Files drive query for "))
|
||||
{
|
||||
text=L"LAN drive query failed";
|
||||
error=filesLogError(line,") failed: Windows error ");
|
||||
if(error==WSAETIMEDOUT) text=L"LAN drive query timed out";
|
||||
}
|
||||
else text=L"Diagnostic entry · details hidden";
|
||||
if(error && *error) text+=L" (Windows error "+std::to_wstring(*error)+L")";
|
||||
return stamp+text;
|
||||
}
|
||||
|
||||
std::vector<std::wstring> recentFilesLogEntries(const ks::Bytes &bytes)
|
||||
{
|
||||
std::vector<std::wstring> entries;
|
||||
if(bytes.empty()) return entries;
|
||||
const std::string_view text(reinterpret_cast<const char*>(bytes.data()),bytes.size());
|
||||
auto end=text.size();
|
||||
while(end && entries.size()<filesLogEntryLimit)
|
||||
{
|
||||
if(text[end-1]=='\n') --end;
|
||||
const auto split=end?text.rfind('\n',end-1):text.npos;
|
||||
const auto begin=split==text.npos?0:split+1;
|
||||
const auto row=text.substr(begin,end-begin);
|
||||
if(!row.empty() && row!="\r") entries.push_back(safeFilesLogEntry(row));
|
||||
end=begin;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
struct FilesLogDraft
|
||||
{
|
||||
std::vector<std::wstring> entries;
|
||||
};
|
||||
|
||||
void refreshFilesLog(HWND dialog,FilesLogDraft &draft)
|
||||
{
|
||||
const bool previous=SendDlgItemMessageW(dialog,filesLogSource,CB_GETCURSEL,0,0)==1;
|
||||
const auto list=GetDlgItem(dialog,filesLogEntries);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
SendMessageW(list,LB_SETHORIZONTALEXTENT,0,0);
|
||||
draft.entries.clear();
|
||||
try
|
||||
{
|
||||
if(const auto data=ks::readActiveLogTail(previous,filesLogReadLimit))
|
||||
{
|
||||
draft.entries=recentFilesLogEntries(*data);
|
||||
SetDlgItemTextW(dialog,filesLogStatus,draft.entries.empty()?L"The Files log has no entries.":
|
||||
L"Most recent first. Select an entry to copy its timestamp and description.");
|
||||
}
|
||||
else SetDlgItemTextW(dialog,filesLogStatus,previous?L"No previous Files log is available yet.":
|
||||
L"No Files log yet. Entries appear when Write log is enabled and Files records a problem.");
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetDlgItemTextW(dialog,filesLogStatus,L"Could not read the Files log. Use Refresh to try again.");
|
||||
}
|
||||
int width=0;
|
||||
const auto dc=GetDC(list);
|
||||
const auto font=reinterpret_cast<HFONT>(SendMessageW(list,WM_GETFONT,0,0));
|
||||
const auto oldFont=dc && font?SelectObject(dc,font):nullptr;
|
||||
for(const auto &entry:draft.entries)
|
||||
{
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(entry.c_str()));
|
||||
if(dc)
|
||||
{
|
||||
SIZE extent{};
|
||||
GetTextExtentPoint32W(dc,entry.c_str(),static_cast<int>(entry.size()),&extent);
|
||||
width=std::max(width,static_cast<int>(extent.cx)+12);
|
||||
}
|
||||
}
|
||||
if(oldFont) SelectObject(dc,oldFont);
|
||||
if(dc) ReleaseDC(list,dc);
|
||||
if(width) SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0);
|
||||
if(!draft.entries.empty()) SendMessageW(list,LB_SETCURSEL,0,0);
|
||||
EnableWindow(GetDlgItem(dialog,filesLogCopy),!draft.entries.empty());
|
||||
}
|
||||
|
||||
LRESULT CALLBACK filesLogListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_KEYDOWN && wp=='C' && (GetKeyState(VK_CONTROL)&0x8000) &&
|
||||
!((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
|
||||
{
|
||||
if(!(lp&(1LL<<30))) SendMessageW(GetParent(list),WM_COMMAND,MAKEWPARAM(filesLogCopy,BN_CLICKED),0);
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(list,message,wp,lp);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK filesLogDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &draft=*reinterpret_cast<FilesLogDraft*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
for(const auto name:{L"Current",L"Previous"})
|
||||
SendDlgItemMessageW(dialog,filesLogSource,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
|
||||
SendDlgItemMessageW(dialog,filesLogSource,CB_SETCURSEL,0,0);
|
||||
SetWindowSubclass(GetDlgItem(dialog,filesLogEntries),filesLogListKeys,1,0);
|
||||
refreshFilesLog(dialog,draft);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
auto &draft=*reinterpret_cast<FilesLogDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(LOWORD(wp)==filesLogRefresh || (LOWORD(wp)==filesLogSource && HIWORD(wp)==CBN_SELCHANGE))
|
||||
{
|
||||
refreshFilesLog(dialog,draft);
|
||||
return TRUE;
|
||||
}
|
||||
if(LOWORD(wp)==filesLogCopy)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,filesLogEntries,LB_GETCURSEL,0,0);
|
||||
if(row>=0 && static_cast<size_t>(row)<draft.entries.size())
|
||||
{
|
||||
if(copyFilesText(dialog,draft.entries[row],L"Could not copy the Files log entry."))
|
||||
SetDlgItemTextW(dialog,filesLogStatus,L"Entry copied.");
|
||||
else SetDlgItemTextW(dialog,filesLogStatus,L"Could not copy the Files log entry.");
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void showFilesLog(HWND owner)
|
||||
{
|
||||
FilesLogDraft draft;
|
||||
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(619),owner,filesLogDialog,
|
||||
reinterpret_cast<LPARAM>(&draft),false,false);
|
||||
dialog.runModal();
|
||||
}
|
||||
+883
-359
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,384 @@
|
||||
#include "lan_network.h"
|
||||
#include "files_mcp.h"
|
||||
#include "lan_pairing.h"
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Json=FilesMcpServer::Json;
|
||||
using Clock=std::chrono::steady_clock;
|
||||
using namespace std::chrono_literals;
|
||||
constexpr size_t maxHeaders=8192,maxRequest=16*1024,maxResponse=512*1024;
|
||||
constexpr std::string_view latestProtocol="2025-11-25";
|
||||
|
||||
bool supportedProtocol(std::string_view version)
|
||||
{
|
||||
return version==latestProtocol || version=="2025-06-18" || version=="2025-03-26";
|
||||
}
|
||||
|
||||
bool readySocket(SOCKET socket,bool write,std::stop_token stop,Clock::time_point deadline)
|
||||
{
|
||||
while(!stop.stop_requested() && Clock::now()<deadline)
|
||||
{
|
||||
fd_set ready;
|
||||
FD_ZERO(&ready);
|
||||
FD_SET(socket,&ready);
|
||||
timeval wait{0,50000};
|
||||
const auto result=select(0,write?nullptr:&ready,write?&ready:nullptr,nullptr,&wait);
|
||||
if(result) return result>0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool appendSocket(SOCKET socket,std::string &data,std::stop_token stop,Clock::time_point deadline)
|
||||
{
|
||||
char buffer[4096];
|
||||
if(!readySocket(socket,false,stop,deadline)) return false;
|
||||
const auto count=recv(socket,buffer,sizeof(buffer),0);
|
||||
if(count<=0) return false;
|
||||
data.append(buffer,count);
|
||||
return true;
|
||||
}
|
||||
|
||||
void sendSocket(SOCKET socket,std::string_view bytes,std::stop_token stop)
|
||||
{
|
||||
const auto deadline=Clock::now()+2s;
|
||||
while(!bytes.empty() && readySocket(socket,true,stop,deadline))
|
||||
{
|
||||
const auto count=send(socket,bytes.data(),static_cast<int>(bytes.size()),0);
|
||||
if(count<=0) return;
|
||||
bytes.remove_prefix(count);
|
||||
}
|
||||
}
|
||||
|
||||
std::string lowerAscii(std::string_view text)
|
||||
{
|
||||
std::string result(text);
|
||||
for(auto &ch:result)
|
||||
if(ch>='A' && ch<='Z') ch=static_cast<char>(ch-'A'+'a');
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string_view trimHeader(std::string_view text)
|
||||
{
|
||||
const auto first=text.find_first_not_of(" \t");
|
||||
return first==text.npos?std::string_view{}:text.substr(first,text.find_last_not_of(" \t")-first+1);
|
||||
}
|
||||
|
||||
struct HttpRequest
|
||||
{
|
||||
std::string_view method,path;
|
||||
std::map<std::string,std::string_view,std::less<>> headers;
|
||||
|
||||
std::string_view header(std::string_view field) const
|
||||
{
|
||||
const auto found=headers.find(field);
|
||||
return found==headers.end()?std::string_view{}:found->second;
|
||||
}
|
||||
};
|
||||
|
||||
std::optional<HttpRequest> parseHeaders(std::string_view data)
|
||||
{
|
||||
HttpRequest request;
|
||||
auto end=data.find("\r\n");
|
||||
const auto line=data.substr(0,end);
|
||||
const auto first=line.find(' '),second=first==line.npos?line.npos:line.find(' ',first+1);
|
||||
if(end==data.npos || !first || second==line.npos || line.substr(second+1)!="HTTP/1.1") return {};
|
||||
request.method=line.substr(0,first);
|
||||
request.path=line.substr(first+1,second-first-1);
|
||||
data.remove_prefix(end+2);
|
||||
while(!data.empty())
|
||||
{
|
||||
end=data.find("\r\n");
|
||||
const auto header=data.substr(0,end);
|
||||
const auto colon=header.find(':');
|
||||
if(!colon || colon==header.npos) return {};
|
||||
const auto name=lowerAscii(header.substr(0,colon));
|
||||
const auto value=trimHeader(header.substr(colon+1));
|
||||
if(!std::ranges::all_of(name,[](char ch)
|
||||
{return (ch>='a' && ch<='z') || (ch>='0' && ch<='9') || ch=='-' || ch=='_';}) ||
|
||||
!std::ranges::all_of(value,[](unsigned char ch){return ch=='\t' || (ch>=32 && ch<127);}) ||
|
||||
!request.headers.emplace(name,value).second)
|
||||
return {};
|
||||
if(end==data.npos) break;
|
||||
data.remove_prefix(end+2);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
bool hasSessionToken(std::string_view authorization,std::string_view token)
|
||||
{
|
||||
if(authorization.size()!=token.size()+7 || lowerAscii(authorization.substr(0,7))!="bearer ") return false;
|
||||
unsigned difference=0;
|
||||
for(size_t i=0;i<token.size();++i)
|
||||
difference|=static_cast<unsigned char>(authorization[i+7]^token[i]);
|
||||
return difference==0;
|
||||
}
|
||||
|
||||
struct HttpReply
|
||||
{
|
||||
const char *status;
|
||||
std::string body;
|
||||
const char *headers="";
|
||||
};
|
||||
|
||||
HttpReply jsonReply(const char *status,Json body)
|
||||
{
|
||||
return {status,body.dump(-1,' ',false,Json::error_handler_t::replace)};
|
||||
}
|
||||
|
||||
HttpReply rpcError(const char *status,const Json &id,int code,const char *message)
|
||||
{
|
||||
return jsonReply(status,{{"jsonrpc","2.0"},{"id",id},{"error",{{"code",code},{"message",message}}}});
|
||||
}
|
||||
|
||||
const Json &mcpTools()
|
||||
{
|
||||
static const auto tools=Json::parse(R"({"tools":[
|
||||
{"name":"get_panels","description":"Read the two Files panes and their current local listings, selections and Find state.",
|
||||
"inputSchema":{"type":"object","properties":{"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"additionalProperties":false},
|
||||
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
|
||||
{"name":"search_files","description":"Search the current local listing or existing Find results by name or relative path.",
|
||||
"inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"query":{"type":"string","minLength":1,"maxLength":128},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"required":["query"],"additionalProperties":false},
|
||||
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
|
||||
{"name":"get_file_metadata","description":"Read cached metadata for a relative path already listed in a current local pane.",
|
||||
"inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"path":{"type":"string","minLength":1,"maxLength":2048}},"required":["path"],"additionalProperties":false},
|
||||
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}}
|
||||
]})");
|
||||
return tools;
|
||||
}
|
||||
|
||||
Json toolResult(const Json &data,bool error=false)
|
||||
{
|
||||
const auto text=error?data.get<std::string>():data.dump(-1,' ',false,Json::error_handler_t::replace);
|
||||
Json result{{"content",Json::array({{{"type","text"},{"text",text}}})},{"isError",error}};
|
||||
if(!error) result["structuredContent"]=data;
|
||||
return result;
|
||||
}
|
||||
|
||||
template<class Read>
|
||||
HttpReply handleRpc(std::string_view body,const Read &read)
|
||||
{
|
||||
Json message,id;
|
||||
try
|
||||
{
|
||||
message=Json::parse(body,[](int depth,Json::parse_event_t,Json &)
|
||||
{
|
||||
if(depth>24) throw std::runtime_error("Request nesting limit");
|
||||
return true;
|
||||
});
|
||||
}
|
||||
catch(const std::exception &) {return rpcError("400 Bad Request",nullptr,-32700,"Invalid JSON");}
|
||||
if(!message.is_object() || message.value("jsonrpc",Json())!="2.0" ||
|
||||
!message.contains("method") || !message["method"].is_string())
|
||||
return rpcError("400 Bad Request",nullptr,-32600,"Invalid request");
|
||||
const auto &method=message["method"].get_ref<const std::string &>();
|
||||
if(!message.contains("id"))
|
||||
{
|
||||
if(method=="notifications/initialized" || method=="notifications/cancelled") return {"202 Accepted",{}};
|
||||
return rpcError("400 Bad Request",nullptr,-32600,"Unsupported notification");
|
||||
}
|
||||
id=message["id"];
|
||||
if(!id.is_number_integer() && (!id.is_string() || id.get_ref<const std::string &>().size()>256))
|
||||
return rpcError("400 Bad Request",nullptr,-32600,"Invalid request id");
|
||||
auto params=message.value("params",Json::object());
|
||||
if(!params.is_object()) return rpcError("200 OK",id,-32602,"Invalid parameters");
|
||||
Json result;
|
||||
if(method=="initialize")
|
||||
{
|
||||
if(!params.contains("protocolVersion") || !params["protocolVersion"].is_string())
|
||||
return rpcError("200 OK",id,-32602,"Protocol version is required");
|
||||
const auto version=params["protocolVersion"].get<std::string>();
|
||||
result={{"protocolVersion",supportedProtocol(version)?version:std::string(latestProtocol)},
|
||||
{"capabilities",{{"tools",Json::object()}}},
|
||||
{"serverInfo",{{"name","kswitcher-files"},{"version","1.0.0"}}},
|
||||
{"instructions","Inspect the current local listings and cached metadata. Search uses the Files panels' current results."}};
|
||||
}
|
||||
else if(method=="ping") result=Json::object();
|
||||
else if(method=="tools/list") result=mcpTools();
|
||||
else if(method=="tools/call")
|
||||
{
|
||||
if(!params.contains("name") || !params["name"].is_string())
|
||||
return rpcError("200 OK",id,-32602,"Tool name is required");
|
||||
const auto &name=params["name"].get_ref<const std::string &>();
|
||||
const auto args=params.value("arguments",Json::object());
|
||||
if(!args.is_object() || !std::ranges::any_of(mcpTools()["tools"],[&](const auto &tool)
|
||||
{return tool["name"]==name;}))
|
||||
return rpcError("200 OK",id,-32602,"Unknown tool or invalid arguments");
|
||||
auto data=read(name,args);
|
||||
const auto failed=data.contains("error");
|
||||
result=failed?toolResult(data.at("error"),true):toolResult(data);
|
||||
}
|
||||
else return rpcError("200 OK",id,-32601,"Method not found");
|
||||
auto answer=jsonReply("200 OK",{{"jsonrpc","2.0"},{"id",id},{"result",std::move(result)}});
|
||||
return answer.body.size()<=maxResponse?std::move(answer):rpcError("200 OK",id,-32603,"Response is too large");
|
||||
}
|
||||
|
||||
template<class Read>
|
||||
HttpReply handleHttp(SOCKET socket,unsigned port,std::string_view token,std::stop_token stop,const Read &read)
|
||||
{
|
||||
std::string bytes;
|
||||
const auto deadline=Clock::now()+2s;
|
||||
size_t end{};
|
||||
while((end=bytes.find("\r\n\r\n"))==bytes.npos)
|
||||
{
|
||||
if(bytes.size()>=maxHeaders) return {"431 Request Header Fields Too Large",{}};
|
||||
if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}};
|
||||
}
|
||||
if(end+4>maxHeaders) return {"431 Request Header Fields Too Large",{}};
|
||||
// Header fields refer into bytes. Parse before appending any further data.
|
||||
const auto request=parseHeaders(std::string_view(bytes).substr(0,end+2));
|
||||
if(!request) return {"400 Bad Request",{}};
|
||||
if(request->headers.contains("origin") || request->header("host")!="127.0.0.1:"+std::to_string(port))
|
||||
return {"403 Forbidden",{}};
|
||||
if(!hasSessionToken(request->header("authorization"),token))
|
||||
return {"401 Unauthorized",{},"WWW-Authenticate: Bearer\r\n"};
|
||||
if(request->path!="/mcp") return {"404 Not Found",{}};
|
||||
if(request->method!="POST") return {"405 Method Not Allowed",{},"Allow: POST\r\n"};
|
||||
if(request->headers.contains("transfer-encoding") ||
|
||||
(request->headers.contains("mcp-protocol-version") && !supportedProtocol(request->header("mcp-protocol-version"))))
|
||||
return {"400 Bad Request",{}};
|
||||
const auto type=request->header("content-type");
|
||||
if(lowerAscii(trimHeader(type.substr(0,type.find(';'))))!="application/json") return {"415 Unsupported Media Type",{}};
|
||||
const auto length=request->header("content-length");
|
||||
size_t count{};
|
||||
if(length.empty()) return {"411 Length Required",{}};
|
||||
const auto converted=std::from_chars(length.data(),length.data()+length.size(),count);
|
||||
if(converted.ec!=std::errc{} || converted.ptr!=length.data()+length.size()) return {"400 Bad Request",{}};
|
||||
if(count>maxRequest) return {"413 Content Too Large",{}};
|
||||
const auto start=end+4;
|
||||
while(bytes.size()-start<count)
|
||||
if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}};
|
||||
if(bytes.size()-start!=count) return {"400 Bad Request",{}};
|
||||
return handleRpc(std::string_view(bytes).substr(start,count),read);
|
||||
}
|
||||
}
|
||||
|
||||
struct FilesMcpServer::Session
|
||||
{
|
||||
struct Query
|
||||
{
|
||||
std::string name;
|
||||
Json arguments;
|
||||
std::promise<Json> result;
|
||||
std::atomic_bool cancelled{};
|
||||
};
|
||||
|
||||
lan::Network network;
|
||||
lan::WinSocket listener;
|
||||
unsigned port{};
|
||||
std::string token=lan::randomHex(32);
|
||||
HWND owner{};
|
||||
std::mutex gate;
|
||||
std::shared_ptr<Query> pending;
|
||||
std::jthread worker;
|
||||
|
||||
explicit Session(HWND window):owner(window)
|
||||
{
|
||||
listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
|
||||
BOOL exclusive=TRUE;
|
||||
u_long nonblocking=1;
|
||||
sockaddr_in address{};
|
||||
address.sin_family=AF_INET;
|
||||
address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
|
||||
int size=sizeof(address);
|
||||
if(listener.value==INVALID_SOCKET || setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,
|
||||
reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
|
||||
ioctlsocket(listener.value,FIONBIO,&nonblocking) ||
|
||||
bind(listener.value,reinterpret_cast<const sockaddr *>(&address),sizeof(address)) ||
|
||||
listen(listener.value,4) || getsockname(listener.value,reinterpret_cast<sockaddr *>(&address),&size))
|
||||
lan::socketError();
|
||||
port=ntohs(address.sin_port);
|
||||
worker=std::jthread([this](std::stop_token stop){run(stop);});
|
||||
}
|
||||
|
||||
~Session()
|
||||
{
|
||||
worker.request_stop();
|
||||
if(worker.joinable()) worker.join();
|
||||
SecureZeroMemory(token.data(),token.size());
|
||||
}
|
||||
|
||||
Json requestUi(std::string_view name,const Json &arguments,std::stop_token stop)
|
||||
{
|
||||
auto query=std::make_shared<Query>();
|
||||
query->name=name;
|
||||
query->arguments=arguments;
|
||||
auto result=query->result.get_future();
|
||||
{
|
||||
std::lock_guard lock(gate);
|
||||
pending=query;
|
||||
}
|
||||
const auto deadline=Clock::now()+2s;
|
||||
if(PostMessageW(owner,filesMcpQueryMessage,0,0))
|
||||
while(!stop.stop_requested() && Clock::now()<deadline)
|
||||
if(result.wait_for(25ms)==std::future_status::ready) return result.get();
|
||||
query->cancelled=true;
|
||||
std::lock_guard lock(gate);
|
||||
if(pending==query) pending.reset();
|
||||
return {{"error","Files did not answer in time."}};
|
||||
}
|
||||
|
||||
void run(std::stop_token stop)
|
||||
{
|
||||
while(!stop.stop_requested())
|
||||
{
|
||||
if(!readySocket(listener.value,false,stop,Clock::now()+100ms)) continue;
|
||||
sockaddr_in peer{};
|
||||
int peerSize=sizeof(peer);
|
||||
lan::WinSocket client;
|
||||
client.value=accept(listener.value,reinterpret_cast<sockaddr *>(&peer),&peerSize);
|
||||
u_long nonblocking=1;
|
||||
if(client.value==INVALID_SOCKET || peer.sin_family!=AF_INET ||
|
||||
peer.sin_addr.s_addr!=htonl(INADDR_LOOPBACK) || ioctlsocket(client.value,FIONBIO,&nonblocking))
|
||||
continue;
|
||||
HttpReply reply{"500 Internal Server Error",{}};
|
||||
try
|
||||
{
|
||||
reply=handleHttp(client.value,port,token,stop,[&](std::string_view name,const Json ¶ms)
|
||||
{return requestUi(name,params,stop);});
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
const auto header=std::string("HTTP/1.1 ")+reply.status+"\r\nConnection: close\r\n"
|
||||
"Cache-Control: no-store\r\nContent-Type: application/json\r\n"+reply.headers+
|
||||
"Content-Length: "+std::to_string(reply.body.size())+"\r\n\r\n";
|
||||
sendSocket(client.value,header+reply.body,stop);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
FilesMcpServer::FilesMcpServer()=default;
|
||||
FilesMcpServer::~FilesMcpServer()=default;
|
||||
|
||||
void FilesMcpServer::start(HWND owner)
|
||||
{
|
||||
if(!session) session=std::make_unique<Session>(owner);
|
||||
}
|
||||
|
||||
void FilesMcpServer::stop() {session.reset();}
|
||||
unsigned FilesMcpServer::port() const {return session?session->port:0;}
|
||||
std::string_view FilesMcpServer::token() const {return session?std::string_view(session->token):std::string_view{};}
|
||||
|
||||
void FilesMcpServer::answer(const ReadTool &read)
|
||||
{
|
||||
if(!session) return;
|
||||
std::shared_ptr<Session::Query> query;
|
||||
{
|
||||
std::lock_guard lock(session->gate);
|
||||
query=std::exchange(session->pending,{});
|
||||
}
|
||||
if(!query || query->cancelled) return;
|
||||
try {query->result.set_value(read(query->name,query->arguments));}
|
||||
catch(const std::exception &) {query->result.set_value({{"error","Files could not read the requested state."}});}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include "../vendor/json.hpp"
|
||||
#include <windows.h>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline constexpr UINT filesMcpQueryMessage=WM_APP+274;
|
||||
|
||||
class FilesMcpServer
|
||||
{
|
||||
public:
|
||||
using Json=nlohmann::json;
|
||||
using ReadTool=std::function<Json(std::string_view,const Json &)>;
|
||||
FilesMcpServer();
|
||||
~FilesMcpServer();
|
||||
FilesMcpServer(const FilesMcpServer &)=delete;
|
||||
FilesMcpServer &operator=(const FilesMcpServer &)=delete;
|
||||
|
||||
void start(HWND owner);
|
||||
void stop();
|
||||
unsigned port() const;
|
||||
std::string_view token() const;
|
||||
void answer(const ReadTool &read);
|
||||
|
||||
private:
|
||||
struct Session;
|
||||
std::unique_ptr<Session> session;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
ks::files::FilesMcpServer filesMcp;
|
||||
constexpr int filesMcpStatus=690,filesMcpEndpoint=691,filesMcpToken=692,filesMcpToggle=693,
|
||||
filesMcpShowToken=694,filesMcpCopyToken=695;
|
||||
constexpr size_t maxMcpRows=50,maxMcpSearchScan=10000;
|
||||
|
||||
std::string mcpSide(int side) {return side==0?"left":"right";}
|
||||
|
||||
bool mcpLocalPanel(const Panel &panel)
|
||||
{
|
||||
return !panel.peer && !panel.ftp && !panel.archive && ks::files::isLocalDocumentPath(panel.directory);
|
||||
}
|
||||
|
||||
std::optional<std::wstring> mcpRelativePath(const Panel &panel,size_t row)
|
||||
{
|
||||
if(row>=panel.rows.size() || row>=panel.sizes.size() || panel.sizes[row]==L"Up") return {};
|
||||
const auto relative=panel.rows[row].lexically_relative(panel.directory);
|
||||
if(relative.empty() || relative.has_root_path()) return {};
|
||||
for(const auto &part:relative)
|
||||
if(!ks::files::validWindowsFileName(part.native())) return {};
|
||||
const auto path=relative.generic_wstring();
|
||||
if(path.size()>2048) return {};
|
||||
return path;
|
||||
}
|
||||
|
||||
Json mcpFileItem(const Panel &panel,size_t row,const std::wstring &relative)
|
||||
{
|
||||
Json item{{"path",ks::utf8(relative)},{"marked",row<panel.marked.size() && panel.marked[row]}};
|
||||
const auto found=panel.metadata.find(panel.rows[row]);
|
||||
if(found==panel.metadata.end())
|
||||
{
|
||||
item["metadataAvailable"]=false;
|
||||
return item;
|
||||
}
|
||||
const auto &info=found->second;
|
||||
const bool directory=(info.attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
|
||||
item["metadataAvailable"]=true;
|
||||
item["kind"]=directory?"directory":"file";
|
||||
item["attributes"]=info.attributes;
|
||||
item["reparsePoint"]=(info.attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0;
|
||||
if(!directory) item["sizeBytes"]=info.size;
|
||||
if(info.modified)
|
||||
{
|
||||
const FILETIME time{static_cast<DWORD>(info.modified),static_cast<DWORD>(info.modified>>32)};
|
||||
SYSTEMTIME utc{};
|
||||
if(FileTimeToSystemTime(&time,&utc))
|
||||
{
|
||||
wchar_t date[32]{};
|
||||
swprintf_s(date,L"%04u-%02u-%02uT%02u:%02u:%02uZ",utc.wYear,utc.wMonth,utc.wDay,
|
||||
utc.wHour,utc.wMinute,utc.wSecond);
|
||||
item["modifiedUtc"]=ks::utf8(date);
|
||||
}
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
std::optional<size_t> mcpPageValue(const Json &args,const char *key,size_t fallback,size_t maximum)
|
||||
{
|
||||
if(!args.contains(key)) return fallback;
|
||||
const auto &value=args.at(key);
|
||||
if(!value.is_number_unsigned() || value>maximum) return {};
|
||||
return value.get<size_t>();
|
||||
}
|
||||
|
||||
bool mcpArgumentNames(const Json &arguments,std::initializer_list<std::string_view> accepted)
|
||||
{
|
||||
for(auto field=arguments.begin();field!=arguments.end();++field)
|
||||
if(std::ranges::find(accepted,std::string_view(field.key()))==accepted.end()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<int> mcpArgumentSide(const Json &arguments)
|
||||
{
|
||||
if(!arguments.contains("side") || arguments.at("side")=="active") return active;
|
||||
if(arguments.at("side")=="left") return 0;
|
||||
if(arguments.at("side")=="right") return 1;
|
||||
return {};
|
||||
}
|
||||
|
||||
Json mcpPanelPage(const Panel &panel,size_t offset,size_t limit,std::wstring_view query={})
|
||||
{
|
||||
Json entries=Json::array();
|
||||
size_t row=std::min(offset,panel.rows.size());
|
||||
const auto scannedEnd=row+std::min(maxMcpSearchScan,panel.rows.size()-row);
|
||||
for(;row<scannedEnd && entries.size()<limit;++row)
|
||||
if(const auto relative=mcpRelativePath(panel,row))
|
||||
if(query.empty() || ks::lower(*relative).find(query)!=std::wstring::npos)
|
||||
entries.push_back(mcpFileItem(panel,row,*relative));
|
||||
return {{"entries",std::move(entries)},{"nextOffset",row<panel.rows.size()?Json(row):Json(nullptr)}};
|
||||
}
|
||||
|
||||
Json mcpPanelState(int side,size_t offset,size_t limit)
|
||||
{
|
||||
const auto &panel=panels[side];
|
||||
Json result{{"side",mcpSide(side)},{"available",mcpLocalPanel(panel)},
|
||||
{"visible",IsWindowVisible(panel.list)!=FALSE}};
|
||||
if(!result.at("available").get<bool>()) return result;
|
||||
result["directory"]=ks::utf8(panel.directory.native());
|
||||
result["mode"]=ks::utf8(panelModeNames[static_cast<size_t>(panel.mode)]);
|
||||
result["scanning"]=panel.scanRequest.has_value();
|
||||
const auto selected=currentPanelRow(panel);
|
||||
if(selected!=LB_ERR)
|
||||
if(const auto path=mcpRelativePath(panel,static_cast<size_t>(selected))) result["cursor"]=ks::utf8(*path);
|
||||
const auto *pending=panel.scanRequest && panel.scanRequest->find?&*panel.scanRequest->find:nullptr;
|
||||
if(pending || panel.findOrigin)
|
||||
{
|
||||
const auto &find=pending?*pending:panel.findOrigin->options;
|
||||
result["find"]={{"mask",ks::utf8(find.mask)},{"includeHidden",find.includeHidden},
|
||||
{"running",pending!=nullptr},{"error",pending?0:panel.findOrigin->error}};
|
||||
}
|
||||
result.update(mcpPanelPage(panel,offset,limit));
|
||||
return result;
|
||||
}
|
||||
|
||||
Json readFilesMcpTool(std::string_view tool,const Json &arguments)
|
||||
{
|
||||
const auto offset=mcpPageValue(arguments,"offset",0,2147483647);
|
||||
const auto limit=mcpPageValue(arguments,"limit",25,maxMcpRows);
|
||||
if(!offset || !limit || !*limit) return {{"error","Invalid page offset or limit."}};
|
||||
if(tool=="get_panels")
|
||||
{
|
||||
if(!mcpArgumentNames(arguments,{"offset","limit"})) return {{"error","Unknown pane argument."}};
|
||||
return {{"active",mcpSide(active)},{"panels",Json::array(
|
||||
{mcpPanelState(0,*offset,*limit),mcpPanelState(1,*offset,*limit)})}};
|
||||
}
|
||||
const auto side=mcpArgumentSide(arguments);
|
||||
if(!side) return {{"error","Choose an active, left or right pane."}};
|
||||
const auto &panel=panels[*side];
|
||||
if(!mcpLocalPanel(panel)) return {{"error","This pane is not a local filesystem listing."}};
|
||||
if(tool=="search_files")
|
||||
{
|
||||
if(!mcpArgumentNames(arguments,{"side","query","offset","limit"}) || !arguments.contains("query") ||
|
||||
!arguments["query"].is_string() || arguments["query"].get_ref<const std::string &>().size()>512)
|
||||
return {{"error","Enter a search query of 1 to 128 characters."}};
|
||||
auto query=ks::wide(arguments["query"].get_ref<const std::string &>());
|
||||
if(query.empty() || query.size()>128 || query.find_first_of(L"\r\n")!=query.npos ||
|
||||
query.find(L'\0')!=query.npos) return {{"error","Enter a search query of 1 to 128 characters."}};
|
||||
auto result=mcpPanelPage(panel,*offset,*limit,ks::lower(std::move(query)));
|
||||
result["side"]=mcpSide(*side);
|
||||
result["scope"]=panel.findOrigin?"find-results":"current-listing";
|
||||
return result;
|
||||
}
|
||||
if(tool!="get_file_metadata" || !mcpArgumentNames(arguments,{"side","path"}) ||
|
||||
!arguments.contains("path") || !arguments["path"].is_string() ||
|
||||
arguments["path"].get_ref<const std::string &>().size()>8192)
|
||||
return {{"error","Choose a relative path from the current pane."}};
|
||||
auto relative=fs::path(ks::wide(arguments["path"].get_ref<const std::string &>()));
|
||||
if(relative.empty() || relative.has_root_path() || relative.native().size()>2048)
|
||||
return {{"error","Choose a relative path from the current pane."}};
|
||||
for(const auto &part:relative)
|
||||
if(!ks::files::validWindowsFileName(part.native()))
|
||||
return {{"error","Choose a relative path from the current pane."}};
|
||||
relative.make_preferred();
|
||||
const auto path=panel.directory/relative;
|
||||
const auto found=std::ranges::find(panel.rows,path);
|
||||
if(found==panel.rows.end()) return {{"error","The file is not in the current pane."}};
|
||||
const auto row=static_cast<size_t>(found-panel.rows.begin());
|
||||
const auto listed=mcpRelativePath(panel,row);
|
||||
if(!listed) return {{"error","The file is not in the current pane."}};
|
||||
return mcpFileItem(panel,row,*listed);
|
||||
}
|
||||
|
||||
void updateFilesMcpDialog(HWND dialog)
|
||||
{
|
||||
const auto port=filesMcp.port();
|
||||
const auto endpoint=port?L"http://127.0.0.1:"+std::to_wstring(port)+L"/mcp":L"";
|
||||
SetDlgItemTextW(dialog,filesMcpEndpoint,endpoint.c_str());
|
||||
SetDlgItemTextW(dialog,filesMcpToggle,port?L"&Stop":L"&Start");
|
||||
EnableWindow(GetDlgItem(dialog,filesMcpShowToken),port!=0);
|
||||
EnableWindow(GetDlgItem(dialog,filesMcpCopyToken),port!=0);
|
||||
if(!port) CheckDlgButton(dialog,filesMcpShowToken,BST_UNCHECKED);
|
||||
const auto token=port && IsDlgButtonChecked(dialog,filesMcpShowToken)==BST_CHECKED?
|
||||
ks::wide(std::string(filesMcp.token())):L"";
|
||||
SetDlgItemTextW(dialog,filesMcpToken,token.c_str());
|
||||
SetDlgItemTextW(dialog,filesMcpStatus,port?
|
||||
L"Running on this computer. Stop to revoke the session token.":L"Stopped.");
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK filesMcpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
updateFilesMcpDialog(dialog);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
|
||||
{
|
||||
SetDlgItemTextW(dialog,filesMcpToken,L"");
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
switch(LOWORD(wp))
|
||||
{
|
||||
case filesMcpToggle:
|
||||
try
|
||||
{
|
||||
if(filesMcp.port()) filesMcp.stop();
|
||||
else filesMcp.start(reinterpret_cast<HWND>(GetWindowLongPtrW(dialog,DWLP_USER)));
|
||||
updateFilesMcpDialog(dialog);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetDlgItemTextW(dialog,filesMcpStatus,L"Could not start the local MCP listener.");
|
||||
}
|
||||
return TRUE;
|
||||
case filesMcpShowToken:
|
||||
updateFilesMcpDialog(dialog);
|
||||
return TRUE;
|
||||
case filesMcpCopyToken:
|
||||
if(filesMcp.port() && copyFilesText(dialog,ks::wide(std::string(filesMcp.token())),L"Could not copy the token."))
|
||||
SetDlgItemTextW(dialog,filesMcpStatus,L"Session token copied.");
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void showFilesMcp(HWND owner)
|
||||
{
|
||||
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(620),owner,filesMcpDialog,
|
||||
reinterpret_cast<LPARAM>(owner),false,false);
|
||||
dialog.runModal();
|
||||
}
|
||||
+339
-94
@@ -1,12 +1,13 @@
|
||||
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
|
||||
optionsImport=525,optionsExport=526,
|
||||
optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372;
|
||||
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions, CompareFiles };
|
||||
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",
|
||||
L"Viewer",L"Editor",L"All settings",L"File comparison"};
|
||||
constexpr int comparisonFontLabel=408,comparisonChooseFont=409,comparisonColorCombo=411,
|
||||
comparisonChooseColor=412,comparisonColorValue=413,comparisonShortcutControl=415;
|
||||
comparisonChooseColor=412,comparisonColorValue=413,comparisonKeySchemesButton=415;
|
||||
constexpr int comparisonControls[]{comparisonFontLabel,comparisonChooseFont,410,comparisonColorCombo,
|
||||
comparisonChooseColor,comparisonColorValue,414,comparisonShortcutControl};
|
||||
comparisonChooseColor,comparisonColorValue,comparisonKeySchemesButton};
|
||||
constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background",
|
||||
L"Menu selection",L"Command bar",L"File cursor"};
|
||||
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
|
||||
@@ -17,13 +18,19 @@ 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 };
|
||||
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};
|
||||
constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307;
|
||||
constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding};
|
||||
constexpr int restoreDocumentsControl=524;
|
||||
constexpr int textTabWidth=357,textLineEnding=359,
|
||||
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368;
|
||||
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368,textRenameScheme=534;
|
||||
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
|
||||
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme};
|
||||
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme,textRenameScheme};
|
||||
constexpr int editingControls[]{354,355,358,textLineEnding};
|
||||
constexpr int markdownSection=1,markdownWidth=374,markdownFamily=376,markdownChoose=377,markdownSize=379;
|
||||
constexpr int markdownControls[]{373,markdownWidth,375,markdownFamily,markdownChoose,378,markdownSize};
|
||||
@@ -52,7 +59,7 @@ constexpr struct
|
||||
{innerFramePadding,&DialogFramePadding::inner,maxDialogFramePadding},
|
||||
{rowTextPadding,&DialogFramePadding::rowText,maxDialogRowTextPadding}};
|
||||
|
||||
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight };
|
||||
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight, BottomLeft };
|
||||
struct OptionsControl
|
||||
{
|
||||
int id;
|
||||
@@ -100,29 +107,34 @@ void showPanelModeOptions(HWND dialog)
|
||||
|
||||
struct OptionsBaseline
|
||||
{
|
||||
FilesAppearance appearance=filesAppearance;
|
||||
LOGFONTW font=displayFont;
|
||||
int points=fontPoints;
|
||||
DialogFramePadding padding=dialogFramePadding;
|
||||
std::array<COLORREF,ColorCount> palette=colors;
|
||||
std::vector<FileStyle> styles=fileStyles;
|
||||
std::array<WORD,2> keys=commandHistoryKeys;
|
||||
bool remoteTerminal=ks::lan::remoteTerminalAllowed();
|
||||
bool remoteHibernate=ks::lan::remoteHibernateAllowed();
|
||||
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
|
||||
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
|
||||
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
|
||||
bool mouseMarks=rightClickMarks, drives=showDriveButtons, compact=compactLayout;
|
||||
bool restoreLocal=restoreDocuments;
|
||||
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
|
||||
ks::files::TextSettings text=ks::files::loadTextPreferences();
|
||||
ComparisonAppearance comparison=readComparisonAppearance();
|
||||
WORD compareShortcut=comparisonShortcut;
|
||||
FilesKeySettings keySettings=filesKeySettings;
|
||||
ks::files::AppearanceScales scales=readAreaScales();
|
||||
};
|
||||
|
||||
struct OptionsDraft
|
||||
{
|
||||
OptionsBaseline baseline;
|
||||
FilesAppearance appearance=baseline.appearance;
|
||||
ks::files::TextSettings text=baseline.text;
|
||||
ComparisonAppearance comparison=baseline.comparison;
|
||||
FilesKeySettings keySettings=baseline.keySettings;
|
||||
ks::files::AppearanceScales scales=baseline.scales;
|
||||
HWND filesWindow{};
|
||||
LOGFONTW font=displayFont;
|
||||
int points=fontPoints;
|
||||
@@ -136,15 +148,16 @@ struct OptionsDraft
|
||||
DWORD location{};
|
||||
int markdownError{};
|
||||
HTREEITEM wideColumnsNode{},markdownNode{};
|
||||
RECT initialClient{};
|
||||
RECT initialClient{}, resetBounds{};
|
||||
UINT initialDpi=96;
|
||||
OptionsControl controls[8]{
|
||||
OptionsControl controls[10]{
|
||||
{optionsTree,OptionsAnchor::StretchHeight},
|
||||
{optionsTitle,OptionsAnchor::StretchWidth},
|
||||
{275,OptionsAnchor::StretchWidth},{277,OptionsAnchor::StretchWidth},
|
||||
{281,OptionsAnchor::StretchWidth},
|
||||
{IDOK,OptionsAnchor::BottomRight},{IDCANCEL,OptionsAnchor::BottomRight},
|
||||
{optionsApply,OptionsAnchor::BottomRight}};
|
||||
{optionsApply,OptionsAnchor::BottomRight},
|
||||
{optionsImport,OptionsAnchor::BottomLeft},{optionsExport,OptionsAnchor::BottomLeft}};
|
||||
|
||||
};
|
||||
|
||||
@@ -162,19 +175,6 @@ bool optionsFontChanged(const OptionsDraft &draft)
|
||||
_wcsicmp(pending.lfFaceName,applied.lfFaceName)!=0;
|
||||
}
|
||||
|
||||
struct OptionsWriteLock
|
||||
{
|
||||
HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite");
|
||||
DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED;
|
||||
|
||||
bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; }
|
||||
~OptionsWriteLock()
|
||||
{
|
||||
if(acquired()) ReleaseMutex(mutex);
|
||||
if(mutex) CloseHandle(mutex);
|
||||
}
|
||||
};
|
||||
|
||||
void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
{
|
||||
BOOL valid{};
|
||||
@@ -187,14 +187,14 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] ||
|
||||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
|
||||
checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives ||
|
||||
checked(compactLayoutControl)!=base.compact ||
|
||||
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) ||
|
||||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
|
||||
draft.framePadding!=base.padding || optionsFontChanged(draft) || draft.appearance!=base.appearance ||
|
||||
checked(optionsRemoteTerminal)!=base.remoteTerminal ||
|
||||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
|
||||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
|
||||
draft.text!=base.text || draft.comparison!=base.comparison ||
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0)!=base.compareShortcut;
|
||||
draft.text!=base.text || draft.comparison!=base.comparison || draft.keySettings!=base.keySettings ||
|
||||
draft.scales!=base.scales;
|
||||
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
|
||||
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
|
||||
}
|
||||
@@ -206,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);
|
||||
@@ -225,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);
|
||||
@@ -252,11 +254,19 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft)
|
||||
case OptionsAnchor::StretchWidth: width+=dx;break;
|
||||
case OptionsAnchor::StretchHeight: height+=dy;break;
|
||||
case OptionsAnchor::BottomRight: x+=dx;y+=dy;break;
|
||||
case OptionsAnchor::BottomLeft: y+=dy;break;
|
||||
}
|
||||
SetWindowPos(GetDlgItem(dialog,control.id),nullptr,x,y,width,height,
|
||||
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.
|
||||
@@ -287,19 +297,22 @@ void populateTextSchemes(HWND dialog,const ks::files::TextSettings &settings)
|
||||
};
|
||||
add(L"Custom");
|
||||
for(const auto name:ks::files::textPaletteNames) add(name);
|
||||
add(L"System (Windows)");
|
||||
for(const auto &scheme:settings.schemes) add(scheme.name.c_str());
|
||||
}
|
||||
|
||||
size_t currentTextScheme(const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
|
||||
{
|
||||
for(size_t index=0;index<std::size(ks::files::textPalettes);++index)
|
||||
const auto presets=std::size(ks::files::textPalettes);
|
||||
if(profile.scheme==ks::files::systemTextScheme) return presets+1;
|
||||
for(size_t index=0;index<presets;++index)
|
||||
if(profile.scheme==ks::files::textPaletteNames[index] && profile.colors==ks::files::textPalettes[index])
|
||||
return index+1;
|
||||
for(size_t index=0;index<settings.schemes.size();++index)
|
||||
{
|
||||
const auto &scheme=settings.schemes[index];
|
||||
if(profile.scheme==scheme.name && profile.colors==scheme.colors)
|
||||
return std::size(ks::files::textPalettes)+index+1;
|
||||
return presets+index+2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -310,6 +323,13 @@ INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
SendDlgItemMessageW(dialog,100,EM_SETLIMITTEXT,ks::files::maxTextPaletteName,0);
|
||||
const auto &name=*reinterpret_cast<const std::wstring*>(lp);
|
||||
if(!name.empty())
|
||||
{
|
||||
SetWindowTextW(dialog,L"Rename color scheme");
|
||||
SetDlgItemTextW(dialog,100,name.c_str());
|
||||
SetDlgItemTextW(dialog,IDOK,L"Rename");
|
||||
}
|
||||
groupDialogButtons(dialog,{IDOK,IDCANCEL},true);
|
||||
return TRUE;
|
||||
}
|
||||
@@ -327,13 +347,22 @@ INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files::TextPreferences &profile)
|
||||
bool reservedTextSchemeName(const std::wstring &name)
|
||||
{
|
||||
return sameSchemeName(name,L"Custom") || sameSchemeName(name,L"System (Windows)") ||
|
||||
sameSchemeName(name,ks::files::systemTextScheme) ||
|
||||
std::any_of(std::begin(ks::files::textPaletteNames),std::end(ks::files::textPaletteNames),
|
||||
[&](const wchar_t *preset){return sameSchemeName(name,preset);});
|
||||
}
|
||||
|
||||
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,bool edit)
|
||||
{
|
||||
auto &profile=settings.profiles[edit];
|
||||
const auto palette=ks::files::resolvedTextProfile(settings,edit).colors;
|
||||
std::wstring name;
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog,
|
||||
reinterpret_cast<LPARAM>(&name))!=IDOK) return;
|
||||
if(sameSchemeName(name,L"Custom") || std::any_of(std::begin(ks::files::textPaletteNames),
|
||||
std::end(ks::files::textPaletteNames),[&](const wchar_t *preset){return sameSchemeName(name,preset);}))
|
||||
if(reservedTextSchemeName(name))
|
||||
{
|
||||
showFilesNotice(dialog,L"Choose a different name for your color scheme.",L"Save color scheme");
|
||||
return;
|
||||
@@ -344,7 +373,7 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
|
||||
{
|
||||
if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",
|
||||
{.confirm=true,.tone=FilesNoticeTone::neutral})!=IDYES) return;
|
||||
existing->colors=profile.colors;
|
||||
existing->colors=palette;
|
||||
profile.scheme=existing->name;
|
||||
}
|
||||
else
|
||||
@@ -354,18 +383,44 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
|
||||
showFilesNotice(dialog,L"The color scheme list is full.",L"Save color scheme");
|
||||
return;
|
||||
}
|
||||
settings.schemes.push_back({name,profile.colors});
|
||||
settings.schemes.push_back({name,palette});
|
||||
profile.scheme=std::move(name);
|
||||
}
|
||||
profile.colors=palette;
|
||||
populateTextSchemes(dialog,settings);
|
||||
}
|
||||
|
||||
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
|
||||
void renameTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
|
||||
{
|
||||
const auto scheme=std::ranges::find_if(settings.schemes,[&](const auto &candidate)
|
||||
{ return sameSchemeName(profile.scheme,candidate.name.c_str()); });
|
||||
if(scheme==settings.schemes.end()) return;
|
||||
auto name=scheme->name;
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog,
|
||||
reinterpret_cast<LPARAM>(&name))!=IDOK || name==scheme->name) return;
|
||||
if(reservedTextSchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &candidate)
|
||||
{return &candidate!=&*scheme && sameSchemeName(name,candidate.name.c_str());}))
|
||||
{
|
||||
showFilesNotice(dialog,L"Choose a unique name for the color scheme.",L"Rename color scheme");
|
||||
return;
|
||||
}
|
||||
for(auto &document:settings.profiles)
|
||||
if(sameSchemeName(document.scheme,scheme->name.c_str())) document.scheme=name;
|
||||
for(auto &role:settings.systemThemes)
|
||||
if(sameSchemeName(role,scheme->name.c_str())) role=name;
|
||||
scheme->name=std::move(name);
|
||||
populateTextSchemes(dialog,settings);
|
||||
}
|
||||
|
||||
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,bool edit)
|
||||
{
|
||||
const auto profile=ks::files::resolvedTextProfile(settings,edit);
|
||||
for(const auto &check:textChecks) CheckDlgButton(dialog,check.id,profile.*check.value?BST_CHECKED:BST_UNCHECKED);
|
||||
SendDlgItemMessageW(dialog,textTabWidth,CB_SETCURSEL,profile.tabWidth-1,0);
|
||||
SendDlgItemMessageW(dialog,textLineEnding,CB_SETCURSEL,profile.lineEnding,0);
|
||||
SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,currentTextScheme(settings,profile),0);
|
||||
const auto selected=currentTextScheme(settings,profile);
|
||||
SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,selected,0);
|
||||
EnableWindow(GetDlgItem(dialog,textRenameScheme),selected>=std::size(ks::files::textPalettes)+2);
|
||||
refreshTextColor(dialog,profile);
|
||||
}
|
||||
|
||||
@@ -400,12 +455,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
if(const auto check=std::find_if(std::begin(textChecks),std::end(textChecks),
|
||||
[id](const auto &entry){return entry.id==id;});check!=std::end(textChecks))
|
||||
profile.*check->value=IsDlgButtonChecked(dialog,id)==BST_CHECKED;
|
||||
else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,profile);
|
||||
else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,draft.page==TextEditor);
|
||||
else if(id==textRenameScheme) renameTextSchemeDraft(dialog,draft.text,profile);
|
||||
else if(id==textChangeColor)
|
||||
{
|
||||
const auto index=row(textColor);
|
||||
if(index>=0 && static_cast<size_t>(index)<profile.colors.size())
|
||||
choosePanelColor(dialog,profile.colors[index],draft.custom.data());
|
||||
{
|
||||
auto palette=ks::files::resolvedTextProfile(draft.text,draft.page==TextEditor).colors;
|
||||
if(choosePanelColor(dialog,palette[index],draft.custom.data()))
|
||||
{
|
||||
profile.colors=palette;
|
||||
profile.scheme.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(HIWORD(command)==CBN_SELCHANGE)
|
||||
{
|
||||
@@ -417,15 +480,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
case textTabWidth: profile.tabWidth=static_cast<int>(selected)+1; break;
|
||||
case textLineEnding: profile.lineEnding=static_cast<int>(selected); break;
|
||||
case textTheme:
|
||||
if(selected==0) profile.scheme.clear();
|
||||
if(selected==0)
|
||||
{
|
||||
profile.colors=ks::files::resolvedTextProfile(draft.text,draft.page==TextEditor).colors;
|
||||
profile.scheme.clear();
|
||||
}
|
||||
else if(const auto scheme=static_cast<size_t>(selected-1);scheme<std::size(ks::files::textPalettes))
|
||||
{
|
||||
profile.scheme=ks::files::textPaletteNames[scheme];
|
||||
profile.colors=ks::files::textPalettes[scheme];
|
||||
}
|
||||
else if(scheme==std::size(ks::files::textPalettes)) profile.scheme=ks::files::systemTextScheme;
|
||||
else
|
||||
{
|
||||
const auto index=scheme-std::size(ks::files::textPalettes);
|
||||
const auto index=scheme-std::size(ks::files::textPalettes)-1;
|
||||
if(index>=draft.text.schemes.size()) return false;
|
||||
profile.scheme=draft.text.schemes[index].name;
|
||||
profile.colors=draft.text.schemes[index].colors;
|
||||
@@ -435,7 +503,7 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
}
|
||||
}
|
||||
else return false;
|
||||
showTextOptions(dialog,draft.text,profile);
|
||||
showTextOptions(dialog,draft.text,draft.page==TextEditor);
|
||||
updateOptionsApply(dialog,draft);
|
||||
return true;
|
||||
}
|
||||
@@ -454,6 +522,65 @@ void showComparisonOptions(HWND dialog,const ComparisonAppearance &appearance)
|
||||
SetDlgItemTextW(dialog,comparisonColorValue,hex);
|
||||
}
|
||||
|
||||
std::optional<AppearanceArea> optionsScaleArea(int page,int section)
|
||||
{
|
||||
if(page==Appearance && section==Font) return AppearanceArea::panels;
|
||||
if(page==CommandLine && section==terminalScaleSection) return AppearanceArea::terminal;
|
||||
if(page==TextViewer) return section==markdownSection?AppearanceArea::markdown:AppearanceArea::viewer;
|
||||
if(page==TextEditor) return AppearanceArea::editor;
|
||||
if(page==CompareFiles) return AppearanceArea::comparison;
|
||||
return {};
|
||||
}
|
||||
|
||||
void showAreaScale(HWND dialog,const OptionsDraft &draft,std::optional<AppearanceArea> area)
|
||||
{
|
||||
const auto label=GetDlgItem(dialog,areaScaleLabel);
|
||||
const auto field=GetDlgItem(dialog,areaScaleControl);
|
||||
ShowWindow(label,area?SW_SHOW:SW_HIDE);
|
||||
ShowWindow(field,area?SW_SHOW:SW_HIDE);
|
||||
if(!area) return;
|
||||
const auto index=ks::files::appearanceIndex(*area);
|
||||
constexpr const wchar_t *labels[]{L"&Panel scale",L"&Viewer scale",L"&Editor scale",L"&Markdown scale",
|
||||
L"&Terminal scale",L"&Comparison scale"};
|
||||
constexpr int top[]{77,232,232,124,29,155};
|
||||
SetWindowTextW(label,labels[index]);
|
||||
RECT labelBox{131,top[index]+3,0,0},fieldBox{257,top[index],0,0};
|
||||
MapDialogRect(dialog,&labelBox);
|
||||
MapDialogRect(dialog,&fieldBox);
|
||||
const auto flags=SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE;
|
||||
SetWindowPos(label,nullptr,labelBox.left,labelBox.top,0,0,flags);
|
||||
SetWindowPos(field,nullptr,fieldBox.left,fieldBox.top,0,0,flags);
|
||||
SendMessageW(field,CB_RESETCONTENT,0,0);
|
||||
const auto selected=draft.scales[index];
|
||||
for(unsigned percent=ks::files::minAppearanceScale;percent<=ks::files::maxAppearanceScale;++percent)
|
||||
{
|
||||
if(percent%5 && percent!=selected) continue;
|
||||
const auto caption=std::to_wstring(percent)+L"%";
|
||||
const auto row=SendMessageW(field,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(caption.c_str()));
|
||||
if(row<0) continue;
|
||||
SendMessageW(field,CB_SETITEMDATA,row,percent);
|
||||
if(percent==selected) SendMessageW(field,CB_SETCURSEL,row,0);
|
||||
}
|
||||
}
|
||||
|
||||
void showSystemThemeRoles(HWND dialog,const ks::files::TextSettings &settings)
|
||||
{
|
||||
constexpr int controls[]{systemLightChoice,systemDarkChoice};
|
||||
for(size_t role=0;role<std::size(controls);++role)
|
||||
{
|
||||
const auto control=GetDlgItem(dialog,controls[role]);
|
||||
SendMessageW(control,CB_RESETCONTENT,0,0);
|
||||
const auto add=[&](const wchar_t *name)
|
||||
{
|
||||
const auto row=SendMessageW(control,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
|
||||
if(row>=0 && sameSchemeName(settings.systemThemes[role],name))
|
||||
SendMessageW(control,CB_SETCURSEL,row,0);
|
||||
};
|
||||
for(const auto name:ks::files::textPaletteNames) add(name);
|
||||
for(const auto &scheme:settings.schemes) add(scheme.name.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
{
|
||||
draft.page=page;
|
||||
@@ -468,7 +595,9 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
else if(section>=0 && !textOptionsPage(page) && page!=CompareFiles)
|
||||
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
|
||||
(section==fileStyleSection?L"File type styles":colorNames[section]):
|
||||
page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font";
|
||||
page==CommandLine?(section==terminalScaleSection?L"Terminal appearance":L"Command history"):
|
||||
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)
|
||||
@@ -496,6 +625,11 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
show(wideColumnControls,page==PanelModes && section==WideColumns);
|
||||
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);
|
||||
if(page==CompareFiles) showComparisonOptions(dialog,draft.comparison);
|
||||
show(dialogFrameControls,page==Appearance && section==DialogFrame);
|
||||
@@ -504,17 +638,20 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
for(const auto &option:frameOptions)
|
||||
SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0);
|
||||
}
|
||||
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
|
||||
constexpr int commandLineControls[]{321,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
|
||||
show(commandLineControls,page==CommandLine && section==0);
|
||||
show(markdownControls,markdown);
|
||||
show(textControls,textOptionsPage(page) && !markdown);
|
||||
ShowWindow(GetDlgItem(dialog,restoreDocumentsControl),page==TextViewer && !markdown?SW_SHOW:SW_HIDE);
|
||||
show(editingControls,page==TextEditor);
|
||||
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
|
||||
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,page==TextEditor);
|
||||
const bool fileTypes=page==PanelColors && section==fileStyleSection;
|
||||
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);
|
||||
ShowWindow(preview,page>=0 && page<CommandLine && section>=0?SW_SHOW:SW_HIDE);
|
||||
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);
|
||||
show(colorOptionControls,page==PanelColors && section>=0 && !fileTypes);
|
||||
@@ -607,27 +744,36 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
addSection(L"File type styles",fileStyleSection,extensionMatches || matches(L"System and hidden") ||
|
||||
matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground"));
|
||||
}
|
||||
else if(page==CommandLine) addSection(L"Command history",0,
|
||||
matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here") ||
|
||||
matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here"));
|
||||
else if(page==CommandLine)
|
||||
{
|
||||
addSection(L"Command history",0,matches(L"Previous command") || matches(L"Keyboard shortcuts") ||
|
||||
matches(L"Allow paired PCs to run PowerShell commands here") || matches(L"Allow paired PCs to hibernate this PC") ||
|
||||
matches(L"Allow paired PCs to update KSwitcher here"));
|
||||
addSection(L"Terminal appearance",terminalScaleSection,matches(L"Terminal scale"));
|
||||
}
|
||||
else if(page==CompareFiles)
|
||||
addSection(L"Font and colors",0,matches(L"Compare files shortcut") || std::any_of(std::begin(comparisonColorNames),
|
||||
addSection(L"Font and colors",0,matches(L"Comparison scale") || matches(L"Compare files shortcut") || matches(L"Keyboard shortcuts") || std::any_of(std::begin(comparisonColorNames),
|
||||
std::end(comparisonColorNames),matches));
|
||||
else if(textOptionsPage(page))
|
||||
{
|
||||
const bool propertyMatches=matches(L"Tab width") ||
|
||||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Customize colors") ||
|
||||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Rename scheme") || matches(L"Customize colors") ||
|
||||
matches(page==TextEditor?L"Editor scale":L"Viewer scale") ||
|
||||
(page==TextEditor && matches(L"Line endings for new lines")) ||
|
||||
(page==TextViewer && matches(L"Restore local Viewer and Editor windows after restart")) ||
|
||||
std::any_of(std::begin(textChecks),std::end(textChecks),[&](const auto &check)
|
||||
{return (page==TextEditor || check.id<354) && matches(check.name);}) ||
|
||||
std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches);
|
||||
addSection(page==TextEditor?L"Editing and appearance":L"Viewing and appearance",0,propertyMatches);
|
||||
if(page==TextViewer) addSection(L"Markdown",markdownSection,
|
||||
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size"));
|
||||
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size") ||
|
||||
matches(L"Markdown scale"));
|
||||
}
|
||||
else
|
||||
{
|
||||
addSection(L"Font",Font,matches(L"Display font"));
|
||||
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"));
|
||||
}
|
||||
@@ -638,6 +784,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
if(!first) SetDlgItemTextW(dialog,optionsTitle,L"No matching settings");
|
||||
}
|
||||
|
||||
#include "files_options_transfer.inl"
|
||||
|
||||
INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
@@ -646,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.
|
||||
@@ -668,9 +817,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
for(const auto label:comparisonColorNames)
|
||||
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
|
||||
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_SETCURSEL,0,0);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETRULES,HKCOMB_NONE,HOTKEYF_SHIFT);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,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,
|
||||
@@ -689,18 +838,37 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
|
||||
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
|
||||
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
|
||||
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
|
||||
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);
|
||||
@@ -727,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)
|
||||
{
|
||||
@@ -746,9 +930,40 @@ 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;
|
||||
case areaScaleControl:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE)
|
||||
if(const auto area=optionsScaleArea(draft->page,draft->section))
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETCURSEL,0,0);
|
||||
if(row>=0)
|
||||
{
|
||||
const auto percent=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETITEMDATA,row,0);
|
||||
if(percent>=ks::files::minAppearanceScale && percent<=ks::files::maxAppearanceScale)
|
||||
draft->scales[ks::files::appearanceIndex(*area)]=static_cast<unsigned>(percent);
|
||||
}
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
case systemLightChoice: case systemDarkChoice:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE)
|
||||
{
|
||||
wchar_t name[ks::files::maxTextPaletteName+1]{};
|
||||
GetDlgItemTextW(dialog,LOWORD(wp),name,std::size(name));
|
||||
if(ks::files::namedTextPalette(draft->text,name)) draft->text.systemThemes[LOWORD(wp)==systemDarkChoice]=name;
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
case 279:
|
||||
if(draft->page==PanelColors && draft->section>=0 && draft->section<ColorCount)
|
||||
{
|
||||
@@ -856,14 +1071,17 @@ 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;
|
||||
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==SystemThemes)))
|
||||
draft->text.systemThemes=ks::files::TextSettings{}.systemThemes;
|
||||
if(draft->page==allOptions || draft->page==CompareFiles)
|
||||
{
|
||||
draft->comparison=ComparisonAppearance{};
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,defaultComparisonShortcut,0);
|
||||
}
|
||||
if(draft->page==allOptions || draft->page==CommandLine)
|
||||
{
|
||||
setOptionHistoryKeys(dialog,defaultHistoryKeys);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,BST_UNCHECKED);
|
||||
CheckDlgButton(dialog,optionsRemoteHibernate,BST_UNCHECKED);
|
||||
CheckDlgButton(dialog,optionsRemoteUpdate,BST_UNCHECKED);
|
||||
@@ -878,13 +1096,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(draft->page==allOptions || (draft->page==PanelColors &&
|
||||
(draft->section<0 || draft->section==fileStyleSection)))
|
||||
draft->styles=defaultFileStyles;
|
||||
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=DialogFrame))
|
||||
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==Font)))
|
||||
{
|
||||
draft->font=defaultFilesFont();
|
||||
draft->points=defaultFontPoints;
|
||||
}
|
||||
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font))
|
||||
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==DialogFrame)))
|
||||
draft->framePadding=defaultDialogFramePadding;
|
||||
if(draft->page==allOptions || (draft->page==TextViewer && draft->section!=markdownSection))
|
||||
CheckDlgButton(dialog,restoreDocumentsControl,BST_UNCHECKED);
|
||||
if(draft->page==allOptions || textOptionsPage(draft->page))
|
||||
for(int page=TextViewer;page<=TextEditor;++page)
|
||||
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
|
||||
@@ -909,25 +1129,20 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
case 201:
|
||||
case 202: case 203: case 204: case 205: case 206: case 207: case 208:
|
||||
case 273: case 274: case rightClickMarksControl: case driveButtonsControl: case compactLayoutControl:
|
||||
case restoreDocumentsControl:
|
||||
case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case 321: case 323: case comparisonShortcutControl:
|
||||
case 321: case comparisonKeySchemesButton:
|
||||
editFilesKeySchemes(dialog,LOWORD(wp)==321?FilesKey::Previous:FilesKey::Compare,&draft->keySettings);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case optionsImport: case optionsExport:
|
||||
transferFilesOptions(dialog,*draft,LOWORD(wp)==optionsImport);
|
||||
return TRUE;
|
||||
case optionsApply:
|
||||
case IDOK:
|
||||
{
|
||||
const auto compareShortcut=static_cast<WORD>(
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0));
|
||||
if(!validComparisonShortcut(compareShortcut))
|
||||
{
|
||||
showFilesNotice(dialog,L"Choose Shift or Ctrl+Shift with a function key. Shift+F4 and Shift+F8 are reserved.",
|
||||
optionsTitles[CompareFiles]);
|
||||
if(IsWindowVisible(GetDlgItem(dialog,comparisonShortcutControl)))
|
||||
SetFocus(GetDlgItem(dialog,comparisonShortcutControl));
|
||||
return TRUE;
|
||||
}
|
||||
if(draft->markdownError)
|
||||
{
|
||||
if(!draft->markdownNode) SetDlgItemTextW(dialog,optionsSearch,L"");
|
||||
@@ -955,6 +1170,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
const auto &base=draft->baseline;
|
||||
const bool keysChanged=draft->keySettings!=base.keySettings;
|
||||
loadFilesKeySettings();
|
||||
if(keysChanged && filesKeySettings!=base.keySettings && filesKeySettings!=draft->keySettings)
|
||||
{
|
||||
showFilesNotice(dialog,L"Keyboard schemes changed in another window. Reopen Options before editing them again.",
|
||||
L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
const auto storedComparison=readComparisonAppearance();
|
||||
const bool comparisonChanged=draft->comparison!=base.comparison;
|
||||
if(comparisonChanged && storedComparison!=base.comparison && storedComparison!=draft->comparison)
|
||||
@@ -964,7 +1187,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
const bool textChanged=draft->text!=base.text;
|
||||
auto textSettings=ks::files::loadTextPreferences();
|
||||
const auto storedText=ks::files::loadTextPreferences();
|
||||
auto textSettings=storedText;
|
||||
if(draft->text.markdown!=base.text.markdown)
|
||||
{
|
||||
if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown)
|
||||
@@ -996,14 +1220,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
textSettings.schemes=draft->text.schemes;
|
||||
}
|
||||
auto keys=optionHistoryKeys(dialog);
|
||||
loadCommandHistoryKeys();
|
||||
for(size_t i=0;i<keys.size();++i)
|
||||
if(keys[i]==base.keys[i]) keys[i]=commandHistoryKeys[i];
|
||||
if(!validHistoryKeys(keys))
|
||||
if(draft->text.systemThemes!=base.text.systemThemes)
|
||||
{
|
||||
showFilesNotice(dialog,L"Choose distinct shortcuts using Ctrl or Alt that are free in Files.",L"Command history");
|
||||
return TRUE;
|
||||
if(textSettings.systemThemes!=base.text.systemThemes && textSettings.systemThemes!=draft->text.systemThemes)
|
||||
{
|
||||
showFilesNotice(dialog,L"System theme choices changed in another window. Reopen Options before editing them again.",
|
||||
L"System themes");
|
||||
return TRUE;
|
||||
}
|
||||
textSettings.systemThemes=draft->text.systemThemes;
|
||||
}
|
||||
const bool stylesChanged=draft->styles!=base.styles;
|
||||
loadFileStyles();
|
||||
@@ -1045,15 +1270,22 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if(keysChanged && !writeFilesJsonPreference(filesKeySchemePreference,serializeFilesKeySettings(draft->keySettings)))
|
||||
{
|
||||
if(textChanged)
|
||||
try {ks::files::saveTextPreferences(storedText);}
|
||||
catch(const std::exception &) {setStatus(L"Could not restore earlier text settings.",true);}
|
||||
if(comparisonChanged) saveComparisonAppearance(storedComparison);
|
||||
if(fontChanged) applyFont(owner,base.font,base.points);
|
||||
if(stylesChanged) saveFileStyles(fileStyles);
|
||||
showFilesNotice(dialog,L"Could not save the keyboard schemes.",L"Keyboard shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial)
|
||||
{
|
||||
if(value!=initial) savePreference(name,value);
|
||||
};
|
||||
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
|
||||
const auto inputKeys=optionHistoryKeys(dialog);
|
||||
saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]);
|
||||
saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]);
|
||||
saveChanged(comparisonShortcutKey,compareShortcut,base.compareShortcut);
|
||||
saveChanged(ks::lan::remoteTerminalPreference,checked(optionsRemoteTerminal),base.remoteTerminal);
|
||||
saveChanged(ks::lan::remoteHibernatePreference,checked(optionsRemoteHibernate),base.remoteHibernate);
|
||||
saveChanged(ks::lan::remoteUpdatePreference,checked(optionsRemoteUpdate),base.remoteUpdate);
|
||||
@@ -1064,6 +1296,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
saveChanged(rightClickMarksKey,checked(rightClickMarksControl),base.mouseMarks);
|
||||
saveChanged(driveButtonsKey,checked(driveButtonsControl),base.drives);
|
||||
saveChanged(compactLayoutKey,checked(compactLayoutControl),base.compact);
|
||||
saveChanged(restoreDocumentsKey,checked(restoreDocumentsControl),base.restoreLocal);
|
||||
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
const auto initialFields=fields;
|
||||
for(int i=0;i<4;++i)
|
||||
@@ -1077,6 +1310,8 @@ 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)
|
||||
{
|
||||
savePreference(L"FontPoints",fontPoints);
|
||||
@@ -1087,14 +1322,20 @@ 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;
|
||||
draft->scales=draft->baseline.scales;
|
||||
showMarkdownOptions(dialog,draft->text.markdown);
|
||||
populateTextSchemes(dialog,draft->text);
|
||||
draft->font=displayFont;
|
||||
@@ -1109,16 +1350,16 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
|
||||
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
|
||||
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
|
||||
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
|
||||
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);
|
||||
@@ -1130,12 +1371,13 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void runOptions(HWND owner,int page)
|
||||
void runOptions(HWND owner,int page,int section=0,bool restoreLocation=true)
|
||||
{
|
||||
loadFilesKeySettings();
|
||||
OptionsDraft draft;
|
||||
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
|
||||
const DWORD initial=static_cast<DWORD>((page<<8)|1);
|
||||
const auto saved=preference(optionsLocationKey,initial);
|
||||
const DWORD initial=static_cast<DWORD>((page<<8)|(section+1));
|
||||
const auto saved=restoreLocation?preference(optionsLocationKey,initial):initial;
|
||||
draft.location=(saved>>8)<=CompareFiles?saved:initial;
|
||||
draft.page=static_cast<int>(draft.location>>8);
|
||||
draft.section=static_cast<int>(draft.location&255)-1;
|
||||
@@ -1152,7 +1394,10 @@ void editOptions(HWND owner)
|
||||
SetFocus(panels[active].list);
|
||||
}
|
||||
|
||||
void editTextOptions(HWND owner,bool edit)
|
||||
void editFilesAppearance(HWND owner,AppearanceArea area)
|
||||
{
|
||||
runOptions(owner,edit?TextEditor:TextViewer);
|
||||
constexpr int pages[]{Appearance,TextViewer,TextEditor,TextViewer,CommandLine,CompareFiles};
|
||||
constexpr int sections[]{Font,0,0,markdownSection,terminalScaleSection,0};
|
||||
const auto index=ks::files::appearanceIndex(area);
|
||||
runOptions(owner,pages[index],sections[index],false);
|
||||
}
|
||||
@@ -7,7 +7,8 @@ void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDra
|
||||
const auto dpi=GetDpiForWindow(item.hwndItem);
|
||||
const auto px=[&](int value){return MulDiv(value,dpi,96);};
|
||||
auto font=draft.font;
|
||||
font.lfHeight=-MulDiv(draft.points,dpi,720);
|
||||
const auto panelScale=draft.scales[ks::files::appearanceIndex(AppearanceArea::panels)];
|
||||
font.lfHeight=-MulDiv(ks::files::scaledAppearanceSize(draft.points,panelScale),dpi,720);
|
||||
font.lfWidth=0;
|
||||
const auto previewFont=CreateFontIndirectW(&font);
|
||||
SelectObject(dc,previewFont?previewFont:mono);
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
constexpr struct
|
||||
{
|
||||
const char *id;
|
||||
const wchar_t *label;
|
||||
int control;
|
||||
} filesTransferGroups[]{
|
||||
{"colors",L"&Colors and file styles",621},
|
||||
{"panels",L"&Panel modes and layout",622},
|
||||
{"keys",L"&Keyboard schemes",623},
|
||||
};
|
||||
|
||||
constexpr struct
|
||||
{
|
||||
const char *id;
|
||||
int control;
|
||||
bool OptionsBaseline::*value;
|
||||
} transferablePanelChecks[]{
|
||||
{"alignFileExtensions",202,&OptionsBaseline::extensions},
|
||||
{"alignFolderExtensions",204,&OptionsBaseline::folders},
|
||||
{"showDetails",203,&OptionsBaseline::details},
|
||||
{"rightClickMarks",rightClickMarksControl,&OptionsBaseline::mouseMarks},
|
||||
{"driveButtons",driveButtonsControl,&OptionsBaseline::drives},
|
||||
{"compactLayout",compactLayoutControl,&OptionsBaseline::compact},
|
||||
};
|
||||
|
||||
struct FilesTransferDraft
|
||||
{
|
||||
bool importing{};
|
||||
Json groups=Json::object();
|
||||
std::array<bool,std::size(filesTransferGroups)> chosen{};
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK filesTransferDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &draft=*reinterpret_cast<FilesTransferDraft*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
SetWindowTextW(dialog,draft.importing?L"Import Files settings":L"Export Files settings");
|
||||
SetDlgItemTextW(dialog,624,draft.importing?
|
||||
L"Choose groups to load into Options. Apply saves the changes.":
|
||||
L"Choose groups to export from your saved Files settings.");
|
||||
SetDlgItemTextW(dialog,IDOK,draft.importing?L"&Load":L"&Export");
|
||||
for(const auto &group:filesTransferGroups)
|
||||
{
|
||||
const bool available=draft.groups.contains(group.id);
|
||||
const auto control=GetDlgItem(dialog,group.control);
|
||||
SetWindowTextW(control,group.label);
|
||||
ShowWindow(control,available?SW_SHOW:SW_HIDE);
|
||||
CheckDlgButton(dialog,group.control,available?BST_CHECKED:BST_UNCHECKED);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
auto &draft=*reinterpret_cast<FilesTransferDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
for(size_t i=0;i<draft.chosen.size();++i)
|
||||
{
|
||||
const auto &group=filesTransferGroups[i];
|
||||
draft.chosen[i]=draft.groups.contains(group.id) && IsDlgButtonChecked(dialog,group.control)==BST_CHECKED;
|
||||
}
|
||||
const bool any=std::ranges::any_of(draft.chosen,[](bool chosen){return chosen;});
|
||||
if(LOWORD(wp)==IDOK && any) FilesModalDialog::finish(dialog,IDOK);
|
||||
else EnableWindow(GetDlgItem(dialog,IDOK),any);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
fs::path chooseFilesTransferPath(HWND owner,bool importing)
|
||||
{
|
||||
std::array<wchar_t,32768> file{};
|
||||
if(!importing) wcscpy_s(file.data(),file.size(),L"KSwitcher.Files.settings.json");
|
||||
OPENFILENAMEW pick{sizeof(pick)};
|
||||
pick.hwndOwner=owner;
|
||||
pick.lpstrTitle=importing?L"Open Files settings JSON":L"Save Files settings JSON";
|
||||
pick.lpstrFilter=L"JSON files (*.json)\0*.json\0All files (*.*)\0*.*\0";
|
||||
pick.lpstrFile=file.data();
|
||||
pick.nMaxFile=static_cast<DWORD>(file.size());
|
||||
pick.lpstrDefExt=L"json";
|
||||
pick.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|
|
||||
(importing?OFN_FILEMUSTEXIST:OFN_OVERWRITEPROMPT);
|
||||
if(importing?GetOpenFileNameW(&pick):GetSaveFileNameW(&pick)) return file.data();
|
||||
if(CommDlgExtendedError()) throw std::runtime_error("Could not open the file picker.");
|
||||
return {};
|
||||
}
|
||||
|
||||
Json exportFilesOptionGroups(const OptionsBaseline &saved)
|
||||
{
|
||||
Json colors{{"panels",saved.palette},{"comparison",saved.comparison.palette},{"fileStyles",serializeFileStyles(saved.styles)}};
|
||||
Json panels{{"leftMode",static_cast<DWORD>(saved.modes[0])},
|
||||
{"rightMode",static_cast<DWORD>(saved.modes[1])},{"sizeWidth",saved.width},{"statusFields",saved.fields}};
|
||||
for(const auto &check:transferablePanelChecks) panels[check.id]=saved.*check.value;
|
||||
return {{"colors",std::move(colors)},{"panels",std::move(panels)},{"keys",serializeFilesKeySettings(saved.keySettings)}};
|
||||
}
|
||||
|
||||
template<typename Palette>
|
||||
void importFilesColors(const Json &value,Palette &palette)
|
||||
{
|
||||
if(!value.is_array()) throw std::runtime_error("Expected an array of colors.");
|
||||
for(size_t i=0;i<std::min(value.size(),palette.size());++i)
|
||||
{
|
||||
if(!value[i].is_number_unsigned() || value[i]>0xffffff)
|
||||
throw std::runtime_error("A color is outside the RGB range.");
|
||||
palette[i]=value[i].template get<COLORREF>();
|
||||
}
|
||||
}
|
||||
|
||||
DWORD importFilesOptionNumber(const Json &value,DWORD minimum,DWORD maximum)
|
||||
{
|
||||
if(!value.is_number_unsigned() || value<minimum || value>maximum)
|
||||
throw std::runtime_error("A panel setting is outside its supported range.");
|
||||
return value.get<DWORD>();
|
||||
}
|
||||
|
||||
std::optional<FilesKeySettings> mergeImportedFilesKeySchemes(HWND owner,const FilesKeySettings &local,const Json &value)
|
||||
{
|
||||
const auto imported=parseFilesKeySettings(value);
|
||||
if(!imported) throw std::runtime_error("The keyboard schemes contain invalid or conflicting bindings.");
|
||||
auto result=local;
|
||||
size_t replacements{};
|
||||
for(size_t i=0;i<imported->schemes.size();++i)
|
||||
{
|
||||
const auto &scheme=imported->schemes[i];
|
||||
const auto existing=std::ranges::find_if(result.schemes,[&](const auto &candidate)
|
||||
{ return sameFilesKeySchemeName(candidate.name,scheme.name); });
|
||||
const auto position=static_cast<size_t>(existing-result.schemes.begin());
|
||||
if(i==imported->active) result.active=position;
|
||||
if(existing==result.schemes.end()) result.schemes.push_back(scheme);
|
||||
else if(existing->keys!=scheme.keys)
|
||||
{
|
||||
++replacements;
|
||||
auto name=existing->name;
|
||||
*existing=scheme;
|
||||
existing->name=std::move(name);
|
||||
}
|
||||
}
|
||||
if(result.schemes.size()>filesKeySchemeLimit)
|
||||
throw std::runtime_error("The imported keyboard schemes exceed the number Files can store.");
|
||||
if(replacements)
|
||||
{
|
||||
const auto prompt=L"Replace "+std::to_wstring(replacements)+
|
||||
(replacements==1?L" keyboard scheme with the same name?":L" keyboard schemes with the same names?");
|
||||
if(showFilesNotice(owner,prompt.c_str(),L"Import Files settings",
|
||||
{.confirm=true,.accept=L"&Replace"})!=IDYES) return {};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void stageImportedFilesOptions(HWND dialog,OptionsDraft &draft,const Json &groups)
|
||||
{
|
||||
auto palette=draft.palette;
|
||||
auto comparison=draft.comparison.palette;
|
||||
auto styles=draft.styles;
|
||||
auto options=OptionsBaseline{};
|
||||
options.modes={panelModeOption(dialog,0),panelModeOption(dialog,1)};
|
||||
options.width=GetDlgItemInt(dialog,201,nullptr,FALSE);
|
||||
options.fields=0;
|
||||
for(int i=0;i<4;++i)
|
||||
if(IsDlgButtonChecked(dialog,205+i)==BST_CHECKED) options.fields|=1u<<i;
|
||||
for(const auto &check:transferablePanelChecks)
|
||||
options.*check.value=IsDlgButtonChecked(dialog,check.control)==BST_CHECKED;
|
||||
|
||||
const auto colorGroup=groups.find("colors");
|
||||
if(colorGroup!=groups.end())
|
||||
{
|
||||
if(!colorGroup->is_object()) throw std::runtime_error("Invalid colors group.");
|
||||
if(colorGroup->contains("panels")) importFilesColors(colorGroup->at("panels"),palette);
|
||||
if(colorGroup->contains("comparison")) importFilesColors(colorGroup->at("comparison"),comparison);
|
||||
if(colorGroup->contains("fileStyles"))
|
||||
{
|
||||
auto parsed=parseFileStyles(colorGroup->at("fileStyles"));
|
||||
if(!parsed) throw std::runtime_error("Invalid file styles.");
|
||||
styles=std::move(*parsed);
|
||||
}
|
||||
}
|
||||
const auto panelGroup=groups.find("panels");
|
||||
if(panelGroup!=groups.end())
|
||||
{
|
||||
if(!panelGroup->is_object()) throw std::runtime_error("Invalid panel modes and layout group.");
|
||||
for(const auto &check:transferablePanelChecks)
|
||||
if(panelGroup->contains(check.id)) options.*check.value=panelGroup->at(check.id).get<bool>();
|
||||
constexpr const char *modeKeys[]{"leftMode","rightMode"};
|
||||
for(size_t i=0;i<options.modes.size();++i)
|
||||
if(panelGroup->contains(modeKeys[i]))
|
||||
options.modes[i]=static_cast<PanelMode>(importFilesOptionNumber(
|
||||
panelGroup->at(modeKeys[i]),0,std::size(panelModeNames)-1));
|
||||
if(panelGroup->contains("sizeWidth"))
|
||||
options.width=importFilesOptionNumber(panelGroup->at("sizeWidth"),6,16);
|
||||
if(panelGroup->contains("statusFields"))
|
||||
options.fields=importFilesOptionNumber(panelGroup->at("statusFields"),0,15);
|
||||
}
|
||||
if(groups.contains("keys"))
|
||||
{
|
||||
auto keys=mergeImportedFilesKeySchemes(dialog,draft.keySettings,groups.at("keys"));
|
||||
if(!keys) return;
|
||||
draft.keySettings=std::move(*keys);
|
||||
}
|
||||
if(colorGroup!=groups.end())
|
||||
{
|
||||
draft.palette=palette;
|
||||
draft.comparison.palette=comparison;
|
||||
draft.styles=std::move(styles);
|
||||
}
|
||||
if(panelGroup!=groups.end())
|
||||
{
|
||||
if(panelGroup->contains("sizeWidth")) SetDlgItemInt(dialog,201,options.width,FALSE);
|
||||
for(int index=0;index<2;++index)
|
||||
SendDlgItemMessageW(dialog,273+index,CB_SETCURSEL,static_cast<WPARAM>(options.modes[index]),0);
|
||||
for(const auto &check:transferablePanelChecks)
|
||||
CheckDlgButton(dialog,check.control,options.*check.value?BST_CHECKED:BST_UNCHECKED);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,options.fields&(1u<<i)?BST_CHECKED:BST_UNCHECKED);
|
||||
}
|
||||
if(draft.page==PanelColors && draft.section==fileStyleSection) updateFileStyleEditor(dialog,draft,true);
|
||||
showOptionsPage(dialog,draft,draft.page,draft.section);
|
||||
updateOptionsApply(dialog,draft);
|
||||
}
|
||||
|
||||
void transferFilesOptions(HWND dialog,OptionsDraft &options,bool importing)
|
||||
{
|
||||
try
|
||||
{
|
||||
FilesTransferDraft transfer{.importing=importing};
|
||||
if(importing)
|
||||
{
|
||||
const auto path=chooseFilesTransferPath(dialog,true);
|
||||
if(path.empty()) return;
|
||||
const auto data=ks::readFile(path,maxFilesJsonBytes);
|
||||
const auto document=Json::parse(data,[](int depth,Json::parse_event_t,Json &)
|
||||
{
|
||||
if(depth>32) throw std::runtime_error("The JSON contains too many nested levels.");
|
||||
return true;
|
||||
});
|
||||
if(document.value("format",std::string{})!="kswitcher-files-settings" || document.at("version")!=1)
|
||||
throw std::runtime_error("This Files settings format or version is unsupported.");
|
||||
const auto &groups=document.at("groups");
|
||||
if(!groups.is_object()) throw std::runtime_error("The document does not contain settings groups.");
|
||||
for(const auto &group:filesTransferGroups)
|
||||
if(groups.contains(group.id)) transfer.groups[group.id]=groups.at(group.id);
|
||||
if(transfer.groups.empty()) throw std::runtime_error("The file does not contain any supported settings groups.");
|
||||
}
|
||||
else transfer.groups=exportFilesOptionGroups(options.baseline);
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(617),dialog,filesTransferDialog,
|
||||
reinterpret_cast<LPARAM>(&transfer))!=IDOK) return;
|
||||
for(size_t i=0;i<transfer.chosen.size();++i)
|
||||
if(!transfer.chosen[i]) transfer.groups.erase(filesTransferGroups[i].id);
|
||||
if(importing) stageImportedFilesOptions(dialog,options,transfer.groups);
|
||||
else
|
||||
{
|
||||
const auto path=chooseFilesTransferPath(dialog,false);
|
||||
if(path.empty()) return;
|
||||
const auto output=Json{{"format","kswitcher-files-settings"},{"version",1},
|
||||
{"groups",std::move(transfer.groups)}}.dump(2)+"\n";
|
||||
const auto temporary=ks::files::temporaryPath(path.parent_path());
|
||||
const bool replace=GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES;
|
||||
ks::atomicWrite(temporary,ks::Bytes(output.begin(),output.end()));
|
||||
if(!MoveFileExW(temporary.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH|(replace?MOVEFILE_REPLACE_EXISTING:0)))
|
||||
{
|
||||
DeleteFileW(temporary.c_str());
|
||||
throw std::runtime_error("Could not publish the settings file.");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(const Json::exception &)
|
||||
{
|
||||
showFilesNotice(dialog,L"The JSON is damaged or contains an invalid value.",L"Files settings");
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
const auto message=ks::wide(error.what());
|
||||
showFilesNotice(dialog,message.c_str(),L"Files settings");
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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);
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
+31
-34
@@ -48,60 +48,54 @@ bool sameFileExtension(std::wstring_view left,std::wstring_view right)
|
||||
right.data(),static_cast<int>(right.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
void loadFileStyles()
|
||||
std::optional<std::vector<FileStyle>> parseFileStyles(const Json &rows)
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>256*1024) return;
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return;
|
||||
try
|
||||
{
|
||||
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
|
||||
if(!rows.is_array() || rows.size()>64) return;
|
||||
if(!rows.is_array() || rows.size()>64) return {};
|
||||
std::vector<FileStyle> parsed;
|
||||
for(const auto &row:rows)
|
||||
{
|
||||
FileStyle style{ks::wide(row.at("extension").get<std::string>())};
|
||||
if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return;
|
||||
if(std::any_of(parsed.begin(),parsed.end(),[&](const auto &existing){return existing.extension==style.extension;}))
|
||||
return;
|
||||
const auto color=[&](const char *key)->std::optional<COLORREF>
|
||||
if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return {};
|
||||
if(std::ranges::any_of(parsed,[&](const auto &existing){return existing.extension==style.extension;}))
|
||||
return {};
|
||||
const auto color=[](const Json &entry,const char *key)->std::optional<COLORREF>
|
||||
{
|
||||
if(!row.contains(key)) return {};
|
||||
const auto value=row.at(key).get<DWORD>();
|
||||
if(value>0xffffff) throw std::runtime_error("Invalid file style color");
|
||||
return value;
|
||||
if(!entry.contains(key)) return {};
|
||||
const auto &value=entry.at(key);
|
||||
if(!value.is_number_unsigned() || value>0xffffff) throw std::runtime_error("Invalid file style color");
|
||||
return value.get<DWORD>();
|
||||
};
|
||||
style.foreground=color("foreground");
|
||||
style.background=color("background");
|
||||
style.foreground=color(row,"foreground");
|
||||
style.background=color(row,"background");
|
||||
style.underline=row.value("underline",false);
|
||||
style.strikeout=row.value("strikeout",false);
|
||||
if(row.contains("states"))
|
||||
{
|
||||
const auto &states=row.at("states");
|
||||
if(!states.is_array() || states.size()!=style.states.size()) return;
|
||||
if(!states.is_array() || states.size()!=style.states.size()) return {};
|
||||
for(size_t i=0;i<style.states.size();++i)
|
||||
{
|
||||
const auto read=[&](const char *key)->std::optional<COLORREF>
|
||||
{
|
||||
if(!states[i].contains(key)) return {};
|
||||
const auto value=states[i].at(key).get<DWORD>();
|
||||
if(value>0xffffff) throw std::runtime_error("Invalid state color");
|
||||
return value;
|
||||
};
|
||||
style.states[i]={read("foreground"),read("background")};
|
||||
if(!states[i].is_object()) return {};
|
||||
style.states[i]={color(states[i],"foreground"),color(states[i],"background")};
|
||||
}
|
||||
}
|
||||
parsed.push_back(std::move(style));
|
||||
}
|
||||
fileStyles=std::move(parsed);
|
||||
return parsed;
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
catch(const std::exception &) {return {};}
|
||||
}
|
||||
|
||||
bool saveFileStyles(const std::vector<FileStyle> &styles)
|
||||
void loadFileStyles()
|
||||
{
|
||||
fileStyles=defaultFileStyles;
|
||||
if(const auto rows=readFilesJsonPreference(fileStyleKey))
|
||||
if(auto parsed=parseFileStyles(*rows)) fileStyles=std::move(*parsed);
|
||||
}
|
||||
|
||||
Json serializeFileStyles(const std::vector<FileStyle> &styles)
|
||||
{
|
||||
auto rows=Json::array();
|
||||
for(const auto &style:styles)
|
||||
@@ -119,9 +113,12 @@ bool saveFileStyles(const std::vector<FileStyle> &styles)
|
||||
}
|
||||
rows.push_back(std::move(row));
|
||||
}
|
||||
const auto data=rows.dump();
|
||||
return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
return rows;
|
||||
}
|
||||
|
||||
bool saveFileStyles(const std::vector<FileStyle> &styles)
|
||||
{
|
||||
return writeFilesJsonPreference(fileStyleKey,serializeFileStyles(styles));
|
||||
}
|
||||
|
||||
struct FileRowStyle
|
||||
|
||||
+71
-25
@@ -42,7 +42,7 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
|
||||
HANDLE trackReplacement(const std::filesystem::path &path)
|
||||
{
|
||||
// A metadata-only handle survives the rename without blocking ReplaceFile.
|
||||
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
const auto handle=CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
|
||||
return handle;
|
||||
@@ -90,15 +90,6 @@ bool sameFile(HANDLE a, HANDLE b)
|
||||
return sameFileIdentity(first,second);
|
||||
}
|
||||
|
||||
std::filesystem::path temporaryPath(const std::filesystem::path &directory)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if (FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id, name, 40))
|
||||
throw std::runtime_error("Cannot create a temporary file name.");
|
||||
return directory / (std::wstring(L".kswitcher-") + name + L".tmp");
|
||||
}
|
||||
|
||||
std::filesystem::path createTemporary(const std::filesystem::path &directory, File &file, DWORD flags)
|
||||
{
|
||||
auto path = temporaryPath(directory);
|
||||
@@ -107,6 +98,11 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
|
||||
return path;
|
||||
}
|
||||
|
||||
void createEditorSnapshot(File &file)
|
||||
{
|
||||
createTemporary(std::filesystem::temp_directory_path(),file,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE);
|
||||
}
|
||||
|
||||
bool isUtf16(TextEncoding encoding)
|
||||
{
|
||||
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
|
||||
@@ -133,6 +129,18 @@ std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
|
||||
return units;
|
||||
}
|
||||
|
||||
std::string encodeUtf8(std::wstring_view units)
|
||||
{
|
||||
if(units.empty()) return {};
|
||||
const auto length=static_cast<int>(units.size());
|
||||
const int required=WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,units.data(),length,nullptr,0,nullptr,nullptr);
|
||||
if(!required) fail("Decode UTF-16");
|
||||
std::string result(required,'\0');
|
||||
if(!WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,units.data(),length,result.data(),required,nullptr,nullptr))
|
||||
fail("Decode UTF-16");
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string encode(std::string_view utf8,TextEncoding encoding)
|
||||
{
|
||||
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
|
||||
@@ -179,8 +187,8 @@ std::string convertLineEndings(std::string_view text,TextLineEnding ending)
|
||||
}
|
||||
}
|
||||
|
||||
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
|
||||
: path_(std::move(path)), editable_(editable)
|
||||
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding,bool snapshotEdits)
|
||||
: path_(std::move(path)), editable_(editable),snapshotEdits_(snapshotEdits && editable)
|
||||
{
|
||||
if(path_.empty())
|
||||
{
|
||||
@@ -210,7 +218,20 @@ TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding
|
||||
encoding_=encoding;
|
||||
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
|
||||
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
|
||||
source_ = source.release();
|
||||
if(snapshotEdits_)
|
||||
{
|
||||
version_=fileVersion(source.handle);
|
||||
File snapshot;
|
||||
createEditorSnapshot(snapshot);
|
||||
for(uint64_t offset=0;offset<size_;)
|
||||
{
|
||||
const auto block=read(source.handle,offset,static_cast<size_t>(std::min(pageBytes,size_-offset)));
|
||||
write(snapshot.handle,block);
|
||||
offset+=block.size();
|
||||
}
|
||||
source_=snapshot.release();
|
||||
}
|
||||
else source_ = source.release();
|
||||
}
|
||||
|
||||
TextDocument::~TextDocument()
|
||||
@@ -289,13 +310,7 @@ std::string TextDocument::decode(std::string bytes) const
|
||||
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
|
||||
}
|
||||
}
|
||||
const auto length = static_cast<int>(units.size());
|
||||
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
|
||||
if (!required) fail("Decode UTF-16");
|
||||
std::string result(required, '\0');
|
||||
if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, result.data(), required, nullptr, nullptr))
|
||||
fail("Decode UTF-16");
|
||||
return result;
|
||||
return encodeUtf8(units);
|
||||
}
|
||||
|
||||
std::string TextDocument::readPage(uint64_t page) const
|
||||
@@ -377,6 +392,15 @@ std::string formatHexAddress(uint64_t offset)
|
||||
return address;
|
||||
}
|
||||
|
||||
std::string formatBinarySymbols(std::string_view bytes)
|
||||
{
|
||||
if(bytes.empty()) return {};
|
||||
auto symbols=decodeMultibyte(bytes,437,0);
|
||||
for(size_t i=0;i<bytes.size();++i)
|
||||
if(const auto marker=binarySymbolMarker(static_cast<unsigned char>(bytes[i]))) symbols[i]=marker;
|
||||
return encodeUtf8(symbols);
|
||||
}
|
||||
|
||||
std::string formatHexPage(std::string_view bytes,uint64_t offset)
|
||||
{
|
||||
constexpr char digits[]="0123456789ABCDEF";
|
||||
@@ -461,13 +485,26 @@ void TextDocument::stage(uint64_t page, std::string_view utf8)
|
||||
bool TextDocument::save()
|
||||
{
|
||||
if (!modified()) return true;
|
||||
const auto verify=[&](HANDLE current) {
|
||||
if(version_ && *version_!=fileVersion(current))
|
||||
throw std::runtime_error("The file changed outside Files. Your editor buffer was kept.");
|
||||
if(!version_ && !sameFile(source_,current))
|
||||
throw std::runtime_error("The file was replaced outside KSwitcher.");
|
||||
};
|
||||
if(version_)
|
||||
{
|
||||
File current{openSource(path_,true)};
|
||||
verify(current.handle);
|
||||
}
|
||||
PendingSave pending;
|
||||
File output;
|
||||
File output,snapshot;
|
||||
if(snapshotEdits_) createEditorSnapshot(snapshot);
|
||||
pending.path = createTemporary(path_.parent_path(), output, FILE_ATTRIBUTE_NORMAL);
|
||||
|
||||
uint64_t written{};
|
||||
const auto append = [&](std::string_view bytes) {
|
||||
write(output.handle, bytes);
|
||||
if(snapshotEdits_) write(snapshot.handle,bytes);
|
||||
written += bytes.size();
|
||||
};
|
||||
const auto copyUntil = [&](uint64_t &offset, uint64_t end) {
|
||||
@@ -491,7 +528,7 @@ bool TextDocument::save()
|
||||
|
||||
File replacement{trackReplacement(pending.path)};
|
||||
File current{openSource(path_, true)};
|
||||
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
|
||||
verify(current.handle);
|
||||
const auto backup = temporaryPath(path_.parent_path());
|
||||
if (const auto error=replaceFileWithBackup(path_,pending.path,backup))
|
||||
{
|
||||
@@ -499,7 +536,9 @@ bool TextDocument::save()
|
||||
fail("Replace original file");
|
||||
}
|
||||
pending.path.clear();
|
||||
const auto newSource = ReOpenFile(replacement.handle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, 0);
|
||||
if(snapshotEdits_) version_=fileVersion(replacement.handle);
|
||||
const auto newSource=snapshotEdits_?snapshot.release():
|
||||
ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
|
||||
DeleteFileW(backup.c_str());
|
||||
CloseHandle(source_);
|
||||
source_ = newSource;
|
||||
@@ -517,10 +556,16 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
|
||||
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
|
||||
const auto bom=format.bom?signature(format.encoding):std::string_view{};
|
||||
PendingSave pending;
|
||||
File output;
|
||||
File output,snapshot;
|
||||
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
|
||||
write(output.handle,bom);
|
||||
write(output.handle,bytes);
|
||||
if(snapshotEdits_)
|
||||
{
|
||||
createEditorSnapshot(snapshot);
|
||||
write(snapshot.handle,bom);
|
||||
write(snapshot.handle,bytes);
|
||||
}
|
||||
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
|
||||
CloseHandle(output.release());
|
||||
File replacement{trackReplacement(pending.path)};
|
||||
@@ -533,7 +578,8 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
|
||||
changes_.clear();
|
||||
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
|
||||
spoolSize_=0;
|
||||
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
|
||||
if(snapshotEdits_) version_=fileVersion(replacement.handle);
|
||||
source_=snapshotEdits_?snapshot.release():ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
|
||||
return source_!=INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include "files_win32_replace.h"
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
@@ -17,6 +17,11 @@ enum class TextLineEnding { preserve, crlf, lf, cr };
|
||||
inline constexpr uint64_t hexPageBytes=64*1024;
|
||||
std::string formatHexAddress(uint64_t offset);
|
||||
std::string formatHexPage(std::string_view bytes,uint64_t offset);
|
||||
constexpr wchar_t binarySymbolMarker(unsigned char byte)
|
||||
{
|
||||
return byte<0x20 || byte==0x7f || byte==0xff || byte=='\\' ? static_cast<wchar_t>(0xe000+byte) : 0;
|
||||
}
|
||||
std::string formatBinarySymbols(std::string_view bytes);
|
||||
|
||||
struct TextSaveFormat
|
||||
{
|
||||
@@ -38,7 +43,7 @@ public:
|
||||
static constexpr size_t editLimit = 8 * pageBytes;
|
||||
|
||||
explicit TextDocument(std::filesystem::path path, bool editable = true,
|
||||
TextEncoding encoding=TextEncoding::automatic);
|
||||
TextEncoding encoding=TextEncoding::automatic,bool snapshotEdits=false);
|
||||
~TextDocument();
|
||||
TextDocument(const TextDocument &) = delete;
|
||||
TextDocument &operator=(const TextDocument &) = delete;
|
||||
@@ -58,6 +63,7 @@ public:
|
||||
bool saveNew(std::filesystem::path path, TextSaveFormat format);
|
||||
const wchar_t *encodingName() const;
|
||||
TextEncoding encoding() const { return encoding_; }
|
||||
const std::optional<LocalFileVersion> &expectedVersion() const {return version_;}
|
||||
|
||||
private:
|
||||
struct Change { uint64_t offset; size_t size; };
|
||||
@@ -68,7 +74,8 @@ private:
|
||||
uint64_t size_{}, spoolSize_{};
|
||||
size_t bom_{};
|
||||
TextEncoding encoding_ = TextEncoding::utf8;
|
||||
bool editable_;
|
||||
bool editable_, snapshotEdits_;
|
||||
std::optional<LocalFileVersion> version_;
|
||||
std::map<uint64_t, Change> changes_;
|
||||
|
||||
std::string decode(std::string bytes) const;
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline constexpr size_t documentColorCount = 10;
|
||||
inline constexpr wchar_t systemTextScheme[]=L"@system";
|
||||
using TextPalette = std::array<COLORREF, 14>;
|
||||
inline constexpr const wchar_t *textPaletteNames[] = {L"FAR (blue)", L"Dark", L"Light"};
|
||||
inline constexpr TextPalette textPalettes[] = {
|
||||
@@ -56,8 +59,11 @@ struct TextSettings
|
||||
TextPreferencesSet profiles;
|
||||
std::vector<NamedTextPalette> schemes;
|
||||
MarkdownPreferences markdown;
|
||||
std::array<std::wstring,2> systemThemes{textPaletteNames[2],textPaletteNames[1]};
|
||||
bool operator==(const TextSettings &) const = default;
|
||||
};
|
||||
std::optional<TextPalette> namedTextPalette(const TextSettings &settings,std::wstring_view name);
|
||||
TextPreferences resolvedTextProfile(const TextSettings &settings,bool editor);
|
||||
TextSettings loadTextPreferences();
|
||||
void saveTextPreferences(const TextSettings &settings);
|
||||
}
|
||||
+431
-67
@@ -1,4 +1,5 @@
|
||||
#include "files_text_window.h"
|
||||
#include "files_help.h"
|
||||
#include "files_image_view.h"
|
||||
#include "files_text_preferences.h"
|
||||
#include "files_menu_paint.h"
|
||||
@@ -73,6 +74,30 @@ void readTextProfile(TextPreferences &prefs, const nlohmann::json &data)
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<TextPalette> namedTextPalette(const TextSettings &settings,std::wstring_view name)
|
||||
{
|
||||
const auto matches=[&](const wchar_t *other)
|
||||
{
|
||||
return !name.empty() && CompareStringOrdinal(name.data(),static_cast<int>(name.size()),other,-1,TRUE)==CSTR_EQUAL;
|
||||
};
|
||||
for(size_t i=0;i<std::size(textPalettes);++i)
|
||||
if(matches(textPaletteNames[i])) return textPalettes[i];
|
||||
for(const auto &scheme:settings.schemes)
|
||||
if(matches(scheme.name.c_str())) return scheme.colors;
|
||||
return {};
|
||||
}
|
||||
|
||||
TextPreferences resolvedTextProfile(const TextSettings &settings,bool editor)
|
||||
{
|
||||
auto profile=settings.profiles[editor];
|
||||
if(profile.scheme==systemTextScheme)
|
||||
{
|
||||
const bool dark=windowsUsesDarkApps();
|
||||
profile.colors=namedTextPalette(settings,settings.systemThemes[dark]).value_or(textPalettes[dark?1:2]);
|
||||
}
|
||||
return profile;
|
||||
}
|
||||
|
||||
TextSettings loadTextPreferences()
|
||||
{
|
||||
TextSettings settings{};
|
||||
@@ -109,6 +134,17 @@ TextSettings loadTextPreferences()
|
||||
}
|
||||
catch (const std::exception &) {}
|
||||
}
|
||||
if(const auto system=data.find("systemThemes");system!=data.end() && system->is_object())
|
||||
{
|
||||
constexpr const char *roles[]{"light","dark"};
|
||||
for(size_t i=0;i<settings.systemThemes.size();++i)
|
||||
if(const auto name=system->find(roles[i]);name!=system->end() && name->is_string())
|
||||
{
|
||||
auto value=wide(name->get<std::string>());
|
||||
if(value.size()<=maxTextPaletteName && namedTextPalette(settings,value))
|
||||
settings.systemThemes[i]=std::move(value);
|
||||
}
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
const wchar_t *legacy[]{L"files-viewer.json", L"files-editor.json"};
|
||||
@@ -140,6 +176,7 @@ void saveTextPreferences(const TextSettings &settings)
|
||||
schemes.push_back({{"name", utf8(scheme.name)}, {"colors", scheme.colors}});
|
||||
data["markdown"]={{"width",settings.markdown.width},{"fontSize",settings.markdown.fontSize},
|
||||
{"font",utf8(settings.markdown.font)}};
|
||||
data["systemThemes"]={{"light",utf8(settings.systemThemes[0])},{"dark",utf8(settings.systemThemes[1])}};
|
||||
const auto json = data.dump(2);
|
||||
atomicWrite(dataDirectory() / L"files-text.json", Bytes(json.begin(), json.end()));
|
||||
}
|
||||
@@ -683,6 +720,19 @@ std::future<std::unique_ptr<RemoteTextFile>> fetchRemoteText(const RemoteTextSou
|
||||
return result;
|
||||
}
|
||||
|
||||
unsigned textAreaScale(TextDialogs dialogs,AppearanceArea area)
|
||||
{
|
||||
return dialogs.readScale?dialogs.readScale(area):100;
|
||||
}
|
||||
|
||||
TextWindowFont scaledDocumentFont(TextDialogs dialogs,bool editor)
|
||||
{
|
||||
auto font=dialogs.readFont();
|
||||
font.tenthsOfPoint=scaledAppearanceSize(font.tenthsOfPoint,
|
||||
textAreaScale(dialogs,editor?AppearanceArea::editor:AppearanceArea::viewer));
|
||||
return font;
|
||||
}
|
||||
|
||||
class TextWindow;
|
||||
std::map<HWND,std::shared_ptr<TextWindow>> textWindows;
|
||||
std::vector<HWND> textWindowOrder;
|
||||
@@ -771,12 +821,12 @@ public:
|
||||
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), draft(options.draft), embedded(quickView), hex(options.hex && !editable),
|
||||
initialBookmark(options.line),
|
||||
prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
prefs(resolvedTextProfile(loadTextPreferences(),editable)), filesFont(scaledDocumentFont(dialogs,editable)),
|
||||
search{dialogs}, previewFragment(fragment)
|
||||
{
|
||||
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
|
||||
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,
|
||||
hex?TextEncoding::utf8:options.encoding);
|
||||
hex?TextEncoding::utf8:options.encoding,isLocalDocumentPath(original));
|
||||
if(options.encoding!=TextEncoding::automatic)
|
||||
{
|
||||
newFormat.encoding=options.encoding;
|
||||
@@ -800,12 +850,18 @@ public:
|
||||
if(smallIcon) DestroyIcon(smallIcon);
|
||||
if(largeIcon) DestroyIcon(largeIcon);
|
||||
}
|
||||
HWND window{}, editor{};
|
||||
HWND window{}, editor{}, quickModeButton{};
|
||||
bool handleKey(const MSG &message);
|
||||
void goToFragment(std::string_view fragment);
|
||||
void previewFile(const std::filesystem::path &path);
|
||||
void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff);
|
||||
bool openBookmark(const ViewerBookmark &bookmark);
|
||||
nlohmann::json sessionState() const;
|
||||
void restoreSession(const nlohmann::json &state);
|
||||
AppearanceArea appearanceArea() const
|
||||
{
|
||||
return previewWanted?AppearanceArea::markdown:edit?AppearanceArea::editor:AppearanceArea::viewer;
|
||||
}
|
||||
std::filesystem::path original;
|
||||
const std::string peerId;
|
||||
|
||||
@@ -860,13 +916,8 @@ private:
|
||||
bool previewWanted{}, previewVisible{}, previewRetried{};
|
||||
ULONGLONG previewDeadline{};
|
||||
ULONGLONG nextFileCheck{};
|
||||
struct FileStamp
|
||||
{
|
||||
uint64_t writeTime, fileIndex, size;
|
||||
DWORD volume;
|
||||
bool operator==(const FileStamp &) const = default;
|
||||
};
|
||||
std::optional<FileStamp> previewStamp;
|
||||
std::optional<LocalFileVersion> previewStamp, observedVersion;
|
||||
bool diskChanged{};
|
||||
struct MarkdownTask
|
||||
{
|
||||
uint64_t revision;
|
||||
@@ -875,6 +926,8 @@ private:
|
||||
};
|
||||
std::string previewText;
|
||||
uint64_t previewRevision{};
|
||||
int renderedScroll{};
|
||||
std::optional<int> sessionScroll;
|
||||
std::optional<MarkdownTask> pendingTask;
|
||||
std::optional<size_t> taskOffset;
|
||||
std::string previewFragment;
|
||||
@@ -918,6 +971,7 @@ private:
|
||||
static constexpr UINT_PTR quickViewTimer = 5;
|
||||
static constexpr UINT_PTR bookmarkTimer = 6;
|
||||
static constexpr UINT_PTR savedViewerTimer = 7;
|
||||
static constexpr UINT_PTR externalChangeTimer = 8;
|
||||
struct BookmarkLocation
|
||||
{
|
||||
std::filesystem::path path;
|
||||
@@ -928,11 +982,14 @@ private:
|
||||
};
|
||||
std::future<BookmarkLocation> bookmarkTask;
|
||||
std::stop_source bookmarkStop;
|
||||
enum class QuickKind { text, html, binary };
|
||||
struct QuickDocument
|
||||
{
|
||||
std::unique_ptr<TextDocument> document;
|
||||
std::string firstPage;
|
||||
std::optional<std::string> markdown;
|
||||
std::optional<std::string> previewCode;
|
||||
QuickKind kind{};
|
||||
size_t binaryBytes{};
|
||||
};
|
||||
std::future<QuickDocument> quickLoading;
|
||||
std::filesystem::path quickPath;
|
||||
@@ -941,7 +998,13 @@ private:
|
||||
uint64_t quickRequest{}, quickReading{};
|
||||
ULONGLONG quickReadyAt{};
|
||||
std::wstring quickError;
|
||||
std::optional<std::string> quickMarkdown;
|
||||
std::optional<std::string> quickPreviewCode;
|
||||
QuickKind quickKind{};
|
||||
bool quickHtmlRendered{}, binaryRepresentations{};
|
||||
size_t quickBinaryBytes{};
|
||||
static constexpr int quickModeControl=159;
|
||||
void applySourceLayoutOptions();
|
||||
void toggleQuickHtml();
|
||||
void pollQuickView();
|
||||
static constexpr UINT trimUndo = WM_APP + 1;
|
||||
static constexpr UINT previewFailed = WM_APP + 2;
|
||||
@@ -1003,7 +1066,7 @@ private:
|
||||
void changeMode();
|
||||
ViewerPosition currentPosition() const;
|
||||
void restorePosition(const ViewerPosition &position);
|
||||
void showTextMode(const ViewerPosition &position,std::string contents);
|
||||
void showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus=true);
|
||||
void suspendEditor(std::unique_ptr<RemoteTextFile> saved={});
|
||||
void restoreEditor();
|
||||
void finishSavedViewer();
|
||||
@@ -1015,7 +1078,9 @@ private:
|
||||
void stopPreview(bool refresh=true,bool keepBrowser=false);
|
||||
void renderPreview(bool keepPosition=false);
|
||||
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
|
||||
std::optional<FileStamp> previewFileStamp() const;
|
||||
std::optional<LocalFileVersion> previewFileStamp() const;
|
||||
void rememberLocalVersion();
|
||||
void pollExternalChanges();
|
||||
void refreshPreview();
|
||||
void startMarkdownTask();
|
||||
void finishMarkdownTask();
|
||||
@@ -1307,8 +1372,8 @@ void TextWindow::reloadPreferences()
|
||||
pendingPreferences = false;
|
||||
auto settings = loadTextPreferences();
|
||||
applyMarkdownPreferences(settings.markdown);
|
||||
auto &profile = settings.profiles[edit];
|
||||
const auto font = search.style.readFont();
|
||||
auto profile=resolvedTextProfile(settings,edit);
|
||||
const auto font=scaledDocumentFont(search.style,edit);
|
||||
const bool fontChanged = font.tenthsOfPoint != filesFont.tenthsOfPoint ||
|
||||
std::memcmp(&font.font, &filesFont.font, sizeof(LOGFONTW)) != 0;
|
||||
if (!fontChanged && profile == prefs) return;
|
||||
@@ -1371,19 +1436,44 @@ void TextWindow::applyPreferences()
|
||||
send(SCI_SETUSETABS, !prefs.tabsAsSpaces);
|
||||
send(SCI_SETTABINDENTS, TRUE);
|
||||
send(SCI_SETBACKSPACEUNINDENTS, TRUE);
|
||||
send(SCI_SETWRAPMODE, !hex && prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE);
|
||||
send(SCI_SETVIEWWS, !hex && prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE);
|
||||
send(SCI_SETVIEWEOL, !hex && prefs.whitespace);
|
||||
applySourceLayoutOptions();
|
||||
applyLineEnding();
|
||||
updateLineNumberMargin();
|
||||
layout();
|
||||
invalidate();
|
||||
}
|
||||
|
||||
void TextWindow::applySourceLayoutOptions()
|
||||
{
|
||||
const bool binary=embedded && quickKind==QuickKind::binary;
|
||||
if(std::exchange(binaryRepresentations,binary)!=binary)
|
||||
{
|
||||
constexpr char digits[]="0123456789ABCDEF";
|
||||
for(int byte=0;byte<256;++byte)
|
||||
{
|
||||
const auto marker=binarySymbolMarker(static_cast<unsigned char>(byte));
|
||||
if(!marker) continue;
|
||||
const auto key=utf8(std::wstring(1,marker));
|
||||
const auto index=reinterpret_cast<WPARAM>(key.c_str());
|
||||
if(binary)
|
||||
{
|
||||
const char value[]{'\\','x',digits[byte>>4],digits[byte&15],0};
|
||||
send(SCI_SETREPRESENTATION,index,reinterpret_cast<LPARAM>(byte=='\\'?"\\\\":value));
|
||||
send(SCI_SETREPRESENTATIONAPPEARANCE,index,SC_REPRESENTATION_PLAIN);
|
||||
}
|
||||
else send(SCI_CLEARREPRESENTATION,index);
|
||||
}
|
||||
}
|
||||
send(SCI_SETWRAPMODE,binary?SC_WRAP_CHAR:!hex && prefs.wrap?SC_WRAP_WORD:SC_WRAP_NONE);
|
||||
send(SCI_SETHSCROLLBAR,!binary);
|
||||
send(SCI_SETVIEWWS,!binary && !hex && prefs.whitespace?SCWS_VISIBLEALWAYS:SCWS_INVISIBLE);
|
||||
send(SCI_SETVIEWEOL,!binary && !hex && prefs.whitespace);
|
||||
}
|
||||
|
||||
void TextWindow::updateLineNumberMargin()
|
||||
{
|
||||
LRESULT width{};
|
||||
if (prefs.numbers && !hex)
|
||||
if (prefs.numbers && !hex && (!embedded || quickKind!=QuickKind::binary))
|
||||
{
|
||||
const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size();
|
||||
const std::string sample(digits, '9');
|
||||
@@ -1591,6 +1681,7 @@ void TextWindow::go(uint64_t index)
|
||||
|
||||
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
|
||||
{
|
||||
rememberLocalVersion();
|
||||
if(hex)
|
||||
{
|
||||
releaseMenu();
|
||||
@@ -1601,8 +1692,9 @@ void TextWindow::initializeDocument(std::optional<std::string> firstPage)
|
||||
return;
|
||||
}
|
||||
if(!firstPage) firstPage=document->readPage(0);
|
||||
automatic=detectLanguage(original,*firstPage);
|
||||
automatic=embedded && quickKind==QuickKind::binary?TextLanguage{}:detectLanguage(original,*firstPage);
|
||||
language=automatic;
|
||||
if(embedded) applySourceLayoutOptions();
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
if(!embedded)
|
||||
{
|
||||
@@ -1633,7 +1725,10 @@ void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
quickReadyAt=GetTickCount64()+80;
|
||||
stopPreview(false,true);
|
||||
document.reset();
|
||||
quickMarkdown.reset();
|
||||
quickPreviewCode.reset();
|
||||
quickKind=QuickKind::text;
|
||||
quickHtmlRendered=false;
|
||||
quickBinaryBytes=0;
|
||||
quickError.clear();
|
||||
layout();
|
||||
SetTimer(window,quickViewTimer,30,nullptr);
|
||||
@@ -1651,7 +1746,11 @@ void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view
|
||||
quickError.clear();
|
||||
stopPreview(false,true);
|
||||
document.reset();
|
||||
quickMarkdown.reset();
|
||||
quickPreviewCode.reset();
|
||||
quickKind=QuickKind::text;
|
||||
quickHtmlRendered=false;
|
||||
quickBinaryBytes=0;
|
||||
applySourceLayoutOptions();
|
||||
}
|
||||
if(quickTextTitle.empty() || quickTextDiff!=diff)
|
||||
{
|
||||
@@ -1681,7 +1780,10 @@ void TextWindow::pollQuickView()
|
||||
original=quickPath;
|
||||
filename=original.filename().wstring();
|
||||
document=std::move(loaded.document);
|
||||
quickMarkdown=std::move(loaded.markdown);
|
||||
quickPreviewCode=std::move(loaded.previewCode);
|
||||
quickKind=loaded.kind;
|
||||
quickHtmlRendered=quickKind==QuickKind::html && quickPreviewCode.has_value();
|
||||
quickBinaryBytes=loaded.binaryBytes;
|
||||
initializeDocument(std::move(loaded.firstPage));
|
||||
}
|
||||
}
|
||||
@@ -1710,13 +1812,23 @@ void TextWindow::pollQuickView()
|
||||
std::packaged_task<QuickDocument()> task([path=quickPath] {
|
||||
auto source=std::make_unique<TextDocument>(path,false);
|
||||
auto first=source->readPage(0);
|
||||
if(first.find('\0')!=std::string::npos)
|
||||
throw std::runtime_error("Binary preview is unavailable.");
|
||||
std::optional<std::string> markdown;
|
||||
if(source->size()<=TextDocument::editLimit && detectLanguage(path,first).lexer=="markdown")
|
||||
markdown=readMarkdownDocument(*source);
|
||||
const auto extension=lower(path.extension().wstring());
|
||||
const auto html=extension==L".html" || extension==L".htm" || extension==L".xhtml";
|
||||
const auto binary=std::any_of(first.begin(),first.end(),[](unsigned char c) {
|
||||
return (c<32 && c!='\t' && c!='\r' && c!='\n' && c!='\f') || c==127;
|
||||
});
|
||||
if(binary && !html)
|
||||
{
|
||||
constexpr size_t limit=4096;
|
||||
const auto bytes=source->readBytes(0,limit);
|
||||
source->releaseReadHandle();
|
||||
return QuickDocument{std::move(source),formatBinarySymbols(bytes),{},QuickKind::binary,bytes.size()};
|
||||
}
|
||||
std::optional<std::string> markup;
|
||||
if(source->size()<=TextDocument::editLimit && (html || detectLanguage(path,first).lexer=="markdown"))
|
||||
markup=readMarkdownDocument(*source);
|
||||
source->releaseReadHandle();
|
||||
return QuickDocument{std::move(source),std::move(first),std::move(markdown)};
|
||||
return QuickDocument{std::move(source),std::move(first),std::move(markup),html?QuickKind::html:QuickKind::text};
|
||||
});
|
||||
quickLoading=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
@@ -1850,6 +1962,7 @@ void TextWindow::finishSave()
|
||||
navigationHistory.clear();
|
||||
updateTitle();
|
||||
}
|
||||
rememberLocalVersion();
|
||||
if (!reopened)
|
||||
{
|
||||
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
|
||||
@@ -1945,10 +2058,64 @@ void TextWindow::restorePosition(const ViewerPosition &position)
|
||||
send(SCI_SETXOFFSET,position.horizontal);
|
||||
}
|
||||
|
||||
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents)
|
||||
void writeDocumentPlacement(nlohmann::json &state,HWND window)
|
||||
{
|
||||
WINDOWPLACEMENT placement{sizeof(placement)};
|
||||
if(GetWindowPlacement(window,&placement))
|
||||
{
|
||||
const auto &rect=placement.rcNormalPosition;
|
||||
state["rect"]={rect.left,rect.top,rect.right,rect.bottom};
|
||||
state["maximized"]=placement.showCmd==SW_SHOWMAXIMIZED ||
|
||||
(placement.flags&WPF_RESTORETOMAXIMIZED)!=0;
|
||||
}
|
||||
}
|
||||
|
||||
RECT readDocumentBounds(const nlohmann::json &state)
|
||||
{
|
||||
if(!state.contains("rect")) return {};
|
||||
const auto rect=state.at("rect").get<std::array<LONG,4>>();
|
||||
return {rect[0],rect[1],rect[2],rect[3]};
|
||||
}
|
||||
|
||||
int restoreDocumentPlacement(HWND window,HWND owner,const RECT &bounds,bool maximized)
|
||||
{
|
||||
if(bounds.left>=bounds.right || bounds.top>=bounds.bottom || !MonitorFromRect(&bounds,MONITOR_DEFAULTTONULL))
|
||||
return IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
|
||||
WINDOWPLACEMENT placement{sizeof(placement)};
|
||||
placement.rcNormalPosition=bounds;
|
||||
placement.showCmd=maximized?SW_SHOWMAXIMIZED:SW_SHOWNORMAL;
|
||||
SetWindowPlacement(window,&placement);
|
||||
return maximized?SW_MAXIMIZE:SW_SHOWNORMAL;
|
||||
}
|
||||
|
||||
nlohmann::json TextWindow::sessionState() const
|
||||
{
|
||||
if(embedded || remote || draft || !document || !isLocalDocumentPath(original)) return nullptr;
|
||||
const auto position=currentPosition();
|
||||
nlohmann::json state{{"path",utf8(original.native())},{"editor",edit},{"hex",hex},
|
||||
{"page",position.page},{"anchor",position.anchor},{"caret",position.caret},
|
||||
{"firstLine",position.firstLine},{"horizontal",position.horizontal}};
|
||||
if(previewVisible) state["renderedScroll"]=renderedScroll;
|
||||
writeDocumentPlacement(state,window);
|
||||
return state;
|
||||
}
|
||||
|
||||
void TextWindow::restoreSession(const nlohmann::json &state)
|
||||
{
|
||||
ViewerPosition position{std::min(state.value("page",uint64_t{}),pageTotal?pageTotal-1:0),
|
||||
state.value("anchor",LRESULT{}),state.value("caret",LRESULT{}),
|
||||
std::max<LRESULT>(0,state.value("firstLine",LRESULT{})),std::max<LRESULT>(0,state.value("horizontal",LRESULT{}))};
|
||||
if(position.page!=page) loadPage(position.page);
|
||||
restorePosition(position);
|
||||
if(state.contains("renderedScroll")) sessionScroll=std::max(0,state.at("renderedScroll").get<int>());
|
||||
}
|
||||
|
||||
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus)
|
||||
{
|
||||
rememberLocalVersion();
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
prefs = loadTextPreferences().profiles[edit];
|
||||
prefs=resolvedTextProfile(loadTextPreferences(),edit);
|
||||
filesFont=scaledDocumentFont(search.style,edit);
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
installLexer();
|
||||
@@ -1959,7 +2126,7 @@ void TextWindow::showTextMode(const ViewerPosition &position,std::string content
|
||||
updateTaskbarGroup();
|
||||
updatePreview();
|
||||
layout();
|
||||
focusContent();
|
||||
if(takeFocus) focusContent();
|
||||
}
|
||||
|
||||
void TextWindow::changeMode()
|
||||
@@ -1967,7 +2134,8 @@ void TextWindow::changeMode()
|
||||
if(!edit && remote && !remote->revision.editable)
|
||||
throw std::runtime_error("The remote file does not support editing.");
|
||||
auto position=currentPosition();
|
||||
auto replacement=std::make_unique<TextDocument>(remote?remote->cache:original,!edit,document->encoding());
|
||||
auto replacement=std::make_unique<TextDocument>(remote?remote->cache:original,!edit,document->encoding(),
|
||||
!remote && isLocalDocumentPath(original));
|
||||
position.page=std::min(position.page,replacement->pages()-1);
|
||||
auto contents=replacement->readPage(position.page);
|
||||
document=std::move(replacement);
|
||||
@@ -2064,8 +2232,17 @@ void TextWindow::updateTaskbarGroup(bool closing)
|
||||
|
||||
bool TextWindow::canPreview() const
|
||||
{
|
||||
return !edit && !hex && !showBookmarkSource && automatic.lexer=="markdown" && document &&
|
||||
document->size()<=TextDocument::editLimit;
|
||||
if(edit || hex || showBookmarkSource || !document || document->size()>TextDocument::editLimit) return false;
|
||||
if(embedded && quickKind==QuickKind::html) return quickHtmlRendered;
|
||||
return automatic.lexer=="markdown";
|
||||
}
|
||||
|
||||
void TextWindow::toggleQuickHtml()
|
||||
{
|
||||
if(!embedded || quickKind!=QuickKind::html || !document || !quickPreviewCode) return;
|
||||
quickHtmlRendered=!quickHtmlRendered;
|
||||
if(quickHtmlRendered) updatePreview();
|
||||
else stopPreview(true,true);
|
||||
}
|
||||
|
||||
void TextWindow::updatePreview()
|
||||
@@ -2094,8 +2271,18 @@ bool TextWindow::startPreviewBrowser()
|
||||
{
|
||||
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
|
||||
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
|
||||
if(key==VK_F1 && !ctrl && !alt && !((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
|
||||
{
|
||||
PostMessageW(window,filesHelpRequest,0,0);
|
||||
return true;
|
||||
}
|
||||
if(embedded)
|
||||
{
|
||||
if(!ctrl && !alt && !(GetKeyState(VK_SHIFT)&0x8000) && key==VK_F6 && quickKind==QuickKind::html)
|
||||
{
|
||||
PostMessageW(window,WM_COMMAND,quickModeControl,0);
|
||||
return true;
|
||||
}
|
||||
if(!ctrl || alt || key!='Q') return false;
|
||||
PostMessageW(GetParent(window),quickViewToggleMessage,0,0);
|
||||
return true;
|
||||
@@ -2131,6 +2318,7 @@ void TextWindow::stopPreview(bool refresh,bool keepBrowser)
|
||||
{
|
||||
KillTimer(window,previewTimer);
|
||||
previewWanted=previewVisible=false;
|
||||
if(embedded && refresh && quickKind==QuickKind::html) quickHtmlRendered=false;
|
||||
previewStamp.reset();
|
||||
++previewRevision;
|
||||
previewText.clear();
|
||||
@@ -2167,33 +2355,70 @@ void TextWindow::goToFragment(std::string_view fragment)
|
||||
else previewFragment=fragment;
|
||||
}
|
||||
|
||||
std::optional<TextWindow::FileStamp> TextWindow::previewFileStamp() const
|
||||
std::optional<LocalFileVersion> TextWindow::previewFileStamp() const
|
||||
{
|
||||
if(remote) return {};
|
||||
if(remote || !isLocalDocumentPath(original)) return {};
|
||||
const auto file=CreateFileW(original.c_str(),FILE_READ_ATTRIBUTES,
|
||||
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(file==INVALID_HANDLE_VALUE) return {};
|
||||
BY_HANDLE_FILE_INFORMATION state{};
|
||||
const auto found=GetFileInformationByHandle(file,&state);
|
||||
std::optional<LocalFileVersion> stamp;
|
||||
try {stamp=fileVersion(file);} catch(const std::system_error &) {}
|
||||
CloseHandle(file);
|
||||
if(!found) return {};
|
||||
const auto combine=[](DWORD high,DWORD low){return (uint64_t{high}<<32)|low;};
|
||||
return FileStamp{combine(state.ftLastWriteTime.dwHighDateTime,state.ftLastWriteTime.dwLowDateTime),
|
||||
combine(state.nFileIndexHigh,state.nFileIndexLow),
|
||||
combine(state.nFileSizeHigh,state.nFileSizeLow),state.dwVolumeSerialNumber};
|
||||
return stamp;
|
||||
}
|
||||
|
||||
void TextWindow::rememberLocalVersion()
|
||||
{
|
||||
if(embedded || remote || !document) return;
|
||||
observedVersion=edit?document->expectedVersion():previewFileStamp();
|
||||
diskChanged=false;
|
||||
}
|
||||
|
||||
void TextWindow::pollExternalChanges()
|
||||
{
|
||||
if(embedded || remote || draft || !document || busy() || previewWanted || navigation.valid() || !observedVersion)
|
||||
return;
|
||||
const auto stamp=previewFileStamp();
|
||||
if(!stamp || stamp==observedVersion) return;
|
||||
if(edit && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !search.style.reloadChanged)) return;
|
||||
try
|
||||
{
|
||||
if(edit)
|
||||
{
|
||||
observedVersion=stamp;
|
||||
diskChanged=true;
|
||||
invalidate();
|
||||
if(!search.style.reloadChanged(window)) return;
|
||||
}
|
||||
auto replacement=std::make_unique<TextDocument>(original,edit,hex?TextEncoding::utf8:TextEncoding::automatic,edit);
|
||||
auto position=currentPosition();
|
||||
const auto pages=hex?1+(replacement->size()?replacement->size()-1:0)/hexPageBytes:replacement->pages();
|
||||
position.page=std::min(position.page,pages-1);
|
||||
auto contents=hex?formatHexPage(replacement->readBytes(position.page*hexPageBytes,hexPageBytes),
|
||||
position.page*hexPageBytes):replacement->readPage(position.page);
|
||||
if(!hex) language=automatic=detectLanguage(original,contents);
|
||||
document=std::move(replacement);
|
||||
showTextMode(position,std::move(contents),edit);
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(edit) search.style.message(window,wide(error.what()).c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::renderPreview(bool keepPosition)
|
||||
{
|
||||
applyMarkdownPreferences(loadTextPreferences().markdown);
|
||||
previewDeadline=GetTickCount64()+30000;
|
||||
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
|
||||
previewText=quickPreviewCode?*quickPreviewCode:readMarkdownDocument(*document);
|
||||
if(!remote) document->releaseReadHandle();
|
||||
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
|
||||
{"canSave",!embedded && !suspendedEditor && (!remote || remote->revision.editable)},{"compact",embedded},
|
||||
{"html",embedded && quickKind==QuickKind::html},
|
||||
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
|
||||
{"keepPosition",keepPosition}};
|
||||
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
|
||||
if(sessionScroll) message["scroll"]=*std::exchange(sessionScroll,{});
|
||||
restoreScroll=false;
|
||||
preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace)));
|
||||
}
|
||||
@@ -2201,8 +2426,9 @@ void TextWindow::renderPreview(bool keepPosition)
|
||||
void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences)
|
||||
{
|
||||
if(!preview.initialized()) return;
|
||||
const auto scale=textAreaScale(search.style,AppearanceArea::markdown);
|
||||
preview.post(wide(nlohmann::json{{"action","appearance"},{"width",preferences.width},
|
||||
{"fontSize",preferences.fontSize},{"font",utf8(preferences.font)}}.dump()));
|
||||
{"fontSize",preferences.fontSize*scale/100.0},{"font",utf8(preferences.font)}}.dump()));
|
||||
}
|
||||
|
||||
void TextWindow::refreshPreview()
|
||||
@@ -2358,6 +2584,7 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
}
|
||||
const auto message=nlohmann::json::parse(utf8(value));
|
||||
const auto action=message.at("action").get<std::string>();
|
||||
if(embedded && quickKind==QuickKind::html && action!="rendered" && action!="failed") return;
|
||||
if(action=="cycle")
|
||||
{
|
||||
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
|
||||
@@ -2366,6 +2593,11 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
if(embedded && action!="image" && action!="rendered" && action!="failed") return;
|
||||
const auto revision=message.value("revision",previewRevision);
|
||||
if(embedded && revision!=previewRevision) return;
|
||||
if(action=="scroll")
|
||||
{
|
||||
if(!embedded && revision==previewRevision) renderedScroll=std::max(0,message.at("top").get<int>());
|
||||
return;
|
||||
}
|
||||
if(action=="failed")
|
||||
{
|
||||
PostMessageW(window,previewFailed,static_cast<WPARAM>(revision),0);
|
||||
@@ -2558,6 +2790,13 @@ void TextWindow::layout()
|
||||
const int top=embedded?row:2*row;
|
||||
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
|
||||
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
|
||||
if(quickModeButton)
|
||||
{
|
||||
const int width=std::min(static_cast<int>(area.right),scale(108));
|
||||
MoveWindow(quickModeButton,area.right-width,0,width,row,TRUE);
|
||||
SetWindowTextW(quickModeButton,quickHtmlRendered?L"Show Source":L"Show Rendered");
|
||||
ShowWindow(quickModeButton,quickKind==QuickKind::html && quickPreviewCode && document?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
|
||||
ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
invalidate();
|
||||
@@ -2633,9 +2872,18 @@ void TextWindow::paint()
|
||||
std::wstring label=L"Quick View";
|
||||
if(!quickPath.empty()) label+=L" · "+quickPath.filename().native();
|
||||
if(!quickError.empty()) label+=L" · "+quickError;
|
||||
else if(quickPath.empty()) label+=L" · Select a local text file";
|
||||
else if(quickPath.empty()) label+=L" · Select a local file";
|
||||
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
|
||||
else if(!previewVisible && pageTotal>1) label+=L" · First page";
|
||||
else if(quickKind==QuickKind::binary)
|
||||
label=L"Binary · "+std::to_wstring(quickBinaryBytes)+L" / "+std::to_wstring(fileSize)+L" B · "+
|
||||
quickPath.filename().native();
|
||||
else
|
||||
{
|
||||
if(quickKind==QuickKind::html) label+=previewVisible?L" · Rendered":L" · Source";
|
||||
if(!previewVisible && pageTotal>1) label+=L" · First page";
|
||||
}
|
||||
if(quickModeButton && IsWindowVisible(quickModeButton))
|
||||
client.right=std::max(0L,client.right-scale(108));
|
||||
if(!quickTextTitle.empty()) label=quickTextTitle;
|
||||
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
|
||||
color(TextColor::chrome),scale(6),label);
|
||||
@@ -2691,6 +2939,7 @@ void TextWindow::paint()
|
||||
if(pageTotal>1)
|
||||
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
|
||||
L" @ "+std::to_wstring(pageOffset);
|
||||
if(diskChanged && edit) status+=L" │ Disk changed";
|
||||
status+=L" │ "+std::to_wstring(fileSize)+L" B";
|
||||
if(bookmarkTask.valid()) status+=L" │ Locating line…";
|
||||
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
|
||||
@@ -2804,7 +3053,7 @@ void TextWindow::command(UINT id)
|
||||
case lexerAuto: language = automatic; installLexer(); return;
|
||||
case lexerPlain: language = {}; installLexer(); return;
|
||||
case options:
|
||||
search.style.options(window, edit);
|
||||
search.style.options(window,appearanceArea());
|
||||
SetFocus(editor);
|
||||
return;
|
||||
default:
|
||||
@@ -2872,7 +3121,13 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
|
||||
bool TextWindow::handleKey(const MSG &message)
|
||||
{
|
||||
if(embedded) return false;
|
||||
if(embedded)
|
||||
{
|
||||
if(quickKind!=QuickKind::html || message.message!=WM_KEYDOWN || message.wParam!=VK_F6 ||
|
||||
((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_MENU))&0x8000)) return false;
|
||||
if(!(message.lParam&(1LL<<30))) toggleQuickHtml();
|
||||
return true;
|
||||
}
|
||||
const auto key = message.wParam;
|
||||
if (message.hwnd != editor) return false;
|
||||
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
|
||||
@@ -2931,7 +3186,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
const auto self=found->second;
|
||||
try
|
||||
{
|
||||
if (message == preferencesChanged)
|
||||
if(message==preferencesChanged || windowsAppThemeChanged(message,lparam))
|
||||
{
|
||||
self->reloadPreferences();
|
||||
return 0;
|
||||
@@ -2953,6 +3208,12 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
self->editor = CreateWindowExW(0, L"Scintilla", L"", WS_CHILD | WS_TABSTOP |
|
||||
WS_VSCROLL | WS_HSCROLL, 0, 0, 0, 0, window, nullptr, GetModuleHandleW(nullptr), nullptr);
|
||||
if (!self->editor) throw std::runtime_error("Cannot create the text control.");
|
||||
if(self->embedded)
|
||||
{
|
||||
self->quickModeButton=CreateWindowW(L"BUTTON",L"Show Source",WS_CHILD|WS_TABSTOP|BS_PUSHBUTTON,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(quickModeControl),GetModuleHandleW(nullptr),nullptr);
|
||||
if(!self->quickModeButton) throw std::runtime_error("Cannot create the Quick View mode button.");
|
||||
}
|
||||
self->send(SCI_SETCODEPAGE, SC_CP_UTF8);
|
||||
self->send(SCI_SETMARGINS, 1);
|
||||
self->send(SCI_SETMODEVENTMASK, SC_MOD_INSERTCHECK | SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT);
|
||||
@@ -2983,6 +3244,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
else self->initializeDocument();
|
||||
if(!self->embedded)
|
||||
{
|
||||
if(!self->remote) SetTimer(window,externalChangeTimer,500,nullptr);
|
||||
self->updateIcons(GetDpiForWindow(window));
|
||||
self->updateTaskbarGroup();
|
||||
}
|
||||
@@ -3050,7 +3312,11 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
if(self->embedded) return 0;
|
||||
if(self->embedded)
|
||||
{
|
||||
if(LOWORD(wparam)==quickModeControl) self->toggleQuickHtml();
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600);
|
||||
else self->command(LOWORD(wparam));
|
||||
return 0;
|
||||
@@ -3065,6 +3331,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
if (wparam == saveTimer) self->finishSave();
|
||||
if (wparam == openTimer) self->finishOpen();
|
||||
if (wparam == previewTimer) self->pollImages();
|
||||
if (wparam == externalChangeTimer) self->pollExternalChanges();
|
||||
if (wparam == navigationTimer) self->finishNavigation();
|
||||
if (wparam == quickViewTimer) self->pollQuickView();
|
||||
if (wparam == bookmarkTimer) self->finishBookmark();
|
||||
@@ -3299,16 +3566,23 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
preview->second->previewFile(path);
|
||||
}
|
||||
|
||||
std::optional<AppearanceArea> textWindowAppearanceArea(HWND window)
|
||||
{
|
||||
const auto entry=textWindows.find(window);
|
||||
if(entry==textWindows.end()) return {};
|
||||
return entry->second->appearanceArea();
|
||||
}
|
||||
|
||||
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff)
|
||||
{
|
||||
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
|
||||
preview->second->previewEmbeddedText(title,contents,diff);
|
||||
}
|
||||
|
||||
ImageViewStyle imageViewStyle(TextDialogs dialogs)
|
||||
ImageViewStyle imageViewStyle(TextDialogs dialogs,bool edit=false)
|
||||
{
|
||||
const auto font=dialogs.readFont();
|
||||
const auto colors=loadTextPreferences().profiles[0].colors;
|
||||
const auto font=scaledDocumentFont(dialogs,edit);
|
||||
const auto colors=resolvedTextProfile(loadTextPreferences(),edit).colors;
|
||||
return {font.font,font.tenthsOfPoint,colors[0],colors[1],colors[2],colors[3],colors[4]};
|
||||
}
|
||||
|
||||
@@ -3323,7 +3597,8 @@ void previewImageQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
}
|
||||
|
||||
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
|
||||
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source)
|
||||
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source,const ImageEditDialogs *editor,
|
||||
const ImageWindowSession *session)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -3353,26 +3628,35 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
|
||||
}
|
||||
}
|
||||
if(!textWindows.contains(owner)) filesOwner=owner;
|
||||
const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load),
|
||||
const auto window=createImageView(owner,false,imageViewStyle(dialogs,editor!=nullptr),std::move(images),path,std::move(load),
|
||||
[](HWND closed) {
|
||||
std::erase(textWindowOrder,closed);
|
||||
quitWhenFilesWindowsClose();
|
||||
},std::move(retry));
|
||||
if(!window) throw std::runtime_error("Could not open the image viewer.");
|
||||
},std::move(retry),editor);
|
||||
if(!window) throw std::runtime_error(editor?"Could not open the image editor.":"Could not open the image viewer.");
|
||||
textWindowOrder.push_back(window);
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(IDI_FILES_VIEWER),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE);
|
||||
const int iconId=editor?IDI_FILES_EDITOR:IDI_FILES_VIEWER;
|
||||
const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(iconId),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE);
|
||||
if(icon) SendMessageW(window,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(icon));
|
||||
setFileWindowTaskbar(window,IDI_FILES_VIEWER,L"HrynCo.KSwitcher.Files.Viewer");
|
||||
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
setFileWindowTaskbar(window,iconId,editor?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
|
||||
if(session) restoreImageWindowSession(window,*session);
|
||||
ShowWindow(window,session?restoreDocumentPlacement(window,owner,session->bounds,session->maximized):
|
||||
IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
SetFocus(window);
|
||||
}
|
||||
catch(const std::exception &error) {dialogs.message(owner,wide(error.what()).c_str());}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(!session) dialogs.message(owner,wide(error.what()).c_str());
|
||||
else log(L"Restore Files image: "+wide(error.what()));
|
||||
}
|
||||
}
|
||||
|
||||
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options)
|
||||
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options,
|
||||
const nlohmann::json *session=nullptr)
|
||||
{
|
||||
HWND created{};
|
||||
if(!edit && !options.draft && !options.hex && !options.line && isImagePath(path))
|
||||
{
|
||||
openImageWindow(owner,{path},path,dialogs,nullptr,backend);
|
||||
@@ -3408,10 +3692,90 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
|
||||
WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,bounds.left,bounds.top,bounds.right-bounds.left,
|
||||
bounds.bottom-bounds.top,nullptr,nullptr,instance,&state);
|
||||
if(!window) return;
|
||||
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
created=window;
|
||||
int show=IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
|
||||
if(session)
|
||||
{
|
||||
state->restoreSession(*session);
|
||||
show=restoreDocumentPlacement(window,owner,readDocumentBounds(*session),session->value("maximized",false));
|
||||
}
|
||||
ShowWindow(window,show);
|
||||
SendMessageW(window,WM_SETFOCUS,0,0);
|
||||
}
|
||||
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(!session) dialogs.message(owner,wide(error.what()).c_str());
|
||||
else
|
||||
{
|
||||
if(created) DestroyWindow(created);
|
||||
log(L"Restore Files document: "+wide(error.what()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
constexpr wchar_t localSessionKey[]=L"LocalDocumentsV1";
|
||||
|
||||
void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled)
|
||||
{
|
||||
if(!enabled)
|
||||
{
|
||||
RegDeleteKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey);
|
||||
return;
|
||||
}
|
||||
auto session=nlohmann::json::array();
|
||||
for(const auto window:textWindowOrder)
|
||||
{
|
||||
if(session.size()>=128) break;
|
||||
if(const auto found=textWindows.find(window);found!=textWindows.end())
|
||||
{
|
||||
auto state=found->second->sessionState();
|
||||
if(!state.is_null()) session.push_back(std::move(state));
|
||||
}
|
||||
else if(const auto image=imageWindowSession(window))
|
||||
{
|
||||
nlohmann::json state{{"path",utf8(image->path.native())},{"editor",image->editor},{"image",true},
|
||||
{"fit",image->fit},{"zoom",image->zoom},{"x",image->x},{"y",image->y}};
|
||||
writeDocumentPlacement(state,window);
|
||||
session.push_back(std::move(state));
|
||||
}
|
||||
}
|
||||
const auto text=session.dump();
|
||||
if(text.size()<=1024*1024)
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,REG_BINARY,text.data(),static_cast<DWORD>(text.size()));
|
||||
}
|
||||
|
||||
void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,
|
||||
const ImageEditDialogs &imageEditor)
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>1024*1024) return;
|
||||
std::string text(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,text.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return;
|
||||
const auto session=nlohmann::json::parse(text.begin(),text.begin()+bytes,nullptr,false);
|
||||
if(!session.is_array()) return;
|
||||
for(size_t i=0;i<std::min<size_t>(128,session.size());++i)
|
||||
{
|
||||
try
|
||||
{
|
||||
const auto &state=session[i];
|
||||
const std::filesystem::path path=wide(state.at("path").get<std::string>());
|
||||
if(!isLocalDocumentPath(path)) continue;
|
||||
const auto attributes=GetFileAttributesW(path.c_str());
|
||||
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY)) continue;
|
||||
const bool editor=state.value("editor",false);
|
||||
if(state.value("image",false))
|
||||
{
|
||||
if(!isImagePath(path) || (editor && !isEditableImagePath(path))) continue;
|
||||
ImageWindowSession image{path,editor,state.value("fit",true),state.value("zoom",1.0),
|
||||
state.value("x",0.0),state.value("y",0.0),readDocumentBounds(state),state.value("maximized",false)};
|
||||
openImageWindow(owner,{path},path,dialogs,nullptr,nullptr,editor?&imageEditor:nullptr,&image);
|
||||
}
|
||||
else openTextWindowImpl(owner,path,editor,dialogs,nullptr,{},true,{.hex=state.value("hex",false)},&state);
|
||||
}
|
||||
catch(const std::exception &error) {log(L"Restore Files document: "+wide(error.what()));}
|
||||
}
|
||||
}
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
|
||||
+11
-2
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include "files_appearance.h"
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
@@ -48,7 +49,7 @@ struct TextDialogs
|
||||
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
|
||||
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
|
||||
void (*prepare)(HWND);
|
||||
void (*options)(HWND, bool);
|
||||
void (*options)(HWND, AppearanceArea);
|
||||
void (*message)(HWND, const wchar_t *);
|
||||
TextWindowFont (*readFont)();
|
||||
FarDropDownPalette (*dropDownPalette)();
|
||||
@@ -57,6 +58,8 @@ struct TextDialogs
|
||||
bool (*dismissOwned)(HWND);
|
||||
bool (*confirmExisting)(HWND);
|
||||
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
|
||||
bool (*reloadChanged)(HWND){};
|
||||
unsigned (*readScale)(AppearanceArea){};
|
||||
};
|
||||
|
||||
struct TextOpenOptions
|
||||
@@ -109,8 +112,11 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path);
|
||||
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff=false);
|
||||
HWND createImageQuickView(HWND owner,TextDialogs dialogs);
|
||||
void previewImageQuickViewFile(HWND window,const std::filesystem::path &path);
|
||||
struct ImageEditDialogs;
|
||||
struct ImageWindowSession;
|
||||
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
|
||||
TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr);
|
||||
TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr,
|
||||
const ImageEditDialogs *editor=nullptr,const ImageWindowSession *session=nullptr);
|
||||
void showAllViewerBookmarks(HWND owner,TextDialogs dialogs);
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
@@ -118,8 +124,11 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
TextOpenOptions options={});
|
||||
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={});
|
||||
void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled);
|
||||
void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,const ImageEditDialogs &imageEditor);
|
||||
void textWindowOwnerClosed();
|
||||
void standaloneFilesWindowOpened();
|
||||
void standaloneFilesWindowClosed();
|
||||
bool cycleTextWindows(HWND current,bool reverse);
|
||||
std::optional<AppearanceArea> textWindowAppearanceArea(HWND window);
|
||||
}
|
||||
@@ -1,18 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <objbase.h>
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline bool isLocalDocumentPath(const std::filesystem::path &path)
|
||||
{
|
||||
std::wstring_view name=path.native();
|
||||
if(name.starts_with(L"\\\\?\\")) name.remove_prefix(4);
|
||||
if(name.size()<3 || name[1]!=L':' || (name[2]!=L'\\' && name[2]!=L'/')) return false;
|
||||
const auto type=GetDriveTypeW(std::wstring(name.substr(0,3)).c_str());
|
||||
return type==DRIVE_FIXED || type==DRIVE_REMOVABLE || type==DRIVE_RAMDISK || type==DRIVE_CDROM;
|
||||
}
|
||||
|
||||
inline std::filesystem::path temporaryPath(const std::filesystem::path &directory)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
|
||||
throw std::runtime_error("Cannot create a temporary file name.");
|
||||
return directory/(std::wstring(L".kswitcher-")+name+L".tmp");
|
||||
}
|
||||
|
||||
inline bool sameFileIdentity(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
|
||||
{
|
||||
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
|
||||
left.nFileIndexLow==right.nFileIndexLow;
|
||||
}
|
||||
|
||||
|
||||
struct LocalFileVersion
|
||||
{
|
||||
BY_HANDLE_FILE_INFORMATION info{};
|
||||
LONGLONG changeTime{};
|
||||
|
||||
bool operator==(const LocalFileVersion &other) const
|
||||
{
|
||||
return sameFileIdentity(info,other.info) && changeTime==other.changeTime &&
|
||||
info.nFileSizeHigh==other.info.nFileSizeHigh && info.nFileSizeLow==other.info.nFileSizeLow &&
|
||||
CompareFileTime(&info.ftLastWriteTime,&other.info.ftLastWriteTime)==0;
|
||||
}
|
||||
};
|
||||
|
||||
inline LocalFileVersion fileVersion(HANDLE file)
|
||||
{
|
||||
LocalFileVersion version;
|
||||
if(!GetFileInformationByHandle(file,&version.info))
|
||||
throw std::system_error(static_cast<int>(GetLastError()),std::system_category(),"Read file revision");
|
||||
FILE_BASIC_INFO basics{};
|
||||
if(GetFileInformationByHandleEx(file,FileBasicInfo,&basics,sizeof(basics)))
|
||||
version.changeTime=basics.ChangeTime.QuadPart;
|
||||
return version;
|
||||
}
|
||||
|
||||
inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement,
|
||||
const std::filesystem::path &backup)
|
||||
{
|
||||
|
||||
+36
-4
@@ -148,6 +148,7 @@ struct LanService::Impl
|
||||
std::mutex inputMutex;
|
||||
std::vector<lan::RoutedInput> inputOut,inputIn;
|
||||
std::map<std::string,uint64_t> inputReady;
|
||||
std::function<int()> additionalHeldKey;
|
||||
std::unique_ptr<lan::InputMesh> router;
|
||||
std::string inputStatus="Input sharing disabled.";
|
||||
size_t inputConnectedPeers{}, inputOnlinePeers{};
|
||||
@@ -155,8 +156,8 @@ struct LanService::Impl
|
||||
bool inputNeedsHelp{};
|
||||
HWND inputWindow{};std::atomic<bool> inputNotification{false};
|
||||
lan::LanClients clients;
|
||||
explicit Impl(const std::filesystem::path &root,HWND window,bool paused)
|
||||
: path(root/L"lan-pairing.bin"),inputPaused(paused),inputWindow(window),clients(root)
|
||||
explicit Impl(const std::filesystem::path &root,HWND window,bool paused,std::function<int()> heldKey)
|
||||
: path(root/L"lan-pairing.bin"),inputPaused(paused),additionalHeldKey(std::move(heldKey)),inputWindow(window),clients(root)
|
||||
{
|
||||
if(std::filesystem::exists(path))
|
||||
{
|
||||
@@ -239,7 +240,8 @@ struct LanService::Impl
|
||||
router.reset();++inputConfiguration;
|
||||
if(enabled&&shareInput&&!inputPaused){
|
||||
std::map<std::string,POINT> layout;for(auto &[peer,cell]:positions.items())if(trusted.contains(peer))layout[peer]={cell[0].get<LONG>(),cell[1].get<LONG>()};
|
||||
router=std::make_unique<lan::InputMesh>(id,lan::windowsInputEnvironment(),std::move(layout),[this](const auto &peer,auto f){return queue(peer,f);});
|
||||
router=std::make_unique<lan::InputMesh>(id,lan::windowsInputEnvironment(additionalHeldKey),std::move(layout),
|
||||
[this](const auto &peer,auto f){return queue(peer,f);});
|
||||
}
|
||||
inputStatus=enabled&&shareInput?"Connecting input channels...":"Input sharing disabled.";
|
||||
observedRevision=0;
|
||||
@@ -282,6 +284,26 @@ struct LanService::Impl
|
||||
router->receive(frame.peer,frame.frame,GetTickCount64(),allowEnter);
|
||||
return takeChange();
|
||||
}
|
||||
std::wstring inputBlockText(const lan::HandoffBlock &block) const
|
||||
{
|
||||
if(!block.key)return {};
|
||||
std::wstring location=L"this PC";
|
||||
if(!block.peer.empty())
|
||||
{
|
||||
auto paired=trusted.find(block.peer);
|
||||
if(paired==trusted.end())return {};
|
||||
location=wide(paired->value("name",block.peer.substr(0,8)));
|
||||
if(location.size()>50)
|
||||
{
|
||||
const bool highSurrogate=location[48]>=0xd800&&location[48]<=0xdbff;
|
||||
location.resize(highSurrogate?48:49);
|
||||
location+=L"…";
|
||||
}
|
||||
}
|
||||
auto input=lan::heldInputName(block.key);
|
||||
return L"Cursor handoff blocked on "+location+L": "+
|
||||
(input.empty()?L"a key or mouse button is held.":input+L" is held.");
|
||||
}
|
||||
void start()
|
||||
{
|
||||
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
|
||||
@@ -827,6 +849,7 @@ struct LanService::Impl
|
||||
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnectedPeers!=0},
|
||||
{"inputStatus",inputPaused?"Input processing paused in the tray.":enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",!inputPaused&&enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
|
||||
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
|
||||
result["inputBlock"]=router?utf8(inputBlockText(router->handoffBlock())):std::string{};
|
||||
result["shareLogs"]=shareLogs;
|
||||
result["files"]=Json::array();
|
||||
result["transferStatus"]=transfers->status;
|
||||
@@ -853,7 +876,8 @@ struct LanService::Impl
|
||||
return encoded(result);
|
||||
}
|
||||
};
|
||||
LanService::LanService(const std::filesystem::path &path,HWND window,bool paused) : impl(std::make_unique<Impl>(path,window,paused)) {}
|
||||
LanService::LanService(const std::filesystem::path &path,HWND window,bool paused,std::function<int()> heldKey)
|
||||
:impl(std::make_unique<Impl>(path,window,paused,std::move(heldKey))) {}
|
||||
LanService::~LanService()=default;
|
||||
Bytes LanService::command(const Bytes &command) { return impl->command(command); }
|
||||
void LanService::startClients() { impl->startClients(); }
|
||||
@@ -888,6 +912,14 @@ LanInputConnections LanService::inputConnections()const
|
||||
return {std::min(impl->inputConnectedPeers,paired),std::min(impl->inputOnlinePeers,paired),paired,impl->inputWorkerStopped};
|
||||
}
|
||||
bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);}
|
||||
std::wstring LanService::inputBlockText()const
|
||||
{
|
||||
const auto block=impl->router?impl->router->handoffBlock():lan::HandoffBlock{};
|
||||
if(!block.key)return {};
|
||||
std::lock_guard lock(impl->mutex);
|
||||
return impl->inputBlockText(block);
|
||||
}
|
||||
void LanService::forgetHeldInput(){if(impl->router)impl->router->forgetHeldKeys();}
|
||||
bool LanService::keyboard(const KBDLLHOOKSTRUCT &k,bool down){return impl->router&&impl->router->keyboard(k,down,GetTickCount64());}
|
||||
bool LanService::mouse(UINT message,const MSLLHOOKSTRUCT &m,bool allowEnter){return impl->router&&impl->router->mouse(message,m,GetTickCount64(),allowEnter);}
|
||||
bool LanService::takeInputChange(){return impl->takeChange();}
|
||||
|
||||
@@ -21,7 +21,8 @@ class LanService
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl;
|
||||
public:
|
||||
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr, bool inputPaused=false);
|
||||
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr, bool inputPaused=false,
|
||||
std::function<int()> additionalHeldKey={});
|
||||
~LanService();
|
||||
Bytes command(const Bytes &);
|
||||
void startClients();
|
||||
@@ -31,6 +32,8 @@ class LanService
|
||||
bool inputEnabled() const;
|
||||
void setInputPaused(bool);
|
||||
LanInputConnections inputConnections() const;
|
||||
std::wstring inputBlockText() const;
|
||||
void forgetHeldInput();
|
||||
bool tickInput(bool allowEnter = true);
|
||||
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
|
||||
bool mouse(UINT, const MSLLHOOKSTRUCT &, bool allowEnter);
|
||||
|
||||
@@ -48,7 +48,8 @@ Json capabilities(bool write, bool erase, unsigned host)
|
||||
{
|
||||
return {{"protocol", 2}, {"hostRevision", host}, {"write", write && host},
|
||||
{"delete", erase && host}, {"move", write && erase && host},
|
||||
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0}};
|
||||
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0},
|
||||
{"conflictPrompt", host != 0}};
|
||||
}
|
||||
fs::path itemPath(const Json &value)
|
||||
{
|
||||
@@ -128,6 +129,27 @@ class ClientTransfer
|
||||
if (!result.at("continue").get<bool>()) throw std::system_error(ERROR_CANCELLED, std::system_category());
|
||||
guard();
|
||||
}
|
||||
bool resolveConflict(const fs::path &path, const Json &incoming, const Json &existing)
|
||||
{
|
||||
if (conflict == "skip") return false;
|
||||
const bool replaceable = directory(incoming) == directory(existing) && !reparse(existing);
|
||||
if (conflict == "replace" && replaceable) return true;
|
||||
if (conflict != "ask") throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
|
||||
if (replaceable && directory(existing)) return true;
|
||||
|
||||
sendJson(send, {{"type", "conflict"}, {"path", utf8(path.native())},
|
||||
{"incoming", incoming}, {"existing", existing}, {"replaceable", replaceable}});
|
||||
for (;;)
|
||||
{
|
||||
const auto answer = Json::parse(receive(256)).at("decision").get<std::string>();
|
||||
guard();
|
||||
if (answer == "wait") continue;
|
||||
if (answer == "skip") return false;
|
||||
if (answer == "replace" && replaceable) return true;
|
||||
if (answer == "cancel") throw std::system_error(ERROR_CANCELLED, std::system_category());
|
||||
throw std::runtime_error("Invalid transfer conflict decision.");
|
||||
}
|
||||
}
|
||||
bool copy(const fs::path &from, const fs::path &to, unsigned depth)
|
||||
{
|
||||
if (depth > 256) throw std::runtime_error("The file tree is too deep.");
|
||||
@@ -139,9 +161,7 @@ class ClientTransfer
|
||||
if (found)
|
||||
{
|
||||
checkFileReply(existing);
|
||||
if (conflict == "skip") { ++skipped; return false; }
|
||||
if (conflict != "replace" || directory(original) != directory(existing))
|
||||
throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
|
||||
if (!resolveConflict(to, original, existing)) { ++skipped; return false; }
|
||||
requireRegular(existing);
|
||||
}
|
||||
|
||||
@@ -199,7 +219,7 @@ public:
|
||||
|
||||
void run(const fs::path &from, const fs::path &to)
|
||||
{
|
||||
if (conflict != "fail" && conflict != "skip" && conflict != "replace")
|
||||
if (conflict != "fail" && conflict != "skip" && conflict != "replace" && conflict != "ask")
|
||||
throw std::runtime_error("Unknown conflict policy.");
|
||||
if (sameHost)
|
||||
{
|
||||
|
||||
+85
-11
@@ -82,8 +82,11 @@ INPUT button(unsigned index,bool down)
|
||||
{MOUSEEVENTF_MIDDLEUP,MOUSEEVENTF_MIDDLEDOWN},{MOUSEEVENTF_XUP,MOUSEEVENTF_XDOWN},{MOUSEEVENTF_XUP,MOUSEEVENTF_XDOWN}};
|
||||
input.mi.dwFlags=flags[index][down];if(index>=3)input.mi.mouseData=index==3?XBUTTON1:XBUTTON2;return input;
|
||||
}
|
||||
bool windowsKeyDown(int key){return (GetAsyncKeyState(key)&0x8000)!=0;}
|
||||
UINT keyScan(int key){return MapVirtualKeyW(UINT(key),MAPVK_VK_TO_VSC_EX);}
|
||||
bool extendedKey(UINT scan){return (scan&0xff00)==0xe000;}
|
||||
}
|
||||
InputEnvironment windowsInputEnvironment()
|
||||
InputEnvironment windowsInputEnvironment(std::function<int()> additionalHeldKey)
|
||||
{
|
||||
auto overlay=std::make_shared<ControlOverlay>();
|
||||
return {
|
||||
@@ -91,7 +94,10 @@ InputEnvironment windowsInputEnvironment()
|
||||
[]{POINT p{};GetCursorPos(&p);return p;},
|
||||
[](const INPUT &i){INPUT input=i;return SendInput(1,&input,sizeof(input))==1;},
|
||||
ordinaryDesktop,
|
||||
[]{for(int key=1;key<256;++key)if(GetAsyncKeyState(key)&0x8000)return true;return false;},
|
||||
[additionalHeldKey=std::move(additionalHeldKey)]{
|
||||
if(additionalHeldKey)if(const int key=additionalHeldKey())return key;
|
||||
for(int key=1;key<256;++key)if(windowsKeyDown(key))return key;
|
||||
return 0;},
|
||||
[]{POINT p{};GetCursorPos(&p);MONITORINFO info{sizeof(info)};
|
||||
if(GetMonitorInfoW(MonitorFromPoint(p,MONITOR_DEFAULTTONEAREST),&info))p={(info.rcMonitor.left+info.rcMonitor.right)/2,(info.rcMonitor.top+info.rcMonitor.bottom)/2};
|
||||
return p;},
|
||||
@@ -99,6 +105,55 @@ InputEnvironment windowsInputEnvironment()
|
||||
monitorDpi
|
||||
};
|
||||
}
|
||||
std::wstring heldInputName(int key)
|
||||
{
|
||||
switch(key)
|
||||
{
|
||||
case VK_LBUTTON:return L"Left mouse button";
|
||||
case VK_RBUTTON:return L"Right mouse button";
|
||||
case VK_MBUTTON:return L"Middle mouse button";
|
||||
case VK_XBUTTON1:return L"Mouse button 4";
|
||||
case VK_XBUTTON2:return L"Mouse button 5";
|
||||
case VK_MEDIA_PLAY_PAUSE:return L"Play/Pause";
|
||||
}
|
||||
if(key>0&&key<UnknownHeldInput)
|
||||
{
|
||||
if(auto name=Hotkey{0,UINT(key)}.format();!name.empty())return name;
|
||||
const auto scan=keyScan(key);
|
||||
wchar_t name[64]{};
|
||||
if(scan&&GetKeyNameTextW(LONG(((scan&0xff)<<16)|(extendedKey(scan)?1u<<24:0u)),name,int(std::size(name))))
|
||||
return name;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
std::vector<INPUT> heldInputReleases(const std::function<bool(int)> &isDown)
|
||||
{
|
||||
std::vector<INPUT> releases;
|
||||
for(int key=1;key<256;++key)
|
||||
{
|
||||
if(!isDown(key))continue;
|
||||
// Windows reports a generic modifier along with its left/right key.
|
||||
if((key==VK_SHIFT&&(isDown(VK_LSHIFT)||isDown(VK_RSHIFT)))||
|
||||
(key==VK_CONTROL&&(isDown(VK_LCONTROL)||isDown(VK_RCONTROL)))||
|
||||
(key==VK_MENU&&(isDown(VK_LMENU)||isDown(VK_RMENU))))continue;
|
||||
const auto mouse=std::find(MouseInputKeys.begin(),MouseInputKeys.end(),key);
|
||||
if(mouse!=MouseInputKeys.end())
|
||||
{
|
||||
auto release=button(unsigned(mouse-MouseInputKeys.begin()),false);
|
||||
release.mi.dwExtraInfo=inputMarker();
|
||||
releases.push_back(release);
|
||||
}
|
||||
else releases.push_back(keyboardInput(WORD(key),KEYEVENTF_KEYUP|
|
||||
(extendedKey(keyScan(key))||key==VK_MEDIA_PLAY_PAUSE?KEYEVENTF_EXTENDEDKEY:0)));
|
||||
}
|
||||
return releases;
|
||||
}
|
||||
bool resetWindowsHeldInput()
|
||||
{
|
||||
if(!ordinaryDesktop())return false;
|
||||
auto releases=heldInputReleases(windowsKeyDown);
|
||||
return releases.empty()||SendInput(UINT(releases.size()),releases.data(),sizeof(INPUT))==releases.size();
|
||||
}
|
||||
bool atEdge(POINT p,RECT r,int side)
|
||||
{return side==0?p.x<=r.left:side==1?p.x>=r.right-1:side==2?p.y<=r.top:p.y>=r.bottom-1;}
|
||||
int edgePosition(POINT p,RECT r,int side)
|
||||
@@ -140,9 +195,15 @@ bool InputRouter::move(POINT p,bool warp)
|
||||
return ok;
|
||||
}
|
||||
bool InputRouter::post(InputFrame f){return connected&&send(f);}
|
||||
bool InputRouter::held()const
|
||||
int InputRouter::heldKey()const
|
||||
{
|
||||
return std::any_of(physical.begin(),physical.end(),[](bool b){return b;})||env.held();
|
||||
const auto key=std::find(physical.begin(),physical.end(),true);
|
||||
return key!=physical.end()?int(key-physical.begin()):env.heldKey();
|
||||
}
|
||||
void InputRouter::noteHeldInput(int key)
|
||||
{
|
||||
if(!blockedKey_)log(L"LAN input: cursor handoff blocked by local input (VK "+std::to_wstring(key)+L")");
|
||||
blockedKey_=key;
|
||||
}
|
||||
void InputRouter::release()
|
||||
{
|
||||
@@ -159,7 +220,7 @@ void InputRouter::local(uint64_t now,int position)
|
||||
}
|
||||
bool InputRouter::handoff(int side,int position,uint64_t now)
|
||||
{
|
||||
if(!multi||mode_!=ControlMode::Sending||held()||side<0||side>3)return false;
|
||||
if(!multi||mode_!=ControlMode::Sending||heldKey()||side<0||side>3)return false;
|
||||
edge=side;transit=true;token=ownershipToken();
|
||||
requested=now;mode(ControlMode::Requesting);
|
||||
if(!post({InputType::Enter,token,edge,std::clamp(position,0,65535)})){cancel(now,"next computer unavailable");return false;}
|
||||
@@ -185,8 +246,10 @@ void InputRouter::tick(bool ready,uint64_t now)
|
||||
{returning=false;if(env.modeChanged)env.modeChanged(ControlMode::Local);}
|
||||
}
|
||||
connected=ready;
|
||||
const bool desktop=ready&&env.desktop();
|
||||
if(blockedKey_)blockedKey_=desktop?heldKey():0;
|
||||
if(!ready)cancel(now,"channel unavailable");
|
||||
else if(!env.desktop())cancel(now,"input desktop unavailable");
|
||||
else if(!desktop)cancel(now,"input desktop unavailable");
|
||||
else if(mode_==ControlMode::Requesting&&now-requested>1000)cancel(now,"handoff acknowledgement timed out");
|
||||
if(mode_==ControlMode::Sending&&awaitingWarp)
|
||||
{
|
||||
@@ -212,9 +275,14 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
|
||||
if(f.type==InputType::Enter)
|
||||
{
|
||||
const wchar_t *declined=nullptr;
|
||||
int blocked=0;
|
||||
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535)
|
||||
declined=L"invalid edge or position";
|
||||
else if(held())declined=L"a local key or mouse button is held";
|
||||
else if((blocked=heldKey())!=0)
|
||||
{
|
||||
noteHeldInput(blocked);
|
||||
post({InputType::Return,f.token,32768,blocked});return;
|
||||
}
|
||||
else if(returning||mode_==ControlMode::Sending||mode_==ControlMode::Receiving||
|
||||
(mode_==ControlMode::Requesting&&preferLocal))
|
||||
declined=L"another handoff is active";
|
||||
@@ -225,7 +293,7 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
|
||||
}
|
||||
if(mode_==ControlMode::Requesting)cancel(now);
|
||||
if(multi)edge=f.a^1;
|
||||
crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
|
||||
blockedKey_=0;crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
|
||||
receivedPoint=edgePoint(env.bounds(),edge,f.b);
|
||||
awaitingEntry=true;entryStarted=now;
|
||||
if(!move(receivedPoint))cancel(now,"destination cursor injection failed");
|
||||
@@ -233,8 +301,13 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
|
||||
}
|
||||
if(f.type==InputType::Accept)
|
||||
{
|
||||
if(mode_!=ControlMode::Requesting||f.token!=token||held()||(!transit&&!atEdge(env.cursor(),env.bounds(),edge))){post({InputType::Return,f.token,32768});if(f.token==token)cancel(now);return;}
|
||||
transit=false;auto r=env.bounds();anchor=env.anchor?env.anchor():POINT{(r.left+r.right)/2,(r.top+r.bottom)/2};mode(ControlMode::Sending);
|
||||
const int blocked=mode_==ControlMode::Requesting&&f.token==token?heldKey():0;
|
||||
if(mode_!=ControlMode::Requesting||f.token!=token||blocked||(!transit&&!atEdge(env.cursor(),env.bounds(),edge)))
|
||||
{
|
||||
if(blocked)noteHeldInput(blocked);
|
||||
post({InputType::Return,f.token,32768});if(f.token==token)cancel(now);return;
|
||||
}
|
||||
blockedKey_=0;transit=false;auto r=env.bounds();anchor=env.anchor?env.anchor():POINT{(r.left+r.right)/2,(r.top+r.bottom)/2};mode(ControlMode::Sending);
|
||||
warpStarted=now;
|
||||
if(!move(anchor,true))cancel(now,"source cursor parking failed");
|
||||
return;
|
||||
@@ -358,8 +431,9 @@ bool InputRouter::mouse(UINT message,const MSLLHOOKSTRUCT &m,uint64_t now,bool a
|
||||
}
|
||||
if(index>=0&&outButtons[size_t(index)]){if(!down)outButtons[size_t(index)]=false;return true;}
|
||||
if(mode_==ControlMode::Local&&connected&&allowEnter&&message==WM_MOUSEMOVE&&now>=cooldown&&
|
||||
env.desktop()&&!held()&&atEdge(m.pt,env.bounds(),edge))
|
||||
env.desktop()&&atEdge(m.pt,env.bounds(),edge))
|
||||
{
|
||||
if(const int blocked=heldKey()){noteHeldInput(blocked);return false;}
|
||||
token=ownershipToken();
|
||||
returnPoint=m.pt;requested=now;mode(ControlMode::Requesting);
|
||||
if(!post({InputType::Enter,token,edge,edgePosition(m.pt,env.bounds(),edge)}))cancel(now);
|
||||
|
||||
+15
-4
@@ -4,18 +4,25 @@
|
||||
namespace ks::lan
|
||||
{
|
||||
enum class ControlMode { Local, Requesting, Sending, Receiving };
|
||||
// The Return frame's second field was unused. Older peers still return control.
|
||||
inline constexpr int UnknownHeldInput = 256;
|
||||
inline constexpr int HeldInputCleared = -1;
|
||||
struct InputEnvironment
|
||||
{
|
||||
std::function<RECT()> bounds;
|
||||
std::function<POINT()> cursor;
|
||||
std::function<bool(const INPUT &)> inject;
|
||||
std::function<bool()> desktop;
|
||||
std::function<bool()> held;
|
||||
std::function<int()> heldKey;
|
||||
std::function<POINT()> anchor;
|
||||
std::function<void(ControlMode)> modeChanged;
|
||||
std::function<int(POINT)> dpi;
|
||||
};
|
||||
InputEnvironment windowsInputEnvironment();
|
||||
inline constexpr std::array MouseInputKeys{VK_LBUTTON,VK_RBUTTON,VK_MBUTTON,VK_XBUTTON1,VK_XBUTTON2};
|
||||
InputEnvironment windowsInputEnvironment(std::function<int()> additionalHeldKey={});
|
||||
std::wstring heldInputName(int key);
|
||||
std::vector<INPUT> heldInputReleases(const std::function<bool(int)> &isDown);
|
||||
bool resetWindowsHeldInput();
|
||||
ULONG_PTR remoteInputMarker();
|
||||
ULONG_PTR cursorWarpMarker();
|
||||
bool atEdge(POINT,RECT,int edge);
|
||||
@@ -34,6 +41,7 @@ class InputRouter
|
||||
bool awaitingWarp{},awaitingEntry{};
|
||||
uint64_t warpStarted{},entryStarted{};
|
||||
bool returning{};POINT returnTarget{};uint64_t returnStarted{};
|
||||
int blockedKey_{};
|
||||
double remainderX{},remainderY{};
|
||||
std::array<bool,256> physical{},outKeys{},remoteKeys{};
|
||||
std::array<INPUT,256> releases{};
|
||||
@@ -42,7 +50,8 @@ class InputRouter
|
||||
bool emit(INPUT);
|
||||
bool move(POINT,bool warp=false);
|
||||
bool post(InputFrame);
|
||||
bool held() const;
|
||||
int heldKey() const;
|
||||
void noteHeldInput(int key);
|
||||
void release();
|
||||
void local(uint64_t now,int position=-1);
|
||||
public:
|
||||
@@ -50,7 +59,9 @@ class InputRouter
|
||||
~InputRouter();
|
||||
void selectEdge(int side,bool prefer){edge=side;preferLocal=prefer;}
|
||||
uint32_t sessionToken()const{return token;}
|
||||
bool canHandoff()const{return mode_==ControlMode::Sending&&!held();}
|
||||
bool canHandoff()const{return mode_==ControlMode::Sending&&!heldKey();}
|
||||
int blockedKey()const{return blockedKey_;}
|
||||
void forgetHeldKeys(){physical.fill(false);}
|
||||
bool handoff(int side,int position,uint64_t now);
|
||||
void returnAt(int side,int position,uint64_t now);
|
||||
ControlMode mode()const{return mode_;}
|
||||
|
||||
+53
-1
@@ -1,8 +1,14 @@
|
||||
#pragma once
|
||||
#include "lan_input.h"
|
||||
#include <map>
|
||||
#include <optional>
|
||||
namespace ks::lan
|
||||
{
|
||||
struct HandoffBlock
|
||||
{
|
||||
std::string peer; // Empty for this PC.
|
||||
int key{};
|
||||
};
|
||||
// The physical input source routes directly to the current destination. A
|
||||
// destination only reports edge crossings; it never relays injected key events.
|
||||
class InputMesh
|
||||
@@ -13,7 +19,17 @@ class InputMesh
|
||||
std::map<std::string,uint64_t> ready;
|
||||
std::function<bool(const std::string &,InputFrame)> send;
|
||||
uint64_t activeGeneration{},routeRevision{};
|
||||
struct Rejection {uint32_t token;uint64_t generation;int key;};
|
||||
std::map<std::string,Rejection> rejectedPeers;
|
||||
std::optional<std::pair<std::string,Rejection>> remoteBlock;
|
||||
InputRouter router;
|
||||
bool sendActive(InputFrame frame)
|
||||
{
|
||||
if(active.empty()||!ready.contains(active)||!send(active,frame))return false;
|
||||
if(frame.type==InputType::Return&&frame.b>0)
|
||||
rejectedPeers.insert_or_assign(active,Rejection{frame.token,ready.at(active),frame.b});
|
||||
return true;
|
||||
}
|
||||
std::string neighbor(const std::string &from,int side)const
|
||||
{
|
||||
POINT p{};if(from!=local){auto found=positions.find(from);if(found==positions.end())return {};p=found->second;}
|
||||
@@ -31,10 +47,17 @@ class InputMesh
|
||||
InputMesh(std::string id,InputEnvironment environment,std::map<std::string,POINT> layout,
|
||||
std::function<bool(const std::string &,InputFrame)> sender)
|
||||
:local(std::move(id)),env(std::move(environment)),positions(std::move(layout)),send(std::move(sender)),
|
||||
router(env,[this](InputFrame f){return !active.empty()&&ready.contains(active)&&send(active,f);},1,true,true){}
|
||||
router(env,[this](InputFrame f){return sendActive(f);},1,true,true){}
|
||||
ControlMode mode()const{return router.mode();}
|
||||
uint64_t revision()const{return router.revision()+routeRevision;}
|
||||
const std::string &peer()const{return active;}
|
||||
HandoffBlock handoffBlock()const
|
||||
{
|
||||
if(router.blockedKey())return {{},router.blockedKey()};
|
||||
if(remoteBlock)return {remoteBlock->first,remoteBlock->second.key};
|
||||
return {};
|
||||
}
|
||||
void forgetHeldKeys(){router.forgetHeldKeys();}
|
||||
void cancel(uint64_t now){router.cancel(now);}
|
||||
void tick(std::map<std::string,uint64_t> connections,uint64_t now)
|
||||
{
|
||||
@@ -44,10 +67,38 @@ class InputMesh
|
||||
if(connected&&activeGeneration!=ready.at(active)){router.cancel(now,"peer reconnected");activeGeneration=ready.at(active);}
|
||||
router.tick(connected,now);
|
||||
}
|
||||
const auto sameConnection=[this](const std::string &peer,const Rejection &rejection){
|
||||
auto connection=ready.find(peer);
|
||||
return connection!=ready.end()&&connection->second==rejection.generation;
|
||||
};
|
||||
if(remoteBlock&&!sameConnection(remoteBlock->first,remoteBlock->second))remoteBlock.reset();
|
||||
const int held=router.blockedKey();
|
||||
for(auto it=rejectedPeers.begin();it!=rejectedPeers.end();)
|
||||
{
|
||||
auto &[peer,rejection]=*it;
|
||||
if(!sameConnection(peer,rejection)){it=rejectedPeers.erase(it);continue;}
|
||||
if(held!=rejection.key&&send(peer,{InputType::Return,rejection.token,32768,held?held:HeldInputCleared}))
|
||||
rejection.key=held;
|
||||
if(!rejection.key)it=rejectedPeers.erase(it);
|
||||
else ++it;
|
||||
}
|
||||
}
|
||||
void receive(const std::string &peer,const InputFrame &f,uint64_t now,bool allowEnter=true)
|
||||
{
|
||||
if(!ready.contains(peer)||!positions.contains(peer))return;
|
||||
if(f.type==InputType::Return)
|
||||
{
|
||||
const bool held=f.b>0&&f.b<=UnknownHeldInput;
|
||||
if(remoteBlock&&remoteBlock->first==peer&&remoteBlock->second.token==f.token)
|
||||
{
|
||||
// These updates belong to a completed request, never the current owner.
|
||||
if(f.b==HeldInputCleared)remoteBlock.reset();
|
||||
else if(held)remoteBlock->second.key=f.b;
|
||||
return;
|
||||
}
|
||||
if(held&&active==peer&&router.mode()==ControlMode::Requesting&&router.sessionToken()==f.token)
|
||||
remoteBlock=std::pair{peer,Rejection{f.token,ready.at(peer),f.b}};
|
||||
}
|
||||
if(f.type==InputType::Enter){
|
||||
if(!allowEnter||f.a<0||f.a>3||(router.mode()!=ControlMode::Local&&active!=peer)){
|
||||
if(!allowEnter)log(L"LAN input: declined cursor handoff during a local text operation or shortcut capture");
|
||||
@@ -66,6 +117,7 @@ class InputMesh
|
||||
router.handoff(f.a,f.b,now);return;
|
||||
}
|
||||
router.receive(f,now);
|
||||
if(router.mode()==ControlMode::Sending||router.mode()==ControlMode::Receiving)remoteBlock.reset();
|
||||
}
|
||||
bool keyboard(const KBDLLHOOKSTRUCT &key,bool down,uint64_t now){return router.keyboard(key,down,now);}
|
||||
bool mouse(UINT message,const MSLLHOOKSTRUCT &mouse,uint64_t now,bool allowEnter=true)
|
||||
|
||||
+52
-11
@@ -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";
|
||||
|
||||
+205
-13
@@ -1,4 +1,5 @@
|
||||
#include "platform.h"
|
||||
#include "windows_command_line.h"
|
||||
#include "../vendor/json.hpp"
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
@@ -17,6 +18,7 @@
|
||||
#include <shldisp.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <wincrypt.h>
|
||||
#include <winhttp.h>
|
||||
#include <wrl/client.h>
|
||||
|
||||
namespace ks
|
||||
@@ -289,7 +291,7 @@ bool ownsClipboard(HWND window)
|
||||
return it->second;
|
||||
});
|
||||
}
|
||||
std::wstring processName(HWND window)
|
||||
std::wstring processImagePath(HWND window)
|
||||
{
|
||||
DWORD pid{};
|
||||
GetWindowThreadProcessId(window, &pid);
|
||||
@@ -300,7 +302,38 @@ std::wstring processName(HWND window)
|
||||
DWORD n = 32768;
|
||||
BOOL ok = QueryFullProcessImageNameW(h, 0, path, &n);
|
||||
CloseHandle(h);
|
||||
return ok ? std::filesystem::path(std::wstring(path, n)).stem().wstring() : L"";
|
||||
return ok ? std::wstring(path, n) : L"";
|
||||
}
|
||||
std::wstring processName(HWND window)
|
||||
{
|
||||
return std::filesystem::path(processImagePath(window)).stem().wstring();
|
||||
}
|
||||
std::wstring shortcutTextControlClass(HWND window)
|
||||
{
|
||||
wchar_t name[256]{};
|
||||
if (!GetClassNameW(window, name, std::size(name))) return {};
|
||||
const auto kind = lower(name);
|
||||
if ((kind != L"edit" && !kind.starts_with(L"richedit")) || !IsWindowEnabled(window) ||
|
||||
(GetWindowLongPtrW(window, GWL_STYLE) & (ES_READONLY | ES_PASSWORD))) return {};
|
||||
return name;
|
||||
}
|
||||
HWND findShortcutTextControl(HWND window, std::wstring_view controlClass, int controlId)
|
||||
{
|
||||
if (!window) return nullptr;
|
||||
struct Search { std::wstring_view kind; int id; HWND target{}; } search{controlClass, controlId};
|
||||
EnumChildWindows(window, [](HWND candidate, LPARAM context) -> BOOL {
|
||||
auto &state = *reinterpret_cast<Search *>(context);
|
||||
if (!IsWindowVisible(candidate) || GetDlgCtrlID(candidate) != state.id || shortcutTextControlClass(candidate) != state.kind)
|
||||
return TRUE;
|
||||
if (state.target)
|
||||
{
|
||||
state.target = nullptr;
|
||||
return FALSE;
|
||||
}
|
||||
state.target = candidate;
|
||||
return TRUE;
|
||||
}, reinterpret_cast<LPARAM>(&search));
|
||||
return search.target;
|
||||
}
|
||||
std::wstring mouseApplicationName(HWND window)
|
||||
{
|
||||
@@ -317,7 +350,9 @@ std::wstring mouseApplicationName(HWND window)
|
||||
}, reinterpret_cast<LPARAM>(&hosted));
|
||||
return hosted.empty() ? name : hosted;
|
||||
}
|
||||
bool launchThroughExplorer(const std::wstring &path)
|
||||
namespace
|
||||
{
|
||||
bool shellOpenThroughExplorer(const std::wstring &target, const std::wstring &arguments, const std::wstring &directory)
|
||||
{
|
||||
HANDLE token{};
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return false;
|
||||
@@ -330,7 +365,9 @@ bool launchThroughExplorer(const std::wstring &path)
|
||||
{
|
||||
SHELLEXECUTEINFOW launch{sizeof(launch)};
|
||||
launch.fMask = SEE_MASK_FLAG_NO_UI;
|
||||
launch.lpFile = path.c_str();
|
||||
launch.lpFile = target.c_str();
|
||||
launch.lpParameters = arguments.empty() ? nullptr : arguments.c_str();
|
||||
launch.lpDirectory = directory.empty() ? nullptr : directory.c_str();
|
||||
launch.nShow = SW_SHOWNORMAL;
|
||||
return ShellExecuteExW(&launch) != FALSE;
|
||||
}
|
||||
@@ -361,8 +398,12 @@ bool launchThroughExplorer(const std::wstring &path)
|
||||
hr = browser->QueryActiveShellView(&viewRaw);
|
||||
std::unique_ptr<IShellView, decltype(release)> view(viewRaw, release);
|
||||
if (FAILED(hr) || !view) return false;
|
||||
IDispatch *backgroundRaw{};
|
||||
hr = view->GetItemObject(SVGIO_BACKGROUND, IID_IDispatch, reinterpret_cast<void **>(&backgroundRaw));
|
||||
std::unique_ptr<IDispatch, decltype(release)> background(backgroundRaw, release);
|
||||
if (FAILED(hr) || !background) return false;
|
||||
IShellFolderViewDual *folderRaw{};
|
||||
hr = view->GetItemObject(SVGIO_BACKGROUND, IID_IShellFolderViewDual, reinterpret_cast<void **>(&folderRaw));
|
||||
hr = background->QueryInterface(IID_IShellFolderViewDual, reinterpret_cast<void **>(&folderRaw));
|
||||
std::unique_ptr<IShellFolderViewDual, decltype(release)> folder(folderRaw, release);
|
||||
if (FAILED(hr) || !folder) return false;
|
||||
IDispatch *applicationRaw{};
|
||||
@@ -373,12 +414,126 @@ bool launchThroughExplorer(const std::wstring &path)
|
||||
hr = application->QueryInterface(IID_IShellDispatch2, reinterpret_cast<void **>(&shellRaw));
|
||||
std::unique_ptr<IShellDispatch2, decltype(release)> shell(shellRaw, release);
|
||||
if (FAILED(hr) || !shell) return false;
|
||||
BSTR executable = SysAllocString(path.c_str());
|
||||
if (!executable) return false;
|
||||
hr = shell->ShellExecute(executable, empty, empty, empty, empty);
|
||||
SysFreeString(executable);
|
||||
std::unique_ptr<OLECHAR, decltype(&SysFreeString)> executable(SysAllocString(target.c_str()), SysFreeString);
|
||||
std::unique_ptr<OLECHAR, decltype(&SysFreeString)> workingDirectory(SysAllocString(directory.c_str()), SysFreeString);
|
||||
std::unique_ptr<OLECHAR, decltype(&SysFreeString)> parameters(SysAllocString(arguments.c_str()), SysFreeString);
|
||||
if (!executable || !workingDirectory || !parameters) return false;
|
||||
VARIANT location{}, shown{}, args{};
|
||||
location.vt = VT_BSTR;
|
||||
location.bstrVal = workingDirectory.get();
|
||||
shown.vt = VT_I4;
|
||||
shown.lVal = SW_SHOWNORMAL;
|
||||
args.vt = VT_BSTR;
|
||||
args.bstrVal = parameters.get();
|
||||
hr = shell->ShellExecute(executable.get(), args, location, empty, shown);
|
||||
return SUCCEEDED(hr);
|
||||
}
|
||||
|
||||
std::filesystem::path shortcutKnownFolder(REFKNOWNFOLDERID folder)
|
||||
{
|
||||
PWSTR raw{};
|
||||
if (FAILED(SHGetKnownFolderPath(folder, 0, nullptr, &raw))) return {};
|
||||
std::unique_ptr<wchar_t, decltype(&CoTaskMemFree)> path(raw, CoTaskMemFree);
|
||||
return std::filesystem::path(path.get());
|
||||
}
|
||||
|
||||
std::filesystem::path chromeUserData()
|
||||
{
|
||||
const auto local = shortcutKnownFolder(FOLDERID_LocalAppData);
|
||||
return local.empty() ? local : local / L"Google/Chrome/User Data";
|
||||
}
|
||||
|
||||
std::filesystem::path chromeExecutable()
|
||||
{
|
||||
constexpr wchar_t key[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe";
|
||||
std::error_code ec;
|
||||
for (const auto hive : {HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE})
|
||||
{
|
||||
wchar_t path[32768]{};
|
||||
DWORD bytes = sizeof(path);
|
||||
if (RegGetValueW(hive, key, nullptr, RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ, nullptr, path, &bytes) == ERROR_SUCCESS)
|
||||
{
|
||||
const std::filesystem::path candidate(path);
|
||||
if (candidate.is_absolute() && lower(candidate.filename().wstring()) == L"chrome.exe" &&
|
||||
std::filesystem::is_regular_file(candidate, ec)) return candidate;
|
||||
}
|
||||
}
|
||||
for (const auto *folder : {&FOLDERID_LocalAppData, &FOLDERID_ProgramFiles, &FOLDERID_ProgramFilesX86})
|
||||
{
|
||||
const auto base = shortcutKnownFolder(*folder);
|
||||
if (base.empty()) continue;
|
||||
const auto candidate = (base / L"Google/Chrome/Application/chrome.exe").make_preferred();
|
||||
if (std::filesystem::is_regular_file(candidate, ec)) return candidate;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool launchThroughExplorer(const std::wstring &path)
|
||||
{
|
||||
return shellOpenThroughExplorer(path, {}, std::filesystem::path(path).parent_path().wstring());
|
||||
}
|
||||
|
||||
bool validShortcutUrl(const std::wstring &url)
|
||||
{
|
||||
if (url.empty() || url.size() > 16384 || std::any_of(url.begin(), url.end(), [](wchar_t ch) {
|
||||
return ch <= L' ' || ch == L'\x7f' || ch == L'\\' || ch == L'"';
|
||||
})) return false;
|
||||
URL_COMPONENTSW parts{};
|
||||
parts.dwStructSize = sizeof(parts);
|
||||
parts.dwHostNameLength = static_cast<DWORD>(-1);
|
||||
return WinHttpCrackUrl(url.c_str(), static_cast<DWORD>(url.size()), 0, &parts) &&
|
||||
(parts.nScheme == INTERNET_SCHEME_HTTP || parts.nScheme == INTERNET_SCHEME_HTTPS) && parts.dwHostNameLength;
|
||||
}
|
||||
|
||||
bool validChromeProfileName(std::wstring_view name)
|
||||
{
|
||||
return !name.empty() && name.size() <= 255 && name.back() != L'.' && name.back() != L' ' &&
|
||||
name.find_first_of(L"<>:\"/\\|?*") == name.npos && std::none_of(name.begin(), name.end(), [](wchar_t ch) {
|
||||
return ch < L' ';
|
||||
});
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::wstring, std::wstring>> chromeShortcutProfiles()
|
||||
{
|
||||
std::vector<std::pair<std::wstring, std::wstring>> profiles;
|
||||
const auto root = chromeUserData();
|
||||
if (root.empty()) return profiles;
|
||||
try
|
||||
{
|
||||
const auto state = nlohmann::json::parse(readFile(root / L"Local State", 16 * 1024 * 1024));
|
||||
const auto &cache = state.at("profile").at("info_cache");
|
||||
if (!cache.is_object()) return profiles;
|
||||
for (const auto &[id, entry] : cache.items())
|
||||
{
|
||||
const auto directory = wide(id);
|
||||
std::error_code ec;
|
||||
if (!validChromeProfileName(directory) || !entry.is_object() ||
|
||||
!std::filesystem::is_directory(root / directory, ec)) continue;
|
||||
auto display = entry.find("name");
|
||||
const auto name = display != entry.end() && display->is_string() ? wide(display->get<std::string>()) : directory;
|
||||
profiles.emplace_back(directory, name.empty() ? directory : name);
|
||||
}
|
||||
}
|
||||
catch (const std::exception &) {} // Chrome may be uninstalled or may be rewriting Local State.
|
||||
return profiles;
|
||||
}
|
||||
|
||||
bool openShortcutUrl(const CustomShortcut &rule)
|
||||
{
|
||||
if (rule.browser == ShortcutBrowser::Default) return shellOpenThroughExplorer(rule.url, {}, {});
|
||||
const auto path = rule.browser == ShortcutBrowser::Chrome ? chromeExecutable() : std::filesystem::path(rule.executable);
|
||||
if (path.empty()) return false;
|
||||
auto arguments = quoteWindowsArgument(rule.url);
|
||||
if (rule.browser == ShortcutBrowser::Chrome && !rule.chromeProfile.empty())
|
||||
{
|
||||
const auto root = chromeUserData();
|
||||
std::error_code ec;
|
||||
if (root.empty() || !std::filesystem::is_directory(root / rule.chromeProfile, ec)) return false;
|
||||
arguments = quoteWindowsArgument(L"--profile-directory=" + rule.chromeProfile) + L" " + arguments;
|
||||
}
|
||||
return shellOpenThroughExplorer(path.wstring(), arguments, path.parent_path().wstring());
|
||||
}
|
||||
bool clipboardHasImage()
|
||||
{
|
||||
return IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
|
||||
@@ -676,9 +831,10 @@ bool needsSelectionDelay(HWND target)
|
||||
{
|
||||
const auto name = lower(processName(target));
|
||||
return name == L"ms-teams" || name == L"msedgewebview2" ||
|
||||
name == L"chrome" || name == L"msedge" || name == L"chatgpt" || name == L"codex";
|
||||
name == L"chrome" || name == L"msedge" || name == L"chatgpt" ||
|
||||
name == L"codex" || name == L"claude";
|
||||
}
|
||||
bool selectPrevious(size_t count, const std::function<bool()> &valid)
|
||||
bool selectPrevious(size_t count, const std::function<bool()> &valid, bool forcePacing)
|
||||
{
|
||||
if (count > 100000)
|
||||
return false;
|
||||
@@ -686,9 +842,10 @@ bool selectPrevious(size_t count, const std::function<bool()> &valid)
|
||||
// Shift+Left events can all use the same caret position and select only one
|
||||
// character. Give each change time to settle before sending the next one.
|
||||
const auto target = GetForegroundWindow();
|
||||
const bool paced = forcePacing || needsSelectionDelay(target);
|
||||
diagnosticEvent(L"SelectPrevious requested=" + std::to_wstring(count) +
|
||||
L" mode=" + (needsSelectionDelay(target) ? std::wstring(L"paced-25ms") : std::wstring(L"batch")));
|
||||
if (needsSelectionDelay(target))
|
||||
(paced ? L" mode=paced-25ms" : L" mode=batch"));
|
||||
if (paced)
|
||||
{
|
||||
for (size_t i = 0; i < count; ++i)
|
||||
{
|
||||
@@ -899,6 +1056,41 @@ void setLoggingEnabled(bool enabled)
|
||||
if (!enabled)
|
||||
diagnosticBuffer.clear();
|
||||
}
|
||||
std::optional<Bytes> readActiveLogTail(bool previous,size_t byteLimit)
|
||||
{
|
||||
std::lock_guard lock(logGate);
|
||||
auto path=logDirectory()/logFilename;
|
||||
if(previous) path+=L".1";
|
||||
const auto raw=CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(raw==INVALID_HANDLE_VALUE)
|
||||
{
|
||||
const auto error=GetLastError();
|
||||
if(error==ERROR_FILE_NOT_FOUND || error==ERROR_PATH_NOT_FOUND) return {};
|
||||
throw std::runtime_error("Cannot open the diagnostic log");
|
||||
}
|
||||
const std::unique_ptr<void,decltype(&CloseHandle)> file(raw,CloseHandle);
|
||||
LARGE_INTEGER size{};
|
||||
if(!GetFileSizeEx(raw,&size) || size.QuadPart<0) throw std::runtime_error("Cannot measure the diagnostic log");
|
||||
const auto limit=std::min<uint64_t>(byteLimit,2*1024*1024);
|
||||
if(!limit || !size.QuadPart) return Bytes{};
|
||||
const auto offset=std::max<int64_t>(0,size.QuadPart-static_cast<int64_t>(limit));
|
||||
LARGE_INTEGER position{};
|
||||
position.QuadPart=offset?offset-1:0;
|
||||
if(!SetFilePointerEx(raw,position,nullptr,FILE_BEGIN)) throw std::runtime_error("Cannot seek in the diagnostic log");
|
||||
Bytes contents(static_cast<size_t>(size.QuadPart-position.QuadPart));
|
||||
DWORD read{};
|
||||
if(!ReadFile(raw,contents.data(),static_cast<DWORD>(contents.size()),&read,nullptr))
|
||||
throw std::runtime_error("Cannot read the diagnostic log");
|
||||
contents.resize(read);
|
||||
if(offset && !contents.empty())
|
||||
{
|
||||
const auto newline=std::find(contents.begin(),contents.end(),'\n');
|
||||
contents.erase(contents.begin(),newline==contents.end()?newline:std::next(newline));
|
||||
}
|
||||
return contents;
|
||||
}
|
||||
|
||||
std::wstring readDiagnosticLog(bool previous)
|
||||
{
|
||||
std::lock_guard lock(logGate);
|
||||
|
||||
+9
-1
@@ -49,8 +49,15 @@ bool ownsClipboard(HWND);
|
||||
bool webViewDescendant(DWORD owner, DWORD host,
|
||||
const std::function<std::optional<std::pair<DWORD, std::wstring>>(DWORD)> &read);
|
||||
std::wstring processName(HWND);
|
||||
std::wstring processImagePath(HWND);
|
||||
std::wstring shortcutTextControlClass(HWND);
|
||||
HWND findShortcutTextControl(HWND, std::wstring_view controlClass, int controlId);
|
||||
std::wstring mouseApplicationName(HWND);
|
||||
bool launchThroughExplorer(const std::wstring &);
|
||||
bool validShortcutUrl(const std::wstring &);
|
||||
bool validChromeProfileName(std::wstring_view);
|
||||
std::vector<std::pair<std::wstring, std::wstring>> chromeShortcutProfiles();
|
||||
bool openShortcutUrl(const CustomShortcut &);
|
||||
enum class ClipboardRead { All, Selection, WithoutImages };
|
||||
bool clipboardHasImage();
|
||||
Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024,
|
||||
@@ -75,7 +82,7 @@ ULONG_PTR inputMarker();
|
||||
bool ownKeyboardInput(const KBDLLHOOKSTRUCT &);
|
||||
INPUT keyboardInput(WORD key, DWORD flags = 0);
|
||||
bool needsSelectionDelay(HWND);
|
||||
bool selectPrevious(size_t count, const std::function<bool()> &valid);
|
||||
bool selectPrevious(size_t count, const std::function<bool()> &valid, bool forcePacing = false);
|
||||
bool modifiersReleased();
|
||||
void releaseModifiers();
|
||||
std::filesystem::path dataDirectory();
|
||||
@@ -107,5 +114,6 @@ void expireDiagnostics(ULONGLONG now);
|
||||
void diagnosticEvent(const std::wstring &message, bool problem = false);
|
||||
void diagnosticOperation(const std::string &json);
|
||||
std::wstring readDiagnosticLog(bool previous);
|
||||
std::optional<Bytes> readActiveLogTail(bool previous,size_t byteLimit);
|
||||
void clearDiagnosticLog(bool previous);
|
||||
} // namespace ks
|
||||
@@ -207,6 +207,36 @@ void validateSettings(const Settings &s)
|
||||
std::vector<std::wstring> keys{s.toggle, s.casing, s.translit, s.undo, s.clipboard, s.screenshot};
|
||||
if (s.filesHotkey) keys.push_back(*s.filesHotkey);
|
||||
keys.insert(keys.end(), s.direct.begin(), s.direct.end());
|
||||
if (s.customShortcuts.size() > 100)
|
||||
throw std::runtime_error("You can configure up to 100 custom shortcuts.");
|
||||
for (const auto &rule : s.customShortcuts)
|
||||
{
|
||||
if (rule.name.size() > 128 || rule.name.find_first_not_of(L" \t\r\n") == std::wstring::npos)
|
||||
throw std::runtime_error("Enter a name of up to 128 characters for the custom shortcut.");
|
||||
const auto key = Hotkey::parse(rule.shortcut);
|
||||
if (!key || !key->key)
|
||||
throw std::runtime_error("Enter a key combination for the custom shortcut.");
|
||||
if (rule.action != CustomShortcutAction::OpenUrl || rule.browser == ShortcutBrowser::Other)
|
||||
{
|
||||
const std::filesystem::path path(rule.executable);
|
||||
if (rule.executable.size() > 32700 || rule.executable.find_first_of(L"\r\n\"") != std::wstring::npos ||
|
||||
rule.executable.find(L'\0') != std::wstring::npos || !path.is_absolute() || lower(path.extension().wstring()) != L".exe")
|
||||
throw std::runtime_error("Choose a program executable (.exe) for the custom shortcut.");
|
||||
}
|
||||
if (rule.action == CustomShortcutAction::OpenUrl)
|
||||
{
|
||||
if (!validShortcutUrl(rule.url)) throw std::runtime_error("Enter a valid HTTP or HTTPS URL.");
|
||||
if (rule.browser != ShortcutBrowser::Default && rule.browser != ShortcutBrowser::Chrome && rule.browser != ShortcutBrowser::Other)
|
||||
throw std::runtime_error("Choose a browser for the URL shortcut.");
|
||||
if (rule.browser == ShortcutBrowser::Chrome && !rule.chromeProfile.empty() && !validChromeProfileName(rule.chromeProfile))
|
||||
throw std::runtime_error("Choose a valid Chrome profile.");
|
||||
}
|
||||
if (rule.action == CustomShortcutAction::SendText &&
|
||||
(rule.controlClass.empty() || rule.controlClass.size() > 255 || rule.text.empty() ||
|
||||
rule.text.size() > 32768 || rule.text.find(L'\0') != std::wstring::npos))
|
||||
throw std::runtime_error("Choose a target text field and enter up to 32,768 characters to insert.");
|
||||
if (rule.enabled) keys.push_back(rule.shortcut);
|
||||
}
|
||||
for (auto &text : keys)
|
||||
{
|
||||
auto key = Hotkey::parse(text);
|
||||
@@ -373,6 +403,40 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
|
||||
s.clipboard = str(j, "clipboardHotkey", s.clipboard);
|
||||
s.screenshot = str(j, "screenshotHotkey", s.screenshot);
|
||||
if (j.contains("filesHotkey")) s.filesHotkey = wide(j.at("filesHotkey").get<std::string>());
|
||||
if (j.contains("customShortcuts"))
|
||||
{
|
||||
const auto &rules = j.at("customShortcuts");
|
||||
if (!rules.is_array()) throw std::runtime_error("Invalid custom shortcut list.");
|
||||
for (const auto &rule : rules)
|
||||
{
|
||||
const auto action = rule.value("action", "launchApp");
|
||||
CustomShortcut shortcut{str(rule, "name", L""), str(rule, "shortcut", L""),
|
||||
str(rule, "executable", L""), rule.value("enabled", true)};
|
||||
if (action == "sendText")
|
||||
{
|
||||
shortcut.action = CustomShortcutAction::SendText;
|
||||
shortcut.controlClass = str(rule, "controlClass", L"");
|
||||
shortcut.text = str(rule, "text", L"");
|
||||
shortcut.controlId = rule.value("controlId", 0);
|
||||
}
|
||||
else if (action == "openUrl")
|
||||
{
|
||||
shortcut.action = CustomShortcutAction::OpenUrl;
|
||||
shortcut.url = str(rule, "url", L"");
|
||||
const auto browser = rule.value("browser", "default");
|
||||
if (browser == "chrome")
|
||||
{
|
||||
shortcut.browser = ShortcutBrowser::Chrome;
|
||||
shortcut.chromeProfile = str(rule, "chromeProfile", L"");
|
||||
}
|
||||
else if (browser == "other") shortcut.browser = ShortcutBrowser::Other;
|
||||
else if (browser != "default") throw std::runtime_error("Unknown shortcut browser.");
|
||||
}
|
||||
else if (action == "launchApp") shortcut.newInstance = rule.value("newInstance", false);
|
||||
else throw std::runtime_error("Unknown custom shortcut action.");
|
||||
s.customShortcuts.push_back(std::move(shortcut));
|
||||
}
|
||||
}
|
||||
s.screenshotAutoOpenEditor = j.value("screenshotAutoOpenEditor", false);
|
||||
if (j.contains("layouts"))
|
||||
{
|
||||
@@ -533,6 +597,37 @@ Bytes encodeSettings(const Settings &s)
|
||||
{"screenshotHotkey", utf8(s.screenshot)},
|
||||
{"screenshotAutoOpenEditor", s.screenshotAutoOpenEditor}};
|
||||
if (s.filesHotkey) j["filesHotkey"] = utf8(*s.filesHotkey);
|
||||
if (!s.customShortcuts.empty())
|
||||
{
|
||||
auto &rules = j["customShortcuts"] = Json::array();
|
||||
for (const auto &rule : s.customShortcuts)
|
||||
{
|
||||
rules.push_back({{"name", utf8(rule.name)}, {"shortcut", utf8(rule.shortcut)},
|
||||
{"executable", utf8(rule.executable)}, {"enabled", rule.enabled}});
|
||||
auto &item = rules.back();
|
||||
if (rule.action == CustomShortcutAction::SendText)
|
||||
{
|
||||
item["action"] = "sendText";
|
||||
item["controlClass"] = utf8(rule.controlClass);
|
||||
item["controlId"] = rule.controlId;
|
||||
item["text"] = utf8(rule.text);
|
||||
}
|
||||
else if (rule.action == CustomShortcutAction::OpenUrl)
|
||||
{
|
||||
item["action"] = "openUrl";
|
||||
item["url"] = utf8(rule.url);
|
||||
item["browser"] = rule.browser == ShortcutBrowser::Chrome ? "chrome" :
|
||||
rule.browser == ShortcutBrowser::Other ? "other" : "default";
|
||||
if (rule.browser == ShortcutBrowser::Chrome && !rule.chromeProfile.empty())
|
||||
item["chromeProfile"] = utf8(rule.chromeProfile);
|
||||
}
|
||||
else
|
||||
{
|
||||
item["action"] = "launchApp";
|
||||
item["newInstance"] = rule.newInstance;
|
||||
}
|
||||
}
|
||||
}
|
||||
j["layouts"] = Json::array();
|
||||
j["appLanguageSets"] = Json::object();
|
||||
for (const auto &[name, set] : s.appLanguageSets)
|
||||
|
||||
@@ -313,6 +313,7 @@ void preserveMissingSettings(Json &profile, const Json &fallback)
|
||||
Bytes sharedSyncSettings(const Settings &s)
|
||||
{
|
||||
auto j = parse(encodeSettings(s));
|
||||
j.erase("customShortcuts"); // Executable paths and target control identifiers belong to this PC.
|
||||
// Windows may enumerate the same installed layouts in a different order on
|
||||
// another PC. Binding order is not user intent (unlike the layout cycle).
|
||||
auto &bindings = j["layoutHotkeys"];
|
||||
|
||||
+228
-195
@@ -10,6 +10,7 @@
|
||||
#include "ui_geometry.h"
|
||||
#include "diagnostics.h"
|
||||
#include "google_drive.h"
|
||||
#include "update.h"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
@@ -480,6 +481,62 @@ HWND makeWindow(App &app, const wchar_t *cls, const wchar_t *title, WNDPROC proc
|
||||
SetPropW(w, L"Dpi", (HANDLE)(UINT_PTR)GetDpiForWindow(w));
|
||||
return w;
|
||||
}
|
||||
#ifndef KS_RESIDENT_APP
|
||||
constexpr int ModalFooterHeight = 50;
|
||||
|
||||
LRESULT CALLBACK settingsModalPaletteProc(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR data)
|
||||
{
|
||||
auto *palette = reinterpret_cast<WindowPalette *>(data);
|
||||
if (msg == WM_ERASEBKGND)
|
||||
{
|
||||
const auto dc = reinterpret_cast<HDC>(wp);
|
||||
RECT area{};
|
||||
GetClientRect(w, &area);
|
||||
FillRect(dc, &area, GetSysColorBrush(COLOR_WINDOW));
|
||||
area.top = std::max(0L, area.bottom - scale(w, ModalFooterHeight));
|
||||
FillRect(dc, &area, palette->brush());
|
||||
fillSurface(dc, {area.left, area.top, area.right, area.top + 1}, palette->edge());
|
||||
return 1;
|
||||
}
|
||||
if (msg == WM_CTLCOLORSTATIC)
|
||||
{
|
||||
const auto dc = reinterpret_cast<HDC>(wp);
|
||||
SetBkColor(dc, GetSysColor(COLOR_WINDOW));
|
||||
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_WINDOW));
|
||||
}
|
||||
if (msg == WM_SYSCOLORCHANGE || msg == WM_THEMECHANGED || msg == WM_SETTINGCHANGE || msg == WM_DWMCOLORIZATIONCOLORCHANGED)
|
||||
{
|
||||
palette->refresh();
|
||||
RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN);
|
||||
}
|
||||
if (msg == WM_NCDESTROY)
|
||||
{
|
||||
RemoveWindowSubclass(w, settingsModalPaletteProc, id);
|
||||
delete palette;
|
||||
}
|
||||
return DefSubclassProc(w, msg, wp, lp);
|
||||
}
|
||||
|
||||
HWND makeSettingsModal(App &app, HWND owner, const wchar_t *cls, const wchar_t *title, WNDPROC proc, int width, int height)
|
||||
{
|
||||
auto palette = std::make_unique<WindowPalette>();
|
||||
palette->refresh();
|
||||
const auto w = makeWindow(app, cls, title, proc, width, height, 0, false, owner);
|
||||
windowLayoutState(w)->fixedClient = true;
|
||||
if (SetWindowSubclass(w, settingsModalPaletteProc, 1, reinterpret_cast<DWORD_PTR>(palette.get()))) palette.release();
|
||||
return w;
|
||||
}
|
||||
|
||||
void settingsModalActions(HWND w, int width, int height, const wchar_t *accept, int extraId = 0, const wchar_t *extra = nullptr)
|
||||
{
|
||||
constexpr int margin = 22, acceptWidth = 120, cancelWidth = 90, gap = 12;
|
||||
const int y = height - (ModalFooterHeight + 28) / 2;
|
||||
const int x = width - margin - acceptWidth;
|
||||
if (extra) button(w, extra, extraId, margin, y, cancelWidth);
|
||||
button(w, L"Cancel", IDCANCEL, x - gap - cancelWidth, y, cancelWidth);
|
||||
control(w, L"BUTTON", accept, WS_TABSTOP | WS_GROUP | BS_DEFPUSHBUTTON, IDOK, x, y, acceptWidth, 28);
|
||||
}
|
||||
#endif
|
||||
void resizeForDpi(HWND w, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
// Creation may send WM_DPICHANGED before controls and the original font exist.
|
||||
@@ -1209,7 +1266,10 @@ 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 CustomShortcutsPage = 21;
|
||||
constexpr int CustomShortcutList = 780, CustomShortcutAdd = 781, CustomShortcutEdit = 782;
|
||||
constexpr int ChatContacts = 710, ChatLayouts = 711, ChatProfileStatus = 712, ChatRemoveProfile = 713, ChatSearch = 714;
|
||||
constexpr int ClipboardExcludedApps = 243, ClipboardAppName = 244, ClipboardAddApp = 245,
|
||||
ClipboardRemoveApp = 246, ClipboardAppPicker = 247;
|
||||
constexpr UINT AppWindowPicked = WM_APP + 78;
|
||||
@@ -1253,6 +1313,8 @@ 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},
|
||||
{"custom-shortcuts", L"Custom shortcuts", L"Assign global keyboard shortcuts to actions in other apps.", ShortcutsPage},
|
||||
};
|
||||
constexpr wchar_t SettingsWindowFile[] = L"configurator-window.json";
|
||||
struct SettingsWindowState
|
||||
@@ -1352,6 +1414,9 @@ struct SettingsView
|
||||
SIZE mouseProfileCheckSize{};
|
||||
unsigned mouseEvents{}, rawMouseEvents{};
|
||||
bool rawMouseRegistered{};
|
||||
std::vector<std::wstring> chatKeys;
|
||||
int chatSelection = -1;
|
||||
bool updatingChatContacts{};
|
||||
SnippetView snippets;
|
||||
HWND clipboardPickerOutline{};
|
||||
};
|
||||
@@ -1393,6 +1458,7 @@ bool mergeSnippetDraft(HWND, SnippetView *, Settings &);
|
||||
void refreshSnippetDraft(HWND, SnippetView *);
|
||||
void fillSnippets(HWND, SnippetView *);
|
||||
void updateSettingsState(HWND w, SettingsView *v);
|
||||
Settings collectSettings(SettingsView *v, std::vector<CustomShortcut> *rules = nullptr);
|
||||
bool matchesSettingsSearch(const SettingsView &v, const std::wstring &text)
|
||||
{
|
||||
if (!v.searching) return false;
|
||||
@@ -1862,6 +1928,17 @@ void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height)
|
||||
}
|
||||
layout.height = fitSettingsColumns(layout, page.first, page.end, available, grid);
|
||||
const int extra = height * 96 / static_cast<int>(dpi) - layout.height;
|
||||
if (v.selectedPage == CustomShortcutsPage)
|
||||
{
|
||||
auto &[list, bounds] = layout.controls[page.end - 1];
|
||||
const int columnWidth = scale(pane, bounds.right - bounds.left) -
|
||||
GetSystemMetricsForDpi(SM_CXVSCROLL, dpi) - 2;
|
||||
ListView_SetColumnWidth(list, 0, columnWidth * 36 / 100);
|
||||
ListView_SetColumnWidth(list, 1, columnWidth * 38 / 100);
|
||||
ListView_SetColumnWidth(list, 2, columnWidth - columnWidth * 36 / 100 - columnWidth * 38 / 100);
|
||||
}
|
||||
if (v.selectedPage == ChatLanguagesPage)
|
||||
stretchSettingsEditors(layout, page.first, page.end, std::min(extra, 160), {ChatContacts, ChatLayouts}, true);
|
||||
if (v.selectedPage == SnippetsPage)
|
||||
stretchSettingsEditors(layout, page.first, page.end, extra, {301, 303}, available < grid.wrapAt);
|
||||
if (v.selectedPage == MousePage)
|
||||
@@ -1953,6 +2030,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 +2045,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 +2352,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,156 +2397,103 @@ 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"
|
||||
#include "ui_custom_shortcuts.inl"
|
||||
void resizeSettingsForDpi(HWND w, int previousDpi, int nextDpi)
|
||||
{
|
||||
auto &v = *reinterpret_cast<SettingsView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
@@ -2627,6 +2614,7 @@ void fillSettings(HWND root, SettingsView *v)
|
||||
value(w, 214, s.clipboard);
|
||||
value(w, 215, s.screenshot);
|
||||
value(w, 216, s.filesHotkey.value_or(L""));
|
||||
fillCustomShortcuts(*v);
|
||||
value(w, 240, std::to_wstring(s.maxItems));
|
||||
value(w, 241, std::to_wstring(s.maxMiB));
|
||||
value(w, 242, std::to_wstring(s.maxImageMiB));
|
||||
@@ -2646,6 +2634,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;
|
||||
@@ -2660,11 +2649,12 @@ int integer(HWND w, int id)
|
||||
throw std::runtime_error("Enter a whole number for history limits");
|
||||
return v;
|
||||
}
|
||||
Settings collectSettings(SettingsView *v)
|
||||
Settings collectSettings(SettingsView *v, std::vector<CustomShortcut> *rules)
|
||||
{
|
||||
HWND w = v->viewport;
|
||||
collectLayout(v);
|
||||
auto s = v->draft;
|
||||
if (rules) s.customShortcuts = std::move(*rules);
|
||||
s.recent = checked(w, 201);
|
||||
s.switchLayout = checked(w, 202);
|
||||
s.writeLog = checked(w, 208);
|
||||
@@ -2899,7 +2889,7 @@ void updateSettingsState(HWND w, SettingsView *v)
|
||||
EnableWindow(GetDlgItem(w, SettingsApply), dirty);
|
||||
const auto closeLabel = dirty ? L"&Cancel" : L"&Close";
|
||||
if (value(w, IDCANCEL) != closeLabel) value(w, IDCANCEL, closeLabel);
|
||||
EnableWindow(GetDlgItem(w, IDOK), dirty || (v->app->settings.autostart && !isLocalBuild()));
|
||||
EnableWindow(GetDlgItem(w, IDOK), dirty);
|
||||
const wchar_t *text = changed ? L"Unsaved settings — click Apply or Save." :
|
||||
snippetsChanged ? L"Unsaved snippets — click Apply or Save." : L"No unsaved settings.";
|
||||
if (value(w, SettingsStatus) != text) value(w, SettingsStatus, text);
|
||||
@@ -3056,6 +3046,21 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (LOWORD(wp) != WA_INACTIVE) updateSettingsState(w, v);
|
||||
break;
|
||||
case WM_NOTIFY:
|
||||
if (handleCustomShortcutList(w, *v, *reinterpret_cast<NMHDR *>(lp))) return 0;
|
||||
if (reinterpret_cast<const NMHDR *>(lp)->idFrom == ChatContacts &&
|
||||
reinterpret_cast<const NMHDR *>(lp)->code == LVN_ITEMCHANGED)
|
||||
{
|
||||
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;
|
||||
@@ -3134,6 +3139,11 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
SettingsStateRefresh refresh{w};
|
||||
HWND pane = v->viewport;
|
||||
if ((id == CustomShortcutAdd || id == CustomShortcutEdit) && HIWORD(wp) == BN_CLICKED)
|
||||
{
|
||||
showCustomShortcut(w, *v, id == CustomShortcutEdit);
|
||||
return 0;
|
||||
}
|
||||
if ((id == OcrUseTesseract && HIWORD(wp) == BN_CLICKED) ||
|
||||
((id == OcrExecutable || id == OcrLanguages) && HIWORD(wp) == EN_CHANGE))
|
||||
{
|
||||
@@ -3188,7 +3198,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 +4012,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 +4137,12 @@ void showSettings(App &app, bool visible)
|
||||
createOcrSettings(pane);
|
||||
page();
|
||||
|
||||
createChatLanguages(pane);
|
||||
page();
|
||||
|
||||
createCustomShortcuts(pane);
|
||||
page();
|
||||
|
||||
v->splitter = control(w, L"STATIC", L"Resize navigation pane", SS_NOTIFY | WS_TABSTOP,
|
||||
SettingsSplitter, 0, 0, 0, 0);
|
||||
SetWindowSubclass(v->splitter, settingsSplitterProc, 1, reinterpret_cast<DWORD_PTR>(v));
|
||||
|
||||
@@ -75,9 +75,17 @@ HWND appPickerTarget(HWND button, LPARAM position)
|
||||
{
|
||||
POINT point{(short)LOWORD(position), (short)HIWORD(position)};
|
||||
ClientToScreen(button, &point);
|
||||
auto target = GetAncestor(WindowFromPoint(point), GA_ROOT);
|
||||
auto child = WindowFromPoint(point);
|
||||
auto target = GetAncestor(child, GA_ROOT);
|
||||
auto dialog = GetParent(button);
|
||||
return target && target != dialog && target != GetWindow(dialog, GW_OWNER) ? target : nullptr;
|
||||
if (!target || target == dialog || target == GetWindow(dialog, GW_OWNER)) return nullptr;
|
||||
if (!GetPropW(button, L"PickShortcutControl")) return target;
|
||||
while (child && child != target)
|
||||
{
|
||||
if (!shortcutTextControlClass(child).empty()) return child;
|
||||
child = GetParent(child);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
void updatePickerOutline(HWND dialog, HWND &outline, HWND target)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
constexpr int RuleName = 783, RuleHotkey = 784, RuleExecutable = 785, RuleBrowse = 786;
|
||||
constexpr int RuleReuseWindow = 787, RuleNewInstance = 788, RuleRemove = 789;
|
||||
constexpr int RuleAction = 790, RuleControl = 791, RuleText = 792, RuleModeLabel = 793, RuleTextLabel = 794;
|
||||
constexpr int RulePickerHelp = 795;
|
||||
constexpr int RuleProgramLabel = 796, RuleUrl = 797, RuleUrlLabel = 798, RuleBrowser = 799, RuleBrowserLabel = 800;
|
||||
constexpr int RuleChromeProfile = 801, RuleChromeProfileLabel = 802, RuleBrowserPath = 803,
|
||||
RuleBrowserBrowse = 804, RuleBrowserPathLabel = 805;
|
||||
constexpr int ShortcutDialogWidth = 620, ShortcutDialogHeight = 425;
|
||||
|
||||
void fillCustomShortcuts(SettingsView &view, int selected = -1)
|
||||
{
|
||||
const auto list = GetDlgItem(view.viewport, CustomShortcutList);
|
||||
const bool filling = std::exchange(view.filling, true);
|
||||
ListView_DeleteAllItems(list);
|
||||
int row = 0;
|
||||
for (const auto &rule : view.draft.customShortcuts)
|
||||
{
|
||||
LVITEMW item{LVIF_TEXT};
|
||||
item.iItem = row;
|
||||
item.pszText = const_cast<wchar_t *>(rule.name.c_str());
|
||||
ListView_InsertItem(list, &item);
|
||||
const wchar_t *action = rule.action == CustomShortcutAction::OpenUrl ? L"Open URL" :
|
||||
rule.action == CustomShortcutAction::SendText ? L"Send text to app" :
|
||||
rule.newInstance ? L"Launch new instance" : L"Activate last used or launch";
|
||||
ListView_SetItemText(list, row, 1, const_cast<wchar_t *>(action));
|
||||
ListView_SetItemText(list, row, 2, const_cast<wchar_t *>(rule.shortcut.c_str()));
|
||||
ListView_SetCheckState(list, row, rule.enabled);
|
||||
++row;
|
||||
}
|
||||
if (selected >= 0 && selected < row)
|
||||
{
|
||||
ListView_SetItemState(list, selected, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
|
||||
ListView_EnsureVisible(list, selected, FALSE);
|
||||
}
|
||||
EnableWindow(GetDlgItem(view.viewport, CustomShortcutEdit), selected >= 0 && selected < row);
|
||||
view.filling = filling;
|
||||
}
|
||||
|
||||
struct CustomShortcutEditor
|
||||
{
|
||||
SettingsView &view;
|
||||
int row;
|
||||
std::optional<CustomShortcut> previous;
|
||||
HWND pickerOutline{};
|
||||
std::wstring controlClass;
|
||||
std::wstring targetExecutable;
|
||||
std::wstring launchExecutable;
|
||||
int controlId = 0;
|
||||
CustomShortcutAction action = CustomShortcutAction::LaunchApp;
|
||||
std::vector<std::pair<std::wstring, std::wstring>> chromeProfiles;
|
||||
bool profilesLoaded = false;
|
||||
};
|
||||
|
||||
void stageCustomShortcuts(SettingsView &view, std::vector<CustomShortcut> rules)
|
||||
{
|
||||
auto proposed = collectSettings(&view, &rules);
|
||||
view.draft.customShortcuts = std::move(proposed.customShortcuts);
|
||||
}
|
||||
|
||||
CustomShortcutAction selectedShortcutAction(HWND w)
|
||||
{
|
||||
return static_cast<CustomShortcutAction>(SendDlgItemMessageW(w, RuleAction, CB_GETCURSEL, 0, 0));
|
||||
}
|
||||
|
||||
ShortcutBrowser selectedShortcutBrowser(HWND w)
|
||||
{
|
||||
return static_cast<ShortcutBrowser>(SendDlgItemMessageW(w, RuleBrowser, CB_GETCURSEL, 0, 0));
|
||||
}
|
||||
|
||||
void refreshCustomShortcutEditor(HWND w, CustomShortcutEditor &editor)
|
||||
{
|
||||
const bool sendsText = editor.action == CustomShortcutAction::SendText;
|
||||
const bool opensUrl = editor.action == CustomShortcutAction::OpenUrl;
|
||||
const bool chrome = opensUrl && selectedShortcutBrowser(w) == ShortcutBrowser::Chrome;
|
||||
const bool other = opensUrl && selectedShortcutBrowser(w) == ShortcutBrowser::Other;
|
||||
const auto picker = GetDlgItem(w, AppWindowPickerIcon);
|
||||
if (sendsText) SetPropW(picker, L"PickShortcutControl", reinterpret_cast<HANDLE>(1));
|
||||
else RemovePropW(picker, L"PickShortcutControl");
|
||||
for (const int id : {RuleProgramLabel, RuleExecutable, AppWindowPickerIcon, RulePickerHelp})
|
||||
ShowWindow(GetDlgItem(w, id), opensUrl ? SW_HIDE : SW_SHOWNA);
|
||||
for (const int id : {RuleControl, RuleTextLabel, RuleText}) ShowWindow(GetDlgItem(w, id), sendsText ? SW_SHOWNA : SW_HIDE);
|
||||
for (const int id : {RuleBrowse, RuleModeLabel, RuleReuseWindow, RuleNewInstance})
|
||||
ShowWindow(GetDlgItem(w, id), sendsText || opensUrl ? SW_HIDE : SW_SHOWNA);
|
||||
for (const int id : {RuleUrl, RuleUrlLabel, RuleBrowser, RuleBrowserLabel})
|
||||
ShowWindow(GetDlgItem(w, id), opensUrl ? SW_SHOWNA : SW_HIDE);
|
||||
for (const int id : {RuleChromeProfile, RuleChromeProfileLabel})
|
||||
ShowWindow(GetDlgItem(w, id), chrome ? SW_SHOWNA : SW_HIDE);
|
||||
for (const int id : {RuleBrowserPath, RuleBrowserBrowse, RuleBrowserPathLabel})
|
||||
ShowWindow(GetDlgItem(w, id), other ? SW_SHOWNA : SW_HIDE);
|
||||
const auto browser = GetDlgItem(w, RuleBrowser);
|
||||
for (auto &[control, bounds] : windowLayoutState(w)->controls)
|
||||
if (control == browser) bounds.right = chrome ? 298 : 598;
|
||||
arrangeWindow(w);
|
||||
if (chrome && !editor.profilesLoaded)
|
||||
{
|
||||
editor.profilesLoaded = true;
|
||||
editor.chromeProfiles = chromeShortcutProfiles();
|
||||
const auto saved = editor.previous ? editor.previous->chromeProfile : std::wstring{};
|
||||
if (!saved.empty() && std::none_of(editor.chromeProfiles.begin(), editor.chromeProfiles.end(),
|
||||
[&](const auto &profile) { return profile.first == saved; }))
|
||||
editor.chromeProfiles.emplace_back(saved, saved + L" (unavailable)");
|
||||
int selected = 0, index = 0;
|
||||
for (const auto &[directory, name] : editor.chromeProfiles)
|
||||
{
|
||||
const bool duplicate = std::count_if(editor.chromeProfiles.begin(), editor.chromeProfiles.end(),
|
||||
[&](const auto &profile) { return profile.second == name; }) > 1;
|
||||
const auto caption = duplicate ? name + L" (" + directory + L")" : name;
|
||||
SendDlgItemMessageW(w, RuleChromeProfile, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(caption.c_str()));
|
||||
++index;
|
||||
if (directory == saved) selected = index;
|
||||
}
|
||||
SendDlgItemMessageW(w, RuleChromeProfile, CB_SETCURSEL, selected, 0);
|
||||
}
|
||||
SendDlgItemMessageW(w, RuleExecutable, EM_SETREADONLY, sendsText, 0);
|
||||
value(w, RulePickerHelp, sendsText ? L"Drag the crosshair onto the text field you want to fill." :
|
||||
L"Drag the crosshair to an open window to select its program.");
|
||||
}
|
||||
|
||||
LRESULT CALLBACK customShortcutProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
auto *editor = reinterpret_cast<CustomShortcutEditor *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
if (!editor) return DefWindowProcW(w, msg, wp, lp);
|
||||
const HWND owner = GetWindow(w, GW_OWNER);
|
||||
try
|
||||
{
|
||||
if (msg == AppWindowPicked)
|
||||
{
|
||||
if (lp == 1)
|
||||
{
|
||||
const auto picked = reinterpret_cast<HWND>(wp);
|
||||
const auto root = GetAncestor(picked, GA_ROOT);
|
||||
const auto path = processImagePath(root);
|
||||
if (editor->action == CustomShortcutAction::SendText)
|
||||
{
|
||||
const auto kind = shortcutTextControlClass(picked);
|
||||
const auto id = GetDlgCtrlID(picked);
|
||||
if (kind.empty() || path.empty() || findShortcutTextControl(root, kind, id) != picked)
|
||||
throw std::runtime_error("Pick a uniquely identifiable, editable Windows text field.");
|
||||
editor->controlClass = kind;
|
||||
editor->controlId = id;
|
||||
editor->targetExecutable = path;
|
||||
value(w, RuleControl, L"Target control: " + kind + L" (ID " + std::to_wstring(id) + L")");
|
||||
}
|
||||
if (path.empty()) throw std::runtime_error("Drop the crosshair onto a program window.");
|
||||
value(w, RuleExecutable, path);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_DRAWITEM && wp == AppWindowPickerIcon)
|
||||
{
|
||||
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
|
||||
return TRUE;
|
||||
}
|
||||
if (msg == WM_COMMAND)
|
||||
{
|
||||
const auto id = LOWORD(wp);
|
||||
if (id == RuleAction && HIWORD(wp) == CBN_SELCHANGE)
|
||||
{
|
||||
if (editor->action == CustomShortcutAction::LaunchApp) editor->launchExecutable = value(w, RuleExecutable);
|
||||
editor->action = selectedShortcutAction(w);
|
||||
refreshCustomShortcutEditor(w, *editor);
|
||||
value(w, RuleExecutable, editor->action == CustomShortcutAction::SendText ? editor->targetExecutable : editor->launchExecutable);
|
||||
return 0;
|
||||
}
|
||||
if (id == RuleBrowser && HIWORD(wp) == CBN_SELCHANGE)
|
||||
{
|
||||
refreshCustomShortcutEditor(w, *editor);
|
||||
return 0;
|
||||
}
|
||||
if (id == RuleBrowse || id == RuleBrowserBrowse)
|
||||
{
|
||||
const auto path = chooseApplicationFile(w, L"Programs (*.exe)\0*.exe\0");
|
||||
if (!path.empty()) value(w, id == RuleBrowse ? RuleExecutable : RuleBrowserPath, path);
|
||||
return 0;
|
||||
}
|
||||
if (id == IDOK || id == RuleRemove)
|
||||
{
|
||||
auto rules = editor->view.draft.customShortcuts;
|
||||
const int row = editor->row;
|
||||
if (row >= 0 && (static_cast<size_t>(row) >= rules.size() || rules[row] != editor->previous))
|
||||
throw std::runtime_error("This shortcut changed while you were editing. Close and reopen the editor.");
|
||||
if (id == RuleRemove)
|
||||
rules.erase(rules.begin() + row);
|
||||
else
|
||||
{
|
||||
CustomShortcut rule{value(w, RuleName), value(w, RuleHotkey), value(w, RuleExecutable),
|
||||
row < 0 || rules[row].enabled, checked(w, RuleNewInstance)};
|
||||
if (editor->action == CustomShortcutAction::SendText)
|
||||
{
|
||||
rule.action = CustomShortcutAction::SendText;
|
||||
rule.controlClass = editor->controlClass;
|
||||
rule.controlId = editor->controlId;
|
||||
rule.text = value(w, RuleText);
|
||||
rule.executable = editor->targetExecutable;
|
||||
rule.newInstance = false;
|
||||
if (rule.controlClass.empty() || rule.text.empty())
|
||||
throw std::runtime_error("Choose a target text field and enter the text to insert.");
|
||||
}
|
||||
else if (editor->action == CustomShortcutAction::OpenUrl)
|
||||
{
|
||||
rule.action = CustomShortcutAction::OpenUrl;
|
||||
rule.url = trimApplicationText(value(w, RuleUrl));
|
||||
rule.browser = selectedShortcutBrowser(w);
|
||||
rule.executable = rule.browser == ShortcutBrowser::Other ? trimApplicationText(value(w, RuleBrowserPath)) : L"";
|
||||
rule.newInstance = false;
|
||||
if (rule.browser == ShortcutBrowser::Chrome)
|
||||
{
|
||||
const auto profile = SendDlgItemMessageW(w, RuleChromeProfile, CB_GETCURSEL, 0, 0);
|
||||
if (profile > 0 && static_cast<size_t>(profile) <= editor->chromeProfiles.size())
|
||||
rule.chromeProfile = editor->chromeProfiles[profile - 1].first;
|
||||
}
|
||||
}
|
||||
if (row < 0) rules.push_back(std::move(rule));
|
||||
else rules[row] = std::move(rule);
|
||||
}
|
||||
const int selection = row < 0 ? static_cast<int>(rules.size()) - 1 : row;
|
||||
stageCustomShortcuts(editor->view, std::move(rules));
|
||||
fillCustomShortcuts(editor->view, selection);
|
||||
updateSettingsState(owner, &editor->view);
|
||||
DestroyWindow(w);
|
||||
return 0;
|
||||
}
|
||||
if (id == IDCANCEL)
|
||||
{
|
||||
DestroyWindow(w);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (msg == WM_CLOSE)
|
||||
{
|
||||
DestroyWindow(w);
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_NCDESTROY)
|
||||
{
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||
delete editor;
|
||||
disposeFont(w);
|
||||
EnableWindow(owner, TRUE);
|
||||
SetForegroundWindow(owner);
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e) { error(w, e); return 0; }
|
||||
return DefWindowProcW(w, msg, wp, lp);
|
||||
}
|
||||
|
||||
void showCustomShortcut(HWND owner, SettingsView &view, bool editing)
|
||||
{
|
||||
const auto list = GetDlgItem(view.viewport, CustomShortcutList);
|
||||
const int row = editing ? ListView_GetNextItem(list, -1, LVNI_SELECTED) : -1;
|
||||
if (editing && row < 0) return;
|
||||
const auto rule = editing ? view.draft.customShortcuts.at(row) : CustomShortcut{};
|
||||
const HWND w = makeSettingsModal(*view.app, owner, L"KSwitcher.CustomShortcut", editing ? L"Edit shortcut" : L"Add shortcut",
|
||||
customShortcutProc, ShortcutDialogWidth, ShortcutDialogHeight);
|
||||
const bool sendsText = rule.action == CustomShortcutAction::SendText;
|
||||
auto *editor = new CustomShortcutEditor{view, row, editing ? std::optional(rule) : std::nullopt, nullptr, rule.controlClass,
|
||||
sendsText ? rule.executable : L"", rule.action == CustomShortcutAction::LaunchApp ? rule.executable : L"",
|
||||
rule.controlId, rule.action};
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(editor));
|
||||
label(w, L"&Name", 22, 16, 340);
|
||||
edit(w, RuleName, 22, 40, 340);
|
||||
label(w, L"&Shortcut", 378, 16, 220);
|
||||
hotkeyEdit(*view.app, w, RuleHotkey, 378, 40, 220);
|
||||
label(w, L"&Action", 22, 80, 576);
|
||||
control(w, WC_COMBOBOXW, L"", WS_TABSTOP | CBS_DROPDOWNLIST, RuleAction, 22, 101, 576, 110);
|
||||
for (const auto *action : {L"Launch app", L"Send text to app", L"Open URL"})
|
||||
SendDlgItemMessageW(w, RuleAction, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(action));
|
||||
SendDlgItemMessageW(w, RuleAction, CB_SETCURSEL, static_cast<WPARAM>(rule.action), 0);
|
||||
control(w, L"STATIC", L"&Program", 0, RuleProgramLabel, 22, 137, 576, 22);
|
||||
edit(w, RuleExecutable, 22, 160, 440);
|
||||
button(w, L"&Browse...", RuleBrowse, 472, 158, 84);
|
||||
createAppWindowPicker(w, AppWindowPickerIcon, 566, 158, 32, editor->pickerOutline, createButtonTooltips(w));
|
||||
control(w, L"STATIC", L"", SS_NOPREFIX, RulePickerHelp, 22, 194, 576, 22);
|
||||
control(w, L"STATIC", L"When you press the shortcut", SS_NOPREFIX, RuleModeLabel, 22, 229, 576, 22);
|
||||
control(w, L"STATIC", L"", SS_NOPREFIX, RuleControl, 22, 223, 576, 22);
|
||||
control(w, L"STATIC", L"Text to insert", SS_NOPREFIX, RuleTextLabel, 22, 251, 576, 22);
|
||||
edit(w, RuleText, 22, 274, 576, 76, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL);
|
||||
SendDlgItemMessageW(w, RuleText, EM_SETLIMITTEXT, 32768, 0);
|
||||
control(w, L"BUTTON", L"Activate the last-used window, or launch the app if it is closed",
|
||||
WS_TABSTOP | WS_GROUP | BS_AUTORADIOBUTTON, RuleReuseWindow, 22, 252, 576, 24);
|
||||
control(w, L"BUTTON", L"Always launch a new instance", BS_AUTORADIOBUTTON, RuleNewInstance, 22, 281, 576, 24);
|
||||
control(w, L"STATIC", L"&URL", 0, RuleUrlLabel, 22, 137, 576, 22);
|
||||
edit(w, RuleUrl, 22, 160, 576);
|
||||
SendDlgItemMessageW(w, RuleUrl, EM_SETLIMITTEXT, 16384, 0);
|
||||
control(w, L"STATIC", L"&Browser", 0, RuleBrowserLabel, 22, 201, 276, 22);
|
||||
control(w, WC_COMBOBOXW, L"", WS_TABSTOP | CBS_DROPDOWNLIST, RuleBrowser, 22, 224, 576, 115);
|
||||
for (const auto *browser : {L"Default browser", L"Google Chrome", L"Other browser"})
|
||||
SendDlgItemMessageW(w, RuleBrowser, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(browser));
|
||||
SendDlgItemMessageW(w, RuleBrowser, CB_SETCURSEL, static_cast<WPARAM>(rule.browser), 0);
|
||||
control(w, L"STATIC", L"Chrome &profile", 0, RuleChromeProfileLabel, 319, 201, 279, 22);
|
||||
control(w, WC_COMBOBOXW, L"", WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWNLIST, RuleChromeProfile, 319, 224, 279, 122);
|
||||
SendDlgItemMessageW(w, RuleChromeProfile, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Use Chrome's default profile"));
|
||||
SendDlgItemMessageW(w, RuleChromeProfile, CB_SETCURSEL, 0, 0);
|
||||
control(w, L"STATIC", L"Browser executable", 0, RuleBrowserPathLabel, 22, 265, 576, 22);
|
||||
edit(w, RuleBrowserPath, 22, 288, 478);
|
||||
button(w, L"Browse...", RuleBrowserBrowse, 510, 286, 88);
|
||||
settingsModalActions(w, ShortcutDialogWidth, ShortcutDialogHeight, editing ? L"Save shortcut" : L"Add shortcut",
|
||||
RuleRemove, editing ? L"&Remove" : nullptr);
|
||||
value(w, RuleName, rule.name);
|
||||
value(w, RuleHotkey, rule.shortcut);
|
||||
value(w, RuleExecutable, rule.executable);
|
||||
value(w, RuleControl, rule.controlClass.empty() ? L"No target field selected" :
|
||||
L"Target control: " + rule.controlClass + L" (ID " + std::to_wstring(rule.controlId) + L")");
|
||||
value(w, RuleText, rule.text);
|
||||
value(w, RuleUrl, rule.url);
|
||||
if (rule.action == CustomShortcutAction::OpenUrl && rule.browser == ShortcutBrowser::Other)
|
||||
value(w, RuleBrowserPath, rule.executable);
|
||||
CheckRadioButton(w, RuleReuseWindow, RuleNewInstance, rule.newInstance ? RuleNewInstance : RuleReuseWindow);
|
||||
refreshCustomShortcutEditor(w, *editor);
|
||||
EnableWindow(owner, FALSE);
|
||||
showRequestedWindow(w);
|
||||
SetFocus(GetDlgItem(w, RuleName));
|
||||
}
|
||||
|
||||
bool handleCustomShortcutList(HWND w, SettingsView &view, const NMHDR &header)
|
||||
{
|
||||
if (header.idFrom != CustomShortcutList || view.filling) return false;
|
||||
if (header.code == NM_DBLCLK)
|
||||
{
|
||||
showCustomShortcut(w, view, true);
|
||||
return true;
|
||||
}
|
||||
if (header.code != LVN_ITEMCHANGED) return false;
|
||||
const auto &change = reinterpret_cast<const NMLISTVIEW &>(header);
|
||||
const auto list = header.hwndFrom;
|
||||
EnableWindow(GetDlgItem(view.viewport, CustomShortcutEdit), ListView_GetNextItem(list, -1, LVNI_SELECTED) >= 0);
|
||||
if (change.iItem < 0 || static_cast<size_t>(change.iItem) >= view.draft.customShortcuts.size() ||
|
||||
!(change.uOldState & LVIS_STATEIMAGEMASK) || !((change.uNewState ^ change.uOldState) & LVIS_STATEIMAGEMASK))
|
||||
return true;
|
||||
try
|
||||
{
|
||||
auto rules = view.draft.customShortcuts;
|
||||
rules[change.iItem].enabled = ListView_GetCheckState(list, change.iItem);
|
||||
stageCustomShortcuts(view, std::move(rules));
|
||||
updateSettingsState(w, &view);
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
view.filling = true;
|
||||
ListView_SetCheckState(list, change.iItem, view.draft.customShortcuts[change.iItem].enabled);
|
||||
view.filling = false;
|
||||
error(w, e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void createCustomShortcuts(HWND pane)
|
||||
{
|
||||
button(pane, L"&Add shortcut...", CustomShortcutAdd, 24, 64, 138);
|
||||
button(pane, L"&Edit...", CustomShortcutEdit, 170, 64, 90);
|
||||
const auto list = control(pane, WC_LISTVIEWW, L"Custom shortcuts", WS_TABSTOP | WS_BORDER | LVS_REPORT |
|
||||
LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, CustomShortcutList, 24, 106, 660, 242);
|
||||
ListView_SetExtendedListViewStyle(list, LVS_EX_FULLROWSELECT | LVS_EX_CHECKBOXES | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP);
|
||||
const std::pair<const wchar_t *, int> columns[]{{L"Name", 235}, {L"Action", 255}, {L"Shortcut", 150}};
|
||||
for (const auto &[title, width] : columns)
|
||||
{
|
||||
LVCOLUMNW column{LVCF_TEXT | LVCF_WIDTH};
|
||||
column.pszText = const_cast<wchar_t *>(title);
|
||||
column.cx = scale(pane, width);
|
||||
ListView_InsertColumn(list, Header_GetItemCount(ListView_GetHeader(list)), &column);
|
||||
}
|
||||
}
|
||||
+141
-25
@@ -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); }
|
||||
@@ -364,6 +364,8 @@ void refreshLan(HWND w,LanView &v)
|
||||
auto mode=v.snapshot.value("controlMode",0);
|
||||
if(mode==2)inputStatus=L"Mouse and keyboard control the OTHER PC. Ctrl+Alt+Esc returns here.";
|
||||
else if(mode==3)inputStatus=L"This PC is controlled remotely. Local physical input takes control back.";
|
||||
const auto inputBlock=v.snapshot.value("inputBlock",std::string{});
|
||||
if(!inputBlock.empty()&&v.snapshot.value("shareInput",false))inputStatus=wide(inputBlock);
|
||||
if (v.draft.contains("shareInput"))
|
||||
inputStatus = L"Click Apply or Save to apply input sharing changes.";
|
||||
setStatus(718,v.layoutError.empty() ? inputStatus : v.layoutError);
|
||||
|
||||
@@ -466,16 +466,23 @@ std::wstring actionApplicationExecutable(std::filesystem::path path)
|
||||
return path.filename().wstring();
|
||||
}
|
||||
|
||||
void browseActionApplication(HWND w, MouseProfileEditor &editor)
|
||||
std::wstring chooseApplicationFile(HWND w, const wchar_t *filter, DWORD flags = 0)
|
||||
{
|
||||
wchar_t path[32768]{};
|
||||
OPENFILENAMEW picker{sizeof(picker)};
|
||||
picker.hwndOwner = w;
|
||||
picker.lpstrFilter = L"Applications and shortcuts (*.exe;*.lnk)\0*.exe;*.lnk\0";
|
||||
picker.lpstrFilter = filter;
|
||||
picker.lpstrFile = path;
|
||||
picker.nMaxFile = static_cast<DWORD>(std::size(path));
|
||||
picker.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_NODEREFERENCELINKS;
|
||||
if (!GetOpenFileNameW(&picker)) return;
|
||||
picker.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | flags;
|
||||
return GetOpenFileNameW(&picker) ? path : L"";
|
||||
}
|
||||
|
||||
void browseActionApplication(HWND w, MouseProfileEditor &editor)
|
||||
{
|
||||
const auto path = chooseApplicationFile(w, L"Applications and shortcuts (*.exe;*.lnk)\0*.exe;*.lnk\0",
|
||||
OFN_NODEREFERENCELINKS);
|
||||
if (path.empty()) return;
|
||||
value(w, ActionApplicationName, actionApplicationExecutable(path));
|
||||
addActionApplication(w, editor);
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.7.4";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.8.13";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
+62
-45
@@ -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 = 22;
|
||||
require(navigation && TreeView_GetCount(navigation) == sections &&
|
||||
TreeView_GetParent(navigation, settingsSection(navigation, 10)) == settingsSection(navigation, 7) &&
|
||||
TreeView_GetParent(navigation, settingsSection(navigation, 11)) == settingsSection(navigation, 0),
|
||||
"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);
|
||||
|
||||
@@ -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){
|
||||
|
||||
@@ -23,10 +23,14 @@ int wmain(int argc,wchar_t **argv)
|
||||
wchar_t executable[32768]{};
|
||||
const auto length=GetModuleFileNameW(nullptr,executable,static_cast<DWORD>(std::size(executable)));
|
||||
if(!length || length>=std::size(executable)) return 1;
|
||||
const std::filesystem::path target=argc==2?argv[1]:executable;
|
||||
const bool browserFixture=argc==2 && std::filesystem::path(executable).filename()==L"browser-fixture.exe";
|
||||
const std::filesystem::path target=argc==2 && !browserFixture?argv[1]:executable;
|
||||
auto report=target;
|
||||
report+=L".opened";
|
||||
std::ofstream result(report,std::ios::binary);
|
||||
result<<"opened";
|
||||
if(browserFixture) {
|
||||
const std::wstring_view url(argv[1]);
|
||||
for(const auto ch:url) result.put(static_cast<char>(ch));
|
||||
} else result<<"opened";
|
||||
return result?0:1;
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+56
-1
@@ -1,4 +1,4 @@
|
||||
#include "files_image_decode.h"
|
||||
#include "files_image_edit.h"
|
||||
#include <windows.h>
|
||||
#include <wincodec.h>
|
||||
#include <webp/encode.h>
|
||||
@@ -84,6 +84,60 @@ void expectDecodeFailure(const fs::path &file,std::string_view text)
|
||||
throw std::runtime_error("invalid image was decoded");
|
||||
}
|
||||
|
||||
void verifyImageEdits(const fs::path &root)
|
||||
{
|
||||
ImageRaster original{4,3,{0xff110001,0xff110002,0xff110003,0xff110004,
|
||||
0xff110005,0x80402010,0xff110007,0xff110008,0xff110009,0xff11000a,0xff11000b,0xff11000c}};
|
||||
const ImageGeometry initial{{0,0,4,3},0};
|
||||
const ImageGeometry clockwise{initial.region,1};
|
||||
const auto rotated=transformImage(original,clockwise);
|
||||
expect(rotated.width==3 && rotated.height==4 && rotated.pixels[0]==original.pixels[8] &&
|
||||
rotated.pixels[11]==original.pixels[3],"clockwise rotation changed pixel order");
|
||||
const auto reversed=transformImage(original,{initial.region,3});
|
||||
expect(reversed.pixels.front()==original.pixels[3] && reversed.pixels.back()==original.pixels[8],
|
||||
"counterclockwise rotation changed pixel order");
|
||||
const auto cropped=transformImage(original,cropImage(clockwise,{1,1,2,2}));
|
||||
expect(cropped.width==2 && cropped.height==2 && cropped.pixels==std::vector<uint32_t>{
|
||||
original.pixels[5],original.pixels[1],original.pixels[6],original.pixels[2]},
|
||||
"crop used coordinates before rotation");
|
||||
bool outside=false;
|
||||
try {cropImage(clockwise,{2,1,2,2});}
|
||||
catch(const std::runtime_error &) {outside=true;}
|
||||
expect(outside,"out-of-bounds crop was accepted");
|
||||
|
||||
const auto png=root/L"Редагування.png";
|
||||
saveImage(cropped,png);
|
||||
const auto saved=decodeImage(png,png);
|
||||
expect(saved.width==2 && saved.height==2 && saved.pixels==cropped.pixels,"PNG copy lost alpha or pixels");
|
||||
const auto before=imageRevision(png);
|
||||
bool collision=false;
|
||||
try {saveImage(rotated,png);}
|
||||
catch(const std::system_error &) {collision=true;}
|
||||
expect(collision && sameImageRevision(before,imageRevision(png)), "Save Copy overwrote an existing image");
|
||||
|
||||
const auto incoming=root/L"external.png";
|
||||
saveImage(original,incoming);
|
||||
fs::rename(png,root/L"first.png");
|
||||
fs::rename(incoming,png);
|
||||
bool stale=false;
|
||||
try {saveImage(cropped,png,&before);}
|
||||
catch(const std::runtime_error &) {stale=true;}
|
||||
expect(stale && decodeImage(png,png).pixels==original.pixels,"Replace overwrote an external revision");
|
||||
const auto current=imageRevision(png);
|
||||
const auto written=saveImage(cropped,png,¤t);
|
||||
expect(sameImageRevision(written,imageRevision(png)), "returned revision did not track the installed image");
|
||||
expect(decodeImage(png,png).pixels==cropped.pixels,"confirmed replacement lost image data");
|
||||
|
||||
const auto jpeg=root/L"copy.jpg";
|
||||
const ImageRaster transparent{8,8,std::vector<uint32_t>(64,0)};
|
||||
saveImage(transparent,jpeg);
|
||||
const auto lossy=decodeImage(jpeg,jpeg);
|
||||
expect(lossy.width==8 && lossy.height==8 && lossy.pixels.front()>=0xfffefefe,
|
||||
"JPEG copy failed to composite transparency on white");
|
||||
for(const auto &entry:fs::directory_iterator(root))
|
||||
expect(entry.path().extension()!=L".tmp","image operation left a staging file");
|
||||
}
|
||||
|
||||
std::vector<uint8_t> animatedWebp(const uint8_t *encoded,size_t size)
|
||||
{
|
||||
expect(size>12,"WebP fixture RIFF body");
|
||||
@@ -109,6 +163,7 @@ int main()
|
||||
{
|
||||
expect(SUCCEEDED(apartment),"initialize COM");
|
||||
Temp temp;
|
||||
verifyImageEdits(temp.path);
|
||||
for(const auto &[name,container]:std::array{
|
||||
std::pair{L"знімок.PNG",&GUID_ContainerFormatPng},
|
||||
std::pair{L"picture.jpeg",&GUID_ContainerFormatJpeg},
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
@@ -99,6 +99,23 @@ try {
|
||||
: { key:'Enter', code:'Enter', windowsVirtualKeyCode:13 };
|
||||
await command('Input.dispatchKeyEvent', { type:'keyDown', ...key });
|
||||
await command('Input.dispatchKeyEvent', { type:'keyUp', ...key });
|
||||
} else if (scenario === 'html-quick') {
|
||||
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
|
||||
document.querySelector('main h1')?.textContent === 'Offline HTML fixture'`), 'rendered HTML');
|
||||
assert.equal(await evaluate(`document.querySelector('main td strong')?.textContent`), 'Formatted table');
|
||||
assert.equal(await evaluate(`document.querySelector('main h1').style.color`), 'teal');
|
||||
assert.equal(await evaluate(`document.querySelector('main h1').style.position`), '');
|
||||
assert.equal(await evaluate(`document.querySelectorAll(
|
||||
'main :is(script, style, link, meta, iframe, object, img, input, [href], [src], [onload], [onclick])'
|
||||
).length`), 0);
|
||||
assert.equal(await evaluate(`document.querySelector('main').textContent.includes('Image description')`), true);
|
||||
assert.equal(await evaluate(`window.documentScriptRan`), undefined);
|
||||
await evaluate(`document.querySelector('main a').click()`);
|
||||
assert.equal(await evaluate('location.href'), 'https://kswitcher-markdown.invalid/markdown.html');
|
||||
if (artifact) {
|
||||
const screenshot = await command('Page.captureScreenshot', { format: 'png' });
|
||||
await writeFile(artifact, Buffer.from(screenshot.data, 'base64'));
|
||||
}
|
||||
} else if (scenario === 'render') {
|
||||
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
|
||||
!!document.querySelector('figure svg') &&
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
#include "lan_network.h"
|
||||
#include "files_mcp.h"
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Server=ks::files::FilesMcpServer;
|
||||
using Json=Server::Json;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
void expect(bool condition,const char *message)
|
||||
{
|
||||
if(!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
bool connectLoopback(SOCKET socket,unsigned port)
|
||||
{
|
||||
sockaddr_in address{};
|
||||
address.sin_family=AF_INET;
|
||||
address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
|
||||
address.sin_port=htons(static_cast<u_short>(port));
|
||||
return connect(socket,reinterpret_cast<const sockaddr*>(&address),sizeof(address))==0;
|
||||
}
|
||||
|
||||
std::string post(unsigned port,const std::string &token,const Json &message,
|
||||
std::string_view extra={},std::string_view host={})
|
||||
{
|
||||
ks::lan::WinSocket client;
|
||||
client.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
|
||||
const DWORD timeout=4000;
|
||||
expect(client.value!=INVALID_SOCKET &&
|
||||
!setsockopt(client.value,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast<const char*>(&timeout),sizeof(timeout)) &&
|
||||
connectLoopback(client.value,port),"Could not connect to fixture listener");
|
||||
const auto body=message.dump();
|
||||
const auto authority=host.empty()?"127.0.0.1:"+std::to_string(port):std::string(host);
|
||||
const auto bytes="POST /mcp HTTP/1.1\r\nHost: "+authority+"\r\nContent-Type: application/json\r\n"
|
||||
"Accept: application/json, text/event-stream\r\n"+
|
||||
(token.empty()?std::string{}:"Authorization: Bearer "+token+"\r\n")+
|
||||
std::string(extra)+"Content-Length: "+std::to_string(body.size())+"\r\n\r\n"+body;
|
||||
expect(send(client.value,bytes.data(),static_cast<int>(bytes.size()),0)==static_cast<int>(bytes.size()),
|
||||
"Could not send fixture request");
|
||||
std::string response;
|
||||
char buffer[4096];
|
||||
for(;;)
|
||||
{
|
||||
const int count=recv(client.value,buffer,sizeof(buffer),0);
|
||||
expect(count>=0,"Fixture request timed out");
|
||||
if(!count) break;
|
||||
response.append(buffer,count);
|
||||
expect(response.size()<1024*1024,"Oversized fixture response");
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
Json content(const std::string &response)
|
||||
{
|
||||
const auto end=response.find("\r\n\r\n");
|
||||
expect(end!=response.npos,"No HTTP headers");
|
||||
return Json::parse(response.substr(end+4));
|
||||
}
|
||||
|
||||
Json request(std::string_view method,Json params=Json::object())
|
||||
{
|
||||
return {{"jsonrpc","2.0"},{"id",4},{"method",method},{"params",std::move(params)}};
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try
|
||||
{
|
||||
ks::lan::Network network;
|
||||
const auto owner=CreateWindowExW(0,L"STATIC",L"Files MCP fixture",0,0,0,0,0,
|
||||
HWND_MESSAGE,nullptr,GetModuleHandleW(nullptr),nullptr);
|
||||
expect(owner!=nullptr,"Could not create fixture owner window");
|
||||
Server server;
|
||||
expect(!server.port() && server.token().empty(),"The listener is enabled by default");
|
||||
server.start(owner);
|
||||
const auto port=server.port();
|
||||
const auto token=std::string(server.token());
|
||||
expect(port && token.size()==64,"The session does not have a listener and token");
|
||||
const auto ping=request("ping");
|
||||
expect(post(port,{},ping).starts_with("HTTP/1.1 401"),"An unauthenticated request was accepted");
|
||||
expect(post(port,std::string(64,'0'),ping).starts_with("HTTP/1.1 401"),"A wrong token was accepted");
|
||||
expect(post(port,token,ping,"Origin: https://example.invalid\r\n").starts_with("HTTP/1.1 403"),
|
||||
"A browser origin was accepted");
|
||||
expect(post(port,token,ping,{},"other.invalid").starts_with("HTTP/1.1 403"),
|
||||
"An unexpected Host was accepted");
|
||||
expect(post(port,token,ping,"Content-Length: 1\r\n").starts_with("HTTP/1.1 400"),
|
||||
"An ambiguous message length was accepted");
|
||||
const auto initialized=content(post(port,token,request("initialize",{{"protocolVersion","2025-11-25"}})));
|
||||
expect(initialized.at("result").at("protocolVersion")=="2025-11-25","Wrong protocol version");
|
||||
const Json notification{{"jsonrpc","2.0"},{"method","notifications/initialized"}};
|
||||
expect(post(port,token,notification).starts_with("HTTP/1.1 202"),"Initialization notification did not succeed");
|
||||
const auto listed=content(post(port,token,request("tools/list")));
|
||||
const auto &tools=listed.at("result").at("tools");
|
||||
expect(tools.size()==3,"The listener advertised unexpected capabilities");
|
||||
for(const auto &tool:tools) expect(tool.at("annotations").at("readOnlyHint")==true,"A tool is not read-only");
|
||||
const auto unknown=content(post(port,token,request("tools/call",{{"name","write_file"}})));
|
||||
expect(unknown.at("error").at("code")==-32602,"An unlisted tool was accepted");
|
||||
|
||||
auto pending=std::async(std::launch::async,[&]
|
||||
{
|
||||
return content(post(port,token,request("tools/call",
|
||||
{{"name","get_panels"},{"arguments",{{"limit",3}}}})));
|
||||
});
|
||||
const auto deadline=std::chrono::steady_clock::now()+3s;
|
||||
while(pending.wait_for(1ms)!=std::future_status::ready && std::chrono::steady_clock::now()<deadline)
|
||||
{
|
||||
MSG message{};
|
||||
if(PeekMessageW(&message,owner,ks::files::filesMcpQueryMessage,ks::files::filesMcpQueryMessage,PM_REMOVE))
|
||||
server.answer([](std::string_view name,const Json &arguments)
|
||||
{
|
||||
if(name!="get_panels" || arguments.at("limit")!=3) return Json{{"error","Wrong query"}};
|
||||
return Json{{"active","left"}};
|
||||
});
|
||||
}
|
||||
expect(pending.get().at("result").at("structuredContent").at("active")=="left",
|
||||
"The server did not return the UI snapshot");
|
||||
|
||||
ks::lan::WinSocket idle;
|
||||
idle.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
|
||||
expect(idle.value!=INVALID_SOCKET && connectLoopback(idle.value,port),"Could not open idle connection");
|
||||
const auto start=std::chrono::steady_clock::now();
|
||||
server.stop();
|
||||
expect(std::chrono::steady_clock::now()-start<1s && !server.port() && server.token().empty(),
|
||||
"Stopping did not cancel the listener or detach the token");
|
||||
server.start(owner);
|
||||
expect(server.token()!=token,"A restarted listener reused a token");
|
||||
expect(post(server.port(),token,ping).starts_with("HTTP/1.1 401"),"A revoked token still works");
|
||||
expect(post(server.port(),std::string(server.token()),ping).starts_with("HTTP/1.1 200"),"The new token failed");
|
||||
server.stop();
|
||||
DestroyWindow(owner);
|
||||
return 0;
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
std::cerr<<error.what()<<'\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
+173
-32
@@ -1,60 +1,133 @@
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe"
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe",
|
||||
[string]$ProfileSubkey = 'Software\KSwitcher\Files',
|
||||
[string]$Node = (Get-Command node -ErrorAction SilentlyContinue).Source,
|
||||
[string]$RenderedImage = '',
|
||||
[string]$BinaryImage = ''
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. "$PSScriptRoot/files_commands_ui.ps1"
|
||||
$browserProbe = $Node -and ((& $Node -p "typeof WebSocket === 'function'") -eq 'true')
|
||||
if($RenderedImage -and !$browserProbe){throw 'A Node runtime with WebSocket is required for a rendered screenshot'}
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class FilesQuickViewProbe {
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr parent, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[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", EntryPoint="PostMessageW")]
|
||||
public static extern bool Post(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr Send(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr FindRow(IntPtr window, uint msg, IntPtr wp, string name);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr wp, StringBuilder text);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-Until([scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 100; $attempt++) {
|
||||
if (& $Condition) { return }
|
||||
function Wait-Until([string]$Label,[scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 150; $attempt++) {
|
||||
$result = & $Condition
|
||||
if ($result) { return $result }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
throw "Timed out waiting for: $Condition"
|
||||
throw "Timed out waiting for $Label"
|
||||
}
|
||||
function Text([IntPtr]$Handle) {
|
||||
$buffer = [Text.StringBuilder]::new(256)
|
||||
[void][FilesQuickViewProbe]::Read($Handle, 13, [IntPtr]$buffer.Capacity, $buffer)
|
||||
$buffer.ToString()
|
||||
}
|
||||
function Select-File([string]$Name) {
|
||||
$row = [FilesQuickViewProbe]::FindRow($leftList, 0x1A2, [IntPtr](-1), $Name)
|
||||
if ($row.ToInt64() -lt 0) { throw "Missing row $Name" }
|
||||
[void][FilesQuickViewProbe]::Send($leftList, 0x186, $row, 0)
|
||||
[void][FilesQuickViewProbe]::Post($window, 273, [IntPtr](0x10000+102), $leftList)
|
||||
}
|
||||
function Preview-Bytes([int]$Count) {
|
||||
[byte[]]$bytes = @(
|
||||
for($i=0; $i -lt $Count; ++$i) {
|
||||
[byte]([FilesQuickViewProbe]::Send($editor, 2007, [IntPtr]$i, 0).ToInt32() -band 255)
|
||||
}
|
||||
)
|
||||
[Text.Encoding]::UTF8.GetString($bytes)
|
||||
}
|
||||
function Browser {
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'html-quick' $RenderedImage 'preview.html'
|
||||
if ($LASTEXITCODE) { throw 'WebView2 verification failed for rendered HTML' }
|
||||
}
|
||||
|
||||
$exe = (Resolve-Path $Executable).Path
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
|
||||
$source = Split-Path $exe
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ProfileSubkey)
|
||||
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor',
|
||||
'LeftPanelMode', 'RightPanelMode', 'WindowPlacement'
|
||||
$saved = @{}
|
||||
foreach ($name in $names) {
|
||||
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
|
||||
}
|
||||
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
$profile = $env:WEBVIEW2_USER_DATA_FOLDER
|
||||
$fixture = [IO.Directory]::CreateTempSubdirectory('ks-files-quick-view-')
|
||||
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
try {
|
||||
$network = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$network.Start()
|
||||
$probe = "http://127.0.0.1:$($network.LocalEndpoint.Port)/should-not-load"
|
||||
$debug = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$debug.Start()
|
||||
$port = $debug.LocalEndpoint.Port
|
||||
$debug.Stop()
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = "--remote-debugging-port=$port --disable-background-networking"
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $fixture.FullName 'webview'
|
||||
$app = $fixture.CreateSubdirectory('app')
|
||||
Copy-Item -LiteralPath $exe,"$source\WebView2Loader.dll","$source\terminal" -Destination $app.FullName -Recurse
|
||||
$left = $fixture.CreateSubdirectory('left')
|
||||
$right = $fixture.CreateSubdirectory('right')
|
||||
$document = Join-Path $left.FullName 'preview.txt'
|
||||
[IO.File]::WriteAllText($document, 'Quick View fixture')
|
||||
$key.SetValue('LeftWide', 1, 'DWord')
|
||||
$key.SetValue('RightWide', 1, 'DWord')
|
||||
[IO.File]::WriteAllText((Join-Path $left.FullName 'preview.html'), @"
|
||||
<!doctype html>
|
||||
<html><head><title>Document title</title>
|
||||
<meta http-equiv="refresh" content="0;url=$probe">
|
||||
<link rel="stylesheet" href="$probe">
|
||||
<style>@import url('$probe');</style>
|
||||
<script>window.documentScriptRan = true;</script></head>
|
||||
<body onload="window.documentScriptRan = true;"><main>
|
||||
<h1 style="color: teal; position: fixed" onclick="window.documentScriptRan = true;">Offline HTML fixture</h1>
|
||||
<table><tr><td><strong>Formatted table</strong></td></tr></table>
|
||||
<a href="$probe">External link</a>
|
||||
<img src="$probe" alt="Image description"><iframe src="$probe"></iframe>
|
||||
<form action="$probe"><input type="submit"></form>
|
||||
</main></body></html>
|
||||
"@)
|
||||
$data = [byte[]]::new(5000)
|
||||
[byte[]]$header = 0,1,9,10,13,27,31,32,65,127,128,255
|
||||
$header.CopyTo($data,0)
|
||||
for ($i=$header.Length; $i -lt $data.Length; ++$i) { $data[$i] = 66 }
|
||||
[IO.File]::WriteAllBytes((Join-Path $left.FullName 'symbols.bin'), $data)
|
||||
$expectedSymbols = -join ([char[]]@(0xe000,0xe001,0xe009,0xe00a,0xe00d,0xe01b,0xe01f,
|
||||
0x20,0x41,0xe07f,0xC7,0xe0ff))
|
||||
$key.SetValue('LeftPanelMode', 1, 'DWord')
|
||||
$key.SetValue('RightPanelMode', 1, 'DWord')
|
||||
$key.SetValue('LeftPath', $left.FullName, 'String')
|
||||
$key.SetValue('RightPath', $right.FullName, 'String')
|
||||
$key.SetValue('LeftCursor', $document, 'String')
|
||||
$key.DeleteValue('RightCursor', $false)
|
||||
$key.DeleteValue('WindowPlacement', $false)
|
||||
|
||||
$process = Start-Process -FilePath $exe -PassThru
|
||||
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
$window = $process.MainWindowHandle
|
||||
Wait-Until { [FilesQuickViewProbe]::Activate($window) }
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
$process = Start-Process -FilePath (Join-Path $app.FullName (Split-Path -Leaf $exe)) -PassThru -WindowStyle Normal
|
||||
$window = Wait-Until 'the Files window' {
|
||||
$process.Refresh()
|
||||
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
|
||||
}
|
||||
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,1500,920,20)
|
||||
$leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102)
|
||||
$rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103)
|
||||
$rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141)
|
||||
@@ -62,12 +135,16 @@ try {
|
||||
if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) {
|
||||
throw 'Expected both file panels in the test window.'
|
||||
}
|
||||
Wait-Until { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) }
|
||||
$keyboard.SendKeys('^q')
|
||||
Wait-Until {
|
||||
[void](Wait-Until 'both panels' { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) })
|
||||
Invoke-FilesCommand $window 'Quick View*'
|
||||
$preview = Wait-Until 'Quick View' {
|
||||
$hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158)
|
||||
$hostWindow -ne [IntPtr]::Zero -and [FilesQuickViewProbe]::IsWindowVisible($hostWindow)
|
||||
if ([FilesQuickViewProbe]::IsWindowVisible($hostWindow)) { $hostWindow }
|
||||
}
|
||||
$editor = [FilesQuickViewProbe]::FindWindowEx($preview,0,'Scintilla',[NullString]::Value)
|
||||
[void](Wait-Until 'the text preview' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
|
||||
$initialWrap = [FilesQuickViewProbe]::Send($editor,2269,0,0)
|
||||
$initialScrollbar = [FilesQuickViewProbe]::Send($editor,2131,0,0)
|
||||
foreach ($control in $rightList, $rightHeading, $rightPath) {
|
||||
if ([FilesQuickViewProbe]::IsWindowVisible($control)) {
|
||||
throw 'A file panel control can draw over the Quick View content.'
|
||||
@@ -75,19 +152,75 @@ try {
|
||||
}
|
||||
if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' }
|
||||
|
||||
$keyboard.SendKeys('^q')
|
||||
Wait-Until { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero }
|
||||
Select-File 'preview.html'
|
||||
$mode = [FilesQuickViewProbe]::GetDlgItem($preview,159)
|
||||
[void](Wait-Until 'the HTML mode switch' { [FilesQuickViewProbe]::IsWindowVisible($mode) -and (Text $mode) -eq 'Show Source' })
|
||||
if ($browserProbe) { Browser }
|
||||
[void][FilesQuickViewProbe]::Post($preview,273,159,$mode)
|
||||
[void](Wait-Until 'the HTML source' {
|
||||
[FilesQuickViewProbe]::IsWindowVisible($editor) -and (Text $mode) -eq 'Show Rendered' -and
|
||||
(Preview-Bytes 15) -eq '<!doctype html>'
|
||||
})
|
||||
[void][FilesQuickViewProbe]::Post($editor,0x100,117,0)
|
||||
[void](Wait-Until 'keyboard switch back to Rendered' { (Text $mode) -eq 'Show Source' })
|
||||
if ($browserProbe) { Browser }
|
||||
if ($network.Pending()) { throw 'Rendering HTML attempted an outbound resource request' }
|
||||
|
||||
Select-File 'symbols.bin'
|
||||
[void](Wait-Until 'binary glyphs in the embedded view' {
|
||||
[FilesQuickViewProbe]::IsWindowVisible($editor) -and [FilesQuickViewProbe]::Send($editor,2269,0,0).ToInt32() -eq 2
|
||||
})
|
||||
if ((Preview-Bytes ([Text.Encoding]::UTF8.GetByteCount($expectedSymbols))) -cne $expectedSymbols) {
|
||||
throw 'Binary control bytes were lost or decoded as text'
|
||||
}
|
||||
$expectedLength = [Text.Encoding]::UTF8.GetByteCount($expectedSymbols) + 4096 - $header.Length
|
||||
if ([FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -ne $expectedLength -or
|
||||
[FilesQuickViewProbe]::Send($editor,2131,0,0).ToInt32() -ne 0) {
|
||||
throw 'Binary preview exceeded its byte limit or enabled horizontal scrolling'
|
||||
}
|
||||
$escapeWidth = [FilesQuickViewProbe]::Send($editor,2164,0,3).ToInt32() -
|
||||
[FilesQuickViewProbe]::Send($editor,2164,0,0).ToInt32()
|
||||
if($escapeWidth -le [FilesQuickViewProbe]::Send($editor,2279,0,0).ToInt32()){
|
||||
throw 'The control byte did not render as a full visible escape'
|
||||
}
|
||||
if($BinaryImage){
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$bounds = [FilesCommandsUi+Rect]::new()
|
||||
[void][FilesCommandsUi]::GetClientRect($preview,[ref]$bounds)
|
||||
$bitmap = [Drawing.Bitmap]::new($bounds.Right,$bounds.Bottom)
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
$dc = $graphics.GetHdc()
|
||||
try { if(![FilesCommandsUi]::PrintWindow($preview,$dc,3)){throw 'Could not render binary preview'} }
|
||||
finally { $graphics.ReleaseHdc($dc) }
|
||||
$bitmap.Save($BinaryImage,[Drawing.Imaging.ImageFormat]::Png)
|
||||
} finally { $graphics.Dispose(); $bitmap.Dispose() }
|
||||
}
|
||||
$wideRows = [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32()
|
||||
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,840,920,20)
|
||||
[void](Wait-Until 'binary rows wrap in a narrower pane' { [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32() -gt $wideRows })
|
||||
|
||||
Select-File 'preview.txt'
|
||||
[void](Wait-Until 'ordinary text preview restored' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
|
||||
if ([FilesQuickViewProbe]::IsWindowVisible($mode) -or [FilesQuickViewProbe]::Send($editor,2269,0,0) -ne $initialWrap -or
|
||||
[FilesQuickViewProbe]::Send($editor,2131,0,0) -ne $initialScrollbar) { throw 'Preview mode leaked into a text file' }
|
||||
[void][FilesQuickViewProbe]::Post($window,0x801F,0,0)
|
||||
[void](Wait-Until 'Quick View closed' { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero })
|
||||
foreach ($control in $rightList, $rightHeading, $rightPath) {
|
||||
if (![FilesQuickViewProbe]::IsWindowVisible($control)) {
|
||||
throw 'A file panel control remained hidden after closing Quick View.'
|
||||
}
|
||||
}
|
||||
'Quick View hides the covered list and chrome, then restores the same controls.'
|
||||
'Quick View verified with offline HTML, source switching, bounded binary glyphs and restored file panels.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() }
|
||||
}
|
||||
if ($network) { $network.Stop() }
|
||||
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = $profile
|
||||
foreach ($name in $names) {
|
||||
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
|
||||
else { $key.DeleteValue($name, $false) }
|
||||
@@ -96,6 +229,14 @@ try {
|
||||
$path = [IO.Path]::GetFullPath($fixture.FullName)
|
||||
if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and
|
||||
[IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) {
|
||||
[IO.Directory]::Delete($path, $true)
|
||||
for($attempt=0; $attempt -lt 50; ++$attempt){
|
||||
try {
|
||||
[IO.Directory]::Delete($path, $true)
|
||||
break
|
||||
} catch [System.IO.IOException] {
|
||||
if($attempt -eq 49){throw}
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -160,11 +160,40 @@ void hexBytes(const fs::path &file)
|
||||
const auto text=ks::files::formatHexPage(bytes,0);
|
||||
check(text.starts_with("0000000000000000 EF BB BF 00 41 FF 7F 0D 0A") &&
|
||||
text.ends_with("|....A.... |"),"Hex and ASCII columns retain unprintable bytes and alignment");
|
||||
const std::string controls("\x00\x01\x09\x0A\x0D\x1B\x1F A\x7F\x80\xFF",12);
|
||||
const std::string symbols(reinterpret_cast<const char *>(u8"\ue000\ue001\ue009\ue00a\ue00d\ue01b\ue01f A\ue07f\u00c7\ue0ff"));
|
||||
check(ks::files::formatBinarySymbols(controls)==symbols,"Quick View displays all control and high bytes as glyphs");
|
||||
const std::string slash(reinterpret_cast<const char *>(u8"\ue05c"));
|
||||
check(ks::files::formatBinarySymbols("\\x00")==slash+"x00","Binary preview distinguishes literal escapes");
|
||||
check(ks::files::formatBinarySymbols({}).empty(),"An empty symbol preview stays empty");
|
||||
const std::string twoRows(17,'a');
|
||||
check(ks::files::formatHexPage(twoRows,0).find("\r\n0000000000000010 61")!=std::string::npos,
|
||||
"Hex offsets advance by the row width");
|
||||
}
|
||||
|
||||
void watchedEditor(const fs::path &file)
|
||||
{
|
||||
writeFile(file,"original bytes");
|
||||
TextDocument editor(file,true,TextEncoding::automatic,true);
|
||||
check(editor.expectedVersion().has_value(),"local editor captured the original version");
|
||||
writeFile(file,"external bytes");
|
||||
check(editor.readPage(0)=="original bytes","external edit replaced the editor snapshot");
|
||||
editor.stage(0,"editor buffer");
|
||||
bool rejected=false;
|
||||
try {editor.save();}
|
||||
catch(const std::runtime_error &error)
|
||||
{
|
||||
rejected=std::string_view(error.what()).find("changed outside Files")!=std::string_view::npos;
|
||||
}
|
||||
check(rejected && editor.readPage(0)=="editor buffer","external edit was overwritten or the draft was cleared");
|
||||
TextDocument reloaded(file,true,TextEncoding::automatic,true);
|
||||
check(reloaded.readPage(0)=="external bytes","reload did not take the external version");
|
||||
reloaded.stage(0,"confirmed write");
|
||||
check(reloaded.save() && reloaded.readPage(0)=="confirmed write","local save lost the new snapshot");
|
||||
writeFile(file,"next change");
|
||||
check(reloaded.readPage(0)=="confirmed write","the post-save editor lost snapshot isolation");
|
||||
}
|
||||
|
||||
void bookmarkedLines(const fs::path &file)
|
||||
{
|
||||
const auto longLine=std::string(TextDocument::pageBytes+32,'x');
|
||||
@@ -256,6 +285,7 @@ int main()
|
||||
rejectExternalReplacement(fixture.directory / L"external.txt");
|
||||
saveDraft(fixture.directory / L"created.txt");
|
||||
hexBytes(fixture.directory / L"raw.bin");
|
||||
watchedEditor(fixture.directory / L"watched.txt");
|
||||
bookmarkedLines(fixture.directory / L"bookmarks.txt");
|
||||
comparisonEdits();
|
||||
sparseFile(fixture.directory / L"5gib.log");
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user