Compare commits
95
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ce99e5af9 | ||
|
|
a517b6ceb0 | ||
|
|
ab41b4383c | ||
|
|
0e9e5dd2ef | ||
|
|
40884cfc9e | ||
|
|
9db4a25c46 | ||
|
|
15a95e5d74 | ||
|
|
0de58834cf | ||
|
|
777af43c66 | ||
|
|
c4a4f5e488 | ||
|
|
00966549d8 | ||
|
|
783a6d69af | ||
|
|
4cd127a597 | ||
|
|
ff0d57d16b | ||
|
|
3be628cd8f | ||
|
|
f5fc7d205c | ||
|
|
7387058dce | ||
|
|
8b3fe947a6 | ||
|
|
7626e6c9c2 | ||
|
|
3af1f09088 | ||
|
|
53842935a7 | ||
|
|
bdd058f493 | ||
|
|
e7624b620e | ||
|
|
367a5fd9f7 | ||
|
|
4095c889c1 | ||
|
|
d8c329c265 | ||
|
|
debd2b9cd9 | ||
|
|
90c93fba8c | ||
|
|
a09d5e72d1 | ||
|
|
c0bca1b4a2 | ||
|
|
d5ee6ee024 | ||
|
|
5cf0ff5140 | ||
|
|
9c3de731ec | ||
|
|
3b487d0af4 | ||
|
|
9c935fe4da | ||
|
|
4f0a1b5f27 | ||
|
|
524a2d4329 | ||
|
|
5bca97f864 | ||
|
|
0d714147ea | ||
|
|
a0aeb62270 | ||
|
|
4be9b24c4b | ||
|
|
9c30dd91b4 | ||
|
|
5ba51ebb00 | ||
|
|
2bc6eb60c9 | ||
|
|
9c1badcb45 | ||
|
|
9dcc20673a | ||
|
|
ec4079b346 | ||
|
|
41cef4d4f3 | ||
|
|
b53b5715ab | ||
|
|
01f44d22b5 | ||
|
|
c78090f7d4 | ||
|
|
0d797c4f35 | ||
|
|
b6eaa2c85d | ||
|
|
72024c3385 | ||
|
|
d60ef626f0 | ||
|
|
e144cd6607 | ||
|
|
05a3f7a8f4 | ||
|
|
12b8f5090c | ||
|
|
19d574edcf | ||
|
|
3840744819 | ||
|
|
94e8ba4304 | ||
|
|
edb1440be0 | ||
|
|
8ef13ca9bd | ||
|
|
c0eca89738 | ||
|
|
0b6709495b | ||
|
|
5f0c51b557 | ||
|
|
733b6deefa | ||
|
|
b3a1e762ec | ||
|
|
219bdd4883 | ||
|
|
d018b91397 | ||
|
|
2d4df0daa8 | ||
|
|
773df250a4 | ||
|
|
b5924feb23 | ||
|
|
c285505d79 | ||
|
|
2e1b0446bc | ||
|
|
5ac3735db3 | ||
|
|
03984705fe | ||
|
|
dedc42f0db | ||
|
|
e5d639a72f | ||
|
|
4d68c80409 | ||
|
|
6af042a524 | ||
|
|
b28789a4f5 | ||
|
|
eaae5389d9 | ||
|
|
88b8536116 | ||
|
|
b8997d1dd2 | ||
|
|
1926bce15f | ||
|
|
afddcafdac | ||
|
|
21d28a0f6d | ||
|
|
f73dce7bb3 | ||
|
|
3c5f59ed91 | ||
|
|
e50fbbc119 | ||
|
|
6c5b09132f | ||
|
|
92774881ed | ||
|
|
353f4c2919 | ||
|
|
733f1b0fc9 |
No files matched your search
@@ -4,5 +4,6 @@
|
||||
/.vs/
|
||||
/.idea/
|
||||
/dist/
|
||||
/Release/KSwitcher-win-x64.zip
|
||||
/build-output.txt
|
||||
*.user
|
||||
+36
-5
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.98 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.7.2 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
@@ -7,6 +7,11 @@ 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 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/kswitcher-files-compare.ico")
|
||||
include(cmake/FilesTextLibraries.cmake)
|
||||
set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files")
|
||||
target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
|
||||
@@ -22,7 +27,7 @@ add_custom_target(check-files-search-arrow
|
||||
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)
|
||||
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
|
||||
else()
|
||||
@@ -47,7 +52,10 @@ target_link_libraries(KSwitcherFiles PRIVATE kscore)
|
||||
target_include_directories(kscore PUBLIC src PRIVATE vendor)
|
||||
target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
|
||||
target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore)
|
||||
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1")
|
||||
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-paused.ico")
|
||||
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
|
||||
target_link_libraries(KSwitcher PRIVATE kscore)
|
||||
@@ -56,6 +64,7 @@ set_target_properties(KSwitcherConfig PROPERTIES OUTPUT_NAME "KSwitcher.Config")
|
||||
target_compile_definitions(KSwitcherConfig PRIVATE KS_CONFIG_APP)
|
||||
target_link_libraries(KSwitcherConfig PRIVATE kscore)
|
||||
add_executable(KSwitcherTests tests/tests.cpp)
|
||||
target_include_directories(KSwitcherTests PRIVATE vendor)
|
||||
add_executable(KSwitcherSyncTests tests/sync.cpp)
|
||||
target_include_directories(KSwitcherSyncTests PRIVATE vendor)
|
||||
target_link_libraries(KSwitcherSyncTests PRIVATE kscore)
|
||||
@@ -78,7 +87,7 @@ if(MSVC)
|
||||
else()
|
||||
target_link_options(KSwitcherFarSnippetTests PRIVATE -municode -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_executable(KSwitcherInputTests tests/input.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
add_executable(KSwitcherInputTests tests/input.cpp tests/input_pause.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherInputTests PRIVATE kscore)
|
||||
target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES)
|
||||
add_executable(KSwitcherScreenshotUITests tests/screenshot_ui.cpp resources/app.rc)
|
||||
@@ -137,6 +146,13 @@ else()
|
||||
target_link_options(KSwitcherLanTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME lan-pairing-regressions COMMAND KSwitcherLanTests)
|
||||
add_executable(KSwitcherLanClientsTests tests/lan_clients.cpp)
|
||||
target_link_libraries(KSwitcherLanClientsTests PRIVATE kscore)
|
||||
if(NOT MSVC)
|
||||
target_link_options(KSwitcherLanClientsTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME lan-trusted-clients COMMAND KSwitcherLanClientsTests)
|
||||
set_tests_properties(lan-trusted-clients PROPERTIES TIMEOUT 15)
|
||||
add_executable(KSwitcherLanFilesTests tests/lan_files.cpp)
|
||||
target_link_libraries(KSwitcherLanFilesTests PRIVATE kscore)
|
||||
add_test(NAME lan-files-regressions COMMAND KSwitcherLanFilesTests)
|
||||
@@ -155,10 +171,21 @@ add_test(NAME files-system-open
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
|
||||
-SystemOpenOnly)
|
||||
set_tests_properties(files-system-open PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
|
||||
add_test(NAME files-comparison-splitter
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>")
|
||||
set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
|
||||
find_program(KSWITCHER_NODE NAMES node)
|
||||
if(KSWITCHER_NODE)
|
||||
add_test(NAME files-terminal-enter
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
|
||||
-TerminalOnly -Node "${KSWITCHER_NODE}")
|
||||
set_tests_properties(files-terminal-enter PROPERTIES RUN_SERIAL TRUE TIMEOUT 90)
|
||||
add_executable(KSwitcherFilesMarkdownLanFixture WIN32 tests/files_markdown_lan.cpp
|
||||
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp)
|
||||
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
|
||||
target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText)
|
||||
@@ -193,7 +220,10 @@ else()
|
||||
target_link_options(KSwitcherChatProfileTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests)
|
||||
add_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout)
|
||||
set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
|
||||
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
|
||||
target_include_directories(KSwitcherHistoryHostTests PRIVATE vendor)
|
||||
target_link_libraries(KSwitcherHistoryHostTests PRIVATE kscore psapi)
|
||||
set_target_properties(KSwitcherHistoryHostTests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/history-host-fixture-$<CONFIG>")
|
||||
add_dependencies(KSwitcherHistoryHostTests KSwitcher KSwitcherScreenshot)
|
||||
@@ -248,6 +278,7 @@ add_test(NAME utilities-regressions COMMAND KSwitcherUtilitiesTests)
|
||||
add_test(NAME stayhere-lifecycle COMMAND powershell -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/stayhere.ps1" -Executable "$<TARGET_FILE:StayHereTest>")
|
||||
add_test(NAME scroll-regressions COMMAND KSwitcherScrollTests)
|
||||
add_test(NAME input-regressions COMMAND KSwitcherInputTests)
|
||||
add_test(NAME tray-input-pause COMMAND KSwitcherInputTests --input-pause)
|
||||
add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests)
|
||||
add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --save-only)
|
||||
add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$<TARGET_FILE:KSwitcher>")
|
||||
|
||||
+224
-31
@@ -1,6 +1,7 @@
|
||||
# Оформлення KSwitcher Files
|
||||
|
||||
Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far.
|
||||
Іконка головного вікна показує дві сині панелі з бірюзовою рамкою та виділеним рядком.
|
||||
|
||||
Власні модальні діалоги панелей, редактора й переглядача використовують
|
||||
`FilesModalDialog`. Escape і клік поза діалогом у клієнтській області Files
|
||||
@@ -18,35 +19,154 @@ Far Manager є зразком для оформлення файлового м
|
||||
не займають місця. Перед завершенням змін перевір коротке повідомлення й
|
||||
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
|
||||
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
|
||||
Панелі, списки попапів і довгі повідомлення використовують вузьку смугу
|
||||
прокрутки зі стрілками вгорі й унизу та крапковою доріжкою. Відтінки доріжки
|
||||
й повзунка залежать від фону, на якому вони малюються. Повзунок світліший
|
||||
за доріжку й показує положення та розмір видимої частини списку.
|
||||
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
|
||||
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
|
||||
Warning і початковий фокус на No.
|
||||
|
||||
## Скорочення
|
||||
|
||||
- **FTP** у меню джерел (Alt+F1 для лівої панелі, Alt+F2 для правої)
|
||||
відкриває список збережених підключень у вибраній панелі. Shift+F4
|
||||
додає підключення, F4 редагує виділене, Enter відкриває його.
|
||||
У формі вкажи назву, сервер, порт (типово 21), ім’я користувача й пароль.
|
||||
Порожнє ім’я означає анонімний вхід. Паролі зберігаються локально
|
||||
із захистом Windows DPAPI. Звичайний FTP передає дані без шифрування.
|
||||
Після підключення панель показує справжній шлях початкового каталогу
|
||||
сервера. Enter або подвійний клік на `..` відкриває батьківську папку.
|
||||
У корені рядка `..` немає. Щоб повернутися до списку підключень,
|
||||
вибери FTP в меню джерел панелі.
|
||||
Назви файлів і папок передаються в UTF-8. Для старого сервера, який
|
||||
використовує системну кодову сторінку Windows, увімкни в профілі
|
||||
**Use Windows encoding for file names** і підключися знову.
|
||||
- F5 копіює поточний або позначені файли й папки між локальною та
|
||||
підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої
|
||||
панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі.
|
||||
Використовуються спільні діалоги Copy, прогресу та конфлікту імен.
|
||||
Поточний файл записується під тимчасовим ім’ям до завершення передачі.
|
||||
Для заміни файла FTP-сервер має приймати перейменування поверх нього.
|
||||
- У підключеній FTP-панелі F3 та Enter відкривають файл у Viewer, а F4
|
||||
відкриває Editor. Файл завантажується у тимчасову копію у фоні.
|
||||
F2 в Editor передає зміни назад на FTP. Якщо сервер повідомляє інший
|
||||
розмір або час зміни файла, запис скасовується, а правки лишаються в редакторі.
|
||||
- У підключеній FTP-панелі F6 перейменовує один файл або папку в поточному
|
||||
каталозі. Якщо нове ім’я зайняте, Files показує помилку. F8 запитує
|
||||
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
|
||||
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
|
||||
|
||||
- **F9 → Commands → Compare files** порівнює два позначені текстові файли
|
||||
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
|
||||
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
|
||||
FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
|
||||
рядків і підсвічуванням вставок, видалень і замін. У замінених рядках
|
||||
виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8)
|
||||
переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків.
|
||||
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
|
||||
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
|
||||
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
|
||||
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
|
||||
Текст файлів і порожня область під ним мають білий фон, рядки
|
||||
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
|
||||
Центральний розділювач можна перетягнути мишею. Під час зміни розміру
|
||||
вікна пропорція колонок зберігається.
|
||||
Ctrl+колесо змінює масштаб тексту в поточному вікні.
|
||||
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
|
||||
на панелі завдань. У **Options → File comparison → Font and colors**
|
||||
можна окремо налаштувати шрифт, тло, текст і кольори змін.
|
||||
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
|
||||
і меню Commands показує поточне призначення.
|
||||
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
|
||||
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
|
||||
Вставлені й видалені порожні рядки враховуються завжди.
|
||||
Кнопка розгортання в системному заголовку збільшує вікно порівняння
|
||||
до робочої області екрана. Повторне натискання відновлює попередній розмір.
|
||||
Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM,
|
||||
до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються
|
||||
як рівнозначні.
|
||||
|
||||
- У меню Files і його списках, що випадають, стрілки вгору й вниз
|
||||
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
|
||||
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
|
||||
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP.
|
||||
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
|
||||
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
|
||||
до закриття меню, навіть коли оновлюється список LAN.
|
||||
|
||||
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
|
||||
документ — у програмі, призначеній для його типу у Windows. EXE запускається
|
||||
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
|
||||
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
|
||||
панелі LAN, спочатку скопіюй його до локальної папки.
|
||||
- Shift+Enter відкриває поточний локальний елемент через Windows.
|
||||
Після успішного відкриття локального файла через Windows його шлях
|
||||
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
|
||||
його курсор приховано. При виборі
|
||||
з історії у командний рядок підставляється команда, яка повторює відкриття.
|
||||
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
|
||||
елемент через Windows.
|
||||
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
|
||||
Введена в командному рядку команда зберігається.
|
||||
|
||||
- У головному вікні клавіатурний фокус залишається в командному рядку.
|
||||
Tab перемикає активну панель, клік вибирає рядок, а стрілки вгору й вниз,
|
||||
Page Up і Page Down пересувають курсор у панелі навіть під час набору команди.
|
||||
Tab без модифікаторів перемикає активну панель, а клік вибирає рядок.
|
||||
Ctrl+U міняє видимі панелі місцями разом із їхніми папками, режимами,
|
||||
курсорами й позначками. Активна панель залишається активною на новому боці.
|
||||
Page Up і Page Down пересувають курсор у панелі. Стрілки вгору й вниз
|
||||
керують панеллю, коли список підказок закритий.
|
||||
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
|
||||
командний рядок порожній.
|
||||
Ctrl+← і Ctrl+→ зміщують розділювач видимих панелей на ширину одного символу.
|
||||
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
|
||||
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
|
||||
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
|
||||
курсора він мав інше оформлення.
|
||||
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
|
||||
текст із буфера обміну в позицію курсора або замінюють виділення.
|
||||
Enter запускає введену команду або відкриває поточний елемент, якщо рядок
|
||||
порожній. Escape очищає рядок.
|
||||
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
|
||||
виконує команду одразу. Коли рядок
|
||||
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
|
||||
Enter передає порожній рядок у термінал.
|
||||
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
|
||||
командного рядка й виконують відповідну дію за тими самими правилами.
|
||||
Локальна команда запускається в папці активної панелі, яку показано
|
||||
перед командним рядком. Після перемикання панелі або переходу до іншої
|
||||
папки наступна команда використовує нову папку навіть у вже відкритому
|
||||
PowerShell. Якщо команда змінює папку (наприклад, через `cd`), панель
|
||||
переходить до неї, якщо користувач за цей час не змінив її розташування.
|
||||
Під час запуску термінала область виводу має темне тло, поки WebView2
|
||||
готує сторінку.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
- Під час набору локальної команди над полем з’являються підказки PowerShell.
|
||||
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
|
||||
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
|
||||
та шляхи відносно робочої папки активної панелі.
|
||||
Після `cd ` список пропонує папки,
|
||||
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
|
||||
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
|
||||
Enter вставляє виділену, а клік вставляє підказку під вказівником.
|
||||
Щоб виконати команду після вставлення, натисни Enter ще раз.
|
||||
Escape закриває список зі збереженням тексту. Без списку Escape очищає
|
||||
рядок, а Tab перемикає панель, якщо панелі відкриті. Доступні підказки стандартної локальної
|
||||
сесії PowerShell, включно з програмами з PATH. Для команд без аргументів,
|
||||
як-от `cls`, список не пропонує шляхи.
|
||||
Для `dotnet` підкоманди й параметри підказує встановлений .NET SDK.
|
||||
Для `git` підкоманди, параметри й доречні назви гілок бере штатний
|
||||
скрипт Git for Windows. Підказки використовують локальні дані репозиторію.
|
||||
- Довідник Windows Commands надає офлайн підказки ключів і підкоманд для
|
||||
системних утиліт. Наприклад, `ipconfig /re` пропонує `/release` і `/renew`,
|
||||
`reg q` пропонує `query`, а `cmd /c dir /` пропонує ключі `dir` для CMD.
|
||||
Каталог також підказує вкладені підкоманди та значення, перелічені в
|
||||
синтаксисі. Наприклад, `netsh interface ipv4 show co` пропонує `config`,
|
||||
а `schtasks /query /fo ` пропонує `CSV`, `LIST` і `TABLE`. F1 у командному
|
||||
рядку відкриває статтю Microsoft Learn для поточної команди чи підкоманди.
|
||||
Якщо ввести `dir` безпосередньо у Files, PowerShell підказує власні параметри.
|
||||
Після `ipconfig /renew ` або `ipconfig /release ` список підказує назви
|
||||
локальних адаптерів із DHCP для IPv4. Назви з пробілами вставляються в лапках.
|
||||
- Коли курсор у кінці рядка, список спочатку показує до 5 різних
|
||||
останніх команд з історії, які починаються з набраного тексту.
|
||||
Вибір підставляє всю команду. Підказки з історії доступні й у LAN-панелі.
|
||||
|
||||
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
|
||||
що й клавіша F8.
|
||||
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
|
||||
@@ -66,6 +186,15 @@ Warning і початковий фокус на No.
|
||||
**Options → Command line → Command history → Allow paired PCs to hibernate this PC**.
|
||||
Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Для цієї дії
|
||||
потрібні оновлення на обох ПК і ввімкнена гібернація Windows.
|
||||
- У **Change drive** (Alt+F1 або Alt+F2) підкреслена дія **Wake** є праворуч
|
||||
від стану офлайн-ПК. Клік по слову або Enter з фокусом на дії надсилає пакет.
|
||||
Статус відображається на тлі списку. Для текстових дій усередині рядків
|
||||
використовуй спільний компонент `InlineListAction` для малювання, фокуса
|
||||
й обробки кліків. KSwitcher
|
||||
має зберегти MAC-адресу мережевого адаптера. Оновіть KSwitcher та дайте
|
||||
обом ПК побачити один одного в локальній мережі. На цільовому ПК потрібна
|
||||
підтримка Wake-on-LAN у прошивці та налаштуваннях адаптера. Рядок стану
|
||||
повідомляє про надсилання пакета або відсутність збереженої MAC-адреси.
|
||||
- **F9 → Commands → Update remote KSwitcher** запускає штатне оновлення для
|
||||
ПК активної LAN-панелі. Підтвердження з іменем ПК показується у Files
|
||||
відправника. На цільовому ПК потрібен дозвіл **Options → Command line →
|
||||
@@ -77,17 +206,36 @@ Warning і початковий фокус на No.
|
||||
|
||||
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
|
||||
курсора командного рядка або замінює виділення. Подвійні лапки додаються
|
||||
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
|
||||
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
|
||||
відкритої в активній панелі.
|
||||
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
|
||||
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
|
||||
панелі показує «Reading» з лічильником прочитаних файлів і папок та
|
||||
підказкою [Esc].
|
||||
До завершення читання панель зберігає попередній список. Escape зупиняє
|
||||
сканування активної панелі й відкриває прочитану частину папки. Якщо
|
||||
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
|
||||
повторює сканування, щоб отримати повний список. Після переходу
|
||||
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
|
||||
панель не перемальовується через цей перехід.
|
||||
Якщо надійшов новіший запит, результат попереднього
|
||||
сканування пропускається. Після підтвердження UAC очікування списку
|
||||
від підвищеного процесу теж відбувається у фоні.
|
||||
- Якщо Windows відмовляє у правах для F5, F6, F7 або F8 на локальних
|
||||
дисках, Files пропонує повторити операцію з правами адміністратора.
|
||||
Після підтвердження UAC допоміжний процес обробляє захищені елементи
|
||||
поточної операції. Відмова в діалозі або в UAC зупиняє операцію.
|
||||
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
|
||||
зберігаються для наявних елементів, а підраховані через F3 розміри папок
|
||||
скидаються. F2 також виконує цю дію.
|
||||
- Ctrl+C копіює весь введений у командний рядок текст, навіть коли виділено
|
||||
лише його частину.
|
||||
- Ctrl+Insert копіює імена позначених файлів і папок активної панелі в порядку
|
||||
відображення, по одному на рядок. Якщо позначок немає, копіюється ім’я під
|
||||
курсором. Шляхи й рядок `..` пропускаються.
|
||||
- Ctrl+C і Ctrl+Insert копіюють виділений текст із виводу термінала.
|
||||
- За відсутності виділення у виводі Ctrl+C копіює весь введений у командний
|
||||
рядок текст, навіть коли виділено лише його частину.
|
||||
- Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок
|
||||
порожній, копіюються імена позначених файлів і папок активної панелі в
|
||||
порядку відображення, по одному на рядок. Якщо позначок немає, копіюється
|
||||
ім’я під курсором. Шляхи й рядок `..` пропускаються.
|
||||
|
||||
- Ctrl+E підставляє останню команду. Повторне натискання
|
||||
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
|
||||
@@ -134,7 +282,8 @@ Warning і початковий фокус на No.
|
||||
- Глобальне скорочення повертає до відкритого вікна Files у поточній сесії Windows або запускає Files, якщо такого вікна немає. Пункт **Files** у треї відкриває нове вікно.
|
||||
|
||||
- Ctrl+Shift+0–9 відкриває діалог Title і Path із поточною папкою. OK додає запис без дублювання, Escape скасовує. Title необов’язковий, порожнє значення показує шлях. Записи LAN зберігають ID ПК, а редагування Path залишає запис на тому самому ПК.
|
||||
- Ctrl+0–9 одразу відкриває єдину папку. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису. Brief і Wide доступні в меню Left/Right та Options.
|
||||
- Ctrl+0–9 відкриває лише папки, призначені натиснутій цифрі. Єдина папка відкривається одразу. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
|
||||
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options.
|
||||
|
||||
## Налаштування Files
|
||||
|
||||
@@ -145,34 +294,65 @@ Warning і початковий фокус на No.
|
||||
відкриває файл у програмі, призначеній Windows для цього типу, а Alt+F4
|
||||
викликає зареєстровану дію Edit. Ці команди також є в меню Commands.
|
||||
F10 або × закривають головне вікно Files. Вбудовані Viewer та Editor
|
||||
відкриваються в окремих немодальних вікнах із власними кнопками на панелі
|
||||
завдань Windows. При повторному відкритті Files пропонує перейти до вже
|
||||
відкриваються в окремих немодальних вікнах. Редактор має іконку олівця,
|
||||
переглядач — іконку ока. Ці іконки видно в заголовку, в Alt+Tab і в окремих
|
||||
групах на панелі завдань Windows. F6 змінює іконку й групу поточного вікна.
|
||||
При повторному відкритті Files пропонує перейти до вже
|
||||
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
|
||||
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
|
||||
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
|
||||
Помилка збереження залишає відкритим редактор зі змінами.
|
||||
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
|
||||
у порядку їх відкриття.
|
||||
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
|
||||
порядку. Коли відкрито лише Files, активна панель не змінюється.
|
||||
- Shift+F4 у локальній панелі відкриває Editor для наявного або нового файла.
|
||||
Порожнє ім’я підставляє `New_File_<дата>_<час>.txt`. Новий файл з’являється
|
||||
на диску після збереження. Esc після змін пропонує Save, Discard або Cancel.
|
||||
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
|
||||
рядків. Скасування параметрів залишає текст у редакторі.
|
||||
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
|
||||
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
|
||||
із підсвічуванням Markdown.
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Клік по чекбоксу
|
||||
одразу записує позначку у вихідний Markdown. У разі помилки збереження
|
||||
попередній стан відновлюється. Підписи з'єднань малюються поверх стрілок.
|
||||
F4 відкриває текст із підсвічуванням Markdown.
|
||||
HTML усередині Markdown підтримує таблиці, текстове форматування, посилання,
|
||||
відносні зображення й окремі стилі, зокрема `white-space: nowrap` у клітинках.
|
||||
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
|
||||
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
|
||||
Вихідний текст приховано, доки Markdown і Mermaid готують перегляд.
|
||||
Звичайний клік відкриває внутрішнє посилання в тому самому вікні,
|
||||
Shift+клік відкриває окреме вікно. Назад і вперед працюють через стрілки
|
||||
перегляду, бічні кнопки миші й Alt+←/→. Ctrl+W закриває перегляд.
|
||||
Ctrl+F або кнопка пошуку відкриває пошук у відрендерованому документі.
|
||||
Пошук без урахування регістру показує кількість збігів і підсвічує поточний.
|
||||
Enter і F3 переходять до наступного збігу, а Shift+Enter і Shift+F3 — до
|
||||
попереднього, циклічно. Escape спочатку закриває поле пошуку.
|
||||
Коли локальний Markdown оновлюється на диску, відкритий перегляд
|
||||
перерендерюється зі збереженням позиції прокрутки.
|
||||
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
|
||||
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
|
||||
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
|
||||
8 МіБ, F3 відкриває текстовий перегляд.
|
||||
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
|
||||
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
|
||||
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
|
||||
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
|
||||
кліку. Mermaid працює офлайн і завантажується лише для документів із
|
||||
діаграмами Mermaid. Якщо WebView2 не завершує запуск, Files один раз
|
||||
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
|
||||
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
|
||||
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
|
||||
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
|
||||
позначених папок в інших рядках рахує позначені папки. Без позначок
|
||||
F3 рахує папку під курсором або відкриває файл. Папки обробляються по черзі,
|
||||
і результат кожної видно в колонці Size у широкому режимі та в рядку
|
||||
стану, коли там увімкнено розмір. Це працює і в LAN- та FTP-панелях. Посилання й
|
||||
junction не обходяться. Недоступний вміст позначається як частковий результат.
|
||||
Папки, які чекають на підрахунок, мають позначку Queued. Через дві секунди
|
||||
підрахунку в рядку поточної папки з’являється спінер.
|
||||
Пересування курсора в списку залишає спінер у рядку папки, яку ще рахують.
|
||||
Esc скасовує поточний підрахунок і чергу активної панелі, залишаючи
|
||||
вже обчислені розміри та поточний каталог.
|
||||
Перехід до іншого каталогу чи джерела панелі скасовує підрахунок.
|
||||
- Під списком кожної панелі з позначками показано кількість позначених
|
||||
елементів і їхній сумарний розмір. Файли враховуються одразу, папки — у
|
||||
міру завершення підрахунку через F3. Позначка ≥ означає, що сума
|
||||
неповна, а число біля «to measure» показує, скільки позначених папок
|
||||
ще без розміру.
|
||||
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
|
||||
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
|
||||
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
|
||||
@@ -207,6 +387,11 @@ Warning і початковий фокус на No.
|
||||
кодування. Нередаговані байти копіюються без перетворення.
|
||||
- Команда Options у панелях, редакторі й переглядачі відкриває один діалог
|
||||
KSwitcher Files Options. Розділи Viewer та Editor зберігають окремі профілі.
|
||||
**Viewer → Markdown** задає максимальну ширину документа (0 — усе вікно),
|
||||
гарнітуру та розмір основного тексту. Порожня гарнітура використовує системний
|
||||
шрифт. Apply одразу оновлює відкриті перегляди Markdown.
|
||||
Після повторного відкриття Options відновлюється останній розділ, зокрема
|
||||
після Cancel. Пошуковий запит і чернетка змін не зберігаються.
|
||||
З редактора або переглядача діалог відкриває відповідний розділ. Apply
|
||||
застосовує зміни до відкритих вікон, Cancel відкидає незастосовану чернетку.
|
||||
Доступні перенесення рядків, номери рядків, показ пробілів і
|
||||
@@ -248,10 +433,6 @@ Warning і початковий фокус на No.
|
||||
у відкритих локальних папках. Фокус залишається там, де був, а курсор
|
||||
лишається на поточному елементі, якщо той ще існує.
|
||||
|
||||
- Ctrl+8 відкриває список усіх ярликів папок. Кожен рядок показує групу
|
||||
й назву або шлях. Enter відкриває папку в активній панелі, F4 редагує
|
||||
ярлик, а Delete прибирає його зі списку.
|
||||
|
||||
- У Change drive повідомлення No paired computers з’являється після
|
||||
успішної відповіді з порожнім списком. Збої локального запиту до
|
||||
KSwitcher відображаються окремо.
|
||||
@@ -283,6 +464,7 @@ Warning і початковий фокус на No.
|
||||
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
|
||||
|
||||
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
|
||||
Розділювач Size проходить по одній вертикалі в заголовку та списку, а праві краї підпису й значень вирівняні.
|
||||
|
||||
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
@@ -294,7 +476,9 @@ Warning і початковий фокус на No.
|
||||
- Власні діалоги Files блокують дії панелей і командного рядка, залишаючи
|
||||
системний заголовок і рамку головного вікна доступними. Клік у Files поза діалогом
|
||||
діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває
|
||||
підтвердження скасування.
|
||||
підтвердження скасування. Перелік і обробка файлів виконуються у фоновому
|
||||
потоці. Діалог залишається доступним під час очікування файлового вводу-виводу.
|
||||
Скасування перевіряється між кроками операції та під час передачі блоків.
|
||||
|
||||
- Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No.
|
||||
|
||||
@@ -307,7 +491,16 @@ Warning і початковий фокус на No.
|
||||
- Search і спільні нижні секції Far використовують компактні проміжки між рядками й кнопками, прив’язані до метрик моноширинного шрифту. У Search висота кнопки дорівнює висоті одного рядка.
|
||||
- Нижні кнопки Far групуються по центру. Їхня ширина залежить від напису й дужок, а проміжок між ними становить приблизно половину символу.
|
||||
- Прапорці Far у Search, Copy і попередженнях використовують спільний компонент. У фокусі короткий системний курсор блимає між дужками, а тло рядка зберігає колір діалогу.
|
||||
- У Copy і Rename/Move помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
|
||||
- У Copy і Rename/Move шлях перевіряється у фоновому потоці, і в цей час
|
||||
діалог можна скасувати. Помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
|
||||
- Помилки копіювання, переміщення й видалення показуються в червоному
|
||||
модальному діалозі Far із причиною помилки та кнопкою OK.
|
||||
- Якщо локальне перейменування або видалення заблоковане, кнопка Processes… відкриває
|
||||
список процесів із назвою та PID. Перевірка папки включає вкладені елементи.
|
||||
End process завершує вибраний процес після окремого підтвердження, після
|
||||
чого список оновлюється. Якщо Windows обмежила доступ або перевірку
|
||||
великої папки завершено частково, про це повідомляється в діалозі.
|
||||
Операцію можна повторити після звільнення файла чи папки.
|
||||
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
|
||||
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
|
||||
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
|
||||
|
||||
+31
-16
@@ -7,21 +7,22 @@ arranged on a monitor grid. Mouse and keyboard follow neighboring cells, includi
|
||||
A → B → C, without relaying input through B. New text and images are also shared
|
||||
with all online paired computers: history and the active clipboard.
|
||||
|
||||
## Files and diagnostic logs
|
||||
## Trusted LAN clients
|
||||
|
||||
In **Settings → Computers → Manage computers…**, select an online paired
|
||||
computer and choose **Send file…**. Both computers need a build with file transfer.
|
||||
Files up to 16 MiB travel over encrypted LAN. On the destination, open
|
||||
**Incoming files…** to save or discard each file. The save dialog suggests the
|
||||
original filename. KSwitcher shows a Windows notification when a file is ready
|
||||
to save, and its tray tooltip shows the pending count. Pending files are held
|
||||
in memory until saved, discarded, or KSwitcher closes.
|
||||
Open **Settings → Computers → Manage computers → Trusted clients** and choose **Add client…**. Select the Dirlume executable and confirm. Dirlume can list existing LAN pairs, browse their drives, and download regular files using each remote computer’s file-access permissions. Pairing credentials stay in the resident KSwitcher process.
|
||||
|
||||
To retrieve the current or rotated diagnostic log, enable **Allow paired
|
||||
computers to download diagnostic logs** on the computer that owns the logs.
|
||||
This setting defaults to off. On the requesting PC, select that computer and
|
||||
choose **Download log…** or **Previous log…**. Diagnostic logs may contain
|
||||
text copied from applications.
|
||||
Select an executable and choose **Remove** to revoke access. Add the executable again after updating it, since KSwitcher checks the approved path and SHA-256 fingerprint.
|
||||
|
||||
## Remote files and diagnostic logs
|
||||
|
||||
Use **KSwitcher Files → Change drive** or Dirlume with a trusted-client entry
|
||||
to browse and copy remote files. Starting in v0.7.0, Manage computers
|
||||
focuses on pairing, shared input and diagnostic logs.
|
||||
|
||||
On the computer that owns the logs, enable **Allow paired computers to download
|
||||
logs** in **Diagnostic logs** (off by default). On the requesting computer,
|
||||
select the paired PC and choose **Current log…** or **Previous log…**.
|
||||
Diagnostic logs may contain text copied from applications.
|
||||
|
||||
### MCP
|
||||
|
||||
@@ -37,8 +38,10 @@ the local resident process running and log downloads enabled on the remote PC.
|
||||
## Set up multiple computers
|
||||
|
||||
1. Install the v0.6.58 or newer on every participating PC. Input protocol v2 requires all participants to update; earlier one-pair builds cannot connect. Preserve local data; do not copy pairing identities between PCs.
|
||||
2. Open **Settings → Computers → Manage computers…** and enable discovery on both PCs.
|
||||
2. Open **Settings → Computers → Manage computers** and enable discovery on both PCs.
|
||||
Only running LAN-enabled KSwitcher instances appear, not generic network devices.
|
||||
In wide windows, Pairing and Input sharing appear side by side. In narrow
|
||||
windows, they stack above Diagnostic logs. Connection help is under Input sharing.
|
||||
3. Match the computer name and instance-ID prefix displayed on the other PC.
|
||||
Select each other, generate one code, enter that same code on both, then click
|
||||
Pair on both within two minutes. Spaces, hyphens and uppercase hex are accepted.
|
||||
@@ -57,6 +60,12 @@ the local resident process running and log downloads enabled on the remote PC.
|
||||
into the source computer restores its cursor at the corresponding edge. Empty
|
||||
cells, diagonal-only neighbors and offline PCs do not transfer control.
|
||||
|
||||
When input sharing is enabled, the tray icon shows a steady gray dot if all
|
||||
paired PCs are offline, a pulsing amber dot while a discovered PC is connecting,
|
||||
a green dot when all online paired PCs are connected, and a red dot if the LAN
|
||||
worker stops. Hover over the icon to see the connection status and the connected
|
||||
count when only some paired PCs are connected.
|
||||
|
||||
The source cursor is parked and hidden beneath a tiny no-activation window. A
|
||||
small banner identifies remote control; no full-screen layered bitmap is retained.
|
||||
The destination uses its own keyboard layout and runs its own hotkeys/snippets.
|
||||
@@ -103,8 +112,14 @@ VLANs, public IPv4 and IPv6-only networks are not supported by discovery yet.
|
||||
A second LAN-enabled KSwitcher cannot use the same ports on one computer.
|
||||
|
||||
Input first tries TCP in the usual direction, then reverse TCP after 1.5 seconds.
|
||||
If TCP has not authenticated after 5 seconds, the lower-ID peer negotiates an
|
||||
encrypted UDP input session on the existing discovery socket (UDP 45883).
|
||||
LAN discovery authenticates paired PCs before starting new input connections.
|
||||
Discovery remains active while all paired PCs are offline and wakes input sharing
|
||||
when one reappears. An authenticated input connection survives missed discovery
|
||||
announcements. Once discovery has expired and the channel closes, further input
|
||||
attempts wait for fresh discovery.
|
||||
After at least 5 seconds, the lower-ID peer starts encrypted UDP fallback on the
|
||||
discovery socket (UDP 45883) once its current TCP connection attempt has failed
|
||||
or reached its 10-second deadline.
|
||||
UDP uses fresh session challenges, authenticated encryption, ordered event
|
||||
numbers, acknowledgements and bounded retries; duplicated packets do not repeat
|
||||
key presses. Two seconds without authenticated traffic or acknowledgement
|
||||
|
||||
@@ -7,11 +7,11 @@ The original [Typlo](https://github.com/bitcodepro/Typlo) project and its data r
|
||||
**[User guide / Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki)** — setup, features, shortcuts, dictionaries, screenshots and troubleshooting in **English** and **[Українська](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk)**. Each wiki page links to its translation.
|
||||
|
||||
From v0.6.72, use **Settings → Snippets** to edit snippets in place and
|
||||
**Save snippets** to save them independently. **Clipboard** contains OCR
|
||||
**Save** to apply snippet edits together with other settings. **Clipboard** contains OCR
|
||||
options. **Sync**, **Computers**, and **Diagnostics** have their own tabs.
|
||||
|
||||
**Українською.** З v0.6.72 сніпети редагуються у **Settings → Snippets**
|
||||
і зберігаються окремою кнопкою **Save snippets**. OCR розміщено у
|
||||
і зберігаються разом з іншими налаштуваннями кнопкою **Save**. OCR розміщено у
|
||||
**Clipboard**, а для синхронізації, ПК та журналу є окремі вкладки
|
||||
**Sync**, **Computers** і **Diagnostics**.
|
||||
|
||||
@@ -148,12 +148,14 @@ updating the application. After verifying a new package, the updater closes File
|
||||
screenshot editors, Settings, and bundled StayHere for that installation. Save open work before approving an update.
|
||||
If settings change in the tray while the configurator is open, a conflicting Save is rejected; reopen
|
||||
the configurator to load the latest settings.
|
||||
Updates from v0.3.x–v0.4.1 first install the compatible **v0.4.2 bridge** through
|
||||
Update in the tray menu. Select Update again to install the full current release;
|
||||
manual extraction is not required. Future full releases use stable `release-vX.Y.Z`
|
||||
tags, which the bridge and newer clients recognize. Older clients ignore those tags
|
||||
and continue to find the bridge instead of skipping it. Versions v0.2.3 and earlier
|
||||
still require the previously documented initial configurator migration.
|
||||
Updates from v0.3.x–v0.4.1 go through the compatible **v0.4.2 bridge**. If tray
|
||||
**Update** does not find it, download [v0.4.2](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2),
|
||||
close KSwitcher and its editors, and extract the bridge ZIP into the installation
|
||||
directory while keeping personal data, dictionaries, and tools. Start v0.4.2
|
||||
and select **Update** to install the current full release. Full releases use
|
||||
stable `release-vX.Y.Z` tags recognized by the bridge and newer clients.
|
||||
Versions v0.2.3 and earlier still require the previously documented initial
|
||||
configurator migration.
|
||||
|
||||
Modern ZIPs contain `release-files.json` (schema, version, file paths, sizes and SHA-256
|
||||
hashes). The updater validates that every packaged file is declared, all hashes match,
|
||||
@@ -183,10 +185,10 @@ Exit [Typlo](https://github.com/bitcodepro/Typlo) when using overlapping shortcu
|
||||
This also works for each layout's **Direct layout shortcut**. Backspace or Delete without modifiers
|
||||
clears a shortcut. Tab moves to the next field. The recorded shortcut is suppressed while the field
|
||||
has focus, so recording the conversion shortcut does not perform a conversion.
|
||||
All configured shortcuts use the existing keyboard hook and can replace ordinary Windows/app
|
||||
The Files shortcut is registered with Windows. The other configured shortcuts use the keyboard hook and can replace ordinary Windows/app
|
||||
shortcuts, including **Win+V** and **Win+Shift+S**, while KSwitcher is running. Only exact configured
|
||||
combinations are intercepted. Unassigned shortcuts and simulated copy/paste pass through.
|
||||
Choose another shortcut or exit KSwitcher to restore the original action. Windows protects
|
||||
Pause input processing, choose another shortcut or exit KSwitcher to restore the original action. Windows protects
|
||||
Ctrl+Alt+Delete and Win+L; these cannot be assigned.
|
||||
|
||||
Keyboard and mouse input forwarded by Microsoft Mouse Without Borders follows the same input
|
||||
@@ -199,6 +201,28 @@ keys cannot trigger recursive commands or overwrite the recorded typing run. Oth
|
||||
is accepted, including key-up events and VK-only keyboard events. Unicode packets do not provide
|
||||
physical key positions and therefore reset recent-word tracking; selection conversion still works.
|
||||
|
||||
### Pause input processing
|
||||
|
||||
Right-click the KSwitcher tray icon and choose **Pause input processing** before testing another keyboard tool.
|
||||
The purple **K** changes to two white pause bars on a gray tile. The tooltip says **Input processing paused** once KSwitcher releases its shortcuts and
|
||||
stops keyboard and mouse actions, autocorrection, snippets, automatic layout switching, LAN mouse and keyboard
|
||||
control, and simulated F15 activity. Clipboard history has its own pause control. You can browse entries
|
||||
during an input pause and paste them after resuming. If you launched the standalone **StayHere** utility,
|
||||
its own tray icon controls its F15 activity.
|
||||
|
||||
Choose **Resume input processing** in the same menu after testing. The tooltip then shows **Input processing active**. If another program still holds a shortcut,
|
||||
KSwitcher identifies the combination and stays paused. Release it in the other program and retry.
|
||||
The pause lasts for the current run.
|
||||
|
||||
**Українською.** Перед тестуванням іншої програми клацни правою кнопкою значок KSwitcher у треї й вибери
|
||||
**Pause input processing**. Фіолетова **K** зміниться на дві білі смуги на сірому тлі. Підказка **Input processing paused** підтвердить паузу. KSwitcher
|
||||
звільняє гарячі клавіші й призупиняє дії клавіатури та миші, автокорекцію, сніпети, автоматичне перемикання
|
||||
розкладки, LAN-керування й імітацію F15. Історія буфера обміну має окремий перемикач. Записи можна переглядати
|
||||
під час паузи та вставляти після відновлення. Якщо окремо запущена утиліта **StayHere**, її імітація F15
|
||||
керується з її власного значка в треї.
|
||||
Для відновлення вибери **Resume input processing**. Підказка покаже **Input processing active**. Якщо комбінація зайнята, звільни вказаний хоткей
|
||||
в іншій програмі та повтори спробу. Пауза діє до завершення поточного запуску.
|
||||
|
||||
### Screen capture and annotations
|
||||
|
||||
Press **Win+Shift+S**, choose **Capture screen region…** in the tray menu, or run
|
||||
@@ -409,8 +433,9 @@ thumbnails and source labels aligned with the scaled fonts and spacing.
|
||||
> З v0.6.50: OCR чатів Viber тимчасово вимкнений. Збережені профілі Viber залишаються, але не діють. Профілі Telegram і Teams та OCR зображень/буфера працюють як раніше.
|
||||
|
||||
|
||||
Settings separates General, Languages, Shortcuts, Clipboard and Tools into native tabs.
|
||||
Switching tabs preserves edits; Save, Cancel, Import and Export stay available below every page.
|
||||
In Settings, choose a section in the navigation tree or use **Search settings** to find an individual option.
|
||||
Drag the divider to resize navigation. The window remembers its size, position, and active section.
|
||||
Switching sections preserves your edits. Save, Cancel, Import and Export stay below every page.
|
||||
|
||||
Open the desired chat in Telegram Desktop or Microsoft Teams, then open Settings → Languages →
|
||||
**Languages for a chat…**. Select the chat and click the languages to include. Choose
|
||||
@@ -431,9 +456,9 @@ profile. Telegram unread counters are ignored. Teams currently recognizes the de
|
||||
Experimental Viber profiles introduced in v0.6.49 are disabled in v0.6.50 because repeated OCR caused delays. There is no background Viber OCR, recognition during language switching, or recognition when opening profiles. Saved Viber profiles are retained and marked inactive; Windows switching and Next layout use their normal/global behavior in Viber. Clipboard and image OCR are unchanged.
|
||||
From v0.6.53, chat profiles (application, visible chat name and ordered language IDs) are included in settings synchronization and manual export/import. Update every synchronizing PC to v0.6.53 or newer first: older clients reject this shared field. Profiles for different chats merge independently; conflicting edits or deletion versus editing of one chat require a choice. Missing Windows layouts stay saved and are skipped during switching, with global-cycle fallback if none are installed. Keep this PC's layouts preserves the global cycle and shortcuts while chat profiles still synchronize. Downloading a pre-v0.6.53 profile preserves existing chat profiles. Chat matching is unchanged; Viber profiles remain inactive.
|
||||
|
||||
**Українською.** Налаштування розділено на вкладки General, Languages, Shortcuts, Clipboard
|
||||
і Tools. Перехід між ними зберігає незбережені зміни; Save, Cancel, Import і Export доступні
|
||||
на кожній вкладці. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages
|
||||
**Українською.** Вибирайте розділ у дереві Settings або шукайте окремий параметр через **Search settings**.
|
||||
Перетягніть розділювач, щоб змінити ширину дерева. Settings запам’ятовує розмір і положення вікна
|
||||
та активний розділ. Перехід між розділами зберігає чернетку. Save, Cancel, Import і Export доступні знизу. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages
|
||||
for a chat…**. Вибери чат і потрібні мови, натисни **Use languages**, а потім **Save**.
|
||||
Набір діє для **Alt+Shift**, **Win+Space**, **Win+Shift+Space** та **Next layout** KSwitcher.
|
||||
Можна вибрати й одну мову; порядок зберігається із загального списку під час редагування профілю. **Remove profile**
|
||||
@@ -459,10 +484,11 @@ Recognition uses Chrome accessibility: the address bar and active document must
|
||||
|
||||
### Snippet autocomplete — v0.6.69
|
||||
|
||||
Starting with v0.6.71, **Enter** accepts a suggestion after you navigate
|
||||
the list with **↑ / ↓**. Without arrow navigation, **Enter** goes to the
|
||||
editor. З v0.6.71 **Enter** після вибору стрілками вставляє сніпет. Без
|
||||
переміщення списком **Enter** надходить до редактора.
|
||||
**Enter** accepts a single visible suggestion directly. When several suggestions
|
||||
are visible, navigate the list with **↑ / ↓** to select one for **Enter**.
|
||||
|
||||
**Українською.** **Enter** одразу підтверджує єдину видиму підказку. Якщо
|
||||
підказок кілька, виберіть потрібну стрілками **↑ / ↓**, а тоді натисніть **Enter**.
|
||||
|
||||
Starting with v0.6.70, suggestions open at the text caret. If the editor
|
||||
provides no caret position, you can still type the complete trigger to
|
||||
@@ -471,14 +497,16 @@ expand the snippet.
|
||||
Type `;` at the start of a trigger to open suggestions near the caret, or
|
||||
type the first three characters of another trigger. The list filters as you
|
||||
type and fits the widest matching trigger. Use **↑ / ↓** and **Tab** or click
|
||||
an entry. **Esc** dismisses the list. Full triggers still expand
|
||||
automatically. See the [snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
|
||||
an entry. **Esc** dismisses the list. Full triggers expand automatically at the
|
||||
start of a word, including when typed in another keyboard layout. See the
|
||||
[snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
|
||||
|
||||
**Українською.** Введіть `;` на початку тригера або три перші символи іншого
|
||||
тригера, щоб відкрити підказки біля курсора. Список фільтрується під час набору
|
||||
й підлаштовує ширину під найдовший збіг. Для вибору натисніть **↑ / ↓** і
|
||||
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери й далі
|
||||
спрацьовують автоматично. Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
|
||||
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери спрацьовують
|
||||
автоматично на межі перед словом, зокрема під час набору в іншій розкладці.
|
||||
Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
|
||||
|
||||
З v0.6.70 підказки відкриваються біля текстового курсора. Якщо редактор не
|
||||
надає його позицію, введіть повний тригер для розгортання сніпета.
|
||||
@@ -489,15 +517,35 @@ ChatGPT and Codex desktop editors use paced selection for snippet triggers. If o
|
||||
|
||||
**Українською.** У настільних ChatGPT і Codex тригер виділяється з паузами між натисканнями. Якщо виділилася лише перевірена кінцева частина, KSwitcher доповнює виділення й перевіряє весь тригер перед заміною. Інший текст або зміна фокусу скасовують операцію. Тригери розпізнаються в різних розкладках. Один сніпет можна прив’язати до кількох програм через **Add app** або назви процесів через кому; ці прив’язки вже підтримують синхронізацію.
|
||||
|
||||
### Snippet macros
|
||||
|
||||
In **Settings → Snippets**, choose **Insert macro or marker…**. Enter a pause duration or click the recording field and press the keys. They appear as you press them. Release the keys and click **Insert**. You can also type expressions into the replacement text. KSwitcher runs each macro between text segments in the listed order. A leading macro runs after the first text segment, as in earlier versions. A snippet needs some replacement text.
|
||||
|
||||
- `{{shift}}`, `{{alt}}` and `{{tab}}` tap individual keys. Key names are case-insensitive. Letters, digits, `F1`–`F24`, navigation and editing keys also work.
|
||||
- `{{altr}}+{{ctrl}}` holds both keys together. Join key markers with `+` without spaces and put modifiers before the final key, as in `{{ctrl}}+{{shift}}+{{A}}`. Use `l` or `r` after `ctrl`, `alt`, `shift` or `win` to select a side. The unsuffixed names use the left keys.
|
||||
- `rider .{pause:50}{enter}` inserts `rider .`, waits 50 milliseconds, then presses Enter. One pause can be 0–10,000 milliseconds. Use `{{return}}` for Enter inside a chord, as in `{{ctrl}}+{{return}}`.
|
||||
- Write `{{cursor}}`, `{{enter}}`, `{{pause:50}}` or `{{{shift}}}` to insert the corresponding marker literally.
|
||||
|
||||
**Українською.** У **Settings → Snippets** натисни **Insert macro or marker…**. Для паузи введи тривалість, а для клавіш клацни поле запису й натисни потрібні клавіші. Вони з’являються під час натискання. Відпусти їх і натисни **Insert**. Макроси також можна вписати в текст заміни. KSwitcher виконує макроси між частинами тексту за порядком запису. Макрос на початку, як і раніше, виконується після першої частини тексту. Сніпет має містити текст заміни.
|
||||
|
||||
- `{{shift}}`, `{{alt}}` і `{{tab}}` натискають окремі клавіші. Регістр назви клавіші не має значення. Також підтримуються літери, цифри, `F1`–`F24`, клавіші навігації та редагування.
|
||||
- `{{altr}}+{{ctrl}}` затискає обидві клавіші разом. З’єднуй маркери знаком `+` без пробілів і став модифікатори перед основною клавішею, як у `{{ctrl}}+{{shift}}+{{A}}`. Суфікси `l` і `r` у назвах `ctrl`, `alt`, `shift` і `win` вибирають ліву й праву клавіші. Без суфікса використовується ліва.
|
||||
- `rider .{pause:50}{enter}` вставляє `rider .`, чекає 50 мілісекунд і натискає Enter. Допустимий діапазон однієї паузи — від 0 до 10 000 мілісекунд. Для Enter у комбінації використовуй `{{return}}`, наприклад `{{ctrl}}+{{return}}`.
|
||||
- Записуй `{{cursor}}`, `{{enter}}`, `{{pause:50}}` або `{{{shift}}}`, щоб вставити відповідний маркер як звичайний текст.
|
||||
|
||||
For example, `$skill-name{pause:500}{enter} Draft text{cursor}` types the token, waits 500 milliseconds, presses Enter once, then types the draft. The focused application handles Enter. Each `{enter}` sends a separate press.
|
||||
|
||||
Наприклад, `$skill-name{pause:500}{enter} Текст чернетки{cursor}` вводить назву, чекає 500 мілісекунд, натискає Enter один раз і вводить чернетку. Enter обробляє програма у фокусі. Кожен `{enter}` надсилає окреме натискання.
|
||||
|
||||
### Application-specific snippets — v0.6.51
|
||||
|
||||
In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Enter executable names separated by commas, or select a currently open application's process and choose **Add app**. For example: `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Use **Save snippets** to apply the changes.
|
||||
In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application. You can also select a process from the dropdown and click **Add app**, or type executable names separated by commas, such as `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Click **Save** at the bottom of Settings to apply the changes.
|
||||
|
||||
A matching application-specific snippet takes precedence over a global snippet with the same trigger. The same trigger can be used for different applications; overlapping scopes for the same trigger are rejected. Existing snippets without a scope remain global. Matching is case-insensitive by process name, with or without `.exe`, and is checked before insertion. No OCR or timer is involved. Chrome scope means the entire browser, not one website.
|
||||
|
||||
Scopes are saved with snippets and included in manual import/export and synchronization; merge conflicts consider the application scopes. Use v0.6.51 or newer on every synchronizing PC before sharing scoped snippets: older versions do not understand the restriction and may treat the snippet as global.
|
||||
|
||||
**Українською.** У **Settings → Snippets** вибери сніпет, увімкни **Only in these applications** та задай назви процесів через кому або вибери відкриту програму зі списку й натисни **Add app**. Наприклад: `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. Натисни **Save snippets**, щоб застосувати зміни.
|
||||
**Українською.** У **Settings → Snippets** вибери сніпет і ввімкни **Only in these applications**. Перетягни мішень поруч із **Add app** на відкрите вікно, щоб додати його програму. Повтори для кожної потрібної програми. Також можна вибрати процес зі списку й натиснути **Add app** або вписати назви процесів через кому, наприклад `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. Натисни **Save** внизу Settings, щоб застосувати зміни.
|
||||
|
||||
Сніпет конкретної програми має пріоритет над глобальним із тим самим тригером. Для різних програм однакові тригери дозволені, для перетинних областей — ні. Старі сніпети залишаються глобальними. Зіставлення за назвою процесу не залежить від регістру та суфікса `.exe`; OCR і таймерів немає. Для Chrome це весь браузер, а не окремий сайт. Обмеження входять до експорту/імпорту та синхронізації. Перед синхронізацією онови всі ПК до v0.6.51 або новішої: старі версії не розуміють обмеження та можуть застосувати сніпет глобально.
|
||||
### Existing features
|
||||
@@ -514,12 +562,12 @@ Scopes are saved with snippets and included in manual import/export and synchron
|
||||
editor selection metadata remain identical. Unobserved or altered foreign copies are rejected.
|
||||
Snippets normally require accessibility verification of their selected trigger and pasted text,
|
||||
even with logging disabled. If verification is unavailable or the paste differs, expansion
|
||||
stops without running cursor or Enter actions. Clipboard changes during paste also cancel actions.
|
||||
stops before placing the cursor or running key actions. Clipboard changes during paste also cancel actions.
|
||||
Far Manager uses its native Alt+Shift+Arrow selection, Ctrl+Insert copy and Shift+Insert
|
||||
paste commands instead: both the trigger and inserted text must match verified clipboard
|
||||
copies from Far. Cancellation restores the full temporary selection, not one cursor step.
|
||||
Far supports nonempty single-line replacements up to 4096 caret steps, including
|
||||
`{cursor}` and verified `{enter}` actions. Empty or multiline replacements are rejected
|
||||
`{cursor}` and key macros after verification. Empty or multiline replacements are rejected
|
||||
before selection; pasting a newline could execute a command before it can be verified.
|
||||
- Teams recent-word conversion uses a single word-selection command and validates the copied range.
|
||||
If the editor's word boundary differs from the recorded typing, it falls back to paced character
|
||||
@@ -536,12 +584,10 @@ Scopes are saved with snippets and included in manual import/export and synchron
|
||||
repeat-conversion state and does not switch the Windows layout.
|
||||
- Case cycling, Russian/Ukrainian transliteration, verified undo and repeated conversion.
|
||||
- Text snippets across layouts, multiline insertion and a verified `{cursor}` position;
|
||||
`{enter}` presses Enter after insertion and cursor placement (once per marker), before buffered typing resumes.
|
||||
For example, `rider .{enter}` inserts `rider .` and presses Enter.
|
||||
macros run between text segments, before buffered typing resumes.
|
||||
Automatic correction is suppressed during snippet expansion and for typing buffered by that expansion; the global setting is preserved.
|
||||
If the trigger cannot be verified after the copy attempts, it is preserved, queued typing resumes,
|
||||
and no Enter action is sent.
|
||||
`{{cursor}}` and `{{enter}}` insert literal markers. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo).
|
||||
and no key actions are sent. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo).
|
||||
- Clipboard history for text, HTML/RTF, file lists, DIB and PNG images; plain-text paste;
|
||||
full-text search, pinning, deletion, full text viewing and image previews.
|
||||
- Image thumbnails and text/file icons appear directly in the history list. Only visible rows
|
||||
@@ -600,8 +646,9 @@ Pressing the history shortcut a second time pastes the second-most-recent item.
|
||||
Data is in `data/` beside the executable, falling back to `%LOCALAPPDATA%/KSwitcher` when
|
||||
the executable's directory is not writable. Each clipboard payload is an encrypted disk file;
|
||||
only bounded previews/metadata stay in memory. Image data is loaded on demand and released when
|
||||
the history popup is hidden. Settings **Write log** (`writeLog`, enabled by default) controls all
|
||||
log writes. Disabling it also clears diagnostic context from memory; existing log files remain.
|
||||
the history popup is hidden. Settings **Write log** (`writeLog`, off by default) controls all
|
||||
log writes. Enable it when collecting diagnostics that may include typed or copied text.
|
||||
Disabling it also clears diagnostic context from memory. Existing log files remain.
|
||||
Diagnostic stages stay in a memory buffer of at most 128 events for 30 seconds.
|
||||
Selection diagnostics include the expected text, each copied candidate before and after suffix
|
||||
recovery, paced Shift+Left progress or batch delivery counts, and clipboard sequence changes,
|
||||
@@ -663,7 +710,7 @@ Conversion is cancelled rather than pasting into a different window or replacing
|
||||
|
||||
## OpenBao synchronization (experimental, opt-in)
|
||||
|
||||
The **Sync...** button is available in Settings for everyone. Synchronization remains disabled
|
||||
Open **Settings → Sync → OpenBao**. Synchronization remains disabled
|
||||
until you configure your own OpenBao and enable it. Connection configuration is saved separately
|
||||
in `sync.json`. The portable data directory is normally `data/` beside the executable; installations
|
||||
without a writable application directory use the existing local-app-data fallback.
|
||||
@@ -675,11 +722,11 @@ authentication mount (default `userpass`). Use the same profile on each of your
|
||||
administrator-provisioned private access, not public account registration. Non-root namespaces,
|
||||
reverse-proxy URL prefixes, MFA login flows and other providers are not implemented yet.
|
||||
|
||||
Enable synchronization and choose **Save / Sign in / Sync**. The dialog saves connection changes
|
||||
immediately; the main Settings window's Save/Cancel does not control this separate configuration.
|
||||
Enable synchronization and choose **Save and sync** on the OpenBao page. This button saves the
|
||||
connection settings separately from the main Settings draft.
|
||||
When synchronization is disabled, connection fields and sync actions are inactive. Check **Enable
|
||||
synchronization** to make them available. To disable an existing connection, uncheck it and click
|
||||
**Save**; this preserves the saved connection and password without starting a sync request.
|
||||
**Save connection**. This preserves the saved connection and password without starting a sync request.
|
||||
**Disconnect / forget password** remains available while synchronization is disabled.
|
||||
A blank password keeps the existing Windows credential for that server, login mount and username.
|
||||
The password is saved in Windows Credential Manager, not in settings exports, logs or the remote
|
||||
@@ -691,7 +738,7 @@ saved credential. A request already sent to the server may still complete; its d
|
||||
will not be applied after the connection changes. Old credentials for other connection identities
|
||||
can be removed in Windows Credential Manager under `KSwitcher.Sync/`.
|
||||
|
||||
On the first connection, **Save / Sign in / Sync** merges the existing profiles without
|
||||
On the first connection, **Save and sync** merges the existing profiles without
|
||||
requiring a whole-profile replacement. Independent entries (such as snippets, exclusions and
|
||||
replacement pairs) are combined. Different values for the same setting remain on their respective
|
||||
sides and appear in **Resolve individual conflicts...**; no value is guessed without a common history.
|
||||
@@ -700,7 +747,7 @@ Nonconflicting changes synchronize immediately, and unresolved conflicts survive
|
||||
- **Upload local** creates the remote profile or replaces it with this PC's saved shared settings.
|
||||
- **Download remote** replaces this PC's shared settings with the server profile.
|
||||
- If the server has no profile yet, choose **Upload local** to create it.
|
||||
- Unsaved edits in Settings are not synchronized. After a successful **Download remote**, the open Settings window refreshes automatically and keeps the selected tab. The download confirmation warns that unsaved edits will be discarded.
|
||||
- Unsaved edits in Settings are not synchronized. After a successful **Download remote**, the open Settings window refreshes automatically and keeps the selected section. The download confirmation warns that unsaved edits will be discarded.
|
||||
- The status distinguishes downloading, downloaded settings, no local changes and failure. HTTP 400 errors identify authentication, download or upload; field errors remain visible until the next action.
|
||||
|
||||
Once connected, the resident checks at startup, every **10 minutes**, and about two seconds after saving settings, on a separate
|
||||
@@ -739,8 +786,8 @@ paths refer to the same locations and may need updating on a fresh installation.
|
||||
Connection details and credentials stay local so you can sign in again after reinstalling.
|
||||
Clipboard history, screenshots and dictionary files are never uploaded. Full synchronization identifies
|
||||
missing keyboard layouts by language (when Windows can identify it) and exact ID.
|
||||
Install the same layout variant, or select **Keep this PC's layouts and layout shortcuts (sync
|
||||
other settings)** and click **Save / Sign in / Sync**. This device-local option keeps the entire
|
||||
Install the same layout variant, or select **Keep this PC's layouts and layout shortcuts**
|
||||
and click **Save and sync**. This device-local option keeps the entire
|
||||
local layout cycle and its direct shortcuts unchanged while synchronizing the other shared settings.
|
||||
The server's layout cycle and direct shortcuts are preserved on automatic sync and explicit Upload;
|
||||
Download also keeps the local layout configuration. Later syncs cannot erase missing server layouts
|
||||
@@ -829,7 +876,7 @@ Target layouts must also be enabled in the layout cycle.
|
||||
|
||||
### Custom replacements and spelling typos
|
||||
|
||||
Two optional modes in **Auto-correction options…** extend layout correction. Both are off by
|
||||
Two optional modes in **General → Correction options** extend layout correction. Both are off by
|
||||
default and require the main **Automatic correction (experimental)** checkbox to be enabled.
|
||||
|
||||
- **Use custom replacements**: enter one `typo=correction` pair per line, for example
|
||||
@@ -872,7 +919,8 @@ after Space, not immediately after a punctuation key. Save Settings to apply cha
|
||||
only to words with a rank at or below that number (for example, 10000). All dictionary words still
|
||||
protect already valid input, and ambiguous alternatives remain unchanged regardless of this limit.
|
||||
**My dictionary** provides separate English, Ukrainian and Russian fields for correct words missing
|
||||
from the bundled dictionaries. Enter words separated by commas or new lines, then click OK and Save
|
||||
from the bundled dictionaries. A hyphen is allowed between letters, as in `test-mt` or `dev-mt`.
|
||||
Enter words separated by commas or new lines, then click OK and Save
|
||||
in Settings. Case and duplicates are normalized automatically; no file editing or ranks are needed.
|
||||
The v0.6.23 bundled Ukrainian dictionary includes `поточні`. The updater preserves existing dictionary files;
|
||||
if upgrading from an older dictionary, add this word in My dictionary → Ukrainian and click OK → Save.
|
||||
@@ -896,8 +944,10 @@ language in the configured dictionary order (the UI uses English, Ukrainian, Rus
|
||||
Different valid spellings remain ambiguous and are left unchanged.
|
||||
**Minimum word length** defaults to 3 and can be set from 1 to 32 letters. Surrounding punctuation
|
||||
does not count toward this minimum; the maximum word length is 32 letters.
|
||||
Known words, ambiguous alternatives, ALL CAPS, mixed-case identifiers, numbers, URLs and email
|
||||
addresses are left unchanged. Short trailing punctuation is retained when the editor selects it
|
||||
Known words, ambiguous alternatives, mixed-case identifiers, numbers, URLs and email addresses
|
||||
are left unchanged. Fully uppercase words can be corrected when the target is in **My dictionary**.
|
||||
For example, add `qa` under English and set the minimum word length to 2 or lower to correct
|
||||
`ЙФ` to `QA` after Space. Short trailing punctuation is retained when the editor selects it
|
||||
together with the word. Actual selected text is verified before replacement. Layout switching follows
|
||||
the existing switch-layout setting. The configured Undo shortcut restores the original and suppresses
|
||||
that word for the rest of the session (until restart).
|
||||
@@ -921,8 +971,11 @@ CC BY-SA 4.0; attribution, pinned source revision and license are in `dictionari
|
||||
|
||||
## Latest compiled release
|
||||
|
||||
The [Release folder](Release/README.md) contains the latest portable Windows x64 ZIP and SHA-256 checksum.
|
||||
Run `./package.ps1 -PublishRelease` after building and testing to refresh the tracked release archive.
|
||||
Download the portable Windows x64 ZIP from [Gitea Releases](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases).
|
||||
The [Release folder](Release/README.md) tracks the release notes, manifest and SHA-256 checksum.
|
||||
Run `./package.ps1 -PublishRelease` after building and testing. Upload `dist/KSwitcher-win-x64.zip`,
|
||||
`dist/KSwitcher/release-files.json` and `Release/SHA256SUMS.txt` as Gitea release assets.
|
||||
Keep the ZIP in `dist/` and attach it to the release without committing it to Git.
|
||||
|
||||
## Verification
|
||||
|
||||
@@ -990,8 +1043,7 @@ Keep `v0.4.2` as the last legacy `vX.Y.Z` release. Publish full packages as
|
||||
`release-vX.Y.Z` (stable, not prerelease), including `release-files.json`,
|
||||
`KSwitcher-win-x64.zip` and `SHA256SUMS.txt`. Never publish a manifest package under a
|
||||
legacy version tag: clients that have not installed the bridge would select it.
|
||||
Keep the compatibility bridge in the first 100 releases returned by Gitea while
|
||||
supporting old clients; their immutable update code only reads that page.
|
||||
Legacy clients only read the first 100 releases returned by Gitea. The bridge is now outside that page. For v0.3.x–v0.4.1, follow the manual bridge installation instructions above.
|
||||
|
||||
### Editors that omit copied trailing spaces
|
||||
|
||||
@@ -1017,7 +1069,9 @@ Check **★ Pinned only** beside the history search box to show only pinned entr
|
||||
|
||||
History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc** closes it even when focus is on the window or an action button, releasing Windows UI allocations with the process. The resident keeps keyboard hooks, clipboard capture and history storage. Search and the pinned-only filter are preserved in encrypted view state. Each fresh opening selects and reveals the newest matching entry; background refreshes preserve the selected record while browsing. If a full-text item viewer is still open, the helper stays alive until the last viewer closes. Pin/delete, formatted/plain paste and OCR remain available; settings and default shortcuts are unchanged.
|
||||
|
||||
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
|
||||
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels.
|
||||
History reuses separate helper processes for OCR and thumbnails so recognition can run alongside previews.
|
||||
Idle history helpers exit after 30 seconds, and closing the history host stops its helpers. During text conversion, a short-lived instance of **KSwitcher.Screenshot.exe** holds the image clipboard backup in memory and restores it only if the clipboard sequence still matches. Selection reads avoid loading image formats. Keep the executables from the same ZIP together. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
|
||||
|
||||
A live development-build test measured **4.37 MiB before history and 4.35 MiB after two open/Esc cycles**, compared with an earlier roughly 8–9 MiB plateau. A same-image clipboard-backup benchmark retained **12.78 MiB before versus 0.05 MiB after**. These measure private working set, not a guaranteed total footprint. Include all helpers when measuring active use: combined memory can be higher while history is open. No forced working-set trimming is used. Existing screenshots and shortcuts remain applicable. The v0.6.38 approach of retaining a hidden history window/RichEdit control is superseded by process termination.
|
||||
|
||||
|
||||
+340
-2
@@ -1,5 +1,343 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.7.2 — 2026-11-24
|
||||
|
||||
Nested entries in the Settings navigation tree have a compact indent that follows Windows display scaling, including when you move Settings between monitors.
|
||||
|
||||
**Українською.** Вкладені пункти в дереві налаштувань мають компактний відступ, який враховує масштаб Windows і перераховується при перенесенні вікна між моніторами.
|
||||
|
||||
## v0.7.1 — 2026-11-24
|
||||
|
||||
OpenBao connection and synchronization actions are now on **Settings → Sync → OpenBao**. Choose **Save and sync** on that page to save the connection and start synchronization. Settings search can find OpenBao fields, and switching sections preserves the connection draft.
|
||||
|
||||
**Українською.** Підключення й дії синхронізації OpenBao тепер доступні в **Settings → Sync → OpenBao**. Натисніть **Save and sync** на цій сторінці, щоб зберегти підключення й запустити синхронізацію. Пошук Settings знаходить поля OpenBao, а перехід між розділами зберігає чернетку підключення.
|
||||
|
||||
## v0.7.0 — 2026-11-24
|
||||
|
||||
- The native Settings window has a resizable navigation tree and a **Search settings** field. Search finds individual settings, highlights matches, and scrolls the selected control into view.
|
||||
- Settings remembers its window position, size, sidebar width, and last section. Pages adapt to narrower windows. **General → Correction options** groups dictionaries, exceptions, word boundaries, and substitutions.
|
||||
- **Computers → Manage computers** opens in Settings and groups pairing, input sharing, and diagnostic logs. Use KSwitcher Files or Dirlume for browsing and copying remote files.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- У нативному вікні Settings з’явилися дерево розділів зі змінною шириною та поле **Search settings**. Пошук знаходить окремі параметри, підсвічує збіги й прокручує до вибраного поля.
|
||||
- Settings запам’ятовує положення й розмір вікна, ширину дерева та останній розділ. Сторінки підлаштовуються під вузькі вікна. У **General → Correction options** згруповано словники, винятки, межі слів і заміни.
|
||||
- **Computers → Manage computers** відкривається в Settings і групує спарювання, спільний ввід та діагностичні журнали. Для перегляду й копіювання файлів з іншого ПК використовуйте KSwitcher Files або Dirlume.
|
||||
|
||||
## v0.6.132 — 2026-11-23
|
||||
|
||||
In **Settings → Snippets**, **Insert macro or marker…** can add cursor and Enter markers, a pause in milliseconds, or a recorded key or key combination. Keys appear as you press them. Release the keys, click **Insert**, and use the main **Save** button to apply snippet edits together with other settings.
|
||||
|
||||
Clipboard snapshots track the sequence after Windows prepares delayed formats. A sequence advance caused by the read can no longer abort the text operation. When image backup fails, diagnostics include the helper's error.
|
||||
|
||||
**Українською.** У **Settings → Snippets** кнопка **Insert macro or marker…** додає маркери курсора й Enter, паузу в мілісекундах або записану клавішу чи комбінацію. Клавіші видно під час натискання. Відпустіть їх, натисніть **Insert** і збережіть правки головною кнопкою **Save**.
|
||||
|
||||
Під час створення копії буфера KSwitcher бере номер послідовності після підготовки відкладених форматів Windows. Зміна номера під час самого читання більше не перериває текстову операцію. Якщо резервне копіювання зображення не вдалося, журнал показує помилку допоміжного процесу.
|
||||
|
||||
## v0.6.131 — 2026-11-23
|
||||
|
||||
In **Settings → Computers → Manage computers… → Trusted clients**, choose **Add client…** and select Dirlume.exe. Dirlume can then browse drives on computers already paired in KSwitcher and download regular files. Remove the executable to revoke access. After updating Dirlume, add the new executable again.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У **Settings → Computers → Manage computers… → Trusted clients** натисніть **Add client…** і виберіть Dirlume.exe. У Dirlume можна відкривати диски комп’ютерів, які вже спарені в KSwitcher, і завантажувати файли. Видаліть виконуваний файл зі списку, щоб відкликати доступ. Після оновлення Dirlume додайте новий файл повторно.
|
||||
|
||||
## v0.6.130 — 2026-11-22
|
||||
|
||||
The tray shows a purple **K** while KSwitcher processes input. Choose **Pause input processing** to see two white pause bars on a gray tile. The purple **K** returns after **Resume input processing** succeeds. If another program still holds a shortcut, the pause bars stay visible.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Фіолетова **K** у треї означає, що KSwitcher обробляє введення. Після вибору **Pause input processing** з’являються дві білі смуги на сірому тлі. Фіолетова **K** повертається після успішного **Resume input processing**. Якщо інша програма ще утримує гарячу клавішу, значок паузи залишається.
|
||||
|
||||
## v0.6.129 — 2026-11-22
|
||||
|
||||
Choose **Pause input processing** in the tray to test another keyboard tool. The tooltip shows **Input processing paused** once KSwitcher releases its shortcuts and stops keyboard and mouse actions, snippets, autocorrection, automatic layout switching, LAN input and simulated F15 activity. Clipboard history can still record entries. Choose **Resume input processing** to restore input. If a shortcut is occupied, KSwitcher names it and stays paused until you retry. Restarting KSwitcher also clears the pause.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Щоб протестувати іншу програму для клавіатури, виберіть **Pause input processing** у треї. Підказка **Input processing paused** з’явиться, коли KSwitcher звільнить гарячі клавіші та призупинить дії клавіатури й миші, сніпети, автокорекцію, автоматичне перемикання розкладки, LAN-керування й імітацію F15. Історія буфера може й далі записувати нові елементи. Виберіть **Resume input processing** для відновлення. Якщо комбінація зайнята, KSwitcher покаже її та залишиться на паузі до повторної спроби. Перезапуск KSwitcher також скидає паузу.
|
||||
|
||||
## v0.6.128 — 2026-11-22
|
||||
|
||||
In **Settings → Snippets**, drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application, then choose **Save snippets**. Esc cancels a drag. Picking the same application twice adds it only once.
|
||||
|
||||
**Українською.**
|
||||
|
||||
На вкладці **Settings → Snippets** перетягніть мішень поруч із **Add app** на відкрите вікно, щоб додати його програму. Повторіть для кожної потрібної програми й натисніть **Save snippets**. Esc скасовує перетягування. Повторний вибір програми не створює дубліката.
|
||||
|
||||
## v0.6.127 — 2026-11-21
|
||||
|
||||
When the snippet popup shows one match, pressing Enter expands it immediately and consumes the key. With several matches, use the arrow keys and then press Enter to confirm.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Якщо у списку підказок є один збіг, Enter одразу розгортає сніпет. KSwitcher перехоплює це натискання. Якщо збігів кілька, виберіть потрібний стрілками й підтвердьте через Enter.
|
||||
|
||||
## v0.6.126 — 2026-11-21 (withdrawn / відкликано)
|
||||
|
||||
Snippet macros send the configured keys at the position where they appear. `$skill{pause:500}{enter} Draft text` types the name, waits 500 milliseconds, presses Enter once, then types the remaining text. The focused application handles each key.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Макроси сніпетів натискають задані клавіші в указаній позиції. `$skill{pause:500}{enter} Текст` вводить назву, чекає 500 мілісекунд, один раз натискає Enter і вводить решту тексту. Кожне натискання обробляє програма у фокусі.
|
||||
|
||||
## v0.6.125 — 2026-11-21 (withdrawn / відкликано)
|
||||
|
||||
Snippet macros between text segments run before the next segment is inserted. In Codex, `$skill{pause:500}{enter} Draft text` selects the matching skill suggestion and leaves the following text in the composer. Extra Enter markers at the same selection point do not submit the draft. Expansion stops when the suggestion cannot be verified.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Макроси між частинами сніпета виконуються перед вставленням наступної частини. У Codex `$skill{pause:500}{enter} Текст чернетки` вибирає відповідний скіл із підказок і залишає наступний текст у редакторі. Повторні маркери Enter у тій самій позиції не надсилають чернетку. Якщо підказку не вдалося перевірити, розгортання зупиняється.
|
||||
|
||||
## v0.6.124 — 2026-11-21
|
||||
|
||||
Snippets can tap keys such as `{{shift}}`, hold combinations such as `{{altr}}+{{ctrl}}`, and wait with `{pause:50}`. After verifying the inserted text and placing `{cursor}`, KSwitcher runs the macros in order. The Snippets tab groups marker buttons and **Macro help…** below the editor, with **Save snippets** at the right.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Сніпети підтримують окремі клавіші, як-от `{{shift}}`, комбінації на кшталт `{{altr}}+{{ctrl}}` і паузи, як-от `{pause:50}` на 50 мс. KSwitcher виконує макроси за порядком запису після перевірки вставленого тексту й встановлення `{cursor}`. На вкладці **Snippets** кнопки маркерів і **Macro help…** згруповані під редактором, а **Save snippets** розташована праворуч.
|
||||
|
||||
## v0.6.123 — 2026-11-20
|
||||
|
||||
- The tray shows a steady gray dot when all paired PCs are offline. The amber dot pulses while a discovered PC is connecting. Green means every online paired PC is connected.
|
||||
- LAN discovery stays active. Once discovery has expired and the last input channel closes, KSwitcher pauses mouse and keyboard connection attempts until a paired PC reappears.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- Коли всі спаровані ПК офлайн, у треї видно статичну сіру крапку. Жовта крапка пульсує під час підключення до знайденого ПК. Зелена означає, що всі доступні спаровані ПК під’єднані.
|
||||
- Пошук у LAN продовжує працювати. Коли строк дії підтвердження присутності спливає й останній канал вводу закривається, KSwitcher призупиняє спроби підключення миші та клавіатури до появи спарованого ПК.
|
||||
|
||||
## v0.6.122 — 2026-11-20
|
||||
|
||||
- LAN mouse and keyboard sharing lets a TCP attempt finish or time out before starting the encrypted UDP fallback.
|
||||
- The tray icon pulses amber while reconnecting, shows green when all paired PCs are connected, and shows red if the LAN service stops. Hover to see connection status and how many PCs are connected. Diagnostic logs distinguish a declined cursor handoff from returned control.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- Під час передавання миші та клавіатури KSwitcher чекає завершення TCP-спроби або її тайм-ауту, перш ніж запустити резервне з’єднання через зашифрований UDP.
|
||||
- Іконка в треї пульсує жовтим під час перепідключення, показує зелену крапку, коли всі спаровані ПК під’єднані, і червону, якщо LAN-модуль зупинився. Наведіть курсор, щоб побачити стан і кількість підключених ПК. У діагностичному журналі видно, коли другий ПК відхилив перехід курсора або повернув керування.
|
||||
|
||||
## v0.6.121 — 2026-11-20
|
||||
|
||||
KSwitcher Files retries WebView2 startup once when a Markdown preview fails to initialize. If the retry succeeds, the same window displays the formatted document. The Markdown viewer loads the bundled Mermaid library only for documents with Mermaid diagrams.
|
||||
|
||||
Snippet expansion now requires a word boundary before the trigger, even after a pause. The same rule applies across keyboard layouts and in Far Manager.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Якщо перегляд Markdown не запускається, KSwitcher Files один раз повторює запуск WebView2. Після успішної спроби форматований документ з’являється в тому самому вікні. Бібліотека Mermaid завантажується лише для документів із діаграмами Mermaid.
|
||||
|
||||
KSwitcher розгортає сніпети, коли тригер відокремлено від попереднього слова. Перевірка діє після паузи, у різних розкладках і у Far Manager.
|
||||
|
||||
## v0.6.120 — 2026-11-20
|
||||
|
||||
Layout conversion starts faster when the Windows clipboard contains an image. KSwitcher keeps the image and accompanying formats in memory for the duration of the operation. It restores them after conversion if the clipboard still belongs to the operation. A newer copy takes precedence.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Перетворення розкладки починається швидше, коли в буфері обміну Windows є зображення. KSwitcher тримає зображення й супровідні формати в пам’яті до завершення операції. Копія відновлюється, якщо буфер усе ще належить операції. Новіше копіювання має пріоритет.
|
||||
|
||||
## v0.6.119 — 2026-11-18
|
||||
|
||||
KSwitcher Files runs local commands in the folder shown at the command prompt. After switching panes or opening a different folder, commands such as `git clone` and relative path suggestions use that folder in the same PowerShell session.
|
||||
|
||||
**Українською.**
|
||||
|
||||
KSwitcher Files запускає локальні команди в папці, показаній перед командним рядком. Після перемикання панелі або переходу до іншої папки команди на кшталт `git clone` і підказки відносних шляхів використовують цю папку в тій самій сесії PowerShell.
|
||||
|
||||
## v0.6.118 — 2026-11-18
|
||||
|
||||
- **Shift+F11** opens a side-by-side comparison of two selected text files from local, LAN or FTP panes. The comparison has its own taskbar button, a movable divider, a native toolbar, **F7/F8** change navigation, and **Ctrl+wheel** text zoom. The shortcut, font and colors are configurable in **Options → File comparison**.
|
||||
- The footer of each file pane shows the number and combined size of marked items, including folders measured by **F3**. **Ctrl+Left/Right** resize the file panes.
|
||||
- When Windows denies access during a supported local **F5–F8** operation, Files offers to retry with administrator rights through UAC.
|
||||
- Markdown task checkboxes save their state to the source file. Mermaid flowchart labels appear above the connecting lines.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Shift+F11** відкриває двостороннє порівняння двох вибраних текстових файлів із локальних, LAN- або FTP-панелей. Вікно має власну кнопку на панелі завдань, рухомий розділювач і системний тулбар. **F7/F8** переходять між змінами, **Ctrl+колесо** змінює масштаб тексту. Комбінація, шрифт і кольори налаштовуються в **Options → File comparison**.
|
||||
- Унизу кожної панелі видно кількість і сумарний розмір позначених елементів, зокрема папок, виміряних через **F3**. **Ctrl+←/→** змінюють ширину панелей.
|
||||
- Якщо Windows відмовляє в доступі під час підтримуваної локальної операції **F5–F8**, Files пропонує повторити її з правами адміністратора через UAC.
|
||||
- Чекбокси Markdown зберігають стан у вихідному файлі. Підписи з’єднань у блок-схемах Mermaid відображаються поверх ліній.
|
||||
|
||||
## v0.6.117 — 2026-11-18
|
||||
|
||||
- KSwitcher Files supports saved FTP connections in both panes. Browse UTF-8 file names, open or edit remote files with **F3/F4**, save with **F2**, copy between a local and FTP pane with **F5**, rename with **F6**, and permanently delete with **F8**.
|
||||
- **F3** measures folders on local, LAN and FTP panes. On `..` it queues every folder in the current list. Waiting folders show **Queued** and the active folder shows a spinner after two seconds. **Esc** cancels the active pane’s calculation and queue.
|
||||
- The source menu separates local drives, FTP and KSwitcher LAN. **1** opens FTP and the remaining displayed digits select LAN actions. Wide pane **Size** dividers align, and **Ctrl+F** on `..` inserts the open folder’s path.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- KSwitcher Files підтримує збережені FTP-підключення в обох панелях. Назви файлів читаються в UTF-8. **F3/F4** відкривають перегляд і редактор, **F2** зберігає зміни, **F5** копіює між локальною та FTP-панелями, **F6** перейменовує, **F8** видаляє без кошика.
|
||||
- **F3** рахує розмір локальних, LAN- і FTP-папок. На `..` до черги додаються всі папки списку. Папки в черзі мають позначку **Queued**, а біля поточної через дві секунди з’являється спінер. **Esc** скасовує підрахунок і чергу активної панелі.
|
||||
- Меню джерел розділяє локальні диски, FTP і KSwitcher LAN. **1** відкриває FTP, решта показаних цифр вибирають LAN-дії. Розділювачі колонки **Size** вирівняні, а **Ctrl+F** на `..` вставляє шлях відкритої папки.
|
||||
|
||||
## v0.6.116 — 2026-11-17
|
||||
|
||||
- Files displays a live count while reading a folder. **Esc** stops the scan and shows the entries already read. **Ctrl+R** reads the folder again. Mouse selection works beyond the first 65,536 rows.
|
||||
- Files shows the path of files opened through Windows in the terminal and command history. Choosing a history entry still inserts the command that reopens the file. The embedded terminal hides its inactive cursor.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- Files показує лічильник під час читання папки. **Esc** зупиняє читання й показує вже прочитані записи. **Ctrl+R** перечитує папку. Вибір мишею працює після перших 65 536 рядків.
|
||||
- Files показує шлях до файла, відкритого через Windows, у терміналі й історії команд. Вибір запису історії підставляє команду для повторного відкриття. Вбудований термінал приховує курсор, коли він неактивний.
|
||||
|
||||
## v0.6.115 — 2026-11-17
|
||||
|
||||
- **Shift+F4** opens or creates a file in the active local panel. Leave the name blank for a generated `New_File_…txt` name. After editing a draft, **Esc → Save** opens options for the file name, encoding, BOM, and line endings.
|
||||
- Typing updates the editor status line without repainting the menu or flashing the editor window.
|
||||
- When **Enter** opens a local file through Windows, Files displays `start 'path'` in the terminal and saves it in command history.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Shift+F4** відкриває або створює файл в активній локальній панелі. Якщо залишити ім’я порожнім, Files підставить `New_File_…txt`. Після редагування чернетки **Esc → Save** відкриває параметри імені, кодування, BOM і кінців рядків.
|
||||
- Під час набору редактор оновлює рядок стану без перемальовування меню й миготіння вікна.
|
||||
- Коли **Enter** відкриває локальний файл через Windows, Files показує `start 'шлях'` у терміналі й додає команду до історії.
|
||||
|
||||
## v0.6.114 — 2026-11-17
|
||||
|
||||
In KSwitcher Files, clicking a row in the inactive pane highlights that row immediately. The previous cursor row in that pane no longer flashes with the active highlight. If it had a custom unfocused cursor color, it returns directly to its normal style.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У KSwitcher Files клік по рядку неактивної панелі одразу підсвічує вибраний рядок. Попередній рядок курсора цієї панелі більше не блимає активним підсвічуванням. Якщо він мав окремий колір неактивного курсора, рядок одразу повертається до звичайного оформлення.
|
||||
|
||||
## v0.6.113 — 2026-11-17
|
||||
|
||||
- KSwitcher Files keeps the terminal output area dark while WebView2 initializes. This fixes the white flash during startup.
|
||||
- The terminal copy regression test checks for a new clipboard write and verifies its contents without first taking clipboard ownership.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- Під час запуску термінала область виводу KSwitcher Files залишається темною, поки WebView2 готує сторінку. Це усуває білий спалах під час відкриття термінала.
|
||||
- Тест копіювання з термінала перевіряє новий запис і його вміст без попереднього захоплення буфера обміну.
|
||||
|
||||
## v0.6.112 — 2026-11-17
|
||||
|
||||
In KSwitcher Files, **Ctrl+Shift+Tab** cycles backward through Files, Editor, and Viewer windows. **Ctrl+Tab** cycles forward. Both shortcuts wrap at the ends of the window list, including in the Markdown preview.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У KSwitcher Files **Ctrl+Shift+Tab** обходить вікна Files, редактора й переглядача у зворотному порядку. **Ctrl+Tab** обходить їх у прямому порядку. Обидві комбінації працюють циклічно, зокрема в перегляді Markdown.
|
||||
|
||||
## v0.6.111 — 2026-11-17
|
||||
|
||||
- KSwitcher Files updates a panel as soon as its background folder scan finishes.
|
||||
- **Ctrl+U** swaps the panels, keeping their folders, view modes, cursors, marked items, and active panel together. Use **Tab** by itself to switch the active panel. **Ctrl+Tab** cycles between Files, Editor, and Viewer windows.
|
||||
- Panels and scrollable Files popups share a Far-style scrollbar with up and down arrows, a dotted track, and a thumb lighter than its background.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- KSwitcher Files оновлює панель одразу після завершення фонового читання папки.
|
||||
- **Ctrl+U** міняє панелі місцями разом із папками, режимами перегляду, курсорами й позначками. Активна панель залишається активною на новому боці. Для перемикання активної панелі натисніть **Tab** без модифікаторів. **Ctrl+Tab** перемикає вікна Files, редактора й переглядача.
|
||||
- Панелі та попапи з прокруткою у Files мають спільний скролбар у стилі Far зі стрілками вгорі й унизу, крапковою доріжкою та повзунком, світлішим за фон.
|
||||
|
||||
## v0.6.110 — 2026-11-17
|
||||
|
||||
Entering a folder or returning to its parent in KSwitcher Files refreshes the affected panel and the command line without repainting the other panel.
|
||||
|
||||
Auto-correction can preserve all uppercase letters when correcting to a word in **My dictionary**. With `qa` in the English personal dictionary and **Minimum word length** set to 2 or lower, typing `ЙФ` and pressing Space yields `QA`.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Під час входу в папку або повернення до батьківської папки KSwitcher Files оновлює потрібну панель і командний рядок. Сусідня панель більше не перемальовується через цей перехід.
|
||||
|
||||
Автокорекція зберігає верхній регістр для слів з **My dictionary**. Якщо в особистому словнику English є `qa`, а **Minimum word length** дорівнює 2 або менше, після пробілу `ЙФ` виправиться на `QA`.
|
||||
|
||||
## v0.6.109 — 2026-11-17
|
||||
|
||||
**Ctrl+0–9** in KSwitcher Files opens the assigned folder or shows only the folders assigned to that digit. **Ctrl+F1** selects Brief and **Ctrl+F2** selects Wide in the active panel. **Ctrl+F3–F12** are reserved for other panel modes. If command history used a Ctrl+function shortcut, set a new binding under **Options → Command line → Command history**.
|
||||
|
||||
**My dictionary** accepts hyphens between letters, for example `test-mt` and `dev-mt`. Enter the correct spelling in the dictionary for its language, then click **OK → Save**. Update all PCs that share settings before syncing hyphenated entries.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У KSwitcher Files **Ctrl+0–9** відкриває призначену папку або показує лише папки, призначені натиснутій цифрі. **Ctrl+F1** вмикає Brief, а **Ctrl+F2** вмикає Wide в активній панелі. **Ctrl+F3–F12** зарезервовані для інших режимів панелей. Якщо історія команд використовувала Ctrl із функціональною клавішею, задайте нову комбінацію в **Options → Command line → Command history**.
|
||||
|
||||
**My dictionary** приймає дефіси між літерами, наприклад `test-mt` і `dev-mt`. Введіть правильне написання у словник відповідної мови й натисніть **OK → Save**. Перед синхронізацією слів із дефісами оновіть усі ПК, які обмінюються налаштуваннями.
|
||||
|
||||
## v0.6.108 — 2026-11-17
|
||||
|
||||
KSwitcher Files adds **Wake** beside the offline status of a paired PC in **Change drive** (Alt+F1 or Alt+F2). Click **Wake** or focus it with the arrow keys and press **Enter**. The status bar reports whether KSwitcher sent the Wake-on-LAN packet.
|
||||
|
||||
Update both PCs and let them discover each other once while the target is online so KSwitcher can save its network adapter’s MAC address. Enable Wake-on-LAN on the target. Ethernet is the most reliable option. Wi-Fi requires compatible Wake on Wireless LAN hardware and drivers.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У KSwitcher Files біля статусу спареного офлайн-ПК у меню **Change drive** (Alt+F1 або Alt+F2) є дія **Wake**. Клацніть **Wake** або виберіть її стрілками й натисніть **Enter**. Рядок стану повідомить, чи вдалося надіслати пакет Wake-on-LAN.
|
||||
|
||||
Оновіть обидва ПК і дайте їм один раз побачити один одного, поки цільовий ПК увімкнено, щоб KSwitcher зберіг MAC-адресу його мережевого адаптера. Увімкніть Wake-on-LAN на цільовому ПК. Найнадійніше підключення через Ethernet. Для Wi-Fi потрібна підтримка Wake on Wireless LAN з боку обладнання й драйвера.
|
||||
|
||||
## v0.6.107 — 2026-11-16
|
||||
|
||||
KSwitcher Files suggests recent commands, PowerShell commands and parameters, and paths as you type. The list works with the panes visible or hidden. Use **Up** or **Down** to select, **Tab** or **Enter** on a selected suggestion to insert it, and **Escape** to close the list. Press **F1** in the command line to open the Microsoft Learn article for a documented Windows command or subcommand.
|
||||
|
||||
The offline Windows command catalog includes nested syntax and documented choices such as `schtasks /query /fo LIST`. After `ipconfig /renew ` or `ipconfig /release `, Files suggests local IPv4 adapters configured for DHCP. With Git for Windows, Git completion includes options and matching branch names. With the .NET SDK, `dotnet` completion delegates to the CLI. The main Files window has a new blue two-pane icon inspired by FAR.
|
||||
|
||||
**Українською.**
|
||||
|
||||
KSwitcher Files підказує недавні команди з історії, команди й параметри PowerShell та шляхи під час набору. Список працює з відкритими й прихованими панелями. Стрілки **↑** і **↓** вибирають підказку, **Tab** або **Enter** на вибраній підказці вставляє її, а **Escape** закриває список. **F1** у командному рядку відкриває статтю Microsoft Learn для документованої команди чи підкоманди Windows.
|
||||
|
||||
Офлайн-каталог команд Windows містить вкладений синтаксис і документовані значення, наприклад `schtasks /query /fo LIST`. Після `ipconfig /renew ` або `ipconfig /release ` Files підказує локальні адаптери з DHCP для IPv4. За наявності Git for Windows підказки Git включають параметри й відповідні назви гілок. За наявності .NET SDK підказки для `dotnet` надає сама утиліта. Головне вікно Files має нову синю іконку з двома панелями в стилі FAR.
|
||||
|
||||
## v0.6.106 — 2026-11-16
|
||||
|
||||
Files scans local and LAN folders and runs copy, move, rename and delete in the background. Copy and Rename/Move validate destinations in the background. A failed operation opens a red Far-style dialog. For local sharing violations, **Processes…** shows possible blockers and **End process** ends the selected process after confirmation. Retry **F6**, **F8**, or **Shift+Delete** after releasing the item.
|
||||
|
||||
The screenshot editor repaints the affected area while dragging. History reuses separate OCR and thumbnail helpers, and Windows OCR scales images to the engine’s size limit. Shortcut and snippet processing does less work on keystrokes, and LAN transfers wait for a timeout before retrying unacknowledged chunks.
|
||||
|
||||
**Write log** defaults to off for new settings. Existing explicit choices still apply. When enabled, diagnostic logs can contain typed or copied text.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Files сканує локальні й LAN-каталоги та виконує копіювання, переміщення, перейменування й видалення у фоні. Copy і Rename/Move перевіряють шлях у фоні. Помилки операцій відкривають червоний діалог у стилі Far. При локальному блокуванні **Processes…** показує можливі процеси, а **End process** завершує вибраний процес після підтвердження. Після звільнення повторіть **F6**, **F8** або **Shift+Delete**.
|
||||
|
||||
Редактор скриншотів перемальовує змінену область під час перетягування. Історія повторно використовує окремі процеси OCR і мініатюр, а Windows OCR масштабує зображення до ліміту рушія. Обробка хоткеїв і сніпетів виконує менше роботи під час набору. LAN-передача повторно надсилає непідтверджені блоки після тайм-ауту.
|
||||
|
||||
**Write log** вимкнено за замовчуванням для нових налаштувань. Явно збережений вибір продовжує діяти. Увімкнений журнал може містити введений або скопійований текст.
|
||||
|
||||
## v0.6.105 — 2026-11-16
|
||||
|
||||
KSwitcher Files gives the Editor a pencil icon and the Viewer an eye icon. The two modes have separate taskbar groups, and **F6** switches the icon and group in the same window. On a PC running KSwitcher as administrator, LAN PowerShell commands such as `dir` now start with standard user rights. This fixes the `0xC0000142` startup failure on that path. This release replaces v0.6.104.
|
||||
|
||||
**Українською.** Редактор KSwitcher Files має іконку олівця, а переглядач — іконку ока. Режими мають окремі групи на панелі завдань Windows, і **F6** перемикає іконку й групу в тому самому вікні. Якщо KSwitcher на ПК-отримувачі запущено від адміністратора, команди PowerShell через LAN, зокрема `dir`, запускаються з правами звичайного користувача. Виправлено помилку запуску `0xC0000142` у цьому сценарії. Цей реліз замінює v0.6.104.
|
||||
|
||||
## v0.6.104 — 2026-11-16
|
||||
|
||||
**Ctrl+F** or the search icon opens search in the rendered KSwitcher Files Markdown preview. Search ignores case and highlights the current match. **Enter** or **F3** moves to the next match, and **Shift+Enter** or **Shift+F3** moves back. **Escape** closes the search first. This release includes the HTML, Markdown appearance, Options and terminal copy updates from v0.6.103.
|
||||
|
||||
**Українською.** **Ctrl+F** або піктограма пошуку відкриває пошук у відрендерованому Markdown у KSwitcher Files. Пошук ігнорує регістр і підсвічує поточний збіг. **Enter** або **F3** переходить до наступного збігу, а **Shift+Enter** або **Shift+F3** повертає до попереднього. **Escape** спочатку закриває пошук. Реліз включає підтримку HTML, налаштування вигляду Markdown, запам’ятовування розділу Options і копіювання з термінала з v0.6.103.
|
||||
|
||||
## v0.6.103 — 2026-11-16
|
||||
|
||||
The KSwitcher Files Markdown preview renders embedded HTML tables and inline styles such as `white-space: nowrap`. **Options → Viewer → Markdown** sets the preview width, font family and font size. Files Options reopens the last section. **Ctrl+C** and **Ctrl+Insert** copy selected terminal output. This release replaces v0.6.102.
|
||||
|
||||
**Українською.** Перегляд Markdown у KSwitcher Files відображає вбудовані HTML-таблиці й стилі, зокрема `white-space: nowrap`. У **Options → Viewer → Markdown** можна задати ширину перегляду, гарнітуру й розмір шрифту. Options відкриває останній відвіданий розділ. **Ctrl+C** і **Ctrl+Insert** копіюють виділений текст із виводу термінала. Цей реліз замінює v0.6.102.
|
||||
|
||||
## v0.6.102 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Ctrl+Insert copies the full command line when it contains text. With an empty command line, it copies names from the active pane. The LAN host returns Windows PowerShell startup errors without waiting for a system error dialog. Files explains DLL initialization failure `0xC0000142` and accepts another command. This release replaces v0.6.101.
|
||||
|
||||
**Українською.** У KSwitcher Files Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок порожній, копіюються імена з активної панелі. ПК, який приймає LAN-команду, повертає помилки запуску Windows PowerShell без очікування системного діалогу. Files пояснює помилку ініціалізації DLL `0xC0000142` і знову приймає команди. Цей реліз замінює v0.6.101.
|
||||
|
||||
## v0.6.101 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Enter opens the selected item when the command line is empty, including when focus is in the terminal output. The Computers window places pairing and the monitor grid side by side so the bottom actions fit at high display scaling. This release replaces v0.6.100.
|
||||
|
||||
**Українською.** У KSwitcher Files Enter відкриває вибраний елемент, коли командний рядок порожній, зокрема коли фокус у виводі термінала. У вікні Computers спарювання та схема моніторів розташовані поруч, тож нижні дії поміщаються і при високому масштабі. Цей реліз замінює v0.6.100.
|
||||
|
||||
## v0.6.100 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Enter and Shift+Enter submit the command line when focus is in the terminal output. The terminal scrolls to the latest output when a command is submitted. While a LAN command is still running, Files shows how to cancel it and keeps the next command in the input field. This release replaces v0.6.99.
|
||||
|
||||
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують введену команду, коли фокус у виводі термінала. Під час запуску команди термінал прокручується до останнього виводу. Поки виконується LAN-команда, Files показує, як її скасувати, і зберігає наступну команду в полі вводу. Цей реліз замінює v0.6.99.
|
||||
|
||||
## v0.6.99 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Enter and Shift+Enter run the command in the command line, including when the file panes are hidden. With visible panes and an empty command line, the keys act on the selected item. A command reveals the terminal output if it was hidden. This release replaces v0.6.98.
|
||||
|
||||
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують команду з командного рядка, зокрема коли файлові панелі приховані. Коли панелі видимі й рядок порожній, клавіші діють на вибраний елемент. Якщо вивід термінала приховано, команда відкриває його. Цей реліз замінює v0.6.98.
|
||||
|
||||
## v0.6.98 — 2026-11-16
|
||||
|
||||
In Files, Enter opens folders in the current pane, uses the Windows default action for local files, and runs BAT and CMD in the embedded terminal. Shift+Enter opens local folders in File Explorer and passes files, including BAT and CMD, to Windows. It preserves the draft command. Left and Right clear the previous cursor highlight when jumping to the first or last row. The FAR-style key bar uses gray key labels on black and dark action names on teal.
|
||||
@@ -332,8 +670,8 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
|
||||
|
||||
## Upgrade
|
||||
|
||||
Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
|
||||
Choose **Update** in the tray menu. For v0.3.x–v0.4.1, install the [v0.4.2 bridge](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2) manually first. Close KSwitcher and its editors, extract the bridge ZIP into the installation folder while keeping personal data, dictionaries, and tools, then start v0.4.2 and choose **Update**. v0.2.3 and earlier require manual installation.
|
||||
|
||||
For a manual upgrade, exit KSwitcher and its configurator and screenshot editors, then extract the entire **KSwitcher-win-x64.zip** into its installation folder. Verify it with **SHA256SUMS.txt**. Keep personal data, customized dictionaries and tools. Keep the three KSwitcher executables together.
|
||||
For a manual upgrade, save your work and exit KSwitcher, Settings, Files, screenshot editors and bundled StayHere. Verify **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**, then extract the entire ZIP into the installation folder. Keep personal data, customized dictionaries and tools.
|
||||
|
||||
See the [English Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home) or [Українська Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk).
|
||||
@@ -1 +1 @@
|
||||
56aa00696a0d285faf64474cb1f3b321c0681bb315807a7c70dceeb95e8469d0 KSwitcher-win-x64.zip
|
||||
e363ed0f3eaae5b893f05734194bcf3f74f79bd93d373c0be4e631579c6fe8b4 KSwitcher-win-x64.zip
|
||||
+44
-44
@@ -1,166 +1,166 @@
|
||||
{
|
||||
"version": "0.6.98",
|
||||
"schema": 1,
|
||||
"files": [
|
||||
{
|
||||
"sha256": "222efeb00661165e15c60ce29865e36904895fee02972199a4aa22e40be24236",
|
||||
"size": 2361856,
|
||||
"size": 2431488,
|
||||
"sha256": "e48f79af357cbf98b993678164ae02a340da0640831d4087fb428dab1dca81ac",
|
||||
"path": "KSwitcher.exe"
|
||||
},
|
||||
{
|
||||
"sha256": "8853a4bddd887fc4e35e4c3e1a3d3c3f863ac36ed509d4294516f09ae86b2c50",
|
||||
"size": 2359808,
|
||||
"size": 2457600,
|
||||
"sha256": "59b11034a4671c3db921db86138ace31565860363583dc15261252356de2a4f5",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
},
|
||||
{
|
||||
"sha256": "27d77cd34fcb4aa6225bba12c87e76b7f410134f713754ace1b1b4cc34150979",
|
||||
"size": 3337216,
|
||||
"size": 3397632,
|
||||
"sha256": "d6dbaa721ff896b3ec1c3101dab75b81a63a0c3c1e5c57cfe9d84e52f1d821c7",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
},
|
||||
{
|
||||
"sha256": "546dcfb34f4bcb7765152ab345ffca99b54b4f77445f7cd50379e07e75d4b048",
|
||||
"size": 3738112,
|
||||
"size": 4403712,
|
||||
"sha256": "69c95a3135878d8974e144ef630ec7cf53df43a61e7243482642fc721b6eadcb",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
},
|
||||
{
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"size": 194912,
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"path": "WebView2Loader.dll"
|
||||
},
|
||||
{
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"size": 1103,
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"path": "terminal/addon-fit-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"size": 1521,
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"path": "terminal/addon-fit.js"
|
||||
},
|
||||
{
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"size": 527,
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"path": "terminal/index.html"
|
||||
},
|
||||
{
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"size": 1073,
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"path": "terminal/markdown-it-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"size": 100786,
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"path": "terminal/markdown-it.js"
|
||||
},
|
||||
{
|
||||
"sha256": "27d3c6d39325d4995162911c352a8e20603513445683ceb0409e628949c39237",
|
||||
"size": 2212,
|
||||
"size": 3599,
|
||||
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
|
||||
"path": "terminal/markdown.html"
|
||||
},
|
||||
{
|
||||
"sha256": "dbf9a062364dcc90b59fd98eb0adb0f153ed95accf26e28f7be9cce8c13ae324",
|
||||
"size": 6534,
|
||||
"size": 17575,
|
||||
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
|
||||
"path": "terminal/markdown.js"
|
||||
},
|
||||
{
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"size": 1089,
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"path": "terminal/mermaid-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"size": 5537838,
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"path": "terminal/mermaid.js"
|
||||
},
|
||||
{
|
||||
"sha256": "0f3edde02b30e7b0f76d0cc88daae5791d720a4b74cf8b34e7c0b4dbe0cf9c9d",
|
||||
"size": 4478,
|
||||
"size": 5065,
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
|
||||
"path": "terminal/terminal.js"
|
||||
},
|
||||
{
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"size": 1261,
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"path": "terminal/xterm-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"size": 7112,
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"path": "terminal/xterm.css"
|
||||
},
|
||||
{
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"size": 488663,
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"path": "terminal/xterm.js"
|
||||
},
|
||||
{
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"size": 4401,
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"path": "LICENSE"
|
||||
},
|
||||
{
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"size": 1096,
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"path": "json-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"size": 883,
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"path": "files-text-license.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "fca41227e9b38bf061298d69806ea66fb00086ae03aec49665e4f68ed2c3f8e9",
|
||||
"size": 94357,
|
||||
"size": 101324,
|
||||
"sha256": "74e79e56a1ed04a6a617d626aedbf4c0a20e9dc83cd1c42d787244c1b48c5330",
|
||||
"path": "README.md"
|
||||
},
|
||||
{
|
||||
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
|
||||
"size": 11418,
|
||||
"size": 12354,
|
||||
"sha256": "a2521642266d88eb5a2e579b8c514eecb63b0586e09dac2bbeea964df92b2474",
|
||||
"path": "LAN-PREVIEW.md"
|
||||
},
|
||||
{
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"size": 732485,
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"path": "dictionaries/en.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"size": 20566,
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"size": 2265,
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"path": "dictionaries/README.md"
|
||||
},
|
||||
{
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"size": 1109134,
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"path": "dictionaries/ru.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"size": 1280,
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"path": "dictionaries/sources.json"
|
||||
},
|
||||
{
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"size": 940799,
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"path": "dictionaries/uk.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"size": 993,
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"path": "tools/README.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
|
||||
"size": 134656,
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
|
||||
"path": "tools/StayHere.exe"
|
||||
},
|
||||
{
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"size": 2796,
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"path": "tools/StayHere-README.md"
|
||||
}
|
||||
]
|
||||
],
|
||||
"schema": 1,
|
||||
"version": "0.7.2"
|
||||
}
|
||||
@@ -107,10 +107,12 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Test build failed' }
|
||||
& .\build\KSwitcherTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Tests failed' }
|
||||
& $compiler @common tests/input.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe
|
||||
& $compiler @common tests/input.cpp tests/input_pause.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Input test build failed' }
|
||||
& .\build\KSwitcherInputTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Input tests failed' }
|
||||
& .\build\KSwitcherInputTests.exe --input-pause
|
||||
if ($LASTEXITCODE) { throw 'Tray pause/resume test failed' }
|
||||
& $compiler @common tests/chat_profiles.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Chat profile test build failed' }
|
||||
& .\build\KSwitcherChatProfileTests.exe
|
||||
|
||||
+3
-4
@@ -41,12 +41,11 @@ try {
|
||||
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,(Join-Path $destination $name),$name,[IO.Compression.CompressionLevel]::Optimal) | Out-Null
|
||||
}
|
||||
} finally { $zip.Dispose(); $stream.Dispose() }
|
||||
Get-FileHash -LiteralPath $archive -Algorithm SHA256
|
||||
$archiveHash = Get-FileHash -LiteralPath $archive -Algorithm SHA256
|
||||
$archiveHash
|
||||
if ($PublishRelease) {
|
||||
$release = Join-Path $root 'Release'
|
||||
New-Item -ItemType Directory -Force $release | Out-Null
|
||||
$published = Join-Path $release 'KSwitcher-win-x64.zip'
|
||||
Copy-Item -LiteralPath $archive -Destination $published -Force
|
||||
$hash = (Get-FileHash -LiteralPath $published -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
$hash = $archiveHash.Hash.ToLowerInvariant()
|
||||
"$hash KSwitcher-win-x64.zip" | Set-Content -LiteralPath (Join-Path $release 'SHA256SUMS.txt') -Encoding ascii
|
||||
}
|
||||
+4
-3
@@ -2,6 +2,7 @@
|
||||
#include <windows.h>
|
||||
#include "resource.h"
|
||||
IDI_KSWITCHER ICON "kswitcher.ico"
|
||||
IDI_KSWITCHER_PAUSED ICON "kswitcher-paused.ico"
|
||||
#ifdef KS_SCREENSHOT_RESOURCES
|
||||
IDI_SCREENSHOT_QUESTION ICON "icons/question.ico"
|
||||
IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
@@ -9,8 +10,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
201 RCDATA "update.ps1"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 0,6,98,0
|
||||
PRODUCTVERSION 0,6,98,0
|
||||
FILEVERSION 0,7,2,0
|
||||
PRODUCTVERSION 0,7,2,0
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
BEGIN
|
||||
@@ -20,7 +21,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
||||
VALUE "ProductName", "KSwitcher"
|
||||
VALUE "FileVersion", "0.6.98"
|
||||
VALUE "FileVersion", "0.7.2"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
+124
-1
@@ -1,11 +1,15 @@
|
||||
#pragma code_page(65001)
|
||||
#include <windows.h>
|
||||
#include <commctrl.h>
|
||||
#include "resource.h"
|
||||
|
||||
#define FAR_EDIT(id, mode, x, y, width, height) \
|
||||
CONTROL "", id, "KSwitcher.Files.FarEdit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height
|
||||
|
||||
1 ICON "kswitcher-files.ico"
|
||||
IDI_FILES_VIEWER ICON "kswitcher-files-viewer.ico"
|
||||
IDI_FILES_EDITOR ICON "kswitcher-files-editor.ico"
|
||||
IDI_FILES_COMPARE ICON "kswitcher-files-compare.ico"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
601 RCDATA "files-text-license.txt"
|
||||
|
||||
@@ -47,16 +51,65 @@ BEGIN
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
|
||||
END
|
||||
|
||||
611 DIALOGEX 0, 0, 332, 96
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Open/create file:", 460, 14, 16, 304, 12
|
||||
FAR_EDIT(461, 0, 14, 29, 304, 14)
|
||||
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
|
||||
LTEXT "&Code page:", 462, 14, 53, 94, 12
|
||||
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
|
||||
CONTROL "", 467, "Static", NOT WS_VISIBLE, 14, 72, 1, 1
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 76, 60, 16
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 76, 60, 16
|
||||
END
|
||||
|
||||
612 DIALOGEX 0, 0, 332, 184
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Save file &as:", 460, 14, 16, 304, 12
|
||||
FAR_EDIT(461, 0, 14, 29, 304, 14)
|
||||
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
|
||||
LTEXT "&Code page:", 462, 14, 53, 94, 12
|
||||
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
|
||||
AUTOCHECKBOX "Add signature (&BOM)", 464, 14, 66, 304, 12
|
||||
CONTROL "", 468, "Static", NOT WS_VISIBLE, 14, 86, 1, 1
|
||||
LTEXT "Change line breaks to:", 469, 14, 87, 304, 12
|
||||
AUTORADIOBUTTON "Do ¬ change", 470, 14, 100, 304, 12, WS_GROUP | WS_TABSTOP
|
||||
AUTORADIOBUTTON "&Windows (CR LF)", 471, 14, 112, 304, 12
|
||||
AUTORADIOBUTTON "&Unix (LF)", 472, 14, 124, 304, 12
|
||||
AUTORADIOBUTTON "&Mac (CR)", 473, 14, 136, 304, 12
|
||||
CONTROL "", 467, "Static", NOT WS_VISIBLE | WS_GROUP, 14, 155, 1, 1
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 157, 60, 16
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 157, 60, 16
|
||||
END
|
||||
|
||||
607 DIALOGEX 0, 0, 185, 57
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL, 14, 16, 157, 13
|
||||
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL, 14, 16, 157, 13
|
||||
AUTOCHECKBOX "&Remember for this session", 101, 14, 30, 157, 13, NOT WS_VISIBLE
|
||||
CONTROL "", 102, "Static", NOT WS_VISIBLE, 14, 35, 1, 1
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
|
||||
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
|
||||
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 129, 38, 51, 15
|
||||
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
|
||||
END
|
||||
|
||||
609 DIALOGEX 0, 0, 350, 135
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 430, 14, 17, 322, 20
|
||||
LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
CONTROL "", 432, "Static", NOT WS_VISIBLE, 14, 108, 1, 1
|
||||
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 56, 110, 80, 16
|
||||
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 140, 110, 74, 16
|
||||
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 218, 110, 65, 16
|
||||
END
|
||||
|
||||
608 DIALOGEX 0, 0, 220, 67
|
||||
@@ -144,6 +197,21 @@ BEGIN
|
||||
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
|
||||
LTEXT "", 367, 345, 184, 45, 12
|
||||
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
|
||||
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
|
||||
EDITTEXT 376, 131, 68, 168, 14, ES_AUTOHSCROLL
|
||||
PUSHBUTTON "Choose &font…", 377, 306, 68, 76, 14
|
||||
LTEXT "Font &size (8–72 pt)", 378, 131, 99, 184, 12
|
||||
EDITTEXT 379, 318, 96, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
LTEXT "", 408, 131, 30, 254, 14
|
||||
PUSHBUTTON "Change &font…", 409, 131, 49, 82, 15
|
||||
LTEXT "Comparison &color", 410, 131, 79, 117, 12
|
||||
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
|
||||
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
|
||||
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
|
||||
@@ -284,3 +352,58 @@ BEGIN
|
||||
FAR_EDIT(325, 0, 12, 28, 361, 16)
|
||||
LISTBOX 324, 12, 49, 361, 155, LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
END
|
||||
|
||||
112 DIALOGEX 0, 0, 360, 186
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "FTP connection"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Name", 381, 16, 18, 328, 12
|
||||
FAR_EDIT(382, ES_LEFT, 16, 31, 328, 15)
|
||||
LTEXT "&Server", 383, 16, 49, 250, 12
|
||||
LTEXT "Por&t", 384, 278, 49, 66, 12
|
||||
FAR_EDIT(385, ES_LEFT, 16, 62, 250, 15)
|
||||
FAR_EDIT(386, ES_LEFT | ES_NUMBER, 278, 62, 66, 15)
|
||||
LTEXT "&User name (blank for anonymous)", 387, 16, 80, 328, 12
|
||||
FAR_EDIT(388, ES_LEFT, 16, 93, 328, 15)
|
||||
LTEXT "&Password", 389, 16, 111, 328, 12
|
||||
EDITTEXT 390, 16, 124, 328, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
|
||||
AUTOCHECKBOX "Use &Windows encoding for file names", 392, 16, 144, 328, 14
|
||||
LTEXT "", 391, 10, 161, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 164, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 164, 86, 18
|
||||
END
|
||||
|
||||
113 DIALOGEX 0, 0, 350, 73
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Rename"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "New name in the current FTP folder:", 210, 14, 15, 322, 12
|
||||
FAR_EDIT(211, 0, 14, 29, 322, 18)
|
||||
LTEXT "", 217, 10, 49, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Rename", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 51, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 51, 86, 18
|
||||
END
|
||||
|
||||
114 DIALOGEX 0, 0, 510, 252
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_CLIPCHILDREN
|
||||
EXSTYLE WS_EX_APPWINDOW
|
||||
CAPTION "Compare files"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "", 400, 4, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 401, 259, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 45, 510, 207
|
||||
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
|
||||
LTEXT "", 403, 216, 12, 98, 14
|
||||
END
|
||||
|
||||
115 DIALOGEX 0, 0, 290, 58
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Compare files"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
|
||||
END
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 3.5 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -1,4 +1,8 @@
|
||||
#pragma once
|
||||
#define IDI_KSWITCHER 101
|
||||
#define IDI_SCREENSHOT_QUESTION 102
|
||||
#define IDI_FILES_VIEWER 103
|
||||
#define IDI_FILES_EDITOR 104
|
||||
#define IDI_FILES_COMPARE 105
|
||||
#define IDI_KSWITCHER_PAUSED 106
|
||||
#define IDC_SCREENSHOT_PENCIL 500
|
||||
@@ -7,13 +7,20 @@
|
||||
<style>
|
||||
:root { color-scheme: light dark; font: 16px/1.55 system-ui, sans-serif; }
|
||||
:root:not(.rendered) body { visibility: hidden; }
|
||||
body { max-width: 960px; margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
|
||||
nav { position: sticky; top: 0; display: flex; gap: .4em; padding-block: .25em; background: Canvas; }
|
||||
body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
|
||||
main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); }
|
||||
nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; }
|
||||
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
|
||||
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
|
||||
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
|
||||
nav button:hover:not(:disabled) { text-decoration: underline; }
|
||||
nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
#search { margin-inline-start: auto; display: flex; align-items: center; gap: .35em;
|
||||
flex: 0 1 22em; min-width: 0; max-width: 100%; }
|
||||
#search[hidden] { display: none; }
|
||||
#search-query { box-sizing: border-box; flex: 1; min-width: 0; width: 0; font: inherit; }
|
||||
#search-status { white-space: nowrap; font-size: .8em; }
|
||||
::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; }
|
||||
@@ -27,15 +34,23 @@ table { display: block; border-collapse: collapse; }
|
||||
th, td { border: 1px solid GrayText; padding: .3em .65em; }
|
||||
img, svg { max-width: 100%; height: auto; }
|
||||
figure { margin: 1em 0; }
|
||||
figure svg .edgeLabel rect { fill: Canvas !important; opacity: 1 !important; stroke: none !important; }
|
||||
.task { list-style: none; }
|
||||
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
|
||||
</style>
|
||||
<nav aria-label="Document history">
|
||||
<nav aria-label="Markdown preview">
|
||||
<button id="back" type="button" title="Back (Alt+Left)" aria-label="Back" disabled>←</button>
|
||||
<button id="forward" type="button" title="Forward (Alt+Right)" aria-label="Forward" disabled>→</button>
|
||||
<button id="search-open" type="button" title="Find (Ctrl+F)" aria-label="Find in document" aria-controls="search" aria-expanded="false">⌕</button>
|
||||
<div id="search" role="search" hidden>
|
||||
<input id="search-query" type="search" aria-label="Find in document" placeholder="Find in document" autocomplete="off">
|
||||
<output id="search-status" for="search-query" aria-live="polite"></output>
|
||||
<button id="search-previous" type="button" title="Previous match (Shift+Enter)" aria-label="Previous match" disabled>↑</button>
|
||||
<button id="search-next" type="button" title="Next match (Enter)" aria-label="Next match" disabled>↓</button>
|
||||
<button id="search-close" type="button" title="Close search (Esc)" aria-label="Close search">×</button>
|
||||
</div>
|
||||
</nav>
|
||||
<main></main>
|
||||
<script src="markdown-it.js"></script>
|
||||
<script src="mermaid.js"></script>
|
||||
<script src="markdown.js"></script>
|
||||
</html>
|
||||
+244
-18
@@ -4,19 +4,45 @@ const bridge = window.chrome.webview;
|
||||
const content = document.querySelector('main');
|
||||
const back = document.querySelector('#back');
|
||||
const forward = document.querySelector('#forward');
|
||||
const markdown = markdownit({ html: false, linkify: true });
|
||||
const searchOpen = document.querySelector('#search-open');
|
||||
const search = document.querySelector('#search');
|
||||
const searchQuery = document.querySelector('#search-query');
|
||||
const searchStatus = document.querySelector('#search-status');
|
||||
const searchPrevious = document.querySelector('#search-previous');
|
||||
const searchNext = document.querySelector('#search-next');
|
||||
const markdown = markdownit({ html: true, linkify: true });
|
||||
let generation = 0;
|
||||
let images = [];
|
||||
let matches = [];
|
||||
let activeMatch = -1;
|
||||
let taskMarkers = new WeakMap();
|
||||
let pendingTask;
|
||||
let previewRevision = 0;
|
||||
let mermaidReady;
|
||||
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: 'strict',
|
||||
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
|
||||
suppressErrorRendering: true,
|
||||
flowchart: { htmlLabels: false }
|
||||
});
|
||||
function loadMermaid() {
|
||||
mermaidReady ??= new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'mermaid.js';
|
||||
script.onload = resolve;
|
||||
script.onerror = () => reject(new Error('Could not load Mermaid'));
|
||||
document.head.append(script);
|
||||
}).then(() => {
|
||||
const renderer = window.mermaid;
|
||||
renderer.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: 'strict',
|
||||
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
|
||||
suppressErrorRendering: true,
|
||||
flowchart: { htmlLabels: false }
|
||||
});
|
||||
return renderer;
|
||||
});
|
||||
return mermaidReady;
|
||||
}
|
||||
|
||||
markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
|
||||
markdown.core.ruler.after('inline', 'task_lists', ({ tokens, src, env }) => {
|
||||
const lines = src.split('\n');
|
||||
for (let i = 2; i < tokens.length; ++i) {
|
||||
const token = tokens[i];
|
||||
if (token.type !== 'inline' || tokens[i - 1].type !== 'paragraph_open' ||
|
||||
@@ -28,13 +54,16 @@ markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
|
||||
const box = new text.constructor('task_checkbox', '', 0);
|
||||
box.checked = marker[1] !== ' ';
|
||||
box.content = token.content.slice(marker[0].length);
|
||||
const line = tokens[i - 1].map?.[0];
|
||||
const sourceMarker = /^[ \t]*(?:>[ \t]*)*(?:[-+*]|\d{1,9}[.)])[ \t]+\[([ xX])\][ \t]+/.exec(lines[line]);
|
||||
if (sourceMarker) box.source = env.taskKey + ':' + line + ':' + (sourceMarker[0].lastIndexOf('[') + 1);
|
||||
token.children.unshift(box);
|
||||
tokens[i - 2].attrJoin('class', 'task');
|
||||
}
|
||||
});
|
||||
markdown.renderer.rules.task_checkbox = (tokens, i) =>
|
||||
'<input type="checkbox" aria-label="' + markdown.utils.escapeHtml(tokens[i].content) + '"' +
|
||||
(tokens[i].checked ? ' checked' : '') + '>';
|
||||
(tokens[i].checked ? ' checked' : '') + (tokens[i].source ? ' data-task="' + tokens[i].source + '"' : '') + '>';
|
||||
markdown.renderer.rules.image = (tokens, i) => {
|
||||
const token = tokens[i];
|
||||
const alt = markdown.renderer.renderInlineAsText(token.children, markdown.options, {});
|
||||
@@ -42,13 +71,69 @@ markdown.renderer.rules.image = (tokens, i) => {
|
||||
return '<img alt="' + escape(alt) + '" data-path="' + escape(token.attrGet('src')) + '">';
|
||||
};
|
||||
|
||||
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
|
||||
tr u ul var wbr`.split(/\s+/));
|
||||
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
|
||||
const tagAttributes = {
|
||||
a: ['href'], col: ['span'], colgroup: ['span'], details: ['open'], img: ['alt', 'width', 'height'],
|
||||
input: ['type', 'checked', 'disabled'], ol: ['start', 'reversed', 'type'], li: ['value'],
|
||||
td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan', 'scope'], time: ['datetime']
|
||||
};
|
||||
const inlineStyles = ['white-space', 'text-align', 'vertical-align', 'color', 'background-color',
|
||||
'font-weight', 'font-style', 'text-decoration-line', 'width', 'max-width'];
|
||||
|
||||
function relativeResource(path) {
|
||||
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
|
||||
}
|
||||
|
||||
function renderContent(text, canSave) {
|
||||
// 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 });
|
||||
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')) {
|
||||
element.remove();
|
||||
continue;
|
||||
}
|
||||
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
|
||||
const task = tag === 'input' && element.getAttribute('data-task');
|
||||
if (task && task.startsWith(taskKey + ':')) {
|
||||
const [, line, column] = task.split(':');
|
||||
taskMarkers.set(element, { line: Number(line), column: Number(column) });
|
||||
element.disabled = !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);
|
||||
}
|
||||
for (const [name, value] of styles) {
|
||||
if (value) element.style.setProperty(name, value);
|
||||
}
|
||||
if (relativeResource(imagePath)) element.dataset.path = imagePath;
|
||||
if (tag === 'a' && element.hasAttribute('href')) {
|
||||
const path = element.getAttribute('href').trim();
|
||||
if (relativeResource(path) || /^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i.test(path)) element.setAttribute('href', path);
|
||||
else element.removeAttribute('href');
|
||||
}
|
||||
}
|
||||
content.replaceChildren(template.content);
|
||||
}
|
||||
|
||||
function send(action, options = {}) {
|
||||
bridge.postMessage(JSON.stringify({ action, ...options }));
|
||||
}
|
||||
|
||||
function scrollToHeading(fragment) {
|
||||
if (!fragment) { window.scrollTo(0, 0); return; }
|
||||
try { document.getElementById(decodeURIComponent(fragment))?.scrollIntoView(); } catch {}
|
||||
try { content.querySelector('#' + CSS.escape(decodeURIComponent(fragment)))?.scrollIntoView(); } catch {}
|
||||
}
|
||||
|
||||
function restorePosition({ fragment, scroll }) {
|
||||
@@ -64,15 +149,115 @@ function navigate(action) {
|
||||
back.addEventListener('click', () => navigate('back'));
|
||||
forward.addEventListener('click', () => navigate('forward'));
|
||||
|
||||
async function render({ text, fragment, scroll, title, keepPosition }) {
|
||||
function updateSearch(reveal = true) {
|
||||
matches = [];
|
||||
activeMatch = -1;
|
||||
const query = searchQuery.value.trim();
|
||||
if (query) {
|
||||
const pattern = query.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
|
||||
const expression = new RegExp(pattern, 'giu');
|
||||
const blockTags = 'article,aside,blockquote,caption,dd,div,dt,figcaption,footer,h1,h2,h3,h4,h5,h6,header,li,p,pre,section,summary,td,th,text';
|
||||
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
|
||||
let block = null;
|
||||
let parts = [];
|
||||
let text = '';
|
||||
const searchBlock = () => {
|
||||
let first = 0;
|
||||
let last = 0;
|
||||
for (const match of text.matchAll(expression)) {
|
||||
const end = match.index + match[0].length;
|
||||
while (parts[first].end <= match.index) ++first;
|
||||
last = Math.max(last, first);
|
||||
while (parts[last].end < end) ++last;
|
||||
matches.push([parts[first].node, match.index - parts[first].start,
|
||||
parts[last].node, end - parts[last].start]);
|
||||
}
|
||||
parts = [];
|
||||
text = '';
|
||||
};
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
const element = node.parentElement;
|
||||
if (!node.length || element.closest('style,svg title,svg desc,svg defs') ||
|
||||
!element.checkVisibility({ visibilityProperty: true })) continue;
|
||||
const nextBlock = element.closest(blockTags);
|
||||
if (block !== nextBlock) searchBlock();
|
||||
block = nextBlock;
|
||||
const start = text.length;
|
||||
text += node.data;
|
||||
parts.push({ node, start, end: text.length });
|
||||
}
|
||||
searchBlock();
|
||||
}
|
||||
showSearchMatch(matches.length ? 0 : -1, reveal);
|
||||
}
|
||||
|
||||
function showSearchMatch(index, reveal) {
|
||||
activeMatch = index;
|
||||
searchPrevious.disabled = searchNext.disabled = matches.length < 2;
|
||||
searchStatus.value = !searchQuery.value.trim() ? '' : index < 0 ? 'No matches' : (index + 1) + ' / ' + matches.length;
|
||||
CSS.highlights.delete('markdown-search-active');
|
||||
if (index < 0) return;
|
||||
const [start, from, end, to] = matches[index];
|
||||
const range = new Range();
|
||||
range.setStart(start, from);
|
||||
range.setEnd(end, to);
|
||||
CSS.highlights.set('markdown-search-active', new Highlight(range));
|
||||
if (!reveal) return;
|
||||
const rect = range.getBoundingClientRect();
|
||||
const toolbarBottom = search.parentElement.getBoundingClientRect().bottom;
|
||||
if (rect.top < toolbarBottom || rect.bottom > innerHeight) {
|
||||
scrollBy(0, rect.top - Math.max(toolbarBottom, innerHeight / 2));
|
||||
}
|
||||
const scroller = start.parentElement.closest('pre, table');
|
||||
if (scroller) {
|
||||
const bounds = scroller.getBoundingClientRect();
|
||||
if (rect.left < bounds.left || rect.right > bounds.right) {
|
||||
scroller.scrollLeft += rect.left - bounds.left;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openSearch() {
|
||||
search.hidden = false;
|
||||
searchOpen.setAttribute('aria-expanded', 'true');
|
||||
searchQuery.focus({ preventScroll: true });
|
||||
searchQuery.select();
|
||||
}
|
||||
|
||||
function closeSearch() {
|
||||
if (search.hidden) return false;
|
||||
const hadFocus = search.contains(document.activeElement);
|
||||
search.hidden = true;
|
||||
searchOpen.setAttribute('aria-expanded', 'false');
|
||||
searchQuery.value = '';
|
||||
updateSearch();
|
||||
if (hadFocus) searchOpen.focus({ preventScroll: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
function stepSearch(direction) {
|
||||
if (search.hidden) openSearch();
|
||||
else if (matches.length) showSearchMatch((activeMatch + direction + matches.length) % matches.length, true);
|
||||
}
|
||||
|
||||
searchOpen.addEventListener('click', openSearch);
|
||||
document.querySelector('#search-close').addEventListener('click', closeSearch);
|
||||
searchQuery.addEventListener('input', () => updateSearch());
|
||||
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 }) {
|
||||
const current = ++generation;
|
||||
if (keepPosition) scroll = window.scrollY;
|
||||
else closeSearch();
|
||||
document.documentElement.classList.remove('rendered');
|
||||
document.title = title;
|
||||
content.innerHTML = markdown.render(text);
|
||||
previewRevision = revision;
|
||||
renderContent(text, canSave);
|
||||
const headings = new Set();
|
||||
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
|
||||
const base = heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
||||
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
||||
let id = base;
|
||||
for (let n = 1; headings.has(id); ++n) id = base + '-' + n;
|
||||
heading.id = id;
|
||||
@@ -83,23 +268,41 @@ async function render({ text, fragment, scroll, title, keepPosition }) {
|
||||
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
|
||||
for (const [index, block] of blocks.entries()) {
|
||||
try {
|
||||
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
|
||||
const renderer = await loadMermaid();
|
||||
if (current !== generation) return;
|
||||
const { svg } = await renderer.render('diagram-' + current + '-' + index, block.textContent);
|
||||
if (current !== generation) return;
|
||||
const figure = document.createElement('figure');
|
||||
figure.innerHTML = svg;
|
||||
const paths = figure.querySelector('g.edgePaths');
|
||||
const labels = figure.querySelector('g.edgeLabels');
|
||||
if (paths && labels && paths.parentNode === labels.parentNode) paths.after(labels);
|
||||
block.parentElement.replaceWith(figure);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (current !== generation) return;
|
||||
const caption = document.createElement('div');
|
||||
caption.textContent = 'Invalid Mermaid diagram';
|
||||
caption.title = error instanceof Error ? error.message : String(error);
|
||||
block.parentElement.before(caption);
|
||||
}
|
||||
}
|
||||
restorePosition({ fragment, scroll });
|
||||
document.documentElement.classList.add('rendered');
|
||||
if (!search.hidden) updateSearch(false);
|
||||
send('rendered');
|
||||
}
|
||||
|
||||
content.addEventListener('change', ({ target }) => {
|
||||
const marker = taskMarkers.get(target);
|
||||
if (!marker) return;
|
||||
if (pendingTask) {
|
||||
target.checked = !target.checked;
|
||||
return;
|
||||
}
|
||||
pendingTask = { target, checked: target.checked };
|
||||
send('save-task', { ...marker, revision: previewRevision, checked: target.checked });
|
||||
});
|
||||
|
||||
content.addEventListener('click', event => {
|
||||
const link = event.target.closest('a');
|
||||
if (!link) return;
|
||||
@@ -116,9 +319,18 @@ document.addEventListener('pointerup', event => {
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
|
||||
if (event.isComposing) return;
|
||||
if (event.ctrlKey && !event.altKey && event.key.toLowerCase() === 'f') {
|
||||
event.preventDefault();
|
||||
send('cycle');
|
||||
openSearch();
|
||||
} else if (event.key === 'F3' || (event.key === 'Enter' && event.target === searchQuery)) {
|
||||
event.preventDefault();
|
||||
stepSearch(event.shiftKey ? -1 : 1);
|
||||
} else if (event.key === 'Escape' && closeSearch()) {
|
||||
event.preventDefault();
|
||||
} else if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
|
||||
event.preventDefault();
|
||||
send('cycle', {reverse: event.shiftKey});
|
||||
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
|
||||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
@@ -134,11 +346,25 @@ bridge.addEventListener('message', ({ data }) => {
|
||||
const message = JSON.parse(data);
|
||||
if (message.action === 'clear') {
|
||||
++generation;
|
||||
closeSearch();
|
||||
document.documentElement.classList.remove('rendered');
|
||||
content.replaceChildren();
|
||||
}
|
||||
if (message.action === 'render') void render(message).catch(() => send('failed'));
|
||||
if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) {
|
||||
if (!message.saved) pendingTask.target.checked = !pendingTask.checked;
|
||||
pendingTask = undefined;
|
||||
}
|
||||
if (message.action === 'appearance') {
|
||||
const style = document.documentElement.style;
|
||||
style.setProperty('--markdown-width', message.width ? message.width + 'px' : 'none');
|
||||
style.setProperty('--markdown-font-size', message.fontSize + 'pt');
|
||||
style.setProperty('--markdown-font', message.font ? CSS.escape(message.font) + ', system-ui, sans-serif' : 'system-ui, sans-serif');
|
||||
}
|
||||
if (message.action === 'anchor') restorePosition(message);
|
||||
if (message.action === 'find') openSearch();
|
||||
if (message.action === 'find-next') stepSearch(message.previous ? -1 : 1);
|
||||
if (message.action === 'escape' && !closeSearch()) send('close');
|
||||
if (message.action === 'back' || message.action === 'forward') navigate(message.action);
|
||||
if (message.action === 'history') {
|
||||
back.disabled = !message.back;
|
||||
|
||||
@@ -3,7 +3,8 @@ const terminal = new Terminal({
|
||||
fontFamily: 'Consolas, monospace',
|
||||
fontSize: 16,
|
||||
cursorBlink: false,
|
||||
stdinDisabled: true,
|
||||
cursorInactiveStyle: 'none',
|
||||
disableStdin: true,
|
||||
theme: { background: '#181818', foreground: '#e8e8e8' },
|
||||
});
|
||||
const fit = new FitAddon.FitAddon();
|
||||
@@ -20,6 +21,7 @@ terminal.parser.registerOscHandler(633, data => {
|
||||
terminal.loadAddon(fit);
|
||||
const host = document.getElementById('terminal');
|
||||
terminal.open(host);
|
||||
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
|
||||
host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true);
|
||||
const screen = host.querySelector('.xterm-screen');
|
||||
let traceEnabled = false;
|
||||
@@ -51,6 +53,11 @@ function anchorOutput() {
|
||||
trace(2);
|
||||
}
|
||||
terminal.attachCustomKeyEventHandler(event => {
|
||||
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
|
||||
if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter');
|
||||
event.preventDefault();
|
||||
return false;
|
||||
}
|
||||
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) return true;
|
||||
if (event.code === 'KeyO') bridge.postMessage('toggle');
|
||||
else if (event.code === 'ArrowUp') bridge.postMessage('grow');
|
||||
@@ -62,7 +69,7 @@ terminal.attachCustomKeyEventHandler(event => {
|
||||
if (!event.repeat) bridge.postMessage('insert-name');
|
||||
}
|
||||
else if (event.key === 'Insert') {
|
||||
if (!event.repeat) bridge.postMessage('copy-panel-names');
|
||||
if (!event.repeat) bridge.postMessage('copy-command-line-or-panel-names');
|
||||
}
|
||||
else if (event.code === 'KeyR') {
|
||||
if (!event.repeat) bridge.postMessage('refresh-panel');
|
||||
@@ -78,6 +85,15 @@ terminal.onScroll(() => {
|
||||
anchorOutput();
|
||||
});
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
if (data === 'clear-selection') {
|
||||
terminal.clearSelection();
|
||||
return;
|
||||
}
|
||||
if (data === 'scroll-bottom') {
|
||||
terminal.scrollToBottom();
|
||||
anchorOutput();
|
||||
return;
|
||||
}
|
||||
if (data === 'trace:on' || data === 'trace:output') {
|
||||
traceEnabled = true;
|
||||
traceOutput = data === 'trace:output';
|
||||
|
||||
+515
-144
File diff suppressed because it is too large.
Load diff
@@ -110,6 +110,13 @@ class App
|
||||
void checkAutostartPath();
|
||||
bool checkingAutostartPath{};
|
||||
HHOOK keyboardHook{}, mouseHook{};
|
||||
enum class InputState { Active, Pausing, Paused };
|
||||
std::atomic<InputState> inputState{InputState::Active};
|
||||
bool installInputHooks();
|
||||
void releaseInputHooks();
|
||||
void toggleInputProcessing();
|
||||
void updateLanInputTimer();
|
||||
void pollLanInput();
|
||||
struct MousePress
|
||||
{
|
||||
HWND target{};
|
||||
@@ -161,14 +168,18 @@ class App
|
||||
bool stop{};
|
||||
UINT taskbarCreated{};
|
||||
bool trayRetryPending{};
|
||||
LanInputConnections trayInput;
|
||||
bool trayInputPulse{};
|
||||
HICON trayBaseIcon(int width, int height) const;
|
||||
bool updateTray(DWORD action);
|
||||
void refreshTrayInput();
|
||||
uint64_t transformAttempt{}, previousAttemptVersion{};
|
||||
size_t incomingLanFileCount{};
|
||||
bool incomingFileBalloon{};
|
||||
std::atomic<uint64_t> activeTransformAttempt{};
|
||||
ULONGLONG previousAttemptAt{};
|
||||
HWND previousAttemptWindow{};
|
||||
int previousAttemptCommand{}, repeatAttempts{};
|
||||
std::vector<std::pair<int, Hotkey>> hookBindings;
|
||||
std::vector<Hotkey> availableBeforePause;
|
||||
Hotkey registeredFilesHotkey{};
|
||||
int filesHotkeyId{};
|
||||
HotkeyHook hotkeyHook;
|
||||
@@ -192,6 +203,7 @@ class App
|
||||
RECT snippetPopupAnchor{};
|
||||
bool snippetCaretPending{};
|
||||
std::optional<RECT> 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);
|
||||
|
||||
+11
-4
@@ -34,13 +34,14 @@ std::wstring layoutLanguage(const Layout &layout)
|
||||
return {};
|
||||
}
|
||||
}
|
||||
bool safeAutoWord(const std::wstring &word, int minimumLength)
|
||||
bool safeAutoWord(const std::wstring &word, int minimumLength, bool allowUppercase)
|
||||
{
|
||||
if (minimumLength < 1 || minimumLength > 32 || word.size() < (size_t)minimumLength || word.size() > 32 ||
|
||||
!std::all_of(word.begin(), word.end(), letter))
|
||||
return false;
|
||||
auto small = lower(word);
|
||||
return word == small || (word.substr(1) == small.substr(1) && word != upper(word));
|
||||
const bool allUppercase = word == upper(word);
|
||||
return word == small || (allUppercase ? allowUppercase : word.substr(1) == small.substr(1));
|
||||
}
|
||||
namespace {
|
||||
constexpr size_t DictionaryBlockWords = 32;
|
||||
@@ -289,9 +290,15 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
||||
if (dictionary == dictionaries.end())
|
||||
continue;
|
||||
auto converted = convert(word, layouts[source], layouts[i], true);
|
||||
if (converted == word || !safeAutoWord(converted, settings.autoMinLength))
|
||||
if (converted == word)
|
||||
continue;
|
||||
int rank = personal(dictionary->first, converted) ? 1 : dictionary->second->rank(converted);
|
||||
const bool knownPersonal = personal(dictionary->first, converted);
|
||||
auto letters = converted;
|
||||
if (knownPersonal)
|
||||
std::erase(letters, L'-');
|
||||
if (!safeAutoWord(letters, settings.autoMinLength, knownPersonal))
|
||||
continue;
|
||||
int rank = knownPersonal ? 1 : dictionary->second->rank(converted);
|
||||
if (!rank)
|
||||
continue;
|
||||
if (matchedText && *matchedText != converted)
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ struct AutoSuggestion
|
||||
std::wstring text;
|
||||
};
|
||||
std::wstring layoutLanguage(const Layout &);
|
||||
bool safeAutoWord(const std::wstring &, int minimumLength = 3);
|
||||
bool safeAutoWord(const std::wstring &, int minimumLength = 3, bool allowUppercase = false);
|
||||
bool autoClosingSelection(const std::wstring &, const Settings & = {});
|
||||
int matchAutoInput(const Run &, const std::wstring &, const std::vector<Layout> &, const Layout &,
|
||||
const Settings & = {});
|
||||
|
||||
+4
-3
@@ -229,16 +229,17 @@ int runConfigurator(HINSTANCE instance, bool snippets, bool logs)
|
||||
MSG message;
|
||||
while ((app.settingsWindow || app.snippetsWindow || app.logWindow) && GetMessageW(&message, nullptr, 0, 0) > 0)
|
||||
{
|
||||
if (app.settingsWindow && !IsWindowEnabled(app.settingsWindow))
|
||||
const auto editor = app.settingsWindow ? app.settingsWindow : app.snippetsWindow;
|
||||
if (editor && !IsWindowEnabled(editor))
|
||||
{
|
||||
HWND popup = GetLastActivePopup(app.settingsWindow);
|
||||
HWND popup = GetLastActivePopup(editor);
|
||||
while (!IsWindowEnabled(popup))
|
||||
{
|
||||
HWND next = GetLastActivePopup(popup);
|
||||
if (next == popup) break;
|
||||
popup = next;
|
||||
}
|
||||
if (popup != app.settingsWindow && IsDialogMessageW(popup, &message)) continue;
|
||||
if (popup != editor && IsDialogMessageW(popup, &message)) continue;
|
||||
}
|
||||
if (app.settingsWindow && IsDialogMessageW(app.settingsWindow, &message)) continue;
|
||||
if (app.snippetsWindow && IsDialogMessageW(app.snippetsWindow, &message)) continue;
|
||||
|
||||
+182
-62
@@ -3,6 +3,7 @@
|
||||
#include <cwctype>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
@@ -21,20 +22,29 @@ int snippetAppPriority(const Snippet &snippet, const std::wstring &process)
|
||||
for (const auto &app : snippet.apps) if (snippetAppName(app) == name && !name.empty()) return 2;
|
||||
return 0;
|
||||
}
|
||||
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet)
|
||||
static bool validSeparatedWord(const std::wstring &text, const std::wstring &alphabet,
|
||||
std::wstring_view separators)
|
||||
{
|
||||
if (text.empty() || text.size() > 32) return false;
|
||||
auto isLetter = [&](wchar_t c) { return alphabet.find(c) != alphabet.npos; };
|
||||
for (size_t i = 0; i < text.size(); ++i)
|
||||
{
|
||||
if (isLetter(text[i])) continue;
|
||||
if (text[i] != L' ' && text[i] != L'\'' && text[i] != L'\u2019' && text[i] != L'\u02bc')
|
||||
if (separators.find(text[i]) == separators.npos)
|
||||
return false;
|
||||
if (i == 0 || i + 1 == text.size() || !isLetter(text[i - 1]) || !isLetter(text[i + 1]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet)
|
||||
{
|
||||
return validSeparatedWord(text, alphabet, L" '\u2019\u02bc");
|
||||
}
|
||||
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet)
|
||||
{
|
||||
return validSeparatedWord(lower(text), alphabet, L"-");
|
||||
}
|
||||
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet)
|
||||
{
|
||||
return text.find(L' ') == text.npos && text.find_first_of(alphabet) != text.npos &&
|
||||
@@ -309,40 +319,6 @@ std::wstring transliterate(const std::wstring &text)
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Template parseTemplate(const std::wstring &text)
|
||||
{
|
||||
Template t;
|
||||
size_t cursor = std::wstring::npos;
|
||||
for (size_t i = 0; i < text.size();)
|
||||
{
|
||||
if (text.compare(i, 9, L"{{enter}}") == 0)
|
||||
{
|
||||
t.text += L"{enter}";
|
||||
i += 9;
|
||||
}
|
||||
else if (text.compare(i, 7, L"{enter}") == 0)
|
||||
{
|
||||
++t.enters;
|
||||
i += 7;
|
||||
}
|
||||
else if (text.compare(i, 10, L"{{cursor}}\0", 10) == 0)
|
||||
{
|
||||
t.text += L"{cursor}";
|
||||
i += 10;
|
||||
}
|
||||
else if (text.compare(i, 8, L"{cursor}") == 0)
|
||||
{
|
||||
cursor = t.text.size();
|
||||
++t.cursors;
|
||||
i += 8;
|
||||
}
|
||||
else
|
||||
t.text += text[i++];
|
||||
}
|
||||
if (cursor != text.npos)
|
||||
t.suffix = t.text.substr(cursor);
|
||||
return t;
|
||||
}
|
||||
namespace
|
||||
{
|
||||
const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
|
||||
@@ -367,7 +343,176 @@ const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
|
||||
{VK_DIVIDE, L"Divide"}, {VK_DECIMAL, L"Decimal"}};
|
||||
return names;
|
||||
}
|
||||
WORD namedKey(const std::wstring &token)
|
||||
{
|
||||
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
|
||||
return upper(token)[0];
|
||||
if (token.size() == 4 && token.starts_with(L"num") && token[3] >= L'0' && token[3] <= L'9')
|
||||
return VK_NUMPAD0 + token[3] - L'0';
|
||||
if (token.size() >= 2 && token[0] == L'f')
|
||||
{
|
||||
wchar_t *tail{};
|
||||
long n = wcstol(token.c_str() + 1, &tail, 10);
|
||||
if (!*tail && n >= 1 && n <= 24) return static_cast<WORD>(VK_F1 + n - 1);
|
||||
return 0;
|
||||
}
|
||||
for (const auto &[key, name] : namedKeys())
|
||||
if (lower(name) == token) return static_cast<WORD>(key);
|
||||
return 0;
|
||||
}
|
||||
WORD snippetKey(std::wstring_view name)
|
||||
{
|
||||
const auto token = lower(std::wstring(name));
|
||||
static constexpr std::pair<std::wstring_view, WORD> modifiers[] = {
|
||||
{L"shift", VK_LSHIFT}, {L"shiftl", VK_LSHIFT}, {L"shiftr", VK_RSHIFT},
|
||||
{L"ctrl", VK_LCONTROL}, {L"ctrll", VK_LCONTROL}, {L"ctrlr", VK_RCONTROL},
|
||||
{L"alt", VK_LMENU}, {L"altl", VK_LMENU}, {L"altr", VK_RMENU},
|
||||
{L"win", VK_LWIN}, {L"winl", VK_LWIN}, {L"winr", VK_RWIN}};
|
||||
for (const auto &[label, key] : modifiers)
|
||||
if (label == token) return key;
|
||||
if (token == L"return") return VK_RETURN;
|
||||
// The old double-braced Enter marker is still an escape.
|
||||
return token == L"enter" ? 0 : namedKey(token);
|
||||
}
|
||||
struct SnippetMarker
|
||||
{
|
||||
std::wstring_view name;
|
||||
size_t length, depth;
|
||||
};
|
||||
std::optional<SnippetMarker> snippetMarker(std::wstring_view input)
|
||||
{
|
||||
if (!input.starts_with(L'{')) return {};
|
||||
size_t depth = 1;
|
||||
while (depth < 3 && depth < input.size() && input[depth] == L'{') ++depth;
|
||||
const auto end = input.find_first_of(L"{}", depth);
|
||||
if (end == input.npos || !input.substr(end).starts_with(std::wstring_view(L"}}}", depth)))
|
||||
return {};
|
||||
return SnippetMarker{input.substr(depth, end - depth), end + depth, depth};
|
||||
}
|
||||
std::optional<DWORD> snippetPause(std::wstring_view token)
|
||||
{
|
||||
constexpr std::wstring_view prefix = L"pause:";
|
||||
constexpr DWORD maxPause = 10000;
|
||||
if (!token.starts_with(prefix) || token.size() == prefix.size()) return {};
|
||||
DWORD duration = 0;
|
||||
for (wchar_t digit : token.substr(prefix.size()))
|
||||
{
|
||||
if (digit < L'0' || digit > L'9') return {};
|
||||
duration = duration * 10 + (digit - L'0');
|
||||
if (duration > maxPause) return {};
|
||||
}
|
||||
return duration;
|
||||
}
|
||||
} // namespace
|
||||
std::wstring snippetKeyName(WORD key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case VK_LSHIFT: return L"Shift";
|
||||
case VK_RSHIFT: return L"ShiftR";
|
||||
case VK_LCONTROL: return L"Ctrl";
|
||||
case VK_RCONTROL: return L"CtrlR";
|
||||
case VK_LMENU: return L"Alt";
|
||||
case VK_RMENU: return L"AltR";
|
||||
case VK_LWIN: return L"Win";
|
||||
case VK_RWIN: return L"WinR";
|
||||
default: return Hotkey{0, key}.format();
|
||||
}
|
||||
}
|
||||
std::wstring formatSnippetInsertion(SnippetInsertion type, std::wstring_view parameter)
|
||||
{
|
||||
if (type == SnippetInsertion::Cursor) return L"{cursor}";
|
||||
if (type == SnippetInsertion::Enter) return L"{enter}";
|
||||
if (type == SnippetInsertion::Pause)
|
||||
{
|
||||
auto pause = L"pause:" + std::wstring(parameter);
|
||||
return snippetPause(pause) ? L"{" + pause + L"}" : std::wstring{};
|
||||
}
|
||||
const bool chord = type == SnippetInsertion::Chord;
|
||||
if (!chord && type != SnippetInsertion::Key) return {};
|
||||
|
||||
std::wstring text;
|
||||
std::vector<WORD> keys;
|
||||
while (true)
|
||||
{
|
||||
const auto end = parameter.find(L'+');
|
||||
const auto token = parameter.substr(0, end);
|
||||
const auto first = token.find_first_not_of(L" \t");
|
||||
if (first == token.npos) return {};
|
||||
auto name = lower(std::wstring(token.substr(first, token.find_last_not_of(L" \t") - first + 1)));
|
||||
if (name == L"enter") name = L"return";
|
||||
const auto key = snippetKey(name);
|
||||
if (!key || std::find(keys.begin(), keys.end(), key) != keys.end()) return {};
|
||||
keys.push_back(key);
|
||||
if (!text.empty()) text += L'+';
|
||||
text += L"{{" + name + L"}}";
|
||||
if (end == parameter.npos) break;
|
||||
if (!chord) return {};
|
||||
parameter.remove_prefix(end + 1);
|
||||
}
|
||||
return chord && keys.size() < 2 ? std::wstring{} : text;
|
||||
}
|
||||
Template parseTemplate(const std::wstring &text)
|
||||
{
|
||||
Template t;
|
||||
std::wstring_view remaining(text);
|
||||
size_t cursor = text.npos;
|
||||
while (!remaining.empty())
|
||||
{
|
||||
const auto marker = snippetMarker(remaining);
|
||||
if (!marker)
|
||||
{
|
||||
t.text += remaining.front();
|
||||
remaining.remove_prefix(1);
|
||||
continue;
|
||||
}
|
||||
const auto [name, length, depth] = *marker;
|
||||
const auto pause = depth <= 2 ? snippetPause(name) : std::nullopt;
|
||||
const WORD key = depth >= 2 ? snippetKey(name) : 0;
|
||||
const bool legacyEscape = name == L"cursor" || name == L"enter";
|
||||
if (depth == 1 && name == L"cursor")
|
||||
{
|
||||
cursor = t.text.size();
|
||||
++t.cursors;
|
||||
}
|
||||
else if (depth == 1 && name == L"enter")
|
||||
t.actions.push_back({t.text.size(), std::vector<WORD>{VK_RETURN}});
|
||||
else if (depth == 1 && pause)
|
||||
t.actions.push_back({t.text.size(), *pause});
|
||||
else if (depth == 2 && key)
|
||||
{
|
||||
std::vector<WORD> keys{key};
|
||||
remaining.remove_prefix(length);
|
||||
while (remaining.starts_with(L'+'))
|
||||
{
|
||||
const auto next = snippetMarker(remaining.substr(1));
|
||||
if (!next || next->depth != 2) break;
|
||||
const WORD nextKey = snippetKey(next->name);
|
||||
if (!nextKey) break;
|
||||
if (std::find(keys.begin(), keys.end(), nextKey) == keys.end())
|
||||
keys.push_back(nextKey);
|
||||
remaining.remove_prefix(1 + next->length);
|
||||
}
|
||||
t.actions.push_back({t.text.size(), std::move(keys)});
|
||||
continue;
|
||||
}
|
||||
else if ((depth >= 2 && legacyEscape) || (depth == 2 && pause) || (depth == 3 && key))
|
||||
t.text += remaining.substr(1, length - 2);
|
||||
else
|
||||
t.text += remaining.substr(0, length);
|
||||
remaining.remove_prefix(length);
|
||||
}
|
||||
if (cursor != text.npos)
|
||||
t.suffix = t.text.substr(cursor);
|
||||
// A leading action has historically followed replacement of the trigger.
|
||||
// Keep that behavior while allowing actions between text segments.
|
||||
const auto first = std::find_if(t.actions.begin(), t.actions.end(),
|
||||
[](const SnippetAction &action) { return action.offset != 0; });
|
||||
const auto firstText = first == t.actions.end() ? t.text.size() : first->offset;
|
||||
for (auto it = t.actions.begin(); it != first; ++it)
|
||||
it->offset = firstText;
|
||||
return t;
|
||||
}
|
||||
std::wstring Hotkey::format() const
|
||||
{
|
||||
if (!key)
|
||||
@@ -413,32 +558,7 @@ std::optional<Hotkey> Hotkey::parse(std::wstring s)
|
||||
h.modifiers |= MOD_WIN;
|
||||
else
|
||||
{
|
||||
if (h.key)
|
||||
return {};
|
||||
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
|
||||
h.key = upper(token)[0];
|
||||
else if (token.size() == 4 && token.substr(0, 3) == L"num" && token[3] >= L'0' &&
|
||||
token[3] <= L'9')
|
||||
h.key = VK_NUMPAD0 + token[3] - L'0';
|
||||
else if (token.size() >= 2 && token[0] == L'f')
|
||||
{
|
||||
wchar_t *tail{};
|
||||
long n = wcstol(token.c_str() + 1, &tail, 10);
|
||||
if (*tail || n < 1 || n > 24)
|
||||
return {};
|
||||
h.key = VK_F1 + (UINT)n - 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (auto &[key, name] : namedKeys())
|
||||
if (lower(name) == token)
|
||||
{
|
||||
h.key = key;
|
||||
break;
|
||||
}
|
||||
if (!h.key)
|
||||
return {};
|
||||
}
|
||||
if (h.key || !(h.key = namedKey(token))) return {};
|
||||
}
|
||||
if (end == s.npos)
|
||||
break;
|
||||
|
||||
+13
-2
@@ -5,6 +5,7 @@
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
#include <windows.h>
|
||||
|
||||
@@ -22,6 +23,7 @@ struct Layout
|
||||
bool letter(wchar_t ch);
|
||||
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet);
|
||||
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet);
|
||||
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet);
|
||||
std::wstring lower(std::wstring text);
|
||||
std::wstring upper(std::wstring text);
|
||||
std::wstring convert(const std::wstring &, const Layout &, const Layout &, bool force = false);
|
||||
@@ -41,13 +43,22 @@ std::wstring snippetAppName(std::wstring);
|
||||
int snippetAppPriority(const Snippet &, const std::wstring &process);
|
||||
std::wstring snippetId(const Snippet &);
|
||||
std::wstring newSnippetId();
|
||||
struct SnippetAction
|
||||
{
|
||||
size_t offset;
|
||||
std::variant<std::vector<WORD>, DWORD> value;
|
||||
bool operator==(const SnippetAction &) const = default;
|
||||
};
|
||||
struct Template
|
||||
{
|
||||
std::wstring text, suffix;
|
||||
std::vector<SnippetAction> actions;
|
||||
int cursors = 0;
|
||||
int enters = 0;
|
||||
};
|
||||
Template parseTemplate(const std::wstring &);
|
||||
enum class SnippetInsertion { Cursor, Enter, Pause, Key, Chord };
|
||||
std::wstring snippetKeyName(WORD);
|
||||
std::wstring formatSnippetInsertion(SnippetInsertion, std::wstring_view parameter);
|
||||
struct Hotkey
|
||||
{
|
||||
UINT modifiers{}, key{};
|
||||
@@ -78,7 +89,7 @@ struct Settings
|
||||
bool autoCorrect = false;
|
||||
bool autoReplace = false, autoTypos = false;
|
||||
std::map<std::wstring, std::wstring> autoReplacements;
|
||||
bool writeLog = true;
|
||||
bool writeLog = false;
|
||||
bool screenshotAutoOpenEditor = false;
|
||||
bool useTesseract = false;
|
||||
std::wstring tesseractPath;
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
#pragma once
|
||||
|
||||
#include "platform.h"
|
||||
#include "files_powershell.h"
|
||||
#include "files_windows_command_catalog.h"
|
||||
#include "../vendor/json.hpp"
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
class CommandCompletion
|
||||
{
|
||||
public:
|
||||
using Json = nlohmann::json;
|
||||
|
||||
CommandCompletion() = default;
|
||||
CommandCompletion(const CommandCompletion &) = delete;
|
||||
CommandCompletion &operator=(const CommandCompletion &) = delete;
|
||||
~CommandCompletion() { close(); }
|
||||
|
||||
bool request(const std::wstring &line, DWORD caret, const std::wstring &directory)
|
||||
{
|
||||
auto message=Json{{"line",utf8(line)},{"caret",caret},{"directory",utf8(directory)}}.dump(
|
||||
-1,' ',true,Json::error_handler_t::replace)+"\n";
|
||||
if(message.size()>32768 || (!process && !start())) return false;
|
||||
if(!write(message))
|
||||
{
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
deadline=GetTickCount64()+5000;
|
||||
return true;
|
||||
}
|
||||
|
||||
// An empty optional means the request is still running.
|
||||
std::optional<Json> poll()
|
||||
{
|
||||
DWORD available{},count{};
|
||||
char chunk[8192];
|
||||
if(!PeekNamedPipe(output,nullptr,0,nullptr,&available,nullptr) ||
|
||||
GetTickCount64()>=deadline || pending.size()>1024*1024)
|
||||
{
|
||||
close();
|
||||
return Json{};
|
||||
}
|
||||
if(available && ReadFile(output,chunk,std::min<DWORD>(available,sizeof(chunk)),&count,nullptr))
|
||||
pending.append(chunk,count);
|
||||
const auto end=pending.find('\n');
|
||||
if(end==pending.npos) return {};
|
||||
auto result=Json::parse(pending.begin(),pending.begin()+end,nullptr,false);
|
||||
pending.erase(0,end+1);
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
HANDLE process{},input{},output{},job{};
|
||||
ULONGLONG deadline{};
|
||||
std::string pending;
|
||||
|
||||
bool write(std::string_view message)
|
||||
{
|
||||
DWORD written{};
|
||||
return WriteFile(input,message.data(),static_cast<DWORD>(message.size()),&written,nullptr) &&
|
||||
written==message.size();
|
||||
}
|
||||
|
||||
bool start()
|
||||
{
|
||||
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
|
||||
HANDLE childInput{},childOutput{};
|
||||
std::string catalog;
|
||||
for(const auto row:windowsCommandCatalog) catalog.append(row).push_back('\n');
|
||||
const auto initial=Json{{"catalog",std::move(catalog)}}.dump()+"\n";
|
||||
const auto inputCapacity=static_cast<DWORD>(initial.size()+32768);
|
||||
const bool pipes=CreatePipe(&childInput,&input,&inheritable,inputCapacity) &&
|
||||
CreatePipe(&output,&childOutput,&inheritable,65536) &&
|
||||
SetHandleInformation(input,HANDLE_FLAG_INHERIT,0) &&
|
||||
SetHandleInformation(output,HANDLE_FLAG_INHERIT,0);
|
||||
const bool started=pipes && launch(childInput,childOutput) && write(initial);
|
||||
if(childInput) CloseHandle(childInput);
|
||||
if(childOutput) CloseHandle(childOutput);
|
||||
if(!started) close();
|
||||
return started;
|
||||
}
|
||||
|
||||
bool launch(HANDLE childInput,HANDLE childOutput)
|
||||
{
|
||||
const auto shell=windowsPowerShell();
|
||||
if(shell.empty()) return false;
|
||||
// The request is data on stdin. PowerShell parses it for completion in this separate session.
|
||||
wchar_t command[]=LR"PS(powershell.exe -NoLogo -NoProfile -NonInteractive -Command "
|
||||
$ProgressPreference = 'SilentlyContinue';
|
||||
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);
|
||||
function Get-CompletedArguments($command, $position, $includeCurrent) {
|
||||
foreach ($element in ($command.CommandElements | Select-Object -Skip 1)) {
|
||||
if ($element.Extent.EndOffset -gt $position -or
|
||||
(!$includeCurrent -and $element.Extent.EndOffset -eq $position)) { break }
|
||||
if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
|
||||
$element.Value;
|
||||
} else { $element.Extent.Text }
|
||||
}
|
||||
}
|
||||
|
||||
function New-ArgumentCompletion([string]$value) {
|
||||
$text = $value;
|
||||
if ($value.StartsWith('@') -or $value -notmatch '^[\p{L}\p{M}\p{N}._/@:+,=\-]+$') {
|
||||
$quote = [string][char]39;
|
||||
$text = $quote + [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($value) + $quote;
|
||||
}
|
||||
[System.Management.Automation.CompletionResult]::new($text, $value, 'ParameterValue', $value)
|
||||
}
|
||||
|
||||
function Get-DhcpAdapterNames {
|
||||
foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
|
||||
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
|
||||
try {
|
||||
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
$initial = ConvertFrom-Json -InputObject ([Console]::ReadLine());
|
||||
$windowsCommands = @{};
|
||||
$windowsHelp = @{};
|
||||
foreach ($row in ($initial.catalog -split '\r?\n')) {
|
||||
if (!$row) { continue }
|
||||
$name, $values, $article = $row.Split([char]9, 3);
|
||||
$windowsCommands[$name] = if ($values) { $values.Split(' ') } else { @() };
|
||||
if ($article) { $windowsHelp[$name] = $article }
|
||||
}
|
||||
$windowsRoots = @($windowsCommands.Keys | Where-Object { !($_.Contains(' ')) } | Sort-Object);
|
||||
$windowsPrograms = @(foreach ($name in $windowsRoots) { $name; $name + '.exe'; $name + '.com' });
|
||||
function Get-WindowsCommandContext($command, $position, $includeCurrent) {
|
||||
if (!$command) { return }
|
||||
$invoked = $command.GetCommandName();
|
||||
if (!$invoked -or !$windowsCommands.ContainsKey([IO.Path]::GetFileNameWithoutExtension($invoked))) { return }
|
||||
$resolved = Get-Command -Name ([WildcardPattern]::Escape($invoked)) -ErrorAction SilentlyContinue |
|
||||
Select-Object -First 1;
|
||||
if ($resolved -is [System.Management.Automation.AliasInfo]) { $resolved = $resolved.ResolvedCommand }
|
||||
if ($resolved -isnot [System.Management.Automation.ApplicationInfo]) { return }
|
||||
$name = [IO.Path]::GetFileNameWithoutExtension($resolved.Name);
|
||||
$arguments = @(Get-CompletedArguments $command $position $includeCurrent);
|
||||
$values = $null;
|
||||
if ($name -eq 'cmd') {
|
||||
for ($i = 0; $i -lt $arguments.Count; ++$i) {
|
||||
if ($arguments[$i] -notin '/c', '/k') { continue }
|
||||
if ($i + 1 -lt $arguments.Count) {
|
||||
$name = [IO.Path]::GetFileNameWithoutExtension($arguments[$i + 1]);
|
||||
$arguments = @($arguments | Select-Object -Skip ($i + 2));
|
||||
} else { $values = $windowsRoots }
|
||||
break
|
||||
}
|
||||
}
|
||||
$root = $name;
|
||||
$article = $windowsHelp[$name];
|
||||
if (!$values) {
|
||||
foreach ($argument in $arguments) {
|
||||
$child = $name + ' ' + $argument;
|
||||
if (!$windowsCommands.ContainsKey($child)) { break }
|
||||
$name = $child;
|
||||
if ($windowsHelp[$name]) { $article = $windowsHelp[$name] }
|
||||
}
|
||||
$values = $windowsCommands[$name];
|
||||
}
|
||||
@{ root = $root; values = $values; arguments = $arguments; article = $article }
|
||||
}
|
||||
|
||||
Register-ArgumentCompleter -Native -CommandName $windowsPrograms -ScriptBlock {
|
||||
param($word, $command, $position)
|
||||
$context = Get-WindowsCommandContext $command $position $false;
|
||||
if (!$context) { return }
|
||||
if ($context.root -eq 'ipconfig' -and $context.arguments.Count -and
|
||||
$context.arguments[0] -in '/renew','/release') {
|
||||
$script:adapterArguments = $true;
|
||||
if ($context.arguments.Count -ne 1) { return }
|
||||
$prefix = ([string]$word).Trim([char[]]@([char]39, [char]34));
|
||||
foreach ($adapterName in (Get-DhcpAdapterNames | Sort-Object -Unique)) {
|
||||
if ($adapterName.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
New-ArgumentCompletion $adapterName
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if ($word -eq '?') { $word = '/?' }
|
||||
foreach ($value in $context.values) {
|
||||
if ($value.StartsWith([string]$word, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
[System.Management.Automation.CompletionResult]::new($value)
|
||||
}
|
||||
}
|
||||
};
|
||||
Register-ArgumentCompleter -Native -CommandName dotnet,dotnet.exe -ScriptBlock {
|
||||
param($word, $command, $position)
|
||||
$offset = $position - $command.Extent.StartOffset;
|
||||
dotnet.exe complete --position $offset $command.ToString() 2>$null | ForEach-Object {
|
||||
[System.Management.Automation.CompletionResult]::new($_)
|
||||
}
|
||||
};
|
||||
function Find-GitCompletionTools {
|
||||
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1;
|
||||
if (!$git) { return }
|
||||
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source));
|
||||
for ($level = 0; $location -and $level -lt 3; ++$level) {
|
||||
$root = $location.FullName;
|
||||
$location = $location.Parent;
|
||||
$bash = Join-Path $root 'usr/bin/bash.exe';
|
||||
if (![IO.File]::Exists($bash)) { continue }
|
||||
foreach ($architecture in 'mingw64', 'mingw32', 'clangarm64') {
|
||||
$script = Join-Path $root ($architecture + '/share/git/completion/git-completion.bash');
|
||||
if ([IO.File]::Exists($script)) { return @{ bash = $bash; script = $script } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Send words as data to Git for Windows. Backslash-quote escapes are for Windows PowerShell's native argv.
|
||||
$gitCompletionRunner = @'
|
||||
export GIT_ALLOW_PROTOCOL= GIT_TERMINAL_PROMPT=0
|
||||
mapfile -t input
|
||||
for i in ~${!input[@]}~; do input[i]=~${input[i]%$'\r'}~; done
|
||||
source ~${input[0]}~ || exit
|
||||
words=(~${input[@]:1}~)
|
||||
cword=$(( ${#words[@]} - 1 ))
|
||||
cur=${words[cword]}
|
||||
prev=${words[cword-1]}
|
||||
__git_main
|
||||
if (( ${#COMPREPLY[@]} )); then printf '%s\n' ~${COMPREPLY[@]}~; fi
|
||||
'@.Replace('~', ('\' + [char]34));
|
||||
$OutputEncoding = [Console]::OutputEncoding;
|
||||
Register-ArgumentCompleter -Native -CommandName git,git.exe -ScriptBlock {
|
||||
param($word, $command, $position)
|
||||
if (!$script:gitCompletionTools) { $script:gitCompletionTools = Find-GitCompletionTools }
|
||||
if (!$script:gitCompletionTools) { return }
|
||||
$arguments = @('git') + @(Get-CompletedArguments $command $position) + @([string]$word);
|
||||
@($script:gitCompletionTools.script) + $arguments |
|
||||
& $script:gitCompletionTools.bash --noprofile --norc -p -c $gitCompletionRunner 2>$null |
|
||||
ForEach-Object {
|
||||
$value = $_.TrimEnd();
|
||||
if ($value) { New-ArgumentCompletion $value }
|
||||
}
|
||||
};
|
||||
function Get-CompletionCommand($request) {
|
||||
$prefix = $request.line.Substring(0, $request.caret).TrimEnd();
|
||||
$ast = [System.Management.Automation.Language.Parser]::ParseInput($prefix, [ref]$null, [ref]$null);
|
||||
$ast.FindAll({
|
||||
param($node)
|
||||
$node -is [System.Management.Automation.Language.CommandAst] -and
|
||||
$node.Extent.EndOffset -eq $prefix.Length
|
||||
}, $true) | Select-Object -Last 1;
|
||||
}
|
||||
function Test-NoCommandArguments($command) {
|
||||
if (!$command) { return $false }
|
||||
$name = $command.GetCommandName();
|
||||
if (!$name) { return $false }
|
||||
$info = Get-Command -Name ([WildcardPattern]::Escape($name)) -ErrorAction SilentlyContinue;
|
||||
if ($info -is [System.Management.Automation.AliasInfo]) { $info = $info.ResolvedCommand }
|
||||
return ($info -is [System.Management.Automation.FunctionInfo] -or
|
||||
$info -is [System.Management.Automation.CmdletInfo]) -and $info.Parameters.Count -eq 0;
|
||||
}
|
||||
while ($null -ne ($line = [Console]::ReadLine())) {
|
||||
try {
|
||||
$request = ConvertFrom-Json -InputObject $line -ErrorAction Stop;
|
||||
Set-Location -LiteralPath $request.directory -ErrorAction Stop;
|
||||
$script:adapterArguments = $false;
|
||||
$command = Get-CompletionCommand $request;
|
||||
$context = Get-WindowsCommandContext $command $request.caret $true;
|
||||
$result = TabExpansion2 -inputScript $request.line -cursorColumn $request.caret;
|
||||
$candidates = $result.CompletionMatches;
|
||||
if ($candidates.Count -and $candidates[0].ResultType -in 'ProviderItem','ProviderContainer' -and
|
||||
($script:adapterArguments -or (Test-NoCommandArguments $command))) {
|
||||
$candidates = $candidates | Where-Object { $_.ResultType -notin 'ProviderItem','ProviderContainer' };
|
||||
}
|
||||
$items = @($candidates | Select-Object -First 100 | ForEach-Object {
|
||||
@{ label = $_.ListItemText; text = $_.CompletionText; directory = ($_.ResultType -eq 'ProviderContainer') }
|
||||
});
|
||||
$reply = @{ index = $result.ReplacementIndex; length = $result.ReplacementLength;
|
||||
matches = $items; article = [string]$context.article };
|
||||
[Console]::WriteLine((ConvertTo-Json -InputObject $reply -Compress -Depth 4));
|
||||
} catch { [Console]::WriteLine('{}') }
|
||||
}")PS";
|
||||
|
||||
job=CreateJobObjectW(nullptr,nullptr);
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
|
||||
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if(!job || !SetInformationJobObject(job,JobObjectExtendedLimitInformation,&limits,sizeof(limits))) return false;
|
||||
|
||||
SIZE_T bytes{};
|
||||
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
|
||||
std::vector<unsigned char> storage(bytes);
|
||||
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes)) return false;
|
||||
HANDLE inherited[]{childInput,childOutput};
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb=sizeof(startup);
|
||||
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
|
||||
startup.StartupInfo.hStdInput=childInput;
|
||||
startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=childOutput;
|
||||
startup.lpAttributeList=attributes;
|
||||
PROCESS_INFORMATION child{};
|
||||
const bool started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
inherited,sizeof(inherited),nullptr,nullptr) &&
|
||||
CreateProcessW(shell.c_str(),command,nullptr,nullptr,TRUE,
|
||||
CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,
|
||||
nullptr,nullptr,&startup.StartupInfo,&child);
|
||||
DeleteProcThreadAttributeList(attributes);
|
||||
if(!started) return false;
|
||||
process=child.hProcess;
|
||||
const bool running=AssignProcessToJobObject(job,process) && ResumeThread(child.hThread)!=DWORD(-1);
|
||||
if(!running) TerminateProcess(process,1);
|
||||
CloseHandle(child.hThread);
|
||||
return running;
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
for(const auto handle:{job,input,output,process})
|
||||
if(handle) CloseHandle(handle);
|
||||
job=input=output=process=nullptr;
|
||||
pending.clear();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,23 @@ constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MA
|
||||
auto commandHistoryKeys=defaultHistoryKeys;
|
||||
constexpr size_t commandHistoryLimit=1000;
|
||||
|
||||
std::wstring commandHistoryLabel(const std::wstring &command)
|
||||
{
|
||||
constexpr std::wstring_view prefix=L"start '";
|
||||
if(!command.starts_with(prefix) || command.size()<=prefix.size() || command.back()!=L'\'')
|
||||
return command;
|
||||
const std::wstring_view literal(command.data()+prefix.size(),command.size()-prefix.size()-1);
|
||||
std::wstring path;
|
||||
for(size_t i=0;i<literal.size();++i)
|
||||
{
|
||||
const auto character=literal[i];
|
||||
if(character==L'\'' || character==L'\u2018' || character==L'\u2019')
|
||||
if(++i==literal.size() || literal[i]!=character) return command;
|
||||
path+=character;
|
||||
}
|
||||
return fs::path(path).is_absolute()?path:command;
|
||||
}
|
||||
|
||||
bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
{
|
||||
if(keys[0]==keys[1]) return false;
|
||||
@@ -12,7 +29,7 @@ bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
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') || function;
|
||||
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;
|
||||
});
|
||||
|
||||
@@ -69,7 +69,7 @@ void populateCommandHistory(HWND dialog)
|
||||
{
|
||||
return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;});
|
||||
};
|
||||
if(containsAll(command+L" "+entry.date))
|
||||
if(containsAll(command+L" "+historyLower(commandHistoryLabel(entry.command))+L" "+entry.date))
|
||||
{
|
||||
matches[0].push_back(index);
|
||||
continue;
|
||||
@@ -91,7 +91,7 @@ void populateCommandHistory(HWND dialog)
|
||||
if(first || date!=lastDate) add(date,-1);
|
||||
first=false;
|
||||
lastDate=date;
|
||||
const auto row=add(entry.command,index);
|
||||
const auto row=add(commandHistoryLabel(entry.command),index);
|
||||
if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row;
|
||||
}
|
||||
}
|
||||
@@ -140,13 +140,7 @@ LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UI
|
||||
SendMessageW(GetParent(list),WM_COMMAND,IDOK,0);
|
||||
return 0;
|
||||
}
|
||||
if(message==LB_GETTOPINDEX || message==WM_NCDESTROY)
|
||||
return DefSubclassProc(list,message,wp,lp);
|
||||
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
|
||||
const auto result=scrollList(list,message,wp,lp);
|
||||
if(top!=SendMessageW(list,LB_GETTOPINDEX,0,0))
|
||||
InvalidateRect(GetParent(list),nullptr,FALSE);
|
||||
return result;
|
||||
return DefSubclassProc(list,message,wp,lp);
|
||||
}
|
||||
|
||||
void sizeCommandHistory(HWND dialog,HWND list)
|
||||
@@ -165,8 +159,9 @@ void sizeCommandHistory(HWND dialog,HWND list)
|
||||
LONG longest{};
|
||||
for(const auto &entry:terminalHistory)
|
||||
{
|
||||
const auto label=commandHistoryLabel(entry.command);
|
||||
SIZE size{};
|
||||
if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast<int>(entry.command.size()),&size))
|
||||
if(GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.size()),&size))
|
||||
longest=std::max(longest,size.cx);
|
||||
}
|
||||
SelectObject(dc,previous);
|
||||
@@ -179,7 +174,7 @@ void sizeCommandHistory(HWND dialog,HWND list)
|
||||
const int gap=MulDiv(4,dpi,96);
|
||||
const int listTop=top+2*textHeight+2*gap;
|
||||
const LONG desired=std::max<LONG>(MulDiv(320,dpi,96),
|
||||
longest+2*cellWidth+2*historyRowInset(dpi)+GetSystemMetricsForDpi(SM_CXVSCROLL,dpi))+2*inset;
|
||||
longest+2*cellWidth+2*historyRowInset(dpi)+scrollBarWidth(list))+2*inset;
|
||||
const auto target=std::min(desired,area.right-area.left);
|
||||
const auto rows=std::max<LRESULT>(1,SendMessageW(list,LB_GETCOUNT,0,0));
|
||||
RECT listWindow{},listClient{};
|
||||
@@ -198,7 +193,7 @@ void sizeCommandHistory(HWND dialog,HWND list)
|
||||
};
|
||||
place(GetDlgItem(dialog,historySearchLabel),top,textHeight);
|
||||
place(GetDlgItem(dialog,historySearch),top+textHeight+gap,textHeight);
|
||||
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-5),
|
||||
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-scrollBarWidth(list)),
|
||||
std::max(1L,height-listTop-inset),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
GetClientRect(list,&listClient);
|
||||
if(rows*textHeight<=listClient.bottom) SendMessageW(list,LB_SETTOPINDEX,0,0);
|
||||
@@ -221,6 +216,7 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM
|
||||
prepareCopyDialog(dialog);
|
||||
const auto list=GetDlgItem(dialog,historyList);
|
||||
SetWindowSubclass(list,historyListScroll,1,0);
|
||||
installScrollBar(list,dialog);
|
||||
SendMessageW(list,WM_SETFONT,reinterpret_cast<WPARAM>(mono),TRUE);
|
||||
SendMessageW(list,LB_SETITEMHEIGHT,0,std::max(1,textHeight));
|
||||
const auto search=GetDlgItem(dialog,historySearch);
|
||||
|
||||
@@ -0,0 +1,868 @@
|
||||
constexpr uint64_t compareFileLimit=2*ks::files::TextDocument::pageBytes;
|
||||
enum ComparisonColor { CompareBackground, CompareText, CompareInsert, CompareDelete, CompareReplace,
|
||||
CompareInline, ComparePadding, CompareDivider, CompareChangedText, CompareColorCount };
|
||||
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();
|
||||
int points=defaultFontPoints;
|
||||
std::array<COLORREF,CompareColorCount> palette{RGB(255,255,255),RGB(24,24,24),RGB(177,226,184),
|
||||
RGB(249,194,194),RGB(251,224,154),RGB(245,170,90),RGB(230,230,230),RGB(160,160,160),RGB(24,24,24)};
|
||||
|
||||
bool operator==(const ComparisonAppearance &other) const
|
||||
{
|
||||
return points==other.points && palette==other.palette && !memcmp(&font,&other.font,sizeof(font));
|
||||
}
|
||||
};
|
||||
|
||||
ComparisonAppearance readComparisonAppearance()
|
||||
{
|
||||
ComparisonAppearance appearance;
|
||||
DWORD bytes=sizeof(appearance);
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,comparisonAppearanceKey,RRF_RT_REG_BINARY,nullptr,
|
||||
&appearance,&bytes)!=ERROR_SUCCESS || bytes!=sizeof(appearance) ||
|
||||
appearance.points<80 || appearance.points>240 ||
|
||||
std::any_of(appearance.palette.begin(),appearance.palette.end(),[](auto color){return color>0xffffff;}))
|
||||
return {};
|
||||
appearance.font.lfFaceName[LF_FACESIZE-1]=0;
|
||||
return appearance;
|
||||
}
|
||||
|
||||
bool saveComparisonAppearance(const ComparisonAppearance &appearance)
|
||||
{
|
||||
return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,comparisonAppearanceKey,REG_BINARY,
|
||||
&appearance,sizeof(appearance))==ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
struct CompareFile
|
||||
{
|
||||
fs::path path;
|
||||
std::wstring label;
|
||||
std::optional<FilesPeer> peer;
|
||||
std::optional<FtpProfile> ftp;
|
||||
};
|
||||
|
||||
struct CompareRow
|
||||
{
|
||||
int left=-1,right=-1;
|
||||
bool changed{};
|
||||
size_t commonStart{},commonEnd{};
|
||||
bool whitespaceOnly{};
|
||||
|
||||
bool hasChange(bool showWhitespace) const {return changed && (showWhitespace || !whitespaceOnly);}
|
||||
};
|
||||
|
||||
struct FileComparison
|
||||
{
|
||||
static constexpr std::array controls{400,401,402,403,407};
|
||||
CompareFile files[2];
|
||||
std::vector<std::wstring> lines[2];
|
||||
std::vector<CompareRow> rows;
|
||||
std::vector<int> changes,allChanges;
|
||||
bool showWhitespace{};
|
||||
RECT initialClient{};
|
||||
std::array<RECT,controls.size()> initialControls{};
|
||||
SIZE minimumWindow{};
|
||||
ComparisonAppearance appearance;
|
||||
HFONT font{};
|
||||
HBRUSH background{};
|
||||
int characterWidth=1;
|
||||
int split=comparisonSplitScale/2;
|
||||
std::optional<int> splitDragOffset;
|
||||
int zoom{},wheelRemainder{};
|
||||
|
||||
~FileComparison()
|
||||
{
|
||||
if(font) DeleteObject(font);
|
||||
if(background) DeleteObject(background);
|
||||
}
|
||||
};
|
||||
|
||||
std::map<HWND,std::unique_ptr<FileComparison>> comparisonWindows;
|
||||
|
||||
LONG comparisonSplitX(const FileComparison &comparison,LONG width)
|
||||
{
|
||||
return MulDiv(width,comparison.split,comparisonSplitScale);
|
||||
}
|
||||
|
||||
void layoutComparisonHeaders(HWND dialog,const FileComparison &comparison)
|
||||
{
|
||||
const auto list=GetDlgItem(dialog,402);
|
||||
RECT bounds{};
|
||||
GetClientRect(list,&bounds);
|
||||
MapWindowPoints(list,dialog,reinterpret_cast<POINT*>(&bounds),2);
|
||||
const auto middle=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
|
||||
const auto inset=comparison.initialControls[0].left;
|
||||
for(int side=0;side<2;++side)
|
||||
{
|
||||
const auto &initial=comparison.initialControls[side];
|
||||
const auto left=(side?middle:bounds.left)+inset;
|
||||
const auto right=(side?bounds.right:middle)-inset;
|
||||
SetWindowPos(GetDlgItem(dialog,400+side),nullptr,left,initial.top,std::max(0L,right-left),
|
||||
initial.bottom-initial.top,SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
font.lfHeight=-MulDiv(points,dpi,720);
|
||||
font.lfWidth=0;
|
||||
if(const auto next=CreateFontIndirectW(&font))
|
||||
{
|
||||
if(comparison.font) DeleteObject(comparison.font);
|
||||
comparison.font=next;
|
||||
}
|
||||
const auto list=GetDlgItem(dialog,402);
|
||||
if(const auto dc=GetDC(list))
|
||||
{
|
||||
const auto previous=SelectObject(dc,comparison.font?comparison.font:mono);
|
||||
TEXTMETRICW metrics{};
|
||||
if(GetTextMetricsW(dc,&metrics))
|
||||
{
|
||||
comparison.characterWidth=std::max(1L,metrics.tmAveCharWidth);
|
||||
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
|
||||
SendMessageW(list,LB_SETITEMHEIGHT,0,metrics.tmHeight+MulDiv(6,dpi,96));
|
||||
SendMessageW(list,LB_SETTOPINDEX,top,0);
|
||||
}
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(list,dc);
|
||||
}
|
||||
InvalidateRect(list,nullptr,TRUE);
|
||||
}
|
||||
|
||||
void applyComparisonAppearance(HWND dialog,FileComparison &comparison)
|
||||
{
|
||||
comparison.appearance=readComparisonAppearance();
|
||||
if(const auto next=CreateSolidBrush(comparison.appearance.palette[CompareBackground]))
|
||||
{
|
||||
if(comparison.background) DeleteObject(comparison.background);
|
||||
comparison.background=next;
|
||||
}
|
||||
applyComparisonFont(dialog,comparison);
|
||||
}
|
||||
|
||||
bool zoomComparison(HWND dialog,FileComparison &comparison,WPARAM wheel)
|
||||
{
|
||||
if(!(GET_KEYSTATE_WPARAM(wheel)&MK_CONTROL)) return false;
|
||||
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;
|
||||
if(zoom!=comparison.zoom)
|
||||
{
|
||||
comparison.zoom=zoom;
|
||||
applyComparisonFont(dialog,comparison);
|
||||
layoutComparisonHeaders(dialog,comparison);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool handleComparisonMessage(MSG &message)
|
||||
{
|
||||
if(!message.hwnd) return false;
|
||||
const auto window=GetAncestor(message.hwnd,GA_ROOT);
|
||||
if(!comparisonWindows.contains(window)) return false;
|
||||
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
|
||||
{
|
||||
SendMessageW(window,WM_CLOSE,0,0);
|
||||
return true;
|
||||
}
|
||||
if(!IsDialogMessageW(window,&message))
|
||||
{
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::vector<std::wstring> readComparisonLines(const CompareFile &input,const std::atomic_bool &canceled)
|
||||
{
|
||||
struct TemporaryDirectory
|
||||
{
|
||||
fs::path path;
|
||||
~TemporaryDirectory()
|
||||
{
|
||||
if(path.empty()) return;
|
||||
std::error_code ignored;
|
||||
fs::remove_all(path,ignored);
|
||||
}
|
||||
} temporary;
|
||||
auto path=input.path;
|
||||
if(input.ftp || input.peer)
|
||||
{
|
||||
const auto directory=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
|
||||
requireFileOperation(fs::create_directory(directory),ERROR_ALREADY_EXISTS);
|
||||
temporary.path=directory;
|
||||
path=directory/L"file";
|
||||
CopyHost source(input.peer?&*input.peer:nullptr,input.ftp);
|
||||
const auto info=source.stat(input.path,canceled);
|
||||
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
|
||||
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
|
||||
ERROR_NOT_SUPPORTED);
|
||||
requireFileOperation(info->size<=compareFileLimit,ERROR_FILE_TOO_LARGE);
|
||||
FilesConnection local;
|
||||
const auto progress=[&](uint64_t,uint64_t){return !canceled;};
|
||||
if(source.ftp) downloadFtpFile(*source.ftp,local,input.path,path,*info,false,progress);
|
||||
else ks::lan::streamFile(*source.files,local,input.peer->id,input.path,path,info->size,
|
||||
info->modified,false,false,progress);
|
||||
}
|
||||
ks::files::TextDocument document(path,false);
|
||||
requireFileOperation(document.size()<=compareFileLimit,ERROR_FILE_TOO_LARGE);
|
||||
std::string text;
|
||||
for(uint64_t page=0;page<document.pages() && !canceled;++page) text+=document.readPage(page);
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
if(std::any_of(text.begin(),text.end(),[](unsigned char ch){
|
||||
return ch<32 && ch!='\t' && ch!='\r' && ch!='\n' && ch!='\f';
|
||||
})) throw std::runtime_error("Select two text files.");
|
||||
if(text.empty()) return {};
|
||||
const auto bytes=static_cast<int>(text.size());
|
||||
const auto count=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,nullptr,0);
|
||||
if(!count) throw std::runtime_error("Compare files supports UTF-8 and UTF-16 text.");
|
||||
std::wstring decoded(count,L'\0');
|
||||
checkFileOperation(MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,decoded.data(),count)!=0);
|
||||
std::vector<std::wstring> lines;
|
||||
size_t start=0;
|
||||
while(true)
|
||||
{
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
if(lines.size()==100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
|
||||
const auto end=decoded.find_first_of(L"\r\n",start);
|
||||
lines.push_back(decoded.substr(start,end==decoded.npos?end:end-start));
|
||||
if(end==decoded.npos) break;
|
||||
start=end+((decoded[end]==L'\r' && end+1<decoded.size() && decoded[end+1]==L'\n')?2:1);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
std::wstring_view comparisonContent(std::wstring_view line)
|
||||
{
|
||||
const auto start=line.find_first_not_of(L" \t");
|
||||
if(start==line.npos) return {};
|
||||
return line.substr(start,line.find_last_not_of(L" \t")-start+1);
|
||||
}
|
||||
|
||||
void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
|
||||
{
|
||||
const auto &left=result.lines[0],&right=result.lines[1];
|
||||
std::map<std::wstring_view,unsigned> ids;
|
||||
std::map<unsigned,unsigned> blankIds;
|
||||
unsigned nextId=1;
|
||||
const auto encode=[&](const auto &lines)
|
||||
{
|
||||
std::vector<unsigned> values;
|
||||
values.reserve(lines.size());
|
||||
unsigned previousContent=0;
|
||||
for(const auto &line:lines)
|
||||
{
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
const auto content=comparisonContent(line);
|
||||
// Blank lines can anchor alignment alongside the preceding content.
|
||||
if(content.empty())
|
||||
{
|
||||
const auto [entry,inserted]=blankIds.try_emplace(previousContent,nextId);
|
||||
nextId+=inserted;
|
||||
values.push_back(entry->second);
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto [entry,inserted]=ids.try_emplace(content,nextId);
|
||||
nextId+=inserted;
|
||||
previousContent=entry->second;
|
||||
values.push_back(previousContent);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
};
|
||||
const auto a=encode(left),b=encode(right);
|
||||
size_t prefix=0, suffix=0;
|
||||
while(prefix<a.size() && prefix<b.size() && a[prefix]==b[prefix]) ++prefix;
|
||||
while(suffix<a.size()-prefix && suffix<b.size()-prefix &&
|
||||
a[a.size()-1-suffix]==b[b.size()-1-suffix]) ++suffix;
|
||||
const auto n=static_cast<int>(a.size()-prefix-suffix),m=static_cast<int>(b.size()-prefix-suffix);
|
||||
const auto append=[&](int x,int y)
|
||||
{
|
||||
CompareRow row{x,y,x<0 || y<0 || left[x]!=right[y]};
|
||||
if(row.changed && (result.rows.empty() || !result.rows.back().changed))
|
||||
result.allChanges.push_back(static_cast<int>(result.rows.size()));
|
||||
if(row.changed && x>=0 && y>=0)
|
||||
{
|
||||
const auto &l=left[x],&r=right[y];
|
||||
row.whitespaceOnly=comparisonContent(l)==comparisonContent(r);
|
||||
const size_t length=std::min(l.size(),r.size());
|
||||
while(row.commonStart<length && l[row.commonStart]==r[row.commonStart]) ++row.commonStart;
|
||||
if(row.commonStart && l[row.commonStart-1]>=0xd800 && l[row.commonStart-1]<=0xdbff)
|
||||
--row.commonStart;
|
||||
while(row.commonEnd<length-row.commonStart &&
|
||||
l[l.size()-1-row.commonEnd]==r[r.size()-1-row.commonEnd]) ++row.commonEnd;
|
||||
if(row.commonEnd && l[l.size()-row.commonEnd]>=0xdc00 && l[l.size()-row.commonEnd]<=0xdfff)
|
||||
--row.commonEnd;
|
||||
}
|
||||
if(row.hasChange(false) && (result.rows.empty() || !result.rows.back().hasChange(false)))
|
||||
result.changes.push_back(static_cast<int>(result.rows.size()));
|
||||
result.rows.push_back(row);
|
||||
};
|
||||
const auto change=[&](size_t x,size_t y,size_t countLeft,size_t countRight)
|
||||
{
|
||||
// Prefer pairing structurally similar lines, leaving unmatched lines on their own side.
|
||||
const auto score=[](std::wstring_view l,std::wstring_view r)
|
||||
{
|
||||
if(l.empty() || r.empty()) return l.empty() && r.empty()?1u:0u;
|
||||
const auto cap=std::min({l.size(),r.size(),size_t{64}});
|
||||
size_t start=0,end=0;
|
||||
while(start<cap && l[start]==r[start]) ++start;
|
||||
while(end<cap-start && l[l.size()-1-end]==r[r.size()-1-end]) ++end;
|
||||
return 1u+static_cast<unsigned>(4*(start+end));
|
||||
};
|
||||
if(!countLeft || !countRight || countLeft>160'000/countRight)
|
||||
{
|
||||
for(size_t i=0;i<std::max(countLeft,countRight);++i)
|
||||
append(i<countLeft?static_cast<int>(x+i):-1,i<countRight?static_cast<int>(y+i):-1);
|
||||
return;
|
||||
}
|
||||
const auto stride=countRight+1;
|
||||
std::vector<std::wstring_view> l,r;
|
||||
for(size_t i=0;i<countLeft;++i) l.push_back(comparisonContent(left[x+i]));
|
||||
for(size_t j=0;j<countRight;++j) r.push_back(comparisonContent(right[y+j]));
|
||||
std::vector<unsigned> best((countLeft+1)*stride);
|
||||
for(size_t i=countLeft;i-->0;)
|
||||
for(size_t j=countRight;j-->0;)
|
||||
best[i*stride+j]=std::max({best[(i+1)*stride+j],best[i*stride+j+1],
|
||||
best[(i+1)*stride+j+1]+score(l[i],r[j])});
|
||||
size_t i=0,j=0;
|
||||
while(i<countLeft && j<countRight)
|
||||
{
|
||||
const auto pairScore=score(l[i],r[j]);
|
||||
if(pairScore && best[i*stride+j]==best[(i+1)*stride+j+1]+pairScore)
|
||||
{
|
||||
append(static_cast<int>(x+i),static_cast<int>(y+j));
|
||||
++i;
|
||||
++j;
|
||||
}
|
||||
else if(best[(i+1)*stride+j]>=best[i*stride+j+1]) append(static_cast<int>(x+i++),-1);
|
||||
else append(-1,static_cast<int>(y+j++));
|
||||
}
|
||||
while(i<countLeft) append(static_cast<int>(x+i++),-1);
|
||||
while(j<countRight) append(-1,static_cast<int>(y+j++));
|
||||
};
|
||||
for(size_t i=0;i<prefix;++i) append(static_cast<int>(i),static_cast<int>(i));
|
||||
if(n && m)
|
||||
{
|
||||
// Myers alignment. Each pass records the farthest left index per edit diagonal.
|
||||
std::vector<std::vector<int>> trace;
|
||||
const auto previousDiagonal=[](const std::vector<int> &prior,int d,int k)
|
||||
{
|
||||
if(k==-d || (k!=d && prior[(d+k-2)/2]<prior[(d+k)/2])) return k+1;
|
||||
return k-1;
|
||||
};
|
||||
bool complete=false;
|
||||
for(int d=0;!complete;++d)
|
||||
{
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
if(d>2'500) throw std::runtime_error("Too many differing lines to align in this comparison.");
|
||||
std::vector<int> level;
|
||||
level.reserve(d+1);
|
||||
for(int k=-d;k<=d;k+=2)
|
||||
{
|
||||
int x=0;
|
||||
if(d)
|
||||
{
|
||||
const auto &prior=trace.back();
|
||||
const auto previous=previousDiagonal(prior,d,k);
|
||||
x=prior[(d-1+previous)/2]+(previous<k);
|
||||
}
|
||||
int y=x-k;
|
||||
while(x<n && y<m && a[prefix+x]==b[prefix+y]) {++x;++y;}
|
||||
level.push_back(x);
|
||||
if(x>=n && y>=m) {complete=true;break;}
|
||||
}
|
||||
trace.push_back(std::move(level));
|
||||
}
|
||||
std::vector<std::pair<int,int>> matches;
|
||||
int x=n,y=m;
|
||||
for(int d=static_cast<int>(trace.size())-1;d>0;--d)
|
||||
{
|
||||
const auto &prior=trace[d-1];
|
||||
const auto previous=previousDiagonal(prior,d,x-y);
|
||||
const int startX=prior[(d-1+previous)/2],startY=startX-previous;
|
||||
while(x>startX && y>startY) {--x;--y;matches.emplace_back(x,y);}
|
||||
x=startX;
|
||||
y=startY;
|
||||
}
|
||||
while(x>0 && y>0) {--x;--y;matches.emplace_back(x,y);}
|
||||
int fromLeft=0,fromRight=0;
|
||||
for(auto it=matches.rbegin();it!=matches.rend();++it)
|
||||
{
|
||||
const auto [leftLine,rightLine]=*it;
|
||||
change(prefix+fromLeft,prefix+fromRight,leftLine-fromLeft,rightLine-fromRight);
|
||||
append(static_cast<int>(prefix+leftLine),static_cast<int>(prefix+rightLine));
|
||||
fromLeft=leftLine+1;
|
||||
fromRight=rightLine+1;
|
||||
}
|
||||
change(prefix+fromLeft,prefix+fromRight,n-fromLeft,m-fromRight);
|
||||
}
|
||||
else change(prefix,prefix,n,m);
|
||||
for(size_t i=0;i<suffix;++i)
|
||||
append(static_cast<int>(a.size()-suffix+i),static_cast<int>(b.size()-suffix+i));
|
||||
}
|
||||
|
||||
void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &item)
|
||||
{
|
||||
const auto dc=item.hDC;
|
||||
const auto bounds=item.rcItem;
|
||||
const auto fill=[&](const RECT &area,COLORREF color)
|
||||
{
|
||||
SetDCBrushColor(dc,color);
|
||||
FillRect(dc,&area,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
};
|
||||
const auto &palette=comparison.appearance.palette;
|
||||
const auto cell=comparison.characterWidth;
|
||||
fill(bounds,palette[CompareBackground]);
|
||||
if(item.itemID>=comparison.rows.size()) return;
|
||||
const auto &row=comparison.rows[item.itemID];
|
||||
const bool changed=row.hasChange(comparison.showWhitespace);
|
||||
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
|
||||
const LONG gutter=std::max(4,cell);
|
||||
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
|
||||
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
|
||||
if(changed) fill(link,highlight);
|
||||
else
|
||||
{
|
||||
const RECT divider{center,bounds.top,center+1,bounds.bottom};
|
||||
fill(divider,palette[CompareDivider]);
|
||||
}
|
||||
if(changed)
|
||||
{
|
||||
const LONG middle=(bounds.top+bounds.bottom)/2;
|
||||
const LONG start=row.left<0?bounds.top:middle,end=row.right<0?bounds.top:middle;
|
||||
SetDCPenColor(dc,palette[CompareChangedText]);
|
||||
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
|
||||
MoveToEx(dc,link.left,start,nullptr);
|
||||
LineTo(dc,link.right,end);
|
||||
SelectObject(dc,pen);
|
||||
}
|
||||
SelectObject(dc,comparison.font?comparison.font:mono);
|
||||
SetBkMode(dc,TRANSPARENT);
|
||||
const auto ink=palette[changed?CompareChangedText:CompareText];
|
||||
SetTextColor(dc,ink);
|
||||
const auto drawSide=[&](int side,int number,RECT area)
|
||||
{
|
||||
if(number<0)
|
||||
{
|
||||
fill(area,palette[ComparePadding]);
|
||||
return;
|
||||
}
|
||||
if(changed) fill(area,highlight);
|
||||
const auto numberText=std::to_wstring(number+1);
|
||||
RECT numberArea=area;
|
||||
numberArea.right=std::min(area.right,area.left+7*cell);
|
||||
DrawTextW(dc,numberText.c_str(),-1,&numberArea,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
|
||||
area.left=std::min(area.right,numberArea.right+cell);
|
||||
const auto &line=comparison.lines[side][number];
|
||||
const auto paneWidth=area.right-area.left;
|
||||
if(paneWidth<=0) return;
|
||||
const auto limit=static_cast<size_t>(paneWidth/cell+2)*4;
|
||||
auto visible=std::wstring_view(line).substr(0,limit);
|
||||
const bool clipped=visible.size()<line.size();
|
||||
if(clipped && visible.back()>=0xd800 && visible.back()<=0xdbff)
|
||||
visible.remove_suffix(1);
|
||||
if(changed && row.left>=0 && row.right>=0)
|
||||
{
|
||||
const auto width=[&](size_t chars)->LONG
|
||||
{
|
||||
if(chars>visible.size()) return paneWidth;
|
||||
RECT measured{};
|
||||
if(chars) DrawTextW(dc,visible.data(),static_cast<int>(chars),&measured,
|
||||
DT_CALCRECT|DT_SINGLELINE|DT_EXPANDTABS|DT_NOPREFIX);
|
||||
return std::min(paneWidth,measured.right);
|
||||
};
|
||||
const auto start=std::min(area.right,area.left+width(row.commonStart));
|
||||
const auto end=std::min(area.right,area.left+width(line.size()-row.commonEnd));
|
||||
const RECT changed{start,area.top,std::min(area.right,std::max(start+2,end)),area.bottom};
|
||||
fill(changed,palette[CompareInline]);
|
||||
}
|
||||
constexpr UINT flags=DT_SINGLELINE|DT_VCENTER|DT_EXPANDTABS|DT_NOPREFIX|DT_END_ELLIPSIS;
|
||||
if(clipped)
|
||||
{
|
||||
auto text=std::wstring(visible)+L"…";
|
||||
DrawTextW(dc,text.c_str(),static_cast<int>(text.size()),&area,flags);
|
||||
}
|
||||
else if(!visible.empty()) DrawTextW(dc,visible.data(),static_cast<int>(visible.size()),&area,flags);
|
||||
};
|
||||
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
|
||||
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
|
||||
if(item.itemState&ODS_SELECTED)
|
||||
{
|
||||
SetDCBrushColor(dc,ink);
|
||||
FrameRect(dc,&bounds,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
}
|
||||
|
||||
LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_KEYDOWN && (wp==VK_F7 || wp==VK_F8))
|
||||
{
|
||||
SendMessageW(GetParent(control),WM_COMMAND,wp==VK_F7?404:405,0);
|
||||
return 0;
|
||||
}
|
||||
if(GetDlgCtrlID(control)!=402) return DefSubclassProc(control,message,wp,lp);
|
||||
const auto dialog=GetParent(control);
|
||||
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!comparison) return DefSubclassProc(control,message,wp,lp);
|
||||
if(message==WM_MOUSEWHEEL && zoomComparison(dialog,*comparison,wp)) return 0;
|
||||
if(message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(control,&client);
|
||||
const auto middle=comparisonSplitX(*comparison,client.right);
|
||||
POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
if(message==WM_SETCURSOR)
|
||||
{
|
||||
if(LOWORD(lp)!=HTCLIENT) return DefSubclassProc(control,message,wp,lp);
|
||||
GetCursorPos(&point);
|
||||
ScreenToClient(control,&point);
|
||||
}
|
||||
const auto grip=MulDiv(5,GetDpiForWindow(control),96);
|
||||
if(comparison->splitDragOffset || std::abs(point.x-middle)<=grip)
|
||||
{
|
||||
SetCursor(LoadCursorW(nullptr,IDC_SIZEWE));
|
||||
if(message!=WM_SETCURSOR)
|
||||
{
|
||||
comparison->splitDragOffset=point.x-middle;
|
||||
SetCapture(control);
|
||||
if(GetCapture()!=control) comparison->splitDragOffset.reset();
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if(comparison->splitDragOffset && (message==WM_MOUSEMOVE || message==WM_LBUTTONUP))
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(control,&client);
|
||||
if(client.right>0)
|
||||
{
|
||||
constexpr int minimumShare=1500;
|
||||
const auto position=GET_X_LPARAM(lp)-*comparison->splitDragOffset;
|
||||
const auto split=std::clamp(MulDiv(position,comparisonSplitScale,client.right),
|
||||
minimumShare,comparisonSplitScale-minimumShare);
|
||||
if(split!=comparison->split)
|
||||
{
|
||||
comparison->split=split;
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
InvalidateRect(control,nullptr,FALSE);
|
||||
}
|
||||
}
|
||||
if(message==WM_LBUTTONUP) ReleaseCapture();
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_CAPTURECHANGED) comparison->splitDragOffset.reset();
|
||||
const auto result=DefSubclassProc(control,message,wp,lp);
|
||||
if(message==WM_PAINT)
|
||||
{
|
||||
RECT client{},last{};
|
||||
GetClientRect(control,&client);
|
||||
const auto count=SendMessageW(control,LB_GETCOUNT,0,0);
|
||||
if(count>0 && SendMessageW(control,LB_GETITEMRECT,count-1,reinterpret_cast<LPARAM>(&last))==LB_ERR)
|
||||
return result;
|
||||
const auto middle=comparisonSplitX(*comparison,client.right);
|
||||
const RECT blank{client.left,std::max(client.top,last.bottom),client.right,client.bottom};
|
||||
if(blank.top<blank.bottom)
|
||||
{
|
||||
const auto dc=GetDC(control);
|
||||
if(dc)
|
||||
{
|
||||
// The list box repaints its rows but can leave earlier divider marks below them.
|
||||
FillRect(dc,&blank,comparison->background?comparison->background:
|
||||
static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
|
||||
const RECT divider{middle,blank.top,middle+1,blank.bottom};
|
||||
SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]);
|
||||
FillRect(dc,÷r,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
ReleaseDC(control,dc);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void layoutComparison(HWND dialog)
|
||||
{
|
||||
const auto *comparison=reinterpret_cast<const FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!comparison || comparison->initialClient.right<=0) return;
|
||||
RECT client{};
|
||||
GetClientRect(dialog,&client);
|
||||
for(size_t i=0;i<FileComparison::controls.size();++i)
|
||||
{
|
||||
const auto id=FileComparison::controls[i];
|
||||
if(id==400 || id==401) continue;
|
||||
auto bounds=comparison->initialControls[i];
|
||||
if(id==402) bounds={0,bounds.top,client.right,client.bottom};
|
||||
SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,bounds.top,
|
||||
bounds.right-bounds.left,std::max(0L,bounds.bottom-bounds.top),
|
||||
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
|
||||
}
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
InvalidateRect(dialog,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void updateComparisonSummary(HWND dialog,const FileComparison &comparison)
|
||||
{
|
||||
const auto blocks=(comparison.showWhitespace?comparison.allChanges:comparison.changes).size();
|
||||
const auto summary=blocks==0?L"Text is identical":blocks==1?L"1 change block":
|
||||
std::to_wstring(blocks)+L" change blocks";
|
||||
SetDlgItemTextW(dialog,403,summary.c_str());
|
||||
const auto toolbar=GetDlgItem(dialog,407);
|
||||
for(const auto id:{404,405}) SendMessageW(toolbar,TB_ENABLEBUTTON,id,MAKELONG(blocks!=0,0));
|
||||
}
|
||||
|
||||
void initializeComparisonToolbar(HWND toolbar)
|
||||
{
|
||||
SendMessageW(toolbar,TB_BUTTONSTRUCTSIZE,sizeof(TBBUTTON),0);
|
||||
SendMessageW(toolbar,TB_SETEXTENDEDSTYLE,0,TBSTYLE_EX_MIXEDBUTTONS);
|
||||
SendMessageW(toolbar,TB_SETMAXTEXTROWS,1,0);
|
||||
const auto first=SendMessageW(toolbar,TB_LOADIMAGES,IDB_HIST_SMALL_COLOR,reinterpret_cast<LPARAM>(HINST_COMMCTRL));
|
||||
const auto icon=[&](int index){return first<0?I_IMAGENONE:static_cast<int>(first)+index;};
|
||||
constexpr BYTE text=BTNS_AUTOSIZE|BTNS_SHOWTEXT;
|
||||
const auto separator=MulDiv(8,GetDpiForWindow(toolbar),96);
|
||||
const TBBUTTON buttons[]{
|
||||
{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")}
|
||||
};
|
||||
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
const auto list=GetDlgItem(dialog,402);
|
||||
const auto toolbar=GetDlgItem(dialog,407);
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
comparison=reinterpret_cast<FileComparison*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
GetClientRect(dialog,&comparison->initialClient);
|
||||
for(size_t i=0;i<FileComparison::controls.size();++i)
|
||||
comparison->initialControls[i]=dialogControlBounds(dialog,FileComparison::controls[i]);
|
||||
RECT window{};
|
||||
GetWindowRect(dialog,&window);
|
||||
comparison->minimumWindow={MulDiv(window.right-window.left,3,4),(window.bottom-window.top)/2};
|
||||
const auto resource=MAKEINTRESOURCEW(IDI_FILES_COMPARE);
|
||||
const auto dpi=GetDpiForWindow(dialog);
|
||||
const auto small=LoadImageW(GetModuleHandleW(nullptr),resource,IMAGE_ICON,
|
||||
GetSystemMetricsForDpi(SM_CXSMICON,dpi),GetSystemMetricsForDpi(SM_CYSMICON,dpi),LR_SHARED);
|
||||
const auto large=LoadIconW(GetModuleHandleW(nullptr),resource);
|
||||
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");
|
||||
for(int side=0;side<2;++side) SetDlgItemTextW(dialog,400+side,comparison->files[side].label.c_str());
|
||||
initializeComparisonToolbar(toolbar);
|
||||
updateComparisonSummary(dialog,*comparison);
|
||||
SetWindowSubclass(list,comparisonKeys,1,0);
|
||||
SetWindowSubclass(toolbar,comparisonKeys,1,0);
|
||||
applyComparisonAppearance(dialog,*comparison);
|
||||
SendMessageW(list,LB_SETCOUNT,comparison->rows.size(),0);
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
if(!comparison->changes.empty()) SendMessageW(list,LB_SETCURSEL,comparison->changes.front(),0);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==filesPreferencesChanged && comparison)
|
||||
{
|
||||
applyComparisonAppearance(dialog,*comparison);
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE)
|
||||
{
|
||||
DestroyWindow(dialog);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_MOUSEWHEEL && comparison && zoomComparison(dialog,*comparison,wp)) return TRUE;
|
||||
if(message==WM_NCDESTROY)
|
||||
{
|
||||
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,nullptr);
|
||||
comparisonWindows.erase(dialog);
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_GETMINMAXINFO && comparison && comparison->minimumWindow.cx)
|
||||
{
|
||||
auto &size=reinterpret_cast<MINMAXINFO*>(lp)->ptMinTrackSize;
|
||||
size.x=comparison->minimumWindow.cx;
|
||||
size.y=comparison->minimumWindow.cy;
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_SIZE && wp!=SIZE_MINIMIZED)
|
||||
{
|
||||
layoutComparison(dialog);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_DRAWITEM && wp==402 && comparison)
|
||||
{
|
||||
drawComparisonRow(*comparison,*reinterpret_cast<const DRAWITEMSTRUCT*>(lp));
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CTLCOLORLISTBOX)
|
||||
return reinterpret_cast<INT_PTR>(comparison && comparison->background?comparison->background:
|
||||
GetStockObject(WHITE_BRUSH));
|
||||
if(message==WM_COMMAND && comparison)
|
||||
{
|
||||
const auto id=LOWORD(wp);
|
||||
if(id==IDCANCEL) {DestroyWindow(dialog);return TRUE;}
|
||||
if(id==406 && HIWORD(wp)==BN_CLICKED)
|
||||
{
|
||||
comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0;
|
||||
updateComparisonSummary(dialog,*comparison);
|
||||
InvalidateRect(list,nullptr,FALSE);
|
||||
return TRUE;
|
||||
}
|
||||
const auto &changes=comparison->showWhitespace?comparison->allChanges:comparison->changes;
|
||||
if((id==404 || id==405) && !changes.empty())
|
||||
{
|
||||
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
|
||||
if(id==404)
|
||||
{
|
||||
const auto previous=std::lower_bound(changes.begin(),changes.end(),current);
|
||||
if(previous!=changes.begin()) SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
|
||||
if(next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(id==402 && HIWORD(wp)==LBN_DBLCLK)
|
||||
{
|
||||
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
|
||||
if(current>=0 && static_cast<size_t>(current)<comparison->rows.size())
|
||||
{
|
||||
const auto &row=comparison->rows[current];
|
||||
const auto side=[&](int file,int line)
|
||||
{
|
||||
return line<0?std::wstring(L"—"):comparison->lines[file][line];
|
||||
};
|
||||
const auto detail=L"Left\n"+side(0,row.left)+L"\n\nRight\n"+side(1,row.right);
|
||||
showFilesNotice(dialog,detail.c_str(),L"Line details");
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDCANCEL)
|
||||
{
|
||||
*reinterpret_cast<std::atomic_bool*>(GetWindowLongPtrW(dialog,DWLP_USER))=true;
|
||||
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
|
||||
return TRUE;
|
||||
}
|
||||
return paintTextDialog(dialog,message,wp,lp,L" Compare files ");
|
||||
}
|
||||
|
||||
void compareSelectedFiles(HWND owner)
|
||||
{
|
||||
auto ¤t=panels[active],&other=panels[1-active];
|
||||
const auto selected=selectedPanelPaths(current);
|
||||
const auto opposite=selectedPanelPaths(other);
|
||||
auto state=std::make_unique<FileComparison>();
|
||||
auto &comparison=*state;
|
||||
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(ftpProfileList(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();
|
||||
const auto location=panelLocation(panel);
|
||||
const auto label=tail+L" · "+location;
|
||||
file={path,label,panel.peer,panel.ftp};
|
||||
return true;
|
||||
};
|
||||
bool valid=false;
|
||||
if(selected.size()==2)
|
||||
valid=pick(current,selected[0],comparison.files[0]) && pick(current,selected[1],comparison.files[1]);
|
||||
else if(selected.size()==1 && opposite.size()==1)
|
||||
valid=pick(current,selected.front(),comparison.files[active]) &&
|
||||
pick(other,opposite.front(),comparison.files[1-active]);
|
||||
if(!valid)
|
||||
{
|
||||
showFilesNotice(owner,L"Mark two text files in the active panel or select one text file in each panel.",
|
||||
L"Compare files");
|
||||
return;
|
||||
}
|
||||
std::atomic_bool canceled{};
|
||||
try
|
||||
{
|
||||
{
|
||||
FileOperationUi worker;
|
||||
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
|
||||
comparisonProgressDialog,reinterpret_cast<LPARAM>(&canceled),false);
|
||||
if(!progress.window()) throw std::runtime_error("Could not open the progress dialog.");
|
||||
progress.show();
|
||||
worker.run(progress.window(),canceled,[&]
|
||||
{
|
||||
for(int side=0;side<2;++side)
|
||||
comparison.lines[side]=readComparisonLines(comparison.files[side],canceled);
|
||||
alignComparison(comparison,canceled);
|
||||
});
|
||||
}
|
||||
if(!canceled)
|
||||
{
|
||||
const auto window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(114),nullptr,
|
||||
comparisonDialog,reinterpret_cast<LPARAM>(&comparison));
|
||||
if(!window) throw std::runtime_error("Could not open the comparison window.");
|
||||
comparisonWindows.emplace(window,std::move(state));
|
||||
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
SetFocus(GetDlgItem(window,402));
|
||||
}
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(canceled || error.code().value()==ERROR_CANCELLED) return;
|
||||
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":
|
||||
fileError(error);
|
||||
showFileOperationError(owner,L"Comparison failed",detail);
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(!canceled) showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
|
||||
}
|
||||
}
|
||||
+34
-16
@@ -52,8 +52,10 @@ LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data)
|
||||
class FilesModalDialog
|
||||
{
|
||||
public:
|
||||
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
|
||||
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument)
|
||||
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument,
|
||||
bool watchOutsideClicks=true)
|
||||
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
|
||||
watchOutsideClicks_(watchOutsideClicks)
|
||||
{
|
||||
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
|
||||
}
|
||||
@@ -108,8 +110,7 @@ public:
|
||||
previous_=activeFilesDialog;
|
||||
activeFilesDialog=window_;
|
||||
entered_=true;
|
||||
if(!filesDialogMouseHook)
|
||||
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
|
||||
refreshMouseHook();
|
||||
if(GetWindowRect(owner_,&ownerBounds_))
|
||||
{
|
||||
if(!layout_) captureLayout();
|
||||
@@ -132,11 +133,7 @@ public:
|
||||
if(!entered_) return;
|
||||
entered_=false;
|
||||
activeFilesDialog=previous_;
|
||||
if(!previous_ && filesDialogMouseHook)
|
||||
{
|
||||
UnhookWindowsHookEx(filesDialogMouseHook);
|
||||
filesDialogMouseHook=nullptr;
|
||||
}
|
||||
refreshMouseHook();
|
||||
if(IsWindow(owner_) && !IsIconic(GetAncestor(owner_,GA_ROOTOWNER)))
|
||||
{
|
||||
SetActiveWindow(owner_);
|
||||
@@ -179,10 +176,15 @@ public:
|
||||
static INT_PTR run(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
|
||||
{
|
||||
FilesModalDialog dialog(instance,resource,owner,procedure,argument);
|
||||
if(!dialog.window()) return -1;
|
||||
dialog.show();
|
||||
return dialog.runModal();
|
||||
}
|
||||
|
||||
INT_PTR runModal()
|
||||
{
|
||||
if(!window_) return -1;
|
||||
show();
|
||||
MSG message{};
|
||||
while(!dialog.finished_ && IsWindow(dialog.window()))
|
||||
while(!finished_ && IsWindow(window_))
|
||||
{
|
||||
const auto status=GetMessageW(&message,nullptr,0,0);
|
||||
if(status<=0)
|
||||
@@ -190,11 +192,11 @@ public:
|
||||
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
|
||||
break;
|
||||
}
|
||||
if(handleMessage(dialog.window(),message)) continue;
|
||||
if(handleMessage(window_,message)) continue;
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
return dialog.result_;
|
||||
return result_;
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -207,7 +209,23 @@ private:
|
||||
DLGPROC procedure_;
|
||||
LPARAM argument_;
|
||||
INT_PTR result_=IDCANCEL;
|
||||
bool entered_{},finished_{};
|
||||
bool entered_{},finished_{},watchOutsideClicks_;
|
||||
|
||||
static void refreshMouseHook()
|
||||
{
|
||||
const auto *active=activeFilesDialog?
|
||||
reinterpret_cast<const FilesModalDialog*>(GetPropW(activeFilesDialog,stateProperty_)):nullptr;
|
||||
if(active && active->watchOutsideClicks_)
|
||||
{
|
||||
if(!filesDialogMouseHook)
|
||||
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
|
||||
}
|
||||
else if(filesDialogMouseHook)
|
||||
{
|
||||
UnhookWindowsHookEx(filesDialogMouseHook);
|
||||
filesDialogMouseHook=nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void captureLayout()
|
||||
{
|
||||
@@ -260,7 +278,7 @@ private:
|
||||
void fitWidth(HWND window,const RECT &owner,bool initial=false)
|
||||
{
|
||||
RECT bounds{};
|
||||
if(!GetWindowRect(window,&bounds)) return;
|
||||
if(IsZoomed(window) || !GetWindowRect(window,&bounds)) return;
|
||||
const int width=std::clamp(static_cast<int>(owner.right-owner.left)-2*ownerMargin(),
|
||||
minimumWidth_,std::max(minimumWidth_,preferredWidth_));
|
||||
const int height=bounds.bottom-bounds.top;
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
constexpr wchar_t operationPipePrefix[]=L"\\\\.\\pipe\\KSwitcher.Files.Operation.";
|
||||
constexpr DWORD operationMessageLimit=256*1024;
|
||||
|
||||
void writeElevationMessage(HANDLE pipe,const Json &message)
|
||||
{
|
||||
const auto bytes=message.dump();
|
||||
requireFileOperation(bytes.size()<=operationMessageLimit,ERROR_BUFFER_OVERFLOW);
|
||||
DWORD written{};
|
||||
checkFileOperation(WriteFile(pipe,bytes.data(),static_cast<DWORD>(bytes.size()),&written,nullptr));
|
||||
requireFileOperation(written==bytes.size(),ERROR_WRITE_FAULT);
|
||||
}
|
||||
|
||||
Json readElevationMessage(HANDLE pipe)
|
||||
{
|
||||
std::array<char,operationMessageLimit> bytes;
|
||||
DWORD read{};
|
||||
checkFileOperation(ReadFile(pipe,bytes.data(),operationMessageLimit,&read,nullptr));
|
||||
return Json::parse(bytes.data(),bytes.data()+read);
|
||||
}
|
||||
|
||||
bool localElevationPath(const fs::path &path)
|
||||
{
|
||||
const auto root=path.root_name().native();
|
||||
return path.is_absolute() && root.size()==2 && root[1]==L':' &&
|
||||
path.native().find(L'\0')==std::wstring::npos && path.has_relative_path() &&
|
||||
GetDriveTypeW(path.root_path().c_str())!=DRIVE_REMOTE;
|
||||
}
|
||||
|
||||
bool allowedElevationRequest(const Json &request)
|
||||
{
|
||||
const auto action=request.at("action").get<std::string>();
|
||||
if(action!="copy" && action!="move" && action!="mkdir" && action!="mkdir-link" &&
|
||||
action!="remove" && action!="recycle" && action!="rmdir" && action!="stat" &&
|
||||
action!="canonical" && action!="list") return false;
|
||||
if(!localElevationPath(filePath(request.at("path")))) return false;
|
||||
if(action=="copy" || action=="move" || action=="mkdir-link")
|
||||
return localElevationPath(filePath(request.at("target")));
|
||||
return true;
|
||||
}
|
||||
|
||||
DWORD serveElevatedFileOperations(const std::wstring &parent,const std::wstring &pipeName)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(!IsUserAnAdmin() || !pipeName.starts_with(operationPipePrefix)) return ERROR_ACCESS_DENIED;
|
||||
DWORD expected{};
|
||||
for(const auto ch:parent)
|
||||
{
|
||||
if(ch<L'0' || ch>L'9' || expected>(MAXDWORD-(ch-L'0'))/10) return ERROR_INVALID_PARAMETER;
|
||||
expected=expected*10+(ch-L'0');
|
||||
}
|
||||
Handle pipe{CreateFileW(pipeName.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
|
||||
SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr)};
|
||||
checkFileOperation(pipe.value!=INVALID_HANDLE_VALUE);
|
||||
ULONG server{};
|
||||
checkFileOperation(GetNamedPipeServerProcessId(pipe.value,&server));
|
||||
requireFileOperation(server==expected,ERROR_ACCESS_DENIED);
|
||||
DWORD mode=PIPE_READMODE_MESSAGE;
|
||||
checkFileOperation(SetNamedPipeHandleState(pipe.value,&mode,nullptr,nullptr));
|
||||
FilesConnection listing;
|
||||
bool more=false;
|
||||
while(true)
|
||||
{
|
||||
const auto request=readElevationMessage(pipe.value);
|
||||
Json reply;
|
||||
try
|
||||
{
|
||||
const auto action=request.at("action").get<std::string>();
|
||||
if(action=="listNext" || action=="list")
|
||||
{
|
||||
requireFileOperation(action=="listNext"?more:allowedElevationRequest(request),ERROR_ACCESS_DENIED);
|
||||
more=false;
|
||||
reply=listing.call(request);
|
||||
more=reply.value("more",false);
|
||||
}
|
||||
else
|
||||
{
|
||||
requireFileOperation(allowedElevationRequest(request),ERROR_ACCESS_DENIED);
|
||||
FilesConnection local;
|
||||
ULONGLONG lastUpdate{};
|
||||
reply=local.call(request,[&](uint64_t done,uint64_t total)
|
||||
{
|
||||
const auto now=GetTickCount64();
|
||||
if(lastUpdate && now-lastUpdate<100 && done!=total) return true;
|
||||
lastUpdate=now;
|
||||
writeElevationMessage(pipe.value,{{"progress",{done,total}}});
|
||||
return readElevationMessage(pipe.value).at("continue").get<bool>();
|
||||
});
|
||||
}
|
||||
}
|
||||
catch(const std::system_error &error) {reply={{"error",error.code().value()}};}
|
||||
catch(const std::exception &) {reply={{"error",ERROR_INVALID_DATA}};}
|
||||
writeElevationMessage(pipe.value,reply);
|
||||
}
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
const auto code=error.code().value();
|
||||
return code==ERROR_BROKEN_PIPE || code==ERROR_NO_DATA?ERROR_SUCCESS:static_cast<DWORD>(code);
|
||||
}
|
||||
catch(const std::exception &) {return ERROR_INVALID_DATA;}
|
||||
}
|
||||
|
||||
class FileOperationElevation
|
||||
{
|
||||
HWND owner_;
|
||||
FileOperationUi *ui_;
|
||||
std::atomic_bool &canceled_;
|
||||
ElevatedHelper helper_;
|
||||
bool connected_{};
|
||||
|
||||
DWORD connect()
|
||||
{
|
||||
const auto deadline=GetTickCount64()+10000;
|
||||
while(!canceled_ && GetTickCount64()<deadline)
|
||||
{
|
||||
if(ConnectNamedPipe(helper_.pipe.value,nullptr) || GetLastError()==ERROR_PIPE_CONNECTED)
|
||||
{
|
||||
ULONG client{};
|
||||
if(!GetNamedPipeClientProcessId(helper_.pipe.value,&client)) return GetLastError();
|
||||
if(client!=GetProcessId(helper_.process.value)) return ERROR_ACCESS_DENIED;
|
||||
DWORD mode=PIPE_READMODE_MESSAGE;
|
||||
if(!SetNamedPipeHandleState(helper_.pipe.value,&mode,nullptr,nullptr)) return GetLastError();
|
||||
connected_=true;
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
if(WaitForSingleObject(helper_.process.value,20)==WAIT_OBJECT_0)
|
||||
{
|
||||
DWORD result{};
|
||||
if(!GetExitCodeProcess(helper_.process.value,&result)) return GetLastError();
|
||||
return result?result:ERROR_PIPE_NOT_CONNECTED;
|
||||
}
|
||||
}
|
||||
return canceled_?ERROR_CANCELLED:ERROR_TIMEOUT;
|
||||
}
|
||||
|
||||
DWORD requestConsent(const Json &request)
|
||||
{
|
||||
if(canceled_) return ERROR_CANCELLED;
|
||||
auto paths=filePath(request.at("path")).wstring();
|
||||
if(request.contains("target")) paths+=L"\r\n"+filePath(request.at("target")).wstring();
|
||||
const auto question=L"Windows denied access to the following path:\r\n"+paths+
|
||||
L"\r\n\r\nRetry with administrator rights for the current operation?";
|
||||
if(showFilesNotice(owner_,question.c_str(),L"Access denied",{.confirm=true})!=IDYES)
|
||||
return ERROR_CANCELLED;
|
||||
const auto error=launchElevatedHelper(owner_,operationPipePrefix,L"--elevated-file-operation",
|
||||
std::to_wstring(GetCurrentProcessId()),helper_);
|
||||
SetForegroundWindow(owner_);
|
||||
return error;
|
||||
}
|
||||
|
||||
Json send(const Json &request,const ks::lan::FileProgress &progress={})
|
||||
{
|
||||
if(canceled_) return {{"error",ERROR_CANCELLED}};
|
||||
writeElevationMessage(helper_.pipe.value,request);
|
||||
for(;;)
|
||||
{
|
||||
auto message=readElevationMessage(helper_.pipe.value);
|
||||
if(!message.contains("progress")) return message;
|
||||
const auto &value=message.at("progress");
|
||||
writeElevationMessage(helper_.pipe.value,{{"continue",!canceled_ &&
|
||||
(!progress || progress(value.at(0).get<uint64_t>(),value.at(1).get<uint64_t>()))}});
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
FileOperationElevation(HWND owner,std::atomic_bool &canceled,FileOperationUi *ui=nullptr):
|
||||
owner_(owner),ui_(ui),canceled_(canceled){}
|
||||
|
||||
Json retry(const Json &request,Json reply,const ks::lan::FileProgress &progress={})
|
||||
{
|
||||
const auto failure=reply.at("error").get<DWORD>();
|
||||
if((failure!=ERROR_ACCESS_DENIED && failure!=ERROR_PRIVILEGE_NOT_HELD && failure!=ERROR_ELEVATION_REQUIRED) ||
|
||||
IsUserAnAdmin() || !allowedElevationRequest(request))
|
||||
return reply;
|
||||
if(!connected_)
|
||||
{
|
||||
auto error=ui_?ui_->invoke([&]{return requestConsent(request);}):requestConsent(request);
|
||||
if(error==ERROR_SUCCESS) error=connect();
|
||||
if(error==ERROR_CANCELLED) canceled_=true;
|
||||
if(error!=ERROR_SUCCESS) return {{"error",error}};
|
||||
}
|
||||
return send(request,progress);
|
||||
}
|
||||
|
||||
Json call(FilesConnection &local,const Json &request,const ks::lan::FileProgress &progress={})
|
||||
{
|
||||
return retry(request,local.call(request,progress),progress);
|
||||
}
|
||||
|
||||
void list(FilesConnection &local,const fs::path &path,const FileVisitor &visit)
|
||||
{
|
||||
const auto request=fileRequest("list",path);
|
||||
auto reply=local.call(request);
|
||||
const bool elevated=reply.at("error")==ERROR_ACCESS_DENIED;
|
||||
if(elevated) reply=retry(request,std::move(reply));
|
||||
listFilePages(std::move(reply),path,visit,[&]{
|
||||
const Json next{{"action","listNext"}};
|
||||
return elevated?send(next):local.call(next);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -152,7 +152,7 @@ bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
|
||||
|
||||
void addFolderShortcut(const Panel &panel,int digit)
|
||||
{
|
||||
if(panel.directory.empty()) return;
|
||||
if(panel.directory.empty() || panel.ftp) return;
|
||||
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
|
||||
panel.peer?panel.peer->name:L""},digit,{}};
|
||||
if(editFolderShortcut(GetParent(panel.list),edit))
|
||||
@@ -187,8 +187,6 @@ struct FolderShortcutView
|
||||
std::vector<int> digits;
|
||||
int rowHeight{};
|
||||
Panel *panel{};
|
||||
bool all{};
|
||||
std::vector<std::pair<int,size_t>> entries;
|
||||
};
|
||||
|
||||
std::wstring shortcutLabel(const FolderShortcut &entry)
|
||||
@@ -201,7 +199,6 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
const auto list=GetDlgItem(dialog,shortcutList);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
view.digits.clear();
|
||||
view.entries.clear();
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
const auto dc=GetDC(dialog);
|
||||
const auto font=SelectObject(dc,mono);
|
||||
@@ -219,23 +216,14 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
GetTextExtentPoint32W(dc,label.data(),static_cast<int>(label.size()),&size);
|
||||
return static_cast<int>(size.cx);
|
||||
};
|
||||
int width=std::max(measure(L"Folder shortcuts"),measure(view.all?L"Del F4":view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
|
||||
int width=std::max(measure(L"Folder shortcuts"),measure(view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
|
||||
const int textInset=dialogRowTextInset(cellWidth);
|
||||
const auto add=[&](const std::wstring &label)
|
||||
{
|
||||
width=std::max(width,measure(label)+2*textInset);
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
};
|
||||
if(view.all)
|
||||
{
|
||||
for(int digit=0;digit<static_cast<int>(folderShortcuts.size());++digit)
|
||||
for(size_t index=0;index<folderShortcuts[digit].size();++index)
|
||||
{
|
||||
view.entries.emplace_back(digit,index);
|
||||
add(std::to_wstring(digit)+L" "+shortcutLabel(folderShortcuts[digit][index]));
|
||||
}
|
||||
}
|
||||
else if(view.digit<0)
|
||||
if(view.digit<0)
|
||||
{
|
||||
for(int digit=0;digit<10;++digit)
|
||||
if(!folderShortcuts[digit].empty())
|
||||
@@ -255,7 +243,8 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
GetWindowRect(owner,&parent);
|
||||
const auto windowWidth=std::max(px(260),static_cast<int>(parent.right-parent.left));
|
||||
const auto windowHeight=std::max(px(140),static_cast<int>(parent.bottom-parent.top));
|
||||
width=std::min(width,std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
|
||||
width=std::min(width+scrollBarWidth(list),
|
||||
std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
|
||||
const auto maxRows=std::max(1,(std::min(windowHeight,static_cast<int>(work.bottom-work.top))-2*listTop)/view.rowHeight);
|
||||
const auto count=static_cast<int>(SendMessageW(list,LB_GETCOUNT,0,0));
|
||||
const int rows=std::min(count,maxRows);
|
||||
@@ -267,7 +256,8 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
const int y=std::clamp(static_cast<int>((parent.top+parent.bottom-h)/2),
|
||||
static_cast<int>(work.top),std::max(static_cast<int>(work.top),static_cast<int>(work.bottom)-h));
|
||||
SetWindowPos(dialog,nullptr,x,y,w,h,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SetWindowPos(list,nullptr,inset,listTop,width,listHeight,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SetWindowPos(list,nullptr,inset,listTop,std::max(1,width-scrollBarWidth(list)),listHeight,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SendMessageW(list,LB_SETCURSEL,std::clamp(selection,0,std::max(0,count-1)),0);
|
||||
InvalidateRect(dialog,nullptr,TRUE);
|
||||
FilesModalDialog::refreshLayout(dialog);
|
||||
@@ -290,7 +280,7 @@ LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags,
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return scrollList(list,message,key,flags);
|
||||
return DefSubclassProc(list,message,key,flags);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
@@ -303,6 +293,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
layoutQuickFolders(dialog,view,0);
|
||||
const auto list=GetDlgItem(dialog,shortcutList);
|
||||
SetWindowSubclass(list,quickFolderKeys,1,0);
|
||||
installScrollBar(list,dialog);
|
||||
SetFocus(list);
|
||||
return FALSE;
|
||||
}
|
||||
@@ -322,7 +313,8 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
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->all?L"Del F4":view->digit<0?L"Enter Esc":quickFolderHints);
|
||||
view->digit<0?L"Enter Esc":quickFolderHints);
|
||||
paintScrollPosition(dialog,dc,GetDlgItem(dialog,shortcutList),colors[Dialog]);
|
||||
EndPaint(dialog,&ps);
|
||||
return TRUE;
|
||||
}
|
||||
@@ -349,7 +341,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(action!=quickRemove && action!=quickEdit && action!=quickInsert && action!=quickMoveUp &&
|
||||
action!=quickMoveDown && action!=IDOK && !(action==shortcutList && HIWORD(wp)==LBN_DBLCLK)) return FALSE;
|
||||
const auto row=SendDlgItemMessageW(dialog,shortcutList,LB_GETCURSEL,0,0);
|
||||
if(!view->all && view->digit<0)
|
||||
if(view->digit<0)
|
||||
{
|
||||
if((action==IDOK || action==shortcutList) && row>=0 && static_cast<size_t>(row)<view->digits.size())
|
||||
{
|
||||
@@ -358,16 +350,8 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
int digit=view->digit;
|
||||
size_t index=static_cast<size_t>(row);
|
||||
if(view->all)
|
||||
{
|
||||
if(index>=view->entries.size() || action==quickInsert ||
|
||||
action==quickMoveUp || action==quickMoveDown) return TRUE;
|
||||
const auto &entry=view->entries[index];
|
||||
digit=entry.first;
|
||||
index=entry.second;
|
||||
}
|
||||
const auto digit=view->digit;
|
||||
const auto index=static_cast<size_t>(row);
|
||||
const auto &group=folderShortcuts[digit];
|
||||
if(action==quickInsert)
|
||||
{
|
||||
@@ -414,7 +398,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
folderShortcuts=std::move(updated);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
if(view->all?view->entries.size()==1:folderShortcuts[digit].empty()) FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
if(folderShortcuts[digit].empty()) FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
else layoutQuickFolders(dialog,*view,static_cast<int>(row));
|
||||
return TRUE;
|
||||
}
|
||||
@@ -424,7 +408,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
|
||||
|
||||
void showFolderShortcuts(Panel &panel,int digit,bool all)
|
||||
void showFolderShortcuts(Panel &panel,int digit)
|
||||
{
|
||||
if(digit>=0)
|
||||
{
|
||||
@@ -447,7 +431,6 @@ void showFolderShortcuts(Panel &panel,int digit,bool all)
|
||||
}
|
||||
FolderShortcutView view{digit};
|
||||
view.panel=&panel;
|
||||
view.all=all;
|
||||
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list),
|
||||
quickFolderDialog,reinterpret_cast<LPARAM>(&view));
|
||||
SetFocus(panel.list);
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
struct FtpProfile
|
||||
{
|
||||
std::wstring name, host, user;
|
||||
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
|
||||
ks::Bytes secret;
|
||||
bool legacyNames{};
|
||||
};
|
||||
|
||||
std::vector<FtpProfile> ftpProfiles;
|
||||
bool ftpProfilesLoaded{};
|
||||
constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles";
|
||||
constexpr DWORD ftpProfilesMaxBytes=1024*1024;
|
||||
const fs::path ftpRoot=L"\\";
|
||||
|
||||
std::wstring ftpPath(const fs::path &path)
|
||||
{
|
||||
auto value=path.native();
|
||||
std::replace(value.begin(),value.end(),L'\\',L'/');
|
||||
return value;
|
||||
}
|
||||
|
||||
bool saveFtpProfiles(const std::vector<FtpProfile> &profiles)
|
||||
{
|
||||
auto rows=Json::array();
|
||||
for(const auto &profile:profiles)
|
||||
rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
|
||||
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
|
||||
{"legacyNames",profile.legacyNames}});
|
||||
const auto data=rows.dump();
|
||||
return data.size()<=ftpProfilesMaxBytes &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
bool loadFtpProfiles()
|
||||
{
|
||||
if(ftpProfilesLoaded) return true;
|
||||
DWORD bytes{};
|
||||
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,
|
||||
RRF_RT_REG_BINARY,nullptr,nullptr,&bytes);
|
||||
if(query==ERROR_FILE_NOT_FOUND)
|
||||
{
|
||||
ftpProfilesLoaded=true;
|
||||
return true;
|
||||
}
|
||||
if(query!=ERROR_SUCCESS || !bytes || bytes>ftpProfilesMaxBytes) return false;
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,RRF_RT_REG_BINARY,
|
||||
nullptr,data.data(),&bytes)!=ERROR_SUCCESS) return false;
|
||||
try
|
||||
{
|
||||
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
|
||||
if(!rows.is_array()) return false;
|
||||
std::vector<FtpProfile> profiles;
|
||||
for(const auto &row:rows)
|
||||
{
|
||||
const auto port=row.at("port").get<unsigned>();
|
||||
if(!port || port>65535) return false;
|
||||
FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
|
||||
ks::wide(row.at("user")),static_cast<INTERNET_PORT>(port),row.at("secret").get<ks::Bytes>(),
|
||||
row.value("legacyNames",false)};
|
||||
if(profile.name.empty() || profile.host.empty()) return false;
|
||||
profiles.push_back(std::move(profile));
|
||||
}
|
||||
ftpProfiles=std::move(profiles);
|
||||
ftpProfilesLoaded=true;
|
||||
return true;
|
||||
}
|
||||
catch(const std::exception &) {return false;}
|
||||
}
|
||||
|
||||
std::wstring ftpPassword(const FtpProfile &profile)
|
||||
{
|
||||
if(profile.secret.empty()) return {};
|
||||
auto bytes=ks::unprotect(profile.secret);
|
||||
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid FTP password");
|
||||
std::wstring password(bytes.size()/sizeof(wchar_t),L'\0');
|
||||
std::copy(bytes.begin(),bytes.end(),reinterpret_cast<unsigned char*>(password.data()));
|
||||
SecureZeroMemory(bytes.data(),bytes.size());
|
||||
return password;
|
||||
}
|
||||
|
||||
struct FtpHandle
|
||||
{
|
||||
HINTERNET value{};
|
||||
~FtpHandle() {if(value) InternetCloseHandle(value);}
|
||||
explicit FtpHandle(HINTERNET handle=nullptr):value(handle) {}
|
||||
FtpHandle(const FtpHandle &)=delete;
|
||||
FtpHandle &operator=(const FtpHandle &)=delete;
|
||||
};
|
||||
|
||||
void requireFileOperation(bool success,DWORD error)
|
||||
{
|
||||
if(!success) throw std::system_error(error,std::system_category());
|
||||
}
|
||||
|
||||
void checkFileOperation(bool success)
|
||||
{
|
||||
if(!success) requireFileOperation(false,GetLastError());
|
||||
}
|
||||
|
||||
class FtpSession
|
||||
{
|
||||
FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)};
|
||||
FtpHandle connection_;
|
||||
fs::path current_;
|
||||
UINT nameCodePage_;
|
||||
|
||||
public:
|
||||
explicit FtpSession(const FtpProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8)
|
||||
{
|
||||
checkFileOperation(internet_.value!=nullptr);
|
||||
DWORD timeout=10000, retries=1;
|
||||
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_TIMEOUT,&timeout,sizeof(timeout));
|
||||
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_RETRIES,&retries,sizeof(retries));
|
||||
InternetSetOptionW(internet_.value,INTERNET_OPTION_RECEIVE_TIMEOUT,&timeout,sizeof(timeout));
|
||||
InternetSetOptionW(internet_.value,INTERNET_OPTION_SEND_TIMEOUT,&timeout,sizeof(timeout));
|
||||
auto password=ftpPassword(profile);
|
||||
const auto user=profile.user.empty()?(password.empty()?nullptr:L"anonymous"):profile.user.c_str();
|
||||
connection_.value=InternetConnectW(internet_.value,profile.host.c_str(),profile.port,
|
||||
user,password.empty()?nullptr:password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
|
||||
const auto error=GetLastError();
|
||||
SecureZeroMemory(password.data(),password.size()*sizeof(wchar_t));
|
||||
requireFileOperation(connection_.value!=nullptr,error);
|
||||
if(!profile.legacyNames)
|
||||
FtpCommandA(handle(),FALSE,0,"OPTS UTF8 ON",0,nullptr);
|
||||
}
|
||||
|
||||
HINTERNET handle() const {return connection_.value;}
|
||||
|
||||
// WinINet's A entry points transfer FTP pathname bytes without a Unicode conversion.
|
||||
std::wstring decodeName(std::string_view bytes) const
|
||||
{
|
||||
if(bytes.empty()) return {};
|
||||
const auto length=static_cast<int>(bytes.size());
|
||||
const auto count=MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,nullptr,0);
|
||||
if(!count)
|
||||
throw std::runtime_error("The FTP server returned a name in another encoding. Check the FTP connection's file name encoding.");
|
||||
std::wstring name(count,L'\0');
|
||||
checkFileOperation(MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,name.data(),count)>0);
|
||||
return name;
|
||||
}
|
||||
|
||||
std::string encodeName(const fs::path &path) const
|
||||
{
|
||||
const auto name=ftpPath(path);
|
||||
if(name.empty()) return {};
|
||||
const auto length=static_cast<int>(name.size());
|
||||
BOOL substituted=FALSE;
|
||||
const auto legacy=nameCodePage_!=CP_UTF8;
|
||||
const auto flags=legacy?WC_NO_BEST_FIT_CHARS:WC_ERR_INVALID_CHARS;
|
||||
const auto replacement=legacy?&substituted:nullptr;
|
||||
const auto count=WideCharToMultiByte(nameCodePage_,flags,name.data(),length,nullptr,0,nullptr,replacement);
|
||||
requireFileOperation(count>0 && !substituted,ERROR_NO_UNICODE_TRANSLATION);
|
||||
std::string bytes(count,'\0');
|
||||
checkFileOperation(WideCharToMultiByte(nameCodePage_,flags,name.data(),length,bytes.data(),count,nullptr,replacement)>0);
|
||||
requireFileOperation(!substituted,ERROR_NO_UNICODE_TRANSLATION);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const fs::path &initialDirectory()
|
||||
{
|
||||
std::string bytes(32768,'\0');
|
||||
DWORD length=static_cast<DWORD>(bytes.size());
|
||||
checkFileOperation(FtpGetCurrentDirectoryA(handle(),bytes.data(),&length));
|
||||
auto initial=decodeName(bytes.c_str());
|
||||
if(initial.empty() || initial.front()!=L'/' || initial.find_first_of(L"\\\r\n")!=initial.npos)
|
||||
throw std::system_error(ERROR_BAD_PATHNAME,std::system_category());
|
||||
const auto first=initial.find_first_not_of(L'/');
|
||||
if(first==initial.npos) current_=ftpRoot;
|
||||
else
|
||||
{
|
||||
initial.erase(1,first-1);
|
||||
std::replace(initial.begin(),initial.end(),L'/',L'\\');
|
||||
current_=fs::path(initial).lexically_normal();
|
||||
if(current_.has_relative_path() && !current_.has_filename()) current_=current_.parent_path();
|
||||
}
|
||||
return current_;
|
||||
}
|
||||
|
||||
void setDirectory(const fs::path &path)
|
||||
{
|
||||
if(current_==path) return;
|
||||
checkFileOperation(FtpSetCurrentDirectoryA(handle(),encodeName(path).c_str()));
|
||||
current_=path;
|
||||
}
|
||||
};
|
||||
|
||||
DWORD listFtpDirectory(FtpSession &session,const fs::path &directory,const FileVisitor &visit,
|
||||
std::stop_token stop={})
|
||||
{
|
||||
if(stop.stop_requested()) return ERROR_CANCELLED;
|
||||
session.setDirectory(directory);
|
||||
if(stop.stop_requested()) return ERROR_CANCELLED;
|
||||
WIN32_FIND_DATAA entry{};
|
||||
const FtpHandle search{FtpFindFirstFileA(session.handle(),nullptr,&entry,
|
||||
INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE,0)};
|
||||
if(!search.value) return GetLastError();
|
||||
do
|
||||
{
|
||||
const auto name=session.decodeName(entry.cFileName);
|
||||
if(name.empty() || name==L"." || name==L".." || name.find_first_of(L"/\\:\r\n")!=name.npos)
|
||||
continue;
|
||||
ULARGE_INTEGER modified{}, size{};
|
||||
FILETIME utc{};
|
||||
if(LocalFileTimeToFileTime(&entry.ftLastWriteTime,&utc))
|
||||
{
|
||||
modified.HighPart=utc.dwHighDateTime;
|
||||
modified.LowPart=utc.dwLowDateTime;
|
||||
}
|
||||
size.HighPart=entry.nFileSizeHigh;
|
||||
size.LowPart=entry.nFileSizeLow;
|
||||
if(!visit(directory/name,{entry.dwFileAttributes,size.QuadPart,modified.QuadPart}))
|
||||
return ERROR_CANCELLED;
|
||||
} while(!stop.stop_requested() && InternetFindNextFileA(search.value,&entry));
|
||||
return stop.stop_requested()?ERROR_CANCELLED:GetLastError();
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr)
|
||||
{
|
||||
FileEntries entries;
|
||||
const auto error=listFtpDirectory(session,directory,[&](const fs::path &path,const FileInfo &info)
|
||||
{
|
||||
if(canceled && *canceled) return false;
|
||||
entries.emplace_back(path,info);
|
||||
return true;
|
||||
});
|
||||
requireFileOperation(error==ERROR_NO_MORE_FILES,error);
|
||||
return entries;
|
||||
}
|
||||
|
||||
std::optional<FileInfo> ftpEntry(const FileEntries &entries,const fs::path &path)
|
||||
{
|
||||
const auto entry=std::find_if(entries.begin(),entries.end(),
|
||||
[&](const auto &item){return item.first==path;});
|
||||
return entry==entries.end()?std::nullopt:std::optional<FileInfo>(entry->second);
|
||||
}
|
||||
|
||||
void renameFtpEntry(FtpSession &ftp,const fs::path &source,const fs::path &target)
|
||||
{
|
||||
ftp.setDirectory(source.parent_path());
|
||||
const auto oldName=ftp.encodeName(source.filename());
|
||||
const auto newName=ftp.encodeName(target.filename());
|
||||
checkFileOperation(FtpRenameFileA(ftp.handle(),oldName.c_str(),newName.c_str()));
|
||||
}
|
||||
|
||||
struct CopyHost
|
||||
{
|
||||
std::optional<FilesConnection> files;
|
||||
std::optional<FtpSession> ftp;
|
||||
FileOperationElevation *elevation{};
|
||||
fs::path listedDirectory;
|
||||
FileEntries listedEntries;
|
||||
|
||||
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile,FileOperationElevation *admin=nullptr)
|
||||
{
|
||||
if(profile) ftp.emplace(*profile);
|
||||
else files.emplace(peer);
|
||||
if(!peer && !profile) elevation=admin;
|
||||
}
|
||||
|
||||
Json request(const Json &message,const ks::lan::FileProgress &progress={})
|
||||
{
|
||||
return elevation?elevation->call(*files,message,progress):files->call(message,progress);
|
||||
}
|
||||
|
||||
const FileEntries &ftpListing(const fs::path &path,const std::atomic_bool &canceled)
|
||||
{
|
||||
if(path!=listedDirectory)
|
||||
{
|
||||
listedEntries=ftpChildren(*ftp,path,&canceled);
|
||||
listedDirectory=path;
|
||||
}
|
||||
return listedEntries;
|
||||
}
|
||||
|
||||
std::optional<FileInfo> stat(const fs::path &path,const std::atomic_bool &canceled)
|
||||
{
|
||||
return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path)));
|
||||
}
|
||||
|
||||
FileEntries children(const fs::path &path,const std::atomic_bool &canceled)
|
||||
{
|
||||
if(ftp) return ftpListing(path,canceled);
|
||||
if(!elevation) return childrenOf(*files,path);
|
||||
FileEntries entries;
|
||||
elevation->list(*files,path,[&](const fs::path &child,const FileInfo &info)
|
||||
{
|
||||
if(canceled) return false;
|
||||
entries.emplace_back(child,info);
|
||||
return true;
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
void makeDirectory(const fs::path &path)
|
||||
{
|
||||
if(!ftp)
|
||||
{
|
||||
checkFileReply(request(fileRequest("mkdir",path)));
|
||||
return;
|
||||
}
|
||||
ftp->setDirectory(path.parent_path());
|
||||
checkFileOperation(FtpCreateDirectoryA(ftp->handle(),ftp->encodeName(path.filename()).c_str()));
|
||||
listedDirectory.clear();
|
||||
}
|
||||
|
||||
void remove(const fs::path &path,bool permanent,DWORD attributes,bool readOnly)
|
||||
{
|
||||
if(ftp)
|
||||
{
|
||||
ftp->setDirectory(path.parent_path());
|
||||
const auto name=ftp->encodeName(path.filename());
|
||||
checkFileOperation(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)?
|
||||
FtpRemoveDirectoryA(ftp->handle(),name.c_str()):FtpDeleteFileA(ftp->handle(),name.c_str()));
|
||||
return;
|
||||
}
|
||||
auto message=fileRequest(permanent?"remove":"recycle",path);
|
||||
message["readOnly"]=readOnly;
|
||||
checkFileReply(request(message));
|
||||
}
|
||||
};
|
||||
|
||||
constexpr DWORD ftpCopyFlags=INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE;
|
||||
|
||||
void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &source,const fs::path &target,
|
||||
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress)
|
||||
{
|
||||
ftp.setDirectory(source.parent_path());
|
||||
const FtpHandle input{FtpOpenFileA(ftp.handle(),ftp.encodeName(source.filename()).c_str(),GENERIC_READ,ftpCopyFlags,0)};
|
||||
checkFileOperation(input.value!=nullptr);
|
||||
auto upload=fileRequest("openWrite",target);
|
||||
upload["transfer"]=ks::lan::randomHex(32);
|
||||
upload["size"]=info.size;
|
||||
try
|
||||
{
|
||||
const auto output=local.call(upload);
|
||||
checkFileReply(output);
|
||||
requireFileOperation(output.value("offset",uint64_t{1})==0,ERROR_FILE_INVALID);
|
||||
uint64_t done=0;
|
||||
ks::Bytes bytes(ks::lan::FileChunk);
|
||||
while(!progress || progress(done,info.size))
|
||||
{
|
||||
DWORD read{};
|
||||
checkFileOperation(InternetReadFile(input.value,bytes.data(),static_cast<DWORD>(bytes.size()),&read));
|
||||
if(!read)
|
||||
{
|
||||
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
|
||||
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
|
||||
checkFileReply(local.call({{"action","commit"},{"replace",replace},{"modified",info.modified}}));
|
||||
return;
|
||||
}
|
||||
requireFileOperation(read<=info.size-done,ERROR_FILE_INVALID);
|
||||
checkFileReply(local.call({{"action","write"},
|
||||
{"data",Json::binary(ks::Bytes(bytes.begin(),bytes.begin()+read))}}));
|
||||
done+=read;
|
||||
}
|
||||
requireFileOperation(false,ERROR_CANCELLED);
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
local.call({{"action","abort"}});
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &source,const fs::path &target,
|
||||
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress,
|
||||
const ks::files::RemoteTextRevision *expected=nullptr)
|
||||
{
|
||||
const auto directory=target.parent_path();
|
||||
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
|
||||
auto open=fileRequest("openRead",source);
|
||||
open["size"]=info.size;
|
||||
open["modified"]=info.modified;
|
||||
checkFileReply(local.call(open));
|
||||
ftp.setDirectory(directory);
|
||||
const auto stage=ftp.encodeName(temporary.filename());
|
||||
bool staged=false;
|
||||
try
|
||||
{
|
||||
uint64_t done=0;
|
||||
{
|
||||
FtpHandle output{FtpOpenFileA(ftp.handle(),stage.c_str(),GENERIC_WRITE,ftpCopyFlags,0)};
|
||||
checkFileOperation(output.value!=nullptr);
|
||||
staged=true;
|
||||
for(;;)
|
||||
{
|
||||
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
|
||||
const auto packet=local.call({{"action","read"}});
|
||||
checkFileReply(packet);
|
||||
const auto &bytes=packet.at("data").get_binary();
|
||||
if(bytes.empty()) break;
|
||||
requireFileOperation(bytes.size()<=info.size-done,ERROR_FILE_INVALID);
|
||||
for(DWORD offset=0;offset<bytes.size();)
|
||||
{
|
||||
DWORD written{};
|
||||
checkFileOperation(InternetWriteFile(output.value,bytes.data()+offset,
|
||||
static_cast<DWORD>(bytes.size()-offset),&written));
|
||||
requireFileOperation(written!=0,ERROR_WRITE_FAULT);
|
||||
offset+=written;
|
||||
}
|
||||
done+=bytes.size();
|
||||
}
|
||||
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
|
||||
checkFileOperation(InternetCloseHandle(output.value));
|
||||
output.value=nullptr;
|
||||
}
|
||||
checkFileReply(local.call({{"action","closeRead"}}));
|
||||
const auto entries=ftpChildren(ftp,directory);
|
||||
const auto uploaded=ftpEntry(entries,temporary);
|
||||
requireFileOperation(uploaded && uploaded->size==done,ERROR_WRITE_FAULT);
|
||||
const auto existing=ftpEntry(entries,target);
|
||||
if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified))
|
||||
throw std::runtime_error("The FTP file changed since it was opened. Your edits are still in the editor.");
|
||||
if(existing)
|
||||
requireFileOperation(replace && !(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
|
||||
ERROR_ALREADY_EXISTS);
|
||||
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
|
||||
renameFtpEntry(ftp,temporary,target);
|
||||
return *uploaded;
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
if(staged) FtpDeleteFileA(ftp.handle(),stage.c_str());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
namespace ftpDialog
|
||||
{
|
||||
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
|
||||
|
||||
std::wstring trim(std::wstring value)
|
||||
{
|
||||
const auto first=value.find_first_not_of(L" \t\r\n");
|
||||
if(first==value.npos) return {};
|
||||
return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1);
|
||||
}
|
||||
|
||||
struct Edit
|
||||
{
|
||||
FtpProfile profile;
|
||||
std::optional<size_t> index;
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" FTP connection ",false,{footer}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
auto &profile=reinterpret_cast<Edit*>(lp)->profile;
|
||||
prepareCopyDialog(dialog);
|
||||
layoutDialogContent(dialog,381);
|
||||
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL})
|
||||
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
for(const auto id:{name,host,user,password})
|
||||
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
|
||||
SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0);
|
||||
SetDlgItemTextW(dialog,name,profile.name.c_str());
|
||||
SetDlgItemTextW(dialog,host,profile.host.c_str());
|
||||
SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str());
|
||||
SetDlgItemTextW(dialog,user,profile.user.c_str());
|
||||
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
|
||||
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
|
||||
try
|
||||
{
|
||||
auto secret=ftpPassword(profile);
|
||||
SetDlgItemTextW(dialog,password,secret.c_str());
|
||||
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetWindowTextW(GetDlgItem(dialog,389),L"&Password (re-enter to replace saved password)");
|
||||
}
|
||||
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
|
||||
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 &edit=*reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
const auto invalid=[&](int field,const wchar_t *message)
|
||||
{
|
||||
showFilesNotice(dialog,message,L"FTP connection");
|
||||
SetFocus(GetDlgItem(dialog,field));
|
||||
return TRUE;
|
||||
};
|
||||
FtpProfile profile;
|
||||
profile.legacyNames=IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
|
||||
profile.name=trim(shortcutField(dialog,name));
|
||||
if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos)
|
||||
return invalid(name,L"Enter a name for this connection.");
|
||||
for(size_t i=0;i<ftpProfiles.size();++i)
|
||||
if(edit.index!=i && CompareStringOrdinal(ftpProfiles[i].name.c_str(),-1,profile.name.c_str(),-1,TRUE)==CSTR_EQUAL)
|
||||
return invalid(name,L"A connection with this name already exists.");
|
||||
profile.host=trim(shortcutField(dialog,host));
|
||||
if(profile.host.empty() || profile.host.find_first_of(L" /\\@\t\r\n")!=profile.host.npos)
|
||||
return invalid(host,L"Enter the server host name or IP address.");
|
||||
const auto value=shortcutField(dialog,port);
|
||||
const auto number=value.empty() || value.find_first_not_of(L"0123456789")!=value.npos?0:std::stoul(value);
|
||||
if(!number || number>65535) return invalid(port,L"Enter a port from 1 to 65535.");
|
||||
profile.port=static_cast<INTERNET_PORT>(number);
|
||||
profile.user=shortcutField(dialog,user);
|
||||
if(profile.user.find_first_of(L"\r\n")!=profile.user.npos)
|
||||
return invalid(user,L"Enter the user name on one line.");
|
||||
try
|
||||
{
|
||||
auto plain=shortcutField(dialog,password);
|
||||
if(!plain.empty())
|
||||
{
|
||||
const auto start=reinterpret_cast<const unsigned char*>(plain.data());
|
||||
ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t));
|
||||
SecureZeroMemory(plain.data(),plain.size()*sizeof(wchar_t));
|
||||
profile.secret=ks::protect(bytes);
|
||||
SecureZeroMemory(bytes.data(),bytes.size());
|
||||
}
|
||||
auto updated=ftpProfiles;
|
||||
if(edit.index) updated[*edit.index]=std::move(profile);
|
||||
else updated.push_back(std::move(profile));
|
||||
if(saveFtpProfiles(updated))
|
||||
{
|
||||
ftpProfiles=std::move(updated);
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
showFilesNotice(dialog,L"Could not save the FTP connection.",L"FTP connection");
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
void editFtpProfile(Panel &panel,bool create)
|
||||
{
|
||||
ftpDialog::Edit edit;
|
||||
if(!create)
|
||||
{
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(row<0 || static_cast<size_t>(row)>=ftpProfiles.size()) return;
|
||||
edit.index=static_cast<size_t>(row);
|
||||
edit.profile=ftpProfiles[*edit.index];
|
||||
}
|
||||
const auto owner=GetParent(panel.list);
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(112),owner,
|
||||
ftpDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
|
||||
for(auto &other:panels)
|
||||
{
|
||||
if(!ftpProfileList(other) || other.scan.valid()) continue;
|
||||
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(ftpProfiles.size()-1)):fs::path{};
|
||||
showFtpProfiles(other,selection);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <algorithm>
|
||||
#include <string_view>
|
||||
#include <windowsx.h>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline COLORREF hoverSurface(COLORREF surface)
|
||||
{
|
||||
return RGB(3*GetRValue(surface)/4,3*GetGValue(surface)/4,3*GetBValue(surface)/4);
|
||||
}
|
||||
|
||||
class InlineListAction
|
||||
{
|
||||
std::wstring_view label;
|
||||
LRESULT pressedRow=LB_ERR;
|
||||
|
||||
public:
|
||||
explicit InlineListAction(std::wstring_view text):label(text){}
|
||||
|
||||
RECT bounds(RECT row,int cellWidth) const
|
||||
{
|
||||
row.right-=2*cellWidth;
|
||||
row.left=std::max(row.left,row.right-static_cast<LONG>(label.size()*cellWidth));
|
||||
return row;
|
||||
}
|
||||
|
||||
bool hit(HWND list,LRESULT row,LPARAM point,int cellWidth) const
|
||||
{
|
||||
RECT item{};
|
||||
if(SendMessageW(list,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&item))==LB_ERR) return false;
|
||||
const auto action=bounds(item,cellWidth);
|
||||
return PtInRect(&action,{GET_X_LPARAM(point),GET_Y_LPARAM(point)});
|
||||
}
|
||||
|
||||
void press(HWND list,LRESULT row)
|
||||
{
|
||||
pressedRow=row;
|
||||
SetCapture(list);
|
||||
}
|
||||
|
||||
bool pressed() const { return pressedRow!=LB_ERR; }
|
||||
void cancel() { pressedRow=LB_ERR; }
|
||||
|
||||
bool release(HWND list,LRESULT row,bool overAction)
|
||||
{
|
||||
const bool activate=pressedRow==row && overAction;
|
||||
cancel();
|
||||
if(GetCapture()==list) ReleaseCapture();
|
||||
return activate;
|
||||
}
|
||||
|
||||
void paint(HDC dc,const RECT &action,int textInset,COLORREF ink,COLORREF surface,bool highlighted) const
|
||||
{
|
||||
SetTextColor(dc,ink);
|
||||
SetBkColor(dc,highlighted?hoverSurface(surface):surface);
|
||||
ExtTextOutW(dc,action.left,action.top+textInset,ETO_OPAQUE|ETO_CLIPPED,&action,
|
||||
label.data(),static_cast<UINT>(label.size()),nullptr);
|
||||
TEXTMETRICW metrics{};
|
||||
GetTextMetricsW(dc,&metrics);
|
||||
const LONG underline=std::min(action.bottom-1,action.top+textInset+metrics.tmAscent+1);
|
||||
const RECT line{action.left,underline,action.right,underline+1};
|
||||
SetDCBrushColor(dc,ink);
|
||||
FillRect(dc,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
bool isSharingError(int error)
|
||||
{
|
||||
return error==ERROR_SHARING_VIOLATION || error==ERROR_LOCK_VIOLATION;
|
||||
}
|
||||
|
||||
constexpr DWORD lockProbeShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
|
||||
constexpr DWORD lockProbeFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
|
||||
|
||||
DWORD probeDeleteAccess(const fs::path &path)
|
||||
{
|
||||
Handle probe{CreateFileW(path.c_str(),DELETE,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)};
|
||||
return probe.value==INVALID_HANDLE_VALUE?GetLastError():ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
struct LockProcess
|
||||
{
|
||||
DWORD pid;
|
||||
FILETIME started{};
|
||||
std::wstring name;
|
||||
};
|
||||
struct LockScan
|
||||
{
|
||||
std::vector<LockProcess> processes;
|
||||
bool incomplete{};
|
||||
};
|
||||
|
||||
LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token stop)
|
||||
{
|
||||
LockScan result;
|
||||
const auto query=reinterpret_cast<decltype(&NtQueryInformationFile)>(
|
||||
GetProcAddress(GetModuleHandleW(L"ntdll.dll"),"NtQueryInformationFile"));
|
||||
if(!query) { result.incomplete=true; return result; }
|
||||
std::set<DWORD> pids;
|
||||
std::vector<ULONG_PTR> buffer(128);
|
||||
const auto inspect=[&](const fs::path &path) {
|
||||
const auto error=probeDeleteAccess(path);
|
||||
if(error==ERROR_SUCCESS) return;
|
||||
if(!isSharingError(error))
|
||||
{
|
||||
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND) result.incomplete=true;
|
||||
return;
|
||||
}
|
||||
Handle file{CreateFileW(path.c_str(),0,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)};
|
||||
if(file.value==INVALID_HANDLE_VALUE) {result.incomplete=true;return;}
|
||||
IO_STATUS_BLOCK status{};
|
||||
// FileProcessIdsUsingFileInformation (47) returns an ULONG count followed by aligned ULONG_PTR PIDs.
|
||||
auto code=query(file.value,&status,buffer.data(),static_cast<ULONG>(buffer.size()*sizeof(ULONG_PTR)),
|
||||
static_cast<FILE_INFORMATION_CLASS>(47));
|
||||
while((static_cast<ULONG>(code)==0xC0000023 || static_cast<ULONG>(code)==0x80000005 ||
|
||||
static_cast<ULONG>(code)==0xC0000004) && buffer.size()<8192)
|
||||
{
|
||||
buffer.resize(buffer.size()*2);
|
||||
code=query(file.value,&status,buffer.data(),static_cast<ULONG>(buffer.size()*sizeof(ULONG_PTR)),
|
||||
static_cast<FILE_INFORMATION_CLASS>(47));
|
||||
}
|
||||
if(code<0 || status.Information<sizeof(ULONG_PTR)) {result.incomplete=true;return;}
|
||||
ULONG count{};
|
||||
memcpy(&count,buffer.data(),sizeof(count));
|
||||
if(count>buffer.size()-1 || size_t(count)+1>status.Information/sizeof(ULONG_PTR))
|
||||
{
|
||||
result.incomplete=true;
|
||||
return;
|
||||
}
|
||||
for(ULONG i=0;i<count;++i)
|
||||
if(const auto pid=buffer[i+1];pid && pid<=MAXDWORD && pid!=GetCurrentProcessId())
|
||||
pids.insert(static_cast<DWORD>(pid));
|
||||
};
|
||||
auto remaining=8192u;
|
||||
const auto deadline=GetTickCount64()+4000;
|
||||
for(const auto &path:paths)
|
||||
{
|
||||
if(stop.stop_requested()) return {};
|
||||
inspect(path);
|
||||
const auto attributes=GetFileAttributesW(path.c_str());
|
||||
if(attributes==INVALID_FILE_ATTRIBUTES || !(attributes&FILE_ATTRIBUTE_DIRECTORY) ||
|
||||
(attributes&FILE_ATTRIBUTE_REPARSE_POINT)) continue;
|
||||
std::error_code error;
|
||||
fs::recursive_directory_iterator it(path,error),end;
|
||||
while(!error && it!=end)
|
||||
{
|
||||
if(stop.stop_requested()) return {};
|
||||
if(!remaining || GetTickCount64()>=deadline) {result.incomplete=true;break;}
|
||||
--remaining;
|
||||
const auto item=it->path();
|
||||
const auto flags=GetFileAttributesW(item.c_str());
|
||||
if(flags==INVALID_FILE_ATTRIBUTES || flags&FILE_ATTRIBUTE_REPARSE_POINT)
|
||||
it.disable_recursion_pending();
|
||||
inspect(item);
|
||||
it.increment(error);
|
||||
}
|
||||
if(error) result.incomplete=true;
|
||||
}
|
||||
for(const auto pid:pids)
|
||||
{
|
||||
Handle process{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,pid)};
|
||||
LockProcess entry{pid};
|
||||
if(process.value)
|
||||
{
|
||||
FILETIME exit{},kernel{},user{};
|
||||
GetProcessTimes(process.value,&entry.started,&exit,&kernel,&user);
|
||||
wchar_t path[32768];
|
||||
DWORD count=std::size(path);
|
||||
if(QueryFullProcessImageNameW(process.value,0,path,&count))
|
||||
entry.name=fs::path(std::wstring_view(path,count)).filename().wstring();
|
||||
}
|
||||
if(entry.name.empty()) entry.name=L"Unknown process";
|
||||
result.processes.push_back(std::move(entry));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
struct LockDialog
|
||||
{
|
||||
std::vector<fs::path> paths;
|
||||
std::vector<LockProcess> processes;
|
||||
std::future<LockScan> scan;
|
||||
std::stop_source stop;
|
||||
};
|
||||
|
||||
constexpr UINT_PTR lockScanTimer=1;
|
||||
|
||||
void refreshLockProcesses(HWND window,LockDialog &state,std::shared_ptr<Handle> terminated={})
|
||||
{
|
||||
if(state.scan.valid()) return;
|
||||
state.processes.clear();
|
||||
SendDlgItemMessageW(window,431,LB_RESETCONTENT,0,0);
|
||||
EnableWindow(GetDlgItem(window,433),FALSE);
|
||||
EnableWindow(GetDlgItem(window,434),FALSE);
|
||||
SetDlgItemTextW(window,430,L"Checking which processes are using the file or folder…");
|
||||
try
|
||||
{
|
||||
std::packaged_task<LockScan()> task([paths=state.paths,stop=state.stop.get_token(),terminated=std::move(terminated)] {
|
||||
if(terminated) WaitForSingleObject(terminated->value,2500);
|
||||
return scanLockProcesses(paths,stop);
|
||||
});
|
||||
auto future=task.get_future();
|
||||
if(!SetTimer(window,lockScanTimer,50,nullptr))
|
||||
throw std::runtime_error("Could not start the process scan.");
|
||||
std::thread(std::move(task)).detach();
|
||||
state.scan=std::move(future);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
KillTimer(window,lockScanTimer);
|
||||
EnableWindow(GetDlgItem(window,434),TRUE);
|
||||
SetDlgItemTextW(window,430,L"Could not start the process scan.");
|
||||
}
|
||||
}
|
||||
|
||||
void endLockProcess(HWND window,LockDialog &state)
|
||||
{
|
||||
const auto index=SendDlgItemMessageW(window,431,LB_GETCURSEL,0,0);
|
||||
if(index<0 || size_t(index)>=state.processes.size()) return;
|
||||
const auto &entry=state.processes[index];
|
||||
auto error=[&](const wchar_t *message) {
|
||||
showFilesNotice(window,message,L"End process",{.tone=FilesNoticeTone::warning});
|
||||
};
|
||||
auto process=std::make_shared<Handle>();
|
||||
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry.pid);
|
||||
FILETIME started{},exited{},kernel{},user{};
|
||||
BOOL critical{};
|
||||
if(!process->value || !(entry.started.dwHighDateTime || entry.started.dwLowDateTime) ||
|
||||
!GetProcessTimes(process->value,&started,&exited,&kernel,&user) ||
|
||||
CompareFileTime(&started,&entry.started)!=0 || !IsProcessCritical(process->value,&critical) || critical)
|
||||
{
|
||||
error(L"This process has exited, is protected, or cannot be identified.");
|
||||
return;
|
||||
}
|
||||
const auto question=L"End "+entry.name+L" (PID "+std::to_wstring(entry.pid)+
|
||||
L")?\r\nUnsaved work in the process may be lost.";
|
||||
if(showFilesNotice(window,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
|
||||
return;
|
||||
if(WaitForSingleObject(process->value,0)==WAIT_TIMEOUT && !TerminateProcess(process->value,1))
|
||||
{
|
||||
const auto message=ks::lastError(L"Could not end the process");
|
||||
error(message.c_str());
|
||||
return;
|
||||
}
|
||||
refreshLockProcesses(window,state,std::move(process));
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(window,DWLP_USER,lp);
|
||||
prepareCopyDialog(window);
|
||||
for(const auto id:{430,431}) SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
const auto list=GetDlgItem(window,431);
|
||||
RECT bounds{};
|
||||
GetWindowRect(list,&bounds);
|
||||
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
|
||||
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
installScrollBar(list,window);
|
||||
layoutDialogButtons(window,432,{433,434,IDOK});
|
||||
SendMessageW(window,DM_SETDEFID,IDOK,0);
|
||||
SetFocus(GetDlgItem(window,IDOK));
|
||||
refreshLockProcesses(window,*reinterpret_cast<LockDialog *>(lp));
|
||||
return FALSE;
|
||||
}
|
||||
auto *data=reinterpret_cast<LockDialog *>(GetWindowLongPtrW(window,DWLP_USER));
|
||||
if(!data) return FALSE;
|
||||
auto &state=*data;
|
||||
if(message==WM_TIMER && wp==lockScanTimer)
|
||||
{
|
||||
if(!state.scan.valid() || state.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
|
||||
return TRUE;
|
||||
KillTimer(window,lockScanTimer);
|
||||
EnableWindow(GetDlgItem(window,434),TRUE);
|
||||
try
|
||||
{
|
||||
auto result=state.scan.get();
|
||||
for(auto &entry:result.processes)
|
||||
{
|
||||
const auto label=entry.name+L" (PID "+std::to_wstring(entry.pid)+L")";
|
||||
if(SendDlgItemMessageW(window,431,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))>=0)
|
||||
state.processes.push_back(std::move(entry));
|
||||
}
|
||||
SetDlgItemTextW(window,430,state.processes.empty()?
|
||||
(result.incomplete?L"No processes found. Some items could not be checked.":L"No locking processes found."):
|
||||
(result.incomplete?L"Possible locking processes. The scan was incomplete.":L"Processes using locked files or folders."));
|
||||
if(!state.processes.empty())
|
||||
{
|
||||
SendDlgItemMessageW(window,431,LB_SETCURSEL,0,0);
|
||||
EnableWindow(GetDlgItem(window,433),TRUE);
|
||||
}
|
||||
}
|
||||
catch(const std::exception &) {SetDlgItemTextW(window,430,L"Could not check for locking processes.");}
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND)
|
||||
{
|
||||
switch(LOWORD(wp))
|
||||
{
|
||||
case 433: endLockProcess(window,state); return TRUE;
|
||||
case 434: refreshLockProcesses(window,state); return TRUE;
|
||||
case IDOK:
|
||||
case IDCANCEL: FilesModalDialog::finish(window,IDCANCEL); return TRUE;
|
||||
}
|
||||
}
|
||||
if(message==WM_CLOSE) {FilesModalDialog::finish(window,IDCANCEL);return TRUE;}
|
||||
return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432},false,GetDlgItem(window,431));
|
||||
}
|
||||
|
||||
void showLockProcesses(HWND owner,std::vector<fs::path> paths)
|
||||
{
|
||||
LockDialog state{std::move(paths)};
|
||||
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,lockProcessesDialog,
|
||||
reinterpret_cast<LPARAM>(&state));
|
||||
state.stop.request_stop();
|
||||
}
|
||||
+2624
-786
File diff suppressed because it is too large.
Load diff
+199
-16
@@ -1,7 +1,12 @@
|
||||
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
|
||||
optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372;
|
||||
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions };
|
||||
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",L"Viewer",L"Editor"};
|
||||
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;
|
||||
constexpr int comparisonControls[]{comparisonFontLabel,comparisonChooseFont,410,comparisonColorCombo,
|
||||
comparisonChooseColor,comparisonColorValue,414,comparisonShortcutControl};
|
||||
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 };
|
||||
@@ -19,6 +24,9 @@ constexpr int textTabWidth=357,textLineEnding=359,
|
||||
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
|
||||
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme};
|
||||
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};
|
||||
constexpr wchar_t optionsLocationKey[]=L"OptionsLocation";
|
||||
constexpr struct
|
||||
{
|
||||
int id;
|
||||
@@ -86,12 +94,15 @@ struct OptionsBaseline
|
||||
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
|
||||
std::array<bool,2> wide{panels[0].wide,panels[1].wide};
|
||||
ks::files::TextSettings text=ks::files::loadTextPreferences();
|
||||
ComparisonAppearance comparison=readComparisonAppearance();
|
||||
WORD compareShortcut=comparisonShortcut;
|
||||
};
|
||||
|
||||
struct OptionsDraft
|
||||
{
|
||||
OptionsBaseline baseline;
|
||||
ks::files::TextSettings text=baseline.text;
|
||||
ComparisonAppearance comparison=baseline.comparison;
|
||||
HWND filesWindow{};
|
||||
LOGFONTW font=displayFont;
|
||||
int points=fontPoints;
|
||||
@@ -102,7 +113,9 @@ struct OptionsDraft
|
||||
int styleIndex=0;
|
||||
bool styleSuggestionsLoaded{};
|
||||
int page=PanelModes, section=PanelLayout;
|
||||
HTREEITEM wideColumnsNode{};
|
||||
DWORD location{};
|
||||
int markdownError{};
|
||||
HTREEITEM wideColumnsNode{},markdownNode{};
|
||||
RECT initialClient{};
|
||||
UINT initialDpi=96;
|
||||
OptionsControl controls[8]{
|
||||
@@ -150,7 +163,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
DWORD fields=0;
|
||||
for(int i=0;i<4;++i) if(checked(205+i)) fields|=1u<<i;
|
||||
const auto &base=draft.baseline;
|
||||
const bool dirty=!valid || width!=base.width ||
|
||||
const bool dirty=!valid || draft.markdownError || width!=base.width ||
|
||||
checked(273)!=base.wide[0] || checked(274)!=base.wide[1] ||
|
||||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
|
||||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
|
||||
@@ -158,7 +171,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
|
||||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
|
||||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
|
||||
draft.text!=base.text;
|
||||
draft.text!=base.text || draft.comparison!=base.comparison ||
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0)!=base.compareShortcut;
|
||||
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
|
||||
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
|
||||
}
|
||||
@@ -333,9 +347,31 @@ void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const k
|
||||
refreshTextColor(dialog,profile);
|
||||
}
|
||||
|
||||
void showMarkdownOptions(HWND dialog,const ks::files::MarkdownPreferences &settings)
|
||||
{
|
||||
// SetDlgItemText sends EN_CHANGE synchronously, so take a snapshot first.
|
||||
const auto values=settings;
|
||||
SetDlgItemInt(dialog,markdownWidth,values.width,FALSE);
|
||||
SetDlgItemInt(dialog,markdownSize,values.fontSize,FALSE);
|
||||
SetDlgItemTextW(dialog,markdownFamily,values.font.c_str());
|
||||
}
|
||||
|
||||
int readMarkdownOptions(HWND dialog,ks::files::MarkdownPreferences &settings)
|
||||
{
|
||||
BOOL widthValid{}, sizeValid{};
|
||||
const auto width=GetDlgItemInt(dialog,markdownWidth,&widthValid,FALSE);
|
||||
const auto size=GetDlgItemInt(dialog,markdownSize,&sizeValid,FALSE);
|
||||
if(!widthValid || width>999999) return markdownWidth;
|
||||
if(!sizeValid || size<8 || size>72) return markdownSize;
|
||||
wchar_t font[LF_FACESIZE]{};
|
||||
GetDlgItemTextW(dialog,markdownFamily,font,std::size(font));
|
||||
settings={width,size,font};
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
{
|
||||
if(!textOptionsPage(draft.page)) return false;
|
||||
if(!textOptionsPage(draft.page) || (draft.page==TextViewer && draft.section==markdownSection)) return false;
|
||||
auto &profile=draft.text.profiles[draft.page==TextEditor];
|
||||
const auto id=LOWORD(command);
|
||||
const auto row=[&](int control){return SendDlgItemMessageW(dialog,control,CB_GETCURSEL,0,0);};
|
||||
@@ -382,16 +418,32 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
return true;
|
||||
}
|
||||
|
||||
void showComparisonOptions(HWND dialog,const ComparisonAppearance &appearance)
|
||||
{
|
||||
const auto points=appearance.points;
|
||||
const auto description=std::wstring(appearance.font.lfFaceName)+L" · "+std::to_wstring(points/10)+
|
||||
(points%10?L"."+std::to_wstring(points%10):L"")+L" pt";
|
||||
SetDlgItemTextW(dialog,comparisonFontLabel,description.c_str());
|
||||
const auto index=SendDlgItemMessageW(dialog,comparisonColorCombo,CB_GETCURSEL,0,0);
|
||||
if(index<0 || index>=CompareColorCount) return;
|
||||
const auto color=appearance.palette[index];
|
||||
wchar_t hex[8]{};
|
||||
swprintf_s(hex,L"#%02X%02X%02X",unsigned(GetRValue(color)),unsigned(GetGValue(color)),unsigned(GetBValue(color)));
|
||||
SetDlgItemTextW(dialog,comparisonColorValue,hex);
|
||||
}
|
||||
|
||||
void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
{
|
||||
draft.page=page;
|
||||
draft.section=section;
|
||||
const bool markdown=page==TextViewer && section==markdownSection;
|
||||
const wchar_t *title=L"No matching settings";
|
||||
if(page==allOptions) title=L"All settings";
|
||||
else if(page>=0)
|
||||
{
|
||||
title=optionsTitles[page];
|
||||
if(section>=0 && !textOptionsPage(page))
|
||||
if(markdown) title=L"Markdown";
|
||||
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";
|
||||
@@ -422,6 +474,8 @@ 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(comparisonControls,page==CompareFiles);
|
||||
if(page==CompareFiles) showComparisonOptions(dialog,draft.comparison);
|
||||
show(dialogFrameControls,page==Appearance && section==DialogFrame);
|
||||
if(page==Appearance && section==DialogFrame)
|
||||
{
|
||||
@@ -430,9 +484,10 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
}
|
||||
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
|
||||
show(commandLineControls,page==CommandLine && section==0);
|
||||
show(textControls,textOptionsPage(page));
|
||||
show(markdownControls,markdown);
|
||||
show(textControls,textOptionsPage(page) && !markdown);
|
||||
show(editingControls,page==TextEditor);
|
||||
if(textOptionsPage(page)) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
|
||||
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[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);
|
||||
@@ -491,20 +546,27 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
const int previousPage=draft.page,previousSection=draft.section;
|
||||
TreeView_DeleteAllItems(tree);
|
||||
draft.wideColumnsNode=nullptr;
|
||||
draft.markdownNode=nullptr;
|
||||
const auto root=add(L"All settings",allOptions,-1,TVI_ROOT);
|
||||
HTREEITEM first{},selected{};
|
||||
for(int page=PanelModes;page<allOptions;++page)
|
||||
for(int page=PanelModes;page<=CompareFiles;++page)
|
||||
{
|
||||
if(page==allOptions) continue;
|
||||
HTREEITEM category{};
|
||||
const bool wholeCategory=matches(optionsTitles[page]) || (!query.empty() && matches(L"All settings"));
|
||||
const auto addSection=[&](const wchar_t *label,int section,bool aliasMatches=false)
|
||||
{
|
||||
if(!wholeCategory && !aliasMatches && !matches(label)) return;
|
||||
if(!category) category=add(optionsTitles[page],page,-1,root);
|
||||
if(!category)
|
||||
{
|
||||
category=add(optionsTitles[page],page,-1,root);
|
||||
if(page==previousPage && previousSection<0) selected=category;
|
||||
}
|
||||
const auto node=add(label,page,section,category);
|
||||
if(!first) first=node;
|
||||
if(page==previousPage && section==previousSection) selected=node;
|
||||
if(page==PanelModes && section==WideColumns) draft.wideColumnsNode=node;
|
||||
if(page==TextViewer && section==markdownSection) draft.markdownNode=node;
|
||||
};
|
||||
if(page==PanelModes)
|
||||
{
|
||||
@@ -526,6 +588,9 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
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==CompareFiles)
|
||||
addSection(L"Font and colors",0,matches(L"Compare files shortcut") || std::any_of(std::begin(comparisonColorNames),
|
||||
std::end(comparisonColorNames),matches));
|
||||
else if(textOptionsPage(page))
|
||||
{
|
||||
const bool propertyMatches=matches(L"Tab width") ||
|
||||
@@ -535,6 +600,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
{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"));
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -569,6 +636,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
|
||||
SendDlgItemMessageW(dialog,201,EM_SETLIMITTEXT,2,0);
|
||||
SendDlgItemMessageW(dialog,markdownWidth,EM_SETLIMITTEXT,6,0);
|
||||
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
|
||||
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
|
||||
showMarkdownOptions(dialog,draft.text.markdown);
|
||||
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 &option:frameOptions)
|
||||
for(DWORD value=0;value<=option.maximum;++value)
|
||||
@@ -626,7 +702,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
const auto &change=*reinterpret_cast<const NMTREEVIEWW*>(lp);
|
||||
if(change.hdr.code==TVN_SELCHANGEDW && change.itemNew.hItem)
|
||||
showOptionsPage(dialog,*draft,static_cast<int>(change.itemNew.lParam>>8),static_cast<int>(change.itemNew.lParam&255)-1);
|
||||
{
|
||||
const auto page=static_cast<int>(change.itemNew.lParam>>8);
|
||||
if(page!=allOptions || !GetWindowTextLengthW(GetDlgItem(dialog,optionsSearch)))
|
||||
draft->location=static_cast<DWORD>(change.itemNew.lParam);
|
||||
showOptionsPage(dialog,*draft,page,static_cast<int>(change.itemNew.lParam&255)-1);
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
@@ -654,6 +735,49 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
showOptionsPage(dialog,*draft,Appearance,Font);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case comparisonChooseFont:
|
||||
if(chooseDisplayFont(dialog,draft->comparison.font,draft->comparison.points))
|
||||
{
|
||||
draft->comparison.font.lfHeight=draft->comparison.font.lfWidth=0;
|
||||
showComparisonOptions(dialog,draft->comparison);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
case comparisonColorCombo:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE) showComparisonOptions(dialog,draft->comparison);
|
||||
return TRUE;
|
||||
case comparisonChooseColor:
|
||||
{
|
||||
const auto index=SendDlgItemMessageW(dialog,comparisonColorCombo,CB_GETCURSEL,0,0);
|
||||
if(index>=0 && index<CompareColorCount &&
|
||||
choosePanelColor(dialog,draft->comparison.palette[index],draft->custom.data()))
|
||||
{
|
||||
showComparisonOptions(dialog,draft->comparison);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
case markdownWidth: case markdownSize: case markdownFamily:
|
||||
if(HIWORD(wp)==EN_CHANGE)
|
||||
{
|
||||
draft->markdownError=readMarkdownOptions(dialog,draft->text.markdown);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
case markdownChoose:
|
||||
{
|
||||
LOGFONTW font{};
|
||||
const auto &settings=draft->text.markdown;
|
||||
wcsncpy_s(font.lfFaceName,settings.font.empty()?L"Segoe UI":settings.font.c_str(),_TRUNCATE);
|
||||
auto size=static_cast<int>(settings.fontSize)*10;
|
||||
font.lfHeight=-MulDiv(size,GetDpiForWindow(dialog),720);
|
||||
if(chooseDisplayFont(dialog,font,size,72))
|
||||
{
|
||||
SetDlgItemTextW(dialog,markdownFamily,font.lfFaceName);
|
||||
SetDlgItemInt(dialog,markdownSize,(size+5)/10,FALSE);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
case outerFramePadding: case innerFramePadding: case rowTextPadding:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE)
|
||||
{
|
||||
@@ -705,6 +829,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
return TRUE;
|
||||
case optionsReset:
|
||||
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);
|
||||
@@ -731,8 +860,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
draft->framePadding=defaultDialogFramePadding;
|
||||
if(draft->page==allOptions || textOptionsPage(draft->page))
|
||||
for(int page=TextViewer;page<=TextEditor;++page)
|
||||
if(draft->page==allOptions || draft->page==page)
|
||||
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
|
||||
draft->text.profiles[page==TextEditor]=ks::files::TextPreferences{};
|
||||
if(draft->page==allOptions || (draft->page==TextViewer && (draft->section<0 || draft->section==markdownSection)))
|
||||
showMarkdownOptions(dialog,ks::files::MarkdownPreferences{});
|
||||
showOptionsPage(dialog,*draft,draft->page,draft->section);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
@@ -753,12 +884,30 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case 321: case 323:
|
||||
case 321: case 323: case comparisonShortcutControl:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
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"");
|
||||
TreeView_SelectItem(GetDlgItem(dialog,optionsTree),draft->markdownNode);
|
||||
showFilesNotice(dialog,L"Enter a width in pixels (0 for full window) and a font size from 8 to 72 pt.",L"Markdown");
|
||||
SetFocus(GetDlgItem(dialog,draft->markdownError));
|
||||
return TRUE;
|
||||
}
|
||||
BOOL valid{};
|
||||
const auto width=GetDlgItemInt(dialog,201,&valid,FALSE);
|
||||
if(!valid || width<6 || width>16)
|
||||
@@ -778,8 +927,26 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
const auto &base=draft->baseline;
|
||||
const auto storedComparison=readComparisonAppearance();
|
||||
const bool comparisonChanged=draft->comparison!=base.comparison;
|
||||
if(comparisonChanged && storedComparison!=base.comparison && storedComparison!=draft->comparison)
|
||||
{
|
||||
showFilesNotice(dialog,L"Comparison settings changed in another window. Reopen Options before editing them again.",
|
||||
optionsTitles[CompareFiles]);
|
||||
return TRUE;
|
||||
}
|
||||
const bool textChanged=draft->text!=base.text;
|
||||
auto textSettings=ks::files::loadTextPreferences();
|
||||
if(draft->text.markdown!=base.text.markdown)
|
||||
{
|
||||
if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown)
|
||||
{
|
||||
showFilesNotice(dialog,L"Markdown settings changed in another window. Reopen Options before editing them again.",
|
||||
L"KSwitcher Files Options");
|
||||
return TRUE;
|
||||
}
|
||||
textSettings.markdown=draft->text.markdown;
|
||||
}
|
||||
for(size_t i=0;i<textSettings.profiles.size();++i)
|
||||
{
|
||||
if(draft->text.profiles[i]==base.text.profiles[i]) continue;
|
||||
@@ -830,11 +997,19 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
showFilesNotice(dialog,L"Could not apply the selected font.",optionsTitles[Appearance]);
|
||||
return TRUE;
|
||||
}
|
||||
if(comparisonChanged && !saveComparisonAppearance(draft->comparison))
|
||||
{
|
||||
if(fontChanged) applyFont(owner,base.font,base.points);
|
||||
if(stylesChanged) saveFileStyles(fileStyles);
|
||||
showFilesNotice(dialog,L"Could not save comparison settings.",optionsTitles[CompareFiles]);
|
||||
return TRUE;
|
||||
}
|
||||
if(textChanged)
|
||||
{
|
||||
try { ks::files::saveTextPreferences(textSettings); }
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(comparisonChanged) saveComparisonAppearance(storedComparison);
|
||||
if(fontChanged) applyFont(owner,base.font,base.points);
|
||||
if(stylesChanged) saveFileStyles(fileStyles);
|
||||
const auto message=L"Could not save text settings. "+ks::wide(error.what());
|
||||
@@ -850,6 +1025,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
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);
|
||||
@@ -884,6 +1060,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
SendMessageW(dialogOwner,filesPreferencesChanged,reinterpret_cast<WPARAM>(owner),0);
|
||||
draft->baseline=OptionsBaseline{};
|
||||
draft->text=draft->baseline.text;
|
||||
draft->comparison=draft->baseline.comparison;
|
||||
showMarkdownOptions(dialog,draft->text.markdown);
|
||||
populateTextSchemes(dialog,draft->text);
|
||||
draft->font=displayFont;
|
||||
draft->points=fontPoints;
|
||||
@@ -898,6 +1076,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,274,panels[1].wide);
|
||||
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());
|
||||
@@ -919,12 +1098,16 @@ void runOptions(HWND owner,int page)
|
||||
{
|
||||
OptionsDraft draft;
|
||||
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
|
||||
draft.page=page;
|
||||
draft.section=textOptionsPage(page)?0:PanelLayout;
|
||||
const DWORD initial=static_cast<DWORD>((page<<8)|1);
|
||||
const auto saved=preference(optionsLocationKey,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;
|
||||
std::copy(std::begin(colors),std::end(colors),draft.palette.begin());
|
||||
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog,
|
||||
reinterpret_cast<LPARAM>(&draft));
|
||||
if(result==-1) setStatus(L"Could not open Files Options.");
|
||||
else savePreference(optionsLocationKey,draft.location);
|
||||
}
|
||||
|
||||
void editOptions(HWND owner)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <string>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline std::wstring windowsPowerShell()
|
||||
{
|
||||
wchar_t system[MAX_PATH]{};
|
||||
const auto length=GetSystemDirectoryW(system,MAX_PATH);
|
||||
return length && length<MAX_PATH
|
||||
? std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe" : std::wstring{};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <algorithm>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline int scrollBarWidth(HWND window) {return std::max(7,MulDiv(12,GetDpiForWindow(window),96));}
|
||||
|
||||
inline int scrollArrowHeight(RECT bounds)
|
||||
{
|
||||
return std::min(bounds.right-bounds.left,(bounds.bottom-bounds.top)/3);
|
||||
}
|
||||
|
||||
struct ScrollPosition
|
||||
{
|
||||
int count, visible, top;
|
||||
|
||||
int last() const {return std::max(0,count-visible);}
|
||||
|
||||
RECT thumb(RECT track) const
|
||||
{
|
||||
const auto arrow=scrollArrowHeight(track);
|
||||
track.top+=arrow;
|
||||
track.bottom-=arrow;
|
||||
const int height=track.bottom-track.top;
|
||||
if(height<=0 || !last()) return {};
|
||||
const int size=std::clamp(MulDiv(height,visible,count),std::min(height,arrow),height);
|
||||
track.top+=MulDiv(std::clamp(top,0,last()),height-size,last());
|
||||
track.bottom=track.top+size;
|
||||
return track;
|
||||
}
|
||||
|
||||
int click(RECT track,int y) const
|
||||
{
|
||||
const auto arrow=scrollArrowHeight(track);
|
||||
const auto grip=thumb(track);
|
||||
const int delta=y<track.top+arrow?-1:y>=track.bottom-arrow?1:
|
||||
y<grip.top?-visible:y>=grip.bottom?visible:0;
|
||||
return std::clamp(top+delta,0,last());
|
||||
}
|
||||
|
||||
int drag(RECT track,int y,int offset) const
|
||||
{
|
||||
const auto grip=thumb(track);
|
||||
const auto arrow=scrollArrowHeight(track);
|
||||
const auto travel=track.bottom-track.top-2*arrow-(grip.bottom-grip.top);
|
||||
return travel>0?std::clamp(MulDiv(y-track.top-arrow-offset,last(),travel),0,last()):top;
|
||||
}
|
||||
};
|
||||
|
||||
inline void paintScrollBar(HDC dc,RECT track,ScrollPosition position,COLORREF background)
|
||||
{
|
||||
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
SetDCBrushColor(dc,background);
|
||||
FillRect(dc,&track,brush);
|
||||
if(!position.last()) return;
|
||||
const auto lighter=[&](int divisor){return RGB(GetRValue(background)+(257-GetRValue(background))/divisor,
|
||||
GetGValue(background)+(257-GetGValue(background))/divisor,
|
||||
GetBValue(background)+(257-GetBValue(background))/divisor);};
|
||||
const auto ink=lighter(4),dots=lighter(7);
|
||||
const int height=scrollArrowHeight(track);
|
||||
struct
|
||||
{
|
||||
BITMAPINFOHEADER header{sizeof(BITMAPINFOHEADER),4,4,1,32,BI_RGB};
|
||||
DWORD pixels[16]{};
|
||||
} tile;
|
||||
for(int y=0;y<4;++y)
|
||||
for(int x=0;x<4;++x)
|
||||
{
|
||||
const auto color=y%2==0 && x%2==y/2?dots:background;
|
||||
// DIB pixels are stored bottom-up in BGR order.
|
||||
tile.pixels[(3-y)*4+x]=RGB(GetBValue(color),GetGValue(color),GetRValue(color));
|
||||
}
|
||||
if(const auto pattern=CreateDIBPatternBrushPt(&tile,DIB_RGB_COLORS))
|
||||
{
|
||||
const RECT channel{track.left,track.top+height,track.right,track.bottom-height};
|
||||
POINT origin{};
|
||||
SetBrushOrgEx(dc,channel.left,channel.top,&origin);
|
||||
FillRect(dc,&channel,pattern);
|
||||
SetBrushOrgEx(dc,origin.x,origin.y,nullptr);
|
||||
DeleteObject(pattern);
|
||||
}
|
||||
SetDCBrushColor(dc,ink);
|
||||
const auto thumb=position.thumb(track);
|
||||
FillRect(dc,&thumb,brush);
|
||||
const int middle=(track.left+track.right)/2;
|
||||
const int radius=std::max(0,(height-3)/2);
|
||||
for(int row=0;row<=radius;++row)
|
||||
{
|
||||
const int y=track.top+(height-radius-1)/2+row;
|
||||
const int mirrored=track.bottom-1-(y-track.top);
|
||||
const RECT up{middle-row,y,middle+row+1,y+1};
|
||||
const RECT down{middle-row,mirrored,middle+row+1,mirrored+1};
|
||||
FillRect(dc,&up,brush);
|
||||
FillRect(dc,&down,brush);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,7 @@ struct FileRowStyle
|
||||
{
|
||||
COLORREF foreground,background;
|
||||
unsigned decorations{};
|
||||
bool operator==(const FileRowStyle &) const = default;
|
||||
};
|
||||
FileRowStyle resolveFileStyle(std::wstring_view extension,bool file,bool dimmed,bool protectedRow,
|
||||
COLORREF foreground,COLORREF background,const std::vector<FileStyle> &styles=fileStyles,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "files_powershell.h"
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
@@ -50,10 +51,8 @@ public:
|
||||
startup.lpAttributeList=attributes;
|
||||
PROCESS_INFORMATION info{};
|
||||
wchar_t command[]=L"powershell.exe -NoLogo -NoProfile -NoExit -Command \"Remove-Module PSReadLine -ErrorAction SilentlyContinue; function global:prompt { $location = Get-Location; $path = if ($location.Provider.Name -eq 'FileSystem') { [Uri]::EscapeDataString($location.ProviderPath) }; ([string][char]27) + ']633;ks-directory:' + $path + [char]7 + [char]27 + '[?25l' }; Clear-Host\"";
|
||||
wchar_t system[MAX_PATH]{};
|
||||
const auto length=GetSystemDirectoryW(system,MAX_PATH);
|
||||
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
|
||||
const bool started=length && length<MAX_PATH &&
|
||||
const auto shell=ks::files::windowsPowerShell();
|
||||
const bool started=!shell.empty() &&
|
||||
UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
|
||||
console,sizeof(console),nullptr,nullptr) &&
|
||||
CreateProcessW(shell.c_str(),command,nullptr,nullptr,FALSE,EXTENDED_STARTUPINFO_PRESENT,
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
#ifdef __MINGW32__
|
||||
__CRT_UUID_DECL(ICoreWebView2_3, 0xA0D6DF20, 0x3B92, 0x416D, 0xAA, 0x0C, 0x43, 0x7A, 0x9C, 0x72, 0x78, 0x57)
|
||||
__CRT_UUID_DECL(ICoreWebView2Controller2, 0xc979903e, 0xd4ca, 0x4228, 0x92, 0xeb, 0x47, 0xee, 0x3f, 0xa9, 0x6e, 0xab)
|
||||
__CRT_UUID_DECL(ICoreWebView2ControllerOptions3, 0xb32b191a, 0x8998, 0x57ca, 0xb7, 0xcb, 0xe0, 0x46, 0x17, 0xe4, 0xce, 0x4a)
|
||||
__CRT_UUID_DECL(ICoreWebView2Environment10, 0xee0eb9df, 0x6f12, 0x46ce, 0xb5, 0x3f, 0x3f, 0x47, 0xb9, 0xc9, 0x28, 0xe0)
|
||||
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler, 0x4e8a3389, 0xc9d8, 0x4bd2, 0xb6, 0xb5, 0x12, 0x4f, 0xee, 0x6c, 0xc1, 0x4d)
|
||||
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4819f3, 0xc9b7, 0x4260, 0x81, 0x27, 0xc9, 0xf5, 0xbd, 0xe7, 0xf6, 0x8c)
|
||||
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
|
||||
@@ -16,6 +19,8 @@ __CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
inline constexpr COLORREF terminalSurface=RGB(24,24,24);
|
||||
|
||||
template<class Interface, class... Args>
|
||||
class TerminalCallback final : public Interface
|
||||
{
|
||||
@@ -56,6 +61,7 @@ class FilesTerminalView
|
||||
RECT bounds{};
|
||||
bool ready{};
|
||||
bool visible{};
|
||||
bool waitForReady{};
|
||||
public:
|
||||
~FilesTerminalView() { close(); }
|
||||
void focus()
|
||||
@@ -94,9 +100,10 @@ public:
|
||||
RECT current{};
|
||||
if(FAILED(controller->get_Bounds(¤t)) || !EqualRect(¤t,&bounds))
|
||||
controller->put_Bounds(bounds);
|
||||
const bool showController=show && (!waitForReady || ready);
|
||||
BOOL currentVisibility{};
|
||||
if(FAILED(controller->get_IsVisible(¤tVisibility)) || !!currentVisibility!=show)
|
||||
controller->put_IsVisible(show);
|
||||
if(FAILED(controller->get_IsVisible(¤tVisibility)) || !!currentVisibility!=showController)
|
||||
controller->put_IsVisible(showController);
|
||||
}
|
||||
void close()
|
||||
{
|
||||
@@ -140,6 +147,9 @@ public:
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
|
||||
const auto assets=folder/L"terminal";
|
||||
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
|
||||
waitForReady=!markdown;
|
||||
constexpr COREWEBVIEW2_COLOR background{
|
||||
255,GetRValue(terminalSurface),GetGValue(terminalSurface),GetBValue(terminalSurface)};
|
||||
lifetime=std::make_shared<int>(0);
|
||||
const std::weak_ptr<int> alive=lifetime;
|
||||
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
|
||||
@@ -153,6 +163,12 @@ public:
|
||||
if(alive.expired()) return S_OK;
|
||||
if(FAILED(result) || !view) { failed(); return S_OK; }
|
||||
controller=view;
|
||||
if(!markdown)
|
||||
{
|
||||
view->put_IsVisible(FALSE);
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2Controller2> colors;
|
||||
if(SUCCEEDED(controller.As(&colors))) colors->put_DefaultBackgroundColor(background);
|
||||
}
|
||||
view->get_CoreWebView2(&web);
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
|
||||
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
|
||||
@@ -207,7 +223,11 @@ public:
|
||||
uri==source &&
|
||||
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
|
||||
{
|
||||
if(wcscmp(value,L"ready")==0) ready=true;
|
||||
if(!ready && wcscmp(value,L"ready")==0)
|
||||
{
|
||||
ready=true;
|
||||
if(waitForReady) layout(bounds,visible);
|
||||
}
|
||||
if(ready) receive(value);
|
||||
}
|
||||
CoTaskMemFree(value);
|
||||
@@ -222,6 +242,18 @@ public:
|
||||
layout(bounds,visible);
|
||||
return S_OK;
|
||||
});
|
||||
if(!markdown)
|
||||
{
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2Environment10> configurable;
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions> options;
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions3> colors;
|
||||
if(SUCCEEDED(env->QueryInterface(IID_PPV_ARGS(&configurable))) &&
|
||||
SUCCEEDED(configurable->CreateCoreWebView2ControllerOptions(&options)) &&
|
||||
SUCCEEDED(options.As(&colors)) &&
|
||||
SUCCEEDED(colors->put_DefaultBackgroundColor(background)) &&
|
||||
SUCCEEDED(configurable->CreateCoreWebView2ControllerWithOptions(host,options.Get(),completed.Get())))
|
||||
return S_OK;
|
||||
}
|
||||
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
|
||||
return S_OK;
|
||||
});
|
||||
|
||||
+142
-42
@@ -38,6 +38,15 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
|
||||
return result;
|
||||
}
|
||||
|
||||
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,
|
||||
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
|
||||
return handle;
|
||||
}
|
||||
|
||||
uint64_t fileSize(HANDLE file)
|
||||
{
|
||||
LARGE_INTEGER size{};
|
||||
@@ -97,10 +106,87 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
|
||||
if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file");
|
||||
return path;
|
||||
}
|
||||
|
||||
bool isUtf16(TextEncoding encoding)
|
||||
{
|
||||
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
|
||||
}
|
||||
|
||||
TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(std::move(path)), editable_(editable)
|
||||
std::string_view signature(TextEncoding encoding)
|
||||
{
|
||||
switch(encoding)
|
||||
{
|
||||
case TextEncoding::utf16le: return "\xff\xfe";
|
||||
case TextEncoding::utf16be: return "\xfe\xff";
|
||||
case TextEncoding::utf8: return "\xef\xbb\xbf";
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
|
||||
{
|
||||
const int length=static_cast<int>(bytes.size());
|
||||
const auto required=MultiByteToWideChar(codePage,flags,bytes.data(),length,nullptr,0);
|
||||
if(!required) fail("Decode text");
|
||||
std::wstring units(required,L'\0');
|
||||
if(!MultiByteToWideChar(codePage,flags,bytes.data(),length,units.data(),required)) fail("Decode text");
|
||||
return units;
|
||||
}
|
||||
|
||||
std::string encode(std::string_view utf8,TextEncoding encoding)
|
||||
{
|
||||
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
|
||||
const auto units=decodeMultibyte(utf8,CP_UTF8,MB_ERR_INVALID_CHARS);
|
||||
if(encoding==TextEncoding::windows1252)
|
||||
{
|
||||
BOOL substituted{};
|
||||
const int length=static_cast<int>(units.size());
|
||||
const auto required=WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,
|
||||
nullptr,0,nullptr,&substituted);
|
||||
if(!required) fail("Encode Windows-1252");
|
||||
if(substituted) throw std::runtime_error("Some characters cannot be saved as Windows-1252. Choose a Unicode encoding.");
|
||||
std::string bytes(required,'\0');
|
||||
if(!WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,bytes.data(),required,nullptr,&substituted))
|
||||
fail("Encode Windows-1252");
|
||||
return bytes;
|
||||
}
|
||||
std::string bytes(units.size()*2,'\0');
|
||||
const size_t low=encoding==TextEncoding::utf16le?0:1;
|
||||
for(size_t i=0;i<units.size();++i)
|
||||
{
|
||||
bytes[2*i+low]=static_cast<char>(units[i]&0xff);
|
||||
bytes[2*i+1-low]=static_cast<char>(units[i]>>8);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
std::string convertLineEndings(std::string_view text,TextLineEnding ending)
|
||||
{
|
||||
if(ending==TextLineEnding::preserve) return std::string(text);
|
||||
const std::string_view replacement=ending==TextLineEnding::crlf?"\r\n":ending==TextLineEnding::lf?"\n":"\r";
|
||||
std::string result;
|
||||
result.reserve(text.size());
|
||||
for(size_t start=0;start<text.size();)
|
||||
{
|
||||
const auto next=text.find_first_of("\r\n",start);
|
||||
result.append(text.substr(start,next==text.npos?text.npos:next-start));
|
||||
if(next==text.npos) break;
|
||||
result.append(replacement);
|
||||
start=next+1;
|
||||
if(text[next]=='\r' && start<text.size() && text[start]=='\n') ++start;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
|
||||
: path_(std::move(path)), editable_(editable)
|
||||
{
|
||||
if(path_.empty())
|
||||
{
|
||||
if(encoding!=TextEncoding::automatic) encoding_=encoding;
|
||||
return;
|
||||
}
|
||||
File source{openSource(path_, editable)};
|
||||
if (editable)
|
||||
{
|
||||
@@ -115,13 +201,15 @@ TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(st
|
||||
}
|
||||
size_ = fileSize(source.handle);
|
||||
const auto prefix = read(source.handle, 0, static_cast<size_t>(std::min<uint64_t>(3, size_)));
|
||||
if (prefix.starts_with("\xef\xbb\xbf")) bom_ = 3;
|
||||
else if (prefix.starts_with("\xff\xfe") || prefix.starts_with("\xfe\xff"))
|
||||
if(encoding==TextEncoding::automatic)
|
||||
{
|
||||
encoding_ = prefix.starts_with("\xff") ? Encoding::utf16le : Encoding::utf16be;
|
||||
bom_ = 2;
|
||||
if (size_ % 2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
|
||||
encoding=TextEncoding::utf8;
|
||||
for(const auto candidate:{TextEncoding::utf16le,TextEncoding::utf16be})
|
||||
if(prefix.starts_with(signature(candidate))) encoding=candidate;
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -135,8 +223,9 @@ const wchar_t *TextDocument::encodingName() const
|
||||
{
|
||||
switch (encoding_)
|
||||
{
|
||||
case Encoding::utf16le: return L"UTF-16 LE";
|
||||
case Encoding::utf16be: return L"UTF-16 BE";
|
||||
case TextEncoding::utf16le: return L"UTF-16 LE";
|
||||
case TextEncoding::utf16be: return L"UTF-16 BE";
|
||||
case TextEncoding::windows1252: return L"Windows-1252";
|
||||
default: return bom_ ? L"UTF-8 BOM" : L"UTF-8";
|
||||
}
|
||||
}
|
||||
@@ -160,40 +249,45 @@ uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
|
||||
if (page >= pages()) return size_;
|
||||
|
||||
const auto offset = bom_ + page * pageBytes;
|
||||
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
|
||||
const auto unit = isUtf16(encoding_) ? 2u : 1u;
|
||||
const auto sample = read(source, offset - unit,
|
||||
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
|
||||
const auto getUnit = [&](size_t i) -> unsigned {
|
||||
const auto first = static_cast<unsigned char>(sample[i]);
|
||||
if (unit == 1) return first;
|
||||
const auto second = static_cast<unsigned char>(sample[i + 1]);
|
||||
return encoding_ == Encoding::utf16le ? first | (second << 8) : (first << 8) | second;
|
||||
return encoding_ == TextEncoding::utf16le ? first | (second << 8) : (first << 8) | second;
|
||||
};
|
||||
if (getUnit(0) == '\n') return offset;
|
||||
for (size_t i = unit; i + unit < sample.size(); i += unit)
|
||||
if (getUnit(i) == '\n') return offset + i;
|
||||
|
||||
size_t i = unit;
|
||||
if (unit == 1)
|
||||
if (encoding_ == TextEncoding::utf8)
|
||||
{
|
||||
// Advance past at most one UTF-8 code point, even on malformed input.
|
||||
while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i;
|
||||
}
|
||||
else if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
|
||||
else if (isUtf16(encoding_))
|
||||
if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
|
||||
if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit;
|
||||
return offset + i - unit;
|
||||
}
|
||||
|
||||
std::string TextDocument::decode(std::string bytes) const
|
||||
{
|
||||
if (encoding_ == Encoding::utf8 || bytes.empty()) return bytes;
|
||||
if (encoding_ == TextEncoding::utf8 || bytes.empty()) return bytes;
|
||||
std::wstring units;
|
||||
units.resize(bytes.size() / 2);
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
if(encoding_==TextEncoding::windows1252) units=decodeMultibyte(bytes,1252,0);
|
||||
else
|
||||
{
|
||||
const auto a = static_cast<unsigned char>(bytes[2 * i]);
|
||||
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
|
||||
units[i] = static_cast<wchar_t>(encoding_ == Encoding::utf16le ? a | (b << 8) : (a << 8) | b);
|
||||
units.resize(bytes.size() / 2);
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
{
|
||||
const auto a = static_cast<unsigned char>(bytes[2 * i]);
|
||||
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
|
||||
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);
|
||||
@@ -204,25 +298,6 @@ std::string TextDocument::decode(std::string bytes) const
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string TextDocument::encode(std::string_view utf8) const
|
||||
{
|
||||
if (encoding_ == Encoding::utf8 || utf8.empty()) return std::string(utf8);
|
||||
const auto length = static_cast<int>(utf8.size());
|
||||
const int required = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, nullptr, 0);
|
||||
if (!required) fail("Encode UTF-16");
|
||||
std::wstring units(required, L'\0');
|
||||
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, units.data(), required))
|
||||
fail("Encode UTF-16");
|
||||
std::string bytes(units.size() * 2, '\0');
|
||||
const int low = encoding_ == Encoding::utf16le ? 0 : 1;
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
{
|
||||
bytes[2 * i + low] = static_cast<char>(units[i] & 0xff);
|
||||
bytes[2 * i + 1 - low] = static_cast<char>(units[i] >> 8);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
std::string TextDocument::readPage(uint64_t page) const
|
||||
{
|
||||
if (const auto it = changes_.find(page); it != changes_.end())
|
||||
@@ -232,6 +307,7 @@ std::string TextDocument::readPage(uint64_t page) const
|
||||
|
||||
std::string TextDocument::readOriginal(uint64_t page) const
|
||||
{
|
||||
if(path_.empty()) return {};
|
||||
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
|
||||
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
|
||||
const auto start = boundary(page,source);
|
||||
@@ -298,17 +374,14 @@ bool TextDocument::save()
|
||||
for (const auto &[page, change] : changes_)
|
||||
{
|
||||
copyUntil(offset, boundary(page));
|
||||
append(encode(read(spool_, change.offset, change.size)));
|
||||
append(encode(read(spool_, change.offset, change.size),encoding_));
|
||||
offset = boundary(page + 1);
|
||||
}
|
||||
copyUntil(offset, size_);
|
||||
if (!FlushFileBuffers(output.handle)) fail("Flush saved file");
|
||||
CloseHandle(output.release());
|
||||
|
||||
// A metadata-only handle survives the rename without blocking ReplaceFile's exclusive open.
|
||||
File replacement{CreateFileW(pending.path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)};
|
||||
if (replacement.handle == INVALID_HANDLE_VALUE) fail("Track replacement file");
|
||||
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.");
|
||||
const auto backup = temporaryPath(path_.parent_path());
|
||||
@@ -336,4 +409,31 @@ bool TextDocument::save()
|
||||
spoolSize_ = 0;
|
||||
return source_ != INVALID_HANDLE_VALUE;
|
||||
}
|
||||
|
||||
bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
|
||||
{
|
||||
if(!path_.empty() || !editable_) throw std::logic_error("The document is not a new editable file.");
|
||||
if(format.encoding==TextEncoding::automatic) format.encoding=TextEncoding::utf8;
|
||||
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;
|
||||
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
|
||||
write(output.handle,bom);
|
||||
write(output.handle,bytes);
|
||||
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
|
||||
CloseHandle(output.release());
|
||||
File replacement{trackReplacement(pending.path)};
|
||||
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Create new file");
|
||||
pending.path.clear();
|
||||
path_=std::move(path);
|
||||
encoding_=format.encoding;
|
||||
bom_=bom.size();
|
||||
size_=bom_+bytes.size();
|
||||
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);
|
||||
return source_!=INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,24 @@
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 };
|
||||
enum class TextLineEnding { preserve, crlf, lf, cr };
|
||||
|
||||
struct TextSaveFormat
|
||||
{
|
||||
TextEncoding encoding=TextEncoding::utf8;
|
||||
bool bom{};
|
||||
TextLineEnding lineEnding=TextLineEnding::preserve;
|
||||
};
|
||||
|
||||
class TextDocument
|
||||
{
|
||||
public:
|
||||
static constexpr uint64_t pageBytes = 1024 * 1024;
|
||||
static constexpr size_t editLimit = 8 * pageBytes;
|
||||
|
||||
explicit TextDocument(std::filesystem::path path, bool editable = true);
|
||||
explicit TextDocument(std::filesystem::path path, bool editable = true,
|
||||
TextEncoding encoding=TextEncoding::automatic);
|
||||
~TextDocument();
|
||||
TextDocument(const TextDocument &) = delete;
|
||||
TextDocument &operator=(const TextDocument &) = delete;
|
||||
@@ -29,10 +40,11 @@ public:
|
||||
bool modified() const { return !changes_.empty(); }
|
||||
bool modifiedWith(uint64_t page, std::string_view current) const;
|
||||
bool save();
|
||||
bool saveNew(std::filesystem::path path, TextSaveFormat format);
|
||||
const wchar_t *encodingName() const;
|
||||
TextEncoding encoding() const { return encoding_; }
|
||||
|
||||
private:
|
||||
enum class Encoding { utf8, utf16le, utf16be };
|
||||
struct Change { uint64_t offset; size_t size; };
|
||||
|
||||
std::filesystem::path path_;
|
||||
@@ -40,13 +52,12 @@ private:
|
||||
HANDLE spool_ = INVALID_HANDLE_VALUE;
|
||||
uint64_t size_{}, spoolSize_{};
|
||||
size_t bom_{};
|
||||
Encoding encoding_ = Encoding::utf8;
|
||||
TextEncoding encoding_ = TextEncoding::utf8;
|
||||
bool editable_;
|
||||
std::map<uint64_t, Change> changes_;
|
||||
|
||||
std::string decode(std::string bytes) const;
|
||||
uint64_t boundary(uint64_t page,HANDLE source) const;
|
||||
std::string readOriginal(uint64_t page) const;
|
||||
std::string encode(std::string_view utf8) const;
|
||||
};
|
||||
}
|
||||
@@ -44,10 +44,18 @@ struct NamedTextPalette
|
||||
};
|
||||
inline constexpr size_t maxTextPalettes = 48;
|
||||
inline constexpr size_t maxTextPaletteName = 48;
|
||||
struct MarkdownPreferences
|
||||
{
|
||||
unsigned width{960}, fontSize{12};
|
||||
std::wstring font;
|
||||
bool operator==(const MarkdownPreferences &) const = default;
|
||||
};
|
||||
|
||||
struct TextSettings
|
||||
{
|
||||
TextPreferencesSet profiles;
|
||||
std::vector<NamedTextPalette> schemes;
|
||||
MarkdownPreferences markdown;
|
||||
bool operator==(const TextSettings &) const = default;
|
||||
};
|
||||
TextSettings loadTextPreferences();
|
||||
|
||||
+524
-159
File diff suppressed because it is too large.
Load diff
+35
-3
@@ -2,8 +2,11 @@
|
||||
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <cstdint>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include "files_text_document.h"
|
||||
|
||||
namespace ks::lan { struct FilesPeer; }
|
||||
|
||||
@@ -20,6 +23,8 @@ struct TextWindowFont
|
||||
int tenthsOfPoint;
|
||||
};
|
||||
|
||||
void setFileWindowTaskbar(HWND window,int iconResource,const wchar_t *identity);
|
||||
|
||||
struct FarDropDownPalette
|
||||
{
|
||||
COLORREF surface, text, selection;
|
||||
@@ -37,7 +42,7 @@ void installFarHistoryKey(HWND field,int arrowId);
|
||||
|
||||
struct TextDialogs
|
||||
{
|
||||
INT_PTR (*confirmSave)(HWND);
|
||||
INT_PTR (*confirmSave)(HWND,bool draft);
|
||||
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
|
||||
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
|
||||
void (*prepare)(HWND);
|
||||
@@ -49,10 +54,37 @@ struct TextDialogs
|
||||
void (*finish)(HWND,INT_PTR);
|
||||
bool (*dismissOwned)(HWND);
|
||||
bool (*confirmExisting)(HWND);
|
||||
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
|
||||
};
|
||||
|
||||
struct TextOpenOptions
|
||||
{
|
||||
TextEncoding encoding=TextEncoding::automatic;
|
||||
bool draft{};
|
||||
};
|
||||
|
||||
struct RemoteTextRevision
|
||||
{
|
||||
uint64_t size{}, modified{};
|
||||
bool editable{};
|
||||
};
|
||||
|
||||
struct RemoteTextSource
|
||||
{
|
||||
using Progress=std::function<bool(uint64_t,uint64_t)>;
|
||||
std::string id;
|
||||
std::wstring name;
|
||||
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
bool,const Progress &,uint64_t)> download;
|
||||
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
const RemoteTextRevision &)> upload;
|
||||
};
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false);
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
|
||||
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);
|
||||
void textWindowOwnerClosed();
|
||||
bool cycleTextWindows(HWND current);
|
||||
bool cycleTextWindows(HWND current,bool reverse);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+325
-47
@@ -7,6 +7,9 @@
|
||||
#include "lan_mesh.h"
|
||||
#include "lan_clipboard.h"
|
||||
#include "lan_layout.h"
|
||||
#include "lan_network.h"
|
||||
#include "lan_wake.h"
|
||||
#include "lan_clients.h"
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
@@ -28,14 +31,41 @@ std::string hostName()
|
||||
wchar_t name[256]{}; DWORD size=256;
|
||||
return GetComputerNameW(name,&size) ? utf8(std::wstring(name,size)) : "KSwitcher";
|
||||
}
|
||||
std::vector<ULONG> broadcasts()
|
||||
Bytes ipv4Adapters()
|
||||
{
|
||||
ULONG size=16384; Bytes data(size);
|
||||
auto flags=GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER;
|
||||
auto result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size);
|
||||
if(result==ERROR_BUFFER_OVERFLOW) { data.resize(size); result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size); }
|
||||
if(result!=NO_ERROR) return {};
|
||||
return data;
|
||||
}
|
||||
std::string wakeMacFor(ULONG remote)
|
||||
{
|
||||
DWORD interfaceIndex{};
|
||||
if(GetBestInterface(remote,&interfaceIndex)!=NO_ERROR) return {};
|
||||
auto data=ipv4Adapters();
|
||||
if(data.empty()) return {};
|
||||
for(auto a=reinterpret_cast<const IP_ADAPTER_ADDRESSES*>(data.data());a;a=a->Next)
|
||||
{
|
||||
if(a->IfIndex!=interfaceIndex || a->OperStatus!=IfOperStatusUp || a->PhysicalAddressLength!=6 ||
|
||||
(a->IfType!=IF_TYPE_ETHERNET_CSMACD && a->IfType!=IF_TYPE_IEEE80211)) continue;
|
||||
std::string result;
|
||||
for(size_t i=0;i<a->PhysicalAddressLength;++i)
|
||||
{
|
||||
const auto byte=a->PhysicalAddress[i];
|
||||
result+="0123456789abcdef"[byte>>4];
|
||||
result+="0123456789abcdef"[byte&15];
|
||||
}
|
||||
return lan::wakePacket(result)?result:std::string{};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
std::vector<ULONG> broadcasts()
|
||||
{
|
||||
auto data=ipv4Adapters();
|
||||
std::vector<ULONG> out;
|
||||
if(result!=NO_ERROR) return out;
|
||||
if(data.empty()) return out;
|
||||
for(auto a=(IP_ADAPTER_ADDRESSES*)data.data();a;a=a->Next)
|
||||
if(a->OperStatus==IfOperStatusUp)
|
||||
for(auto u=a->FirstUnicastAddress;u;u=u->Next)
|
||||
@@ -47,9 +77,48 @@ std::vector<ULONG> broadcasts()
|
||||
return out;
|
||||
}
|
||||
}
|
||||
void lan::wakeFilesPeer(const std::string &id)
|
||||
{
|
||||
const auto settings=Json::parse(unprotect(readFile(dataDirectory()/L"lan-pairing.bin",256*1024)));
|
||||
const auto &trusted=settings.at("trusted");
|
||||
if(!settings.value("enabled",false) || !trusted.contains(id))
|
||||
throw std::runtime_error("Enable KSwitcher LAN and select a paired PC.");
|
||||
const auto packet=wakePacket(trusted.at(id).value("wakeMac",""));
|
||||
if(!packet) throw std::runtime_error("No saved MAC address. Run updated KSwitcher on this PC while it is online once.");
|
||||
const auto destinations=broadcasts();
|
||||
if(destinations.empty()) throw std::runtime_error("No local IPv4 network is available.");
|
||||
Network network;
|
||||
WinSocket socket{::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)};
|
||||
if(socket.value==INVALID_SOCKET) socketError();
|
||||
const BOOL broadcast=TRUE;
|
||||
if(setsockopt(socket.value,SOL_SOCKET,SO_BROADCAST,reinterpret_cast<const char*>(&broadcast),sizeof(broadcast)))
|
||||
socketError();
|
||||
bool sent=false;
|
||||
int error=WSAEHOSTUNREACH;
|
||||
for(const auto ip:destinations)
|
||||
{
|
||||
sockaddr_in destination{};
|
||||
destination.sin_family=AF_INET;
|
||||
destination.sin_port=htons(9);
|
||||
destination.sin_addr.s_addr=ip;
|
||||
if(sendto(socket.value,reinterpret_cast<const char*>(packet->data()),static_cast<int>(packet->size()),0,
|
||||
reinterpret_cast<const sockaddr*>(&destination),sizeof(destination))==SOCKET_ERROR)
|
||||
error=WSAGetLastError();
|
||||
else sent=true;
|
||||
}
|
||||
if(!sent) throw std::system_error(error,std::system_category());
|
||||
}
|
||||
|
||||
struct LanService::Impl
|
||||
{
|
||||
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; };
|
||||
struct Peer
|
||||
{
|
||||
std::string name,epoch;
|
||||
sockaddr_in address{};
|
||||
uint64_t seen{},verified{};
|
||||
bool files{};
|
||||
bool present(uint64_t now)const{return verified && now-verified<lan::PeerLifetime;}
|
||||
};
|
||||
std::filesystem::path path;
|
||||
std::string id,epoch=lan::randomHex(16),name=hostName(),status="Disabled.";
|
||||
std::map<std::string,Peer> peers;
|
||||
@@ -66,9 +135,12 @@ struct LanService::Impl
|
||||
std::mutex mutex;
|
||||
std::thread worker;
|
||||
bool shareInput{};
|
||||
bool inputPaused{};
|
||||
std::mutex transportMutex;
|
||||
bool resetInputChannels{};
|
||||
std::string inputPeer;
|
||||
int inputEdge=1;
|
||||
std::atomic<bool> inputConnected{false},abortInput{false};
|
||||
std::atomic<bool> abortInput{false};
|
||||
std::atomic<uint64_t> inputEpoch{0};
|
||||
std::atomic<uint64_t> inputConfiguration{0};
|
||||
std::atomic<bool> layoutChanged{false};
|
||||
@@ -78,9 +150,13 @@ struct LanService::Impl
|
||||
std::map<std::string,uint64_t> inputReady;
|
||||
std::unique_ptr<lan::InputMesh> router;
|
||||
std::string inputStatus="Input sharing disabled.";
|
||||
size_t inputConnectedPeers{}, inputOnlinePeers{};
|
||||
bool inputWorkerStopped{};
|
||||
bool inputNeedsHelp{};
|
||||
HWND inputWindow{};std::atomic<bool> inputNotification{false};
|
||||
explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window)
|
||||
lan::LanClients clients;
|
||||
explicit Impl(const std::filesystem::path &root,HWND window,bool paused)
|
||||
: path(root/L"lan-pairing.bin"),inputPaused(paused),inputWindow(window),clients(root)
|
||||
{
|
||||
if(std::filesystem::exists(path))
|
||||
{
|
||||
@@ -104,7 +180,105 @@ struct LanService::Impl
|
||||
configureRouter();
|
||||
if(enabled) start();
|
||||
}
|
||||
~Impl() { stop(); }
|
||||
~Impl() { clients.stop(); stop(); }
|
||||
void startClients()
|
||||
{
|
||||
clients.start([this](const Json &request, const auto &allowed, const auto &send) {
|
||||
const auto action = request.at("action").get<std::string>();
|
||||
auto reply = [&](const Json &result) {
|
||||
const auto text = result.dump();
|
||||
send(text.data(), DWORD(text.size()));
|
||||
};
|
||||
lan::FilesPeer target;
|
||||
std::string local, key;
|
||||
auto machines = Json::array();
|
||||
{
|
||||
std::lock_guard gate(commandGate);
|
||||
std::lock_guard lock(mutex);
|
||||
const auto now = GetTickCount64();
|
||||
const auto reachable = [&](const Peer &peer) {
|
||||
return enabled && peer.files && peer.verified && now - peer.verified < lan::PeerLifetime;
|
||||
};
|
||||
if (action == "peers")
|
||||
{
|
||||
refreshFiles = true;
|
||||
for (const auto &[peer, pair] : trusted.items())
|
||||
{
|
||||
const auto found = peers.find(peer);
|
||||
machines.push_back({{"id", peer}, {"name", pair.at("name")},
|
||||
{"online", found != peers.end() && reachable(found->second)}});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (action != "drives" && action != "list" && action != "download")
|
||||
throw std::runtime_error("Unsupported LAN client operation.");
|
||||
const auto peer = request.at("peer").get<std::string>();
|
||||
const auto found = peers.find(peer);
|
||||
if (!trusted.contains(peer) || found == peers.end() || !reachable(found->second))
|
||||
throw std::runtime_error("The paired computer is offline or file browsing is unavailable.");
|
||||
char address[INET_ADDRSTRLEN]{};
|
||||
auto ip = found->second.address.sin_addr;
|
||||
if (!InetNtopA(AF_INET, &ip, address, sizeof(address)))
|
||||
throw std::runtime_error("The paired computer has no usable address.");
|
||||
target = {peer, address, wide(found->second.name), lan::FilesPort, true};
|
||||
local = id;
|
||||
key = trusted.at(peer).at("key").get<std::string>();
|
||||
}
|
||||
}
|
||||
if (action == "peers")
|
||||
{
|
||||
reply(machines);
|
||||
return;
|
||||
}
|
||||
lan::FilesConnection connection(target, local, key);
|
||||
if (action == "drives")
|
||||
{
|
||||
const auto result = connection.call({{"action", "drives"}});
|
||||
lan::checkFileReply(result);
|
||||
reply(result.at("drives"));
|
||||
return;
|
||||
}
|
||||
const auto path = lan::filePath(request.at("path"));
|
||||
if (action == "list")
|
||||
{
|
||||
auto page = connection.call(lan::fileRequest("list", path));
|
||||
auto entries = Json::array();
|
||||
size_t bytes{};
|
||||
for (;;)
|
||||
{
|
||||
lan::checkFileReply(page);
|
||||
for (auto &entry : page.at("entries"))
|
||||
{
|
||||
bytes += entry.dump().size() + 1;
|
||||
if (bytes > 8 * 1024 * 1024) throw std::runtime_error("The remote directory listing is too large.");
|
||||
entries.push_back(std::move(entry));
|
||||
}
|
||||
if (!page.at("more").get<bool>()) break;
|
||||
allowed();
|
||||
page = connection.call({{"action", "listNext"}});
|
||||
}
|
||||
reply(entries);
|
||||
return;
|
||||
}
|
||||
const auto file = connection.call(lan::fileRequest("stat", path));
|
||||
lan::checkFileReply(file);
|
||||
auto open = lan::fileRequest("openRead", path);
|
||||
open["size"] = file.at("size");
|
||||
open["modified"] = file.at("modified");
|
||||
lan::checkFileReply(connection.call(open));
|
||||
reply({{"size", file.at("size")}});
|
||||
for (;;)
|
||||
{
|
||||
allowed();
|
||||
const auto chunk = connection.call({{"action", "read"}});
|
||||
lan::checkFileReply(chunk);
|
||||
const auto &data = chunk.at("data").get_binary();
|
||||
send(data.data(), DWORD(data.size()));
|
||||
if (data.empty()) break;
|
||||
}
|
||||
});
|
||||
}
|
||||
void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted},
|
||||
{"shareInput",shareInput},{"shareLogs",shareLogs},{"inputPeer",inputPeer},{"inputEdge",inputEdge},{"positions",positions}}))); }
|
||||
bool queue(const std::string &peer,lan::InputFrame frame)
|
||||
@@ -122,13 +296,32 @@ struct LanService::Impl
|
||||
{
|
||||
if(router)router->cancel(GetTickCount64());
|
||||
router.reset();++inputConfiguration;
|
||||
if(enabled&&shareInput){
|
||||
if(enabled&&shareInput&&!inputPaused){
|
||||
std::map<std::string,POINT> layout;for(auto &[peer,cell]:positions.items())if(trusted.contains(peer))layout[peer]={cell[0].get<LONG>(),cell[1].get<LONG>()};
|
||||
router=std::make_unique<lan::InputMesh>(id,lan::windowsInputEnvironment(),std::move(layout),[this](const auto &peer,auto f){return queue(peer,f);});
|
||||
}
|
||||
inputStatus=enabled&&shareInput?"Connecting input channels...":"Input sharing disabled.";
|
||||
observedRevision=0;
|
||||
}
|
||||
void setInputPaused(bool paused)
|
||||
{
|
||||
// A poll can own a batch outside the queues. Finish that poll before
|
||||
// cancelling the router and discarding both directions of the old session.
|
||||
std::lock_guard transportLock(transportMutex);
|
||||
std::lock_guard lock(mutex);
|
||||
if (inputPaused == paused) return;
|
||||
inputPaused = paused;
|
||||
configureRouter();
|
||||
if (paused)
|
||||
{
|
||||
resetInputChannels = true;
|
||||
std::lock_guard queueLock(inputMutex);
|
||||
inputIn.clear();
|
||||
inputOut.clear();
|
||||
inputReady.clear();
|
||||
inputConnectedPeers = inputOnlinePeers = 0;
|
||||
}
|
||||
}
|
||||
bool takeChange()
|
||||
{
|
||||
auto revision=router?router->revision():0;auto configuration=inputConfiguration.load();
|
||||
@@ -151,6 +344,7 @@ struct LanService::Impl
|
||||
void start()
|
||||
{
|
||||
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
|
||||
updateInputStatus(0,0,"Waiting for paired computers...",false);
|
||||
worker=std::thread([this]{ run(); });
|
||||
}
|
||||
void stop()
|
||||
@@ -158,17 +352,38 @@ struct LanService::Impl
|
||||
if(router)router->cancel(GetTickCount64());
|
||||
stopping=true;
|
||||
if(worker.joinable()) worker.join();
|
||||
inputConnected=false;++inputEpoch;
|
||||
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
|
||||
std::lock_guard lock(mutex); pending.reset(); peers.clear();clipboard=std::make_unique<lan::ClipboardExchange>(id);
|
||||
transfers=std::make_unique<lan::ClipboardExchange>(id,"file-transfer");incomingFiles.clear();logDownload.reset();
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,0,FALSE);
|
||||
}
|
||||
void updateInputStatus(size_t connected,size_t online,std::string status,bool needsHelp,bool stopped=false)
|
||||
{
|
||||
bool changed;
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
changed=connected!=inputConnectedPeers||online!=inputOnlinePeers||stopped!=inputWorkerStopped;
|
||||
inputConnectedPeers=connected;
|
||||
inputOnlinePeers=online;
|
||||
inputWorkerStopped=stopped;
|
||||
inputStatus=std::move(status);
|
||||
inputNeedsHelp=needsHelp;
|
||||
}
|
||||
if(changed&&inputWindow)PostMessageW(inputWindow,LanInputStatusMessage,0,0);
|
||||
}
|
||||
void send(SOCKET socket,const sockaddr_in &address,const Json &j)
|
||||
{
|
||||
auto bytes=j.dump(); if(bytes.size()>2048) return;
|
||||
sendto(socket,bytes.data(),int(bytes.size()),0,(const sockaddr*)&address,sizeof(address));
|
||||
}
|
||||
Json discoveryAnnouncement(bool filesListening)const
|
||||
{
|
||||
auto hello=lan::envelope("hello",id);
|
||||
hello["name"]=name;
|
||||
hello["epoch"]=epoch;
|
||||
hello["clipboardSession"]=clipboard->session();
|
||||
hello["fileSession"]=transfers->session();
|
||||
hello["filesBrowse"]=filesListening;
|
||||
return hello;
|
||||
}
|
||||
std::string heartbeat(const std::string &from,const std::string &to,const std::string &a,const std::string &b)
|
||||
{ return "KSwitcher LAN v1|presence|"+from+"|"+to+"|"+a+"|"+b; }
|
||||
void receiveTransfers(uint64_t now)
|
||||
@@ -180,10 +395,7 @@ struct LanService::Impl
|
||||
auto end=std::find(item.bytes.begin(),item.bytes.end(),0);
|
||||
if(end!=item.bytes.begin() && end!=item.bytes.end() && end-item.bytes.begin()<=1024 &&
|
||||
item.bytes.end()-end-1<=16*1024*1024)
|
||||
{
|
||||
incomingFiles.push_back(std::move(item));
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),TRUE);
|
||||
}
|
||||
}
|
||||
else if(item.app=="log-request" && item.bytes.size()==33)
|
||||
{
|
||||
@@ -206,7 +418,7 @@ struct LanService::Impl
|
||||
}
|
||||
transfers->deliveries.clear();
|
||||
}
|
||||
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now)
|
||||
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now,bool filesListening)
|
||||
{
|
||||
if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return;
|
||||
auto other=j.value("id",""); if(!lan::identifier(other)||other==id) return;
|
||||
@@ -217,21 +429,33 @@ struct LanService::Impl
|
||||
if(display.empty()||display.size()>128||!lan::identifier(session)||
|
||||
std::any_of(display.begin(),display.end(),[](unsigned char c){return c<32||c==127;})) return;
|
||||
// Discovery is untrusted and never grants input access.
|
||||
if(!peers.contains(other) && peers.size()>=64) return;
|
||||
const bool firstAnnouncement=!peers.contains(other);
|
||||
if(firstAnnouncement && peers.size()>=64) return;
|
||||
auto &peer=peers[other];
|
||||
// A fresh announcement rotates the challenge every three seconds; it
|
||||
// does not revoke a recent successful proof for the same address.
|
||||
// Only a valid presence response renews verified, so untrusted/replayed
|
||||
// announcements cannot extend its PeerLifetime expiry.
|
||||
if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0;
|
||||
const bool addressChanged=peer.address.sin_addr.s_addr!=address.sin_addr.s_addr;
|
||||
if(addressChanged) peer.verified=0;
|
||||
clipboard->peerSession(other,j.value("clipboardSession",""));
|
||||
transfers->peerSession(other,j.value("fileSession",""));
|
||||
peer.files=j.value("filesBrowse",false);
|
||||
peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now;
|
||||
if(trusted.contains(other))
|
||||
{
|
||||
// A returning peer can prove presence right away using our current challenge.
|
||||
if(firstAnnouncement) send(socket,address,discoveryAnnouncement(filesListening));
|
||||
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
|
||||
response["proof"]=lan::mac(trusted[other].at("key"),heartbeat(id,other,epoch,session));
|
||||
const auto &key=trusted[other].at("key");
|
||||
const auto challenge=heartbeat(id,other,epoch,session);
|
||||
response["proof"]=lan::mac(key,challenge);
|
||||
const auto wakeMac=wakeMacFor(address.sin_addr.s_addr);
|
||||
if(!wakeMac.empty())
|
||||
{
|
||||
response["wakeMac"]=wakeMac;
|
||||
response["wakeProof"]=lan::mac(key,challenge+"|wake|"+wakeMac);
|
||||
}
|
||||
send(socket,address,response);
|
||||
}
|
||||
return;
|
||||
@@ -260,7 +484,21 @@ struct LanService::Impl
|
||||
}
|
||||
if(type=="presence" && trusted.contains(other) && j.value("epoch","")==peer.epoch &&
|
||||
lan::equal(j.value("proof",""),lan::mac(trusted[other].at("key"),heartbeat(other,id,peer.epoch,epoch))))
|
||||
{ peer.verified=now; return; }
|
||||
{
|
||||
peer.verified=now;
|
||||
auto &entry=trusted.at(other);
|
||||
const auto wakeMac=j.value("wakeMac","");
|
||||
if(lan::wakePacket(wakeMac) && wakeMac!=entry.value("wakeMac","") &&
|
||||
lan::equal(j.value("wakeProof",""),
|
||||
lan::mac(entry.at("key"),heartbeat(other,id,peer.epoch,epoch)+"|wake|"+wakeMac)))
|
||||
{
|
||||
auto previous=entry;
|
||||
entry["wakeMac"]=wakeMac;
|
||||
try {save();}
|
||||
catch(const std::exception &){entry=std::move(previous);}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(pending && pending->peer==other)
|
||||
{
|
||||
for(const auto &response:pending->receive(j,now)) send(socket,address,response);
|
||||
@@ -325,14 +563,17 @@ struct LanService::Impl
|
||||
if(peers.contains(target))send(socket,peers.at(target).address,packet);
|
||||
});
|
||||
clipboardActive=clipboard->active()||transfers->active();
|
||||
if(shareInput)for(auto &[peer,entry]:trusted.items())
|
||||
endpoints.push_back({peer,entry.at("key"),peers.contains(peer)?peers.at(peer).address.sin_addr.s_addr:0});
|
||||
if(shareInput&&!inputPaused)for(auto &[peer,entry]:trusted.items())
|
||||
{
|
||||
const auto found=peers.find(peer);
|
||||
const bool discovered=found!=peers.end()&&found->second.present(now);
|
||||
endpoints.push_back({.id=peer,.key=entry.at("key"),
|
||||
.address=discovered?found->second.address.sin_addr.s_addr:0,.discovered=discovered});
|
||||
}
|
||||
if(refreshFiles.exchange(false) || now>=nextHello)
|
||||
{
|
||||
epoch=lan::randomHex(16); // Fresh challenge prevents replayed presence from staying online.
|
||||
auto hello=lan::envelope("hello",id); hello["name"]=name; hello["epoch"]=epoch;hello["clipboardSession"]=clipboard->session();
|
||||
hello["fileSession"]=transfers->session();
|
||||
hello["filesBrowse"]=filesListening;
|
||||
const auto hello=discoveryAnnouncement(filesListening);
|
||||
for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); }
|
||||
nextHello=now+3000;
|
||||
}
|
||||
@@ -348,10 +589,17 @@ struct LanService::Impl
|
||||
}
|
||||
}
|
||||
std::vector<lan::RoutedInput> out,in;
|
||||
std::unique_lock transportLock(transportMutex);
|
||||
if (resetInputChannels)
|
||||
{
|
||||
hub.poll({}, {}, in, now);
|
||||
resetInputChannels = false;
|
||||
}
|
||||
if (inputPaused) endpoints.clear();
|
||||
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
|
||||
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
|
||||
hub.poll(endpoints,out,in,now);
|
||||
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
|
||||
auto readyPeers=hub.ready();const auto connected=readyPeers.size();
|
||||
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
|
||||
for(auto &frame:in){
|
||||
if(!inputIn.empty()&&inputIn.back().peer==frame.peer&&inputIn.back().epoch==frame.epoch){
|
||||
@@ -364,8 +612,11 @@ struct LanService::Impl
|
||||
}
|
||||
if(!in.empty()&&inputWindow&&!inputNotification.exchange(true))
|
||||
if(!PostMessageW(inputWindow,LanInputReadyMessage,0,0))inputNotification=false;
|
||||
{std::lock_guard lock(mutex);inputStatus=hub.status();inputNeedsHelp=hub.needsHelp();}
|
||||
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,!endpoints.empty()||clipboardActive?5000:100000};
|
||||
const auto online=hub.onlinePeers();
|
||||
updateInputStatus(connected,online,online||endpoints.empty()?hub.status():
|
||||
"All paired PCs are offline. Waiting for LAN discovery.",hub.needsHelp());
|
||||
transportLock.unlock();
|
||||
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,online||clipboardActive?5000:100000};
|
||||
int ready=select(0,&read,nullptr,nullptr,&delay);
|
||||
if(ready==SOCKET_ERROR) throw std::runtime_error("LAN discovery socket failed.");
|
||||
if(ready>0) for(int count=0;count<64;++count)
|
||||
@@ -378,23 +629,28 @@ struct LanService::Impl
|
||||
auto j=Json::parse(buffer,buffer+received);
|
||||
if(j.value("type","")=="input-udp"){
|
||||
bool allowed=false;auto peer=j.value("id","");
|
||||
{std::lock_guard lock(mutex);allowed=shareInput&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
|
||||
{std::lock_guard lock(mutex);allowed=shareInput&&!inputPaused&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
|
||||
if(allowed)hub.receiveDatagram(j,GetTickCount64());
|
||||
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64());}
|
||||
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64(),filesListening);}
|
||||
}
|
||||
catch(const Json::exception &) {} // Malformed network data cannot interrupt discovery.
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(const std::exception &e) { std::lock_guard lock(mutex); status=std::string("LAN stopped: ")+e.what(); }
|
||||
inputConnected=false;++inputEpoch;
|
||||
{std::lock_guard lock(mutex);if(shareInput)inputStatus="Input connection closed.";}
|
||||
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
|
||||
++inputEpoch;
|
||||
updateInputStatus(0,0,"Input connection closed.",false,true);
|
||||
if(socket!=INVALID_SOCKET) closesocket(socket);
|
||||
if(winsock) WSACleanup();
|
||||
}
|
||||
std::mutex commandGate;
|
||||
Bytes command(const Bytes &input)
|
||||
{
|
||||
std::lock_guard commandLock(commandGate);
|
||||
auto j=Json::parse(input); auto action=j.value("action","status");
|
||||
if (action == "trustedClients" || action == "trustClient" || action == "removeClient")
|
||||
return encoded(clients.settings(action, j));
|
||||
if(action=="enable")
|
||||
{
|
||||
stop();
|
||||
@@ -403,7 +659,7 @@ struct LanService::Impl
|
||||
configureRouter();
|
||||
if(enabled) start(); else status="Disabled. No discovery sockets or worker thread.";
|
||||
}
|
||||
std::lock_guard lock(mutex);
|
||||
std::unique_lock lock(mutex);
|
||||
auto now=GetTickCount64();
|
||||
if(action=="filesPeers") refreshFiles=true;
|
||||
if(action=="shareLogs")
|
||||
@@ -417,12 +673,16 @@ struct LanService::Impl
|
||||
if(action=="sendFile" || action=="requestLog")
|
||||
{
|
||||
auto peer=j.at("peer").get<std::string>();
|
||||
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
|
||||
now-peers.at(peer).verified>=lan::PeerLifetime)
|
||||
throw std::runtime_error("Select an online paired computer.");
|
||||
if(!transfers->hasSession(peer))throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers.");
|
||||
const auto checkPeer = [&] {
|
||||
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).present(now))
|
||||
throw std::runtime_error("Select an online paired computer.");
|
||||
if(!transfers->hasSession(peer))
|
||||
throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers.");
|
||||
};
|
||||
checkPeer();
|
||||
if(action=="sendFile")
|
||||
{
|
||||
lock.unlock();
|
||||
auto file=std::filesystem::path(wide(j.at("path").get<std::string>()));
|
||||
auto name=utf8(file.filename().wstring());
|
||||
if(name.empty()||name.size()>1024)throw std::runtime_error("Invalid file name.");
|
||||
@@ -432,6 +692,9 @@ struct LanService::Impl
|
||||
if(std::filesystem::file_size(file)>fileLimit)throw std::runtime_error("File size limit is 16 MiB.");
|
||||
auto bytes=readFile(file,fileLimit);
|
||||
payload.insert(payload.end(),bytes.begin(),bytes.end());
|
||||
lock.lock();
|
||||
now=GetTickCount64();
|
||||
checkPeer();
|
||||
transfers->queue({peer},std::move(payload),"file",now);
|
||||
return encoded({{"queued",true}});
|
||||
}
|
||||
@@ -463,17 +726,24 @@ struct LanService::Impl
|
||||
}
|
||||
if(action=="saveFile"||action=="discardFile")
|
||||
{
|
||||
auto found=std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){
|
||||
return file.id==j.at("id").get<std::string>() && file.peer==j.at("peer").get<std::string>();
|
||||
});
|
||||
const auto id=j.at("id").get<std::string>(), peer=j.at("peer").get<std::string>();
|
||||
const auto findFile = [&] {
|
||||
return std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){
|
||||
return file.id==id && file.peer==peer;
|
||||
});
|
||||
};
|
||||
auto found=findFile();
|
||||
if(found==incomingFiles.end())throw std::runtime_error("This file is no longer available.");
|
||||
if(action=="saveFile")
|
||||
{
|
||||
auto start=std::find(found->bytes.begin(),found->bytes.end(),0)+1;
|
||||
atomicWrite(wide(j.at("path").get<std::string>()),Bytes(start,found->bytes.end()));
|
||||
const Bytes bytes(start,found->bytes.end());
|
||||
lock.unlock();
|
||||
atomicWrite(wide(j.at("path").get<std::string>()),bytes);
|
||||
lock.lock();
|
||||
found=findFile();
|
||||
}
|
||||
incomingFiles.erase(found);
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
|
||||
if(found!=incomingFiles.end()) incomingFiles.erase(found);
|
||||
}
|
||||
if(action=="position")
|
||||
{
|
||||
@@ -520,15 +790,14 @@ struct LanService::Impl
|
||||
trusted.erase(peer);positions.erase(peer);if(trusted.empty())shareInput=false;
|
||||
try{save();}catch(...){trusted=std::move(oldTrusted);positions=std::move(oldPositions);shareInput=oldSharing;throw;}
|
||||
std::erase_if(incomingFiles,[&](const auto &file){return file.peer==peer;});
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
|
||||
if(logDownload && logDownload->peer==peer)logDownload.reset();
|
||||
if(pending&&pending->peer==peer)pending.reset();
|
||||
configureRouter();
|
||||
status="Pair removed on this computer.";
|
||||
}
|
||||
Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()},
|
||||
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnected.load()},
|
||||
{"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
|
||||
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnectedPeers!=0},
|
||||
{"inputStatus",inputPaused?"Input processing paused in the tray.":enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",!inputPaused&&enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
|
||||
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
|
||||
result["shareLogs"]=shareLogs;
|
||||
result["files"]=Json::array();
|
||||
@@ -548,7 +817,7 @@ struct LanService::Impl
|
||||
if(action=="filesPeers" && !trusted.contains(peer)) continue;
|
||||
char ip[INET_ADDRSTRLEN]{}; InetNtopA(AF_INET,(void*)&p.address.sin_addr,ip,sizeof(ip));
|
||||
result["peers"].push_back({{"id",peer},{"name",p.name},{"address",ip},{"paired",trusted.contains(peer)},
|
||||
{"verified",p.verified && now-p.verified<lan::PeerLifetime},{"online",true},
|
||||
{"verified",p.present(now)},{"online",true},
|
||||
{"fileTransfer",transfers->hasSession(peer)},{"filesBrowse",p.files}});
|
||||
}
|
||||
for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer))
|
||||
@@ -556,9 +825,10 @@ struct LanService::Impl
|
||||
return encoded(result);
|
||||
}
|
||||
};
|
||||
LanService::LanService(const std::filesystem::path &path,HWND window) : impl(std::make_unique<Impl>(path,window)) {}
|
||||
LanService::LanService(const std::filesystem::path &path,HWND window,bool paused) : impl(std::make_unique<Impl>(path,window,paused)) {}
|
||||
LanService::~LanService()=default;
|
||||
Bytes LanService::command(const Bytes &command) { return impl->command(command); }
|
||||
void LanService::startClients() { impl->startClients(); }
|
||||
bool LanService::clipboardEnabled()const
|
||||
{
|
||||
std::lock_guard lock(impl->mutex);
|
||||
@@ -580,7 +850,15 @@ std::vector<LanClipboard> LanService::takeClipboard()
|
||||
result.push_back({d.peer,impl->trusted.at(d.peer).at("name"),d.app,std::move(d.bytes),d.sequence});
|
||||
impl->clipboard->deliveries.clear();return result;
|
||||
}
|
||||
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput;}
|
||||
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput&&!impl->inputPaused;}
|
||||
void LanService::setInputPaused(bool paused){impl->setInputPaused(paused);}
|
||||
LanInputConnections LanService::inputConnections()const
|
||||
{
|
||||
std::lock_guard lock(impl->mutex);
|
||||
if(!inputEnabled())return {};
|
||||
const auto paired=impl->trusted.size();
|
||||
return {std::min(impl->inputConnectedPeers,paired),std::min(impl->inputOnlinePeers,paired),paired,impl->inputWorkerStopped};
|
||||
}
|
||||
bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);}
|
||||
bool LanService::keyboard(const KBDLLHOOKSTRUCT &k,bool down){return impl->router&&impl->router->keyboard(k,down,GetTickCount64());}
|
||||
bool LanService::mouse(UINT message,const MSLLHOOKSTRUCT &m,bool allowEnter){return impl->router&&impl->router->mouse(message,m,GetTickCount64(),allowEnter);}
|
||||
|
||||
@@ -5,22 +5,32 @@
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69;
|
||||
inline constexpr UINT LanFilesChangedMessage=WM_APP+70;
|
||||
inline constexpr UINT LanUpdateRequestedMessage=WM_APP+90;
|
||||
inline constexpr UINT LanInputStatusMessage=WM_APP+91;
|
||||
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
|
||||
struct LanInputConnections
|
||||
{
|
||||
size_t connected{}, online{}, paired{};
|
||||
bool stopped{};
|
||||
bool reconnecting()const{return !stopped&&connected<online;}
|
||||
bool operator==(const LanInputConnections &) const = default;
|
||||
};
|
||||
// Discovery, pairing and optional encrypted input within the resident process.
|
||||
class LanService
|
||||
{
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl;
|
||||
public:
|
||||
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr);
|
||||
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr, bool inputPaused=false);
|
||||
~LanService();
|
||||
Bytes command(const Bytes &);
|
||||
void startClients();
|
||||
bool clipboardEnabled() const;
|
||||
void publishClipboard(Bytes, const std::string &);
|
||||
std::vector<LanClipboard> takeClipboard();
|
||||
bool inputEnabled() const;
|
||||
void setInputPaused(bool);
|
||||
LanInputConnections inputConnections() const;
|
||||
bool tickInput(bool allowEnter = true);
|
||||
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
|
||||
bool mouse(UINT, const MSLLHOOKSTRUCT &, bool allowEnter);
|
||||
|
||||
+25
-11
@@ -213,6 +213,7 @@ bool InputChannel::adopt(uintptr_t accepted,uint64_t now)
|
||||
impl->connecting=false;impl->begin(now);impl->socket=SOCKET(accepted);return true;
|
||||
}
|
||||
bool InputChannel::ready()const{return impl->authenticated;}
|
||||
bool InputChannel::handshaking()const{return impl->socket!=INVALID_SOCKET&&!impl->authenticated;}
|
||||
uint64_t InputChannel::generation()const{return impl->changed;}
|
||||
std::string InputChannel::status()const{
|
||||
return impl->lastError.empty() ? impl->state : impl->lastError+" Retrying automatically.";
|
||||
@@ -221,7 +222,16 @@ void InputChannel::disconnect(){impl->reset(GetTickCount64(),"Input disconnected
|
||||
std::string InputChannel::transport()const{return impl->reverse?"reverse TCP":"direct TCP";}
|
||||
struct InputHub::Impl
|
||||
{
|
||||
struct Link { InputEndpoint endpoint;std::unique_ptr<InputChannel> channel;std::unique_ptr<InputDatagram> udp;uint64_t generation{},epoch{},since{},failedSince{};bool udpReady{};std::string lastState; };
|
||||
struct Link
|
||||
{
|
||||
InputEndpoint endpoint;
|
||||
std::unique_ptr<InputChannel> channel;
|
||||
std::unique_ptr<InputDatagram> udp;
|
||||
uint64_t generation{},epoch{},since{},failedSince{};
|
||||
bool udpReady{};
|
||||
std::string lastState;
|
||||
bool ready()const{return channel->ready()||udp->ready();}
|
||||
};
|
||||
struct Pending {SOCKET socket;uint32_t address;uint64_t since;};
|
||||
std::string local;uint16_t port;SOCKET listener=INVALID_SOCKET;
|
||||
std::map<std::string,Link> links;std::vector<Pending> pending;uint64_t epoch{},retry{};
|
||||
@@ -235,17 +245,18 @@ struct InputHub::Impl
|
||||
currentTime=now;
|
||||
for(auto it=links.begin();it!=links.end();){
|
||||
auto match=std::find_if(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id==it->first&&e.key==it->second.endpoint.key&&e.port==it->second.endpoint.port;});
|
||||
if(match==endpoints.end())it=links.erase(it);else ++it;
|
||||
// Discovery gates new attempts. An authenticated connection can outlive discovery.
|
||||
if(match==endpoints.end()||(!match->discovered&&!it->second.ready()))it=links.erase(it);else ++it;
|
||||
}
|
||||
for(auto &e:endpoints)if(e.id!=local&&!links.contains(e.id)){
|
||||
for(auto &e:endpoints)if(e.discovered&&e.id!=local&&!links.contains(e.id)){
|
||||
Link link;link.endpoint=e;link.channel=std::make_unique<InputChannel>(local,e.id,e.key,0,e.port,true);
|
||||
link.udp=std::make_unique<InputDatagram>(local,e.id,e.key);link.since=link.failedSince=now;link.epoch=++epoch;links.emplace(e.id,std::move(link));
|
||||
}
|
||||
// Discovery is a hint, not the lifetime of authenticated input sessions.
|
||||
// Keep the last usable address across missed announcements. A new address
|
||||
// is used only once a channel is down, never to tear down working input.
|
||||
for(auto &e:endpoints){if(e.id==local)continue;auto &link=links.at(e.id);
|
||||
if(e.address&&!link.channel->ready()&&e.address!=link.endpoint.address){
|
||||
for(auto &e:endpoints){if(!e.discovered||e.id==local)continue;auto &link=links.at(e.id);
|
||||
if(e.address&&!link.ready()&&e.address!=link.endpoint.address){
|
||||
link.channel->disconnect();link.endpoint.address=e.address;
|
||||
}
|
||||
}
|
||||
@@ -279,14 +290,16 @@ struct InputHub::Impl
|
||||
}
|
||||
for(auto &[id,link]:links){
|
||||
std::vector<InputFrame> frames,received;for(auto &f:out)if(f.peer==id&&(!f.epoch||f.epoch==link.epoch))enqueueInput(frames,f.frame);
|
||||
if(sendDatagram&&!link.channel->ready()&&!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);link.channel->disconnect();frames.clear();}
|
||||
// Let an in-flight TCP connection finish or hit its own deadline.
|
||||
// Check before poll() so another TCP retry cannot starve UDP fallback.
|
||||
if(sendDatagram&&!link.channel->ready()&&!link.channel->handshaking()&&
|
||||
!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);frames.clear();}
|
||||
if(link.udp->active()){
|
||||
link.udp->poll(frames,received,now,sendDatagram);
|
||||
if(!link.udp->active()){link.since=now;link.channel->disconnect();received.clear();}
|
||||
}else link.channel->poll(link.endpoint.address,frames,received,now);
|
||||
if(link.udpReady!=link.udp->ready()){link.udpReady=link.udp->ready();link.epoch=++epoch;}
|
||||
bool ready=link.channel->ready()||link.udp->ready();
|
||||
if(ready)link.failedSince=link.since=now;
|
||||
if(link.ready())link.failedSince=link.since=now;
|
||||
auto state=link.udp->ready()?"Input connected via encrypted UDP.":link.udp->active()?"Trying encrypted UDP over discovery...":link.channel->ready()?"Input connected via "+link.channel->transport()+".":link.channel->status();
|
||||
if(state!=link.lastState){link.lastState=state;log(L"LAN input peer "+wide(id.substr(0,8))+L": "+wide(state));}
|
||||
if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;}
|
||||
@@ -297,7 +310,8 @@ struct InputHub::Impl
|
||||
InputHub::InputHub(std::string id,uint16_t port):impl(std::make_unique<Impl>(std::move(id),port)){}
|
||||
InputHub::~InputHub()=default;
|
||||
void InputHub::poll(const std::vector<InputEndpoint> &peers,const std::vector<RoutedInput> &out,std::vector<RoutedInput> &in,uint64_t now){impl->poll(peers,out,in,now);}
|
||||
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.channel->ready()||l.udp->ready())result[id]=l.epoch;return result;}
|
||||
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.ready())result[id]=l.epoch;return result;}
|
||||
size_t InputHub::onlinePeers()const{return impl->links.size();}
|
||||
std::string InputHub::status()const{
|
||||
auto count=ready().size();if(count==impl->links.size()&&count){
|
||||
std::string routes;for(auto &[id,l]:impl->links){if(!routes.empty())routes+=", ";routes+=id.substr(0,8)+": "+(l.udp->ready()?"encrypted UDP":l.channel->transport());}
|
||||
@@ -305,7 +319,7 @@ std::string InputHub::status()const{
|
||||
}
|
||||
if(needsHelp())return "Automatic connection attempts have not succeeded for every PC. Enable input on both PCs. Open Connection help for firewall commands.";
|
||||
if(!impl->error.empty())return impl->error;
|
||||
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready())return l.lastState;
|
||||
for(auto &[id,l]:impl->links)if(!l.ready())return l.lastState;
|
||||
return "Waiting for paired computers...";
|
||||
}
|
||||
void InputHub::disconnect(){for(auto &[id,l]:impl->links){l.channel->disconnect();l.udp->reset();l.since=impl->currentTime;}}
|
||||
@@ -318,7 +332,7 @@ void InputHub::receiveDatagram(const Json &j,uint64_t now){
|
||||
if(!active&&link.udp->active())link.channel->disconnect();
|
||||
}
|
||||
bool InputHub::needsHelp()const{
|
||||
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready()&&impl->currentTime-l.failedSince>=15000)return true;
|
||||
for(auto &[id,l]:impl->links)if(!l.ready()&&impl->currentTime-l.failedSince>=15000)return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -55,12 +55,19 @@ class InputChannel
|
||||
void poll(uint32_t peerAddress,const std::vector<InputFrame> &out,std::vector<InputFrame> &in,uint64_t now);
|
||||
bool adopt(uintptr_t socket,uint64_t now);
|
||||
bool ready() const;
|
||||
bool handshaking() const;
|
||||
uint64_t generation() const;
|
||||
std::string status() const;
|
||||
void disconnect();
|
||||
std::string transport()const;
|
||||
};
|
||||
struct InputEndpoint {std::string id,key;uint32_t address{};uint16_t port=45884;};
|
||||
struct InputEndpoint
|
||||
{
|
||||
std::string id,key;
|
||||
uint32_t address{};
|
||||
uint16_t port=45884;
|
||||
bool discovered=true;
|
||||
};
|
||||
struct RoutedInput {std::string peer;InputFrame frame;uint64_t epoch{};};
|
||||
class InputHub
|
||||
{
|
||||
@@ -70,6 +77,7 @@ class InputHub
|
||||
~InputHub();
|
||||
void poll(const std::vector<InputEndpoint> &,const std::vector<RoutedInput> &,std::vector<RoutedInput> &,uint64_t now);
|
||||
std::map<std::string,uint64_t> ready()const;
|
||||
size_t onlinePeers()const;
|
||||
std::string status()const;
|
||||
void disconnect();
|
||||
using SendDatagram=std::function<void(const std::string &,const Json &)>;
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
#pragma once
|
||||
#include "lan_pairing.h"
|
||||
#include <bcrypt.h>
|
||||
#include <sddl.h>
|
||||
#include <array>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
class LanClients
|
||||
{
|
||||
struct Handle
|
||||
{
|
||||
HANDLE value{};
|
||||
~Handle() { if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value); }
|
||||
explicit operator bool() const { return value && value != INVALID_HANDLE_VALUE; }
|
||||
};
|
||||
struct ClientImage
|
||||
{
|
||||
Handle file;
|
||||
std::wstring path;
|
||||
std::string digest;
|
||||
FILETIME modified{};
|
||||
explicit ClientImage(const std::wstring &filename)
|
||||
: file{CreateFileW(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_SEQUENTIAL_SCAN, nullptr)}
|
||||
{
|
||||
if (!file || GetFileType(file.value) != FILE_TYPE_DISK)
|
||||
throw std::runtime_error("Choose a readable executable.");
|
||||
wchar_t finalPath[32768];
|
||||
const auto length = GetFinalPathNameByHandleW(file.value, finalPath, DWORD(std::size(finalPath)), 0);
|
||||
if (!length || length >= std::size(finalPath) ||
|
||||
_wcsicmp(std::filesystem::path(std::wstring(finalPath, length)).extension().c_str(), L".exe") ||
|
||||
!GetFileTime(file.value, nullptr, nullptr, &modified))
|
||||
throw std::runtime_error("Choose a Windows .exe file.");
|
||||
path.assign(finalPath, length);
|
||||
|
||||
struct Hash
|
||||
{
|
||||
BCRYPT_HASH_HANDLE handle{};
|
||||
~Hash() { if (handle) BCryptDestroyHash(handle); }
|
||||
} hash;
|
||||
std::array<unsigned char, 65536> buffer{};
|
||||
std::array<unsigned char, 32> bytes{};
|
||||
if (BCryptCreateHash(BCRYPT_SHA256_ALG_HANDLE, &hash.handle, nullptr, 0, nullptr, 0, 0) < 0)
|
||||
throw std::runtime_error("Could not fingerprint the executable.");
|
||||
DWORD count{};
|
||||
do
|
||||
{
|
||||
if (!ReadFile(file.value, buffer.data(), DWORD(buffer.size()), &count, nullptr) ||
|
||||
(count && BCryptHashData(hash.handle, buffer.data(), count, 0) < 0))
|
||||
throw std::runtime_error("Could not fingerprint the executable.");
|
||||
} while (count);
|
||||
if (BCryptFinishHash(hash.handle, bytes.data(), ULONG(bytes.size()), 0) < 0)
|
||||
throw std::runtime_error("Could not fingerprint the executable.");
|
||||
for (auto byte : bytes)
|
||||
{
|
||||
digest += "0123456789abcdef"[byte >> 4];
|
||||
digest += "0123456789abcdef"[byte & 15];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const std::filesystem::path store;
|
||||
mutable std::mutex storeMutex;
|
||||
Handle stopped{CreateEventW(nullptr, TRUE, FALSE, nullptr)};
|
||||
std::jthread thread;
|
||||
bool io(HANDLE pipe, void *buffer, DWORD length, bool write) const
|
||||
{
|
||||
auto *cursor = static_cast<unsigned char *>(buffer);
|
||||
while (length)
|
||||
{
|
||||
Handle event{CreateEventW(nullptr, TRUE, FALSE, nullptr)};
|
||||
if (!event) return false;
|
||||
OVERLAPPED op{};
|
||||
op.hEvent = event.value;
|
||||
DWORD count{};
|
||||
const auto completed = write ? WriteFile(pipe, cursor, length, &count, &op) :
|
||||
ReadFile(pipe, cursor, length, &count, &op);
|
||||
if (!completed && (GetLastError() != ERROR_IO_PENDING || !wait(pipe, op, count, 10000))) return false;
|
||||
if (!count) return false;
|
||||
cursor += count;
|
||||
length -= count;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool wait(HANDLE pipe, OVERLAPPED &op, DWORD &count, DWORD timeout) const
|
||||
{
|
||||
const HANDLE events[]{stopped.value, op.hEvent};
|
||||
if (WaitForMultipleObjects(2, events, FALSE, timeout) != WAIT_OBJECT_0 + 1)
|
||||
{
|
||||
CancelIoEx(pipe, &op);
|
||||
GetOverlappedResult(pipe, &op, &count, TRUE);
|
||||
return false;
|
||||
}
|
||||
return GetOverlappedResult(pipe, &op, &count, FALSE) != FALSE;
|
||||
}
|
||||
bool writeFrame(HANDLE pipe, const void *buffer, DWORD length) const
|
||||
{
|
||||
return io(pipe, &length, sizeof(length), true) &&
|
||||
(!length || io(pipe, const_cast<void *>(buffer), length, true));
|
||||
}
|
||||
Json clients() const
|
||||
{
|
||||
return std::filesystem::exists(store) ? Json::parse(unprotect(readFile(store, 256 * 1024))) : Json::array();
|
||||
}
|
||||
using Rule = std::function<void()>;
|
||||
Rule authorize(HANDLE pipe) const
|
||||
{
|
||||
ULONG pid{};
|
||||
if (!GetNamedPipeClientProcessId(pipe, &pid))
|
||||
throw std::runtime_error("Could not identify the local client.");
|
||||
auto process = std::make_shared<Handle>();
|
||||
process->value = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, pid);
|
||||
wchar_t filename[32768];
|
||||
DWORD length = DWORD(std::size(filename));
|
||||
FILETIME started{}, exited{}, kernel{}, user{};
|
||||
if (!*process || !QueryFullProcessImageNameW(process->value, 0, filename, &length) ||
|
||||
!GetProcessTimes(process->value, &started, &exited, &kernel, &user))
|
||||
throw std::runtime_error("Could not identify the local client.");
|
||||
auto image = std::make_shared<ClientImage>(std::wstring(filename, length));
|
||||
if (CompareFileTime(&image->modified, &started) > 0)
|
||||
throw std::runtime_error("Restart the client after replacing its executable.");
|
||||
Rule check = [this, process, image] {
|
||||
if (WaitForSingleObject(stopped.value, 0) != WAIT_TIMEOUT ||
|
||||
WaitForSingleObject(process->value, 0) != WAIT_TIMEOUT)
|
||||
throw std::runtime_error("The local client disconnected.");
|
||||
std::lock_guard lock(storeMutex);
|
||||
for (const auto &entry : clients())
|
||||
if (!_wcsicmp(wide(entry.at("path").get<std::string>()).c_str(), image->path.c_str()) &&
|
||||
entry.at("sha256") == image->digest) return;
|
||||
throw std::runtime_error("Authorize this executable in KSwitcher → Computers → Trusted clients.");
|
||||
};
|
||||
check();
|
||||
return check;
|
||||
}
|
||||
struct LocalMemory
|
||||
{
|
||||
void *value{};
|
||||
~LocalMemory() { if (value) LocalFree(value); }
|
||||
};
|
||||
using Send = std::function<void(const void *, DWORD)>;
|
||||
using Route = std::function<void(const Json &, const Rule &, const Send &)>;
|
||||
void serve(const Route &route, const std::wstring &instance) const
|
||||
{
|
||||
HANDLE rawToken{};
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &rawToken)) return;
|
||||
Handle token{rawToken};
|
||||
DWORD size{};
|
||||
GetTokenInformation(token.value, TokenUser, nullptr, 0, &size);
|
||||
Bytes info(size);
|
||||
if (!size || !GetTokenInformation(token.value, TokenUser, info.data(), size, &size)) return;
|
||||
LPWSTR sid{};
|
||||
if (!ConvertSidToStringSidW(reinterpret_cast<TOKEN_USER *>(info.data())->User.Sid, &sid)) return;
|
||||
LocalMemory sidOwner{sid};
|
||||
const auto sddl = std::wstring(L"D:P(A;;GA;;;") + sid + L")";
|
||||
PSECURITY_DESCRIPTOR descriptor{};
|
||||
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(), SDDL_REVISION_1, &descriptor, nullptr)) return;
|
||||
LocalMemory descriptorOwner{descriptor};
|
||||
SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE};
|
||||
DWORD session{};
|
||||
if (!ProcessIdToSessionId(GetCurrentProcessId(), &session)) return;
|
||||
const auto name = L"\\\\.\\pipe\\KSwitcher.LAN.Clients.v1." + std::to_wstring(session) + instance;
|
||||
Handle pipe{CreateNamedPipeW(name.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
|
||||
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_REJECT_REMOTE_CLIENTS, 1, 65536, 65536, 0, &security)};
|
||||
if (!pipe) return;
|
||||
while (WaitForSingleObject(stopped.value, 0) == WAIT_TIMEOUT)
|
||||
{
|
||||
Handle event{CreateEventW(nullptr, TRUE, FALSE, nullptr)};
|
||||
if (!event) return;
|
||||
OVERLAPPED op{};
|
||||
op.hEvent = event.value;
|
||||
DWORD count{};
|
||||
if (!ConnectNamedPipe(pipe.value, &op))
|
||||
{
|
||||
const auto error = GetLastError();
|
||||
if (error == ERROR_NO_DATA)
|
||||
{
|
||||
DisconnectNamedPipe(pipe.value);
|
||||
continue;
|
||||
}
|
||||
if (error != ERROR_PIPE_CONNECTED &&
|
||||
(error != ERROR_IO_PENDING || !wait(pipe.value, op, count, INFINITE))) return;
|
||||
}
|
||||
try
|
||||
{
|
||||
DWORD length{};
|
||||
if (io(pipe.value, &length, sizeof(length), false) && length && length <= 16384)
|
||||
{
|
||||
std::string request(length, '\0');
|
||||
if (io(pipe.value, request.data(), length, false))
|
||||
{
|
||||
auto check = authorize(pipe.value);
|
||||
route(Json::parse(request), check, [&](const void *data, DWORD bytes) {
|
||||
check();
|
||||
if (!writeFrame(pipe.value, data, bytes)) throw std::runtime_error("The local client disconnected.");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
const auto error = Json{{"error", e.what()}}.dump(-1, ' ', false, Json::error_handler_t::replace);
|
||||
writeFrame(pipe.value, error.data(), DWORD(error.size()));
|
||||
}
|
||||
// Let the client consume the final response before recycling the pipe.
|
||||
char acknowledgement{};
|
||||
io(pipe.value, &acknowledgement, 1, false);
|
||||
DisconnectNamedPipe(pipe.value);
|
||||
}
|
||||
}
|
||||
public:
|
||||
explicit LanClients(const std::filesystem::path &root) : store(root / L"lan-clients.bin") {}
|
||||
~LanClients() { if (stopped) SetEvent(stopped.value); }
|
||||
void start(Route route, std::wstring instance = {})
|
||||
{
|
||||
if (stopped) thread = std::jthread([this, route = std::move(route), instance = std::move(instance)] {
|
||||
serve(route, instance);
|
||||
});
|
||||
}
|
||||
void stop() { if (stopped) SetEvent(stopped.value); if (thread.joinable()) thread.join(); }
|
||||
Json settings(const std::string &action, const Json &request) const
|
||||
{
|
||||
std::lock_guard lock(storeMutex);
|
||||
auto entries = clients();
|
||||
if (action == "trustedClients") return entries;
|
||||
const auto path = wide(request.at("path").get<std::string>());
|
||||
if (action == "trustClient")
|
||||
{
|
||||
ClientImage image(path);
|
||||
std::erase_if(entries.get_ref<Json::array_t &>(), [&](const auto &entry) {
|
||||
return !_wcsicmp(wide(entry.at("path").template get<std::string>()).c_str(), image.path.c_str());
|
||||
});
|
||||
if (entries.size() >= 64) throw std::runtime_error("The trusted client list is full.");
|
||||
entries.push_back({{"path", utf8(image.path)}, {"sha256", image.digest}});
|
||||
}
|
||||
else
|
||||
{
|
||||
std::erase_if(entries.get_ref<Json::array_t &>(), [&](const auto &entry) {
|
||||
return !_wcsicmp(wide(entry.at("path").template get<std::string>()).c_str(), path.c_str());
|
||||
});
|
||||
}
|
||||
const auto text = entries.dump();
|
||||
atomicWrite(store, protect(Bytes(text.begin(), text.end())));
|
||||
return entries;
|
||||
}
|
||||
};
|
||||
}
|
||||
+52
-14
@@ -13,7 +13,20 @@ class ClipboardExchange
|
||||
{
|
||||
static constexpr size_t Limit=32*1024*1024, Chunk=480, Window=32;
|
||||
struct Item {std::string id,app;Bytes bytes;};
|
||||
struct Sending {std::deque<std::shared_ptr<Item>> queue;size_t ack{};bool begun{};uint64_t last{},progress{};};
|
||||
struct Sending
|
||||
{
|
||||
std::deque<std::shared_ptr<Item>> queue;
|
||||
size_t ack{}, sentUpTo{};
|
||||
bool begun{};
|
||||
uint64_t retryAt{}, progress{};
|
||||
void reset(uint64_t now)
|
||||
{
|
||||
ack=sentUpTo=0;
|
||||
begun=false;
|
||||
retryAt=0;
|
||||
progress=now;
|
||||
}
|
||||
};
|
||||
struct Receiving {std::string id,app;Bytes bytes;size_t size{};uint64_t last{};DWORD sequence{};};
|
||||
std::string local, type, domain, boot=randomHex(16);
|
||||
std::map<std::string,std::string> sessions;
|
||||
@@ -55,12 +68,12 @@ class ClipboardExchange
|
||||
if(s.queue.empty())return;
|
||||
bool reset=s.queue.front()->app.starts_with(prefix);
|
||||
std::erase_if(s.queue,[&](const auto &item){return item->app.starts_with(prefix);});
|
||||
if(reset){s.ack=0;s.begun=false;s.last=0;s.progress=GetTickCount64();}
|
||||
if(reset)s.reset(GetTickCount64());
|
||||
}
|
||||
void peerSession(const std::string &peer,const std::string &value){
|
||||
if(!identifier(value))return;
|
||||
if(sessions.contains(peer)&&sessions.at(peer)!=value){
|
||||
auto found=sending.find(peer);if(found!=sending.end()){found->second.ack=0;found->second.begun=false;found->second.last=0;}
|
||||
auto found=sending.find(peer);if(found!=sending.end())found->second.reset(found->second.progress);
|
||||
if(type!="clipboard"){
|
||||
auto previous=receiving.find(peer);
|
||||
if(previous!=receiving.end()){incomingBytes-=previous->second.size;receiving.erase(previous);}
|
||||
@@ -76,7 +89,7 @@ class ClipboardExchange
|
||||
for(auto &[peer,s]:sending)for(auto &item:s.queue)if(counted.insert(item.get()).second)total+=item->bytes.size();
|
||||
if(total>2*Limit)throw std::runtime_error("LAN clipboard queue is full.");
|
||||
auto item=std::make_shared<Item>(Item{randomHex(16),app.size()>128?std::string("Application"):app,std::move(bytes)});
|
||||
for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty()){s.ack=0;s.begun=false;s.last=0;s.progress=now;}s.queue.push_back(item);}
|
||||
for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty())s.reset(now);s.queue.push_back(item);}
|
||||
if(!peers.empty())status=type=="clipboard"?"Sending clipboard to "+std::to_string(peers.size())+" paired computers...":"Sending…";
|
||||
}
|
||||
template<class Send>void poll(const Json &trusted,uint64_t now,Send send)
|
||||
@@ -88,14 +101,30 @@ class ClipboardExchange
|
||||
auto &peer=it->first;auto &s=it->second;
|
||||
if(!trusted.contains(peer)||s.queue.empty()){it=sending.erase(it);continue;}
|
||||
if(now-s.progress>30000){status="Transfer timed out.";it=sending.erase(it);continue;}
|
||||
if(sessions.contains(peer)&&(!s.last||now-s.last>=100))
|
||||
auto &item=*s.queue.front();
|
||||
const auto limit=std::min(item.bytes.size(),s.ack+Window*Chunk);
|
||||
const bool retry=s.retryAt && now>=s.retryAt;
|
||||
const bool sendBegin=!s.begun && (!s.retryAt || retry);
|
||||
const bool sendChunks=s.begun && (s.sentUpTo<limit || retry);
|
||||
if(sessions.contains(peer) && (sendBegin || sendChunks))
|
||||
{
|
||||
auto &item=*s.queue.front();auto key=trusted.at(peer).at("key").template get<std::string>();
|
||||
if(!s.begun)send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}}));
|
||||
else for(size_t offset=s.ack,n=0;offset<item.bytes.size()&&n<Window;offset+=Chunk,++n)
|
||||
send(peer,seal(peer,key,{{"op","chunk"},{"item",item.id},{"offset",offset},
|
||||
{"bytes",Json::binary(Bytes(item.bytes.begin()+offset,item.bytes.begin()+std::min(offset+Chunk,item.bytes.size())))}}));
|
||||
s.last=now;
|
||||
auto key=trusted.at(peer).at("key").template get<std::string>();
|
||||
if(sendBegin)
|
||||
send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}}));
|
||||
else
|
||||
{
|
||||
// ACKs open new slots. Only a timeout retransmits outstanding chunks.
|
||||
if(retry) s.sentUpTo=s.ack;
|
||||
while(s.sentUpTo<limit)
|
||||
{
|
||||
const auto offset=s.sentUpTo;
|
||||
const auto end=std::min(offset+Chunk,item.bytes.size());
|
||||
send(peer,seal(peer,key,{{"op","chunk"},{"item",item.id},{"offset",offset},
|
||||
{"bytes",Json::binary(Bytes(item.bytes.begin()+offset,item.bytes.begin()+end))}}));
|
||||
s.sentUpTo=end;
|
||||
}
|
||||
}
|
||||
if(!s.retryAt || retry) s.retryAt=now+100;
|
||||
}
|
||||
++it;
|
||||
}
|
||||
@@ -119,10 +148,19 @@ class ClipboardExchange
|
||||
{
|
||||
auto found=sending.find(peer);if(found==sending.end()||found->second.queue.empty())return;
|
||||
auto &s=found->second;auto &item=*s.queue.front();auto offset=body.at("offset").get<size_t>();
|
||||
if(item.id!=id||offset>item.bytes.size()||offset<s.ack||offset>s.ack+Window*Chunk||(offset!=item.bytes.size()&&offset%Chunk))return;
|
||||
const auto maxAck=s.begun?s.sentUpTo:Window*Chunk;
|
||||
if(item.id!=id||offset>item.bytes.size()||offset<s.ack||offset>maxAck||(offset!=item.bytes.size()&&offset%Chunk))return;
|
||||
if(offset==s.ack&&s.begun)return;
|
||||
s.begun=true;s.ack=offset;s.progress=now;s.last=0;
|
||||
if(offset==item.bytes.size()){s.queue.pop_front();s.ack=0;s.begun=false;status=type=="clipboard"?"Clipboard delivered.":"Transfer delivered.";}
|
||||
s.begun=true;
|
||||
s.ack=offset;
|
||||
s.sentUpTo=std::max(s.sentUpTo,offset);
|
||||
s.progress=now;
|
||||
s.retryAt=offset<s.sentUpTo?now+100:0;
|
||||
if(offset==item.bytes.size()){
|
||||
s.queue.pop_front();
|
||||
s.reset(now);
|
||||
status=type=="clipboard"?"Clipboard delivered.":"Transfer delivered.";
|
||||
}
|
||||
return;
|
||||
}
|
||||
for(auto &done:completed[peer])if(done.first==id){ack(done.second);return;}
|
||||
|
||||
+50
-28
@@ -1,3 +1,4 @@
|
||||
#include "files_powershell.h"
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <shellapi.h>
|
||||
@@ -7,11 +8,13 @@
|
||||
#include <bcrypt.h>
|
||||
#include <wincrypt.h>
|
||||
#include <sddl.h>
|
||||
#include <winsafer.h>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include "lan_files.h"
|
||||
#include "lan_channel.h"
|
||||
#include "lan_network.h"
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
@@ -109,28 +112,6 @@ DWORD createJunction(const fs::path &name,const fs::path &target)
|
||||
constexpr size_t FrameLimit=256*1024;
|
||||
constexpr DWORD SocketTimeout=5000;
|
||||
|
||||
struct WinSocket
|
||||
{
|
||||
SOCKET value=INVALID_SOCKET;
|
||||
~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);}
|
||||
};
|
||||
|
||||
void socketError()
|
||||
{
|
||||
throw std::system_error(WSAGetLastError(),std::system_category());
|
||||
}
|
||||
|
||||
struct Network
|
||||
{
|
||||
Network()
|
||||
{
|
||||
WSADATA data{};
|
||||
if(const auto error=WSAStartup(MAKEWORD(2,2),&data))
|
||||
throw std::system_error(error,std::system_category());
|
||||
}
|
||||
~Network(){WSACleanup();}
|
||||
};
|
||||
|
||||
class Wire
|
||||
{
|
||||
SOCKET socket;
|
||||
@@ -257,6 +238,40 @@ DWORD requestSystemHibernate()
|
||||
return GetExitCodeProcess(process.value,&exitCode)?exitCode:GetLastError();
|
||||
}
|
||||
|
||||
DWORD restrictElevatedCommandToken(HANDLE token,FileHandle &restricted)
|
||||
{
|
||||
// A synthetic LUA token made directly from an elevated token can fail to
|
||||
// initialize KernelBase when the child starts without a console window.
|
||||
SAFER_LEVEL_HANDLE level{};
|
||||
if(!SaferCreateLevel(SAFER_SCOPEID_USER,SAFER_LEVELID_NORMALUSER,SAFER_LEVEL_OPEN,&level,nullptr))
|
||||
return GetLastError();
|
||||
const auto filtered=SaferComputeTokenFromLevel(level,token,&restricted.value,0,nullptr);
|
||||
const auto filterError=GetLastError();
|
||||
SaferCloseLevel(level);
|
||||
if(!filtered) return filterError;
|
||||
|
||||
// Preserve DISABLE_MAX_PRIVILEGE without creating a second filtered token.
|
||||
LUID changeNotify{};
|
||||
if(!LookupPrivilegeValueW(nullptr,SE_CHANGE_NOTIFY_NAME,&changeNotify)) return GetLastError();
|
||||
DWORD size{};
|
||||
if(!GetTokenInformation(restricted.value,TokenPrivileges,nullptr,0,&size) &&
|
||||
GetLastError()!=ERROR_INSUFFICIENT_BUFFER) return GetLastError();
|
||||
std::vector<BYTE> storage(size);
|
||||
const auto privileges=reinterpret_cast<TOKEN_PRIVILEGES *>(storage.data());
|
||||
if(!GetTokenInformation(restricted.value,TokenPrivileges,privileges,size,&size)) return GetLastError();
|
||||
DWORD removed{};
|
||||
for(DWORD i=0;i<privileges->PrivilegeCount;++i)
|
||||
{
|
||||
const auto &luid=privileges->Privileges[i].Luid;
|
||||
if(luid.LowPart!=changeNotify.LowPart || luid.HighPart!=changeNotify.HighPart)
|
||||
privileges->Privileges[removed++]={luid,SE_PRIVILEGE_REMOVED};
|
||||
}
|
||||
if(!removed) return ERROR_SUCCESS;
|
||||
privileges->PrivilegeCount=removed;
|
||||
AdjustTokenPrivileges(restricted.value,FALSE,privileges,0,nullptr,nullptr);
|
||||
return GetLastError();
|
||||
}
|
||||
|
||||
struct RemoteCommand
|
||||
{
|
||||
FileHandle job,process,output;
|
||||
@@ -288,15 +303,22 @@ struct RemoteCommand
|
||||
auto arguments=L"powershell.exe -NoLogo -NoProfile -NonInteractive -OutputFormat Text -Command "
|
||||
L"\"& ([ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('"+
|
||||
encoded+L"'))))\"";
|
||||
wchar_t system[MAX_PATH]{};
|
||||
if(!GetSystemDirectoryW(system,MAX_PATH)) return GetLastError();
|
||||
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
|
||||
const auto shell=ks::files::windowsPowerShell();
|
||||
if(shell.empty()) return ERROR_PATH_NOT_FOUND;
|
||||
|
||||
FileHandle token,restricted,read,write,input,processJob;
|
||||
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|
|
||||
TOKEN_ADJUST_DEFAULT,&token.value) ||
|
||||
!CreateRestrictedToken(token.value,DISABLE_MAX_PRIVILEGE|LUA_TOKEN,0,nullptr,0,nullptr,0,nullptr,
|
||||
&restricted.value)) return GetLastError();
|
||||
TOKEN_ADJUST_DEFAULT,&token.value)) return GetLastError();
|
||||
TOKEN_ELEVATION elevation{};
|
||||
DWORD elevationSize{};
|
||||
if(!GetTokenInformation(token.value,TokenElevation,&elevation,sizeof(elevation),&elevationSize))
|
||||
return GetLastError();
|
||||
if(elevation.TokenIsElevated)
|
||||
{
|
||||
if(const auto error=restrictElevatedCommandToken(token.value,restricted)) return error;
|
||||
}
|
||||
else if(!CreateRestrictedToken(token.value,DISABLE_MAX_PRIVILEGE|LUA_TOKEN,0,nullptr,0,nullptr,0,nullptr,
|
||||
&restricted.value)) return GetLastError();
|
||||
PSID medium{};
|
||||
if(!ConvertStringSidToSidW(L"S-1-16-8192",&medium)) return GetLastError();
|
||||
TOKEN_MANDATORY_LABEL label{{medium,SE_GROUP_INTEGRITY}};
|
||||
|
||||
+16
-4
@@ -211,9 +211,18 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
|
||||
if(!connected||!env.desktop()){cancel(now);return;}
|
||||
if(f.type==InputType::Enter)
|
||||
{
|
||||
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535||held()||returning||
|
||||
mode_==ControlMode::Sending||mode_==ControlMode::Receiving||(mode_==ControlMode::Requesting&&preferLocal))
|
||||
{post({InputType::Return,f.token,32768});return;}
|
||||
const wchar_t *declined=nullptr;
|
||||
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535)
|
||||
declined=L"invalid edge or position";
|
||||
else if(held())declined=L"a local key or mouse button is held";
|
||||
else if(returning||mode_==ControlMode::Sending||mode_==ControlMode::Receiving||
|
||||
(mode_==ControlMode::Requesting&&preferLocal))
|
||||
declined=L"another handoff is active";
|
||||
if(declined)
|
||||
{
|
||||
log(std::wstring(L"LAN input: declined cursor handoff: ")+declined);
|
||||
post({InputType::Return,f.token,32768});return;
|
||||
}
|
||||
if(mode_==ControlMode::Requesting)cancel(now);
|
||||
if(multi)edge=f.a^1;
|
||||
crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
|
||||
@@ -231,7 +240,10 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
|
||||
return;
|
||||
}
|
||||
if(f.token!=token||!token)return;
|
||||
if(f.type==InputType::Return){log(L"LAN input: peer returned control");local(now,std::clamp(f.a,0,65535));return;}
|
||||
if(f.type==InputType::Return){
|
||||
log(mode_==ControlMode::Requesting?L"LAN input: peer declined cursor handoff":L"LAN input: peer returned control");
|
||||
local(now,std::clamp(f.a,0,65535));return;
|
||||
}
|
||||
if(mode_!=ControlMode::Receiving)return;
|
||||
bool ok=true;
|
||||
if(f.type==InputType::Move)
|
||||
|
||||
@@ -50,6 +50,7 @@ class InputMesh
|
||||
if(!ready.contains(peer)||!positions.contains(peer))return;
|
||||
if(f.type==InputType::Enter){
|
||||
if(!allowEnter||f.a<0||f.a>3||(router.mode()!=ControlMode::Local&&active!=peer)){
|
||||
if(!allowEnter)log(L"LAN input: declined cursor handoff during a local text operation or shortcut capture");
|
||||
send(peer,{InputType::Return,f.token,32768});return;
|
||||
}
|
||||
if(router.mode()==ControlMode::Local)select(peer,f.a^1,now);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
#include <winsock2.h>
|
||||
#include <system_error>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
inline void socketError()
|
||||
{
|
||||
throw std::system_error(WSAGetLastError(),std::system_category());
|
||||
}
|
||||
|
||||
struct WinSocket
|
||||
{
|
||||
SOCKET value=INVALID_SOCKET;
|
||||
~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);}
|
||||
};
|
||||
|
||||
struct Network
|
||||
{
|
||||
Network()
|
||||
{
|
||||
WSADATA data{};
|
||||
if(const auto error=WSAStartup(MAKEWORD(2,2),&data))
|
||||
throw std::system_error(error,std::system_category());
|
||||
}
|
||||
~Network(){WSACleanup();}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
inline std::optional<std::array<unsigned char,102>> wakePacket(std::string_view mac)
|
||||
{
|
||||
constexpr std::string_view digits="0123456789abcdef";
|
||||
std::array<unsigned char,6> address{};
|
||||
if(mac.size()!=2*address.size()) return {};
|
||||
for(size_t i=0;i<address.size();++i)
|
||||
{
|
||||
const auto high=digits.find(mac[2*i]),low=digits.find(mac[2*i+1]);
|
||||
if(high==digits.npos || low==digits.npos) return {};
|
||||
address[i]=static_cast<unsigned char>(16*high+low);
|
||||
}
|
||||
if((address.front()&1) || std::all_of(address.begin(),address.end(),[](auto byte){return byte==0;}))
|
||||
return {};
|
||||
std::array<unsigned char,102> packet{};
|
||||
std::fill_n(packet.begin(),6,0xff);
|
||||
for(auto next=packet.begin()+6;next!=packet.end();next+=address.size())
|
||||
std::copy(address.begin(),address.end(),next);
|
||||
return packet;
|
||||
}
|
||||
|
||||
void wakeFilesPeer(const std::string &id);
|
||||
}
|
||||
@@ -38,6 +38,8 @@ bool shouldElevateOnLaunch()
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||
{
|
||||
// Inherited by unattended children such as the LAN PowerShell process.
|
||||
SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS);
|
||||
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
int argc{};
|
||||
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
|
||||
|
||||
+48
-17
@@ -1,5 +1,6 @@
|
||||
#include "ocr.h"
|
||||
#include <memory>
|
||||
#include <atomic>
|
||||
#include <roapi.h>
|
||||
#include <wincodec.h>
|
||||
#include <winstring.h>
|
||||
@@ -99,6 +100,38 @@ struct OcrOperation : IInspectable
|
||||
virtual HRESULT STDMETHODCALLTYPE GetCompleted(IUnknown **) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE Results(OcrResult **) = 0;
|
||||
};
|
||||
class OcrCompletion final : public IUnknown
|
||||
{
|
||||
// Windows.Foundation.AsyncOperationCompletedHandler<Windows.Media.Ocr.OcrResult>.
|
||||
static constexpr GUID interfaceId{0x989c1371,0x444a,0x5e7e,{0xb1,0x97,0x9e,0xaa,0xf9,0xd2,0x82,0x9a}};
|
||||
static constexpr GUID agileId{0x94ea2b94,0xe9cc,0x49e0,{0xc0,0xff,0xee,0x64,0xca,0x8f,0x5b,0x90}};
|
||||
std::atomic<ULONG> references{1};
|
||||
|
||||
public:
|
||||
const HANDLE event=CreateEventW(nullptr,TRUE,FALSE,nullptr);
|
||||
~OcrCompletion(){if(event) CloseHandle(event);}
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **value) override
|
||||
{
|
||||
if(!value) return E_POINTER;
|
||||
*value=nullptr;
|
||||
if(iid!=IID_IUnknown && iid!=interfaceId && iid!=agileId) return E_NOINTERFACE;
|
||||
*value=static_cast<IUnknown *>(this);
|
||||
AddRef();
|
||||
return S_OK;
|
||||
}
|
||||
ULONG STDMETHODCALLTYPE AddRef() override {return ++references;}
|
||||
ULONG STDMETHODCALLTYPE Release() override
|
||||
{
|
||||
const auto count=--references;
|
||||
if(!count) delete this;
|
||||
return count;
|
||||
}
|
||||
virtual HRESULT STDMETHODCALLTYPE Invoke(OcrOperation *,INT32)
|
||||
{
|
||||
return SetEvent(event)?S_OK:HRESULT_FROM_WIN32(GetLastError());
|
||||
}
|
||||
};
|
||||
|
||||
struct AsyncInfo : IInspectable
|
||||
{
|
||||
virtual HRESULT STDMETHODCALLTYPE Id(UINT32 *) = 0;
|
||||
@@ -253,13 +286,12 @@ std::wstring recognizeText(const Clip &clip)
|
||||
RoUninitialize();
|
||||
}
|
||||
} apartment;
|
||||
auto pixels = decodeImage(clip);
|
||||
Com<OcrStatics> ocr;
|
||||
factory(L"Windows.Media.Ocr.OcrEngine", L"{5bffa85a-3384-3540-9940-699120d428a8}", ocr);
|
||||
UINT32 max{};
|
||||
check(ocr->MaxDimension(&max));
|
||||
if (pixels.width > max || pixels.height > max)
|
||||
throw std::runtime_error("Image exceeds Windows OCR's maximum dimensions");
|
||||
if (!max) throw std::runtime_error("Windows OCR reported an invalid image size limit");
|
||||
auto pixels = decodeImage(clip,max,max);
|
||||
Com<OcrEngine> engine;
|
||||
check(ocr->FromProfile(engine.out()));
|
||||
if (!engine.p)
|
||||
@@ -282,21 +314,20 @@ std::wstring recognizeText(const Clip &clip)
|
||||
check(engine->Recognize(bitmap.p, operation.out()));
|
||||
Com<AsyncInfo> info;
|
||||
check(operation->QueryInterface(guid(L"{00000036-0000-0000-c000-000000000046}"), (void **)info.out()));
|
||||
auto deadline = GetTickCount64() + 30000;
|
||||
INT32 status{};
|
||||
do
|
||||
Com<OcrCompletion> completed;
|
||||
completed.p=new OcrCompletion;
|
||||
if(!completed->event) check(HRESULT_FROM_WIN32(GetLastError()));
|
||||
check(operation->PutCompleted(completed.p));
|
||||
const auto wait=WaitForSingleObject(completed->event,30000);
|
||||
if(wait!=WAIT_OBJECT_0)
|
||||
{
|
||||
check(info->Status(&status));
|
||||
if (status == 0)
|
||||
{
|
||||
if (GetTickCount64() > deadline)
|
||||
{
|
||||
info->Cancel();
|
||||
throw std::runtime_error("Windows OCR timed out");
|
||||
}
|
||||
Sleep(20);
|
||||
}
|
||||
} while (status == 0);
|
||||
const auto error=wait==WAIT_FAILED?GetLastError():ERROR_TIMEOUT;
|
||||
info->Cancel();
|
||||
if(error==ERROR_TIMEOUT) throw std::runtime_error("Windows OCR timed out");
|
||||
check(HRESULT_FROM_WIN32(error));
|
||||
}
|
||||
INT32 status{};
|
||||
check(info->Status(&status));
|
||||
if (status != 1)
|
||||
{
|
||||
HRESULT failure{};
|
||||
|
||||
+29
-11
@@ -11,8 +11,19 @@ class PasteProbe
|
||||
IUIAutomationElement *element{};
|
||||
IUIAutomationTextPattern *pattern{};
|
||||
|
||||
static std::optional<std::wstring> rangeText(IUIAutomationTextRange *range)
|
||||
{
|
||||
BSTR value{};
|
||||
const HRESULT hr = range->GetText(8193, &value);
|
||||
std::wstring text(value ? value : L"", SysStringLen(value));
|
||||
SysFreeString(value);
|
||||
if (FAILED(hr)) return {};
|
||||
return text;
|
||||
}
|
||||
|
||||
public:
|
||||
std::wstring status = L"not-requested";
|
||||
std::optional<std::wstring> precedingCharacter;
|
||||
PasteProbe(bool enabled, HWND target)
|
||||
{
|
||||
if (!enabled)
|
||||
@@ -48,11 +59,11 @@ class PasteProbe
|
||||
!pattern)
|
||||
return;
|
||||
}
|
||||
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr)
|
||||
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr, bool readPreceding = false)
|
||||
: PasteProbe(enabled, target)
|
||||
{
|
||||
if (!pattern) return;
|
||||
auto selected = read(1, false);
|
||||
auto selected = read(1, false, readPreceding);
|
||||
auto normalize = [](std::wstring value)
|
||||
{
|
||||
for (size_t at = 0; (at = value.find(L"\r\n", at)) != value.npos;)
|
||||
@@ -80,7 +91,7 @@ class PasteProbe
|
||||
if (automation)
|
||||
automation->Release();
|
||||
}
|
||||
std::optional<std::wstring> read(int characters, bool allowCaret = true)
|
||||
std::optional<std::wstring> read(int characters, bool allowCaret = true, bool readPreceding = false)
|
||||
{
|
||||
if (!pattern)
|
||||
return {};
|
||||
@@ -162,19 +173,26 @@ class PasteProbe
|
||||
if (SUCCEEDED(hr) && moved != -characters)
|
||||
hr = E_FAIL;
|
||||
}
|
||||
BSTR value{};
|
||||
if (SUCCEEDED(hr))
|
||||
hr = range->GetText(8193, &value);
|
||||
auto text = SUCCEEDED(hr) ? rangeText(range) : std::nullopt;
|
||||
if (readPreceding && text &&
|
||||
SUCCEEDED(range->MoveEndpointByRange(TextPatternRangeEndpoint_End, range, TextPatternRangeEndpoint_Start)))
|
||||
{
|
||||
int moved{};
|
||||
if (SUCCEEDED(range->MoveEndpointByUnit(TextPatternRangeEndpoint_Start, TextUnit_Character, -1, &moved)))
|
||||
{
|
||||
if (moved == 0)
|
||||
precedingCharacter.emplace();
|
||||
else if (auto previous = rangeText(range); previous && !previous->empty())
|
||||
precedingCharacter = std::move(previous);
|
||||
}
|
||||
}
|
||||
range->Release();
|
||||
if (FAILED(hr))
|
||||
if (!text)
|
||||
{
|
||||
SysFreeString(value);
|
||||
status = L"range-read-failed";
|
||||
return {};
|
||||
}
|
||||
std::wstring text(value ? value : L"", SysStringLen(value));
|
||||
SysFreeString(value);
|
||||
if (text.size() > 8192)
|
||||
if (text->size() > 8192)
|
||||
{
|
||||
status = L"readback-size-limit";
|
||||
return {};
|
||||
|
||||
+46
-23
@@ -349,14 +349,18 @@ bool launchThroughExplorer(const std::wstring &path)
|
||||
SysFreeString(executable);
|
||||
return SUCCEEDED(hr);
|
||||
}
|
||||
Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<DWORD> expected)
|
||||
bool clipboardHasImage()
|
||||
{
|
||||
return IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
|
||||
IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"));
|
||||
}
|
||||
Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<DWORD> expected,
|
||||
DWORD *capturedSequence)
|
||||
{
|
||||
ClipboardLock lock(window);
|
||||
if (expected && *expected != GetClipboardSequenceNumber())
|
||||
throw std::runtime_error("Clipboard changed while taking snapshot");
|
||||
if (mode == ClipboardRead::WithoutImages &&
|
||||
(IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
|
||||
IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))))
|
||||
if (mode == ClipboardRead::WithoutImages && clipboardHasImage())
|
||||
throw std::runtime_error("Clipboard changed to an image");
|
||||
Clip c;
|
||||
size_t total = 0;
|
||||
@@ -392,6 +396,8 @@ Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<
|
||||
total += size;
|
||||
c.formats.push_back(std::move(format));
|
||||
}
|
||||
// Delayed rendering can advance the sequence while this read holds the clipboard open.
|
||||
if (capturedSequence) *capturedSequence = GetClipboardSequenceNumber();
|
||||
return c;
|
||||
}
|
||||
DWORD writeClipboard(HWND window, const Clip &c) { return writeClipboardGuarded(window, c, {}); }
|
||||
@@ -490,32 +496,44 @@ INPUT keyboardInput(WORD key, DWORD flags)
|
||||
return input;
|
||||
}
|
||||
bool chord(WORD key, UINT mods)
|
||||
{
|
||||
WORD keys[5];
|
||||
size_t count = 0;
|
||||
for (auto [modifier, vk] : {std::pair<UINT, WORD>{MOD_CONTROL, VK_CONTROL},
|
||||
{MOD_ALT, VK_MENU}, {MOD_SHIFT, VK_SHIFT}, {MOD_WIN, VK_LWIN}})
|
||||
if (mods & modifier)
|
||||
keys[count++] = vk;
|
||||
keys[count++] = key;
|
||||
return chord(std::span<const WORD>(keys, count));
|
||||
}
|
||||
bool chord(std::span<const WORD> keys)
|
||||
{
|
||||
std::vector<INPUT> inputs;
|
||||
inputs.reserve(2 * keys.size());
|
||||
auto add = [&](WORD k, bool up)
|
||||
{
|
||||
INPUT i = keyboardInput(k, up ? KEYEVENTF_KEYUP : 0);
|
||||
if (k >= VK_LSHIFT && k <= VK_RMENU)
|
||||
{
|
||||
i.ki.wScan = static_cast<WORD>(MapVirtualKeyW(k, MAPVK_VK_TO_VSC));
|
||||
i.ki.dwFlags |= KEYEVENTF_SCANCODE;
|
||||
}
|
||||
if ((k >= VK_PRIOR && k <= VK_DOWN) || k == VK_INSERT || k == VK_DELETE ||
|
||||
k == VK_DIVIDE || k == VK_LWIN || k == VK_SNAPSHOT ||
|
||||
k == VK_DIVIDE || k == VK_LWIN || k == VK_RWIN || k == VK_RMENU ||
|
||||
k == VK_RCONTROL || k == VK_SNAPSHOT ||
|
||||
(k >= VK_VOLUME_MUTE && k <= VK_VOLUME_UP))
|
||||
i.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
|
||||
inputs.push_back(i);
|
||||
};
|
||||
for (auto [m, k] : {std::pair<UINT, WORD>{MOD_CONTROL, VK_CONTROL},
|
||||
{MOD_ALT, VK_MENU},
|
||||
{MOD_SHIFT, VK_SHIFT},
|
||||
{MOD_WIN, VK_LWIN}})
|
||||
if (mods & m)
|
||||
add(k, false);
|
||||
add(key, false);
|
||||
add(key, true);
|
||||
for (auto [m, k] : {std::pair<UINT, WORD>{MOD_WIN, VK_LWIN},
|
||||
{MOD_SHIFT, VK_SHIFT},
|
||||
{MOD_ALT, VK_MENU},
|
||||
{MOD_CONTROL, VK_CONTROL}})
|
||||
if (mods & m)
|
||||
add(k, true);
|
||||
return SendInput((UINT)inputs.size(), inputs.data(), sizeof(INPUT)) == inputs.size();
|
||||
for (WORD key : keys) add(key, false);
|
||||
for (auto it = keys.rbegin(); it != keys.rend(); ++it) add(*it, true);
|
||||
const auto sent = SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT));
|
||||
if (sent == inputs.size()) return true;
|
||||
// Release any keys already pressed if Windows accepted only part of the chord.
|
||||
const auto pending = std::min<size_t>(sent, inputs.size() - sent);
|
||||
if (pending)
|
||||
SendInput(static_cast<UINT>(pending), inputs.data() + inputs.size() - pending, sizeof(INPUT));
|
||||
return false;
|
||||
}
|
||||
std::optional<SystemVolume> changeSystemVolume(MouseActionType action, int step)
|
||||
{
|
||||
@@ -738,6 +756,11 @@ namespace
|
||||
std::recursive_mutex logGate;
|
||||
bool loggingEnabled = false;
|
||||
std::wstring logFilename = L"kswitcher.log";
|
||||
const std::filesystem::path &logDirectory()
|
||||
{
|
||||
static const auto directory = dataDirectory();
|
||||
return directory;
|
||||
}
|
||||
DiagnosticBuffer diagnosticBuffer;
|
||||
}
|
||||
size_t DiagnosticBuffer::expire(ULONGLONG now)
|
||||
@@ -778,7 +801,7 @@ void setLoggingEnabled(bool enabled)
|
||||
std::wstring readDiagnosticLog(bool previous)
|
||||
{
|
||||
std::lock_guard lock(logGate);
|
||||
auto path = dataDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
|
||||
auto path = logDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
|
||||
if (!std::filesystem::exists(path))
|
||||
return previous ? L"No previous log is available yet." : L"No log yet. Entries will appear when a problem is detected.";
|
||||
auto bytes = readFile(path, 2 * 1024 * 1024);
|
||||
@@ -796,7 +819,7 @@ void clearDiagnosticLog(bool previous)
|
||||
{
|
||||
// Serialize clearing with writes and rotation. Never delete the other log.
|
||||
std::lock_guard lock(logGate);
|
||||
auto path = dataDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
|
||||
auto path = logDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
|
||||
std::filesystem::remove(path);
|
||||
if (!previous)
|
||||
diagnosticBuffer.clear();
|
||||
@@ -845,7 +868,7 @@ void log(const std::wstring &message)
|
||||
return;
|
||||
try
|
||||
{
|
||||
auto path = dataDirectory() / logFilename;
|
||||
auto path = logDirectory() / logFilename;
|
||||
std::error_code ec;
|
||||
auto size = std::filesystem::file_size(path, ec);
|
||||
if (!ec && size > 256 * 1024)
|
||||
|
||||
+4
-1
@@ -50,12 +50,15 @@ std::wstring processName(HWND);
|
||||
std::wstring mouseApplicationName(HWND);
|
||||
bool launchThroughExplorer(const std::wstring &);
|
||||
enum class ClipboardRead { All, Selection, WithoutImages };
|
||||
bool clipboardHasImage();
|
||||
Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024,
|
||||
ClipboardRead = ClipboardRead::All, std::optional<DWORD> expected = {});
|
||||
ClipboardRead = ClipboardRead::All, std::optional<DWORD> expected = {},
|
||||
DWORD *capturedSequence = nullptr);
|
||||
DWORD writeClipboard(HWND, const Clip &);
|
||||
DWORD writeClipboardGuarded(HWND, const Clip &, std::optional<DWORD> expected);
|
||||
Clip textClip(const std::wstring &);
|
||||
bool chord(WORD key, UINT modifiers = 0);
|
||||
bool chord(std::span<const WORD> keys);
|
||||
struct SystemVolume
|
||||
{
|
||||
int percent{};
|
||||
|
||||
+173
-26
@@ -84,6 +84,13 @@ struct Surface
|
||||
Surface(const Surface &) = delete;
|
||||
Surface &operator=(const Surface &) = delete;
|
||||
};
|
||||
struct SavedDc
|
||||
{
|
||||
HDC dc;
|
||||
int level;
|
||||
explicit SavedDc(HDC value):dc(value),level(SaveDC(value)) {}
|
||||
~SavedDc() { if(level) RestoreDC(dc,level); }
|
||||
};
|
||||
using Mark = ScreenshotMark;
|
||||
HFONT textFont(const Mark &m)
|
||||
{
|
||||
@@ -169,7 +176,9 @@ struct Capture
|
||||
{
|
||||
ScreenshotHost &app;
|
||||
std::unique_ptr<Surface> image;
|
||||
std::unique_ptr<Surface> dimmed, frame;
|
||||
std::unique_ptr<Surface> dimmed, frame, rendered;
|
||||
bool renderedMarksValid{};
|
||||
RECT dragDamage{};
|
||||
bool editing{}, dragging{}, arrow{}, owned{}, copied{};
|
||||
bool autoOpenEditor;
|
||||
bool highlight{};
|
||||
@@ -249,6 +258,7 @@ struct Capture
|
||||
void remember(const std::vector<Mark> &previous)
|
||||
{
|
||||
copied=false;
|
||||
renderedMarksValid=false;
|
||||
history.remember(previous);
|
||||
syncHistory();
|
||||
}
|
||||
@@ -471,6 +481,76 @@ RECT markBounds(const Mark &m)
|
||||
}
|
||||
return r;
|
||||
}
|
||||
RECT inkBounds(const Mark &m)
|
||||
{
|
||||
auto bounds=markBounds(m);
|
||||
const auto padding=m.number?std::clamp(m.radius,8,200)+4:
|
||||
m.isHighlight()?std::clamp(m.thickness,4,100)/2+4:
|
||||
m.isText()?4:std::clamp(m.thickness,1,30)*5+14;
|
||||
InflateRect(&bounds,padding,padding);
|
||||
return bounds;
|
||||
}
|
||||
void includeInk(RECT &area,const Mark &m)
|
||||
{
|
||||
const auto bounds=inkBounds(m);
|
||||
UnionRect(&area,&area,&bounds);
|
||||
if(m.isLine() && !m.label.empty())
|
||||
{
|
||||
const auto labelBounds=inkBounds(screenshotArrowLabel(m));
|
||||
UnionRect(&area,&area,&labelBounds);
|
||||
}
|
||||
}
|
||||
|
||||
Mark shapePreview(const Capture &c)
|
||||
{
|
||||
Mark preview{c.start,c.end,0};
|
||||
preview.color=c.currentColor;
|
||||
preview.style=c.lineStyle;
|
||||
preview.ends=c.straight || c.shape!=ScreenshotShape::None?LineEnds::None:c.arrowEnds;
|
||||
preview.shape=c.shape;
|
||||
return preview;
|
||||
}
|
||||
|
||||
RECT dragInk(const Capture &c)
|
||||
{
|
||||
RECT area{};
|
||||
if(c.part!=MarkPart::None)
|
||||
{
|
||||
// Moving an attachment can update linked lines and their labels as well.
|
||||
for(size_t i=0;i<c.marks.size();++i)
|
||||
{
|
||||
const auto &mark=c.marks[i];
|
||||
if(i==static_cast<size_t>(c.selected) || mark.fromLink.target || mark.toLink.target ||
|
||||
mark.fromNumber || mark.toNumber)
|
||||
includeInk(area,mark);
|
||||
}
|
||||
}
|
||||
else includeInk(area,(c.highlight || c.freehand)?c.stroke:shapePreview(c));
|
||||
return area;
|
||||
}
|
||||
|
||||
void invalidateDrag(HWND w,Capture &c,const RECT &before)
|
||||
{
|
||||
const auto after=dragInk(c);
|
||||
RECT affected{};
|
||||
UnionRect(&affected,&before,&after);
|
||||
UnionRect(&c.dragDamage,&c.dragDamage,&affected);
|
||||
const auto x=[&](LONG value) {return c.view.left+MulDiv(value,c.view.right-c.view.left,c.image->width);};
|
||||
const auto y=[&](LONG value) {return c.view.top+MulDiv(value,c.view.bottom-c.view.top,c.image->height);};
|
||||
RECT windowArea{x(affected.left),y(affected.top),x(affected.right),y(affected.bottom)};
|
||||
// Handles and antialiased scaling extend beyond the rasterized ink.
|
||||
int padding=4;
|
||||
if(c.part!=MarkPart::None && c.selected>=0 && c.selected<int(c.marks.size()))
|
||||
{
|
||||
const auto &selected=c.marks[c.selected];
|
||||
padding+=std::max(4,c.unit/8);
|
||||
if(!selected.number && !selected.isHighlight()) padding+=c.unit*2;
|
||||
}
|
||||
InflateRect(&windowArea,padding,padding);
|
||||
RECT visible{};
|
||||
if(IntersectRect(&visible,&windowArea,&c.canvas)) InvalidateRect(w,&visible,FALSE);
|
||||
}
|
||||
|
||||
std::pair<POINT,POINT> thicknessSegment(const Mark &m)
|
||||
{
|
||||
if(m.shape!=ScreenshotShape::None) {
|
||||
@@ -492,7 +572,8 @@ void drawHighlight(HDC dc,const Mark &m)
|
||||
r.left=std::max(0L,r.left-radius-1); r.top=std::max(0L,r.top-radius-1);
|
||||
r.right=std::min(target.dsBm.bmWidth,r.right+radius+2);
|
||||
r.bottom=std::min(target.dsBm.bmHeight,r.bottom+radius+2);
|
||||
if(r.right<=r.left || r.bottom<=r.top) return;
|
||||
RECT clip{};
|
||||
if(GetClipBox(dc,&clip)==ERROR || !IntersectRect(&r,&r,&clip)) return;
|
||||
Surface mask(r.right-r.left,r.bottom-r.top);
|
||||
PatBlt(mask.dc,0,0,mask.width,mask.height,BLACKNESS);
|
||||
LOGBRUSH white{BS_SOLID,RGB(255,255,255),0};
|
||||
@@ -519,7 +600,7 @@ void drawHighlight(HDC dc,const Mark &m)
|
||||
for(int channel=0;channel<3;++channel) at[channel]=static_cast<unsigned char>(at[channel]*(153+channels[channel]*102/255)/255);
|
||||
}
|
||||
}
|
||||
void drawMarks(HDC dc, const std::vector<Mark> &marks, const Mark *preview = nullptr)
|
||||
void drawMarks(HDC dc,const std::vector<Mark> &marks,const Mark *preview=nullptr,const RECT *damage=nullptr)
|
||||
{
|
||||
for(const auto &m:marks) if(m.isHighlight()) drawHighlight(dc,m);
|
||||
if(preview && preview->isHighlight()) drawHighlight(dc,*preview);
|
||||
@@ -533,6 +614,12 @@ void drawMarks(HDC dc, const std::vector<Mark> &marks, const Mark *preview = nul
|
||||
SetTextColor(dc, RGB(255,255,255));
|
||||
auto draw = [&](const Mark &m)
|
||||
{
|
||||
if(damage)
|
||||
{
|
||||
const auto bounds=inkBounds(m);
|
||||
RECT overlap{};
|
||||
if(!IntersectRect(&overlap,&bounds,damage)) return;
|
||||
}
|
||||
auto markPen=CreatePen(PS_SOLID,3,m.color);
|
||||
auto markBrush=CreateSolidBrush(m.color);
|
||||
auto previousMarkPen=SelectObject(dc,markPen),previousMarkBrush=SelectObject(dc,markBrush);
|
||||
@@ -1050,6 +1137,8 @@ void edit(HWND w, Capture &c)
|
||||
c.image = std::move(cropped);
|
||||
c.dimmed.reset();
|
||||
c.frame.reset();
|
||||
c.rendered.reset();
|
||||
c.renderedMarksValid=false;
|
||||
c.editing = true;
|
||||
if (activeCapture == w) activeCapture = nullptr;
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
@@ -1184,6 +1273,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
bool pencil=c->selected>=0 && c->marks[c->selected].freehand;
|
||||
if(pencil && c->marks[c->selected].smoothing!=amount) {
|
||||
if(!c->smoothingDrag) c->remember(c->marks);
|
||||
c->renderedMarksValid=false;
|
||||
setScreenshotSmoothing(c->marks[c->selected],amount);
|
||||
resolveScreenshotLinks(c->marks);
|
||||
c->smoothingDrag=LOWORD(wp)==TB_THUMBTRACK;
|
||||
@@ -1296,7 +1386,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (LOWORD(wp)==12 || LOWORD(wp)==18)
|
||||
{
|
||||
bool changed=LOWORD(wp)==12?c->history.undo(c->marks):c->history.redo(c->marks);
|
||||
if(changed) { c->copied=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; }
|
||||
if(changed) { c->copied=false; c->renderedMarksValid=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; }
|
||||
c->syncHistory();
|
||||
}
|
||||
if (LOWORD(wp)==10 || LOWORD(wp)==11 || LOWORD(wp)==19 || LOWORD(wp)==36 || LOWORD(wp)==37 || LOWORD(wp)==38 || (LOWORD(wp)>=21 && LOWORD(wp)<=27))
|
||||
@@ -1321,6 +1411,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
InvalidateRect(GetDlgItem(w,38),nullptr,FALSE);
|
||||
}
|
||||
|
||||
if(c->dragging) c->renderedMarksValid=false;
|
||||
SetFocus(w); captureCursor(w,*c); InvalidateRect(w,nullptr,FALSE); return 0;
|
||||
case WM_KEYDOWN:
|
||||
if(wp==VK_SHIFT && c->editing && c->dragging && c->freehand && c->part==MarkPart::None && !c->strokeConstrained) {
|
||||
@@ -1463,6 +1554,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
c->strokeUsedConstraint=(wp&MK_SHIFT)!=0;
|
||||
}
|
||||
c->dragging=true; SetCapture(w);
|
||||
if(c->editing) invalidateDrag(w,*c,{});
|
||||
}
|
||||
InvalidateRect(w,nullptr,FALSE); return 0;
|
||||
}
|
||||
@@ -1522,7 +1614,18 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (c->dragging)
|
||||
{
|
||||
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
const auto previousSelection=region(c->start,c->end);
|
||||
const auto previousInk=c->editing && msg==WM_MOUSEMOVE?dragInk(*c):RECT{};
|
||||
c->end=c->editing?imagePoint(*c,p,c->part!=MarkPart::Thickness && c->part!=MarkPart::Rotation):POINT{std::clamp(p.x,0L,LONG(c->image->width)),std::clamp(p.y,0L,LONG(c->image->height))};
|
||||
if(!c->editing && msg==WM_MOUSEMOVE)
|
||||
{
|
||||
const auto selection=region(c->start,c->end);
|
||||
RECT dirty{};
|
||||
if(UnionRect(&dirty,&previousSelection,&selection))
|
||||
InvalidateRect(w,&dirty,FALSE);
|
||||
captureCursor(w,*c);
|
||||
return 0;
|
||||
}
|
||||
if(c->editing && c->part==MarkPart::None && c->shape!=ScreenshotShape::None)
|
||||
c->end=constrainScreenshotShape(c->shape,c->start,c->end,c->image->width,c->image->height);
|
||||
if(c->editing && (c->highlight || c->freehand) && c->part==MarkPart::None) {
|
||||
@@ -1593,6 +1696,12 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
c->marks[c->selected]=dragScreenshotMark(c->original,c->part,c->start,c->end,c->image->width,c->image->height,(GetKeyState(VK_SHIFT)&0x8000)!=0);
|
||||
resolveScreenshotLinks(c->marks);
|
||||
}
|
||||
if(c->editing && msg==WM_MOUSEMOVE)
|
||||
{
|
||||
invalidateDrag(w,*c,previousInk);
|
||||
captureCursor(w,*c);
|
||||
return 0;
|
||||
}
|
||||
if (msg==WM_LBUTTONUP)
|
||||
{
|
||||
c->dragging=false; ReleaseCapture();
|
||||
@@ -1675,9 +1784,10 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
c->panning=false;
|
||||
if(c->dragging && c->part!=MarkPart::None)
|
||||
{
|
||||
c->marks=std::move(c->beforeDrag); c->part=MarkPart::None;
|
||||
c->marks=std::move(c->beforeDrag); c->renderedMarksValid=false; c->part=MarkPart::None;
|
||||
}
|
||||
c->dragging=false; InvalidateRect(w,nullptr,FALSE); return 0;
|
||||
c->dragging=false; c->renderedMarksValid=false; c->dragDamage={};
|
||||
InvalidateRect(w,nullptr,FALSE); return 0;
|
||||
case WM_GETMINMAXINFO:
|
||||
if (c->editing)
|
||||
{
|
||||
@@ -1710,14 +1820,16 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
// Compose the entire frame off screen. Never expose a cleared desktop
|
||||
// or a partially drawn selection between mouse moves.
|
||||
auto buffer=c->frame->dc;
|
||||
BitBlt(buffer,0,0,c->image->width,c->image->height,c->dimmed->dc,0,0,SRCCOPY);
|
||||
const auto &dirty=ps.rcPaint;
|
||||
const int width=dirty.right-dirty.left,height=dirty.bottom-dirty.top;
|
||||
BitBlt(buffer,dirty.left,dirty.top,width,height,c->dimmed->dc,dirty.left,dirty.top,SRCCOPY);
|
||||
if (c->dragging)
|
||||
{
|
||||
auto r=region(c->start,c->end);
|
||||
BitBlt(buffer,r.left,r.top,r.right-r.left,r.bottom-r.top,c->image->dc,r.left,r.top,SRCCOPY);
|
||||
FrameRect(buffer,&r,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
|
||||
}
|
||||
BitBlt(dc,0,0,c->image->width,c->image->height,buffer,0,0,SRCCOPY);
|
||||
BitBlt(dc,dirty.left,dirty.top,width,height,buffer,dirty.left,dirty.top,SRCCOPY);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1725,6 +1837,9 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (!c->frame || c->frame->width!=width || c->frame->height!=height)
|
||||
c->frame=std::make_unique<Surface>(width,height);
|
||||
auto buffer=c->frame->dc;
|
||||
const SavedDc savedFrame(buffer);
|
||||
const auto &dirty=ps.rcPaint;
|
||||
IntersectClipRect(buffer,dirty.left,dirty.top,dirty.right,dirty.bottom);
|
||||
FillRect(buffer,&client,GetSysColorBrush(COLOR_APPWORKSPACE));
|
||||
RECT toolbar{0,0,client.right,c->panelHeight};
|
||||
FillRect(buffer,&toolbar,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
|
||||
@@ -1737,26 +1852,58 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
LineTo(buffer,MulDiv(x,dpi,96),MulDiv(31,dpi,96));
|
||||
}
|
||||
SelectObject(buffer,previous); DeleteObject(divider);
|
||||
Surface rendered(c->image->width,c->image->height);
|
||||
BitBlt(rendered.dc,0,0,rendered.width,rendered.height,c->image->dc,0,0,SRCCOPY);
|
||||
Mark preview{c->start,c->end,0};
|
||||
preview.color=c->currentColor;
|
||||
preview.style=c->lineStyle; preview.ends=c->straight || c->shape!=ScreenshotShape::None?LineEnds::None:c->arrowEnds;
|
||||
preview.shape=c->shape;
|
||||
auto visibleMarks=c->marks;
|
||||
if(c->inlineText && c->textIndex>=0) {
|
||||
if(c->editingLabel) visibleMarks[c->textIndex].label.clear();
|
||||
else visibleMarks.erase(visibleMarks.begin()+c->textIndex);
|
||||
const auto preview=shapePreview(*c);
|
||||
const auto *previewMark=c->dragging && c->part==MarkPart::None?
|
||||
((c->highlight || c->freehand)?&c->stroke:&preview):nullptr;
|
||||
const auto *source=c->image.get();
|
||||
if(!c->marks.empty() || previewMark)
|
||||
{
|
||||
const bool inlineEdit=c->inlineText && c->textIndex>=0;
|
||||
const bool partial=c->renderedMarksValid && !inlineEdit;
|
||||
if(!c->rendered)
|
||||
c->rendered=std::make_unique<Surface>(source->width,source->height);
|
||||
auto &rendered=*c->rendered;
|
||||
RECT imageArea{0,0,rendered.width,rendered.height}, repaint=imageArea;
|
||||
if(partial) IntersectRect(&repaint,&imageArea,&c->dragDamage);
|
||||
if(!IsRectEmpty(&repaint))
|
||||
{
|
||||
c->renderedMarksValid=false;
|
||||
BitBlt(rendered.dc,repaint.left,repaint.top,repaint.right-repaint.left,repaint.bottom-repaint.top,
|
||||
source->dc,repaint.left,repaint.top,SRCCOPY);
|
||||
if(inlineEdit)
|
||||
{
|
||||
auto visibleMarks=c->marks;
|
||||
if(c->editingLabel) visibleMarks[c->textIndex].label.clear();
|
||||
else visibleMarks.erase(visibleMarks.begin()+c->textIndex);
|
||||
drawMarks(rendered.dc,visibleMarks,previewMark);
|
||||
}
|
||||
else if(partial)
|
||||
{
|
||||
const SavedDc previousClip(rendered.dc);
|
||||
IntersectClipRect(rendered.dc,repaint.left,repaint.top,repaint.right,repaint.bottom);
|
||||
drawMarks(rendered.dc,c->marks,previewMark,&repaint);
|
||||
}
|
||||
else drawMarks(rendered.dc,c->marks,previewMark);
|
||||
c->renderedMarksValid=!inlineEdit;
|
||||
}
|
||||
source=&rendered;
|
||||
}
|
||||
drawMarks(rendered.dc,visibleMarks,c->dragging && c->part==MarkPart::None?((c->highlight || c->freehand)?&c->stroke:&preview):nullptr);
|
||||
else
|
||||
{
|
||||
c->rendered.reset();
|
||||
c->renderedMarksValid=false;
|
||||
}
|
||||
c->dragDamage={};
|
||||
SetStretchBltMode(buffer,HALFTONE); SetBrushOrgEx(buffer,0,0,nullptr);
|
||||
int savedCanvas=SaveDC(buffer);
|
||||
IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom);
|
||||
StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top,
|
||||
rendered.dc,0,0,rendered.width,rendered.height,SRCCOPY);
|
||||
drawHandles(buffer,*c);
|
||||
RestoreDC(buffer,savedCanvas);
|
||||
BitBlt(dc,0,0,width,height,buffer,0,0,SRCCOPY);
|
||||
{
|
||||
const SavedDc savedCanvas(buffer);
|
||||
IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom);
|
||||
StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top,
|
||||
source->dc,0,0,source->width,source->height,SRCCOPY);
|
||||
drawHandles(buffer,*c);
|
||||
}
|
||||
BitBlt(dc,dirty.left,dirty.top,dirty.right-dirty.left,dirty.bottom-dirty.top,
|
||||
buffer,dirty.left,dirty.top,SRCCOPY);
|
||||
}
|
||||
}
|
||||
catch (...) { EndPaint(w,&ps); throw; }
|
||||
|
||||
+19
-3
@@ -50,9 +50,25 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
||||
std::wstring token;
|
||||
bool autoOpenEditor=false, writeLog=false;
|
||||
int argc{}; auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
|
||||
if(argc==3 && std::wstring(argv[1])==L"--clipboard-snapshot") {
|
||||
std::filesystem::path request=argv[2]; LocalFree(argv);
|
||||
return ks::runClipboardSnapshot(request);
|
||||
const bool clipboardSnapshot = argc == 6 && std::wstring_view(argv[1]) == L"--clipboard-snapshot";
|
||||
const bool historyImageWorker = argc == 5 && std::wstring_view(argv[1]) == L"--history-image-worker";
|
||||
if (clipboardSnapshot || historyImageWorker)
|
||||
{
|
||||
HANDLE handles[4]{};
|
||||
for (int i = 0; i < argc - 2; ++i)
|
||||
{
|
||||
wchar_t *end{};
|
||||
const auto value=std::wcstoull(argv[i+2],&end,10);
|
||||
if(!value || *end || value>UINTPTR_MAX) { LocalFree(argv); return 1; }
|
||||
handles[i]=reinterpret_cast<HANDLE>(static_cast<uintptr_t>(value));
|
||||
}
|
||||
LocalFree(argv);
|
||||
if (clipboardSnapshot) return ks::runClipboardSnapshot(handles[0], handles[1], handles[2], handles[3]);
|
||||
const auto initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
if(FAILED(initialized)) return 1;
|
||||
const auto result=ks::runHistoryImageWorker(handles[0],handles[1],handles[2]);
|
||||
CoUninitialize();
|
||||
return result;
|
||||
}
|
||||
if(argc==3 && (std::wstring(argv[1])==L"--capture-history" || std::wstring(argv[1])==L"--history-ocr")) {
|
||||
bool ocr=std::wstring(argv[1])==L"--history-ocr";
|
||||
|
||||
+296
-109
@@ -28,9 +28,9 @@ std::wstring newSnippetId()
|
||||
}
|
||||
namespace
|
||||
{
|
||||
Bytes jsonBytes(const Json &j)
|
||||
Bytes jsonBytes(const Json &j, int indent = 2)
|
||||
{
|
||||
auto s = j.dump(2);
|
||||
auto s = j.dump(indent);
|
||||
return Bytes(s.begin(), s.end());
|
||||
}
|
||||
Json parse(const Bytes &bytes)
|
||||
@@ -269,8 +269,9 @@ void validateSettings(const Settings &s)
|
||||
if (alphabet.empty() || words.size() > 10000)
|
||||
throw std::runtime_error("Invalid personal dictionary language or too many words");
|
||||
for (const auto &word : words)
|
||||
if (word.empty() || word.size() > 32 || lower(word).find_first_not_of(alphabet) != word.npos)
|
||||
throw std::runtime_error("Personal words must contain 1-32 letters of their selected language");
|
||||
if (!validPersonalWord(word, alphabet))
|
||||
throw std::runtime_error("Personal words must be 1-32 characters, with letters of the selected language. "
|
||||
"A hyphen (-) is allowed between letters.");
|
||||
}
|
||||
if (s.maxItems < 10 || s.maxItems > 10000 || s.maxMiB < 1 || s.maxMiB > 2048 || s.maxImageMiB < 1 ||
|
||||
s.maxImageMiB > 64)
|
||||
@@ -327,7 +328,7 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
|
||||
throw std::runtime_error("Not a KSwitcher or Typlo settings file");
|
||||
s.recent = j.value("convertLastWord", true);
|
||||
s.switchLayout = j.value("switchSystemLayout", true);
|
||||
s.writeLog = j.value("writeLog", true);
|
||||
s.writeLog = j.value("writeLog", s.writeLog);
|
||||
s.history = j.value("historyEnabled", true);
|
||||
s.useTesseract = j.value("useTesseract", false);
|
||||
s.tesseractPath = str(j, "tesseractPath");
|
||||
@@ -685,7 +686,127 @@ Clip decodeClip(const Bytes &b)
|
||||
throw std::runtime_error("Trailing clipboard data");
|
||||
return clip;
|
||||
}
|
||||
History::History(const std::filesystem::path &folder) : folder_(folder)
|
||||
namespace
|
||||
{
|
||||
struct ImageWorkerControl
|
||||
{
|
||||
static constexpr size_t MaxPath=32768;
|
||||
wchar_t request[MaxPath];
|
||||
int result;
|
||||
};
|
||||
struct ImageWorkerHandle
|
||||
{
|
||||
HANDLE value{};
|
||||
~ImageWorkerHandle() { reset(); }
|
||||
void reset()
|
||||
{
|
||||
if(value) CloseHandle(std::exchange(value,nullptr));
|
||||
}
|
||||
};
|
||||
template <typename Control>
|
||||
struct ImageWorkerView
|
||||
{
|
||||
Control *control{};
|
||||
~ImageWorkerView() { reset(); }
|
||||
void reset()
|
||||
{
|
||||
if(control) UnmapViewOfFile(std::exchange(control,nullptr));
|
||||
}
|
||||
};
|
||||
template <typename Control>
|
||||
struct ImageWorkerChannel
|
||||
{
|
||||
ImageWorkerHandle mapping, requestReady, responseReady, process;
|
||||
ImageWorkerView<Control> view;
|
||||
|
||||
~ImageWorkerChannel() { stop(); }
|
||||
void stop() noexcept
|
||||
{
|
||||
if (process.value && WaitForSingleObject(process.value, 0) == WAIT_TIMEOUT)
|
||||
{
|
||||
TerminateProcess(process.value, ERROR_CANCELLED);
|
||||
WaitForSingleObject(process.value, INFINITE);
|
||||
}
|
||||
process.reset();
|
||||
view.reset();
|
||||
mapping.reset();
|
||||
requestReady.reset();
|
||||
responseReady.reset();
|
||||
}
|
||||
void open()
|
||||
{
|
||||
SECURITY_ATTRIBUTES security{sizeof(security), nullptr, TRUE};
|
||||
mapping.value = CreateFileMappingW(INVALID_HANDLE_VALUE, &security, PAGE_READWRITE, 0, sizeof(Control), nullptr);
|
||||
requestReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
|
||||
responseReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
|
||||
if (!mapping.value || !requestReady.value || !responseReady.value)
|
||||
throw std::runtime_error("Cannot create image helper channel");
|
||||
view.control = static_cast<Control *>(MapViewOfFile(mapping.value, FILE_MAP_WRITE, 0, 0, sizeof(Control)));
|
||||
if (!view.control) throw std::runtime_error("Cannot map image helper channel");
|
||||
}
|
||||
void start(std::wstring_view mode, HANDLE parent = nullptr)
|
||||
{
|
||||
std::vector<HANDLE> inherited{mapping.value, requestReady.value, responseReady.value};
|
||||
if (parent) inherited.push_back(parent);
|
||||
SIZE_T bytes{};
|
||||
InitializeProcThreadAttributeList(nullptr, 1, 0, &bytes);
|
||||
Bytes storage(bytes);
|
||||
auto attributes = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if (!InitializeProcThreadAttributeList(attributes, 1, 0, &bytes))
|
||||
throw std::runtime_error("Cannot initialize image helper startup");
|
||||
struct Attributes
|
||||
{
|
||||
LPPROC_THREAD_ATTRIBUTE_LIST value;
|
||||
~Attributes() { DeleteProcThreadAttributeList(value); }
|
||||
} cleanup{attributes};
|
||||
if (!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
inherited.data(), inherited.size() * sizeof(HANDLE), nullptr, nullptr))
|
||||
throw std::runtime_error("Cannot configure image helper startup");
|
||||
|
||||
const auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
|
||||
auto command = L"\"" + helper.wstring() + L"\" ";
|
||||
command += mode;
|
||||
for (auto handle : inherited) command += L" " + std::to_wstring(reinterpret_cast<uintptr_t>(handle));
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb = sizeof(startup);
|
||||
startup.lpAttributeList = attributes;
|
||||
PROCESS_INFORMATION child{};
|
||||
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, TRUE,
|
||||
CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, nullptr, helper.parent_path().c_str(),
|
||||
&startup.StartupInfo, &child))
|
||||
throw std::runtime_error(utf8(lastError(L"Cannot start image helper")));
|
||||
process.value = child.hProcess;
|
||||
CloseHandle(child.hThread);
|
||||
for (auto handle : inherited) SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
|
||||
}
|
||||
DWORD waitForResponse(DWORD timeout) const
|
||||
{
|
||||
HANDLE signals[]{responseReady.value, process.value};
|
||||
return WaitForMultipleObjects(2, signals, FALSE, timeout);
|
||||
}
|
||||
};
|
||||
struct HistoryImageWorker
|
||||
{
|
||||
std::timed_mutex mutex;
|
||||
ImageWorkerChannel<ImageWorkerControl> channel;
|
||||
int perform(const std::filesystem::path &, const std::function<bool()> &);
|
||||
};
|
||||
struct ClipboardSnapshotControl
|
||||
{
|
||||
DWORD sequence;
|
||||
char captureError[256];
|
||||
};
|
||||
}
|
||||
|
||||
struct HistoryImageWorkers
|
||||
{
|
||||
// A slow recognition must not delay history thumbnails.
|
||||
HistoryImageWorker recognition, thumbnails;
|
||||
};
|
||||
|
||||
History::~History() = default;
|
||||
History::History(const std::filesystem::path &folder)
|
||||
: folder_(folder), imageWorkers_(std::make_unique<HistoryImageWorkers>())
|
||||
{
|
||||
std::filesystem::create_directories(folder_);
|
||||
loadIndex();
|
||||
@@ -724,92 +845,104 @@ void History::loadIndex()
|
||||
}
|
||||
entries_ = std::move(loaded);
|
||||
}
|
||||
void History::reload() { std::lock_guard lock(mutex_); loadIndex(); }
|
||||
void ClipboardSnapshot::cleanup() noexcept
|
||||
void History::reload()
|
||||
{
|
||||
if (request_.empty()) return;
|
||||
std::error_code ignored;
|
||||
for (const auto *suffix : {L"", L".snapshot", L".result"})
|
||||
std::filesystem::remove(std::filesystem::path(request_.wstring() + suffix), ignored);
|
||||
request_.clear();
|
||||
std::lock_guard writer(indexWriter_);
|
||||
std::lock_guard lock(mutex_);
|
||||
loadIndex();
|
||||
}
|
||||
ClipboardSnapshot::~ClipboardSnapshot() { cleanup(); }
|
||||
DWORD ClipboardSnapshot::run(bool restore, DWORD sequence)
|
||||
struct ClipboardSnapshot::Helper
|
||||
{
|
||||
atomicWrite(request_, protect(jsonBytes(Json{{"schema", 1}, {"restore", restore}, {"sequence", sequence}})));
|
||||
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
|
||||
auto command = L"\"" + helper.wstring() + L"\" --clipboard-snapshot \"" + request_.wstring() + L"\"";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
|
||||
PROCESS_INFORMATION process{};
|
||||
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
|
||||
nullptr, helper.parent_path().c_str(), &startup, &process))
|
||||
throw std::runtime_error("Cannot start clipboard snapshot helper");
|
||||
CloseHandle(process.hThread);
|
||||
auto wait = WaitForSingleObject(process.hProcess, 10000);
|
||||
DWORD result = ERROR_GEN_FAILURE;
|
||||
ImageWorkerChannel<ClipboardSnapshotControl> channel;
|
||||
};
|
||||
ClipboardSnapshot::ClipboardSnapshot() = default;
|
||||
ClipboardSnapshot::~ClipboardSnapshot() = default;
|
||||
DWORD ClipboardSnapshot::capture(HWND window, DWORD sequence)
|
||||
{
|
||||
helper_.reset();
|
||||
clip_ = {};
|
||||
if (!clipboardHasImage())
|
||||
{
|
||||
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence, &sequence);
|
||||
return sequence;
|
||||
}
|
||||
auto helper = std::make_unique<Helper>();
|
||||
auto &channel = helper->channel;
|
||||
channel.open();
|
||||
channel.view.control->sequence = sequence;
|
||||
// Let the helper discard its private copy if the resident exits unexpectedly.
|
||||
ImageWorkerHandle parent;
|
||||
const auto self = GetCurrentProcess();
|
||||
if (!DuplicateHandle(self, self, self, &parent.value, SYNCHRONIZE, TRUE, 0))
|
||||
throw std::runtime_error("Cannot pass resident lifetime to clipboard helper");
|
||||
channel.start(L"--clipboard-snapshot", parent.value);
|
||||
const auto wait = channel.waitForResponse(10000);
|
||||
if (wait == WAIT_TIMEOUT)
|
||||
throw std::runtime_error("Clipboard snapshot helper timed out during capture");
|
||||
if (wait == WAIT_FAILED)
|
||||
throw std::runtime_error(utf8(lastError(L"Cannot wait for clipboard snapshot helper")));
|
||||
if (wait != WAIT_OBJECT_0)
|
||||
{
|
||||
TerminateProcess(process.hProcess, ERROR_TIMEOUT);
|
||||
WaitForSingleObject(process.hProcess, INFINITE);
|
||||
const auto &error = channel.view.control->captureError;
|
||||
if (error[0]) throw std::runtime_error(std::string("Clipboard snapshot capture: ") + error);
|
||||
DWORD exitCode{};
|
||||
if (GetExitCodeProcess(channel.process.value, &exitCode))
|
||||
throw std::runtime_error("Clipboard snapshot helper exited during capture (code " +
|
||||
std::to_string(exitCode) + ")");
|
||||
throw std::runtime_error(utf8(lastError(L"Cannot read clipboard snapshot helper exit code")));
|
||||
}
|
||||
GetExitCodeProcess(process.hProcess, &result);
|
||||
CloseHandle(process.hProcess);
|
||||
if (wait != WAIT_OBJECT_0 || result) throw std::runtime_error("Clipboard snapshot helper failed");
|
||||
return parse(unprotect(readFile(request_.wstring() + L".result", 4096))).at("sequence").get<DWORD>();
|
||||
}
|
||||
void ClipboardSnapshot::capture(HWND window, DWORD sequence)
|
||||
{
|
||||
cleanup();
|
||||
clip_ = {};
|
||||
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
|
||||
!IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")))
|
||||
{
|
||||
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence);
|
||||
return;
|
||||
}
|
||||
request_ = std::filesystem::temp_directory_path() / (L"ks-clipboard-" + newSnippetId() + L".request");
|
||||
try { run(false, sequence); }
|
||||
catch (...) { cleanup(); throw; }
|
||||
sequence = channel.view.control->sequence;
|
||||
helper_ = std::move(helper);
|
||||
return sequence;
|
||||
}
|
||||
DWORD ClipboardSnapshot::restore(HWND window, DWORD sequence)
|
||||
{
|
||||
return request_.empty() ? writeClipboardGuarded(window, clip_, sequence) : run(true, sequence);
|
||||
if (!helper_) return writeClipboardGuarded(window, clip_, sequence);
|
||||
auto &channel = helper_->channel;
|
||||
if (!channel.process.value)
|
||||
throw std::runtime_error("Clipboard snapshot helper is unavailable");
|
||||
channel.view.control->sequence = sequence;
|
||||
DWORD result{};
|
||||
if (!SetEvent(channel.requestReady.value) || WaitForSingleObject(channel.process.value, 10000) != WAIT_OBJECT_0 ||
|
||||
!GetExitCodeProcess(channel.process.value, &result) || result != 0)
|
||||
{
|
||||
channel.stop();
|
||||
throw std::runtime_error("Clipboard snapshot helper failed to restore");
|
||||
}
|
||||
return channel.view.control->sequence;
|
||||
}
|
||||
int runClipboardSnapshot(const std::filesystem::path &request)
|
||||
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent)
|
||||
{
|
||||
ImageWorkerView<ClipboardSnapshotControl> view{static_cast<ClipboardSnapshotControl *>(
|
||||
MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(ClipboardSnapshotControl)))};
|
||||
if (!view.control) return 1;
|
||||
try
|
||||
{
|
||||
if (!request.is_absolute() || !request.filename().wstring().starts_with(L"ks-clipboard-") ||
|
||||
request.extension() != L".request") return 1;
|
||||
auto job = parse(unprotect(readFile(request, 4096)));
|
||||
if (job.at("schema") != 1) return 1;
|
||||
auto sequence = job.at("sequence").get<DWORD>();
|
||||
const auto snapshot = request.wstring() + L".snapshot";
|
||||
if (job.at("restore").get<bool>())
|
||||
{
|
||||
auto clip = decodeClip(unprotect(readFile(snapshot, 70 * 1024 * 1024)));
|
||||
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
|
||||
if (!window) return 1;
|
||||
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
|
||||
sequence = writeClipboardGuarded(window, clip, sequence);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
|
||||
if (sequence != GetClipboardSequenceNumber()) return 2;
|
||||
atomicWrite(snapshot, protect(encodeClip(clip)));
|
||||
}
|
||||
atomicWrite(request.wstring() + L".result", protect(jsonBytes(Json{{"sequence", sequence}})));
|
||||
auto &sequence = view.control->sequence;
|
||||
const auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence, &sequence);
|
||||
if (!SetEvent(responseReady)) return 1;
|
||||
// The captured formats stay in this process.
|
||||
HANDLE signals[]{parent, requestReady};
|
||||
if (WaitForMultipleObjects(2, signals, FALSE, INFINITE) != WAIT_OBJECT_0 + 1) return 1;
|
||||
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
|
||||
if (!window) return 1;
|
||||
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
|
||||
view.control->sequence = writeClipboardGuarded(window, clip, view.control->sequence);
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
auto &message = view.control->captureError;
|
||||
strncpy_s(message, error.what(), _TRUNCATE);
|
||||
return 1;
|
||||
}
|
||||
catch (...) { return 1; }
|
||||
}
|
||||
bool History::captureImage(DWORD sequence, const std::wstring &app, const Settings &settings)
|
||||
{
|
||||
// Serialize helper index changes with all resident history mutations. Only
|
||||
// metadata is reloaded: GetClipboardData's image allocations die with the child.
|
||||
std::lock_guard lock(mutex_);
|
||||
std::lock_guard writer(indexWriter_);
|
||||
if (sequence != GetClipboardSequenceNumber()) return false;
|
||||
auto request = std::filesystem::absolute(folder_) / (L"capture-" + newSnippetId() + L".request");
|
||||
struct Cleanup {
|
||||
@@ -838,7 +971,10 @@ bool History::captureImage(DWORD sequence, const std::wstring &app, const Settin
|
||||
}
|
||||
GetExitCodeProcess(process.hProcess, &result);
|
||||
CloseHandle(process.hProcess);
|
||||
loadIndex(); // Also reconcile any completed atomic save before a child failure.
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
loadIndex(); // Also reconcile any completed atomic save before a child failure.
|
||||
}
|
||||
if (wait != WAIT_OBJECT_0) throw std::runtime_error("Image history helper timed out");
|
||||
if (result == 2) return false;
|
||||
if (result == 3) throw std::runtime_error("Clipboard exceeds the configured size limit");
|
||||
@@ -861,9 +997,7 @@ int runImageHistoryCapture(const std::filesystem::path &request)
|
||||
!IsClipboardFormatAvailable(RegisterClipboardFormatW(L"Clipboard Viewer Ignore"));
|
||||
};
|
||||
if (!valid()) return 2;
|
||||
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
|
||||
!IsClipboardFormatAvailable(CF_BITMAP) &&
|
||||
!IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))) return 2;
|
||||
if (!clipboardHasImage()) return 2;
|
||||
auto clip = readClipboard(nullptr, size_t(settings.maxImageMiB) * 1024 * 1024);
|
||||
if (!valid()) return 2;
|
||||
for (const auto &format : clip.formats)
|
||||
@@ -893,7 +1027,7 @@ void History::saveIndex()
|
||||
{"files", e.files}, {"ocrState", e.ocrState}, {"ocrProfile", utf8(e.ocrProfile)},
|
||||
{"fingerprintVersion", 1}, {"contentHash", e.contentHash},
|
||||
{"imageHash", e.imageHash}, {"pixelHash", e.pixelHash}});
|
||||
atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j)));
|
||||
atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j, -1)));
|
||||
}
|
||||
std::vector<Entry> History::entries() const
|
||||
{
|
||||
@@ -1007,6 +1141,7 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s,
|
||||
image |= f.id == CF_DIB || f.id == CF_DIBV5 || f.name == L"PNG";
|
||||
files |= f.id == CF_HDROP;
|
||||
}
|
||||
std::lock_guard writer(indexWriter_);
|
||||
std::lock_guard lock(mutex_);
|
||||
Entry fingerprints;
|
||||
fingerprints.contentHash = clipboardHash(data);
|
||||
@@ -1068,6 +1203,7 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s,
|
||||
}
|
||||
void History::remove(const std::wstring &id)
|
||||
{
|
||||
std::lock_guard writer(indexWriter_);
|
||||
std::lock_guard lock(mutex_);
|
||||
if (!validId(id))
|
||||
return;
|
||||
@@ -1082,6 +1218,7 @@ void History::remove(const std::wstring &id)
|
||||
}
|
||||
void History::pin(const std::wstring &id)
|
||||
{
|
||||
std::lock_guard writer(indexWriter_);
|
||||
std::lock_guard lock(mutex_);
|
||||
for (auto &e : entries_)
|
||||
if (e.id == id)
|
||||
@@ -1090,6 +1227,7 @@ void History::pin(const std::wstring &id)
|
||||
}
|
||||
void History::clear()
|
||||
{
|
||||
std::lock_guard writer(indexWriter_);
|
||||
std::lock_guard lock(mutex_);
|
||||
auto old = entries_;
|
||||
entries_.clear();
|
||||
@@ -1101,7 +1239,84 @@ void History::clear()
|
||||
std::filesystem::remove(folder_ / (e.id + L".ocr"), ec);
|
||||
}
|
||||
}
|
||||
static Bytes historyImageJob(const std::filesystem::path &folder, const std::wstring &id,
|
||||
namespace
|
||||
{
|
||||
int HistoryImageWorker::perform(const std::filesystem::path &request,const std::function<bool()> &cancelled)
|
||||
{
|
||||
std::unique_lock lock(mutex,std::defer_lock);
|
||||
const auto checkCancelled=[&] {
|
||||
if(cancelled && cancelled()) throw std::runtime_error("History OCR cancelled");
|
||||
};
|
||||
while(!lock.try_lock_for(std::chrono::milliseconds(100))) checkCancelled();
|
||||
checkCancelled();
|
||||
const auto &path=request.native();
|
||||
if(path.size()>=ImageWorkerControl::MaxPath)
|
||||
throw std::runtime_error("History OCR request path is too long");
|
||||
|
||||
try
|
||||
{
|
||||
for(int attempt=0;attempt<2;++attempt)
|
||||
{
|
||||
if(!channel.process.value || WaitForSingleObject(channel.process.value,0)!=WAIT_TIMEOUT)
|
||||
{
|
||||
channel.stop();
|
||||
channel.open();
|
||||
channel.start(L"--history-image-worker");
|
||||
}
|
||||
checkCancelled();
|
||||
std::copy(path.begin(),path.end(),channel.view.control->request);
|
||||
channel.view.control->request[path.size()]=L'\0';
|
||||
if(!SetEvent(channel.requestReady.value)) throw std::runtime_error("Cannot request history OCR");
|
||||
const auto deadline=GetTickCount64()+60000;
|
||||
for(;;)
|
||||
{
|
||||
const auto wait=channel.waitForResponse(100);
|
||||
if(wait==WAIT_OBJECT_0)
|
||||
{
|
||||
checkCancelled();
|
||||
return channel.view.control->result;
|
||||
}
|
||||
if(wait==WAIT_OBJECT_0+1)
|
||||
{
|
||||
DWORD code{};
|
||||
if(GetExitCodeProcess(channel.process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
|
||||
throw std::runtime_error("History OCR helper exited before responding");
|
||||
}
|
||||
if(wait!=WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper");
|
||||
checkCancelled();
|
||||
if(GetTickCount64()>=deadline) throw std::runtime_error("History OCR helper timed out");
|
||||
}
|
||||
channel.stop();
|
||||
}
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
// The child must stop writing before the request and response files are cleaned up.
|
||||
channel.stop();
|
||||
throw;
|
||||
}
|
||||
throw std::runtime_error("History OCR helper did not accept the request");
|
||||
}
|
||||
}
|
||||
|
||||
int runHistoryImageWorker(HANDLE mapping,HANDLE requestReady,HANDLE responseReady)
|
||||
{
|
||||
ImageWorkerView<ImageWorkerControl> view{static_cast<ImageWorkerControl *>(
|
||||
MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)))};
|
||||
if(!view.control) return 1;
|
||||
for(;;)
|
||||
{
|
||||
const auto wait=WaitForSingleObject(requestReady,30000);
|
||||
if(wait==WAIT_TIMEOUT) return WAIT_TIMEOUT;
|
||||
if(wait!=WAIT_OBJECT_0) return 1;
|
||||
const auto &request=view.control->request;
|
||||
const auto end=std::find(std::begin(request),std::end(request),L'\0');
|
||||
view.control->result=end==std::end(request)?1:runHistoryOcr(std::wstring(std::begin(request),end));
|
||||
if(!SetEvent(responseReady)) return 1;
|
||||
}
|
||||
}
|
||||
|
||||
static Bytes historyImageJob(HistoryImageWorker &worker,const std::filesystem::path &folder,const std::wstring &id,
|
||||
const Json &job, const std::function<bool()> &cancelled)
|
||||
{
|
||||
if (!validId(id)) throw std::runtime_error("Invalid history ID");
|
||||
@@ -1117,36 +1332,7 @@ static Bytes historyImageJob(const std::filesystem::path &folder, const std::wst
|
||||
}
|
||||
} cleanup{request, response};
|
||||
atomicWrite(request, protect(jsonBytes(job)));
|
||||
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
|
||||
auto command = L"\"" + helper.wstring() + L"\" --history-ocr \"" + request.wstring() + L"\"";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
|
||||
PROCESS_INFORMATION process{};
|
||||
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
|
||||
nullptr, helper.parent_path().c_str(), &startup, &process))
|
||||
throw std::runtime_error(utf8(lastError(L"Cannot start history OCR helper")));
|
||||
CloseHandle(process.hThread);
|
||||
struct Child {
|
||||
HANDLE handle;
|
||||
~Child() {
|
||||
if (WaitForSingleObject(handle, 0) != WAIT_OBJECT_0) {
|
||||
TerminateProcess(handle, ERROR_CANCELLED);
|
||||
WaitForSingleObject(handle, INFINITE);
|
||||
}
|
||||
CloseHandle(handle);
|
||||
}
|
||||
} child{process.hProcess};
|
||||
auto deadline = GetTickCount64() + 60000;
|
||||
for (;;) {
|
||||
auto wait = WaitForSingleObject(child.handle, 100);
|
||||
if (wait == WAIT_OBJECT_0) break;
|
||||
if (wait != WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper");
|
||||
if (cancelled && cancelled()) throw std::runtime_error("History OCR cancelled");
|
||||
if (GetTickCount64() >= deadline) throw std::runtime_error("History OCR helper timed out");
|
||||
}
|
||||
DWORD result{};
|
||||
if (!GetExitCodeProcess(child.handle, &result) || result)
|
||||
throw std::runtime_error("History OCR helper failed: " + std::to_string(result));
|
||||
if(worker.perform(request,cancelled)) throw std::runtime_error("History OCR helper failed");
|
||||
return unprotect(readFile(response, 8 * 1024 * 1024));
|
||||
}
|
||||
std::wstring History::recognizeImage(const std::wstring &id, const Settings &settings,
|
||||
@@ -1154,14 +1340,14 @@ std::wstring History::recognizeImage(const std::wstring &id, const Settings &set
|
||||
{
|
||||
Json job{{"schema", 1}, {"id", utf8(id)}, {"tesseract", settings.useTesseract},
|
||||
{"path", utf8(settings.tesseractPath)}, {"languages", utf8(settings.tesseractLanguages)}};
|
||||
auto reply = parse(historyImageJob(folder_, id, job, cancelled));
|
||||
auto reply = parse(historyImageJob(imageWorkers_->recognition,folder_, id, job, cancelled));
|
||||
if (reply.at("schema") != 1 || str(reply, "id") != id)
|
||||
throw std::runtime_error("Invalid history OCR response");
|
||||
return str(reply, "text");
|
||||
}
|
||||
Pixels History::thumbnail(const std::wstring &id, const std::function<bool()> &cancelled) const
|
||||
{
|
||||
auto bytes = historyImageJob(folder_, id, Json{{"schema", 1}, {"id", utf8(id)}, {"thumbnail", true}}, cancelled);
|
||||
auto bytes = historyImageJob(imageWorkers_->thumbnails,folder_, id, Json{{"schema", 1}, {"id", utf8(id)}, {"thumbnail", true}}, cancelled);
|
||||
size_t at = 0;
|
||||
auto width = get32(bytes, at), height = get32(bytes, at);
|
||||
if (!width || !height || width > 208 || height > 128 || bytes.size() - at != width * height * 4)
|
||||
@@ -1200,6 +1386,7 @@ int runHistoryOcr(const std::filesystem::path &request)
|
||||
}
|
||||
bool History::saveOcr(const std::wstring &id, const std::optional<std::wstring> &text, const Settings &settings)
|
||||
{
|
||||
std::lock_guard writer(indexWriter_);
|
||||
std::lock_guard lock(mutex_);
|
||||
auto it = std::find_if(entries_.begin(), entries_.end(), [&](auto &e) { return e.id == id; });
|
||||
// A late OCR completion must never recreate a deleted/pruned image.
|
||||
|
||||
+11
-7
@@ -5,6 +5,7 @@
|
||||
namespace ks
|
||||
{
|
||||
struct Pixels;
|
||||
struct HistoryImageWorkers;
|
||||
Settings loadSettings(const std::filesystem::path &, const std::vector<Layout> &);
|
||||
Settings decodeSettings(const Bytes &, const std::vector<Layout> &);
|
||||
Bytes encodeSettings(const Settings &);
|
||||
@@ -26,12 +27,15 @@ class History
|
||||
std::filesystem::path folder_;
|
||||
std::vector<Entry> entries_;
|
||||
mutable std::mutex mutex_;
|
||||
std::unique_ptr<HistoryImageWorkers> imageWorkers_;
|
||||
std::mutex indexWriter_; // Serializes resident mutations with the image capture helper.
|
||||
void saveIndex();
|
||||
void loadIndex();
|
||||
void prune(const Settings &);
|
||||
|
||||
public:
|
||||
explicit History(const std::filesystem::path &);
|
||||
~History();
|
||||
void reload();
|
||||
std::vector<Entry> entries() const;
|
||||
Clip load(const std::wstring &id) const;
|
||||
@@ -53,20 +57,20 @@ Clip decodeClip(const Bytes &);
|
||||
bool sameClipboardImage(const Clip &, const Clip &);
|
||||
int runImageHistoryCapture(const std::filesystem::path &request);
|
||||
int runHistoryOcr(const std::filesystem::path &request);
|
||||
// Image backups stay encrypted on disk and are read/written only by a short-lived helper.
|
||||
int runHistoryImageWorker(HANDLE mapping, HANDLE requestReady, HANDLE responseReady);
|
||||
// Image backups are held in memory by a helper for the lifetime of the transaction.
|
||||
class ClipboardSnapshot
|
||||
{
|
||||
struct Helper;
|
||||
Clip clip_;
|
||||
std::filesystem::path request_;
|
||||
void cleanup() noexcept;
|
||||
DWORD run(bool restore, DWORD sequence);
|
||||
std::unique_ptr<Helper> helper_;
|
||||
public:
|
||||
ClipboardSnapshot() = default;
|
||||
ClipboardSnapshot();
|
||||
ClipboardSnapshot(const ClipboardSnapshot &) = delete;
|
||||
ClipboardSnapshot &operator=(const ClipboardSnapshot &) = delete;
|
||||
~ClipboardSnapshot();
|
||||
void capture(HWND, DWORD sequence);
|
||||
DWORD capture(HWND, DWORD sequence);
|
||||
DWORD restore(HWND, DWORD sequence);
|
||||
};
|
||||
int runClipboardSnapshot(const std::filesystem::path &request);
|
||||
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent);
|
||||
} // namespace ks
|
||||
+1820
-469
File diff suppressed because it is too large.
Load diff
@@ -14,7 +14,6 @@ struct AppLanguagesView
|
||||
bool dirty{};
|
||||
HWND pickerOutline{};
|
||||
};
|
||||
constexpr UINT AppWindowPicked = WM_APP + 78;
|
||||
void showAppLanguageStatus(HWND w, const AppLanguagesView &v)
|
||||
{
|
||||
if (v.selection < 0)
|
||||
@@ -130,7 +129,7 @@ void updatePickerOutline(HWND dialog, HWND &outline, HWND target)
|
||||
}
|
||||
LRESULT CALLBACK appWindowPickerProc(HWND button, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR data)
|
||||
{
|
||||
HWND dialog = GetParent(button);
|
||||
HWND dialog = GetAncestor(button, GA_ROOT);
|
||||
auto &outline = *reinterpret_cast<HWND *>(data);
|
||||
if (msg == WM_LBUTTONDOWN)
|
||||
{
|
||||
@@ -177,11 +176,27 @@ LRESULT CALLBACK appWindowPickerProc(HWND button, UINT msg, WPARAM wp, LPARAM lp
|
||||
if (msg == WM_NCDESTROY) RemoveWindowSubclass(button, appWindowPickerProc, id);
|
||||
return DefSubclassProc(button, msg, wp, lp);
|
||||
}
|
||||
void createAppWindowPicker(HWND w, int id, int x, int y, int width, HWND &outline)
|
||||
HWND createButtonTooltips(HWND owner)
|
||||
{
|
||||
control(w, L"BUTTON", L" ⊕ Drag to window", WS_TABSTOP | BS_PUSHBUTTON | BS_LEFT,
|
||||
id, x, y, width, 28);
|
||||
SetWindowSubclass(GetDlgItem(w, id), appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&outline));
|
||||
return CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, owner, nullptr,
|
||||
GetModuleHandleW(nullptr), nullptr);
|
||||
}
|
||||
void addButtonTooltip(HWND tips, HWND owner, int id, const wchar_t *text)
|
||||
{
|
||||
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, owner,
|
||||
reinterpret_cast<UINT_PTR>(GetDlgItem(owner, id))};
|
||||
tool.lpszText = const_cast<wchar_t *>(text);
|
||||
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
|
||||
}
|
||||
constexpr int AppWindowPickerIcon = 753;
|
||||
void createAppWindowPicker(HWND w, int id, int x, int y, int width, HWND &outline, HWND tips = nullptr)
|
||||
{
|
||||
const bool icon = id == AppWindowPickerIcon;
|
||||
HWND picker = control(w, L"BUTTON", icon ? L"Drag to application window" : L" ⊕ Drag to window",
|
||||
WS_TABSTOP | (icon ? BS_OWNERDRAW : BS_PUSHBUTTON | BS_LEFT), id, x, y, width, 28);
|
||||
SetWindowSubclass(picker, appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&outline));
|
||||
if (tips) addButtonTooltip(tips, w, id, L"Drag to an application window");
|
||||
}
|
||||
LRESULT CALLBACK appLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
|
||||
+246
-105
@@ -1,7 +1,7 @@
|
||||
// Uses the resident service; the configurator never opens a discovery socket.
|
||||
struct LanView
|
||||
{
|
||||
HWND parent{};
|
||||
HWND owner{};
|
||||
App *app{};
|
||||
nlohmann::json snapshot=nlohmann::json::object();
|
||||
std::vector<std::string> ids;
|
||||
@@ -11,7 +11,7 @@ struct LanView
|
||||
std::vector<std::wstring> rows;
|
||||
std::string logRequest;
|
||||
std::filesystem::path logDestination;
|
||||
std::wstring transferMessage;
|
||||
std::wstring logMessage;
|
||||
};
|
||||
nlohmann::json lanRequest(App &app,const nlohmann::json &request)
|
||||
{
|
||||
@@ -23,19 +23,116 @@ std::string selectedLan(HWND w,LanView &v)
|
||||
auto index=SendDlgItemMessageW(w,702,LB_GETCURSEL,0,0);
|
||||
return index>=0 && size_t(index)<v.ids.size() ? v.ids[size_t(index)] : "";
|
||||
}
|
||||
std::filesystem::path pickLanFile(HWND owner, bool save, const wchar_t *suggestion=L"")
|
||||
std::filesystem::path pickLanFile(HWND owner, bool save, const wchar_t *suggestion=L"",
|
||||
const wchar_t *filter=L"All files\0*.*\0")
|
||||
{
|
||||
wchar_t path[32768]{};
|
||||
wcsncpy_s(path,suggestion,_TRUNCATE);
|
||||
OPENFILENAMEW dialog{sizeof(dialog)};
|
||||
dialog.hwndOwner=owner;
|
||||
dialog.lpstrFilter=L"All files\0*.*\0";
|
||||
dialog.lpstrFilter=filter;
|
||||
dialog.lpstrFile=path;
|
||||
dialog.nMaxFile=std::size(path);
|
||||
dialog.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|(save?OFN_OVERWRITEPROMPT:OFN_FILEMUSTEXIST);
|
||||
if(save?GetSaveFileNameW(&dialog):GetOpenFileNameW(&dialog))return path;
|
||||
return {};
|
||||
}
|
||||
|
||||
struct LanClientsView
|
||||
{
|
||||
App *app{};
|
||||
nlohmann::json entries;
|
||||
};
|
||||
void refreshLanClients(HWND window, LanClientsView &view)
|
||||
{
|
||||
view.entries = lanRequest(*view.app, {{"action", "trustedClients"}});
|
||||
SendDlgItemMessageW(window, 732, LB_RESETCONTENT, 0, 0);
|
||||
for (const auto &entry : view.entries)
|
||||
{
|
||||
auto path = wide(entry.at("path").get<std::string>());
|
||||
if (path.starts_with(L"\\\\?\\UNC\\")) path = L"\\\\" + path.substr(8);
|
||||
else if (path.starts_with(L"\\\\?\\")) path.erase(0, 4);
|
||||
SendDlgItemMessageW(window, 732, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(path.c_str()));
|
||||
const auto width = scale(window, int(path.size()) * 9);
|
||||
if (width > SendDlgItemMessageW(window, 732, LB_GETHORIZONTALEXTENT, 0, 0))
|
||||
SendDlgItemMessageW(window, 732, LB_SETHORIZONTALEXTENT, width, 0);
|
||||
}
|
||||
EnableWindow(GetDlgItem(window, 734), FALSE);
|
||||
}
|
||||
LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
auto *view = reinterpret_cast<LanClientsView *>(GetWindowLongPtrW(window, GWLP_USERDATA));
|
||||
if (msg == WM_DPICHANGED) { resizeForDpi(window, wp, lp); return 0; }
|
||||
if (msg == WM_CLOSE || (msg == WM_COMMAND && LOWORD(wp) == IDCANCEL))
|
||||
{
|
||||
DestroyWindow(window);
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_DESTROY)
|
||||
{
|
||||
const auto parent = GetWindow(window, GW_OWNER);
|
||||
EnableWindow(parent, TRUE);
|
||||
SetForegroundWindow(parent);
|
||||
delete view;
|
||||
return 0;
|
||||
}
|
||||
if (view && msg == WM_COMMAND)
|
||||
{
|
||||
const auto id = LOWORD(wp);
|
||||
const auto index = SendDlgItemMessageW(window, 732, LB_GETCURSEL, 0, 0);
|
||||
if (id == 732 && HIWORD(wp) == LBN_SELCHANGE)
|
||||
{
|
||||
EnableWindow(GetDlgItem(window, 734), index != LB_ERR);
|
||||
return 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (id == 733)
|
||||
{
|
||||
const auto path = pickLanFile(window, false, L"", L"Windows executables (*.exe)\0*.exe\0");
|
||||
if (!path.empty() && MessageBoxW(window,
|
||||
(L"Allow this application to browse and download files from paired computers?\n\n" + path.wstring()).c_str(),
|
||||
L"Trust a LAN client", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) == IDYES)
|
||||
{
|
||||
lanRequest(*view->app, {{"action", "trustClient"}, {"path", utf8(path.wstring())}});
|
||||
refreshLanClients(window, *view);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (id == 734 && index >= 0 && size_t(index) < view->entries.size())
|
||||
{
|
||||
lanRequest(*view->app, {{"action", "removeClient"}, {"path", view->entries[size_t(index)].at("path")}});
|
||||
refreshLanClients(window, *view);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
MessageBoxW(window, wide(error.what()).c_str(), L"Trusted clients", MB_OK | MB_ICONERROR);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return DefWindowProcW(window, msg, wp, lp);
|
||||
}
|
||||
void showLanClients(HWND parent, App &app)
|
||||
{
|
||||
auto window = makeWindow(app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 280, 0, false);
|
||||
SetWindowLongPtrW(window, GWLP_HWNDPARENT, reinterpret_cast<LONG_PTR>(parent));
|
||||
auto view = new LanClientsView{&app};
|
||||
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(view));
|
||||
label(window, L"Trusted executables can browse and download files from paired computers.", 16, 14, 578);
|
||||
control(window, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | WS_BORDER | LBS_NOTIFY |
|
||||
LBS_NOINTEGRALHEIGHT, 732, 16, 42, 578, 152);
|
||||
label(window, L"Add the executable again after updating it.", 16, 202, 578);
|
||||
button(window, L"&Add client…", 733, 16, 236, 126);
|
||||
button(window, L"&Remove", 734, 150, 236, 110);
|
||||
button(window, L"&Close", IDCANCEL, 494, 236, 100);
|
||||
try { refreshLanClients(window, *view); }
|
||||
catch (...) { DestroyWindow(window); throw; }
|
||||
EnableWindow(parent, FALSE);
|
||||
showRequestedWindow(window);
|
||||
SetForegroundWindow(window);
|
||||
}
|
||||
LRESULT CALLBACK lanHelpProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(msg==WM_DPICHANGED){resizeForDpi(w,wp,lp);return 0;}
|
||||
@@ -67,13 +164,13 @@ void refreshLan(HWND w,LanView &v)
|
||||
if(state=="ready")
|
||||
{
|
||||
v.logRequest.clear();
|
||||
v.transferMessage.clear();
|
||||
v.logMessage.clear();
|
||||
atomicWrite(v.logDestination,decodeLanLog(reply.at("logHex")));
|
||||
v.transferMessage=L"Diagnostic log saved.";
|
||||
v.logMessage=L"Diagnostic log saved.";
|
||||
}
|
||||
else if(state=="denied")v.transferMessage=L"Remote diagnostic downloads are disabled on that PC.";
|
||||
else if(state=="unavailable")v.transferMessage=L"The selected log is unavailable on that PC.";
|
||||
else v.transferMessage=L"The remote log download timed out.";
|
||||
else if(state=="denied")v.logMessage=L"Remote diagnostic downloads are disabled on that PC.";
|
||||
else if(state=="unavailable")v.logMessage=L"The selected log is unavailable on that PC.";
|
||||
else v.logMessage=L"The remote log download timed out.";
|
||||
v.logRequest.clear();
|
||||
}
|
||||
}
|
||||
@@ -91,14 +188,8 @@ void refreshLan(HWND w,LanView &v)
|
||||
for(const auto &peer:next["peers"])
|
||||
{
|
||||
auto id=peer.at("id").get<std::string>();ids.push_back(id);
|
||||
std::wstring state=L"Not paired";
|
||||
if(peer.at("paired").get<bool>()){
|
||||
bool connected=next.value("inputReady",nlohmann::json::object()).contains(id);
|
||||
state=connected?L"Pair saved — input connected":
|
||||
!next.value("shareInput",false)?L"Pair saved — input disabled here":
|
||||
!peer.value("online",false)?L"Pair saved — computer offline":L"Pair saved — input not connected";
|
||||
}
|
||||
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"] — "+state);
|
||||
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"]"+
|
||||
(peer.at("paired").get<bool>()?L" — Paired":L""));
|
||||
}
|
||||
// Presence/challenge refreshes must not repaint or reset the pairing list.
|
||||
if(v.ids!=ids||v.rows!=rows)
|
||||
@@ -131,39 +222,49 @@ void refreshLan(HWND w,LanView &v)
|
||||
std::wstring peerName;
|
||||
for(const auto &peer:v.snapshot["peers"])
|
||||
if(peer.at("id")==v.snapshot.value("pendingPeer",std::string{}))peerName=wide(peer.at("name").get<std::string>());
|
||||
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair there too. Pair is not saved yet.";
|
||||
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair on the other PC.";
|
||||
}
|
||||
value(w,708,v.error.empty() ? pairingStatus : v.error);
|
||||
value(w,705,pending ? L"Waiting..." : L"&Pair");
|
||||
value(w,710,v.ids.empty() ? (enabled ? L"No KSwitcher found. Enable discovery on the other PC too. UDP 45883 must be allowed on your private network." : L"Discovery is disabled on this computer.") : L"Select the matching KSwitcher name and ID shown on the other computer.");
|
||||
const wchar_t *peerStatus=L"Select the name and ID shown on the other PC.";
|
||||
if(v.ids.empty()) peerStatus=enabled?L"No computers found. Enable discovery on both PCs and allow UDP 45883.":
|
||||
L"Discovery is disabled on this computer.";
|
||||
else if(paired)
|
||||
{
|
||||
const bool connected=v.snapshot.value("inputReady",nlohmann::json::object()).contains(selected);
|
||||
peerStatus=connected?L"Pair saved — input connected":
|
||||
!v.snapshot.value("shareInput",false)?L"Pair saved — input disabled here":
|
||||
!online?L"Pair saved — computer offline":L"Pair saved — input not connected";
|
||||
}
|
||||
value(w,710,peerStatus);
|
||||
EnableWindow(GetDlgItem(w,705),enabled&&online&&!pending&&!paired);
|
||||
EnableWindow(GetDlgItem(w,706),pending);
|
||||
EnableWindow(GetDlgItem(w,707),paired);
|
||||
bool canTransfer=false;
|
||||
bool canDownloadLogs=false;
|
||||
for(const auto &peer:v.snapshot["peers"])
|
||||
if(peer.at("id")==selected)canTransfer=paired&&peer.value("verified",false)&&peer.value("fileTransfer",false);
|
||||
EnableWindow(GetDlgItem(w,726),canTransfer);
|
||||
EnableWindow(GetDlgItem(w,727),canTransfer&&v.logRequest.empty());
|
||||
EnableWindow(GetDlgItem(w,728),canTransfer&&v.logRequest.empty());
|
||||
EnableWindow(GetDlgItem(w,730),!v.snapshot["files"].empty());
|
||||
if(peer.at("id")==selected)canDownloadLogs=paired&&peer.value("verified",false)&&peer.value("fileTransfer",false);
|
||||
EnableWindow(GetDlgItem(w,727),canDownloadLogs&&v.logRequest.empty());
|
||||
EnableWindow(GetDlgItem(w,728),canDownloadLogs&&v.logRequest.empty());
|
||||
CheckDlgButton(w,729,v.snapshot.value("shareLogs",false)?BST_CHECKED:BST_UNCHECKED);
|
||||
auto fileCount=v.snapshot["files"].size();
|
||||
auto transferStatus=v.transferMessage;
|
||||
if(transferStatus.empty())transferStatus=wide(v.snapshot.value("transferStatus",std::string{}));
|
||||
value(w,731,fileCount?L"Incoming files: "+std::to_wstring(fileCount):transferStatus);
|
||||
if (value(w, 731) != v.logMessage)
|
||||
{
|
||||
value(w, 731, v.logMessage);
|
||||
ShowWindow(GetDlgItem(w, 731), v.logMessage.empty() ? SW_HIDE : SW_SHOWNA);
|
||||
arrangeWindow(GetParent(w));
|
||||
arrangeWindow(w);
|
||||
}
|
||||
for(int id:{703,704}) EnableWindow(GetDlgItem(w,id),enabled&&!pending&&!paired);
|
||||
auto positions=v.snapshot.value("positions",nlohmann::json::object());
|
||||
EnableWindow(GetDlgItem(w,715),enabled&&!positions.empty()&&!v.snapshot.value("shareInput",false));
|
||||
EnableWindow(GetDlgItem(w,716),v.snapshot.value("shareInput",false));
|
||||
auto gridState=positions.dump()+v.snapshot["peers"].dump()+selected+v.snapshot.value("controlPeer",std::string{})+v.snapshot.value("inputReady",nlohmann::json::object()).dump()+(v.snapshot.value("shareInput",false)?"1":"0");
|
||||
if(gridState!=v.gridState){v.gridState=std::move(gridState);InvalidateRect(GetDlgItem(w,721),nullptr,FALSE);}
|
||||
std::wstring detail=L"Drag paired monitors to empty cells. This PC stays fixed. Arrow keys also work.";
|
||||
detail=L"Drag monitors to neighboring cells. Mouse crosses shared edges; empty cells block passage.";
|
||||
const std::wstring detail=L"Drag monitors or use arrow keys. The pointer crosses shared edges.";
|
||||
value(w,719,v.error.empty()?detail:v.error);
|
||||
auto inputStatus=wide(v.snapshot.value("inputStatus",std::string("Input sharing disabled.")));
|
||||
if(!v.snapshot.value("shareInput",false))
|
||||
inputStatus=!enabled ? L"Enable discovery to set up mouse and keyboard sharing." :
|
||||
selected.empty() ? L"Select a computer in the list above to enable input." :
|
||||
selected.empty() ? L"Select a computer in the pairing list to enable input." :
|
||||
!paired ? L"Pair the selected computer first." :
|
||||
L"Arrange the monitors, then enable input sharing on all PCs.";
|
||||
auto mode=v.snapshot.value("controlMode",0);
|
||||
@@ -175,14 +276,43 @@ void refreshLan(HWND w,LanView &v)
|
||||
#include "ui_lan_layout.inl"
|
||||
LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(msg==WM_DPICHANGED) {resizeForDpi(w,wp,lp);return 0;}
|
||||
if (msg == WM_SIZE) arrangeWindow(w);
|
||||
auto v=(LanView*)GetWindowLongPtrW(w,GWLP_USERDATA);
|
||||
if(!v) return DefWindowProcW(w,msg,wp,lp);
|
||||
if(msg==WM_DESTROY) {DestroyWindow(GetDlgItem(w,721));KillTimer(w,1);EnableWindow(v->parent,TRUE);SetForegroundWindow(v->parent);delete v;SetWindowLongPtrW(w,GWLP_USERDATA,0);return 0;}
|
||||
if(msg==WM_CLOSE||(msg==WM_COMMAND&&LOWORD(wp)==IDCANCEL)) {DestroyWindow(w);return 0;}
|
||||
if (msg == WM_NCDESTROY)
|
||||
{
|
||||
KillTimer(w, 1);
|
||||
delete windowLayoutState(w);
|
||||
RemovePropW(w, L"WindowLayout");
|
||||
delete v;
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||
return DefWindowProcW(w, msg, wp, lp);
|
||||
}
|
||||
if (msg == WM_CTLCOLORSTATIC)
|
||||
return SendMessageW(GetParent(w), msg, wp, lp);
|
||||
if (msg == WM_PAINT)
|
||||
{
|
||||
paintSettingsMatches(w);
|
||||
return 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
if(msg==WM_TIMER) {refreshLan(w,*v);return 0;}
|
||||
if (msg == WM_SHOWWINDOW)
|
||||
{
|
||||
if (wp)
|
||||
{
|
||||
SetTimer(w, 1, 1000, nullptr);
|
||||
refreshLan(w, *v);
|
||||
}
|
||||
else if (v->logRequest.empty()) KillTimer(w, 1);
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_TIMER && wp == 1)
|
||||
{
|
||||
if (IsWindowVisible(w) || !v->logRequest.empty()) refreshLan(w, *v);
|
||||
else KillTimer(w, 1);
|
||||
return 0;
|
||||
}
|
||||
if(msg==WM_COMMAND)
|
||||
{
|
||||
int id=LOWORD(wp); auto peer=selectedLan(w,*v);
|
||||
@@ -190,7 +320,8 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
if(HIWORD(wp)!=BN_CLICKED) return DefWindowProcW(w,msg,wp,lp);
|
||||
if(!IsWindowEnabled(GetDlgItem(w,id)))return 0;
|
||||
v->error.clear();
|
||||
if(id==722){showLanHelp(w,*v->app);return 0;}
|
||||
if(id==722){showLanHelp(v->owner,*v->app);return 0;}
|
||||
if(id==735){showLanClients(v->owner,*v->app);return 0;}
|
||||
if(id==701) lanRequest(*v->app,{{"action","enable"},{"enabled",!v->snapshot.value("enabled",false)}});
|
||||
if(id==704)
|
||||
{
|
||||
@@ -201,49 +332,18 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
if(id==705) lanRequest(*v->app,{{"action","pair"},{"peer",peer},{"code",utf8(value(w,703))}});
|
||||
if(id==706) lanRequest(*v->app,{{"action","cancel"}});
|
||||
if(id==707) lanRequest(*v->app,{{"action","forget"},{"peer",peer}});
|
||||
if(id==726)
|
||||
{
|
||||
auto file=pickLanFile(w,false);
|
||||
if(!file.empty())
|
||||
{
|
||||
lanRequest(*v->app,{{"action","sendFile"},{"peer",peer},{"path",utf8(file.wstring())}});
|
||||
v->transferMessage.clear();
|
||||
}
|
||||
}
|
||||
if(id==727||id==728)
|
||||
{
|
||||
auto destination=pickLanFile(w,true,id==728?L"kswitcher-previous.log":L"kswitcher-remote.log");
|
||||
auto destination=pickLanFile(v->owner,true,id==728?L"kswitcher-previous.log":L"kswitcher-remote.log");
|
||||
if(!destination.empty())
|
||||
{
|
||||
auto reply=lanRequest(*v->app,{{"action","requestLog"},{"peer",peer},{"previous",id==728}});
|
||||
v->logDestination=std::move(destination);
|
||||
v->logRequest=reply.at("request").get<std::string>();
|
||||
v->transferMessage=L"Downloading diagnostic log...";
|
||||
v->logMessage=L"Downloading diagnostic log...";
|
||||
}
|
||||
}
|
||||
if(id==729)lanRequest(*v->app,{{"action","shareLogs"},{"enabled",IsDlgButtonChecked(w,729)==BST_CHECKED}});
|
||||
if(id==730 && !v->snapshot["files"].empty())
|
||||
{
|
||||
const auto file=v->snapshot["files"].front();
|
||||
auto name=wide(file.at("name").get<std::string>());
|
||||
auto question=wide(file.at("sender").get<std::string>())+L" sent "+name+L" ("+
|
||||
std::to_wstring(file.at("size").get<size_t>())+L" bytes).\n\nSave this file? Choose No to discard it.";
|
||||
auto answer=MessageBoxW(w,question.c_str(),L"Incoming file",MB_YESNOCANCEL|MB_ICONQUESTION);
|
||||
if(answer==IDYES || answer==IDNO)
|
||||
{
|
||||
// A peer supplies the display name. Only offer it as a plain Windows filename.
|
||||
const bool validName = !name.empty() && name.size() <= 255 &&
|
||||
name.find_first_of(L"<>:\"/\\|?*") == name.npos &&
|
||||
name.back() != L'.' && name.back() != L' ' &&
|
||||
std::none_of(name.begin(), name.end(), [](wchar_t c) { return c < L' '; });
|
||||
auto destination=answer==IDYES?pickLanFile(w,true,validName?name.c_str():L"received-file"):
|
||||
std::filesystem::path{};
|
||||
if(answer==IDNO||!destination.empty())
|
||||
lanRequest(*v->app,{{"action",answer==IDYES?"saveFile":"discardFile"},{"id",file.at("id")},
|
||||
{"peer",file.at("peer")},{"path",utf8(destination.wstring())}});
|
||||
}
|
||||
v->transferMessage.clear();
|
||||
}
|
||||
if(id==715)
|
||||
{
|
||||
lanRequest(*v->app,{{"action","input"},{"enabled",true}});
|
||||
@@ -255,41 +355,82 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
catch(const std::exception &e) {v->error=wide(e.what());value(w,708,v->error);}
|
||||
return DefWindowProcW(w,msg,wp,lp);
|
||||
}
|
||||
void showLan(HWND parent,App &app)
|
||||
constexpr int LanPadding = 16, LanPairingWidth = 332, LanLayoutLeft = 366, LanLayoutWidth = 348;
|
||||
constexpr int LanDiagnosticsTop = 364;
|
||||
constexpr int LanSettingsWidth = LanLayoutLeft + LanLayoutWidth + LanPadding, LanSettingsHeight = 506;
|
||||
HWND createLanSettings(HWND pane, App &app)
|
||||
{
|
||||
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,740,908,0,false);
|
||||
SetWindowLongPtrW(w,GWLP_HWNDPARENT,(LONG_PTR)parent);
|
||||
auto v=new LanView{parent,&app};SetWindowLongPtrW(w,GWLP_USERDATA,(LONG_PTR)v);
|
||||
label(w,L"Changes here save automatically. No need to click Save in Settings.",18,16,700);
|
||||
control(w,L"STATIC",L"",0,709,18,45,700,24);
|
||||
button(w,L"&Enable discovery",701,18,78,210);
|
||||
label(w,L"Only enabled KSwitcher instances announce themselves.",244,82,470);
|
||||
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,18,120,700,96);
|
||||
control(w,L"STATIC",L"",0,710,18,224,700,40);
|
||||
label(w,L"Same pairing c&ode on both computers",18,273,700);
|
||||
edit(w,703,18,301,470);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
|
||||
button(w,L"&Generate code",704,504,300,214);
|
||||
label(w,L"Generate once, enter that code on both PCs, select each other, then click Pair on both.",18,338,700);
|
||||
button(w,L"&Pair",705,18,370,140);button(w,L"Cancel &pairing",706,174,370,160);button(w,L"&Forget pair",707,350,370,160);
|
||||
control(w,L"STATIC",L"",0,708,18,412,700,40);
|
||||
label(w,L"Arrange your computers",18,458,700);
|
||||
WNDCLASSW panel{};
|
||||
panel.hInstance = app.instance;
|
||||
panel.lpfnWndProc = lanProc;
|
||||
panel.lpszClassName = L"KSwitcher.LAN.Settings";
|
||||
panel.hCursor = LoadCursorW(nullptr, IDC_ARROW);
|
||||
panel.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
|
||||
RegisterClassW(&panel);
|
||||
HWND w = CreateWindowExW(WS_EX_CONTROLPARENT, panel.lpszClassName, L"",
|
||||
WS_CHILD | WS_CLIPCHILDREN, 0, 0, scale(pane, LanSettingsWidth),
|
||||
scale(pane, LanSettingsHeight), pane, reinterpret_cast<HMENU>(262), app.instance, nullptr);
|
||||
if (!w) throw std::runtime_error("Cannot create computer settings.");
|
||||
auto v = new LanView{GetAncestor(pane, GA_ROOT), &app};
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(v));
|
||||
SetPropW(w, L"Font", GetPropW(pane, L"Font"));
|
||||
auto layout = new WindowLayout{LanSettingsWidth, LanSettingsHeight, 0, 0, true, true};
|
||||
SetPropW(w, L"WindowLayout", layout);
|
||||
constexpr int left = LanPadding, pairingWidth = LanPairingWidth, right = LanLayoutLeft, rightWidth = LanLayoutWidth;
|
||||
constexpr int gap = 10, rowHeight = 28;
|
||||
constexpr int discoveryWidth = (pairingWidth - gap) / 2;
|
||||
settingsGroupLabel(w, L"Pairing", left, 14, pairingWidth);
|
||||
control(w, L"STATIC", L"", 0, 709, left, 39, pairingWidth, 22);
|
||||
button(w, L"&Enable discovery", 701, left, 65, discoveryWidth);
|
||||
button(w, L"&Trusted clients…", 735, left + discoveryWidth + gap, 65, discoveryWidth);
|
||||
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | WS_BORDER | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT,
|
||||
702, left, 98, pairingWidth, 70);
|
||||
control(w, L"STATIC", L"", 0, 710, left, 173, pairingWidth, 33);
|
||||
constexpr int codeTop = 235, actionTop = codeTop + rowHeight + 8;
|
||||
constexpr int generateWidth = 135, codeWidth = pairingWidth - gap - generateWidth;
|
||||
constexpr int actionWidth = (pairingWidth - 2 * gap) / 3, actionStep = actionWidth + gap;
|
||||
label(w, L"Same pairing c&ode on both PCs", left, 211, pairingWidth);
|
||||
edit(w, 703, left, codeTop, codeWidth, rowHeight);
|
||||
SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
|
||||
button(w, L"&Generate code", 704, left + codeWidth + gap, codeTop, generateWidth);
|
||||
button(w, L"&Pair", 705, left, actionTop, actionWidth);
|
||||
button(w, L"Ca&ncel", 706, left + actionStep, actionTop, actionWidth);
|
||||
button(w, L"&Forget pair", 707, left + 2 * actionStep, actionTop, actionWidth);
|
||||
control(w, L"STATIC", L"", 0, 708, left, actionTop + rowHeight + 5, pairingWidth, 42);
|
||||
|
||||
constexpr int gridTop = 43, gridHeight = 151, inputButtonWidth = (rightWidth - gap) / 2;
|
||||
settingsGroupLabel(w, L"Input sharing", right, 14, rightWidth);
|
||||
WNDCLASSW gridClass{};gridClass.lpfnWndProc=lanGridProc;gridClass.hInstance=app.instance;gridClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);gridClass.lpszClassName=L"KSwitcher.LAN.Layout";RegisterClassW(&gridClass);
|
||||
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer above, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
|
||||
scale(w,18),scale(w,486),scale(w,700),scale(w,180),w,reinterpret_cast<HMENU>(721),app.instance,v);
|
||||
windowLayoutState(w)->controls.push_back({grid,{18,486,718,666}});
|
||||
control(w,L"STATIC",L"",0,719,18,674,700,24);
|
||||
button(w,L"Enable &input sharing",715,18,706,330);
|
||||
button(w,L"&Stop input sharing",716,370,706,240);
|
||||
control(w,L"STATIC",L"",0,718,18,744,700,30);
|
||||
button(w,L"Send file…",726,18,774,144);
|
||||
button(w,L"Incoming files…",730,174,774,160);
|
||||
button(w,L"Download log…",727,346,774,164);
|
||||
button(w,L"Previous log…",728,522,774,196);
|
||||
control(w,L"BUTTON",L"Allow paired computers to download diagnostic logs",BS_AUTOCHECKBOX|WS_TABSTOP,729,18,808,700,24);
|
||||
control(w,L"STATIC",L"",0,731,18,835,700,24);
|
||||
button(w,L"Connection &help",722,18,864,300);
|
||||
button(w,L"&Close",IDCANCEL,618,864,100);
|
||||
EnableWindow(parent,FALSE);showRequestedWindow(w);SetForegroundWindow(w);
|
||||
SetTimer(w,1,1000,nullptr);
|
||||
try {refreshLan(w,*v);} catch(const std::exception &e){v->error=wide(e.what());value(w,708,v->error);}
|
||||
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer in the list, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
|
||||
scale(w,right),scale(w,gridTop),scale(w,rightWidth),scale(w,gridHeight),w,reinterpret_cast<HMENU>(721),app.instance,v);
|
||||
windowLayoutState(w)->controls.push_back({grid,{right,gridTop,right+rightWidth,gridTop+gridHeight}});
|
||||
control(w, L"STATIC", L"", 0, 719, right, 200, rightWidth, 35);
|
||||
button(w, L"Enable &input sharing", 715, right, 240, inputButtonWidth);
|
||||
button(w, L"&Stop input sharing", 716, right + inputButtonWidth + gap, 240, inputButtonWidth);
|
||||
control(w, L"STATIC", L"", 0, 718, right, 274, rightWidth, 38);
|
||||
button(w, L"Connection &help", 722, right, 317, 232);
|
||||
|
||||
constexpr int fullWidth = right + rightWidth - left;
|
||||
constexpr int logButtonWidth = (fullWidth - gap) / 2;
|
||||
settingsGroupLabel(w, L"Diagnostic logs", left, LanDiagnosticsTop, fullWidth);
|
||||
checkbox(w, L"Allow paired computers to download logs", 729, left, LanDiagnosticsTop + 28, fullWidth);
|
||||
button(w, L"Current log…", 727, left, LanDiagnosticsTop + 62, logButtonWidth);
|
||||
button(w, L"Previous log…", 728, left + logButtonWidth + gap, LanDiagnosticsTop + 62, logButtonWidth);
|
||||
ShowWindow(control(w, L"STATIC", L"", 0, 731, left, LanDiagnosticsTop + 96, fullWidth, 22), SW_HIDE);
|
||||
SetWindowSubclass(grid, scrollChildProc, 2, 0);
|
||||
captureSettingsGeometry(*layout, 0, w);
|
||||
layout->arranging = false;
|
||||
return w;
|
||||
}
|
||||
|
||||
int fitLanSettings(HWND panel, int width)
|
||||
{
|
||||
auto &layout = *windowLayoutState(panel);
|
||||
layout.width = 1;
|
||||
// The final control is feedback for the diagnostic log actions.
|
||||
const auto end = layout.controls.size() - (GetWindowTextLengthW(GetDlgItem(panel, 731)) ? 0 : 1);
|
||||
layout.height = fitSettingsColumns(layout, 0, end, width,
|
||||
{LanPadding, LanLayoutLeft + LanLayoutWidth, LanLayoutLeft, LanPadding + LanPairingWidth,
|
||||
LanDiagnosticsTop, 640});
|
||||
return layout.height;
|
||||
}
|
||||
+150
-52
@@ -1,12 +1,96 @@
|
||||
std::wstring selectedMouseProfile(HWND w, const SettingsView &view)
|
||||
{
|
||||
const auto row = ListView_GetNextItem(GetDlgItem(w, 731), -1, LVNI_SELECTED);
|
||||
const auto row = ListView_GetNextItem(GetDlgItem(settingsPage(w), 731), -1, LVNI_SELECTED);
|
||||
return row < 0 || static_cast<size_t>(row) >= view.mouseProfiles.size() ? GlobalMouseProfile : view.mouseProfiles[row];
|
||||
}
|
||||
|
||||
constexpr int RenameMouseProfile = 757, DeleteMouseProfile = 758;
|
||||
constexpr int AddMouseEvent = 762, MouseEventCapture = 763, MouseEventNameField = 764, MouseEventStatus = 765;
|
||||
|
||||
void prepareMouseProfileChecks(HWND list, SettingsView &view)
|
||||
{
|
||||
const auto native = ListView_GetImageList(list, LVSIL_STATE);
|
||||
int width{}, height{};
|
||||
if (!native || !ImageList_GetIconSize(native, &width, &height)) return;
|
||||
const auto checked = ImageList_GetIcon(native, 1, ILD_TRANSPARENT);
|
||||
const auto unchecked = ImageList_GetIcon(native, 0, ILD_TRANSPARENT);
|
||||
// Keep the native checked states and keyboard handling. Use transparent state
|
||||
// images so only the glyph we place at the center of the column is visible.
|
||||
const auto blank = ImageList_Create(1, height, ILC_COLOR32 | ILC_MASK, 2, 0);
|
||||
const std::vector<WORD> white(height, 0xFFFF);
|
||||
const auto mask = CreateBitmap(1, height, 1, 1, white.data());
|
||||
const bool ready = blank && checked && unchecked && mask &&
|
||||
ImageList_Add(blank, mask, mask) == 0 && ImageList_Add(blank, mask, mask) == 1;
|
||||
if (mask) DeleteObject(mask);
|
||||
if (!ready)
|
||||
{
|
||||
if (blank) ImageList_Destroy(blank);
|
||||
if (checked) DestroyIcon(checked);
|
||||
if (unchecked) DestroyIcon(unchecked);
|
||||
return;
|
||||
}
|
||||
if (const auto previous = ListView_SetImageList(list, blank, LVSIL_STATE)) ImageList_Destroy(previous);
|
||||
view.mouseProfileChecks = {unchecked, checked};
|
||||
const auto dpi = GetDpiForWindow(list);
|
||||
view.mouseProfileCheckSize = {MulDiv(width, 96, dpi), MulDiv(height, 96, dpi)};
|
||||
}
|
||||
bool mouseProfileCheckBounds(HWND list, const SettingsView &view, int row, RECT &glyph, RECT &cell)
|
||||
{
|
||||
if (row < 0 || !view.mouseProfileChecks.front()) return false;
|
||||
const auto header = ListView_GetHeader(list);
|
||||
RECT column{}, item{};
|
||||
if (!Header_GetItemRect(header, 0, &column) || !ListView_GetItemRect(list, row, &item, LVIR_BOUNDS))
|
||||
return false;
|
||||
MapWindowPoints(header, list, reinterpret_cast<POINT *>(&column), 2);
|
||||
const int width = scale(list, view.mouseProfileCheckSize.cx), height = scale(list, view.mouseProfileCheckSize.cy);
|
||||
const LONG left = column.left + (column.right - column.left - width) / 2;
|
||||
const LONG top = item.top + (item.bottom - item.top - height) / 2;
|
||||
glyph = {left, top, left + width, top + height};
|
||||
cell = {column.left, item.top, column.right, item.bottom};
|
||||
return true;
|
||||
}
|
||||
LRESULT drawMouseProfileChecks(const SettingsView &view, const NMLVCUSTOMDRAW &draw)
|
||||
{
|
||||
if (!view.mouseProfileChecks.front()) return CDRF_DODEFAULT;
|
||||
if (draw.nmcd.dwDrawStage == CDDS_PREPAINT) return CDRF_NOTIFYITEMDRAW;
|
||||
if (draw.nmcd.dwDrawStage == CDDS_ITEMPREPAINT) return CDRF_NOTIFYPOSTPAINT;
|
||||
if (draw.nmcd.dwDrawStage == CDDS_ITEMPOSTPAINT)
|
||||
{
|
||||
const auto list = draw.nmcd.hdr.hwndFrom;
|
||||
const auto row = static_cast<int>(draw.nmcd.dwItemSpec);
|
||||
RECT glyph{}, cell{};
|
||||
if (mouseProfileCheckBounds(list, view, row, glyph, cell))
|
||||
{
|
||||
const auto saved = SaveDC(draw.nmcd.hdc);
|
||||
IntersectClipRect(draw.nmcd.hdc, cell.left, cell.top, cell.right, cell.bottom);
|
||||
// The list view reserves a small strip for its native state image and
|
||||
// paints it separately from the selected row. Blend that strip back in.
|
||||
const int strip = scale(list, 4);
|
||||
if (cell.right - cell.left > 2 * strip)
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(list, &client);
|
||||
const int sample = std::min<int>(cell.right - strip, client.right - 1);
|
||||
if (sample > cell.left + strip)
|
||||
{
|
||||
const auto background = GetPixel(draw.nmcd.hdc, sample, (cell.top + cell.bottom) / 2);
|
||||
if (background != CLR_INVALID)
|
||||
{
|
||||
SetDCBrushColor(draw.nmcd.hdc, background);
|
||||
RECT nativeStrip{cell.left, cell.top + 1, cell.left + strip, cell.bottom - 1};
|
||||
FillRect(draw.nmcd.hdc, &nativeStrip, reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto icon = view.mouseProfileChecks[ListView_GetCheckState(list, row) != FALSE];
|
||||
DrawIconEx(draw.nmcd.hdc, glyph.left, glyph.top, icon, glyph.right - glyph.left,
|
||||
glyph.bottom - glyph.top, 0, nullptr, DI_NORMAL);
|
||||
RestoreDC(draw.nmcd.hdc, saved);
|
||||
}
|
||||
}
|
||||
return CDRF_DODEFAULT;
|
||||
}
|
||||
|
||||
std::wstring mouseActionLabel(const MouseAction &action)
|
||||
{
|
||||
if (action.type == MouseActionType::Shortcut) return action.shortcut.format();
|
||||
@@ -25,7 +109,7 @@ int mouseEventAtRow(HWND list, int row)
|
||||
|
||||
void selectMouseEvent(HWND w, int event)
|
||||
{
|
||||
HWND list = GetDlgItem(w, 733);
|
||||
HWND list = GetDlgItem(settingsPage(w), 733);
|
||||
LVFINDINFOW search{LVFI_PARAM};
|
||||
search.lParam = event;
|
||||
const int row = ListView_FindItem(list, -1, &search);
|
||||
@@ -37,9 +121,9 @@ void selectMouseEvent(HWND w, int event)
|
||||
void fillMouseEvents(HWND w, SettingsView &view, int selection = 0)
|
||||
{
|
||||
const auto profile = selectedMouseProfile(w, view);
|
||||
EnableWindow(GetDlgItem(w, RenameMouseProfile), isNamedMouseProfile(profile));
|
||||
EnableWindow(GetDlgItem(w, DeleteMouseProfile), isNamedMouseProfile(profile));
|
||||
HWND list = GetDlgItem(w, 733);
|
||||
EnableWindow(GetDlgItem(settingsPage(w), RenameMouseProfile), isNamedMouseProfile(profile));
|
||||
EnableWindow(GetDlgItem(settingsPage(w), DeleteMouseProfile), isNamedMouseProfile(profile));
|
||||
HWND list = GetDlgItem(settingsPage(w), 733);
|
||||
ListView_DeleteAllItems(list);
|
||||
for (int event = 0; event < static_cast<int>(std::size(MouseEvents)); ++event)
|
||||
{
|
||||
@@ -79,14 +163,14 @@ std::set<std::wstring> profileApplications(const Settings &settings, const std::
|
||||
|
||||
void selectMouseProfile(HWND w, int row)
|
||||
{
|
||||
auto list = GetDlgItem(w, 731);
|
||||
auto list = GetDlgItem(settingsPage(w), 731);
|
||||
ListView_SetItemState(list, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
|
||||
ListView_EnsureVisible(list, row, FALSE);
|
||||
}
|
||||
|
||||
void appendMouseProfile(HWND w, SettingsView &view, const std::wstring &profile)
|
||||
{
|
||||
auto list = GetDlgItem(w, 731);
|
||||
auto list = GetDlgItem(settingsPage(w), 731);
|
||||
std::wstring text;
|
||||
for (const auto &app : profile == GlobalMouseProfile ? std::set<std::wstring>{} : profileApplications(view.draft, profile))
|
||||
{
|
||||
@@ -135,7 +219,7 @@ bool blockMouseProfileStateChange(HWND w, SettingsView &view, const NMLISTVIEW &
|
||||
void fillMouseProfiles(HWND w, SettingsView &view)
|
||||
{
|
||||
const auto previous = selectedMouseProfile(w, view);
|
||||
ListView_DeleteAllItems(GetDlgItem(w, 731));
|
||||
ListView_DeleteAllItems(GetDlgItem(settingsPage(w), 731));
|
||||
view.mouseProfiles.clear();
|
||||
appendMouseProfile(w, view, GlobalMouseProfile);
|
||||
for (const auto &[app, bindings] : view.draft.mouseBindings)
|
||||
@@ -163,12 +247,12 @@ LRESULT CALLBACK mouseButtonCaptureProc(HWND field, UINT msg, WPARAM wp, LPARAM
|
||||
{
|
||||
SetFocus(field);
|
||||
SetCapture(field);
|
||||
HWND settings = GetParent(field);
|
||||
HWND settings = GetAncestor(field, GA_ROOT);
|
||||
auto *view = reinterpret_cast<SettingsView *>(GetWindowLongPtrW(settings, GWLP_USERDATA));
|
||||
if (view)
|
||||
selectMouseEvent(settings, doubleClick && button < 3 ? button + 5 : button);
|
||||
if (view)
|
||||
value(settings, 738, std::wstring(L"Window event: ") + MouseButtonNames[button] +
|
||||
value(settingsPage(settings), 738, std::wstring(L"Window event: ") + MouseButtonNames[button] +
|
||||
L" | Presses: " + std::to_wstring(++view->mouseEvents));
|
||||
}
|
||||
else if (GetCapture() == field)
|
||||
@@ -187,7 +271,7 @@ bool registerMouseTestInput(HWND w)
|
||||
|
||||
void readMouseTestInput(HWND w, SettingsView &view, HRAWINPUT handle)
|
||||
{
|
||||
HWND capture = GetDlgItem(w, 737);
|
||||
HWND capture = GetDlgItem(settingsPage(w), 737);
|
||||
if (!IsWindowVisible(capture)) return;
|
||||
RAWINPUT input{};
|
||||
UINT size = sizeof(input);
|
||||
@@ -203,7 +287,7 @@ void readMouseTestInput(HWND w, SettingsView &view, HRAWINPUT handle)
|
||||
{
|
||||
if (!(input.data.mouse.usButtonFlags & downFlags[i])) continue;
|
||||
|
||||
value(w, 739, std::wstring(L"Raw Input: ") + MouseButtonNames[i] +
|
||||
value(settingsPage(w), 739, std::wstring(L"Raw Input: ") + MouseButtonNames[i] +
|
||||
L" | Presses: " + std::to_wstring(++view.rawMouseEvents));
|
||||
}
|
||||
}
|
||||
@@ -272,7 +356,6 @@ struct MouseProfileEditor
|
||||
|
||||
constexpr int ActionApplications = 748, ActionApplicationName = 749, AddActionApp = 750, RemoveActionApp = 751;
|
||||
constexpr int BrowseActionApp = 752;
|
||||
constexpr int PickActionApp = 753;
|
||||
constexpr int AddMouseProfile = 754, MouseProfileName = 755;
|
||||
|
||||
void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
|
||||
@@ -295,7 +378,7 @@ void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
|
||||
FrameRect(item.hDC, &folder, ink);
|
||||
FillRect(item.hDC, &tab, ink);
|
||||
}
|
||||
else if (item.CtlID == PickActionApp)
|
||||
else if (item.CtlID == AppWindowPickerIcon)
|
||||
{
|
||||
RECT target{x - half, y - half, x + half + 1, y + half + 1};
|
||||
RECT horizontal{x - half - weight, y, x + half + weight + 1, y + 1};
|
||||
@@ -344,14 +427,6 @@ void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
|
||||
}
|
||||
}
|
||||
|
||||
void addActionApplicationTooltip(HWND tips, HWND editor, int id, const wchar_t *text)
|
||||
{
|
||||
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, editor,
|
||||
reinterpret_cast<UINT_PTR>(GetDlgItem(editor, id))};
|
||||
tool.lpszText = const_cast<wchar_t *>(text);
|
||||
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
|
||||
}
|
||||
|
||||
void fillActionApplications(HWND w, const MouseProfileEditor &editor)
|
||||
{
|
||||
SendDlgItemMessageW(w, ActionApplications, LB_RESETCONTENT, 0, 0);
|
||||
@@ -501,7 +576,7 @@ LRESULT CALLBACK mouseActionEditorProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
EnableWindow(parent, TRUE);
|
||||
SetForegroundWindow(parent);
|
||||
SetFocus(GetDlgItem(parent, 733));
|
||||
SetFocus(GetDlgItem(settingsPage(parent), 733));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -586,7 +661,7 @@ int mouseProfileRowAt(HWND list, POINT point)
|
||||
|
||||
void showMouseListMenu(HWND list, POINT point, bool profiles)
|
||||
{
|
||||
HWND w = GetParent(list);
|
||||
HWND w = GetAncestor(list, GA_ROOT);
|
||||
int event;
|
||||
if (point.x == -1 && point.y == -1)
|
||||
{
|
||||
@@ -629,15 +704,36 @@ void showMouseListMenu(HWND list, POINT point, bool profiles)
|
||||
if (command) SendMessageW(w, WM_COMMAND, command, 0);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK mouseEventListProc(HWND list, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR)
|
||||
LRESULT CALLBACK mouseEventListProc(HWND list, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR data)
|
||||
{
|
||||
const bool profiles = GetDlgCtrlID(list) == 731;
|
||||
if (profiles && (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK))
|
||||
{
|
||||
const auto &view = *reinterpret_cast<SettingsView *>(data);
|
||||
POINT pt{GET_X_LPARAM(lp), GET_Y_LPARAM(lp)};
|
||||
LVHITTESTINFO hit{pt};
|
||||
ListView_HitTest(list, &hit);
|
||||
const int row = mouseProfileRowAt(list, pt);
|
||||
RECT glyph{}, cell{};
|
||||
if (mouseProfileCheckBounds(list, view, row, glyph, cell))
|
||||
{
|
||||
const bool onGlyph = PtInRect(&glyph, pt) && PtInRect(&cell, pt);
|
||||
if (onGlyph || (msg == WM_LBUTTONDOWN && (hit.flags & LVHT_ONITEMSTATEICON)))
|
||||
{
|
||||
SetFocus(list);
|
||||
selectMouseProfile(GetAncestor(list, GA_ROOT), row);
|
||||
if (onGlyph && msg == WM_LBUTTONDOWN)
|
||||
ListView_SetCheckState(list, row, !ListView_GetCheckState(list, row));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (profiles && msg == WM_LBUTTONDBLCLK)
|
||||
{
|
||||
const int row = mouseProfileRowAt(list, {GET_X_LPARAM(lp), GET_Y_LPARAM(lp)});
|
||||
if (row >= 0)
|
||||
{
|
||||
const auto owner = GetParent(list);
|
||||
const auto owner = GetAncestor(list, GA_ROOT);
|
||||
selectMouseProfile(owner, row);
|
||||
SendMessageW(owner, WM_COMMAND, RenameMouseProfile, 0);
|
||||
}
|
||||
@@ -676,7 +772,7 @@ LRESULT CALLBACK mouseProfileNameProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_DRAWITEM && (wp == AddActionApp || wp == RemoveActionApp || wp == BrowseActionApp || wp == PickActionApp))
|
||||
if (msg == WM_DRAWITEM && (wp == AddActionApp || wp == RemoveActionApp || wp == BrowseActionApp || wp == AppWindowPickerIcon))
|
||||
{
|
||||
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
|
||||
return TRUE;
|
||||
@@ -775,18 +871,13 @@ void showMouseProfileName(HWND owner, SettingsView &view, bool renaming)
|
||||
control(w, L"BUTTON", L"&Remove application", WS_TABSTOP | BS_OWNERDRAW, RemoveActionApp, 430, 100, 32, 28);
|
||||
HWND appName = edit(w, ActionApplicationName, 18, 207, 324);
|
||||
SendMessageW(appName, EM_SETCUEBANNER, FALSE, reinterpret_cast<LPARAM>(L"Application executable (e.g. chrome.exe)"));
|
||||
HWND picker = control(w, L"BUTTON", L"Drag to application window", WS_TABSTOP | BS_OWNERDRAW,
|
||||
PickActionApp, 350, 205, 32, 28);
|
||||
SetWindowSubclass(picker, appWindowPickerProc, 1, reinterpret_cast<DWORD_PTR>(&editor->pickerOutline));
|
||||
HWND tips = createButtonTooltips(w);
|
||||
createAppWindowPicker(w, AppWindowPickerIcon, 350, 205, 32, editor->pickerOutline, tips);
|
||||
control(w, L"BUTTON", L"&Browse for application", WS_TABSTOP | BS_OWNERDRAW, BrowseActionApp, 390, 205, 32, 28);
|
||||
control(w, L"BUTTON", L"Add a&pplication", WS_TABSTOP | BS_OWNERDRAW, AddActionApp, 430, 205, 32, 28);
|
||||
HWND tips = CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, w, nullptr,
|
||||
view.app->instance, nullptr);
|
||||
addActionApplicationTooltip(tips, w, RemoveActionApp, L"Remove application");
|
||||
addActionApplicationTooltip(tips, w, AddActionApp, L"Add application");
|
||||
addActionApplicationTooltip(tips, w, BrowseActionApp, L"Browse for an executable or shortcut");
|
||||
addActionApplicationTooltip(tips, w, PickActionApp, L"Drag to an application window");
|
||||
addButtonTooltip(tips, w, RemoveActionApp, L"Remove application");
|
||||
addButtonTooltip(tips, w, AddActionApp, L"Add application");
|
||||
addButtonTooltip(tips, w, BrowseActionApp, L"Browse for an executable or shortcut");
|
||||
fillActionApplications(w, *editor);
|
||||
control(w, L"BUTTON", renaming ? L"&Apply" : L"&Add", WS_TABSTOP | BS_DEFPUSHBUTTON, IDOK, 248, 251, 100, 28);
|
||||
button(w, L"Cancel", IDCANCEL, 362, 251, 100);
|
||||
@@ -956,7 +1047,7 @@ LRESULT CALLBACK addMouseEventProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
EnableWindow(parent, TRUE);
|
||||
SetForegroundWindow(parent);
|
||||
SetFocus(GetDlgItem(parent, 733));
|
||||
SetFocus(GetDlgItem(settingsPage(parent), 733));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1010,7 +1101,7 @@ bool handleMouseBindings(HWND w, SettingsView &view, WPARAM wp)
|
||||
return true;
|
||||
}
|
||||
if (id != EditMouseEvent && id != ResetMouseEvent) return false;
|
||||
const HWND list = GetDlgItem(w, 733);
|
||||
const HWND list = GetDlgItem(settingsPage(w), 733);
|
||||
const int event = mouseEventAtRow(list, ListView_GetNextItem(list, -1, LVNI_SELECTED));
|
||||
if (event < 0) return true;
|
||||
if (id == EditMouseEvent) showMouseActionEditor(w, view, event);
|
||||
@@ -1028,38 +1119,38 @@ void scaleMouseTableColumns(HWND w, int previousDpi, int nextDpi)
|
||||
{
|
||||
for (int id : {731, 733})
|
||||
{
|
||||
const auto list = GetDlgItem(w, id);
|
||||
const auto list = GetDlgItem(settingsPage(w), id);
|
||||
const int count = Header_GetItemCount(ListView_GetHeader(list));
|
||||
for (int column = 0; column < count; ++column)
|
||||
ListView_SetColumnWidth(list, column, MulDiv(ListView_GetColumnWidth(list, column), nextDpi, previousDpi));
|
||||
}
|
||||
}
|
||||
|
||||
void createMousePage(HWND w, SettingsView &view)
|
||||
void createMousePage(HWND root, SettingsView &view)
|
||||
{
|
||||
HWND w = view.viewport;
|
||||
constexpr int profilesLeft = 18, actionsLeft = 369, tableWidth = 333;
|
||||
constexpr int profilesRight = profilesLeft + tableWidth;
|
||||
label(w, L"Profiles", 18, 64, 120);
|
||||
label(w, L"Mouse events", actionsLeft, 64, tableWidth - 30);
|
||||
settingsGroupLabel(w, L"Profiles", profilesLeft, 64, 120);
|
||||
settingsGroupLabel(w, L"Mouse events", actionsLeft, 64, tableWidth - 30);
|
||||
control(w, L"BUTTON", L"Add mouse event", WS_TABSTOP | BS_OWNERDRAW, AddMouseEvent,
|
||||
actionsLeft + tableWidth - 24, 61, 24, 24);
|
||||
control(w, L"BUTTON", L"Delete profile", WS_TABSTOP | BS_OWNERDRAW, DeleteMouseProfile, profilesRight - 80, 61, 24, 24);
|
||||
control(w, L"BUTTON", L"Edit profile", WS_TABSTOP | BS_OWNERDRAW, RenameMouseProfile, profilesRight - 52, 61, 24, 24);
|
||||
control(w, L"BUTTON", L"Add profile", WS_TABSTOP | BS_OWNERDRAW, AddMouseProfile, profilesRight - 24, 61, 24, 24);
|
||||
HWND tips = CreateWindowExW(WS_EX_TOPMOST, TOOLTIPS_CLASSW, nullptr, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, w, nullptr,
|
||||
view.app->instance, nullptr);
|
||||
addActionApplicationTooltip(tips, w, AddMouseProfile, L"Add profile");
|
||||
addActionApplicationTooltip(tips, w, RenameMouseProfile, L"Edit profile");
|
||||
addActionApplicationTooltip(tips, w, DeleteMouseProfile, L"Delete profile");
|
||||
addActionApplicationTooltip(tips, w, AddMouseEvent, L"Add mouse event");
|
||||
HWND tips = createButtonTooltips(w);
|
||||
addButtonTooltip(tips, w, AddMouseProfile, L"Add profile");
|
||||
addButtonTooltip(tips, w, RenameMouseProfile, L"Edit profile");
|
||||
addButtonTooltip(tips, w, DeleteMouseProfile, L"Delete profile");
|
||||
addButtonTooltip(tips, w, AddMouseEvent, L"Add mouse event");
|
||||
constexpr int listTop = 90, listHeight = 224;
|
||||
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES};
|
||||
InitCommonControlsEx(&controls);
|
||||
constexpr DWORD listStyle = WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER;
|
||||
HWND profiles = control(w, WC_LISTVIEWW, L"", listStyle, 731, profilesLeft, listTop, tableWidth, listHeight);
|
||||
SetWindowSubclass(profiles, mouseEventListProc, 3, 0);
|
||||
SetWindowSubclass(profiles, mouseEventListProc, 3, reinterpret_cast<DWORD_PTR>(&view));
|
||||
ListView_SetExtendedListViewStyle(profiles, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP | LVS_EX_CHECKBOXES);
|
||||
prepareMouseProfileChecks(profiles, view);
|
||||
wchar_t nameTitle[] = L"Name", activeTitle[] = L"Active", applicationsTitle[] = L"Applications";
|
||||
LVCOLUMNW profileColumn{LVCF_TEXT | LVCF_WIDTH};
|
||||
profileColumn.pszText = activeTitle;
|
||||
@@ -1073,6 +1164,13 @@ void createMousePage(HWND w, SettingsView &view)
|
||||
ListView_InsertColumn(profiles, 2, &profileColumn);
|
||||
int order[]{1, 0, 2};
|
||||
ListView_SetColumnOrderArray(profiles, 3, order);
|
||||
HDITEMW alignment{HDI_FORMAT};
|
||||
const auto header = ListView_GetHeader(profiles);
|
||||
if (Header_GetItem(header, 0, &alignment))
|
||||
{
|
||||
alignment.fmt = (alignment.fmt & ~HDF_JUSTIFYMASK) | HDF_CENTER;
|
||||
Header_SetItem(header, 0, &alignment);
|
||||
}
|
||||
HWND list = control(w, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT |
|
||||
LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 733, actionsLeft, listTop, tableWidth, listHeight);
|
||||
SetWindowSubclass(list, mouseEventListProc, 3, 0);
|
||||
@@ -1090,7 +1188,7 @@ void createMousePage(HWND w, SettingsView &view)
|
||||
737, profilesLeft, listTop + listHeight + 10, tableWidth, 56);
|
||||
SetWindowSubclass(GetDlgItem(w, 737), mouseButtonCaptureProc, 1, 0);
|
||||
control(w, L"STATIC", L"Window event: waiting for a press", 0, 738, actionsLeft, 370, tableWidth, 20);
|
||||
view.rawMouseRegistered = registerMouseTestInput(w);
|
||||
view.rawMouseRegistered = registerMouseTestInput(root);
|
||||
control(w, L"STATIC", view.rawMouseRegistered ? L"Raw Input: waiting for a press" : L"Raw Input: unavailable",
|
||||
0, 739, actionsLeft, 394, tableWidth, 20);
|
||||
}
|
||||
+93
-44
@@ -1,5 +1,6 @@
|
||||
#include "ui_sync_conflicts.inl"
|
||||
struct SyncView { HWND parent; App *app; bool actionError{}; };
|
||||
constexpr int SyncSave = 614;
|
||||
struct SyncView { App *app; bool initialized{}, actionError{}; };
|
||||
void updateSyncControls(HWND w, App &app)
|
||||
{
|
||||
bool enabled = checked(w, 601);
|
||||
@@ -7,14 +8,14 @@ void updateSyncControls(HWND w, App &app)
|
||||
for (int id : {602, 603, 604, 605, 606, 607, 610, 611, 613})
|
||||
EnableWindow(GetDlgItem(w, id), enabled);
|
||||
EnableWindow(GetDlgItem(w, 612), enabled && savedEnabled);
|
||||
EnableWindow(GetDlgItem(w, IDOK), enabled || savedEnabled);
|
||||
value(w, IDOK, enabled ? L"&Save / Sign in / Sync" : L"&Save");
|
||||
EnableWindow(GetDlgItem(w, SyncSave), enabled || savedEnabled);
|
||||
value(w, SyncSave, enabled ? L"Save and s&ync" : L"S&ave connection");
|
||||
std::wstring status;
|
||||
if (!enabled)
|
||||
status = savedEnabled ? L"Click Save to disable synchronization." :
|
||||
status = savedEnabled ? L"Click Save connection to disable synchronization." :
|
||||
L"Synchronization is disabled. Enable it above to configure and sync.";
|
||||
else if (!savedEnabled)
|
||||
status = L"Configure the connection, then click Save / Sign in / Sync to enable synchronization.";
|
||||
status = L"Configure the connection, then click Save and sync to enable synchronization.";
|
||||
else
|
||||
status = app.syncCommand();
|
||||
auto *view = reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
@@ -33,11 +34,30 @@ SyncConfig syncFields(HWND w)
|
||||
}
|
||||
LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if (msg == WM_DPICHANGED) { resizeForDpi(w, wp, lp); return 0; }
|
||||
if (msg == WM_SIZE) arrangeWindow(w);
|
||||
auto *v = reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
if (!v) return DefWindowProcW(w, msg, wp, lp);
|
||||
try
|
||||
{
|
||||
if (msg == WM_PAINT) { paintSettingsMatches(w); return 0; }
|
||||
if (msg == WM_CTLCOLORSTATIC) return SendMessageW(GetParent(w), msg, wp, lp);
|
||||
if (msg == WM_SHOWWINDOW)
|
||||
{
|
||||
if (!wp) KillTimer(w, 1);
|
||||
else
|
||||
{
|
||||
if (!v->initialized)
|
||||
{
|
||||
const auto c = loadSyncConfig(v->app->data);
|
||||
check(w, 601, c.enabled); check(w, 613, c.keepLocalLayouts);
|
||||
value(w, 602, c.server); value(w, 603, c.username);
|
||||
value(w, 605, c.mount); value(w, 606, c.path); value(w, 607, c.authMount);
|
||||
v->initialized = true;
|
||||
}
|
||||
updateSyncControls(w, *v->app);
|
||||
SetTimer(w, 1, 1000, nullptr);
|
||||
}
|
||||
}
|
||||
if (msg == WM_TIMER)
|
||||
{
|
||||
updateSyncControls(w, *v->app);
|
||||
@@ -52,10 +72,9 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
updateSyncControls(w, *v->app);
|
||||
return 0;
|
||||
}
|
||||
if ((id == IDOK || id == 610 || id == 611 || id == 612) &&
|
||||
if ((id == SyncSave || id == 610 || id == 611 || id == 612) &&
|
||||
!IsWindowEnabled(GetDlgItem(w, id))) return 0;
|
||||
if (id == 612) { showSyncConflicts(w, *v->app); return 0; }
|
||||
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
|
||||
if (id == 609)
|
||||
{
|
||||
v->actionError = false;
|
||||
@@ -70,12 +89,12 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
KillTimer(w, 1);
|
||||
return 0;
|
||||
}
|
||||
if (id == IDOK || id == 610 || id == 611)
|
||||
if (id == SyncSave || id == 610 || id == 611)
|
||||
{
|
||||
v->actionError = false;
|
||||
if (!checked(w, 601))
|
||||
{
|
||||
if (id != IDOK) return 0;
|
||||
if (id != SyncSave) return 0;
|
||||
auto c = loadSyncConfig(v->app->data);
|
||||
c.enabled = false;
|
||||
saveSyncConfig(v->app->data, c);
|
||||
@@ -83,7 +102,7 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
updateSyncControls(w, *v->app);
|
||||
return 0;
|
||||
}
|
||||
if (id != IDOK && MessageBoxW(w, id == 610 ?
|
||||
if (id != SyncSave && MessageBoxW(GetAncestor(w, GA_ROOT), id == 610 ?
|
||||
L"Replace this PC's shared settings with the remote profile? A local backup will be saved. The open Settings window will refresh automatically; its unsaved edits will be discarded." :
|
||||
L"Replace the remote profile with this PC's saved settings? OpenBao retains older versions according to its retention policy. Unsaved edits are not included.",
|
||||
L"Resolve synchronization", MB_YESNO | MB_ICONWARNING) != IDYES) return 0;
|
||||
@@ -111,44 +130,74 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
value(w, 608, wide(e.what()));
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
|
||||
if (msg == WM_NCDESTROY)
|
||||
{
|
||||
KillTimer(w, 1);
|
||||
EnableWindow(v->parent, TRUE); SetForegroundWindow(v->parent);
|
||||
disposeFont(w); delete v; SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||
delete windowLayoutState(w);
|
||||
RemovePropW(w, L"WindowLayout");
|
||||
RemovePropW(w, L"Font");
|
||||
delete v;
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||
}
|
||||
return DefWindowProcW(w, msg, wp, lp);
|
||||
}
|
||||
void showSyncOptions(HWND parent, App &app)
|
||||
constexpr int SyncSettingsWidth = 660, SyncSettingsHeight = 550;
|
||||
constexpr int SyncSettingsMargin = 16, SyncSettingsGap = 16, SyncFieldsTop = 78, SyncActionsTop = 294;
|
||||
constexpr int SyncColumnWidth = (SyncSettingsWidth - 2 * SyncSettingsMargin - SyncSettingsGap) / 2;
|
||||
constexpr int SyncRightColumn = SyncSettingsMargin + SyncColumnWidth + SyncSettingsGap;
|
||||
HWND createSyncSettings(HWND pane, App &app)
|
||||
{
|
||||
auto c = loadSyncConfig(app.data);
|
||||
HWND w = makeWindow(app, L"KSwitcher.Sync", L"Settings synchronization - OpenBao", syncProc, 660, 672);
|
||||
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)new SyncView{parent, &app});
|
||||
checkbox(w, L"&Enable synchronization with your OpenBao (KV v2)", 601, 18, 18, 620);
|
||||
check(w, 601, c.enabled);
|
||||
label(w, L"Se&rver (HTTPS)", 18, 60, 160); edit(w, 602, 190, 56, 450); value(w, 602, c.server);
|
||||
label(w, L"User&name", 18, 100, 160); edit(w, 603, 190, 96, 450); value(w, 603, c.username);
|
||||
label(w, L"&Password", 18, 140, 160); edit(w, 604, 190, 136, 450, 25, ES_AUTOHSCROLL | ES_PASSWORD);
|
||||
label(w, L"Leave password blank to use the saved Windows credential.", 190, 166, 450);
|
||||
label(w, L"KV v2 &mount", 18, 210, 160); edit(w, 605, 190, 206, 450); value(w, 605, c.mount);
|
||||
label(w, L"Profile pa&th", 18, 250, 160); edit(w, 606, 190, 246, 450); value(w, 606, c.path);
|
||||
label(w, L"&Login mount", 18, 290, 160); edit(w, 607, 190, 286, 450); value(w, 607, c.authMount);
|
||||
label(w, L"Sync uses saved settings. Download remote refreshes the open Settings window.", 18, 330, 622);
|
||||
edit(w, 608, 18, 362, 622, 76, ES_MULTILINE | ES_READONLY | WS_VSCROLL | ES_AUTOVSCROLL);
|
||||
value(w, 608, app.syncCommand());
|
||||
checkbox(w, L"&Keep this PC's layouts and layout shortcuts (sync other settings)", 613, 18, 446, 622);
|
||||
check(w, 613, c.keepLocalLayouts);
|
||||
button(w, L"&Save / Sign in / Sync", IDOK, 18, 484, 200);
|
||||
button(w, L"&Download remote", 610, 230, 484, 195);
|
||||
button(w, L"&Upload local", 611, 437, 484, 203);
|
||||
button(w, L"Resolve &individual conflicts...", 612, 18, 530, 300);
|
||||
label(w, L"Background check: every 10 minutes", 330, 534, 310);
|
||||
button(w, L"Disconnect / &forget password", 609, 18, 582, 290);
|
||||
button(w, L"&Close", IDCANCEL, 540, 582, 100);
|
||||
updateSyncControls(w, app);
|
||||
EnableWindow(parent, FALSE);
|
||||
SetTimer(w, 1, 1000, nullptr);
|
||||
showRequestedWindow(w); SetForegroundWindow(w);
|
||||
WNDCLASSW panel{};
|
||||
panel.hInstance = app.instance;
|
||||
panel.lpfnWndProc = syncProc;
|
||||
panel.lpszClassName = L"KSwitcher.Sync";
|
||||
panel.hCursor = LoadCursorW(nullptr, IDC_ARROW);
|
||||
panel.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
|
||||
RegisterClassW(&panel);
|
||||
HWND w = CreateWindowExW(WS_EX_CONTROLPARENT, panel.lpszClassName, L"", WS_CHILD | WS_CLIPCHILDREN,
|
||||
0, 0, scale(pane, SyncSettingsWidth), scale(pane, SyncSettingsHeight),
|
||||
pane, reinterpret_cast<HMENU>(SettingsSyncPanel), app.instance, nullptr);
|
||||
if (!w) throw std::runtime_error("Cannot create OpenBao settings.");
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(new SyncView{&app}));
|
||||
SetPropW(w, L"Font", GetPropW(pane, L"Font"));
|
||||
auto *layout = new WindowLayout{SyncSettingsWidth, SyncSettingsHeight, 0, 0, true, true};
|
||||
SetPropW(w, L"WindowLayout", layout);
|
||||
constexpr int left = SyncSettingsMargin, width = SyncSettingsWidth - 2 * left;
|
||||
settingsGroupLabel(w, L"Connection", left, 14, width);
|
||||
checkbox(w, L"&Enable synchronization with OpenBao", 601, left, 42, width);
|
||||
auto field = [&](int id, const wchar_t *name, int x, int y, DWORD style = ES_AUTOHSCROLL)
|
||||
{
|
||||
label(w, name, x, y, SyncColumnWidth);
|
||||
edit(w, id, x, y + 24, SyncColumnWidth, 25, style);
|
||||
};
|
||||
field(602, L"Se&rver (HTTPS)", left, SyncFieldsTop);
|
||||
field(603, L"User&name", left, SyncFieldsTop + 59);
|
||||
field(604, L"&Password", left, SyncFieldsTop + 118, ES_AUTOHSCROLL | ES_PASSWORD);
|
||||
label(w, L"Leave blank to use the saved Windows credential.", left, 250, SyncColumnWidth);
|
||||
field(605, L"KV v2 &mount", SyncRightColumn, SyncFieldsTop);
|
||||
field(606, L"Profile pa&th", SyncRightColumn, SyncFieldsTop + 59);
|
||||
field(607, L"&Login mount", SyncRightColumn, SyncFieldsTop + 118);
|
||||
checkbox(w, L"&Keep this PC's layouts and layout shortcuts", 613, left, SyncActionsTop, width);
|
||||
settingsGroupLabel(w, L"Synchronization", left, SyncActionsTop + 38, width);
|
||||
label(w, L"Sync uses saved settings. Download remote refreshes the open Settings window.", left, 360, width);
|
||||
button(w, L"Save and s&ync", SyncSave, left, 387, 196);
|
||||
button(w, L"&Download remote", 610, 222, 387, 200);
|
||||
button(w, L"&Upload local", 611, 432, 387, 212);
|
||||
edit(w, 608, left, 423, width, 66, ES_MULTILINE | ES_READONLY | WS_VSCROLL | ES_AUTOVSCROLL);
|
||||
button(w, L"Resolve &individual conflicts…", 612, left, 499, SyncColumnWidth);
|
||||
button(w, L"Disconnect / &forget password", 609, SyncRightColumn, 499, SyncColumnWidth);
|
||||
for (int id : {602, 603, 604, 605, 606, 607, 610, 611, 612, 613, SyncSave})
|
||||
EnableWindow(GetDlgItem(w, id), FALSE);
|
||||
captureSettingsGeometry(*layout, 0, w);
|
||||
layout->arranging = false;
|
||||
return w;
|
||||
}
|
||||
int fitSyncSettings(HWND panel, int width)
|
||||
{
|
||||
auto &layout = *windowLayoutState(panel);
|
||||
layout.width = 1;
|
||||
layout.height = fitSettingsColumns(layout, 0, layout.controls.size(), width,
|
||||
{SyncSettingsMargin, SyncSettingsWidth - SyncSettingsMargin, SyncRightColumn,
|
||||
SyncSettingsMargin + SyncColumnWidth, SyncActionsTop, 610, 0, SyncFieldsTop});
|
||||
return layout.height;
|
||||
}
|
||||
@@ -51,7 +51,8 @@ LRESULT CALLBACK syncConflictsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
|
||||
if (msg == WM_NCDESTROY)
|
||||
{
|
||||
EnableWindow(v->parent, TRUE); SetForegroundWindow(v->parent);
|
||||
const auto owner = GetAncestor(v->parent, GA_ROOT);
|
||||
EnableWindow(owner, TRUE); SetForegroundWindow(owner);
|
||||
disposeFont(w); delete v; SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||
}
|
||||
return DefWindowProcW(w, msg, wp, lp);
|
||||
@@ -60,8 +61,9 @@ void showSyncConflicts(HWND parent, App &app)
|
||||
{
|
||||
auto conflicts = decodeSyncConflicts(app.syncConflictData());
|
||||
if (conflicts.empty()) { value(parent, 608, L"No pending conflicts. Run Sync to check for changes."); return; }
|
||||
const auto owner = GetAncestor(parent, GA_ROOT);
|
||||
HWND w = makeWindow(app, L"KSwitcher.SyncConflicts", L"Resolve individual settings", syncConflictsProc, 800, 560);
|
||||
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
|
||||
SetWindowLongPtrW(w, GWLP_HWNDPARENT, reinterpret_cast<LONG_PTR>(owner));
|
||||
auto *v = new SyncConflictView{parent, &app, std::move(conflicts), {}};
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
|
||||
label(w, L"Choose a value for each conflicting setting. Other changes are already synchronized.", 18, 16, 760);
|
||||
@@ -76,5 +78,5 @@ void showSyncConflicts(HWND parent, App &app)
|
||||
button(w, L"&Apply choices", IDOK, 526, 488, 140);
|
||||
button(w, L"&Cancel", IDCANCEL, 678, 488, 100);
|
||||
SendDlgItemMessageW(w, 620, LB_SETCURSEL, 0, 0); showConflictValues(w, v);
|
||||
EnableWindow(parent, FALSE); showRequestedWindow(w); SetForegroundWindow(w);
|
||||
EnableWindow(owner, FALSE); showRequestedWindow(w); SetForegroundWindow(w);
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.98";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.7.2";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
+631
-116
@@ -2,6 +2,7 @@
|
||||
#include "ocr.h"
|
||||
#include "screenshot.h"
|
||||
#include "lan_pairing.h"
|
||||
#include "settings_ui.h"
|
||||
#include <iostream>
|
||||
#include <commctrl.h>
|
||||
|
||||
@@ -22,6 +23,172 @@ void require(bool ok, const char *message)
|
||||
if (!ok) throw std::runtime_error(message);
|
||||
++passed;
|
||||
}
|
||||
void settingsWindowStateChecks(const std::filesystem::path &root)
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, root);
|
||||
ks::showSettings(app);
|
||||
auto settings = app.settingsWindow;
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
require(GetMonitorInfoW(MonitorFromWindow(settings, MONITOR_DEFAULTTONEAREST), &monitor),
|
||||
"settings opens on a monitor");
|
||||
const int dpi = GetDpiForWindow(settings);
|
||||
const auto work = monitor.rcWork;
|
||||
const int width = std::min<int>(work.right - work.left, MulDiv(810, dpi, 96));
|
||||
const int height = std::min<int>(work.bottom - work.top, MulDiv(490, dpi, 96));
|
||||
SetWindowPos(settings, nullptr, std::min<int>(work.left + MulDiv(45, dpi, 96), work.right - width),
|
||||
std::min<int>(work.top + MulDiv(55, dpi, 96), work.bottom - height),
|
||||
width, height, SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
selectSettingsPage(settings, 14);
|
||||
const auto splitter = GetDlgItem(settings, 270);
|
||||
SendMessageW(splitter, WM_KEYDOWN, VK_RIGHT, 0);
|
||||
SendMessageW(splitter, WM_KEYDOWN, VK_RIGHT, 0);
|
||||
RECT frame{}, split{};
|
||||
GetWindowRect(settings, &frame);
|
||||
GetWindowRect(splitter, &split);
|
||||
SendMessageW(settings, WM_CLOSE, 0, 0);
|
||||
require(!app.settingsWindow && std::filesystem::exists(root / L"configurator-window.json") &&
|
||||
!std::filesystem::exists(root / L"settings.json"), "closing saves only display preferences");
|
||||
|
||||
ks::showSettings(app);
|
||||
settings = app.settingsWindow;
|
||||
RECT restored{}, restoredSplit{};
|
||||
GetWindowRect(settings, &restored);
|
||||
GetWindowRect(GetDlgItem(settings, 270), &restoredSplit);
|
||||
const auto navigation = settingsNavigation(settings);
|
||||
require(EqualRect(&restored, &frame) && EqualRect(&restoredSplit, &split),
|
||||
"reopen restores position, size and sidebar width");
|
||||
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 14) &&
|
||||
IsWindowVisible(GetDlgItem(settingsViewport(settings), 412)), "reopen restores the nested selection");
|
||||
ShowWindow(settings, SW_MAXIMIZE);
|
||||
SendMessageW(settings, WM_CLOSE, 0, 0);
|
||||
ks::showSettings(app);
|
||||
settings = app.settingsWindow;
|
||||
require(IsZoomed(settings), "reopen restores maximization");
|
||||
ShowWindow(settings, SW_RESTORE);
|
||||
GetWindowRect(settings, &restored);
|
||||
require(EqualRect(&restored, &frame), "normal frame survives maximization");
|
||||
ShowWindow(settings, SW_MINIMIZE);
|
||||
SendMessageW(settings, WM_CLOSE, 0, 0);
|
||||
ks::showSettings(app);
|
||||
settings = app.settingsWindow;
|
||||
GetWindowRect(settings, &restored);
|
||||
require(!IsIconic(settings) && EqualRect(&restored, &frame), "closing minimized retains the normal frame");
|
||||
SendMessageW(settings, WM_CLOSE, 0, 0);
|
||||
|
||||
const auto file = root / L"configurator-window.json";
|
||||
const auto offscreen = R"({"frame":[-20000,-20000,-18000,-18800],"page":"retired-page"})";
|
||||
ks::atomicWrite(file, ks::Bytes(offscreen, offscreen + std::char_traits<char>::length(offscreen)));
|
||||
ks::showSettings(app);
|
||||
settings = app.settingsWindow;
|
||||
GetWindowRect(settings, &restored);
|
||||
GetMonitorInfoW(MonitorFromWindow(settings, MONITOR_DEFAULTTONEAREST), &monitor);
|
||||
require(restored.left >= monitor.rcWork.left && restored.top >= monitor.rcWork.top &&
|
||||
restored.right <= monitor.rcWork.right && restored.bottom <= monitor.rcWork.bottom,
|
||||
"placement from a disconnected monitor fits the current work area");
|
||||
require(TreeView_GetSelection(settingsNavigation(settings)) == settingsSection(settingsNavigation(settings), 0),
|
||||
"unknown page falls back to General");
|
||||
SendMessageW(settings, WM_CLOSE, 0, 0);
|
||||
}
|
||||
std::wstring pickTestApplication(HWND picker, bool cancel = false)
|
||||
{
|
||||
RECT dialogBounds{};
|
||||
GetWindowRect(GetParent(picker), &dialogBounds);
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
require(GetMonitorInfoW(MonitorFromWindow(picker, MONITOR_DEFAULTTONEAREST), &monitor),
|
||||
"monitor work area available");
|
||||
const auto targetX = std::clamp(dialogBounds.left + 32, monitor.rcWork.left, monitor.rcWork.right - 120);
|
||||
const auto targetY = std::clamp(dialogBounds.top + 100, monitor.rcWork.top, monitor.rcWork.bottom - 48);
|
||||
HWND target = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, L"EDIT", L"Picker fixture",
|
||||
WS_POPUP | WS_VISIBLE, targetX, targetY, 120, 48,
|
||||
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
|
||||
require(picker && target, "window picker and target available");
|
||||
POINT drop{targetX + 1, targetY + 1};
|
||||
require(GetAncestor(WindowFromPoint(drop), GA_ROOT) == target, "fixture window is under the drop point");
|
||||
ScreenToClient(picker, &drop);
|
||||
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
|
||||
require(GetCapture() == picker, "window picker captures drag");
|
||||
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
|
||||
HWND outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
|
||||
RECT outlineBounds{}, targetBounds{};
|
||||
require(IsWindowVisible(outline) && GetWindowRect(outline, &outlineBounds) &&
|
||||
GetWindowRect(target, &targetBounds) && EqualRect(&outlineBounds, &targetBounds), "drag highlights the target window");
|
||||
if (cancel) SendMessageW(picker, WM_KEYDOWN, VK_ESCAPE, 0);
|
||||
else SendMessageW(picker, WM_LBUTTONUP, 0, MAKELPARAM(drop.x, drop.y));
|
||||
require(!IsWindow(outline) && GetCapture() != picker, "finishing the drag clears the outline and releases capture");
|
||||
auto pickedApp = ks::applicationName(ks::processName(target));
|
||||
DestroyWindow(target);
|
||||
return pickedApp;
|
||||
}
|
||||
void lanWindowLayoutChecks(const std::filesystem::path &root)
|
||||
{
|
||||
const std::string peer(32,'b');
|
||||
const nlohmann::json fixture={{"version",1},{"id",std::string(32,'a')},{"enabled",false},
|
||||
{"trusted",{{peer,{{"name","Paired desktop"},{"key",std::string(64,'f')}}}}},
|
||||
{"positions",{{peer,nlohmann::json::array({1,0})}}}};
|
||||
const auto data=fixture.dump();
|
||||
std::filesystem::create_directories(root);
|
||||
ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(data.begin(),data.end())));
|
||||
ks::App app(GetModuleHandleW(nullptr),true,root);
|
||||
ks::showSettings(app);
|
||||
HWND lan=showComputerSettings(app.settingsWindow);
|
||||
require(lan && IsWindowVisible(lan),"Computers panel is visible");
|
||||
require(!GetDlgItem(lan, 726) && !GetDlgItem(lan, 730), "Computers panel omits direct file transfer actions");
|
||||
require(IsWindowVisible(GetDlgItem(lan, 727)) && IsWindowVisible(GetDlgItem(lan, 728)),
|
||||
"Computers panel retains current and previous diagnostic log actions");
|
||||
const auto dpi=GetDpiForWindow(lan);
|
||||
RECT client{};GetClientRect(lan,&client);
|
||||
std::vector<std::pair<int,RECT>> placed;
|
||||
for(HWND child=GetWindow(lan,GW_CHILD);child;child=GetWindow(child,GW_HWNDNEXT))
|
||||
{
|
||||
if (!IsWindowVisible(child)) continue;
|
||||
RECT bounds{};GetWindowRect(child,&bounds);
|
||||
MapWindowPoints(nullptr,lan,reinterpret_cast<POINT *>(&bounds),2);
|
||||
require(bounds.left>=0&&bounds.top>=0&&bounds.right<=client.right&&bounds.bottom<=client.bottom,
|
||||
"Computers control is fully visible");
|
||||
const int id=GetDlgCtrlID(child);
|
||||
for(const auto &[otherId,other]:placed)
|
||||
{
|
||||
RECT overlap{};
|
||||
if(IntersectRect(&overlap,&bounds,&other))
|
||||
throw std::runtime_error("Computers controls overlap: "+std::to_string(id)+" and "+std::to_string(otherId)+
|
||||
" at "+std::to_string(overlap.left)+","+std::to_string(overlap.top));
|
||||
}
|
||||
placed.push_back({id,bounds});
|
||||
}
|
||||
auto boundsFor = [&](int id)
|
||||
{
|
||||
RECT rect{};
|
||||
require(GetWindowRect(GetDlgItem(lan, id), &rect), "pairing control has bounds");
|
||||
return rect;
|
||||
};
|
||||
const auto code = boundsFor(703), generate = boundsFor(704);
|
||||
const auto pair = boundsFor(705), cancel = boundsFor(706), forget = boundsFor(707);
|
||||
const auto help = boundsFor(722), permission = boundsFor(729);
|
||||
const auto currentLog = boundsFor(727), previousLog = boundsFor(728);
|
||||
require(help.bottom < permission.top && permission.bottom < currentLog.top &&
|
||||
currentLog.top == previousLog.top && currentLog.bottom == previousLog.bottom &&
|
||||
std::abs((currentLog.right - currentLog.left) - (previousLog.right - previousLog.left)) <= 1 &&
|
||||
currentLog.left == permission.left && std::abs(previousLog.right - permission.right) <= 1,
|
||||
"diagnostic logs have a separate full-width group with equal actions");
|
||||
const int gap = MulDiv(10, dpi, 96);
|
||||
require(code.top == generate.top && code.bottom == generate.bottom &&
|
||||
std::abs(generate.left - code.right - gap) <= 1, "code input and Generate code share the same row");
|
||||
require(pair.top == cancel.top && cancel.top == forget.top &&
|
||||
pair.bottom == cancel.bottom && cancel.bottom == forget.bottom &&
|
||||
pair.right - pair.left == cancel.right - cancel.left &&
|
||||
cancel.right - cancel.left == forget.right - forget.left &&
|
||||
pair.left == code.left && std::abs(forget.right - generate.right) <= 1 &&
|
||||
std::abs(cancel.left - pair.right - gap) <= 1 && std::abs(forget.left - cancel.right - gap) <= 1,
|
||||
"pairing buttons align with the code row and have equal widths and gaps");
|
||||
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
auto dc=GetDC(lan);
|
||||
auto screenshot=ks::screenshotClip(dc,client.right,client.bottom,{});
|
||||
ReleaseDC(lan,dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-compact-layout.png",
|
||||
ks::encodePng(ks::decodeImage(screenshot)));
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
std::cout<<"Computers layout verified at "<<dpi<<" DPI.\n";
|
||||
}
|
||||
void contextChecks()
|
||||
{
|
||||
ks::Settings scoped;
|
||||
@@ -113,14 +280,220 @@ void contextChecks()
|
||||
require(hook.update(VK_LSHIFT, true, MOD_ALT | MOD_CONTROL, true) == 0, "do not consume Ctrl+Alt+Shift");
|
||||
require(hook.update('A', true, MOD_ALT, true) == 0, "ordinary keys pass");
|
||||
}
|
||||
void snippetEditorChecks(ks::App &app, const std::filesystem::path &root)
|
||||
{
|
||||
app.settings.snippets = {{L";scope", L"Example{pause:50}", L"scope-fixture"}};
|
||||
ks::showSettings(app);
|
||||
HWND parent = app.settingsWindow;
|
||||
auto saveEnabled = [&] { return IsWindowEnabled(GetDlgItem(parent, IDOK)); };
|
||||
auto status = [&] {
|
||||
wchar_t text[256]{};
|
||||
GetDlgItemTextW(parent, 261, text, 256);
|
||||
return std::wstring(text);
|
||||
};
|
||||
require(!saveEnabled(),"Settings starts clean before editing a snippet");
|
||||
ks::showSnippets(app);
|
||||
HWND snippets = settingsViewport(parent);
|
||||
require(!app.snippetsWindow && IsWindowVisible(GetDlgItem(snippets, 301)),
|
||||
"opening Snippets from Settings selects its inline editor");
|
||||
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
|
||||
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
|
||||
require(!GetDlgItem(snippets, 318), "inline editor has only the Settings Save button");
|
||||
require(!saveEnabled() && status()==L"No unsaved settings.", "selecting a snippet leaves the editor clean");
|
||||
const auto replacement = GetDlgItem(snippets, 303);
|
||||
auto replaceSnippetText = [&](const wchar_t *text) {
|
||||
SendMessageW(replacement, EM_SETSEL, 0, -1);
|
||||
SendMessageW(replacement, EM_REPLACESEL, TRUE, reinterpret_cast<LPARAM>(text));
|
||||
};
|
||||
auto selectInsertion = [](HWND picker, int action) {
|
||||
SendDlgItemMessageW(picker, 321, CB_SETCURSEL, action, 0);
|
||||
SendMessageW(picker, WM_COMMAND, MAKEWPARAM(321, CBN_SELCHANGE), 0);
|
||||
};
|
||||
auto openInsertion = [&](int action) {
|
||||
SendMessageW(snippets, WM_COMMAND, 320, 0);
|
||||
const auto picker = findTestWindow(L"KSwitcher.SnippetInsertion", nullptr);
|
||||
require(picker && GetWindow(picker, GW_OWNER) == parent && !IsWindowEnabled(parent),
|
||||
"insertion picker opens over the snippet editor");
|
||||
selectInsertion(picker, action);
|
||||
return picker;
|
||||
};
|
||||
auto captureInsertion = [](HWND picker, const wchar_t *file) {
|
||||
RedrawWindow(picker, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
RECT client{};
|
||||
GetClientRect(picker, &client);
|
||||
auto dc = GetDC(picker);
|
||||
auto image = ks::screenshotClip(dc, client.right, client.bottom, {});
|
||||
ReleaseDC(picker, dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / file,
|
||||
ks::encodePng(ks::decodeImage(image)));
|
||||
};
|
||||
SendMessageW(replacement, EM_SETSEL, 7, -1);
|
||||
auto insertion = openInsertion(0);
|
||||
const auto parameter = GetDlgItem(insertion, 323);
|
||||
RECT actionRect{}, markerParameter{}, pauseParameter{}, dialog{};
|
||||
GetWindowRect(GetDlgItem(insertion, 321), &actionRect);
|
||||
GetWindowRect(parameter, &markerParameter);
|
||||
GetClientRect(insertion, &dialog);
|
||||
require(IsWindowVisible(parameter) && !IsWindowEnabled(parameter), "cursor marker keeps a visible disabled parameter");
|
||||
require(actionRect.top == markerParameter.top && actionRect.right < markerParameter.left &&
|
||||
dialog.bottom < MulDiv(170, GetDpiForWindow(insertion), 96), "compact picker places Action and Parameter on one row");
|
||||
captureInsertion(insertion, L"snippet-insertion-marker.png");
|
||||
selectInsertion(insertion, 2);
|
||||
GetWindowRect(parameter, &pauseParameter);
|
||||
require(IsWindowVisible(parameter) && IsWindowEnabled(parameter) && EqualRect(&markerParameter, &pauseParameter),
|
||||
"pause enables its parameter without moving the field");
|
||||
require(pauseParameter.right - pauseParameter.left <= MulDiv(70, GetDpiForWindow(insertion), 96) &&
|
||||
SendMessageW(parameter, EM_GETLIMITTEXT, 0, 0) == 5, "pause uses a compact field limited to five digits");
|
||||
SetDlgItemTextW(insertion, 323, L"10001");
|
||||
require(!IsWindowEnabled(GetDlgItem(insertion, IDOK)), "invalid pause cannot be inserted");
|
||||
SetDlgItemTextW(insertion, 323, L"10000");
|
||||
require(IsWindowEnabled(GetDlgItem(insertion, IDOK)), "five-digit maximum pause fits the numeric field");
|
||||
SetDlgItemTextW(insertion, 323, L"100");
|
||||
require(IsWindowEnabled(GetDlgItem(insertion, IDOK)), "valid pause enables Insert");
|
||||
captureInsertion(insertion, L"snippet-insertion.png");
|
||||
SendMessageW(insertion, WM_COMMAND, IDOK, 0);
|
||||
require(saveEnabled() && status().find(L"Unsaved snippets") == 0,
|
||||
"editing just the pause enables the Settings Save button");
|
||||
auto replacementText = [&] {
|
||||
wchar_t text[256]{};
|
||||
GetWindowTextW(replacement, text, 256);
|
||||
return std::wstring(text);
|
||||
};
|
||||
require(replacementText() == L"Example{pause:100}", "insertion replaces the selected pause");
|
||||
insertion = openInsertion(4);
|
||||
RECT chordParameter{};
|
||||
GetWindowRect(GetDlgItem(insertion, 323), &chordParameter);
|
||||
require(chordParameter.right - chordParameter.left > pauseParameter.right - pauseParameter.left &&
|
||||
SendDlgItemMessageW(insertion, 323, EM_GETLIMITTEXT, 0, 0) > 5, "key combinations retain a wider input");
|
||||
require((GetWindowLongPtrW(GetDlgItem(insertion, 323), GWL_STYLE) & ES_READONLY) &&
|
||||
!IsWindowEnabled(GetDlgItem(insertion, IDOK)), "key recorder starts empty and rejects typed text");
|
||||
auto record = [](HWND picker, std::initializer_list<WORD> keys) {
|
||||
SendDlgItemMessageW(picker, 323, WM_KEYUP, VK_SPACE, 0);
|
||||
for (auto key : keys) SendMessageW(picker, WM_APP + 160, key, TRUE);
|
||||
for (auto key : keys) SendMessageW(picker, WM_APP + 160, key, FALSE);
|
||||
};
|
||||
record(insertion, {VK_LCONTROL});
|
||||
require(!IsWindowEnabled(GetDlgItem(insertion, IDOK)), "one pressed key cannot supply a combination");
|
||||
auto keyText = [&] {
|
||||
wchar_t text[32]{};
|
||||
GetDlgItemTextW(insertion, 323, text, 32);
|
||||
return std::wstring(text);
|
||||
};
|
||||
SendDlgItemMessageW(insertion, 323, WM_KEYUP, VK_SPACE, 0);
|
||||
SendMessageW(insertion, WM_APP + 160, VK_LCONTROL, TRUE);
|
||||
require(keyText() == L"Ctrl", "first key appears before release");
|
||||
SendMessageW(insertion, WM_APP + 160, VK_RETURN, TRUE);
|
||||
require(keyText() == L"Ctrl+Enter" && !IsWindowEnabled(GetDlgItem(insertion, IDOK)),
|
||||
"the entire chord appears while keys are still held");
|
||||
captureInsertion(insertion, L"snippet-key-held.png");
|
||||
SendMessageW(insertion, WM_APP + 160, VK_LCONTROL, FALSE);
|
||||
require(keyText() == L"Ctrl+Enter" && !IsWindowEnabled(GetDlgItem(insertion, IDOK)),
|
||||
"releasing one key keeps the chord visible while recording finishes");
|
||||
SendMessageW(insertion, WM_APP + 160, VK_RETURN, FALSE);
|
||||
require(IsWindowEnabled(GetDlgItem(insertion, IDOK)), "recorded Ctrl+Enter enables insertion");
|
||||
captureInsertion(insertion, L"snippet-key-recorded.png");
|
||||
SendMessageW(insertion, WM_COMMAND, IDOK, 0);
|
||||
require(replacementText() == L"Example{pause:100}{{ctrl}}+{{return}}", "chord converts Enter to the supported key spelling");
|
||||
insertion = openInsertion(1);
|
||||
require(IsWindowVisible(GetDlgItem(insertion, 323)) && !IsWindowEnabled(GetDlgItem(insertion, 323)),
|
||||
"Enter marker keeps its parameter visible and disabled");
|
||||
SendMessageW(insertion, WM_COMMAND, IDOK, 0);
|
||||
insertion = openInsertion(0);
|
||||
SendMessageW(insertion, WM_COMMAND, IDOK, 0);
|
||||
require(replacementText().ends_with(L"{enter}{cursor}"), "Enter and cursor markers use the same picker");
|
||||
insertion = openInsertion(3);
|
||||
record(insertion, {VK_RSHIFT});
|
||||
wchar_t keyName[32]{};
|
||||
GetDlgItemTextW(insertion, 323, keyName, 32);
|
||||
require(std::wstring(keyName) == L"ShiftR" && IsWindowEnabled(GetDlgItem(insertion, IDOK)),
|
||||
"tap recording recognizes a right-hand modifier by itself");
|
||||
SendMessageW(insertion, WM_COMMAND, IDCANCEL, 0);
|
||||
require(replacementText().ends_with(L"{enter}{cursor}"), "cancelling insertion preserves replacement text");
|
||||
replaceSnippetText(L"Example{pause:50}");
|
||||
require(!saveEnabled() && status()==L"No unsaved settings.", "reverting the pause clears the pending change");
|
||||
replaceSnippetText(L"Example{pause:100}");
|
||||
require(IsDlgButtonChecked(snippets,314)==BST_UNCHECKED, "old snippet shows everywhere");
|
||||
HWND scopePicker = GetDlgItem(snippets, 753);
|
||||
require(IsWindowVisible(scopePicker) && !IsWindowEnabled(scopePicker), "global snippet disables the window picker");
|
||||
CheckDlgButton(snippets,314,BST_CHECKED);
|
||||
SendMessageW(snippets,WM_COMMAND,314,0);
|
||||
require(IsWindowEnabled(scopePicker), "restricting the snippet enables the window picker");
|
||||
SetDlgItemTextW(snippets,315,L"Notepad.exe");
|
||||
auto secondApp = SendDlgItemMessageW(snippets,316,CB_ADDSTRING,0,(LPARAM)L"MS-Teams.EXE");
|
||||
SendDlgItemMessageW(snippets,316,CB_SETCURSEL,secondApp,0);
|
||||
SendMessageW(snippets,WM_COMMAND,317,0);
|
||||
SendMessageW(snippets,WM_COMMAND,317,0);
|
||||
wchar_t appList[128]{};
|
||||
GetDlgItemTextW(snippets,315,appList,128);
|
||||
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "Add app appends a second application without duplicates");
|
||||
pickTestApplication(scopePicker, true);
|
||||
GetDlgItemTextW(snippets,315,appList,128);
|
||||
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "cancelling the picker preserves the snippet scope");
|
||||
auto pickedProcess = pickTestApplication(scopePicker);
|
||||
pickTestApplication(scopePicker);
|
||||
GetDlgItemTextW(snippets,315,appList,128);
|
||||
require(std::wstring(appList) == L"Notepad.exe, MS-Teams.EXE, " + pickedProcess + L".exe",
|
||||
"dropping on a window appends its process once to the existing snippet scope");
|
||||
const std::vector<std::wstring> savedScope{L"notepad", L"ms-teams", pickedProcess};
|
||||
RedrawWindow(snippets,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
RECT snippetRect{};GetClientRect(snippets,&snippetRect);
|
||||
HDC snippetDc=GetDC(snippets);
|
||||
auto snippetImage=ks::screenshotClip(snippetDc,snippetRect.right,snippetRect.bottom,{});
|
||||
ReleaseDC(snippets,snippetDc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"snippet-scopes.png",ks::encodePng(ks::decodeImage(snippetImage)));
|
||||
const auto logSetting = !app.settings.writeLog;
|
||||
CheckDlgButton(settingsViewport(parent), 208, logSetting ? BST_CHECKED : BST_UNCHECKED);
|
||||
SendMessageW(parent, WM_COMMAND, MAKEWPARAM(208, BN_CLICKED), 0);
|
||||
SendMessageW(parent, WM_COMMAND, IDOK, 0);
|
||||
require(!IsWindow(parent), "Settings Save closes the inline snippet editor");
|
||||
const auto savedSettings = ks::loadSettings(root / L"settings.json", app.layouts);
|
||||
require(savedSettings.snippets[0].apps == savedScope && savedSettings.snippets[0].text == L"Example{pause:100}" &&
|
||||
savedSettings.writeLog == logSetting, "one Save persists the snippet and general settings together");
|
||||
ks::showSnippets(app);snippets=app.snippetsWindow;
|
||||
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
|
||||
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
|
||||
require(IsDlgButtonChecked(snippets,314)==BST_CHECKED, "scope restored when reopening editor");
|
||||
SetDlgItemTextW(snippets,315,L"chrome.exe");
|
||||
pickTestApplication(GetDlgItem(snippets, 753));
|
||||
GetDlgItemTextW(snippets,315,appList,128);
|
||||
require(std::wstring(appList) == L"chrome.exe, " + pickedProcess + L".exe",
|
||||
"standalone snippet editor adds the dropped application");
|
||||
SendMessageW(snippets,WM_COMMAND,IDCANCEL,0);
|
||||
require(app.settings.snippets[0].apps==savedScope, "cancel preserves existing scope");
|
||||
}
|
||||
int main()
|
||||
}
|
||||
int main(int argc,char **argv)
|
||||
{
|
||||
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-chat-tests-" + std::to_wstring(GetCurrentProcessId()));
|
||||
try
|
||||
{
|
||||
if(argc==2 && std::string_view(argv[1])=="--lan-layout")
|
||||
{
|
||||
lanWindowLayoutChecks(root);
|
||||
std::filesystem::remove_all(root);
|
||||
CoUninitialize();
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--snippets")
|
||||
{
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, root);
|
||||
if (app.layouts.empty()) app.layouts.push_back({nullptr, L"win:04090409", L"English"});
|
||||
app.settings.cycle = {app.layouts.front().id};
|
||||
app.settings.toggle = app.settings.casing = app.settings.translit = app.settings.undo = L"";
|
||||
app.settings.clipboard = app.settings.screenshot = L"";
|
||||
app.settings.direct.assign(app.layouts.size(), L"");
|
||||
app.settings.history = app.settings.autoCorrect = false;
|
||||
snippetEditorChecks(app, root);
|
||||
}
|
||||
std::filesystem::remove_all(root);
|
||||
CoUninitialize();
|
||||
std::cout << "PASS snippet editor (" << passed << " checks)\n";
|
||||
return 0;
|
||||
}
|
||||
contextChecks();
|
||||
settingsWindowStateChecks(root / L"window-state");
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, root);
|
||||
require(!app.layouts.empty(), "installed layouts available");
|
||||
@@ -137,17 +510,17 @@ int main()
|
||||
require(!saveEnabled() && status()==L"No unsaved settings.","new Settings shows clean state with Save disabled");
|
||||
SendMessageW(parent,WM_COMMAND,IDOK,0);
|
||||
require(IsWindow(parent),"Save command with no changes does not apply or close Settings");
|
||||
bool originalLog=IsDlgButtonChecked(parent,208)==BST_CHECKED;
|
||||
CheckDlgButton(parent,208,originalLog?BST_UNCHECKED:BST_CHECKED);
|
||||
bool originalLog=IsDlgButtonChecked(settingsViewport(parent),208)==BST_CHECKED;
|
||||
CheckDlgButton(settingsViewport(parent),208,originalLog?BST_UNCHECKED:BST_CHECKED);
|
||||
SendMessageW(parent,WM_COMMAND,MAKEWPARAM(208,BN_CLICKED),0);
|
||||
require(saveEnabled() && status().find(L"Unsaved settings") == 0,"checkbox edit immediately marks Settings dirty");
|
||||
CheckDlgButton(parent,208,originalLog?BST_CHECKED:BST_UNCHECKED);
|
||||
CheckDlgButton(settingsViewport(parent),208,originalLog?BST_CHECKED:BST_UNCHECKED);
|
||||
SendMessageW(parent,WM_COMMAND,MAKEWPARAM(208,BN_CLICKED),0);
|
||||
require(!saveEnabled(),"reverting checkbox disables Save again");
|
||||
wchar_t originalLimit[32]{}; GetDlgItemTextW(parent,240,originalLimit,32);
|
||||
SetDlgItemTextW(parent,240,L"invalid");
|
||||
wchar_t originalLimit[32]{}; GetDlgItemTextW(settingsViewport(parent),240,originalLimit,32);
|
||||
SetDlgItemTextW(settingsViewport(parent),240,L"invalid");
|
||||
require(saveEnabled(),"invalid text remains an unsaved edit");
|
||||
SetDlgItemTextW(parent,240,originalLimit);
|
||||
SetDlgItemTextW(settingsViewport(parent),240,originalLimit);
|
||||
require(!saveEnabled(),"restoring valid original text clears dirty state");
|
||||
SendMessageW(parent,WM_COMMAND,257,0);
|
||||
HWND ocr=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
|
||||
@@ -166,33 +539,41 @@ int main()
|
||||
SetDlgItemTextW(ocr,503,languages);
|
||||
SendMessageW(ocr,WM_COMMAND,IDOK,0);
|
||||
require(!saveEnabled(),"reverting OCR draft in child clears parent dirty state");
|
||||
SendMessageW(parent,WM_COMMAND,255,0);
|
||||
HWND automatic=findTestWindow(L"KSwitcher.AutoOptions",nullptr);
|
||||
require(automatic!=nullptr,"automatic correction preferences open");
|
||||
bool replace=IsDlgButtonChecked(automatic,414)==BST_CHECKED;
|
||||
CheckDlgButton(automatic,414,replace?BST_UNCHECKED:BST_CHECKED);
|
||||
SendMessageW(automatic,WM_COMMAND,IDOK,0);
|
||||
require(!IsWindow(automatic) && saveEnabled(),"accepted auto-correction edits enable Save");
|
||||
SendMessageW(parent,WM_COMMAND,255,0);
|
||||
automatic=findTestWindow(L"KSwitcher.AutoOptions",nullptr);
|
||||
CheckDlgButton(automatic,414,replace?BST_CHECKED:BST_UNCHECKED);
|
||||
SendMessageW(automatic,WM_COMMAND,IDOK,0);
|
||||
require(!saveEnabled(),"reverting auto-correction draft disables Save");
|
||||
HWND tabs = GetDlgItem(parent, 260);
|
||||
require(tabs && TabCtrl_GetItemCount(tabs) == 10, "ten settings categories");
|
||||
const auto correction = settingsViewport(parent);
|
||||
require(!GetDlgItem(correction, 255), "General no longer has a correction options button");
|
||||
selectSettingsPage(parent, 16);
|
||||
require(IsWindowVisible(GetDlgItem(correction, 414)) && IsWindowEnabled(parent) &&
|
||||
!findTestWindow(L"KSwitcher.AutoOptions", nullptr), "correction options open inline");
|
||||
const bool replace = IsDlgButtonChecked(correction, 414) == BST_CHECKED;
|
||||
SendMessageW(GetDlgItem(correction, 414), BM_CLICK, 0, 0);
|
||||
require(saveEnabled(), "inline correction edits enable Save");
|
||||
selectSettingsPage(parent, 0);
|
||||
selectSettingsPage(parent, 16);
|
||||
require((IsDlgButtonChecked(correction, 414) == BST_CHECKED) != replace,
|
||||
"correction edits survive switching pages");
|
||||
SendMessageW(GetDlgItem(correction, 414), BM_CLICK, 0, 0);
|
||||
require(!saveEnabled(), "reverting an inline correction edit disables Save");
|
||||
HWND navigation = settingsNavigation(parent);
|
||||
constexpr int sections = 18;
|
||||
require(navigation && TreeView_GetCount(navigation) == sections &&
|
||||
TreeView_GetParent(navigation, settingsSection(navigation, 10)) == settingsSection(navigation, 7) &&
|
||||
TreeView_GetParent(navigation, settingsSection(navigation, 11)) == settingsSection(navigation, 0),
|
||||
"correction and computer settings are nested under their sections");
|
||||
for (int section = 12; section <= 16; ++section)
|
||||
require(TreeView_GetParent(navigation, settingsSection(navigation, section)) == settingsSection(navigation, 11),
|
||||
"each correction subsection belongs to the correction branch");
|
||||
require(!GetDlgItem(parent, 262), "no separate Manage computers button");
|
||||
wchar_t mcpConfig[4096]{};
|
||||
GetDlgItemTextW(parent, 281, mcpConfig, std::size(mcpConfig));
|
||||
GetDlgItemTextW(settingsViewport(parent), 281, mcpConfig, std::size(mcpConfig));
|
||||
const std::wstring config(mcpConfig);
|
||||
require(config.starts_with(L"[mcp_servers.kswitcher]\r\ncommand = \"") &&
|
||||
config.find(L"KSwitcher.Config.exe\"\r\nargs = [\"--mcp\"]") != std::wstring::npos,
|
||||
"MCP tab shows a Codex stdio configuration");
|
||||
for (int page = 0; page < TabCtrl_GetItemCount(tabs); ++page)
|
||||
"MCP section shows a Codex stdio configuration");
|
||||
for (int page = 0; page < sections; ++page)
|
||||
{
|
||||
TabCtrl_SetCurSel(tabs, page);
|
||||
NMHDR notification{tabs, 260, TCN_SELCHANGE};
|
||||
SendMessageW(parent, WM_NOTIFY, 260, (LPARAM)¬ification);
|
||||
selectSettingsPage(parent, page);
|
||||
std::vector<RECT> boxes;
|
||||
for (HWND child = GetWindow(parent, GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
|
||||
for (HWND child = GetWindow(settingsViewport(parent), GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
|
||||
{
|
||||
if (!(GetWindowLongPtrW(child, GWL_STYLE) & WS_VISIBLE)) continue;
|
||||
RECT rect{}; GetWindowRect(child, &rect);
|
||||
@@ -208,13 +589,208 @@ int main()
|
||||
HDC dc = GetDC(parent);
|
||||
auto clip = ks::screenshotClip(dc, rect.right, rect.bottom, {});
|
||||
ReleaseDC(parent, dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / (L"settings-tab-" + std::to_wstring(page) + L".png"),
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / (L"settings-section-" + std::to_wstring(page) + L".png"),
|
||||
ks::encodePng(ks::decodeImage(clip)));
|
||||
}
|
||||
TabCtrl_SetCurSel(tabs, 1);
|
||||
NMHDR notification{tabs, 260, TCN_SELCHANGE};
|
||||
SendMessageW(parent, WM_NOTIFY, 260, (LPARAM)¬ification);
|
||||
require(!saveEnabled(),"changing tabs leaves Settings clean");
|
||||
selectSettingsPage(parent, 11);
|
||||
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 12) &&
|
||||
IsWindowVisible(GetDlgItem(correction, 401)), "selecting an empty group opens its first page");
|
||||
selectSettingsPage(parent, 0);
|
||||
SetFocus(navigation);
|
||||
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
|
||||
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 12) &&
|
||||
IsWindowVisible(GetDlgItem(correction, 401)), "arrow keys enter the first correction subsection");
|
||||
SendMessageW(navigation, WM_KEYDOWN, VK_UP, 0);
|
||||
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 0),
|
||||
"Up from the first child skips the empty parent");
|
||||
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
|
||||
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
|
||||
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 13),
|
||||
"Down reaches the subsequent child");
|
||||
SendMessageW(navigation, WM_KEYDOWN, VK_LEFT, 0);
|
||||
const auto correctionBranch = settingsSection(navigation, 11);
|
||||
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 0) &&
|
||||
!(TreeView_GetItemState(navigation, correctionBranch, TVIS_EXPANDED) & TVIS_EXPANDED),
|
||||
"Left exits and collapses the group");
|
||||
selectSettingsPage(parent, 16);
|
||||
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
|
||||
require(TreeView_GetSelection(navigation) == settingsSection(navigation, 1) &&
|
||||
IsWindowVisible(GetDlgItem(settingsViewport(parent), 220)) &&
|
||||
!IsWindowVisible(GetDlgItem(settingsViewport(parent), 201)), "arrow keys select the visible page");
|
||||
MSG tab{navigation, WM_KEYDOWN, VK_TAB};
|
||||
require(IsDialogMessageW(parent, &tab) && GetFocus() == GetDlgItem(settingsViewport(parent), 220),
|
||||
"Tab enters the active settings page");
|
||||
RECT frame{};
|
||||
GetWindowRect(parent, &frame);
|
||||
const UINT dpi = GetDpiForWindow(parent);
|
||||
const auto rootNode = TreeView_GetRoot(navigation);
|
||||
const auto dictionariesNode = settingsSection(navigation, 12);
|
||||
const auto checkLabelIndent = [&](UINT targetDpi)
|
||||
{
|
||||
RECT rootLabel{}, childLabel{}, dictionariesLabel{};
|
||||
require(TreeView_GetItemRect(navigation, rootNode, &rootLabel, TRUE) &&
|
||||
TreeView_GetItemRect(navigation, correctionBranch, &childLabel, TRUE) &&
|
||||
TreeView_GetItemRect(navigation, dictionariesNode, &dictionariesLabel, TRUE),
|
||||
"measure tree labels on all three levels");
|
||||
const int indent = MulDiv(16, targetDpi, 96);
|
||||
require(childLabel.left - rootLabel.left == indent &&
|
||||
dictionariesLabel.left - childLabel.left == indent,
|
||||
"tree labels use a compact indent at the current DPI");
|
||||
};
|
||||
checkLabelIndent(dpi);
|
||||
for (const UINT targetDpi : {96u, 144u, 192u, 240u, dpi})
|
||||
{
|
||||
SendMessageW(parent, WM_DPICHANGED, MAKEWPARAM(targetDpi, targetDpi), reinterpret_cast<LPARAM>(&frame));
|
||||
checkLabelIndent(targetDpi);
|
||||
}
|
||||
const auto splitter = GetDlgItem(parent, 270);
|
||||
const auto viewport = settingsViewport(parent);
|
||||
RECT paneBefore{}, paneAfter{}, footerBefore{}, footerAfter{};
|
||||
GetWindowRect(viewport, &paneBefore);
|
||||
GetWindowRect(GetDlgItem(parent, IDCANCEL), &footerBefore);
|
||||
const int grip = MulDiv(4, dpi, 96), movement = MulDiv(50, dpi, 96);
|
||||
SendMessageW(splitter, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(grip, 10));
|
||||
require(GetCapture() == splitter, "splitter captures a drag");
|
||||
SendMessageW(splitter, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(grip + movement, 10));
|
||||
SendMessageW(splitter, WM_LBUTTONUP, 0, MAKELPARAM(grip, 10));
|
||||
GetWindowRect(viewport, &paneAfter);
|
||||
GetWindowRect(GetDlgItem(parent, IDCANCEL), &footerAfter);
|
||||
require(GetCapture() != splitter && std::abs(paneAfter.left - paneBefore.left - movement) <= 1 &&
|
||||
paneAfter.right == paneBefore.right && EqualRect(&footerBefore, &footerAfter),
|
||||
"dragging resizes the two panes and keeps the footer fixed");
|
||||
const int draggedPosition = paneAfter.left;
|
||||
SendMessageW(splitter, WM_KEYDOWN, VK_LEFT, 0);
|
||||
GetWindowRect(viewport, &paneAfter);
|
||||
require(std::abs(paneAfter.left - draggedPosition + MulDiv(12, dpi, 96)) <= 1,
|
||||
"arrow keys resize the panes");
|
||||
const auto heading = GetDlgItem(parent, 266);
|
||||
const auto exportButton = GetDlgItem(parent, 251);
|
||||
const int inset = MulDiv(8, dpi, 96);
|
||||
const COLORREF stale = RGB(7, 97, 83);
|
||||
RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
// Simulate stale splitter and button pixels in the areas affected by a drag.
|
||||
for (HWND child : {heading, exportButton})
|
||||
{
|
||||
const auto dc = GetDC(child);
|
||||
const bool marked = SetPixelV(dc, inset, inset, stale) && GetPixel(dc, inset, inset) == stale;
|
||||
ReleaseDC(child, dc);
|
||||
require(marked, "fixture can plant a stale pixel");
|
||||
}
|
||||
SendMessageW(splitter, WM_LBUTTONDBLCLK, MK_LBUTTON, MAKELPARAM(grip, 10));
|
||||
GetWindowRect(viewport, &paneAfter);
|
||||
require(EqualRect(&paneBefore, &paneAfter), "double-click restores the default split");
|
||||
RedrawWindow(parent, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
for (HWND child : {heading, exportButton})
|
||||
{
|
||||
const auto dc = GetDC(child);
|
||||
const auto pixel = GetPixel(dc, inset, inset);
|
||||
ReleaseDC(child, dc);
|
||||
require(pixel != CLR_INVALID && pixel != stale, "moving the splitter repaints the heading and footer");
|
||||
}
|
||||
RECT repaintClient{};
|
||||
GetClientRect(parent, &repaintClient);
|
||||
const auto repaintDc = GetDC(parent);
|
||||
auto repaint = ks::screenshotClip(repaintDc, repaintClient.right, repaintClient.bottom, {});
|
||||
ReleaseDC(parent, repaintDc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"settings-splitter-repaint.png",
|
||||
ks::encodePng(ks::decodeImage(repaint)));
|
||||
TreeView_SetItemHeight(navigation, 30);
|
||||
SendMessageW(parent, WM_DPICHANGED, MAKEWPARAM(dpi, dpi), reinterpret_cast<LPARAM>(&frame));
|
||||
require(TreeView_GetItemHeight(navigation) == (MulDiv(30, dpi, 96) & ~1),
|
||||
"the navigation row height follows the window DPI");
|
||||
selectSettingsPage(parent, 5);
|
||||
SetWindowPos(parent, nullptr, 0, 0, frame.right - frame.left, MulDiv(430, dpi, 96),
|
||||
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
|
||||
const auto pane = settingsViewport(parent);
|
||||
const auto cancel = GetDlgItem(parent, IDCANCEL);
|
||||
RECT before{}, after{};
|
||||
GetWindowRect(cancel, &before);
|
||||
SendMessageW(pane, WM_VSCROLL, SB_BOTTOM, 0);
|
||||
SCROLLINFO scroll{sizeof(scroll), SIF_POS};
|
||||
GetScrollInfo(pane, SB_VERT, &scroll);
|
||||
GetWindowRect(cancel, &after);
|
||||
require(scroll.nPos > 0 && EqualRect(&before, &after), "the footer stays fixed while the page scrolls");
|
||||
selectSettingsPage(parent, 0);
|
||||
selectSettingsPage(parent, 5);
|
||||
SCROLLINFO restored{sizeof(restored), SIF_POS};
|
||||
GetScrollInfo(pane, SB_VERT, &restored);
|
||||
require(restored.nPos == scroll.nPos, "returning to a page preserves its scroll position");
|
||||
SetWindowPos(parent, nullptr, 0, 0, frame.right - frame.left, frame.bottom - frame.top,
|
||||
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
|
||||
const auto search = GetDlgItem(parent, 269);
|
||||
SetWindowTextW(search, L"mou");
|
||||
const auto profilesResult = TreeView_GetChild(navigation, TreeView_GetRoot(navigation));
|
||||
const auto eventsResult = TreeView_GetNextSibling(navigation, profilesResult);
|
||||
require(profilesResult && eventsResult, "Mouse search exposes two results on the same page");
|
||||
SetFocus(navigation);
|
||||
TreeView_SelectItem(navigation, profilesResult);
|
||||
require(TreeView_GetSelection(navigation) == profilesResult, "the search tree selects Profiles");
|
||||
const auto profilesLabel = FindWindowExW(pane, nullptr, L"Static", L"Profiles");
|
||||
const auto eventsLabel = FindWindowExW(pane, nullptr, L"Static", L"Mouse events");
|
||||
require(profilesLabel && eventsLabel, "both search targets are on the Mouse page");
|
||||
auto outline = [&](HWND label)
|
||||
{
|
||||
RECT bounds{};
|
||||
GetWindowRect(label, &bounds);
|
||||
MapWindowPoints(nullptr, pane, reinterpret_cast<POINT *>(&bounds), 2);
|
||||
const auto dc = GetDC(pane);
|
||||
const auto color = GetPixel(dc, bounds.left - MulDiv(3, dpi, 96), (bounds.top + bounds.bottom) / 2);
|
||||
ReleaseDC(pane, dc);
|
||||
return color;
|
||||
};
|
||||
RedrawWindow(pane, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
HIGHCONTRASTW contrast{sizeof(contrast)};
|
||||
SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0);
|
||||
if (!(contrast.dwFlags & HCF_HIGHCONTRASTON))
|
||||
require(outline(profilesLabel) == RGB(7, 97, 83) && outline(eventsLabel) == RGB(157, 111, 21),
|
||||
"the selected result has its own outline within the current page");
|
||||
SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0);
|
||||
require(TreeView_GetSelection(navigation) == eventsResult, "Down selects the next result");
|
||||
RedrawWindow(pane, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
if (!(contrast.dwFlags & HCF_HIGHCONTRASTON))
|
||||
require(outline(profilesLabel) == RGB(157, 111, 21) && outline(eventsLabel) == RGB(7, 97, 83),
|
||||
"the active outline moves when selecting another result on the same page");
|
||||
SetWindowTextW(search, L"correction options personal dictionary Ukrainian");
|
||||
SetFocus(search);
|
||||
SendMessageW(search, WM_KEYDOWN, VK_RETURN, 0);
|
||||
SendMessageW(navigation, WM_KEYDOWN, VK_RETURN, 0);
|
||||
require(GetFocus() == GetDlgItem(correction, 412), "search follows the correction hierarchy to a specific dictionary");
|
||||
SetWindowTextW(search, L"clipboard max count");
|
||||
SetFocus(search);
|
||||
SendMessageW(search, WM_KEYDOWN, VK_RETURN, 0);
|
||||
SendMessageW(navigation, WM_KEYDOWN, VK_RETURN, 0);
|
||||
require(GetFocus() == GetDlgItem(settingsViewport(parent), 240),
|
||||
"search finds a field by its aliases and Enter focuses the field");
|
||||
SetWindowTextW(search, L"gEnErAtE CoDe");
|
||||
auto match = TreeView_GetChild(navigation, TreeView_GetRoot(navigation));
|
||||
require(TreeView_GetCount(navigation) >= 2 && match, "search finds a nested action case-insensitively");
|
||||
TreeView_SelectItem(navigation, match);
|
||||
const auto embedded = GetDlgItem(settingsViewport(parent), 262);
|
||||
require(IsWindowVisible(embedded) && IsWindowEnabled(parent) &&
|
||||
!findTestWindow(L"KSwitcher.LAN", nullptr), "search opens Manage computers in the configurator");
|
||||
RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
RECT searchRect{};
|
||||
GetClientRect(parent, &searchRect);
|
||||
auto searchDc = GetDC(parent);
|
||||
const auto searchImage = ks::screenshotClip(searchDc, searchRect.right, searchRect.bottom, {});
|
||||
ReleaseDC(parent, searchDc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"settings-search.png",
|
||||
ks::encodePng(ks::decodeImage(searchImage)));
|
||||
SetWindowTextW(search, L"no-such-setting-123");
|
||||
require(TreeView_GetCount(navigation) == 1, "no matches leaves a single result message");
|
||||
SetWindowTextW(search, L"");
|
||||
require(TreeView_GetCount(navigation) == sections &&
|
||||
TreeView_GetSelection(navigation) == settingsSection(navigation, 10),
|
||||
"clearing search restores the tree and its active page");
|
||||
SetWindowTextW(search, L"OpenBao server");
|
||||
const auto serverResult = TreeView_GetChild(navigation, TreeView_GetRoot(navigation));
|
||||
require(serverResult && TreeView_SelectItem(navigation, serverResult), "search finds the OpenBao server field");
|
||||
const auto sync = GetDlgItem(pane, 271);
|
||||
require(IsWindowVisible(GetDlgItem(sync, 602)) && IsWindowEnabled(parent),
|
||||
"search reveals the embedded OpenBao page");
|
||||
SetWindowTextW(search, L"");
|
||||
selectSettingsPage(parent, 1);
|
||||
require(!saveEnabled(),"changing sections leaves Settings clean");
|
||||
SendMessageW(parent, WM_COMMAND, 259, 0);
|
||||
HWND dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr);
|
||||
require(dialog && !IsWindowEnabled(parent), "chat dialog opens with disabled parent");
|
||||
@@ -252,9 +828,15 @@ int main()
|
||||
SendMessageW(dialog, WM_COMMAND, IDOK, 0);
|
||||
require(!IsWindow(dialog) && IsWindowEnabled(parent), "profile applies to settings draft");
|
||||
require(saveEnabled() == (app.layouts.size()>1),"accepted chat edits refresh Save immediately");
|
||||
selectSettingsPage(parent, 16);
|
||||
SetDlgItemTextW(correction, 412, L"Релізик\r\nрелізик, словечко");
|
||||
SetDlgItemTextW(correction, 416, L" HeLo = Hello\r\n");
|
||||
SendMessageW(parent, WM_COMMAND, IDOK, 0);
|
||||
require(!app.settingsWindow && app.settings.chatCycles.at(key).size() == app.layouts.size(), "settings saves selected languages");
|
||||
require(ks::loadSettings(root / L"settings.json", app.layouts).chatCycles == app.settings.chatCycles, "profile saved to disk");
|
||||
const auto saved = ks::loadSettings(root / L"settings.json", app.layouts);
|
||||
require(saved.chatCycles == app.settings.chatCycles, "profile saved to disk");
|
||||
require(saved.autoWords.at(L"uk") == std::vector<std::wstring>{L"релізик", L"словечко"} &&
|
||||
saved.autoReplacements.at(L"helo") == L"hello", "Settings Save normalizes and persists correction edits");
|
||||
ks::showSettings(app);
|
||||
parent = app.settingsWindow;
|
||||
require(!saveEnabled(),"reopened saved Settings is clean");
|
||||
@@ -290,36 +872,8 @@ int main()
|
||||
SendDlgItemMessageW(dialog, 722, LB_SETSEL, TRUE, -1);
|
||||
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(722, LBN_SELCHANGE), 0);
|
||||
HWND picker = GetDlgItem(dialog, 728);
|
||||
RECT dialogBounds{};
|
||||
GetWindowRect(dialog, &dialogBounds);
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
require(GetMonitorInfoW(MonitorFromWindow(dialog, MONITOR_DEFAULTTONEAREST), &monitor),
|
||||
"monitor work area available");
|
||||
const auto targetX = std::clamp(dialogBounds.left + 32, monitor.rcWork.left, monitor.rcWork.right - 120);
|
||||
const auto targetY = std::clamp(dialogBounds.top + 100, monitor.rcWork.top, monitor.rcWork.bottom - 48);
|
||||
HWND target = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, L"EDIT", L"Picker fixture",
|
||||
WS_POPUP | WS_VISIBLE, targetX, targetY, 120, 48,
|
||||
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
|
||||
require(picker && target, "window picker and target available");
|
||||
POINT drop{targetX + 1, targetY + 1};
|
||||
require(GetAncestor(WindowFromPoint(drop), GA_ROOT) == target, "fixture window is under the drop point");
|
||||
ScreenToClient(picker, &drop);
|
||||
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
|
||||
require(GetCapture() == picker, "window picker captures drag");
|
||||
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
|
||||
HWND outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
|
||||
RECT outlineBounds{}, targetBounds{};
|
||||
require(IsWindowVisible(outline) && GetWindowRect(outline, &outlineBounds) &&
|
||||
GetWindowRect(target, &targetBounds) && EqualRect(&outlineBounds, &targetBounds), "drag highlights the target window");
|
||||
SendMessageW(picker, WM_KEYDOWN, VK_ESCAPE, 0);
|
||||
require(!IsWindow(outline) && GetCapture() != picker, "Escape clears the outline and releases capture");
|
||||
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
|
||||
SendMessageW(picker, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(drop.x, drop.y));
|
||||
outline = findTestWindow(L"KSwitcher.AppPickerOutline", nullptr);
|
||||
SendMessageW(picker, WM_LBUTTONUP, 0, MAKELPARAM(drop.x, drop.y));
|
||||
require(!IsWindow(outline), "dropping clears the outline");
|
||||
auto pickedApp = ks::applicationName(ks::processName(target));
|
||||
DestroyWindow(target);
|
||||
pickTestApplication(picker, true);
|
||||
auto pickedApp = pickTestApplication(picker);
|
||||
auto pickedRow = SendDlgItemMessageW(dialog, 720, LB_FINDSTRINGEXACT, -1, (LPARAM)pickedApp.c_str());
|
||||
require(GetCapture() != picker && pickedRow >= 0 &&
|
||||
SendDlgItemMessageW(dialog, 720, LB_GETCURSEL, 0, 0) == pickedRow, "dropping on a window selects its executable");
|
||||
@@ -368,60 +922,24 @@ int main()
|
||||
SendMessageW(parent, WM_COMMAND, IDOK, 0);
|
||||
require(!ks::applicationLanguageSet(app.settings, L"codex"), "use defaults removes only selected application profile");
|
||||
require(ks::applicationLanguageSet(app.settings, L"notepad") != nullptr, "default reset leaves other application profile intact");
|
||||
app.settings.snippets = {{L";scope", L"Example", L"scope-fixture"}};
|
||||
ks::showSettings(app); parent=app.settingsWindow;
|
||||
require(!saveEnabled(),"Settings starts clean before separately saved snippet edit");
|
||||
ks::showSnippets(app);
|
||||
HWND snippets = parent;
|
||||
require(!app.snippetsWindow && IsWindowVisible(GetDlgItem(snippets, 301)),
|
||||
"opening Snippets from Settings selects its inline editor");
|
||||
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
|
||||
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
|
||||
require(IsDlgButtonChecked(snippets,314)==BST_UNCHECKED, "old snippet shows everywhere");
|
||||
CheckDlgButton(snippets,314,BST_CHECKED);
|
||||
SendMessageW(snippets,WM_COMMAND,314,0);
|
||||
SetDlgItemTextW(snippets,315,L"Notepad.exe");
|
||||
auto secondApp = SendDlgItemMessageW(snippets,316,CB_ADDSTRING,0,(LPARAM)L"MS-Teams.EXE");
|
||||
SendDlgItemMessageW(snippets,316,CB_SETCURSEL,secondApp,0);
|
||||
SendMessageW(snippets,WM_COMMAND,317,0);
|
||||
SendMessageW(snippets,WM_COMMAND,317,0);
|
||||
wchar_t appList[128]{};
|
||||
GetDlgItemTextW(snippets,315,appList,128);
|
||||
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "Add app appends a second application without duplicates");
|
||||
SendMessageW(snippets,WM_COMMAND,318,0);
|
||||
require(IsWindow(snippets) && app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "inline snippet editor saves selected applications");
|
||||
require(!saveEnabled() && status()==L"No unsaved settings.","separately saved snippet edit leaves Settings clean");
|
||||
RedrawWindow(snippets,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
RECT snippetRect{};GetClientRect(snippets,&snippetRect);
|
||||
HDC snippetDc=GetDC(snippets);
|
||||
auto snippetImage=ks::screenshotClip(snippetDc,snippetRect.right,snippetRect.bottom,{});
|
||||
ReleaseDC(snippets,snippetDc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"snippet-scopes.png",ks::encodePng(ks::decodeImage(snippetImage)));
|
||||
SendMessageW(parent,WM_COMMAND,IDCANCEL,0);
|
||||
ks::showSnippets(app);snippets=app.snippetsWindow;
|
||||
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
|
||||
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
|
||||
require(IsDlgButtonChecked(snippets,314)==BST_CHECKED, "scope restored when reopening editor");
|
||||
SetDlgItemTextW(snippets,315,L"chrome.exe");
|
||||
SendMessageW(snippets,WM_COMMAND,IDCANCEL,0);
|
||||
require(app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "cancel preserves existing scope");
|
||||
snippetEditorChecks(app, root);
|
||||
ks::showSettings(app);parent=app.settingsWindow;
|
||||
SendMessageW(parent,WM_COMMAND,262,0);
|
||||
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
|
||||
require(lan && !IsWindowEnabled(parent),"LAN pairing opens a native child window");
|
||||
HWND lan=showComputerSettings(parent);
|
||||
require(lan && IsWindowVisible(lan) && IsWindowEnabled(parent),
|
||||
"LAN pairing opens in the Settings content area");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,705)),"pairing disabled without discovered peer");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,706)),"no cancellation without pending pairing");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,707)),"cannot forget nonexistent pair");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,715)),"input sharing requires a paired computer");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,716)),"stop input disabled when sharing is off");
|
||||
require(GetDlgItem(lan,721)!=nullptr,"monitor arrangement grid is present");
|
||||
require(!(GetWindowLongPtrW(lan,GWL_STYLE)&(WS_THICKFRAME|WS_MAXIMIZEBOX)),"LAN window has a fixed size");
|
||||
require((GetWindowLongPtrW(lan,GWL_STYLE)&WS_CHILD)!=0,"LAN content is a child panel");
|
||||
require(GetDlgItem(lan,711)==nullptr,"obsolete side radios are removed");
|
||||
require(SendDlgItemMessageW(lan,702,LB_GETCOUNT,0,0)==0,"disabled discovery lists no generic network devices");
|
||||
require(!std::filesystem::exists(root/L"lan-pairing.bin"),"opening LAN settings does not enable or save discovery");
|
||||
SendMessageW(lan,WM_COMMAND,722,0);
|
||||
auto help=findTestWindow(L"KSwitcher.LAN.Help",nullptr);
|
||||
require(help&&!IsWindowEnabled(lan),"connection help opens without changing network settings");
|
||||
require(help&&!IsWindowEnabled(parent),"connection help opens without changing network settings");
|
||||
wchar_t command[4096]{};GetDlgItemTextW(help,723,command,4096);
|
||||
require(std::wstring(command).find(ks::executable())!=std::wstring::npos&&
|
||||
std::wstring(command).find(L"-LocalPort 45884")!=std::wstring::npos&&
|
||||
@@ -433,13 +951,12 @@ int main()
|
||||
auto helpImage=ks::screenshotClip(helpDc,helpRect.right,helpRect.bottom,{});ReleaseDC(help,helpDc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-connection-help.png",ks::encodePng(ks::decodeImage(helpImage)));
|
||||
SendMessageW(help,WM_COMMAND,IDCANCEL,0);
|
||||
require(IsWindowEnabled(lan),"closing connection help returns to LAN setup");
|
||||
require(IsWindowEnabled(parent),"closing connection help returns to LAN setup");
|
||||
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
RECT lanRect{};GetClientRect(lan,&lanRect);HDC lanDc=GetDC(lan);
|
||||
auto lanImage=ks::screenshotClip(lanDc,lanRect.right,lanRect.bottom,{});ReleaseDC(lan,lanDc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-pairing.png",ks::encodePng(ks::decodeImage(lanImage)));
|
||||
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);
|
||||
require(IsWindowEnabled(parent)&&!saveEnabled(),"closing discovery restores Settings without false unsaved state");
|
||||
require(IsWindowEnabled(parent)&&!saveEnabled(),"opening discovery leaves Settings clean");
|
||||
require(status().find(L"Network changes save automatically")!=std::wstring::npos,"Settings explains why network actions do not enable Save");
|
||||
SendMessageW(parent,WM_COMMAND,IDCANCEL,0);
|
||||
}
|
||||
@@ -448,10 +965,9 @@ int main()
|
||||
{"trusted",{{std::string(32,'b'),{{"name","Test paired KSwitcher"},{"key",std::string(64,'f')}}}}}};
|
||||
auto text=fixture.dump();ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(text.begin(),text.end())));
|
||||
ks::App pairedApp(GetModuleHandleW(nullptr),true,root);ks::showSettings(pairedApp);
|
||||
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,262,0);
|
||||
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
|
||||
HWND lan=showComputerSettings(pairedApp.settingsWindow);
|
||||
require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"single saved pair selected automatically when opening LAN settings");
|
||||
wchar_t pairState[512]{};SendDlgItemMessageW(lan,702,LB_GETTEXT,0,(LPARAM)pairState);
|
||||
wchar_t pairState[512]{};GetDlgItemTextW(lan,710,pairState,std::size(pairState));
|
||||
require(std::wstring(pairState).find(L"Pair saved — input disabled here")!=std::wstring::npos,"saved pairing does not imply an active input connection");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,705))&&!IsWindowEnabled(GetDlgItem(lan,703))&&!IsWindowEnabled(GetDlgItem(lan,704)),"saved pair disables pairing and code controls");
|
||||
SendDlgItemMessageW(lan,702,LB_SETCURSEL,-1,0);
|
||||
@@ -475,8 +991,7 @@ int main()
|
||||
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
RECT r{};GetClientRect(lan,&r);HDC dc=GetDC(lan);auto screenshot=ks::screenshotClip(dc,r.right,r.bottom,{});ReleaseDC(lan,dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-screen-layout.png",ks::encodePng(ks::decodeImage(screenshot)));
|
||||
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);
|
||||
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
}
|
||||
{
|
||||
using J=ks::lan::Json;const std::string b(32,'b'),c(32,'c');
|
||||
@@ -485,7 +1000,7 @@ int main()
|
||||
{"positions",{{b,J::array({-1,0})},{c,J::array({1,0})}}}};
|
||||
auto text=fixture.dump();ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(text.begin(),text.end())));
|
||||
ks::App layoutApp(GetModuleHandleW(nullptr),true,root);ks::showSettings(layoutApp);
|
||||
SendMessageW(layoutApp.settingsWindow,WM_COMMAND,262,0);auto lan=findTestWindow(L"KSwitcher.LAN",nullptr);auto grid=GetDlgItem(lan,721);
|
||||
auto lan=showComputerSettings(layoutApp.settingsWindow);auto grid=GetDlgItem(lan,721);
|
||||
RECT r{};GetClientRect(grid,&r);
|
||||
auto point=[&](int column,int row){return MAKELPARAM((2*column+1)*r.right/10,(2*row+1)*r.bottom/6);};
|
||||
SendMessageW(grid,WM_LBUTTONDOWN,MK_LBUTTON,point(1,1));SendMessageW(grid,WM_MOUSEMOVE,MK_LBUTTON,point(1,0));SendMessageW(grid,WM_LBUTTONUP,0,point(1,0));
|
||||
@@ -494,7 +1009,7 @@ int main()
|
||||
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
GetClientRect(lan,&r);auto dc=GetDC(lan);auto screenshot=ks::screenshotClip(dc,r.right,r.bottom,{});ReleaseDC(lan,dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-three-computers.png",ks::encodePng(ks::decodeImage(screenshot)));
|
||||
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);SendMessageW(layoutApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
SendMessageW(layoutApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
}
|
||||
std::filesystem::remove_all(root);
|
||||
std::cout << "Passed " << passed << " chat profile checks\n";
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include <psapi.h>
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <future>
|
||||
#include <thread>
|
||||
static void require(bool ok, const char *name) {
|
||||
if (!ok) throw std::runtime_error(name);
|
||||
std::cout << "PASS " << name << '\n';
|
||||
@@ -39,12 +41,66 @@ static void verifyImage(HWND w) {
|
||||
}
|
||||
require(c.text()==L"Snapshot mixed text","preserves accompanying text");
|
||||
}
|
||||
static LRESULT CALLBACK delayedImageOwner(HWND window, UINT message, WPARAM format, LPARAM param) {
|
||||
if (message == WM_RENDERFORMAT && format == CF_DIB) {
|
||||
const auto dib = ks::imageDib(ks::Pixels{1, 1, ks::Bytes{77, 0, 0, 255}});
|
||||
if (auto data = GlobalAlloc(GMEM_MOVEABLE, dib.data.size())) {
|
||||
if (auto bytes = GlobalLock(data)) {
|
||||
memcpy(bytes, dib.data.data(), dib.data.size());
|
||||
GlobalUnlock(data);
|
||||
if (SetClipboardData(CF_DIB, data)) return 0;
|
||||
}
|
||||
GlobalFree(data);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcW(window, message, format, param);
|
||||
}
|
||||
static void verifyDelayedImageSnapshot(HWND window) {
|
||||
std::promise<HWND> ready;
|
||||
auto owner = ready.get_future();
|
||||
std::jthread publisher([&] {
|
||||
WNDCLASSW wc{};
|
||||
wc.lpfnWndProc = delayedImageOwner;
|
||||
wc.hInstance = GetModuleHandleW(nullptr);
|
||||
wc.lpszClassName = L"KSwitcher.DelayedClipboardFixture";
|
||||
HWND delayed = RegisterClassW(&wc) ? CreateWindowExW(0, wc.lpszClassName, L"", 0, 0, 0, 0, 0,
|
||||
HWND_MESSAGE, nullptr, wc.hInstance, nullptr) : nullptr;
|
||||
bool published = false;
|
||||
if (delayed && OpenClipboard(delayed)) {
|
||||
if (EmptyClipboard()) SetClipboardData(CF_DIB, nullptr);
|
||||
published = IsClipboardFormatAvailable(CF_DIB) && GetClipboardOwner() == delayed;
|
||||
CloseClipboard();
|
||||
}
|
||||
ready.set_value(published ? delayed : nullptr);
|
||||
if (published) {
|
||||
MSG message{};
|
||||
while (GetMessageW(&message, delayed, 0, 0) > 0 && message.message != WM_CLOSE)
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
if (delayed) DestroyWindow(delayed);
|
||||
});
|
||||
const auto delayed = owner.get();
|
||||
require(delayed != nullptr, "publishes a delayed image format");
|
||||
struct CloseOwner { HWND window; ~CloseOwner() { PostMessageW(window, WM_CLOSE, 0, 0); } } close{delayed};
|
||||
const auto before = GetClipboardSequenceNumber();
|
||||
ks::ClipboardSnapshot snapshot;
|
||||
const auto captured = snapshot.capture(window, before);
|
||||
require(captured == GetClipboardSequenceNumber(), "snapshot reports the sequence after delayed rendering");
|
||||
const auto temporary = ks::writeClipboard(window, ks::textClip(L"temporary"));
|
||||
snapshot.restore(window, temporary);
|
||||
const auto clip = ks::readClipboard(window);
|
||||
const auto image = ks::decodeImage(clip);
|
||||
require(image.width == 1 && image.height == 1 && image.bgra.front() == 77, "restores the delayed image");
|
||||
}
|
||||
int main(int argc,char**argv) {
|
||||
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
HWND w=owner(); int result=0; ks::Clip original; bool saved=false;
|
||||
try {
|
||||
std::string mode=argc>1?argv[1]:"suite";
|
||||
if(mode=="publish") {
|
||||
if(mode=="temporary") {
|
||||
ks::writeClipboard(w,ks::textClip(L"temporary"));
|
||||
} else if(mode=="publish") {
|
||||
ks::Pixels p{1566,1068,ks::Bytes(1566*1068*4,255)}; p.bgra[0]=77;
|
||||
auto dib=ks::imageDib(p); auto v5=dib;
|
||||
BITMAPV5HEADER h{}; h.bV5Size=sizeof(h); h.bV5Width=p.width; h.bV5Height=-p.height;
|
||||
@@ -60,9 +116,17 @@ int main(int argc,char**argv) {
|
||||
auto clip=ks::readClipboard(w,64*1024*1024);
|
||||
ks::writeClipboard(w,ks::textClip(L"temporary")); ks::writeClipboard(w,clip);
|
||||
} else {
|
||||
ks::ClipboardSnapshot snapshot; snapshot.capture(w,GetClipboardSequenceNumber());
|
||||
auto seq=ks::writeClipboard(w,ks::textClip(L"temporary"));
|
||||
require(snapshot.restore(w,seq)==GetClipboardSequenceNumber(),"helper returns current sequence");
|
||||
ks::ClipboardSnapshot snapshot;
|
||||
auto started=GetTickCount64();
|
||||
snapshot.capture(w,GetClipboardSequenceNumber());
|
||||
std::cout<<"Image snapshot capture: "<<GetTickCount64()-started<<" ms\n";
|
||||
// A separate publisher avoids blocking clipboard notifications on this waiting test thread.
|
||||
child(L"temporary");
|
||||
const auto seq=GetClipboardSequenceNumber();
|
||||
started=GetTickCount64();
|
||||
const auto restored=snapshot.restore(w,seq);
|
||||
std::cout<<"Image snapshot restore: "<<GetTickCount64()-started<<" ms\n";
|
||||
require(restored==GetClipboardSequenceNumber(),"helper returns current sequence");
|
||||
}
|
||||
auto after=resident();
|
||||
auto report="baseline="+std::to_string(baseline)+" after="+std::to_string(after)+" delta="+std::to_string(int64_t(after)-int64_t(baseline))+"\n";
|
||||
@@ -78,6 +142,16 @@ int main(int argc,char**argv) {
|
||||
bool rejected=false;
|
||||
try {ks::readClipboard(w,32*1024*1024,ks::ClipboardRead::WithoutImages,seq);} catch(...) {rejected=true;}
|
||||
require(rejected,"resident rejects images before reading their data");
|
||||
{
|
||||
ks::ClipboardSnapshot snapshot;
|
||||
try {snapshot.capture(w,seq-1); rejected=false;}
|
||||
catch(const std::runtime_error &error) {
|
||||
rejected=std::string_view(error.what()).find("Clipboard changed while taking snapshot") != std::string_view::npos;
|
||||
}
|
||||
require(rejected,"stale image snapshot reports the sequence mismatch");
|
||||
snapshot.capture(w,seq);
|
||||
}
|
||||
require(GetClipboardSequenceNumber()==seq,"discarding an image snapshot leaves the clipboard untouched");
|
||||
{
|
||||
ks::ClipboardSnapshot snapshot; snapshot.capture(w,seq);
|
||||
auto stale=ks::writeClipboard(w,ks::textClip(L"temporary"));
|
||||
@@ -100,6 +174,7 @@ int main(int argc,char**argv) {
|
||||
auto marked=ks::textClip(L"line"); marked.formats.push_back({0,L"MSDEVLineSelect",ks::Bytes{1}});
|
||||
ks::writeClipboard(w,marked);
|
||||
require(ks::readClipboard(w,1024,ks::ClipboardRead::Selection).formats.size()==2,"selection reader preserves editor guard metadata");
|
||||
verifyDelayedImageSnapshot(w);
|
||||
std::cout<<"PASS clipboard snapshot suite\n";
|
||||
}
|
||||
} catch(const std::exception &e) {std::cerr<<"FAIL "<<e.what()<<'\n';result=1;}
|
||||
|
||||
+32
-8
@@ -19,6 +19,7 @@ public static class ConfigurationTestUi {
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindow(string cls,string title);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr w,int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowEnabled(IntPtr w);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr w);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr w,uint msg,IntPtr wp,IntPtr lp);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr w,uint msg,IntPtr wp,IntPtr lp);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SetText(IntPtr w,uint msg,IntPtr wp,string text);
|
||||
@@ -41,7 +42,8 @@ function Window($class) {
|
||||
for($i=0;$i -lt 100;$i++) {
|
||||
$title=switch($class){'KSwitcher.Main'{'KSwitcher'};'KSwitcher.Settings'{'KSwitcher settings'};'KSwitcher.Snippets'{'Text snippets'};'KSwitcher.Logs'{'KSwitcher diagnostic operations'}}
|
||||
$window=[ConfigurationTestUi]::FindWindow($class,$title)
|
||||
if($window -ne [IntPtr]::Zero){return $window}
|
||||
if($window -ne [IntPtr]::Zero -and
|
||||
($class -eq 'KSwitcher.Main' -or [ConfigurationTestUi]::IsWindowVisible($window))) { return $window }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
foreach($process in $processes){$process.Refresh(); Write-Host ("Diagnostic process {0}: exited={1} title={2}" -f $process.Id,$process.HasExited,$process.MainWindowTitle)}
|
||||
@@ -57,6 +59,14 @@ function Launch($file,$argument) {
|
||||
function Click($window,$id) {
|
||||
$null=[ConfigurationTestUi]::PostMessage($window,0x111,[IntPtr]$id,[IntPtr]::Zero)
|
||||
}
|
||||
function SelectSection($settings,$index) {
|
||||
$navigation=[ConfigurationTestUi]::GetDlgItem($settings,260)
|
||||
$node=[ConfigurationTestUi]::SendMessage($navigation,0x110a,[IntPtr]::Zero,[IntPtr]::Zero)
|
||||
for($i=0;$i -lt $index;$i++) {
|
||||
$node=[ConfigurationTestUi]::SendMessage($navigation,0x110a,[IntPtr]1,$node)
|
||||
}
|
||||
$null=[ConfigurationTestUi]::SendMessage($navigation,0x110b,[IntPtr]9,$node)
|
||||
}
|
||||
function TestLogs {
|
||||
'test-marker' | Set-Content -LiteralPath (Join-Path $root 'data/kswitcher.log')
|
||||
$config=Launch 'KSwitcher.Config.exe' '--logs'
|
||||
@@ -101,9 +111,15 @@ try {
|
||||
$second=Launch 'KSwitcher.Config.exe' ''
|
||||
Assert ($second.WaitForExit(6000) -and $second.ExitCode -eq 0) 'second launch forwards to existing instance'
|
||||
Assert ((Window 'KSwitcher.Settings') -eq $settings) 'existing settings window reused'
|
||||
$pane=[ConfigurationTestUi]::GetDlgItem($settings,264)
|
||||
$null=[ConfigurationTestUi]::PostMessage($main,0x312,[IntPtr]21,[IntPtr]::Zero)
|
||||
$editor=[ConfigurationTestUi]::GetDlgItem($pane,301)
|
||||
for($i=0;$i -lt 100 -and ![ConfigurationTestUi]::IsWindowVisible($editor);$i++) { Start-Sleep -Milliseconds 50 }
|
||||
Assert ([ConfigurationTestUi]::IsWindowVisible($editor)) 'resident Snippets command selects the inline editor'
|
||||
# Only inject into the isolated fixture window, never another foreground app.
|
||||
Assert ([ConfigurationTestUi]::GetForegroundWindow() -eq $settings) 'fixture owns foreground before shortcut capture test'
|
||||
$field=[ConfigurationTestUi]::GetDlgItem($settings,210)
|
||||
SelectSection $settings 2
|
||||
$field=[ConfigurationTestUi]::GetDlgItem($pane,210)
|
||||
Assert ([ConfigurationTestUi]::FocusControl($field)) 'shortcut field receives actual focus'
|
||||
Assert ([ConfigurationTestUi]::PressF24() -eq 2) 'test F24 events accepted'
|
||||
$text=[Text.StringBuilder]::new(128)
|
||||
@@ -114,7 +130,7 @@ try {
|
||||
Start-Sleep -Milliseconds 20
|
||||
}
|
||||
Assert ($text.ToString() -eq 'F24') 'resident hook forwards shortcut capture to configurator'
|
||||
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($settings,240),0x0c,[IntPtr]::Zero,'321')
|
||||
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($pane,240),0x0c,[IntPtr]::Zero,'321')
|
||||
Click $settings 1
|
||||
Assert ($config.WaitForExit(6000) -and $config.ExitCode -eq 0) 'save exits configurator'
|
||||
Assert ((Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json).maxItems -eq 321) 'save committed through resident process'
|
||||
@@ -122,27 +138,35 @@ try {
|
||||
$resident.Refresh(); Assert (!$resident.HasExited) 'resident survives settings save'
|
||||
$config=Launch 'KSwitcher.Config.exe' ''
|
||||
$settings=Window 'KSwitcher.Settings'
|
||||
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($settings,240),0x0c,[IntPtr]::Zero,'456')
|
||||
$pane=[ConfigurationTestUi]::GetDlgItem($settings,264)
|
||||
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($pane,240),0x0c,[IntPtr]::Zero,'456')
|
||||
Click $settings 2
|
||||
$prompt=[IntPtr]::Zero
|
||||
for($i=0;$i -lt 100 -and $prompt -eq [IntPtr]::Zero;$i++) {
|
||||
$prompt=[ConfigurationTestUi]::FindWindow('#32770',('KSwitcher {0} Unsaved settings' -f [char]0x2014))
|
||||
if($prompt -eq [IntPtr]::Zero) { Start-Sleep -Milliseconds 50 }
|
||||
}
|
||||
Assert ($prompt -ne [IntPtr]::Zero) 'cancel asks about unsaved changes'
|
||||
Click $prompt 7
|
||||
Assert ($config.WaitForExit(6000)) 'cancel exits configurator'
|
||||
Assert ((Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json).maxItems -eq 321) 'cancel preserves saved settings'
|
||||
$config=Launch 'KSwitcher.Config.exe' '--snippets'
|
||||
$snippets=Window 'KSwitcher.Snippets'
|
||||
$null=[ConfigurationTestUi]::SendMessage($snippets,0,[IntPtr]::Zero,[IntPtr]::Zero)
|
||||
foreach($id in @(302,303,311,312,313)) {
|
||||
foreach($id in @(302,303,311,320)) {
|
||||
Assert (![ConfigurationTestUi]::IsWindowEnabled([ConfigurationTestUi]::GetDlgItem($snippets,$id))) "snippet control $id disabled without selection"
|
||||
}
|
||||
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]310,[IntPtr]::Zero)
|
||||
foreach($id in @(302,303,311,312,313)) {
|
||||
foreach($id in @(302,303,311,320)) {
|
||||
Assert ([ConfigurationTestUi]::IsWindowEnabled([ConfigurationTestUi]::GetDlgItem($snippets,$id))) 'Add enables snippet editing'
|
||||
}
|
||||
$null=[ConfigurationTestUi]::SetText([ConfigurationTestUi]::GetDlgItem($snippets,303),0x0c,[IntPtr]::Zero,'preserved snippet')
|
||||
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]310,[IntPtr]::Zero)
|
||||
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]311,[IntPtr]::Zero)
|
||||
foreach($id in @(302,303,311,312,313)) {
|
||||
foreach($id in @(302,303,311,320)) {
|
||||
Assert (![ConfigurationTestUi]::IsWindowEnabled([ConfigurationTestUi]::GetDlgItem($snippets,$id))) 'deleting selection disables snippet editing'
|
||||
}
|
||||
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]312,[IntPtr]::Zero)
|
||||
$null=[ConfigurationTestUi]::SendMessage($snippets,0x111,[IntPtr]320,[IntPtr]::Zero)
|
||||
$snippetText=[Text.StringBuilder]::new(128)
|
||||
$null=[ConfigurationTestUi]::GetText([ConfigurationTestUi]::GetDlgItem($snippets,303),0x0d,[IntPtr]128,$snippetText)
|
||||
Assert ($snippetText.Length -eq 0) 'marker command cannot edit an unselected snippet'
|
||||
|
||||
@@ -84,9 +84,11 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) {
|
||||
{
|
||||
ks::App app(instance,false,folder/L"data");app.window=owner;
|
||||
app.settings.history=false;app.settings.autoCorrect=false;app.settings.writeLog=true;
|
||||
auto prepare=[&](wchar_t last=L'r') {
|
||||
auto prepare=[&](wchar_t last=L'r', wchar_t prefix=0) {
|
||||
if(!ks::activateWindow(target))throw std::runtime_error("isolated Far lost foreground");
|
||||
key(VK_ESCAPE);key('Y',0,LEFT_CTRL_PRESSED);key(VK_OEM_1,L':',SHIFT_PRESSED);key(WORD(towupper(last)),last);
|
||||
key(VK_ESCAPE);key('Y',0,LEFT_CTRL_PRESSED);
|
||||
if(prefix)key(prefix==L' '?VK_SPACE:WORD(towupper(prefix)),prefix);
|
||||
key(VK_OEM_1,L':',SHIFT_PRESSED);key(WORD(towupper(last)),last);
|
||||
app.run.reset();app.run.window=target;app.run.layout=ks::windowLayout(target);
|
||||
app.run.at=GetTickCount64();app.run.keys=L":r";
|
||||
};
|
||||
@@ -103,6 +105,11 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) {
|
||||
require(ks::readClipboard(owner).text()==sentinel.text(),"snippet restores original clipboard");
|
||||
prepare(L'x');before=position();original=row();expand(L"rider .{enter}");
|
||||
require(row()==original && position().X==before.X,"mismatched trigger restores original caret and never executes Enter");
|
||||
prepare(L'r',L'x');before=position();original=row();expand(L"rider .");
|
||||
require(row()==original && position().X==before.X,"trigger inside a word restores original caret");
|
||||
prepare(L'r',L' ');before=position();expand(L"rider .");
|
||||
require(row().substr(before.X-3,8)==L" rider ." && position().X==before.X+5,
|
||||
"trigger after a space preserves the separator");
|
||||
prepare();before=position();original=row();expand(L"left{cursor}right");
|
||||
require(row().substr(before.X-2,9)==L"leftright" && position().X==before.X+2,"cursor marker uses Far selection semantics");
|
||||
prepare();before=position();original=row();expand(L"first\nsecond{enter}");
|
||||
|
||||
+563
-17
@@ -1,7 +1,10 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Executable,
|
||||
[Parameter(Mandatory)][string]$Fixture,
|
||||
[switch]$SystemOpenOnly
|
||||
[switch]$SystemOpenOnly,
|
||||
[switch]$TerminalOnly,
|
||||
[int]$ScanEntries = 0,
|
||||
[string]$Node='node'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type @"
|
||||
@@ -10,6 +13,10 @@ using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class FilesActivationUi {
|
||||
public static void CreateScanFiles(string directory, int count) {
|
||||
for (int i = 0; i < count; i++)
|
||||
using (System.IO.File.Create(System.IO.Path.Combine(directory, i.ToString("D6") + ".txt"))) {}
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
@@ -21,7 +28,35 @@ public static class FilesActivationUi {
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint relation);
|
||||
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr window, IntPtr dc);
|
||||
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
|
||||
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
|
||||
public static uint ReadScreenCenter(IntPtr window) {
|
||||
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
|
||||
try {
|
||||
Rect bounds;
|
||||
if (!GetWindowRect(window, out bounds)) throw new InvalidOperationException("Missing terminal output.");
|
||||
var dc = GetDC(IntPtr.Zero);
|
||||
if (dc == IntPtr.Zero) throw new InvalidOperationException("Could not read the screen.");
|
||||
try { return GetPixel(dc, (bounds.Left + bounds.Right) / 2, (bounds.Top + bounds.Bottom) / 2); }
|
||||
finally { ReleaseDC(IntPtr.Zero, dc); }
|
||||
} finally {
|
||||
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool HasWarningBackground(IntPtr window) {
|
||||
var dc = GetDC(window);
|
||||
if (dc == IntPtr.Zero) return false;
|
||||
try { return GetPixel(dc, 2, 2) == 0x80; }
|
||||
finally { ReleaseDC(window, dc); }
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
@@ -73,6 +108,42 @@ function Wait-Until([string]$Description, [scriptblock]$Condition) {
|
||||
throw "Timed out waiting for $Description"
|
||||
}
|
||||
|
||||
function Invoke-ClipboardOperation([scriptblock]$Operation) {
|
||||
for ($attempt = 1; $attempt -le 3; $attempt++) {
|
||||
try { return (& $Operation) }
|
||||
catch {
|
||||
# CLIPBRD_E_CANT_OPEN means another process is using the shared clipboard.
|
||||
if ($_.Exception.GetBaseException().HResult -ne 0x800401D0 -or
|
||||
$attempt -eq 3) { throw }
|
||||
[Windows.Forms.Application]::DoEvents()
|
||||
Start-Sleep -Milliseconds 25
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Find-OperationDialog($Owner, [int]$Control) {
|
||||
$candidate = [IntPtr]::Zero
|
||||
while ($true) {
|
||||
$candidate = [FilesActivationUi]::FindWindowEx([IntPtr]::Zero, $candidate, '#32770', [NullString]::Value)
|
||||
if ($candidate -eq [IntPtr]::Zero) { return [IntPtr]::Zero }
|
||||
if (![FilesActivationUi]::IsWindowVisible($candidate) -or
|
||||
[FilesActivationUi]::GetDlgItem($candidate, $Control) -eq [IntPtr]::Zero) { continue }
|
||||
$parent = [FilesActivationUi]::GetWindow($candidate, 4)
|
||||
while ($parent -ne [IntPtr]::Zero) {
|
||||
if ($parent -eq $Owner) { return $candidate }
|
||||
$parent = [FilesActivationUi]::GetWindow($parent, 4)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Answer-OperationDialog([int]$Control, [int]$Answer) {
|
||||
Wait-Until "operation dialog with control $Control" {
|
||||
(Find-OperationDialog $window $Control) -ne [IntPtr]::Zero
|
||||
}
|
||||
$dialog = Find-OperationDialog $window $Control
|
||||
[void][FilesActivationUi]::PostMessage($dialog, 0x111, [IntPtr]$Answer, [IntPtr]::Zero)
|
||||
}
|
||||
|
||||
function Read-Text($Control, $Message = 0x0D, $Parameter = 32768) {
|
||||
$buffer = [Text.StringBuilder]::new(32768)
|
||||
[void][FilesActivationUi]::Read($Control, $Message, [IntPtr]$Parameter, $buffer)
|
||||
@@ -114,6 +185,11 @@ function Send-Terminal([string]$Command) {
|
||||
Press-Enter $inputBox
|
||||
}
|
||||
|
||||
function Send-InteractiveTerminal([string]$Command, [string]$EnterKey = '{ENTER}') {
|
||||
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, $Command)
|
||||
$keys.SendKeys($EnterKey)
|
||||
}
|
||||
|
||||
function Assert-Open($List, $Target, [bool]$DoubleClick) {
|
||||
$report = "$Target.opened"
|
||||
Remove-Item -LiteralPath $report -ErrorAction SilentlyContinue
|
||||
@@ -131,9 +207,11 @@ $extension = ".ksfiles$unique"
|
||||
$progId = "KSwitcher.Files.Test.$unique"
|
||||
$saved = @{}
|
||||
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
|
||||
'ShowDetails', 'StatusFields', 'CommandHistory', 'WindowPlacement'
|
||||
'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement'
|
||||
$process = $null
|
||||
$trace = $null
|
||||
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
$webviewProfile=$env:WEBVIEW2_USER_DATA_FOLDER
|
||||
try {
|
||||
foreach ($name in $profileValues) {
|
||||
if ($name -in $profile.GetValueNames()) {
|
||||
@@ -150,7 +228,7 @@ try {
|
||||
Copy-Item -LiteralPath "$source\WebView2Loader.dll", "$source\terminal" -Destination $app -Recurse
|
||||
$program = Join-Path $leftDir 'Test program.exe'
|
||||
Copy-Item -LiteralPath $Fixture -Destination $program
|
||||
$document = Join-Path $(if($SystemOpenOnly){$leftDir}else{$rightDir}) "Test document$extension"
|
||||
$document = Join-Path $(if($SystemOpenOnly -or $TerminalOnly){$leftDir}else{$rightDir}) "Test document$extension"
|
||||
[IO.File]::WriteAllText($document, 'Document fixture')
|
||||
$association = $classes.CreateSubKey($extension)
|
||||
$association.SetValue('', $progId)
|
||||
@@ -170,6 +248,33 @@ try {
|
||||
foreach ($name in 'LeftWide', 'RightWide', 'ShowDetails') { $profile.SetValue($name, 1) }
|
||||
$profile.SetValue('StatusFields', 3)
|
||||
|
||||
if($TerminalOnly){
|
||||
$terminalPage = Join-Path $app 'terminal/index.html'
|
||||
$page = Get-Content -Raw -LiteralPath $terminalPage
|
||||
$page = $page.Replace('<style>','<style media="not all">').Replace('src="terminal.js"','src="startup-fixture.js"')
|
||||
[IO.File]::WriteAllText($terminalPage,$page)
|
||||
[IO.File]::WriteAllText((Join-Path $app 'terminal/startup-fixture.js'), @'
|
||||
function startTerminalFixture() {
|
||||
document.querySelector('style').media = 'all';
|
||||
const script = document.createElement('script');
|
||||
script.src = 'terminal.js';
|
||||
document.body.append(script);
|
||||
}
|
||||
'@)
|
||||
$listener=[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$listener.Start()
|
||||
$port=$listener.LocalEndpoint.Port
|
||||
$listener.Stop()
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=$port"
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $root 'webview'
|
||||
}
|
||||
if($SystemOpenOnly) {
|
||||
$profile.SetValue('PreviousCommandKey',0x0245,'DWord')
|
||||
$profile.SetValue('CommandHistoryKey',0x0477,'DWord')
|
||||
}
|
||||
if ($ScanEntries) {
|
||||
[FilesActivationUi]::CreateScanFiles("$leftDir\Test folder", $ScanEntries)
|
||||
}
|
||||
$process = Start-Process -FilePath $testExe -ArgumentList '--terminal-output-trace' -PassThru
|
||||
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
|
||||
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
@@ -180,6 +285,49 @@ try {
|
||||
$output = [FilesActivationUi]::GetDlgItem($window, 145)
|
||||
$inputBox = [FilesActivationUi]::FindWindowEx($window, [IntPtr]::Zero, 'Edit', $null)
|
||||
|
||||
if ($ScanEntries) {
|
||||
Wait-Until 'visible Files window' { [FilesActivationUi]::Activate($window) }
|
||||
Wait-Until 'folder fixture row' { (Find-Row $left '[Test folder]') -ge 0 }
|
||||
$folderRow = Find-Row $left '[Test folder]'
|
||||
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
|
||||
Press-Enter $inputBox
|
||||
Wait-Until 'nonzero folder scan progress' {
|
||||
[FilesActivationUi]::IsWindowVisible($status) -and
|
||||
(Read-Text $status) -match '^Reading ([1-9][0-9]*) \[Esc\]$'
|
||||
}
|
||||
$progress = Read-Text $status
|
||||
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]27, [IntPtr]::Zero)
|
||||
Wait-Until 'partial folder result' { (Read-Text $status) -match '^Partial: \d+$' }
|
||||
$partial = [FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() - 1
|
||||
$partialStatus = Read-Text $status
|
||||
if ($partial -le 0 -or $partial -ge $ScanEntries -or
|
||||
$partialStatus -ne "Partial: $partial" -or
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -ne "$leftDir\Test folder") {
|
||||
throw "Unexpected partial listing of $partial entries."
|
||||
}
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
$fullScan = [Diagnostics.Stopwatch]::StartNew()
|
||||
$keys.SendKeys('^r')
|
||||
Wait-Until 'complete folder result after Ctrl+R' {
|
||||
[FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $ScanEntries + 1
|
||||
}
|
||||
$fullScan.Stop()
|
||||
Write-Output "$progress. $partialStatus. Full scan: $ScanEntries files in $($fullScan.ElapsedMilliseconds) ms."
|
||||
$target = 65536
|
||||
[void][FilesActivationUi]::Send($left, 0x197, [IntPtr]$target, [IntPtr]::Zero)
|
||||
if ([FilesActivationUi]::Send($left, 0x18E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $target) {
|
||||
throw "Could not scroll row $target to the top."
|
||||
}
|
||||
$point = [IntPtr]((2 -shl 16) -bor 6)
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x201, [IntPtr]1, $point)
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x202, [IntPtr]::Zero, $point)
|
||||
Wait-Until 'mouse selection past the 16-bit row limit' {
|
||||
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $target
|
||||
}
|
||||
Write-Output "Clicked row $target after scrolling it to the top."
|
||||
return
|
||||
}
|
||||
|
||||
if($SystemOpenOnly) {
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
$explorer = New-Object -ComObject Shell.Application
|
||||
@@ -209,14 +357,10 @@ try {
|
||||
Wait-Until 'Files command line focused for document Shift+Enter' {
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'unsubmitted command')
|
||||
$keys.SendKeys('+{ENTER}')
|
||||
Wait-Until 'Shift+Enter invoking the default Windows file association' {
|
||||
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
|
||||
}
|
||||
if((Read-Text $inputBox) -cne 'unsubmitted command'){
|
||||
throw 'Shift+Enter changed the draft command.'
|
||||
}
|
||||
Wait-Until 'Files active for plain Enter' { [FilesActivationUi]::Activate($window) }
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
|
||||
Remove-Item -LiteralPath "$document.opened"
|
||||
@@ -224,7 +368,195 @@ try {
|
||||
Wait-Until 'plain Enter invoking the default Windows file association' {
|
||||
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
|
||||
}
|
||||
$command="start '$($document.Replace("'","''"))'"
|
||||
Wait-Until 'the system open action in terminal output and command history' {
|
||||
$history=$profile.GetValue('CommandHistory')
|
||||
[FilesActivationUi]::IsWindowVisible($output) -and $history -and
|
||||
([Text.Encoding]::Unicode.GetString($history).Split([char]0) -ccontains $command) -and
|
||||
(Select-String -LiteralPath $trace -Pattern ('^'+[regex]::Escape($document.Substring(0,24))) -Quiet)
|
||||
}
|
||||
Wait-Until 'Files active for command history' { [FilesActivationUi]::Activate($window) }
|
||||
$keys.SendKeys('%{F8}')
|
||||
$historyDialog=[IntPtr]::Zero
|
||||
Wait-Until 'command history showing only the opened file path' {
|
||||
$script:historyDialog=[FilesActivationUi]::GetForegroundWindow()
|
||||
$list=[FilesActivationUi]::GetDlgItem($historyDialog,324)
|
||||
$list -ne [IntPtr]::Zero -and (Find-Row $list $document) -ge 0
|
||||
}
|
||||
$historyList=[FilesActivationUi]::GetDlgItem($historyDialog,324)
|
||||
$historyRow=Find-Row $historyList $document
|
||||
[void][FilesActivationUi]::Send($historyList,0x186,[IntPtr]$historyRow,[IntPtr]::Zero)
|
||||
[void][FilesActivationUi]::PostMessage($historyDialog,0x111,[IntPtr]1,[IntPtr]::Zero)
|
||||
Wait-Until 'selecting the history path restoring a runnable command' { (Read-Text $inputBox) -ceq $command }
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
|
||||
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
|
||||
Remove-Item -LiteralPath "$document.opened"
|
||||
}
|
||||
if($SystemOpenOnly -or $TerminalOnly){
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
if ($TerminalOnly) {
|
||||
Wait-Until 'Files active for the terminal startup check' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$keys.SendKeys('^o')
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-pause'
|
||||
if ($LASTEXITCODE) { throw 'Could not pause terminal page initialization.' }
|
||||
foreach ($frame in 1..10) {
|
||||
if ([FilesActivationUi]::GetForegroundWindow() -ne $window -or
|
||||
![FilesActivationUi]::IsWindowVisible($output)) { throw 'The terminal must be visible for the startup check.' }
|
||||
$pixel = [FilesActivationUi]::ReadScreenCenter($output)
|
||||
if ($pixel -ne 0x181818) { throw ('Unexpected terminal startup background 0x{0:X6}.' -f $pixel) }
|
||||
Start-Sleep -Milliseconds 30
|
||||
}
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-resume'
|
||||
if ($LASTEXITCODE) { throw 'Could not resume terminal page initialization.' }
|
||||
Wait-Until 'the terminal rendering after startup' {
|
||||
Select-String -LiteralPath $trace -SimpleMatch ' web-anchor ' -Quiet -ErrorAction SilentlyContinue
|
||||
}
|
||||
$keys.SendKeys('^o')
|
||||
Wait-Until 'file panes restored after the startup check' { [FilesActivationUi]::IsWindowVisible($left) }
|
||||
Write-Output 'Verified the dark terminal background before WebView initialization completes.'
|
||||
}
|
||||
foreach($case in @(
|
||||
@{Name='enter-panes'; Keys='{ENTER}'},
|
||||
@{Name='shift-enter-panes'; Keys='+{ENTER}'},
|
||||
@{Name='enter-terminal'; Keys='{ENTER}'; HidePanes=$true},
|
||||
@{Name='shift-enter-terminal'; Keys='+{ENTER}'}
|
||||
)) {
|
||||
Wait-Until 'Files command line active' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
if($case.HidePanes){
|
||||
$keys.SendKeys('^o')
|
||||
Wait-Until 'file panes hidden' { ![FilesActivationUi]::IsWindowVisible($left) }
|
||||
}
|
||||
$marker=Join-Path $root "$($case.Name).txt"
|
||||
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
|
||||
Send-InteractiveTerminal $command $case.Keys
|
||||
Wait-Until "$($case.Name) running the command" {
|
||||
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
|
||||
!(Read-Text $inputBox)
|
||||
}
|
||||
if(Test-Path -LiteralPath "$document.opened"){
|
||||
throw "$($case.Name) did not give the command line priority."
|
||||
}
|
||||
}
|
||||
Write-Output 'Verified command-line priority for Enter and Shift+Enter with panels visible and hidden.'
|
||||
if(!$TerminalOnly){return}
|
||||
foreach($name in 'zzzz-dir-first','zzzz-dir-second'){
|
||||
[IO.File]::WriteAllText((Join-Path $leftDir $name),'dir marker')
|
||||
Send-InteractiveTerminal 'dir'
|
||||
Wait-Until "dir rendering $name in terminal output" {
|
||||
!(Read-Text $inputBox) -and
|
||||
(Select-String -LiteralPath $trace -SimpleMatch $name -Quiet -ErrorAction SilentlyContinue)
|
||||
}
|
||||
}
|
||||
$keys.SendKeys('^o')
|
||||
Wait-Until 'file panes visible again' { [FilesActivationUi]::IsWindowVisible($left) }
|
||||
$listing=Join-Path $root 'dir-visible.txt'
|
||||
Send-InteractiveTerminal "dir -Name | Set-Content -LiteralPath '$($listing.Replace("'","''"))'"
|
||||
Wait-Until 'dir running after restoring the file panes' {
|
||||
!(Read-Text $inputBox) -and (Test-Path -LiteralPath $listing) -and
|
||||
([IO.File]::ReadAllLines($listing) -ccontains 'zzzz-dir-second')
|
||||
}
|
||||
Write-Output 'Verified repeated dir commands in the same terminal with file panes hidden and visible.'
|
||||
$rightChild = Join-Path $rightDir "Command's [folder]"
|
||||
[void][IO.Directory]::CreateDirectory($rightChild)
|
||||
$childRow = "[$([IO.Path]::GetFileName($rightChild))]"
|
||||
Wait-Until 'new folder in the right panel' { (Find-Row $right $childRow) -ge 0 }
|
||||
$keys.SendKeys('{TAB}')
|
||||
Send-InteractiveTerminal 'cmd /d /c "cd > panel-cwd.txt"'
|
||||
Wait-Until 'native command running in the newly active right panel' {
|
||||
(Test-Path -LiteralPath (Join-Path $rightDir 'panel-cwd.txt')) -and
|
||||
(Find-Row $right 'panel-cwd.txt') -ge 0
|
||||
}
|
||||
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr](Find-Row $right $childRow), [IntPtr]::Zero)
|
||||
Press-Enter $inputBox
|
||||
$rightPath = [FilesActivationUi]::GetDlgItem($window, 143)
|
||||
Wait-Until 'navigation to the right panel subfolder' { (Read-Text $rightPath) -ceq $rightChild }
|
||||
Send-InteractiveTerminal 'cmd /d /c "cd > child-cwd.txt"'
|
||||
Wait-Until 'native command running in the navigated folder' {
|
||||
(Test-Path -LiteralPath (Join-Path $rightChild 'child-cwd.txt')) -and
|
||||
(Find-Row $right 'child-cwd.txt') -ge 0
|
||||
}
|
||||
Send-InteractiveTerminal 'cd ..'
|
||||
Wait-Until 'PowerShell cd navigating the right panel' { (Find-Row $right 'panel-cwd.txt') -ge 0 }
|
||||
$keys.SendKeys('{TAB}')
|
||||
Send-InteractiveTerminal 'cmd /d /c "cd > left-cwd.txt"'
|
||||
Wait-Until 'native command running back in the left panel' {
|
||||
(Test-Path -LiteralPath (Join-Path $leftDir 'left-cwd.txt')) -and
|
||||
(Find-Row $left 'left-cwd.txt') -ge 0
|
||||
}
|
||||
Write-Output 'Verified native commands follow panel switches and folder navigation in the same PowerShell session.'
|
||||
$marker=Join-Path $root 'webview-enter.txt'
|
||||
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$command)
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
|
||||
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
|
||||
Wait-Until 'the terminal WebView forwarding Enter to the command line' {
|
||||
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
|
||||
!(Read-Text $inputBox)
|
||||
}
|
||||
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
|
||||
# The left panel is already active after the working-directory check.
|
||||
$folderRow = Find-Row $left '[Test folder]'
|
||||
if ($folderRow -lt 0) { throw 'Missing folder for the terminal clipboard check.' }
|
||||
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
|
||||
$outputSelection = 'terminal-output-copy-fixture'
|
||||
Send-InteractiveTerminal "Write-Output '$outputSelection'"
|
||||
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$savedClipboard = Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
|
||||
try {
|
||||
$nativeDraft = "Get-Item -LiteralPath '$leftDir'"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$nativeDraft)
|
||||
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]0,[IntPtr]4)
|
||||
$keys.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the full command line with a partial selection' {
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $nativeDraft
|
||||
}
|
||||
$webviewDraft = "Get-Item -LiteralPath '$rightDir'"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$webviewDraft)
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-copy'
|
||||
if($LASTEXITCODE){throw 'Could not send Ctrl+Insert through the terminal WebView.'}
|
||||
Wait-Until 'Ctrl+Insert copying the command line with focus in the terminal WebView' {
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $webviewDraft
|
||||
}
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-select-output'
|
||||
if($LASTEXITCODE){throw 'Could not select the terminal output fixture.'}
|
||||
Wait-Until 'focus returned to the command line after selecting terminal output' {
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
foreach($key in '^c','^{INSERT}') {
|
||||
# Require a new clipboard write without making the test process the clipboard owner.
|
||||
$beforeCopy = [FilesActivationUi]::GetClipboardSequenceNumber()
|
||||
$keys.SendKeys($key)
|
||||
Wait-Until "$key copying only the selected terminal output with a command present" {
|
||||
[FilesActivationUi]::GetClipboardSequenceNumber() -ne $beforeCopy -and
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $outputSelection
|
||||
}
|
||||
if ((Read-Text $inputBox) -cne $webviewDraft) { throw 'Copying output changed the command line.' }
|
||||
}
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
|
||||
$keys.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the selected folder name when the command line is empty' {
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq 'Test folder'
|
||||
}
|
||||
} finally {
|
||||
Invoke-ClipboardOperation {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
}
|
||||
}
|
||||
}
|
||||
Write-Output 'Verified Ctrl+C and Ctrl+Insert copy the selected output, then fall back to the command line or panel.'
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
|
||||
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
|
||||
Wait-Until 'Enter from the terminal opening the selected folder in the pane' {
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -eq "$leftDir\Test folder"
|
||||
}
|
||||
Write-Output 'Verified Enter from the terminal opens the selected folder with an empty command line.'
|
||||
return
|
||||
}
|
||||
|
||||
@@ -240,6 +572,20 @@ try {
|
||||
}
|
||||
if ((Read-Text $inputBox) -cne 'draft command') { throw 'Pane navigation changed the command line.' }
|
||||
$shell = New-Object -ComObject WScript.Shell
|
||||
Wait-Until 'Files activation for Ctrl+F' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
foreach ($case in @(
|
||||
@{ Row = '..'; Path = $rightDir },
|
||||
@{ Row = '[Test folder]'; Path = (Join-Path $rightDir 'Test folder') }
|
||||
)) {
|
||||
Select-Row $right $case.Row
|
||||
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
|
||||
[void][FilesActivationUi]::Send($inputBox, 0xB1, [IntPtr]6, [IntPtr]13)
|
||||
$shell.SendKeys('^f')
|
||||
$path = if ($case.Path.Contains(' ')) { '"{0}"' -f $case.Path } else { $case.Path }
|
||||
Wait-Until "Ctrl+F inserting the path for $($case.Row)" { (Read-Text $inputBox) -ceq "draft $path" }
|
||||
}
|
||||
$fileName = [IO.Path]::GetFileName($document)
|
||||
foreach ($name in $fileName, 'Test folder') {
|
||||
$label = if ($name -eq $fileName) { $name } else { "[$name]" }
|
||||
@@ -321,7 +667,7 @@ try {
|
||||
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
|
||||
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$savedClipboard=[Windows.Forms.Clipboard]::GetDataObject()
|
||||
$savedClipboard=Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
|
||||
$programName=[IO.Path]::GetFileName($program)
|
||||
$expectedNames="Test folder`r`n$programName"
|
||||
try {
|
||||
@@ -334,18 +680,20 @@ try {
|
||||
}
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $expectedNames
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $expectedNames
|
||||
}
|
||||
Select-Row $right $fileName
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $fileName
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $fileName
|
||||
}
|
||||
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
|
||||
} finally {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
Invoke-ClipboardOperation {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,17 +712,24 @@ try {
|
||||
Select-Row $right "[$name]"
|
||||
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
}
|
||||
Select-Row $right '[Size C]'
|
||||
Select-Row $right $fileName
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
Wait-Until 'completion of the marked size batch' { (Read-Text $status) -ceq 'Size C Folder' }
|
||||
Select-Row $right '[Size B]'
|
||||
Wait-Until 'F3 size for a marked folder' { (Read-Text $status) -ceq 'Size B 23 B' }
|
||||
Wait-Until 'F3 on a file measuring a marked folder' { (Read-Text $status) -ceq 'Size B 23 B' }
|
||||
Select-Row $right '[Size C]'
|
||||
if ((Read-Text $status) -cne 'Size C Folder') { throw 'F3 measured the unmarked cursor folder.' }
|
||||
Select-Row $right '..'
|
||||
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
Select-Row $right '[Size C]'
|
||||
Wait-Until 'F3 on the parent row measuring all folders' { (Read-Text $status) -ceq 'Size C 31 B' }
|
||||
foreach($name in 'Size A','Size B'){
|
||||
Select-Row $right "[$name]"
|
||||
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
}
|
||||
Select-Row $right $fileName
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
$viewerTitle='Viewer '+[char]0x2014+" $document"
|
||||
Wait-Until 'F3 opening a file when folders are marked' {
|
||||
Wait-Until 'F3 opening a file with no marked folders' {
|
||||
[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle) -ne [IntPtr]::Zero
|
||||
}
|
||||
$viewer=[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle)
|
||||
@@ -392,7 +747,198 @@ try {
|
||||
(Find-Row $right '[Size B]')
|
||||
}
|
||||
Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.'
|
||||
|
||||
$operationName = 'Background operation.txt'
|
||||
$leftOperation = Join-Path $leftDir 'Operations'
|
||||
$rightOperation = Join-Path $rightDir 'Operations'
|
||||
New-Item -ItemType Directory -Path $leftOperation, $rightOperation | Out-Null
|
||||
$operationSource = Join-Path $leftOperation $operationName
|
||||
$operationTarget = Join-Path $rightOperation $operationName
|
||||
Invoke-Row $left '[Operations]' $false
|
||||
Invoke-Row $right '[Operations]' $false
|
||||
Wait-Until 'operation folders loaded in both panes' {
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 142))) -eq $leftOperation -and
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 143))) -eq $rightOperation
|
||||
}
|
||||
[IO.File]::WriteAllText($operationSource, 'source contents')
|
||||
[IO.File]::WriteAllText($operationTarget, 'original target')
|
||||
Select-Row $left $operationName
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x74, [IntPtr]::Zero)
|
||||
Answer-OperationDialog 211 1
|
||||
Answer-OperationDialog 230 6
|
||||
Wait-Until 'copy after overwrite confirmation' {
|
||||
(Read-Text $status) -ceq 'Copy complete.' -and
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
if ([IO.File]::ReadAllText($operationTarget) -cne 'source contents') {
|
||||
throw 'Copy did not replace the target contents.'
|
||||
}
|
||||
[IO.File]::Delete($operationTarget)
|
||||
Select-Row $left $operationName
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero)
|
||||
Wait-Until 'move destination field' { (Find-OperationDialog $window 211) -ne [IntPtr]::Zero }
|
||||
$moveDialog = Find-OperationDialog $window 211
|
||||
$destinationField = [FilesActivationUi]::GetDlgItem($moveDialog, 211)
|
||||
$validDestination = Read-Text $destinationField
|
||||
$missingDestination = Join-Path $rightOperation 'missing\destination.txt'
|
||||
[void][FilesActivationUi]::Write($destinationField, 0x0C, [IntPtr]::Zero, $missingDestination)
|
||||
Answer-OperationDialog 211 1
|
||||
Answer-OperationDialog 100 1
|
||||
Wait-Until 'focus returns to the move destination after asynchronous validation' {
|
||||
[FilesActivationUi]::Focus($window) -eq $destinationField
|
||||
}
|
||||
if (!(Test-Path -LiteralPath $operationSource)) { throw 'Invalid destination started the move.' }
|
||||
[void][FilesActivationUi]::Write($destinationField, 0x0C, [IntPtr]::Zero, $validDestination)
|
||||
$lockReady = Join-Path $root 'lock.ready'
|
||||
$locker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $operationSource,$lockReady) -WindowStyle Hidden -PassThru
|
||||
try {
|
||||
Wait-Until 'file locked by the fixture process' { Test-Path -LiteralPath $lockReady }
|
||||
Answer-OperationDialog 211 1
|
||||
Wait-Until 'red modal error for a locked file' {
|
||||
$errorDialog = Find-OperationDialog $window 100
|
||||
$errorDialog -ne [IntPtr]::Zero -and [FilesActivationUi]::HasWarningBackground($errorDialog)
|
||||
}
|
||||
$errorDialog = Find-OperationDialog $window 100
|
||||
$reason = Read-Text ([FilesActivationUi]::GetDlgItem($errorDialog, 100))
|
||||
if (!$reason -or (Read-Text $status).Contains($reason)) {
|
||||
throw 'The move failure reason must appear in the modal dialog.'
|
||||
}
|
||||
Answer-OperationDialog 100 103
|
||||
Wait-Until 'the locker appears with its PID' {
|
||||
$dialog = Find-OperationDialog $window 431
|
||||
if ($dialog -eq [IntPtr]::Zero) { return $false }
|
||||
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
|
||||
(Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $locker.Id)) -ge 0
|
||||
}
|
||||
$dialog = Find-OperationDialog $window 431
|
||||
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
|
||||
$row = Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $locker.Id)
|
||||
[void][FilesActivationUi]::Send($list, 0x186, [IntPtr]$row, [IntPtr]::Zero)
|
||||
Answer-OperationDialog 431 433
|
||||
Answer-OperationDialog 100 7
|
||||
Wait-Until 'End process confirmation closes after No' {
|
||||
(Find-OperationDialog $window 100) -eq [IntPtr]::Zero
|
||||
}
|
||||
if ($locker.HasExited) { throw 'Declining the confirmation ended the process.' }
|
||||
Answer-OperationDialog 431 433
|
||||
Answer-OperationDialog 100 6
|
||||
if (!$locker.WaitForExit(5000)) { throw 'Confirming End process did not terminate the locker.' }
|
||||
Wait-Until 'the process list refreshes after termination' {
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($dialog, 430))) -like 'No locking processes found*'
|
||||
}
|
||||
Answer-OperationDialog 431 1
|
||||
} finally {
|
||||
if (!$locker.HasExited) { $locker.Kill(); $locker.WaitForExit() }
|
||||
$locker.Dispose()
|
||||
}
|
||||
Select-Row $left $operationName
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero)
|
||||
Answer-OperationDialog 211 1
|
||||
Wait-Until 'move and asynchronous pane refresh' {
|
||||
!(Test-Path -LiteralPath $operationSource) -and
|
||||
(Find-Row $left $operationName) -eq -1 -and (Find-Row $right $operationName) -ge 0
|
||||
}
|
||||
Select-Row $right $operationName
|
||||
Wait-Until 'Files activation for Shift+Delete' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$shell.SendKeys('+{DELETE}')
|
||||
Answer-OperationDialog 240 6
|
||||
Wait-Until 'permanent deletion and asynchronous pane refresh' {
|
||||
!(Test-Path -LiteralPath $operationTarget) -and (Find-Row $right $operationName) -eq -1 -and
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
Write-Output 'Copy overwrite, move and permanent deletion completed through their Files dialogs.'
|
||||
|
||||
$lockedFolder = Join-Path $leftOperation 'Locked folder'
|
||||
[IO.Directory]::CreateDirectory($lockedFolder) | Out-Null
|
||||
$folderReady = Join-Path $root 'folder-lock.ready'
|
||||
$folderLocker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $lockedFolder,$folderReady) -WindowStyle Hidden -PassThru
|
||||
try {
|
||||
Wait-Until 'folder locked by the fixture process' { Test-Path -LiteralPath $folderReady }
|
||||
Select-Row $left '[Locked folder]'
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero)
|
||||
Answer-OperationDialog 211 1
|
||||
Answer-OperationDialog 100 103
|
||||
Wait-Until 'the folder locker appears with its PID' {
|
||||
$dialog = Find-OperationDialog $window 431
|
||||
if ($dialog -eq [IntPtr]::Zero) { return $false }
|
||||
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
|
||||
(Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $folderLocker.Id)) -ge 0
|
||||
}
|
||||
Answer-OperationDialog 431 1
|
||||
} finally {
|
||||
if (!$folderLocker.HasExited) { $folderLocker.Kill(); $folderLocker.WaitForExit() }
|
||||
$folderLocker.Dispose()
|
||||
}
|
||||
Write-Output 'The blocking-process dialog identified both a file lock and a folder lock by PID.'
|
||||
|
||||
foreach ($useRecycleBin in $false, $true) {
|
||||
$name = if ($useRecycleBin) { 'Held for Recycle Bin' } else { 'Held for permanent deletion.txt' }
|
||||
$target = Join-Path $leftOperation $name
|
||||
if ($useRecycleBin) { [IO.Directory]::CreateDirectory($target) | Out-Null }
|
||||
else { [IO.File]::WriteAllText($target, 'fixture') }
|
||||
$label = if ($useRecycleBin) { "[$name]" } else { $name }
|
||||
$ready = Join-Path $root "delete-lock-$useRecycleBin.ready"
|
||||
$deleteLocker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $target,$ready) -WindowStyle Hidden -PassThru
|
||||
try {
|
||||
Wait-Until 'deletion target held by the fixture' { Test-Path -LiteralPath $ready }
|
||||
Select-Row $left $label
|
||||
if ($useRecycleBin) {
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x77, [IntPtr]::Zero)
|
||||
} else {
|
||||
Wait-Until 'Files activation for blocked Shift+Delete' { [FilesActivationUi]::Activate($window) }
|
||||
$shell.SendKeys('+{DELETE}')
|
||||
}
|
||||
Answer-OperationDialog 240 6
|
||||
Wait-Until 'red failure dialog for blocked deletion' {
|
||||
$dialog = Find-OperationDialog $window 100
|
||||
$dialog -ne [IntPtr]::Zero -and [FilesActivationUi]::HasWarningBackground($dialog)
|
||||
}
|
||||
Answer-OperationDialog 100 103
|
||||
$processLabel = 'KSwitcherFilesActivationFixture.exe (PID {0})' -f $deleteLocker.Id
|
||||
Wait-Until 'deletion blocker appears in the process list' {
|
||||
$dialog = Find-OperationDialog $window 431
|
||||
$dialog -ne [IntPtr]::Zero -and
|
||||
(Find-Row ([FilesActivationUi]::GetDlgItem($dialog, 431)) $processLabel) -ge 0
|
||||
}
|
||||
$dialog = Find-OperationDialog $window 431
|
||||
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
|
||||
[void][FilesActivationUi]::Send($list, 0x186, [IntPtr](Find-Row $list $processLabel), [IntPtr]::Zero)
|
||||
Answer-OperationDialog 431 433
|
||||
Answer-OperationDialog 100 6
|
||||
if (!$deleteLocker.WaitForExit(5000)) { throw 'End process did not release the deletion target.' }
|
||||
Wait-Until 'deletion blocker list refreshes' {
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($dialog, 430))) -like 'No locking processes found*'
|
||||
}
|
||||
Answer-OperationDialog 431 1
|
||||
Wait-Until 'Files regains focus after closing the process list' {
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
} finally {
|
||||
if (!$deleteLocker.HasExited) { $deleteLocker.Kill(); $deleteLocker.WaitForExit() }
|
||||
$deleteLocker.Dispose()
|
||||
}
|
||||
Select-Row $left $label
|
||||
Wait-Until 'Files activation for deletion retry' { [FilesActivationUi]::Activate($window) }
|
||||
$shell.SendKeys('+{DELETE}')
|
||||
Answer-OperationDialog 240 6
|
||||
Wait-Until 'deletion succeeds after ending the blocker' {
|
||||
!(Test-Path -LiteralPath $target) -and (Find-Row $left $label) -eq -1
|
||||
}
|
||||
}
|
||||
Write-Output 'Blocked permanent file deletion and folder recycling opened the shared process dialog and released their blockers.'
|
||||
} catch {
|
||||
if ($inputBox -and $status) {
|
||||
Write-Output "Command input length: $((Read-Text $inputBox).Length). Status: $(Read-Text $status)"
|
||||
}
|
||||
if ($trace -and (Test-Path -LiteralPath $trace)) {
|
||||
Get-Content -LiteralPath $trace -Tail 25
|
||||
}
|
||||
throw
|
||||
} finally {
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=$webviewFlags
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER=$webviewProfile
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
if (!$process.WaitForExit(4000)) { $process.Kill(); $process.WaitForExit() }
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string_view>
|
||||
|
||||
int wmain(int argc,wchar_t **argv)
|
||||
{
|
||||
if(argc==4 && std::wstring_view(argv[1])==L"--hold")
|
||||
{
|
||||
const auto handle=CreateFileW(argv[2],GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,nullptr,
|
||||
OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,nullptr);
|
||||
if(handle==INVALID_HANDLE_VALUE) return 1;
|
||||
const auto ready=CreateFileW(argv[3],GENERIC_WRITE,FILE_SHARE_READ,nullptr,CREATE_ALWAYS,0,nullptr);
|
||||
if(ready==INVALID_HANDLE_VALUE){CloseHandle(handle);return 1;}
|
||||
CloseHandle(ready);
|
||||
Sleep(INFINITE);
|
||||
CloseHandle(handle);
|
||||
return 0;
|
||||
}
|
||||
// A launch through the embedded terminal would inherit its console.
|
||||
DWORD consoleProcesses[1]{};
|
||||
if(GetConsoleProcessList(consoleProcesses,1)>1) return 1;
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Executable,
|
||||
[string]$Screenshot
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @"
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class CompletionTest {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string name, string title);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, IntPtr process);
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern bool AttachThreadInput(uint first, uint second, bool attach);
|
||||
[DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
|
||||
public static void Activate(IntPtr window) {
|
||||
var own = GetCurrentThreadId();
|
||||
var foreground = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
|
||||
bool attached = foreground != 0 && own != foreground && AttachThreadInput(own, foreground, true);
|
||||
try { SetForegroundWindow(window); }
|
||||
finally { if (attached) AttachThreadInput(own, foreground, false); }
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect bounds);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint relation);
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Point { public int X, Y; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(Point point);
|
||||
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, int message, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, int message, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SetText(IntPtr window, int message, IntPtr w, string text);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr GetText(IntPtr window, int message, IntPtr w, StringBuilder text);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr ItemRect(IntPtr window, int message, IntPtr w, out Rect bounds);
|
||||
}
|
||||
"@
|
||||
|
||||
function Wait-Until([string]$Description, [scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 120; ++$attempt) {
|
||||
if (& $Condition) { return }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
throw "Timed out waiting for $Description"
|
||||
}
|
||||
|
||||
function Set-Line([string]$Line) {
|
||||
[void][CompletionTest]::SetText($edit, 0x000C, 0, $Line)
|
||||
[void][CompletionTest]::Send($edit, 0x00B1, $Line.Length, $Line.Length)
|
||||
}
|
||||
|
||||
function Read-Line {
|
||||
$text = [Text.StringBuilder]::new(2049)
|
||||
[void][CompletionTest]::GetText($edit, 0x000D, $text.Capacity, $text)
|
||||
$text.ToString()
|
||||
}
|
||||
|
||||
function Suggestions([string]$Expected, [int]$Count = -1) {
|
||||
Wait-Until "suggestion '$Expected' (count $Count)" {
|
||||
if (![CompletionTest]::IsWindowVisible($list)) { return $false }
|
||||
$found = [CompletionTest]::SetText($list, 0x01A2, -1, $Expected).ToInt64()
|
||||
$size = [CompletionTest]::Send($list, 0x018B, 0, 0).ToInt64()
|
||||
$found -ge 0 -and ($Count -lt 0 -or $size -eq $Count)
|
||||
}
|
||||
}
|
||||
|
||||
function Press-Key([int]$Key) {
|
||||
if (![CompletionTest]::PostMessage($edit, 0x0100, $Key, 1)) { throw 'Could not post key' }
|
||||
}
|
||||
|
||||
function Toggle-Panels {
|
||||
Wait-Until 'foreground Files window before toggling panes' {
|
||||
if ([CompletionTest]::GetForegroundWindow() -eq $window) { return $true }
|
||||
[void]$keyboard.AppActivate($process.Id)
|
||||
[CompletionTest]::Activate($window)
|
||||
[CompletionTest]::GetForegroundWindow() -eq $window
|
||||
}
|
||||
$keyboard.SendKeys('^o')
|
||||
}
|
||||
|
||||
function Read-SuggestionFrameColor {
|
||||
$frame = [CompletionTest]::GetWindow($list, 2)
|
||||
$bounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($frame, [ref]$bounds)
|
||||
$pixel = [Drawing.Bitmap]::new(1, 1)
|
||||
$graphics = [Drawing.Graphics]::FromImage($pixel)
|
||||
try {
|
||||
$graphics.CopyFromScreen($bounds.Left + 2, $bounds.Top + 2, 0, 0, $pixel.Size)
|
||||
$pixel.GetPixel(0, 0).ToArgb()
|
||||
} finally {
|
||||
$graphics.Dispose()
|
||||
$pixel.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function Test-DotnetCompletion {
|
||||
if (!$hasDotnetSdk) { return }
|
||||
Set-Line 'dotnet '
|
||||
Suggestions 'build'
|
||||
Set-Line 'dotnet bu'
|
||||
Suggestions 'build'
|
||||
Set-Line 'dotnet build --no-res'
|
||||
Suggestions '--no-restore'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, '--no-restore')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'dotnet option insertion' { (Read-Line) -ceq 'dotnet build --no-restore' }
|
||||
}
|
||||
|
||||
function Test-GitCompletion {
|
||||
if (!$gitFixture) { return }
|
||||
Set-Line 'git ch'
|
||||
Suggestions 'checkout'
|
||||
Set-Line 'git --ver'
|
||||
Suggestions '--version'
|
||||
$switch = 'git -C "' + $gitFixture + '" switch '
|
||||
Set-Line ($switch + '--de')
|
||||
Suggestions '--detach'
|
||||
$prefix = $switch + 'comp'
|
||||
Set-Line $prefix
|
||||
Suggestions 'completion-one'
|
||||
Suggestions 'completion-two'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'completion-one')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'Git branch insertion' { (Read-Line) -ceq ($prefix + 'letion-one') }
|
||||
}
|
||||
|
||||
function Test-WindowsCommandCompletion {
|
||||
Set-Line 'ipconfig '
|
||||
Suggestions '/all'
|
||||
Set-Line 'ipconfig /re'
|
||||
Suggestions '/renew'
|
||||
Suggestions '/release'
|
||||
Set-Line 'ipconfig ?'
|
||||
Suggestions '/?'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, '/?')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'ipconfig help switch insertion' { (Read-Line) -ceq 'ipconfig /?' }
|
||||
|
||||
Set-Line 'tasklist.exe /f'
|
||||
Suggestions '/fo'
|
||||
Set-Line 'robocopy /mi'
|
||||
Suggestions '/mir'
|
||||
Set-Line 'reg q'
|
||||
Suggestions 'query'
|
||||
Set-Line 'reg query /r'
|
||||
Suggestions '/reg:64'
|
||||
Set-Line 'cmd /c dir /'
|
||||
Suggestions '/w'
|
||||
Set-Line 'dir -Fi'
|
||||
Suggestions 'File'
|
||||
}
|
||||
|
||||
function Test-NestedWindowsCommandCompletion {
|
||||
Set-Line 'netsh interface ip'
|
||||
Suggestions 'ipv4'
|
||||
Set-Line 'netsh interface ipv4 sh'
|
||||
Suggestions 'show'
|
||||
Set-Line 'netsh interface ipv4 show co'
|
||||
Suggestions 'config'
|
||||
Set-Line 'netsh interface ipv4 show config na'
|
||||
Suggestions 'name='
|
||||
Set-Line 'fsutil file queryallocranges of'
|
||||
Suggestions 'offset='
|
||||
Set-Line 'wevtutil query-events /sb'
|
||||
Suggestions '/sbm:'
|
||||
Set-Line 'schtasks /query /fo L'
|
||||
Suggestions 'LIST'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'LIST')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'nested Windows option insertion' { (Read-Line) -ceq 'schtasks /query /fo LIST' }
|
||||
}
|
||||
|
||||
function Test-IpconfigAdapterCompletion {
|
||||
$adapters = foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
|
||||
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
|
||||
try {
|
||||
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
|
||||
} catch {}
|
||||
}
|
||||
if (!$adapters) { return }
|
||||
$name = $adapters | Where-Object { $_ -match '^[\p{L}\p{N}-]+ [\p{L}\p{N} ]+$' } | Select-Object -First 1
|
||||
if ($name) {
|
||||
$prefix = '"' + $name.Substring(0, $name.IndexOf(' ') + 1)
|
||||
$expected = "'" + $name + "'"
|
||||
} else {
|
||||
$name = $adapters | Where-Object { $_ -match '^[\p{L}\p{N}-]+$' } | Select-Object -First 1
|
||||
if (!$name) { return }
|
||||
$prefix = $name.Substring(0, 1).ToUpperInvariant()
|
||||
$expected = $name
|
||||
}
|
||||
Set-Line 'ipconfig /renew '
|
||||
Suggestions $name
|
||||
Set-Line ('ipconfig.exe /release ' + $prefix)
|
||||
Suggestions $name
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, $name)
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'ipconfig adapter insertion' { (Read-Line) -ceq ('ipconfig.exe /release ' + $expected) }
|
||||
}
|
||||
|
||||
function Test-PathCompletion {
|
||||
$prefix = 'cd "' + $root + '\Al'
|
||||
Set-Line $prefix
|
||||
Suggestions 'Alpine' 2
|
||||
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'p', 1)
|
||||
Suggestions 'Alpha Space' 2
|
||||
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'h', 1)
|
||||
Suggestions 'Alpha Space' 1
|
||||
|
||||
$row = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::ItemRect($list, 0x0198, 0, [ref]$row)
|
||||
$listBounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($list, [ref]$listBounds)
|
||||
$mouse = [CompletionTest+Point]::new()
|
||||
$mouse.X = $listBounds.Left + 5
|
||||
$mouse.Y = $listBounds.Top + (($row.Top + $row.Bottom) -shr 1)
|
||||
if ([CompletionTest]::WindowFromPoint($mouse) -ne $list) { throw 'The suggestions list is covered' }
|
||||
$point = ((($row.Top + $row.Bottom) -shr 1) -shl 16) -bor 5
|
||||
[void][CompletionTest]::PostMessage($list, 0x0201, 1, $point)
|
||||
Wait-Until 'click insertion with quotes' { (Read-Line) -ceq ('cd "' + $root + '\Alpha Space"') }
|
||||
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'\', 1)
|
||||
Suggestions 'Nested' 1
|
||||
|
||||
Press-Key 0x1B
|
||||
Wait-Until 'Escape dismissal' { ![CompletionTest]::IsWindowVisible($list) }
|
||||
if ((Read-Line) -cne ('cd "' + $root + '\Alpha Space\"')) { throw 'Escape changed the command line' }
|
||||
}
|
||||
|
||||
$root = Join-Path ([IO.Path]::GetTempPath()) ("KSwitcherCompletion-" + [guid]::NewGuid().ToString('N'))
|
||||
$process = $null
|
||||
$dotnet = Get-Command dotnet.exe -CommandType Application -ErrorAction SilentlyContinue
|
||||
$hasDotnetSdk = $dotnet -and [bool](& $dotnet.Source --list-sdks)
|
||||
$historyKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$historyPrefix = "Write-Output 'completion-$([guid]::NewGuid().ToString('N'))"
|
||||
$latest = "$historyPrefix-alpha-recent'"
|
||||
$earlier = "$historyPrefix-alpha-earlier'"
|
||||
$other = "$historyPrefix-beta'"
|
||||
$combined = "Get-ChildItem -Name # $([guid]::NewGuid().ToString('N'))"
|
||||
$clearPrefix = ' cls '
|
||||
$clearHistory = "$clearPrefix# $([guid]::NewGuid().ToString('N'))"
|
||||
$fixture = "2026-01-01`0$earlier`02026-01-01`0$other`02026-01-01`0$earlier`02026-01-01`0$latest`02026-01-01`0$combined`02026-01-01`0$clearHistory`0"
|
||||
|
||||
function Remove-HistoryFixture {
|
||||
$bytes = $historyKey.GetValue('CommandHistory')
|
||||
if ($bytes -isnot [byte[]]) { return }
|
||||
$current = [Text.Encoding]::Unicode.GetString($bytes)
|
||||
$clean = $current.Replace($fixture, '')
|
||||
if ($clean -ceq $current) { return }
|
||||
if ($clean.Length -eq 0 -and $null -eq $originalHistory) {
|
||||
$historyKey.DeleteValue('CommandHistory', $false)
|
||||
} else {
|
||||
$historyKey.SetValue('CommandHistory', [Text.Encoding]::Unicode.GetBytes($clean), 'Binary')
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$originalHistory = $historyKey.GetValue('CommandHistory')
|
||||
$history = if ($null -ne $originalHistory) { [Text.Encoding]::Unicode.GetString($originalHistory) } else { '' }
|
||||
$historyKey.SetValue('CommandHistory', [Text.Encoding]::Unicode.GetBytes($history + $fixture), 'Binary')
|
||||
[void](New-Item -ItemType Directory -Path "$root\Alpha Space\Nested", "$root\Alpine")
|
||||
$gitFixture = $null
|
||||
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($git) {
|
||||
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source))
|
||||
for ($level = 0; $location -and $level -lt 3; ++$level) {
|
||||
$installation = $location.FullName
|
||||
$location = $location.Parent
|
||||
if (!(Test-Path -LiteralPath (Join-Path $installation 'usr/bin/bash.exe'))) { continue }
|
||||
$gitFixture = Join-Path $root 'Git Repo'
|
||||
[void](New-Item -ItemType Directory -Path $gitFixture)
|
||||
& $git.Source -C $gitFixture init --quiet --template= --initial-branch=main
|
||||
if ($LASTEXITCODE) { throw 'Could not initialize the Git fixture' }
|
||||
& $git.Source -C $gitFixture -c user.name=Test -c user.email=test@example.invalid -c commit.gpgSign=false -c core.hooksPath=NUL commit --quiet --allow-empty -m fixture
|
||||
if ($LASTEXITCODE) { throw 'Could not create the Git fixture commit' }
|
||||
& $git.Source -C $gitFixture branch completion-one
|
||||
if ($LASTEXITCODE) { throw 'Could not create Git fixture branch completion-one' }
|
||||
& $git.Source -C $gitFixture branch completion-two
|
||||
if ($LASTEXITCODE) { throw 'Could not create Git fixture branch completion-two' }
|
||||
break
|
||||
}
|
||||
}
|
||||
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru -WindowStyle Normal
|
||||
Wait-Until 'Files window' {
|
||||
$process.Refresh()
|
||||
$process.MainWindowHandle -ne [IntPtr]::Zero
|
||||
}
|
||||
Remove-HistoryFixture
|
||||
$window = $process.MainWindowHandle
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
Wait-Until 'foreground Files window' {
|
||||
[void]$keyboard.AppActivate($process.Id)
|
||||
[CompletionTest]::Activate($window)
|
||||
[CompletionTest]::GetForegroundWindow() -eq $window
|
||||
}
|
||||
$edit = [CompletionTest]::FindWindowEx($window, 0, 'Edit', [System.Management.Automation.Language.NullString]::Value)
|
||||
$list = [CompletionTest]::GetDlgItem($window, 149)
|
||||
if (!$edit -or !$list) { throw 'Missing command line or suggestions list' }
|
||||
|
||||
[void][CompletionTest]::SetThreadDpiAwarenessContext(-4)
|
||||
$status = [CompletionTest]::GetDlgItem($window, 144)
|
||||
$panel = [CompletionTest]::GetDlgItem($window, 102)
|
||||
$statusBounds = [CompletionTest+Rect]::new()
|
||||
$panelBounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($panel, [ref]$panelBounds)
|
||||
[void][CompletionTest]::GetWindowRect($status, [ref]$statusBounds)
|
||||
if ($statusBounds.Left -ge $panelBounds.Right) {
|
||||
Press-Key 0x09
|
||||
Wait-Until 'left panel active' {
|
||||
$bounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($status, [ref]$bounds)
|
||||
$bounds.Left -lt $panelBounds.Right
|
||||
}
|
||||
[void][CompletionTest]::GetWindowRect($status, [ref]$statusBounds)
|
||||
}
|
||||
|
||||
Set-Line $clearPrefix
|
||||
Suggestions $clearHistory 1
|
||||
|
||||
Set-Line 'Get-Chi'
|
||||
Suggestions 'Get-ChildItem'
|
||||
Suggestions $combined
|
||||
|
||||
$frame = [CompletionTest]::GetWindow($list, 2)
|
||||
$frameBounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($frame, [ref]$frameBounds)
|
||||
$x = [Math]::Max($statusBounds.Left, $frameBounds.Left)
|
||||
$y = [Math]::Max($statusBounds.Top, $frameBounds.Top)
|
||||
$w = [Math]::Min($statusBounds.Right, $frameBounds.Right) - $x
|
||||
$h = [Math]::Min($statusBounds.Bottom, $frameBounds.Bottom) - $y
|
||||
if ($w -le 0 -or $h -le 0) { throw 'Suggestions and status must overlap for the repaint check' }
|
||||
$before = [Drawing.Bitmap]::new($w, $h)
|
||||
$after = [Drawing.Bitmap]::new($w, $h)
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($before)
|
||||
try { $graphics.CopyFromScreen($x, $y, 0, 0, $before.Size) } finally { $graphics.Dispose() }
|
||||
[void][CompletionTest]::SetText($status, 0x000C, 0, ('Status repaint test ' * 48))
|
||||
[void][CompletionTest]::RedrawWindow($status, 0, 0, 0x0105)
|
||||
$graphics = [Drawing.Graphics]::FromImage($after)
|
||||
try { $graphics.CopyFromScreen($x, $y, 0, 0, $after.Size) } finally { $graphics.Dispose() }
|
||||
for ($rowPixel = 0; $rowPixel -lt $h; ++$rowPixel) {
|
||||
for ($columnPixel = 0; $columnPixel -lt $w; ++$columnPixel) {
|
||||
if ($before.GetPixel($columnPixel, $rowPixel) -ne $after.GetPixel($columnPixel, $rowPixel)) {
|
||||
throw 'Status repaint drew over command suggestions'
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$before.Dispose()
|
||||
$after.Dispose()
|
||||
}
|
||||
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'Get-ChildItem')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x09
|
||||
Wait-Until 'Tab insertion' { (Read-Line) -ceq 'Get-ChildItem' }
|
||||
|
||||
Set-Line ($historyPrefix.ToUpperInvariant())
|
||||
Suggestions $latest 3
|
||||
Set-Line "$historyPrefix-alpha"
|
||||
Suggestions $earlier 2
|
||||
Press-Key 0x09
|
||||
Wait-Until 'most recent history insertion' { (Read-Line) -ceq $latest }
|
||||
|
||||
Set-Line 'Get-ChildItem -Pa'
|
||||
Suggestions 'Path'
|
||||
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'Path')
|
||||
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'Enter insertion' { (Read-Line) -ceq 'Get-ChildItem -Path' }
|
||||
|
||||
Test-PathCompletion
|
||||
Test-DotnetCompletion
|
||||
Test-GitCompletion
|
||||
Test-WindowsCommandCompletion
|
||||
Test-NestedWindowsCommandCompletion
|
||||
Test-IpconfigAdapterCompletion
|
||||
|
||||
# Toggle with a populated list and verify the same draft and suggestions remain accessible.
|
||||
Set-Line "$historyPrefix-alpha"
|
||||
Suggestions $latest 2
|
||||
$frameColor = Read-SuggestionFrameColor
|
||||
$output = [CompletionTest]::GetDlgItem($window, 145)
|
||||
Toggle-Panels
|
||||
Wait-Until 'terminal-only view' {
|
||||
[CompletionTest]::IsWindowVisible($output) -and ![CompletionTest]::IsWindowVisible($panel) -and
|
||||
[CompletionTest]::GetWindow($output, 5) -ne [IntPtr]::Zero
|
||||
}
|
||||
Suggestions $latest 2
|
||||
# Let WebView2 finish its first compositor update after showing the terminal.
|
||||
Start-Sleep -Milliseconds 350
|
||||
if ((Read-SuggestionFrameColor) -ne $frameColor) {
|
||||
throw 'Terminal output drew over command suggestions with panels hidden'
|
||||
}
|
||||
if ($Screenshot) {
|
||||
[void][CompletionTest]::SetThreadDpiAwarenessContext(-4)
|
||||
$bounds = [CompletionTest+Rect]::new()
|
||||
[void][CompletionTest]::GetWindowRect($window, [ref]$bounds)
|
||||
$bitmap = [Drawing.Bitmap]::new($bounds.Right - $bounds.Left, $bounds.Bottom - $bounds.Top)
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
$graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bitmap.Size)
|
||||
$bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png)
|
||||
} finally {
|
||||
$graphics.Dispose()
|
||||
$bitmap.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
Press-Key 0x28
|
||||
Press-Key 0x0D
|
||||
Wait-Until 'history insertion with panels hidden' { (Read-Line) -ceq $latest }
|
||||
Test-PathCompletion
|
||||
Test-DotnetCompletion
|
||||
Test-GitCompletion
|
||||
Test-WindowsCommandCompletion
|
||||
Test-NestedWindowsCommandCompletion
|
||||
Test-IpconfigAdapterCompletion
|
||||
|
||||
Toggle-Panels
|
||||
Wait-Until 'panels restored' { [CompletionTest]::IsWindowVisible($panel) }
|
||||
Set-Line "$historyPrefix-alpha"
|
||||
Suggestions $latest 2
|
||||
'Command completion passed with panels visible and hidden'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id }
|
||||
Remove-HistoryFixture
|
||||
$historyKey.Dispose()
|
||||
if ($gitFixture -and (Test-Path -LiteralPath $gitFixture)) {
|
||||
$resolved = (Resolve-Path -LiteralPath $gitFixture).ProviderPath
|
||||
if ($resolved -eq [IO.Path]::GetFullPath((Join-Path $root 'Git Repo'))) {
|
||||
Remove-Item -LiteralPath $resolved -Recurse -Force
|
||||
}
|
||||
}
|
||||
foreach ($path in "$root\Alpha Space\Nested", "$root\Alpha Space", "$root\Alpine", $root) {
|
||||
if (Test-Path -LiteralPath $path) { [IO.Directory]::Delete($path) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
param([Parameter(Mandatory)][string]$Executable)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class ComparisonSplitterUi {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Point { public int X, Y; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point);
|
||||
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
|
||||
[DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(18, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(18, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-For([string]$Name, [scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 50; ++$attempt) {
|
||||
$value = & $Condition
|
||||
if ($value) { return $value }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
throw "Timed out waiting for $Name."
|
||||
}
|
||||
|
||||
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance'
|
||||
$saved = @{}
|
||||
foreach ($name in $names) {
|
||||
if ($name -in $preferences.GetValueNames()) {
|
||||
$saved[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
|
||||
}
|
||||
}
|
||||
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
|
||||
$root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N'))
|
||||
$dpi = [ComparisonSplitterUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$process = $null
|
||||
try {
|
||||
$left = Join-Path $root 'left'
|
||||
$right = Join-Path $root 'right'
|
||||
[void][IO.Directory]::CreateDirectory($left)
|
||||
[void][IO.Directory]::CreateDirectory($right)
|
||||
[IO.File]::WriteAllText((Join-Path $left 'sample.txt'), "one`ntwo")
|
||||
[IO.File]::WriteAllText((Join-Path $right 'sample.txt'), "one`nthree")
|
||||
$preferences.SetValue('LeftPath', $left)
|
||||
$preferences.SetValue('RightPath', $right)
|
||||
foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance') {
|
||||
$preferences.DeleteValue($name, $false)
|
||||
}
|
||||
|
||||
$process = Start-Process -FilePath (Resolve-Path -LiteralPath $Executable) -PassThru
|
||||
$main = Wait-For 'the Files window' {
|
||||
$process.Refresh()
|
||||
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
|
||||
}
|
||||
foreach ($id in 102, 103) {
|
||||
$panel = [ComparisonSplitterUi]::GetDlgItem($main, $id)
|
||||
[void](Wait-For 'the test file in the panel' {
|
||||
[ComparisonSplitterUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2
|
||||
})
|
||||
[void][ComparisonSplitterUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
|
||||
}
|
||||
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr]132, [IntPtr]::Zero)
|
||||
$picker = [ComparisonSplitterUi]::GetDlgItem($main, 121)
|
||||
[void](Wait-For 'the Commands menu' { [ComparisonSplitterUi]::IsWindowVisible($picker) })
|
||||
$row = -1
|
||||
$count = [ComparisonSplitterUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
|
||||
for ($i = 0; $i -lt $count; ++$i) {
|
||||
$label = [Text.StringBuilder]::new(128)
|
||||
[void][ComparisonSplitterUi]::Read($picker, 393, [IntPtr]$i, $label)
|
||||
if ($label.ToString() -like 'Compare files*') { $row = $i; break }
|
||||
}
|
||||
if ($row -lt 0) { throw 'Missing Compare files command.' }
|
||||
[void][ComparisonSplitterUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero)
|
||||
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr](0x20000 + 121), $picker)
|
||||
$list = Wait-For 'the foreground comparison list' {
|
||||
$dialog = [IntPtr]::Zero
|
||||
while (($dialog = [ComparisonSplitterUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
|
||||
[uint32]$ownerPid = 0
|
||||
[void][ComparisonSplitterUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
|
||||
if ($ownerPid -ne $process.Id) { continue }
|
||||
$control = [ComparisonSplitterUi]::GetDlgItem($dialog, 402)
|
||||
if ([ComparisonSplitterUi]::IsWindowVisible($control) -and [ComparisonSplitterUi]::Activate($dialog)) {
|
||||
return $control
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$bounds = [ComparisonSplitterUi+Rect]::new()
|
||||
[void][ComparisonSplitterUi]::GetClientRect($list, [ref]$bounds)
|
||||
$middle = [int]($bounds.Right / 2)
|
||||
$destination = [int]($bounds.Right * 0.65)
|
||||
$mouseY = 30 -shl 16
|
||||
[void][ComparisonSplitterUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
|
||||
for ($x = $middle + 5; $x -lt $destination; $x += 5) {
|
||||
[void][ComparisonSplitterUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
|
||||
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
}
|
||||
[void][ComparisonSplitterUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
|
||||
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
$origin = [ComparisonSplitterUi+Point]::new()
|
||||
[void][ComparisonSplitterUi]::ClientToScreen($list, [ref]$origin)
|
||||
$bitmap = [Drawing.Bitmap]::new($bounds.Right, 1)
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try { $graphics.CopyFromScreen($origin.X, ($origin.Y + $bounds.Bottom - 10), 0, 0, $bitmap.Size) }
|
||||
finally { $graphics.Dispose() }
|
||||
$ink = @(for ($x = $middle - 4; $x -le $destination + 4; ++$x) {
|
||||
if ($bitmap.GetPixel($x, 0).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x }
|
||||
})
|
||||
# Desktop scaling can spread the single-pixel divider across two adjacent screen pixels.
|
||||
if (!$ink.Count -or $ink.Count -gt 2 -or [Math]::Abs($ink[0] - $destination) -gt 1 -or
|
||||
($ink.Count -eq 2 -and $ink[1] - $ink[0] -ne 1)) {
|
||||
throw "Expected one divider under the last row at $destination. Found $($ink.Count) marked pixels, starting at $($ink | Select-Object -First 8)."
|
||||
}
|
||||
} finally { $bitmap.Dispose() }
|
||||
'Verified that dragging leaves exactly one divider below the file contents.'
|
||||
} 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()
|
||||
if ($dpi) { [void][ComparisonSplitterUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
if (Test-Path -LiteralPath $root) {
|
||||
$resolved = (Resolve-Path -LiteralPath $root).Path
|
||||
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-files-splitter-*') {
|
||||
Remove-Item -LiteralPath $resolved -Recurse -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,28 @@
|
||||
param([string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe")
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe",
|
||||
[switch]$OfflineWake,
|
||||
[switch]$FtpProfiles,
|
||||
[string]$Screenshot
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class FilesDriveShortcutTest {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr SendMessage(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr SendRect(IntPtr window, uint msg, IntPtr w, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
}
|
||||
'@
|
||||
function Wait-Until([scriptblock]$Condition) {
|
||||
@@ -24,20 +37,160 @@ function Read-Text($Control, $Message = 13, $Parameter = 32768) {
|
||||
[void][FilesDriveShortcutTest]::SendMessage($Control, $Message, [IntPtr]$Parameter, $buffer)
|
||||
$buffer.ToString()
|
||||
}
|
||||
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
|
||||
$preferences = $null
|
||||
$savedPreferences = @{}
|
||||
$process = $null
|
||||
$previousDpi = [FilesDriveShortcutTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
try {
|
||||
if ($FtpProfiles) {
|
||||
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$preferenceNames = 'FtpProfiles', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
|
||||
foreach ($name in $preferenceNames) {
|
||||
if ($name -in $preferences.GetValueNames()) {
|
||||
$savedPreferences[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
|
||||
}
|
||||
}
|
||||
$profile = '[{"name":"Test FTP profile","host":"localhost","user":"","port":21,"secret":[]}]'
|
||||
$preferences.SetValue('FtpProfiles', [Text.Encoding]::UTF8.GetBytes($profile), 'Binary')
|
||||
foreach ($name in 'LeftWide', 'RightWide') { $preferences.SetValue($name, 1, 'DWord') }
|
||||
}
|
||||
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
|
||||
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
$window = $process.MainWindowHandle
|
||||
$picker = [FilesDriveShortcutTest]::GetDlgItem($window, 121)
|
||||
$path = [FilesDriveShortcutTest]::GetDlgItem($window, 142)
|
||||
function Open-Picker {
|
||||
[void][FilesDriveShortcutTest]::PostMessage($window, 260, [IntPtr]112, [IntPtr]::Zero)
|
||||
function Open-Picker([int]$Side = 0) {
|
||||
[void][FilesDriveShortcutTest]::PostMessage($window, 260, [IntPtr](112 + $Side), [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::IsWindowVisible($picker) }
|
||||
}
|
||||
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 {
|
||||
$client = [FilesDriveShortcutTest+Rect]::new()
|
||||
[void][FilesDriveShortcutTest]::GetClientRect($picker, [ref]$client)
|
||||
$bitmap = [Drawing.Bitmap]::new($client.Right, $client.Bottom)
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
$dc = $graphics.GetHdc()
|
||||
try {
|
||||
if (![FilesDriveShortcutTest]::PrintWindow($picker, $dc, 2)) { throw 'Could not render drive picker.' }
|
||||
} finally { $graphics.ReleaseHdc($dc) }
|
||||
return $bitmap
|
||||
} finally { $graphics.Dispose() }
|
||||
}
|
||||
function Press-Shortcut([char]$Key) {
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 258, [IntPtr][int]$Key, [IntPtr]::Zero)
|
||||
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
|
||||
}
|
||||
if ($FtpProfiles) {
|
||||
foreach ($side in 0, 1) {
|
||||
Open-Picker $side
|
||||
$rows = @(Read-Picker)
|
||||
$row = [Array]::IndexOf($rows, 'FTP')
|
||||
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'KSwitcher LAN') {
|
||||
throw "Source groups are missing separators in panel $side."
|
||||
}
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$row, $null)
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row - 2 }
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
|
||||
Wait-Until {
|
||||
$selected = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32()
|
||||
$selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 1)
|
||||
}
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 407, [IntPtr]($row - 2), $null)
|
||||
$bitmap = Render-Picker
|
||||
try {
|
||||
$divider = [FilesDriveShortcutTest+Rect]::new()
|
||||
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]($row - 1), [ref]$divider)
|
||||
$y = $divider.Top + [int][Math]::Floor(($divider.Bottom - $divider.Top) / 2)
|
||||
if ($y -le 0 -or $y -ge $bitmap.Height) { throw "Group divider is outside the rendered menu in panel $side (row $row, y $y, height $($bitmap.Height), top $([FilesDriveShortcutTest]::SendMessage($picker,398,[IntPtr]::Zero,$null)))." }
|
||||
$line = $bitmap.GetPixel(4, $y).ToArgb()
|
||||
if ($line -eq $bitmap.GetPixel(4, $y - 1).ToArgb() -or
|
||||
$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 }
|
||||
}
|
||||
}
|
||||
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'
|
||||
$panelPath = [FilesDriveShortcutTest]::GetDlgItem($window, 142 + $side)
|
||||
$list = [FilesDriveShortcutTest]::GetDlgItem($window, 102 + $side)
|
||||
Wait-Until { (Read-Text $panelPath) -ceq 'FTP' }
|
||||
if ((Read-Text $list 393 0) -cne 'Test FTP profile') { throw "Saved FTP profile missing from panel $side." }
|
||||
$graphics = [Drawing.Graphics]::FromHwnd($list)
|
||||
try {
|
||||
$dc = $graphics.GetHdc()
|
||||
try {
|
||||
if (![FilesDriveShortcutTest]::PrintWindow($list, $dc, 2)) { throw "FTP rows failed to render in panel $side." }
|
||||
} finally { $graphics.ReleaseHdc($dc) }
|
||||
} finally { $graphics.Dispose() }
|
||||
if ($process.HasExited) { throw "Files exited while rendering the FTP profile in panel $side." }
|
||||
}
|
||||
Write-Output 'Both source menus rendered the FTP shortcut, skipped group dividers, and opened FTP with 1.'
|
||||
return
|
||||
}
|
||||
if ($OfflineWake) {
|
||||
function Click-Picker([int]$X, [int]$Y) {
|
||||
$point = [IntPtr](($Y -shl 16) -bor $X)
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 513, [IntPtr]1, $point)
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 514, [IntPtr]::Zero, $point)
|
||||
}
|
||||
Open-Picker
|
||||
$rows = @(Read-Picker)
|
||||
$wake = -1
|
||||
for ($i = 0; $i -lt $rows.Count; $i++) {
|
||||
if ($rows[$i] -match '^ (Offline|Looking for PC\.\.\.) \tWake$') { $wake = $i; break }
|
||||
}
|
||||
if ($wake -lt 0) { throw 'This check requires an offline paired PC with a Wake action.' }
|
||||
$rect = [FilesDriveShortcutTest+Rect]::new()
|
||||
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]$wake, [ref]$rect)
|
||||
$original = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null)
|
||||
Click-Picker ($rect.Left + 16) ([int](($rect.Top + $rect.Bottom) / 2))
|
||||
Start-Sleep -Milliseconds 100
|
||||
if (![FilesDriveShortcutTest]::IsWindowVisible($picker) -or
|
||||
[FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null) -ne $original) {
|
||||
throw 'Clicking outside the Wake label selected or activated the status row.'
|
||||
}
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 675, [IntPtr]::Zero, [IntPtr]::Zero)
|
||||
$normal = Render-Picker
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$wake, $null)
|
||||
$focused = Render-Picker
|
||||
try {
|
||||
$changed = @(for ($x = $rect.Left; $x -lt [Math]::Min($rect.Right, $normal.Width); $x++) {
|
||||
if ($normal.GetPixel($x,$rect.Top) -ne $focused.GetPixel($x,$rect.Top)) { $x }
|
||||
})
|
||||
$width = $rect.Right - $rect.Left
|
||||
if (!$changed.Count -or $changed[0] -lt ($rect.Left + $width / 2) -or $changed[-1] -ge $rect.Right - 2) {
|
||||
throw 'Wake focus must highlight only the inline action and leave the status and trailing space unchanged.'
|
||||
}
|
||||
if ($Screenshot) { $focused.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png) }
|
||||
Click-Picker ([int](($changed[0]+$changed[-1])/2)) ([int](($rect.Top+$rect.Bottom)/2))
|
||||
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
|
||||
} finally { $normal.Dispose(); $focused.Dispose() }
|
||||
Open-Picker
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$wake, $null)
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]13, [IntPtr]::Zero)
|
||||
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
|
||||
Write-Output 'Wake focus and mouse activation are limited to the inline action. Enter activates the focused action.'
|
||||
return
|
||||
}
|
||||
Open-Picker
|
||||
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
|
||||
$rows = @(for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i })
|
||||
@@ -64,5 +217,17 @@ try {
|
||||
}
|
||||
Write-Output 'Remote drives appeared automatically on both opens.'
|
||||
} finally {
|
||||
if (!$process.HasExited) { [void]$process.CloseMainWindow() }
|
||||
if ($previousDpi) { [void][FilesDriveShortcutTest]::SetThreadDpiAwarenessContext($previousDpi) }
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
if ($preferences -and !$process.WaitForExit(3000)) { Stop-Process -Id $process.Id; $process.WaitForExit() }
|
||||
}
|
||||
if ($preferences) {
|
||||
foreach ($name in $preferenceNames) {
|
||||
if ($savedPreferences.ContainsKey($name)) {
|
||||
$preferences.SetValue($name, $savedPreferences[$name][0], $savedPreferences[$name][1])
|
||||
} else { $preferences.DeleteValue($name, $false) }
|
||||
}
|
||||
$preferences.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe",
|
||||
[string]$Screenshot
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class FilesShortcutWindow {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Point { public int X, Y; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint command);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr window, ref Point point);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr Send(IntPtr window, uint message, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr SendMessage(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
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;
|
||||
}
|
||||
}
|
||||
'@
|
||||
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 Read-Text($Control, $Message = 13, $Parameter = 2048) {
|
||||
$buffer = [Text.StringBuilder]::new(2048)
|
||||
[void][FilesShortcutWindow]::SendMessage($Control, $Message, [IntPtr]$Parameter, $buffer)
|
||||
$buffer.ToString()
|
||||
}
|
||||
function Read-ShortcutDialog {
|
||||
$foreground = [FilesShortcutWindow]::GetForegroundWindow()
|
||||
if ([FilesShortcutWindow]::GetWindow($foreground, 4) -eq $window -and
|
||||
[FilesShortcutWindow]::GetDlgItem($foreground, 310) -ne [IntPtr]::Zero) { return $foreground }
|
||||
return [IntPtr]::Zero
|
||||
}
|
||||
|
||||
$exe = (Resolve-Path $Executable).Path
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$saved = @{}
|
||||
$names = 'FolderShortcuts', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
|
||||
foreach ($name in $names) {
|
||||
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
|
||||
}
|
||||
$folder = [IO.Directory]::CreateTempSubdirectory('ks-files-shortcuts-').FullName
|
||||
$previousDpi = [FilesShortcutWindow]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
try {
|
||||
$groups = [object[]]::new(10)
|
||||
for ($digit = 0; $digit -lt 10; $digit++) { $groups[$digit] = @() }
|
||||
foreach ($entry in @(@(3, 'Three'), @(4, 'Four'), @(8, 'Eight A'), @(8, 'Eight B'))) {
|
||||
$path = [IO.Directory]::CreateDirectory((Join-Path $folder $entry[1])).FullName
|
||||
$groups[$entry[0]] += @{ path = $path; peer = ''; name = ''; title = $entry[1] }
|
||||
}
|
||||
$groups[9] = @(1..200 | ForEach-Object {
|
||||
@{ path = (Join-Path $folder "Folder $_"); peer = ''; name = ''; title = "Folder $_" }
|
||||
})
|
||||
$key.SetValue('FolderShortcuts', [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $groups -Depth 4)), 'Binary')
|
||||
foreach ($name in 'LeftWide', 'RightWide') { $key.SetValue($name, 1, 'DWord') }
|
||||
foreach ($name in 'LeftPath', 'RightPath') { $key.SetValue($name, $folder, 'String') }
|
||||
$key.DeleteValue('WindowPlacement', $false)
|
||||
|
||||
$process = Start-Process -FilePath $exe -PassThru
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
$window = $process.MainWindowHandle
|
||||
Wait-Until { [FilesShortcutWindow]::Activate($window) }
|
||||
$heading = [FilesShortcutWindow]::GetDlgItem($window, 140)
|
||||
$rightHeading = [FilesShortcutWindow]::GetDlgItem($window, 141)
|
||||
$leftPath = [FilesShortcutWindow]::GetDlgItem($window, 142)
|
||||
Wait-Until { (Read-Text $leftPath) -eq $folder }
|
||||
|
||||
$keyboard.SendKeys('^8')
|
||||
Wait-Until { (Read-ShortcutDialog) -ne [IntPtr]::Zero }
|
||||
$dialog = Read-ShortcutDialog
|
||||
$list = [FilesShortcutWindow]::GetDlgItem($dialog, 310)
|
||||
$count = [FilesShortcutWindow]::SendMessage($list, 395, [IntPtr]::Zero, $null).ToInt32()
|
||||
$rows = for ($row = 0; $row -lt $count; $row++) { Read-Text $list 393 $row }
|
||||
if (($rows -join '|') -cne 'Eight A|Eight B') {
|
||||
throw "Ctrl+8 should display only its two assigned folders. Actual rows: $($rows -join ' | ')"
|
||||
}
|
||||
if ($Screenshot) {
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$bounds = [FilesShortcutWindow+Rect]::new()
|
||||
if (![FilesShortcutWindow]::GetWindowRect($dialog, [ref]$bounds)) { throw 'Cannot locate the rendered popup.' }
|
||||
$bitmap = [Drawing.Bitmap]::new(($bounds.Right - $bounds.Left), ($bounds.Bottom - $bounds.Top))
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try { $graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bitmap.Size) }
|
||||
finally { $graphics.Dispose() }
|
||||
$bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png)
|
||||
} finally { $bitmap.Dispose() }
|
||||
}
|
||||
$keyboard.SendKeys('{ESC}')
|
||||
Wait-Until { [FilesShortcutWindow]::GetForegroundWindow() -eq $window }
|
||||
$keyboard.SendKeys('^4')
|
||||
Wait-Until { (Read-Text $leftPath) -eq (Join-Path $folder 'Four') }
|
||||
if (![FilesShortcutWindow]::IsWindowVisible($heading)) { throw 'Ctrl+4 changed panel mode.' }
|
||||
$keyboard.SendKeys('^{TAB}')
|
||||
$keyboard.SendKeys('^{F1}')
|
||||
Wait-Until {
|
||||
![FilesShortcutWindow]::IsWindowVisible($heading) -or
|
||||
![FilesShortcutWindow]::IsWindowVisible($rightHeading)
|
||||
}
|
||||
if (![FilesShortcutWindow]::IsWindowVisible($rightHeading)) {
|
||||
throw 'Ctrl+Tab changed the active panel.'
|
||||
}
|
||||
$keyboard.SendKeys('{TAB}')
|
||||
$keyboard.SendKeys('^{F1}')
|
||||
Wait-Until { ![FilesShortcutWindow]::IsWindowVisible($rightHeading) }
|
||||
$keyboard.SendKeys('^{F2}')
|
||||
Wait-Until { [FilesShortcutWindow]::IsWindowVisible($rightHeading) }
|
||||
$keyboard.SendKeys('{TAB}')
|
||||
Wait-Until { ![FilesShortcutWindow]::IsWindowVisible($heading) }
|
||||
|
||||
$rightPath = [FilesShortcutWindow]::GetDlgItem($window, 143)
|
||||
$leftList = [FilesShortcutWindow]::GetDlgItem($window, 102)
|
||||
$rightList = [FilesShortcutWindow]::GetDlgItem($window, 103)
|
||||
$keyboard.SendKeys('^u')
|
||||
Wait-Until {
|
||||
(Read-Text ([FilesShortcutWindow]::GetDlgItem($window, 142))) -eq $folder -and
|
||||
(Read-Text ([FilesShortcutWindow]::GetDlgItem($window, 143))) -eq (Join-Path $folder 'Four') -and
|
||||
[FilesShortcutWindow]::IsWindowVisible($rightHeading)
|
||||
}
|
||||
$movedLeft = [FilesShortcutWindow+Rect]::new()
|
||||
$movedRight = [FilesShortcutWindow+Rect]::new()
|
||||
if (![FilesShortcutWindow]::GetWindowRect($rightList, [ref]$movedLeft) -or
|
||||
![FilesShortcutWindow]::GetWindowRect($leftList, [ref]$movedRight) -or
|
||||
$movedLeft.Right -gt $movedRight.Left -or
|
||||
[FilesShortcutWindow]::IsWindowVisible($heading)) {
|
||||
throw 'Ctrl+U did not move the visible panel lists with their modes.'
|
||||
}
|
||||
$keyboard.SendKeys('^3')
|
||||
Wait-Until { (Read-Text $leftPath) -eq (Join-Path $folder 'Three') }
|
||||
if ((Read-Text $rightPath) -ne $folder) { throw 'Ctrl+U did not preserve the active panel.' }
|
||||
$keyboard.SendKeys('^u')
|
||||
Wait-Until { [FilesShortcutWindow]::GetDlgItem($window, 142) -eq $leftPath }
|
||||
$keyboard.SendKeys('^{F2}')
|
||||
Wait-Until { [FilesShortcutWindow]::IsWindowVisible($heading) }
|
||||
|
||||
$keyboard.SendKeys('^9')
|
||||
Wait-Until { (Read-ShortcutDialog) -ne [IntPtr]::Zero }
|
||||
$dialog = Read-ShortcutDialog
|
||||
$list = [FilesShortcutWindow]::GetDlgItem($dialog, 310)
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$bounds = [FilesShortcutWindow+Rect]::new()
|
||||
if (![FilesShortcutWindow]::GetWindowRect($list, [ref]$bounds)) { throw 'Missing overflow list.' }
|
||||
Start-Sleep -Milliseconds 150
|
||||
$barWidth = [int][Math]::Round(12 * [FilesShortcutWindow]::GetDpiForWindow($list) / 96)
|
||||
$bitmap = [Drawing.Bitmap]::new($barWidth, ($bounds.Bottom - $bounds.Top))
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try { $graphics.CopyFromScreen($bounds.Right, $bounds.Top, 0, 0, $bitmap.Size) }
|
||||
finally { $graphics.Dispose() }
|
||||
$background = $bitmap.GetPixel(0, 0)
|
||||
$thumb = $bitmap.GetPixel(0, $barWidth + 1)
|
||||
$trackColors = @(0..4 | ForEach-Object {
|
||||
$x = $_
|
||||
0..7 | ForEach-Object { $bitmap.GetPixel($x, [int]($bitmap.Height / 2) + $_).ToArgb() }
|
||||
} | Sort-Object -Unique)
|
||||
$hasArrow = {
|
||||
param($y)
|
||||
$center = [int][Math]::Floor($barWidth / 2)
|
||||
@(0..($barWidth - 1) | Where-Object {
|
||||
$bitmap.GetPixel($center, $y + $_).ToArgb() -eq $thumb.ToArgb()
|
||||
}).Count -gt 0
|
||||
}
|
||||
if ($thumb.GetBrightness() -le $background.GetBrightness() -or $trackColors.Count -ne 2 -or
|
||||
!(& $hasArrow 0) -or !(& $hasArrow ($bitmap.Height - $barWidth))) {
|
||||
throw "Unexpected scrollbar pixels. Background $background, thumb $thumb, track colors $($trackColors.Count), arrows $(& $hasArrow 0)/$(& $hasArrow ($bitmap.Height - $barWidth))."
|
||||
}
|
||||
} finally { $bitmap.Dispose() }
|
||||
$arrow = [FilesShortcutWindow+Point]::new()
|
||||
$arrow.X = $bounds.Right + [int]($barWidth / 2)
|
||||
$arrow.Y = $bounds.Bottom - [int]($barWidth / 2)
|
||||
if (![FilesShortcutWindow]::ScreenToClient($dialog, [ref]$arrow)) { throw 'Cannot locate the down arrow.' }
|
||||
$arrowPoint = [IntPtr](($arrow.Y -shl 16) -bor $arrow.X)
|
||||
[void][FilesShortcutWindow]::Send($dialog, 0x0201, [IntPtr]1, $arrowPoint)
|
||||
if ([FilesShortcutWindow]::Send($list, 0x018E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne 1) {
|
||||
throw 'The down arrow should scroll the list by one row.'
|
||||
}
|
||||
$grip = [FilesShortcutWindow+Point]::new()
|
||||
$grip.X = $bounds.Right + [int]($barWidth / 2)
|
||||
$grip.Y = $bounds.Top + $barWidth + 4
|
||||
if (![FilesShortcutWindow]::ScreenToClient($dialog, [ref]$grip)) { throw 'Cannot locate the thumb.' }
|
||||
$gripPoint = [IntPtr](($grip.Y -shl 16) -bor $grip.X)
|
||||
$dragPoint = [IntPtr]((($grip.Y + 3 * $barWidth) -shl 16) -bor $grip.X)
|
||||
[void][FilesShortcutWindow]::Send($dialog, 0x0201, [IntPtr]1, $gripPoint)
|
||||
[void][FilesShortcutWindow]::Send($dialog, 0x0200, [IntPtr]1, $dragPoint)
|
||||
[void][FilesShortcutWindow]::Send($dialog, 0x0202, [IntPtr]::Zero, $dragPoint)
|
||||
if ([FilesShortcutWindow]::Send($list, 0x018E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -le 1) {
|
||||
throw 'Dragging the scrollbar thumb should advance the list.'
|
||||
}
|
||||
$keyboard.SendKeys('{ESC}')
|
||||
Write-Output 'Verified folder shortcuts, panel swapping, and the rendered overflow scrollbar.'
|
||||
} finally {
|
||||
if ($previousDpi) { [void][FilesShortcutWindow]::SetThreadDpiAwarenessContext($previousDpi) }
|
||||
if ($process -and !$process.HasExited) {
|
||||
$keyboard.SendKeys('{ESC}')
|
||||
if (!$process.CloseMainWindow() -or !$process.WaitForExit(2500)) { $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()
|
||||
[IO.Directory]::Delete($folder, $true)
|
||||
}
|
||||
+184
-7
@@ -1,6 +1,7 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Executable,
|
||||
[string]$Screenshot,
|
||||
[string]$SearchScreenshot,
|
||||
[string]$Node = 'node',
|
||||
[string]$LanFixture
|
||||
)
|
||||
@@ -10,6 +11,37 @@ using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class MarkdownUi {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct PropertyKey {
|
||||
public Guid Format;
|
||||
public uint Id;
|
||||
}
|
||||
[StructLayout(LayoutKind.Explicit, Size = 24)]
|
||||
struct PropertyValue {
|
||||
[FieldOffset(0)] public ushort Type;
|
||||
[FieldOffset(8)] public IntPtr Text;
|
||||
}
|
||||
[ComImport, Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
interface IPropertyStore {
|
||||
void GetCount(out uint count);
|
||||
void GetAt(uint index, out PropertyKey key);
|
||||
void GetValue(ref PropertyKey key, out PropertyValue value);
|
||||
}
|
||||
[DllImport("shell32.dll", PreserveSig = false)]
|
||||
static extern void SHGetPropertyStoreForWindow(IntPtr window, ref Guid iid, out IPropertyStore store);
|
||||
[DllImport("ole32.dll")] static extern int PropVariantClear(ref PropertyValue value);
|
||||
|
||||
public static string TaskbarProperty(IntPtr window, uint property) {
|
||||
var iid = typeof(IPropertyStore).GUID;
|
||||
var key = new PropertyKey { Format = new Guid("9f4c2855-9f79-4b39-a8d0-e1d42de1d5f3"), Id = property };
|
||||
SHGetPropertyStoreForWindow(window, ref iid, out var store);
|
||||
try {
|
||||
store.GetValue(ref key, out var value);
|
||||
try { return value.Type == 31 ? Marshal.PtrToStringUni(value.Text) : null; }
|
||||
finally { PropVariantClear(ref value); }
|
||||
} finally { Marshal.ReleaseComObject(store); }
|
||||
}
|
||||
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
@@ -22,10 +54,12 @@ public static class MarkdownUi {
|
||||
keybd_event(0x12,0,2,UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
}
|
||||
public static void CycleWindow() {
|
||||
public static void CycleWindow(bool reverse = false) {
|
||||
keybd_event(0x11,0,0,UIntPtr.Zero);
|
||||
if (reverse) keybd_event(0x10,0,0,UIntPtr.Zero);
|
||||
keybd_event(0x09,0,0,UIntPtr.Zero);
|
||||
keybd_event(0x09,0,2,UIntPtr.Zero);
|
||||
if (reverse) keybd_event(0x10,0,2,UIntPtr.Zero);
|
||||
keybd_event(0x11,0,2,UIntPtr.Zero);
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
@@ -83,6 +117,34 @@ function Scintilla($Window) {
|
||||
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
|
||||
}
|
||||
|
||||
function Assert-ReopenedMarkdown($Window, $File) {
|
||||
try { Browser 'reopen' '' $File }
|
||||
finally {
|
||||
if ([MarkdownUi]::IsWindowVisible((Scintilla $Window))) { throw "$File opened as raw text." }
|
||||
}
|
||||
}
|
||||
|
||||
function Close-Preview($Window) {
|
||||
Post $Window 0x10 0
|
||||
[void](Wait-For 'the Markdown preview to close' { ![MarkdownUi]::IsWindowVisible($Window) })
|
||||
}
|
||||
|
||||
function Assert-TextWindowAppearance($Window, [string]$Mode) {
|
||||
$identity = "HrynCo.KSwitcher.Files.$Mode"
|
||||
$resource = if($Mode -eq 'Editor') { ',-104' } else { ',-103' }
|
||||
[void](Wait-For "the $Mode taskbar group" { [MarkdownUi]::TaskbarProperty($Window,5) -ceq $identity })
|
||||
$taskbarIcon = [MarkdownUi]::TaskbarProperty($Window,3)
|
||||
if (!$taskbarIcon -or !$taskbarIcon.EndsWith($resource)) {
|
||||
throw "$Mode taskbar icon was '$taskbarIcon'."
|
||||
}
|
||||
$small = [MarkdownUi]::Send($Window,0x7f,0,0)
|
||||
$large = [MarkdownUi]::Send($Window,0x7f,1,0)
|
||||
if (!$small.ToInt64() -or !$large.ToInt64() -or $small -eq $large) {
|
||||
throw "$Mode must expose both a small title-bar icon and a large switcher icon."
|
||||
}
|
||||
@{ Small = $small; Large = $large }
|
||||
}
|
||||
|
||||
function Append-Character($Control, [char]$Character) {
|
||||
[void][MarkdownUi]::Send($Control,2318,0,0)
|
||||
[void][MarkdownUi]::Send($Control,0x102,[int]$Character,0)
|
||||
@@ -104,7 +166,7 @@ $docs = Join-Path $root 'docs'
|
||||
$profileCaptured = $false
|
||||
$profile = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$saved = @{}
|
||||
$profileValues = 'LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
|
||||
$profileValues = 'LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement','OptionsLocation'
|
||||
$process = $null
|
||||
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
$data = $env:WEBVIEW2_USER_DATA_FOLDER
|
||||
@@ -117,17 +179,29 @@ try {
|
||||
| Header |
|
||||
| ------ |
|
||||
| Cell |
|
||||
| <span id="nowrap-cell" style="white-space: nowrap; color: red; position: fixed" onclick="void 0">In Development</span> |
|
||||
|
||||
<table id="html-table">
|
||||
<caption>Raw HTML table</caption>
|
||||
<tr><th colspan="2">Priority</th></tr>
|
||||
<tr><td><strong>Highest</strong></td><td>—</td></tr>
|
||||
</table>
|
||||
|
||||
- [ ] Pending
|
||||
- [x] Complete
|
||||
|
||||
## Збіг пошуку
|
||||
|
||||
Рядок для **збіг пошуку**.
|
||||
|
||||

|
||||

|
||||
[Child](child/Other.md#target-heading)
|
||||
<img alt="HTML relative image" src="images/tiny%20image.png">
|
||||
<a href="child/Other.md#target-heading">Child</a>
|
||||
|
||||
~~~mermaid
|
||||
flowchart TD
|
||||
A[Render target] --> B[Result]
|
||||
A[Render target] -->|Transition| B[Result]
|
||||
~~~
|
||||
|
||||
~~~mermaid
|
||||
@@ -142,6 +216,8 @@ const value = 42;
|
||||
'@
|
||||
$original = Join-Path $docs 'Preview.md'
|
||||
[IO.File]::WriteAllText($original,$fixture)
|
||||
[IO.File]::WriteAllText("$docs\Reopen.md",'# Reopened Markdown')
|
||||
[IO.File]::WriteAllText("$docs\Second.md",'# Second Markdown')
|
||||
$childText = '# Linked Markdown' + "`n`n" + (("Filler paragraph.`n`n") * 60) + '## Target heading'
|
||||
[IO.File]::WriteAllText("$docs\child\Other.md",$childText)
|
||||
[IO.File]::WriteAllText("$docs\Plain.txt",'Plain text')
|
||||
@@ -160,7 +236,7 @@ const value = 42;
|
||||
$profileCaptured = $true
|
||||
$profile.SetValue('LeftPath',$docs)
|
||||
$profile.SetValue('RightPath',$docs)
|
||||
foreach ($name in 'LeftCursor','RightCursor','WindowPlacement') { $profile.DeleteValue($name,$false) }
|
||||
foreach ($name in 'LeftCursor','RightCursor','WindowPlacement','OptionsLocation') { $profile.DeleteValue($name,$false) }
|
||||
|
||||
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$listener.Start()
|
||||
@@ -173,13 +249,83 @@ const value = 42;
|
||||
[MarkdownUi]::Activate($main)
|
||||
$panel = [MarkdownUi]::GetDlgItem($main,102)
|
||||
|
||||
$previewScript = Join-Path $app 'terminal\markdown.js'
|
||||
$originalScript = [IO.File]::ReadAllText($previewScript)
|
||||
try {
|
||||
# Let the page load without sending the ready message until Files starts a new WebView.
|
||||
[IO.File]::WriteAllText($previewScript,"document.documentElement.dataset.startup = 'stalled';")
|
||||
Open-File 'Reopen.md' 0x72
|
||||
$window = Wait-For 'the stalled Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Reopen.md' }
|
||||
Browser 'startup-stalled'
|
||||
} finally { [IO.File]::WriteAllText($previewScript,$originalScript) }
|
||||
Assert-ReopenedMarkdown $window 'Reopen.md'
|
||||
Close-Preview $window
|
||||
Write-Output 'Verified that the same viewer renders Markdown after a stalled WebView2 startup.'
|
||||
|
||||
Open-File 'Reopen.md' 0x72
|
||||
$window = Wait-For 'the Markdown viewer before early close' { Find-Window 'KSwitcher.Files.Text' 'Reopen.md' }
|
||||
Close-Preview $window
|
||||
foreach ($file in 'Reopen.md','Second.md','Reopen.md','Second.md','Reopen.md','Second.md') {
|
||||
Open-File $file 0x72
|
||||
$window = Wait-For "the reopened $file viewer" { Find-Window 'KSwitcher.Files.Text' $file }
|
||||
Assert-ReopenedMarkdown $window $file
|
||||
Close-Preview $window
|
||||
}
|
||||
Write-Output 'Verified six immediate Markdown reopens after closing the initial preview during startup.'
|
||||
|
||||
Open-File 'Preview.md' 0x72
|
||||
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
|
||||
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
|
||||
if ([MarkdownUi]::IsWindowVisible((Scintilla $window))) {
|
||||
throw 'F3 showed the source text while starting the Markdown preview.'
|
||||
}
|
||||
Browser 'render' $Screenshot
|
||||
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Checking a task modified the read-only file.' }
|
||||
Post $window 0x111 3
|
||||
Browser 'search-menu'
|
||||
Browser 'search' $SearchScreenshot
|
||||
Post $main 0x111 133
|
||||
$options = Wait-For 'the shared Files Options dialog' { Find-Window '#32770' 'KSwitcher Files Options' }
|
||||
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,270),0x0C,0,'Markdown')
|
||||
[void](Wait-For 'the Markdown settings section' { [MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374)) })
|
||||
foreach($field in @(@(374,'1200'),@(376,'Georgia'),@(379,'18'))){
|
||||
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,$field[0]),0x0C,0,$field[1])
|
||||
}
|
||||
Post $options 0x111 1
|
||||
[void](Wait-For 'Options to close after saving Markdown settings' { ![MarkdownUi]::IsWindowVisible($options) })
|
||||
Browser 'appearance-width'
|
||||
|
||||
Post $main 0x111 133
|
||||
$options = Wait-For 'reopened Files Options' { Find-Window '#32770' 'KSwitcher Files Options' }
|
||||
if (![MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374))) {
|
||||
throw 'Files Options did not restore its last section.'
|
||||
}
|
||||
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,374),0x0C,0,'0')
|
||||
Post $options 0x111 2
|
||||
[void](Wait-For 'Options to close on Cancel' { ![MarkdownUi]::IsWindowVisible($options) })
|
||||
Browser 'appearance-width'
|
||||
|
||||
Post $main 0x111 133
|
||||
$options = Wait-For 'Files Options after Cancel' { Find-Window '#32770' 'KSwitcher Files Options' }
|
||||
if (![MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374))) {
|
||||
throw 'Cancel did not preserve the last Options section.'
|
||||
}
|
||||
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,374),0x0C,0,'0')
|
||||
Post $options 0x111 1
|
||||
[void](Wait-For 'Options to close after saving full width' { ![MarkdownUi]::IsWindowVisible($options) })
|
||||
Browser 'appearance-full'
|
||||
Write-Output 'Verified live Markdown width and font settings, Cancel and reopening the last Options section.'
|
||||
Browser 'toggle-first-task'
|
||||
$checkedFixture=$fixture.Replace('- [ ] Pending','- [x] Pending')
|
||||
[void](Wait-For 'Markdown checkbox saved to the source file' { [IO.File]::ReadAllText($original) -ceq $checkedFixture })
|
||||
Browser 'close'
|
||||
[void](Wait-For 'the initial preview to close' { ![MarkdownUi]::IsWindowVisible($window) })
|
||||
[MarkdownUi]::Activate($main)
|
||||
Wait-Foreground $main
|
||||
Open-File 'Preview.md' 0x72
|
||||
$window=Wait-For 'the reopened Markdown preview' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
|
||||
Browser 'first-task-checked'
|
||||
Browser 'toggle-first-task'
|
||||
[void](Wait-For 'the unchecked Markdown marker to save' { [IO.File]::ReadAllText($original) -ceq $fixture })
|
||||
[IO.File]::WriteAllText($original,($fixture.Replace('Перегляд Markdown','Зміна на диску')))
|
||||
Browser 'Зміна на диску' '' 'Preview.md'
|
||||
$replacement = Join-Path $docs 'Preview-replacement.md'
|
||||
@@ -190,12 +336,17 @@ const value = 42;
|
||||
Browser 'edit'
|
||||
$editor = Wait-For 'F6 in WebView2 to open the editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
|
||||
if ($editor -ne $window) { throw 'F6 changed windows.' }
|
||||
$editorIcons = Assert-TextWindowAppearance $window 'Editor'
|
||||
if ($editorIcons.Small -eq $viewerIcons.Small -or $editorIcons.Large -eq $viewerIcons.Large) {
|
||||
throw 'F6 did not replace both viewer icons with editor icons.'
|
||||
}
|
||||
[MarkdownUi]::Activate($window)
|
||||
Wait-Foreground $window
|
||||
[MarkdownUi]::CycleWindow()
|
||||
Wait-Foreground $main
|
||||
[MarkdownUi]::CycleWindow()
|
||||
Wait-Foreground $window
|
||||
Write-Output 'Verified Ctrl+Tab between Files and the Markdown editor.'
|
||||
$control = Scintilla $window
|
||||
if ([MarkdownUi]::Send($control,2140,0,0).ToInt64()) { throw 'The editor is read-only.' }
|
||||
Append-Character $control 'X'
|
||||
@@ -207,6 +358,10 @@ const value = 42;
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 7
|
||||
Browser 'Перегляд Markdown'
|
||||
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
|
||||
if ($viewerIcons.Small -eq $editorIcons.Small -or $viewerIcons.Large -eq $editorIcons.Large) {
|
||||
throw 'F6 did not restore both viewer icons.'
|
||||
}
|
||||
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Discard changed the Markdown file.' }
|
||||
Browser 'ctrl-follow'
|
||||
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window -or (Find-Window 'KSwitcher.Files.Text' 'Other.md')) {
|
||||
@@ -214,16 +369,29 @@ const value = 42;
|
||||
}
|
||||
Browser 'shift-follow'
|
||||
$child = Wait-For 'the Shift+click Markdown window' { Find-Window 'KSwitcher.Files.Text' 'Other.md' $window }
|
||||
[void](Assert-TextWindowAppearance $child 'Viewer')
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
[MarkdownUi]::Activate($child)
|
||||
Wait-Foreground $child
|
||||
Browser 'cycle' '' 'Other.md'
|
||||
Wait-Foreground $main
|
||||
[MarkdownUi]::CycleWindow()
|
||||
Wait-Foreground $window
|
||||
Browser 'cycle' '' 'Preview.md'
|
||||
Wait-Foreground $child
|
||||
Browser 'cycle-reverse' '' 'Other.md'
|
||||
Wait-Foreground $window
|
||||
Browser 'edit' '' 'Preview.md'
|
||||
[void](Wait-For 'the first window to switch to Editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' })
|
||||
[MarkdownUi]::CycleWindow($true)
|
||||
Wait-Foreground $main
|
||||
[MarkdownUi]::CycleWindow($true)
|
||||
Wait-Foreground $child
|
||||
Write-Output 'Verified backward Ctrl+Shift+Tab cycling through three windows and wrapping at Files.'
|
||||
Browser 'close' '' 'Other.md'
|
||||
[void](Wait-For 'Ctrl+W to close the Shift+click window' { ![MarkdownUi]::IsWindowVisible($child) })
|
||||
Post (Scintilla $window) 0x100 0x75
|
||||
Browser 'Перегляд Markdown' '' 'Preview.md'
|
||||
Browser 'follow'
|
||||
if ((Wait-For 'the in-place Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
|
||||
throw 'A normal click did not stay in the same window.'
|
||||
@@ -242,11 +410,14 @@ const value = 42;
|
||||
|
||||
Open-File 'Preview.md' 0x73
|
||||
$window = Wait-For 'F4 to open the Markdown editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
|
||||
[void](Assert-TextWindowAppearance $window 'Editor')
|
||||
Write-Output 'Verified F3/F4 icons, separate taskbar groups and regrouping when the same window switches modes with F6.'
|
||||
$control = Scintilla $window
|
||||
Append-Character $control 'Y'
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 6
|
||||
Browser 'Перегляд Markdown'
|
||||
Browser 'appearance-full'
|
||||
if (![IO.File]::ReadAllText($original).EndsWith('Y')) { throw 'F6 rendered before saving.' }
|
||||
Post $window 0x10 0
|
||||
[void](Wait-For 'the saved Markdown viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
@@ -271,7 +442,8 @@ const value = 42;
|
||||
}
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 7
|
||||
Post $window 0x10 0
|
||||
Browser 'external-replacement'
|
||||
Browser 'close'
|
||||
[void](Wait-For 'the conflict fixture to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
|
||||
Open-File 'Plain.txt' 0x72
|
||||
@@ -313,11 +485,16 @@ const value = 42;
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'lan-webview'
|
||||
$process = Start-Process -FilePath $lanExe -ArgumentList ('"{0}"' -f $original) -PassThru -WindowStyle Normal
|
||||
$window = Wait-For 'the LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Loopback peer' }
|
||||
[void](Assert-TextWindowAppearance $window 'Viewer')
|
||||
Browser 'render'
|
||||
Browser 'toggle-first-task'
|
||||
[void](Wait-For 'Markdown checkbox uploaded to the LAN peer' { [IO.File]::ReadAllText($original) -ceq $checkedFixture })
|
||||
Browser 'search'
|
||||
Browser 'edit'
|
||||
if ((Wait-For 'LAN F6 editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }) -ne $window) {
|
||||
throw 'LAN F6 changed windows.'
|
||||
}
|
||||
[void](Assert-TextWindowAppearance $window 'Editor')
|
||||
$control = Scintilla $window
|
||||
Append-Character $control 'L'
|
||||
Post $control 0x100 0x75
|
||||
|
||||
@@ -3,6 +3,7 @@ import { writeFile } from 'node:fs/promises';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
const [port, scenario, artifact, title] = process.argv.slice(2);
|
||||
const terminalScenario = scenario.startsWith('terminal-');
|
||||
let socket;
|
||||
const pending = new Map();
|
||||
let sequence = 0;
|
||||
@@ -38,12 +39,21 @@ async function evaluate(expression) {
|
||||
return reply.result.value;
|
||||
}
|
||||
|
||||
async function pressKey(key, code, windowsVirtualKeyCode, modifiers = 0) {
|
||||
const params = { key, code, windowsVirtualKeyCode, modifiers };
|
||||
await command('Input.dispatchKeyEvent', { type: 'keyDown', ...params });
|
||||
await command('Input.dispatchKeyEvent', { type: 'keyUp', ...params });
|
||||
}
|
||||
|
||||
const target = await waitFor(async () => {
|
||||
const response = await fetch('http://127.0.0.1:' + port + '/json/list').catch(() => null);
|
||||
if (!response?.ok) return;
|
||||
return (await response.json()).find(item => item.url === 'https://kswitcher-markdown.invalid/markdown.html' &&
|
||||
const url = terminalScenario
|
||||
? 'https://kswitcher-terminal.invalid/index.html'
|
||||
: 'https://kswitcher-markdown.invalid/markdown.html';
|
||||
return (await response.json()).find(item => item.url === url &&
|
||||
(!title || item.title === title));
|
||||
}, 'the Markdown page in WebView2');
|
||||
}, 'the target WebView2 page');
|
||||
socket = new WebSocket(target.webSocketDebuggerUrl);
|
||||
socket.addEventListener('message', event => {
|
||||
const reply = JSON.parse(event.data);
|
||||
@@ -59,7 +69,31 @@ await new Promise((resolve, reject) => {
|
||||
});
|
||||
|
||||
try {
|
||||
if (scenario === 'render') {
|
||||
if (scenario === 'terminal-startup-pause' || scenario === 'terminal-startup-resume') {
|
||||
await waitFor(() => evaluate('typeof startTerminalFixture === "function"'), 'the delayed terminal page');
|
||||
if (scenario === 'terminal-startup-resume') await evaluate('startTerminalFixture()');
|
||||
} else if (scenario === 'terminal-select-output') {
|
||||
const selection = await waitFor(() => evaluate(`(() => {
|
||||
const marker = 'terminal-output-copy-fixture';
|
||||
const buffer = terminal.buffer.active;
|
||||
for (let row = buffer.viewportY; row < buffer.viewportY + terminal.rows; row++) {
|
||||
if (buffer.getLine(row)?.translateToString(true) !== marker) continue;
|
||||
terminal.select(0, row, marker.length);
|
||||
document.querySelector('#terminal').dispatchEvent(new PointerEvent('pointerup', { bubbles:true }));
|
||||
return terminal.getSelection();
|
||||
}
|
||||
})()`), 'the terminal output fixture');
|
||||
assert.equal(selection, 'terminal-output-copy-fixture');
|
||||
} else if (terminalScenario) {
|
||||
assert.equal(await evaluate('terminal.options.cursorInactiveStyle'), 'none');
|
||||
assert.equal(await evaluate('document.querySelectorAll(".xterm-cursor-outline").length'), 0);
|
||||
await evaluate('document.querySelector(".xterm-helper-textarea").focus()');
|
||||
const key = scenario === 'terminal-copy'
|
||||
? { key:'Insert', code:'Insert', modifiers:2, windowsVirtualKeyCode:45 }
|
||||
: { key:'Enter', code:'Enter', windowsVirtualKeyCode:13 };
|
||||
await command('Input.dispatchKeyEvent', { type:'keyDown', ...key });
|
||||
await command('Input.dispatchKeyEvent', { type:'keyUp', ...key });
|
||||
} else if (scenario === 'render') {
|
||||
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
|
||||
!!document.querySelector('figure svg') &&
|
||||
document.querySelector('img')?.naturalWidth === 1`), 'rendered Mermaid SVG and relative image');
|
||||
@@ -69,8 +103,28 @@ try {
|
||||
return style.borderTopWidth === '0px' && style.backgroundColor === 'rgba(0, 0, 0, 0)';
|
||||
})`), true);
|
||||
assert.equal(await evaluate(`document.querySelector('td').textContent`), 'Cell');
|
||||
assert.deepEqual(await evaluate(`(() => {
|
||||
const span = document.querySelector('td #nowrap-cell');
|
||||
return span && [span.textContent, getComputedStyle(span).whiteSpace,
|
||||
getComputedStyle(span).color, span.style.position, span.hasAttribute('onclick')];
|
||||
})()`), ['In Development', 'nowrap', 'rgb(255, 0, 0)', '', false]);
|
||||
assert.deepEqual(await evaluate(`(() => {
|
||||
const table = document.querySelector('#html-table');
|
||||
return table && [table.caption.textContent, table.querySelector('th').colSpan,
|
||||
table.querySelector('td strong').textContent];
|
||||
})()`), ['Raw HTML table', 2, 'Highest']);
|
||||
await waitFor(() => evaluate(`document.querySelector('img[alt="HTML relative image"]')?.naturalWidth === 1`),
|
||||
'the relative image in HTML');
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').getBoundingClientRect().height > 0`), true);
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').textContent.includes('Render target')`), true);
|
||||
assert.equal(await evaluate(`(() => {
|
||||
const paths = document.querySelector('figure svg g.edgePaths');
|
||||
const labels = document.querySelector('figure svg g.edgeLabels');
|
||||
const background = labels?.querySelector('.edgeLabel rect');
|
||||
return !!(paths && labels && background && labels.textContent.includes('Transition') &&
|
||||
(paths.compareDocumentPosition(labels) & Node.DOCUMENT_POSITION_FOLLOWING) &&
|
||||
getComputedStyle(background).opacity === '1');
|
||||
})()`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
|
||||
document.querySelector('main').textContent.includes('Invalid Mermaid diagram')`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-js') && !document.querySelector('iframe')`), true);
|
||||
@@ -78,13 +132,127 @@ try {
|
||||
.every(entry => entry.name.startsWith(location.origin + '/') || entry.name.startsWith('data:'))`), true);
|
||||
await waitFor(() => evaluate(`document.querySelector('img[alt="Missing image"]')?.title === 'Image unavailable'`),
|
||||
'missing image feedback');
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => box.checked)`), [false, true]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => { box.click(); return box.checked; })`), [true, false]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => { box.click(); return box.checked; })`), [false, true]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => box.checked)`), [false, true]);
|
||||
if (artifact) {
|
||||
const { cssContentSize } = await command('Page.getLayoutMetrics');
|
||||
const { data } = await command('Page.captureScreenshot', { captureBeyondViewport: true,
|
||||
clip: { x:0, y:0, width:cssContentSize.width, height:Math.min(cssContentSize.height, 620), scale:1 } });
|
||||
await writeFile(artifact, Buffer.from(data, 'base64'));
|
||||
}
|
||||
} else if (scenario === 'startup-stalled') {
|
||||
await waitFor(() => evaluate(`document.documentElement?.dataset.startup === 'stalled'`),
|
||||
'the preview page to load without announcing readiness');
|
||||
} else if (scenario === 'reopen') {
|
||||
const heading = title === 'Reopen.md' ? 'Reopened Markdown' : 'Second Markdown';
|
||||
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
|
||||
document.querySelector('h1')?.textContent === ${JSON.stringify(heading)}`), heading);
|
||||
assert.equal(await evaluate(`performance.getEntriesByName(new URL('mermaid.js', location.href).href).length`),
|
||||
0, 'Reopening a document without diagrams must not load Mermaid');
|
||||
} else if (scenario === 'external-replacement') {
|
||||
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
|
||||
document.querySelector('main')?.textContent.trim() === 'An external replacement'`),
|
||||
'the replacement file rendered after discarding edits');
|
||||
} else if (scenario === 'diagram-reference') {
|
||||
await waitFor(() => evaluate("document.documentElement.classList.contains('rendered')"), 'rendered diagram page');
|
||||
const diagram = await evaluate(`(() => {
|
||||
const svg = document.querySelector('figure svg');
|
||||
const paths = svg?.querySelector('g.edgePaths');
|
||||
const labels = svg?.querySelector('g.edgeLabels');
|
||||
return {
|
||||
error: document.querySelector('pre code.language-mermaid')?.parentElement.previousElementSibling?.title,
|
||||
labels: [...(labels?.querySelectorAll('.edgeLabel') ?? [])]
|
||||
.map(label => label.textContent.trim()).filter(Boolean),
|
||||
paintedAbove: !!(paths && labels &&
|
||||
(paths.compareDocumentPosition(labels) & Node.DOCUMENT_POSITION_FOLLOWING)),
|
||||
opaque: [...(labels?.querySelectorAll('.edgeLabel rect') ?? [])].every(rect =>
|
||||
getComputedStyle(rect).opacity === '1'),
|
||||
};
|
||||
})()`);
|
||||
assert.equal(diagram.error, undefined, diagram.error);
|
||||
assert.deepEqual(diagram.labels.sort(), ['F3', 'F6', 'F6']);
|
||||
assert.equal(diagram.paintedAbove && diagram.opaque, true);
|
||||
if (artifact) {
|
||||
const { data } = await command('Page.captureScreenshot');
|
||||
await writeFile(artifact, Buffer.from(data, 'base64'));
|
||||
}
|
||||
} else if (scenario === 'toggle-first-task' || scenario === 'first-task-checked') {
|
||||
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
|
||||
!!document.querySelector('main li.task input')`), 'rendered Markdown task');
|
||||
if (scenario === 'toggle-first-task') {
|
||||
const target = "document.querySelector('main li.task input')";
|
||||
const before = await evaluate(target + '.checked');
|
||||
await evaluate(target + '.click()');
|
||||
await waitFor(() => evaluate(`!pendingTask && ${target}.checked !== ${before}`), 'saved Markdown task');
|
||||
}
|
||||
else
|
||||
assert.equal(await evaluate(`document.querySelector('main li.task input').checked`), true);
|
||||
} else if (scenario === 'search-menu' || scenario === 'search') {
|
||||
const searchFocused = 'document.activeElement === document.getElementById("search-query")';
|
||||
const searchClosed = 'document.getElementById("search").hidden';
|
||||
if (scenario === 'search-menu') {
|
||||
await waitFor(() => evaluate(searchFocused), 'the viewer menu opening rendered Markdown search');
|
||||
await pressKey('Escape', 'Escape', 27);
|
||||
await waitFor(() => evaluate(searchClosed), 'Escape closing only the search');
|
||||
} else {
|
||||
await pressKey('f', 'KeyF', 70, 2);
|
||||
await waitFor(() => evaluate(searchFocused), 'Ctrl+F opening search and focusing the search field');
|
||||
const status = 'document.getElementById("search-status").value';
|
||||
const active = '[...(CSS.highlights.get("markdown-search-active") || [])][0]?.toString()';
|
||||
const query = async text => {
|
||||
await evaluate('document.getElementById("search-query").select()');
|
||||
await command('Input.insertText', { text });
|
||||
};
|
||||
await query('ЗБІГ ПОШУКУ');
|
||||
assert.equal(await evaluate(status), '1 / 2');
|
||||
const toolbar = await evaluate(`({
|
||||
queryWidth: document.getElementById('search-query').getBoundingClientRect().width,
|
||||
closeRight: document.getElementById('search-close').getBoundingClientRect().right,
|
||||
viewportWidth: document.documentElement.clientWidth
|
||||
})`);
|
||||
assert.ok(toolbar.queryWidth >= 100 && toolbar.closeRight <= toolbar.viewportWidth,
|
||||
'The search controls must fit the viewer: ' + JSON.stringify(toolbar));
|
||||
assert.equal(await evaluate(active), 'Збіг пошуку');
|
||||
await pressKey('Enter', 'Enter', 13);
|
||||
assert.equal(await evaluate(status), '2 / 2');
|
||||
assert.equal(await evaluate(active), 'збіг пошуку');
|
||||
await pressKey('F3', 'F3', 114);
|
||||
assert.equal(await evaluate(status), '1 / 2');
|
||||
await pressKey('Enter', 'Enter', 13, 8);
|
||||
assert.equal(await evaluate(status), '2 / 2');
|
||||
await pressKey('F3', 'F3', 114, 8);
|
||||
assert.equal(await evaluate(status), '1 / 2');
|
||||
await evaluate('document.getElementById("search-previous").click()');
|
||||
assert.equal(await evaluate(status), '2 / 2');
|
||||
await evaluate('document.getElementById("search-next").click()');
|
||||
assert.equal(await evaluate(status), '1 / 2');
|
||||
if (artifact) {
|
||||
const { data } = await command('Page.captureScreenshot');
|
||||
await writeFile(artifact, Buffer.from(data, 'base64'));
|
||||
}
|
||||
await query('для збіг пошуку');
|
||||
assert.equal(await evaluate(status), '1 / 1');
|
||||
assert.equal(await evaluate(active), 'для збіг пошуку');
|
||||
await query('RENDER TARGET');
|
||||
assert.equal(await evaluate(status), '1 / 1');
|
||||
assert.equal(await evaluate(active), 'Render target');
|
||||
await query('[no matches]');
|
||||
assert.equal(await evaluate(status), 'No matches');
|
||||
assert.equal(await evaluate(active), undefined);
|
||||
await pressKey('Escape', 'Escape', 27);
|
||||
assert.equal(await evaluate(searchClosed), true);
|
||||
assert.equal(await evaluate('document.documentElement.classList.contains("rendered")'), true);
|
||||
await evaluate('document.getElementById("search-open").click()');
|
||||
assert.equal(await evaluate(searchFocused), true);
|
||||
await evaluate('document.getElementById("search-close").click()');
|
||||
assert.equal(await evaluate(searchClosed), true);
|
||||
}
|
||||
} else if (scenario === 'appearance-width' || scenario === 'appearance-full') {
|
||||
const width = scenario === 'appearance-full' ? 'none' : '1200px';
|
||||
await waitFor(() => evaluate(`(() => {
|
||||
const text = getComputedStyle(document.querySelector('main'));
|
||||
return getComputedStyle(document.body).maxWidth === ${JSON.stringify(width)} &&
|
||||
text.fontSize === '24px' && text.fontFamily.startsWith('Georgia,');
|
||||
})()`), 'the saved Markdown width, font family and font size');
|
||||
} else if (scenario === 'edit') {
|
||||
await command('Input.dispatchKeyEvent', { type: 'keyDown', key: 'F6', code: 'F6', windowsVirtualKeyCode: 117 });
|
||||
} else if (['follow', 'shift-follow', 'ctrl-follow'].includes(scenario)) {
|
||||
@@ -99,8 +267,9 @@ try {
|
||||
} else if (scenario === 'back' || scenario === 'forward') {
|
||||
await waitFor(() => evaluate(`!document.getElementById('${scenario}').disabled`), scenario);
|
||||
await evaluate(`document.getElementById('${scenario}').click()`);
|
||||
} else if (scenario === 'cycle') {
|
||||
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers:2, windowsVirtualKeyCode:9});
|
||||
} else if (scenario === 'cycle' || scenario === 'cycle-reverse') {
|
||||
const modifiers = scenario === 'cycle-reverse' ? 10 : 2;
|
||||
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers, windowsVirtualKeyCode:9});
|
||||
} else if (scenario === 'close') {
|
||||
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'w', code:'KeyW', modifiers:2, windowsVirtualKeyCode:87});
|
||||
} else {
|
||||
|
||||
@@ -57,7 +57,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
||||
return font;
|
||||
};
|
||||
dialogs.confirmExisting=[](HWND){return true;};
|
||||
dialogs.confirmSave=[](HWND)->INT_PTR {return IDYES;};
|
||||
dialogs.confirmSave=[](HWND,bool)->INT_PTR {return IDYES;};
|
||||
dialogs.message=[](HWND,const wchar_t *message){log(message);};
|
||||
dialogs.dismissOwned=[](HWND){return false;};
|
||||
files::openTextWindow(owner,document,false,dialogs,&peer);
|
||||
|
||||
@@ -11,7 +11,16 @@ public static class PanelFrameWindow {
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
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;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
@@ -38,11 +47,10 @@ function Read-Strip($X, $Y, $Width, $Height) {
|
||||
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
|
||||
$previousDpi = [PanelFrameWindow]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
try {
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
for ($attempt = 0; $attempt -lt 50; $attempt++) {
|
||||
$process.Refresh()
|
||||
$window = $process.MainWindowHandle
|
||||
if ($window -and $keyboard.AppActivate($process.Id)) { break }
|
||||
if ($window -and [PanelFrameWindow]::Activate($window)) { break }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
Start-Sleep -Milliseconds 300
|
||||
@@ -67,10 +75,19 @@ try {
|
||||
$x = $list.Left + 16
|
||||
$top = @(Read-Strip $x ($path.Top + [Math]::Floor(($path.Bottom - $path.Top) / 2) - 2) 1 4)
|
||||
if (($top -join ',') -ne ($side -join ',')) { throw "Panel $panel has an inconsistent top frame." }
|
||||
$start = $list.Left + [int](($list.Right - $list.Left) / 2)
|
||||
$width = $list.Right - $start
|
||||
$bodyPixels = @(Read-Strip $start ($list.Top + 2) $width 1)
|
||||
$headerPixels = @(Read-Strip $start ($header.Top + 2) $width 1)
|
||||
$bodyDivider = [Array]::IndexOf($bodyPixels, $side[0])
|
||||
$headerDivider = [Array]::IndexOf($headerPixels, $side[0])
|
||||
if ($bodyDivider -lt 0 -or $headerDivider -ne $bodyDivider) {
|
||||
throw "Panel $panel Size column divider is misaligned. Header offset: $headerDivider. Body offset: $bodyDivider."
|
||||
}
|
||||
$bottom = @(Read-Strip $x ($list.Bottom + 4) 1 ($header.Bottom - $header.Top + 6))
|
||||
$bottom = $bottom[($bottom.Count - 4)..($bottom.Count - 1)]
|
||||
if (($bottom -join ',') -ne ($side -join ',')) { throw "Panel $panel has an inconsistent bottom frame." }
|
||||
Write-Output "Panel $panel double frame verified on screen."
|
||||
Write-Output "Panel $panel double frame and Size column divider verified on screen."
|
||||
}
|
||||
} finally {
|
||||
if ($previousDpi) { [void][PanelFrameWindow]::SetThreadDpiAwarenessContext($previousDpi) }
|
||||
|
||||
+150
-33
@@ -1,4 +1,4 @@
|
||||
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly)
|
||||
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly,[switch]$CreateFileOnly)
|
||||
$ErrorActionPreference='Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @"
|
||||
@@ -19,6 +19,21 @@ public static class SearchArrowTest {
|
||||
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags);
|
||||
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hwnd);
|
||||
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
|
||||
[DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr hwnd, IntPtr rect, bool erase);
|
||||
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
|
||||
[DllImport("gdi32.dll")] static extern bool SetPixelV(IntPtr dc, int x, int y, uint color);
|
||||
public static bool EditorMenuProbe(IntPtr window, bool write) {
|
||||
const uint color = 0x00ff00ff;
|
||||
var dc = GetDC(window);
|
||||
if (dc == IntPtr.Zero) throw new InvalidOperationException("Cannot sample the editor.");
|
||||
try {
|
||||
if (write && !SetPixelV(dc, 4, 4, color))
|
||||
throw new InvalidOperationException("Cannot mark the editor menu.");
|
||||
return GetPixel(dc, 4, 4) == color;
|
||||
} finally { ReleaseDC(window, dc); }
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
|
||||
@@ -242,7 +257,7 @@ foreach($name in 'A.txt','B.txt','C.txt','D.txt'){
|
||||
$copy=Join-Path $scratch 'KSwitcher.Files.search-arrow-test.exe'
|
||||
Copy-Item -LiteralPath $Executable -Destination $copy
|
||||
$profile=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
|
||||
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement','FileStyles'
|
||||
$saved=@{}
|
||||
foreach($name in $keysToRestore){
|
||||
if($name -in $profile.GetValueNames()){
|
||||
@@ -256,19 +271,130 @@ try {
|
||||
$profile.SetValue('RightPath',$rightFixture)
|
||||
$profile.DeleteValue('LeftCursor',$false)
|
||||
$profile.DeleteValue('RightCursor',$false)
|
||||
$styles='[{"extension":".txt","background":3158064,"states":[{},{},{"background":3166352}]}]'
|
||||
$profile.SetValue('FileStyles',[Text.Encoding]::UTF8.GetBytes($styles),'Binary')
|
||||
$process=Start-Process -FilePath $copy -ArgumentList '--terminal-trace' -PassThru -WindowStyle Normal
|
||||
$paintTrace=Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
|
||||
$previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$main = Wait-Until { Find-Window 'KSwitcher.Files' $process.Id }
|
||||
$leftPanel=[SearchArrowTest]::GetDlgItem($main,102)
|
||||
$rightPanel=[SearchArrowTest]::GetDlgItem($main,103)
|
||||
$clicks=if(!$KeyboardCursorOnly){
|
||||
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
|
||||
# Initial directory scans repaint both panels when their results arrive.
|
||||
[void](Wait-Until {
|
||||
[SearchArrowTest]::SendText($leftPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0 -and
|
||||
[SearchArrowTest]::SendText($rightPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0
|
||||
})
|
||||
if ($CreateFileOnly) {
|
||||
function Assert-DialogSurface($Dialog, [int]$Red, [int]$Green) {
|
||||
$bounds=Read-Bounds $Dialog
|
||||
$bitmap=[Drawing.Bitmap]::new(1,1)
|
||||
try {
|
||||
$graphics=[Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
[void](Wait-Until {
|
||||
$graphics.CopyFromScreen(($bounds.Left+4),($bounds.Top+4),0,0,$bitmap.Size)
|
||||
$pixel=$bitmap.GetPixel(0,0)
|
||||
$pixel.R -eq $Red -and $pixel.G -eq $Green -and $pixel.B -eq $Green
|
||||
})
|
||||
} finally { $graphics.Dispose() }
|
||||
} finally { $bitmap.Dispose() }
|
||||
}
|
||||
$keyboard=New-Object -ComObject WScript.Shell
|
||||
[void](Wait-Until { $keyboard.AppActivate($process.Id) })
|
||||
$keyboard.SendKeys('+{F4}')
|
||||
$open=Wait-Until { Find-Window '#32770' $process.Id 461 }
|
||||
Assert-DialogSurface $open 192 192
|
||||
Post $open 0x111 1
|
||||
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
|
||||
$title=[Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($editor,0xD,$title.Capacity,$title)
|
||||
if ($title.ToString() -notmatch '(New_File_[0-9-]+_[0-9.]+\.txt)$') { throw "Missing generated name in $title." }
|
||||
$generated=$Matches[1]
|
||||
if (Test-Path -LiteralPath (Join-Path $scratch $generated)) { throw 'Opening a draft created a file.' }
|
||||
$control=Wait-Until { [SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[NullString]::Value) }
|
||||
Start-Sleep -Milliseconds 150
|
||||
if (![SearchArrowTest]::EditorMenuProbe($editor,$true)) { throw 'Cannot mark the editor menu for the repaint check.' }
|
||||
foreach($ch in 'First'.ToCharArray()){Post $control 0x102 ([int]$ch)}
|
||||
Post $control 0x100 13
|
||||
foreach($ch in 'Second'.ToCharArray()){Post $control 0x102 ([int]$ch)}
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($control,2159,0,0).ToInt64() })
|
||||
Start-Sleep -Milliseconds 150
|
||||
$menuWasPreserved=[SearchArrowTest]::EditorMenuProbe($editor,$false)
|
||||
[void][SearchArrowTest]::InvalidateRect($editor,0,$false)
|
||||
if (!$menuWasPreserved) { throw 'Typing in a draft repainted the unchanged editor menu.' }
|
||||
foreach($cancel in $true,$false) {
|
||||
Post $control 0x100 27
|
||||
$confirm=Wait-Until { Find-Window '#32770' $process.Id 6 }
|
||||
Assert-DialogSurface $confirm 128 0
|
||||
Post $confirm 0x111 6
|
||||
$save=Wait-Until { Find-Window '#32770' $process.Id 464 }
|
||||
Assert-DialogSurface $save 192 192
|
||||
$name=[SearchArrowTest]::GetDlgItem($save,461)
|
||||
$current=[Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($name,0xD,$current.Capacity,$current)
|
||||
if ($current.ToString() -ne $generated) { throw 'Save options did not carry the generated name.' }
|
||||
if ($cancel) {
|
||||
Post $save 0x111 2
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindow($save) -and [SearchArrowTest]::IsWindow($editor) })
|
||||
continue
|
||||
}
|
||||
[void][SearchArrowTest]::SendText($name,0x0C,0,'created.txt')
|
||||
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,464),0xF1,1,0)
|
||||
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,472),0xF5,0,0)
|
||||
Post $save 0x111 1
|
||||
}
|
||||
$result=Join-Path $scratch 'created.txt'
|
||||
[void](Wait-Until { (Test-Path -LiteralPath $result) -and ![SearchArrowTest]::IsWindow($editor) })
|
||||
if ([Convert]::ToHexString([IO.File]::ReadAllBytes($result)) -ne 'EFBBBF46697273740A5365636F6E64') {
|
||||
throw 'The saved bytes must contain a UTF-8 BOM and LF line endings.'
|
||||
}
|
||||
Write-Output 'Verified Shift+F4, the generated name, Escape confirmation, cancellation, and Save options.'
|
||||
return
|
||||
}
|
||||
if (!$KeyboardCursorOnly) {
|
||||
$leftPath = [SearchArrowTest]::GetDlgItem($main,142)
|
||||
foreach ($step in @(@{ Row='[Right fixture]'; Path=$rightFixture }, @{ Row='..'; Path=$scratch })) {
|
||||
Select-Row $leftPanel $step.Row
|
||||
Start-Sleep -Milliseconds 150
|
||||
$lineCount = @(Get-Content -LiteralPath $paintTrace).Count
|
||||
Post $leftPanel 0x100 13
|
||||
[void](Wait-Until {
|
||||
$path = [Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($leftPath,0xD,$path.Capacity,$path)
|
||||
$path.ToString() -eq $step.Path
|
||||
})
|
||||
[void](Wait-Until {
|
||||
$highlight = Read-PanelHighlights $paintTrace $lineCount
|
||||
@($highlight.Keys -like '0/*').Count -gt 0
|
||||
})
|
||||
Start-Sleep -Milliseconds 150
|
||||
$draws = (Read-PanelHighlights $paintTrace $lineCount).Keys
|
||||
if ($draws -like '1/*') { throw "Opening $($step.Row) repainted rows in the other panel." }
|
||||
}
|
||||
Write-Output 'Verified folder navigation repaints only the panel that changes directories.'
|
||||
}
|
||||
$clicks=if(!$KeyboardCursorOnly){
|
||||
@(@{Panel=$leftPanel; Index=0},
|
||||
@{Panel=$rightPanel; Index=1; Label='A.txt'},
|
||||
@{Panel=$leftPanel; Index=0; Label='A.txt'},
|
||||
@{Panel=$rightPanel; Index=1; Label='..'; UnfocusedStyle=$true},
|
||||
@{Panel=$rightPanel; Index=1; Label='A.txt'})
|
||||
}
|
||||
$activeIndex=0
|
||||
foreach($check in $clicks) {
|
||||
$before=[SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32()
|
||||
$top=[SearchArrowTest]::Send($check.Panel,0x18E,0,0).ToInt32()
|
||||
$row=if($before -eq $top){$top+1}else{$top}
|
||||
$row=if($check.Label){[SearchArrowTest]::SendText($check.Panel,0x1A2,-1,$check.Label).ToInt32()}
|
||||
elseif($before -eq $top){$top+1}else{$top}
|
||||
if($row -lt 0 -or $row -eq $before){throw 'The click fixture must move the cursor.'}
|
||||
$previousKey="$($check.Index)/$before"
|
||||
$expected=@{"$($check.Index)/$row"='1'}
|
||||
if($check.Index -ne $activeIndex){
|
||||
$source=if($activeIndex -eq 0){$leftPanel}else{$rightPanel}
|
||||
$sourceRow=[SearchArrowTest]::Send($source,0x188,0,0).ToInt32()
|
||||
$expected["$activeIndex/$sourceRow"]='0'
|
||||
}
|
||||
if($check.Index -eq $activeIndex -or $check.UnfocusedStyle){$expected[$previousKey]='0'}
|
||||
[void](Wait-Until { Test-Path -LiteralPath $paintTrace })
|
||||
Start-Sleep -Milliseconds 150
|
||||
$lineCount=@(Get-Content -LiteralPath $paintTrace).Count
|
||||
@@ -276,14 +402,15 @@ try {
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32() -eq $row })
|
||||
Start-Sleep -Milliseconds 150
|
||||
$highlight=Read-PanelHighlights $paintTrace $lineCount
|
||||
$draws=@($highlight.Keys)
|
||||
if("$($check.Index)/$row" -notin $draws -or $draws.Count -gt 3){
|
||||
throw "Clicking a row repainted unrelated file rows. Drawn rows: $draws"
|
||||
if($highlight.Count -ne $expected.Count -or
|
||||
@($expected.Keys | Where-Object {$highlight[$_] -ne $expected[$_]}).Count){
|
||||
throw "Unexpected cursor redraw. Expected rows: $($expected.Keys -join ', '). Drawn rows: $($highlight.Keys -join ', ')."
|
||||
}
|
||||
if($highlight["$($check.Index)/$row"] -ne '1' -or
|
||||
($before -ge $top -and $highlight["$($check.Index)/$before"] -ne '0')){
|
||||
throw 'The new row must be painted active and the previous visible row must lose its highlight.'
|
||||
if($check.Index -ne $activeIndex -and (Get-Content -LiteralPath $paintTrace | Select-Object -Skip $lineCount |
|
||||
Where-Object {$_ -match "^\d+ panel-draw $($check.Index) $before 1 "})){
|
||||
throw 'The old row in the destination panel flashed as the active cursor.'
|
||||
}
|
||||
$activeIndex=$check.Index
|
||||
}
|
||||
if($clicks){Write-Output 'Verified file clicks repaint only cursor rows in the active pane and when changing panes.'}
|
||||
Post $main 0x111 132
|
||||
@@ -319,22 +446,7 @@ try {
|
||||
Post $commandMenu 0x100 27
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindowVisible($commandMenu) })
|
||||
Write-Output 'Verified Commands grouping, arrow navigation, and inert separators.'
|
||||
$panel = Wait-Until { $handle = [SearchArrowTest]::GetDlgItem($main,102); if ($handle -ne [IntPtr]::Zero) { $handle } }
|
||||
$pathControl = [SearchArrowTest]::GetDlgItem($main,142)
|
||||
$pathText = [Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($pathControl,0xD,$pathText.Capacity,$pathText)
|
||||
$path=$pathText.ToString()
|
||||
if ([IO.Path]::GetPathRoot($path) -ne [IO.Path]::GetPathRoot($scratch)) {
|
||||
throw 'Select a local left-panel folder on the test executable drive before running this interactive test.'
|
||||
}
|
||||
foreach ($component in $path.Substring(3).Split('\',[System.StringSplitOptions]::RemoveEmptyEntries)) {
|
||||
Select-Row $panel '..'
|
||||
[void][SearchArrowTest]::Send($panel,0x100,13,0)
|
||||
}
|
||||
foreach ($component in $scratch.Substring(3).Split('\')) {
|
||||
Select-Row $panel "[$component]"
|
||||
[void][SearchArrowTest]::Send($panel,0x100,13,0)
|
||||
}
|
||||
$panel = $leftPanel
|
||||
$fixtureRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,([IO.Path]::GetFileName($fixture))).ToInt32()
|
||||
Click-PanelRow $panel $fixtureRow
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($panel,0x188,0,0).ToInt32() -eq $fixtureRow })
|
||||
@@ -421,10 +533,10 @@ try {
|
||||
if (!(Test-Path -LiteralPath (Join-Path $scratch $newFolder) -PathType Container)) {
|
||||
throw 'F7 did not create the folder in the active panel.'
|
||||
}
|
||||
$newRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,"[$newFolder]")
|
||||
if ($newRow.ToInt64() -lt 0 -or [SearchArrowTest]::Send($panel,0x188,0,0) -ne $newRow) {
|
||||
throw 'F7 did not select the new folder.'
|
||||
}
|
||||
[void](Wait-Until {
|
||||
$newRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,"[$newFolder]")
|
||||
$newRow.ToInt64() -ge 0 -and [SearchArrowTest]::Send($panel,0x188,0,0) -eq $newRow
|
||||
})
|
||||
Post $main 0x111 115
|
||||
$makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 }
|
||||
$nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361)
|
||||
@@ -526,6 +638,10 @@ try {
|
||||
!(Test-Path -LiteralPath (Join-Path $linkPath 'link-target.txt') -PathType Leaf)) {
|
||||
throw "F7 did not create a $expected pointing to Alpha."
|
||||
}
|
||||
[void](Wait-Until {
|
||||
$linkRow = [SearchArrowTest]::SendText($panel,0x1A2,-1,"[$linkName]")
|
||||
$linkRow.ToInt64() -ge 0 -and [SearchArrowTest]::Send($panel,0x188,0,0) -eq $linkRow
|
||||
})
|
||||
}
|
||||
Write-Output 'Verified F7 history, quoted batch names, and directory link handling.'
|
||||
Select-Row $panel ([IO.Path]::GetFileName($fixture))
|
||||
@@ -649,6 +765,7 @@ try {
|
||||
} finally { $bitmap.Dispose() }
|
||||
}
|
||||
|
||||
Select-Row $panel ([IO.Path]::GetFileName($fixture))
|
||||
Post $panel 0x100 0x73
|
||||
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
|
||||
$firstControl=[SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[System.Management.Automation.Language.NullString]::Value)
|
||||
@@ -684,8 +801,8 @@ try {
|
||||
if ([SearchArrowTest]::GetWindow($otherEditor,4) -ne [IntPtr]::Zero) { throw 'The second editor is owned.' }
|
||||
$editorIdentity=[SearchArrowTest]::TaskbarIdentity($editor)
|
||||
$otherIdentity=[SearchArrowTest]::TaskbarIdentity($otherEditor)
|
||||
if (!$editorIdentity -or !$otherIdentity -or $editorIdentity -eq $otherIdentity) {
|
||||
throw 'Editor windows do not have distinct Windows taskbar identities.'
|
||||
if ($editorIdentity -cne 'HrynCo.KSwitcher.Files.Editor' -or $otherIdentity -cne $editorIdentity) {
|
||||
throw 'Both editor windows must use the Editor group on the Windows taskbar.'
|
||||
}
|
||||
Post $otherEditor 0x10 0
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindow($otherEditor) })
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using ks::files::TextDocument;
|
||||
using ks::files::TextEncoding;
|
||||
using ks::files::TextLineEnding;
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -141,6 +143,43 @@ void sparseFile(const fs::path &file)
|
||||
document.stage(index, "edited");
|
||||
check(document.readPage(index) == "edited", "Stage an edit past 4 GiB");
|
||||
}
|
||||
|
||||
void saveDraft(const fs::path &file)
|
||||
{
|
||||
TextDocument draft({});
|
||||
check(draft.readPage(0).empty() && draft.pages()==1, "Start with an empty draft");
|
||||
draft.stage(0,"one\r\ntwo\rthree\n");
|
||||
writeFile(file,"existing");
|
||||
bool rejected{};
|
||||
try {draft.saveNew(file,{});}
|
||||
catch(const std::exception &) {rejected=true;}
|
||||
check(rejected && draft.modified() && readFile(file)=="existing", "Preserve a conflicting file and the draft");
|
||||
fs::remove(file);
|
||||
check(draft.saveNew(file,{TextEncoding::utf8,true,TextLineEnding::lf}), "Save a draft as a new file");
|
||||
check(readFile(file)=="\xef\xbb\xbfone\ntwo\nthree\n" && draft.readPage(0)=="one\ntwo\nthree\n",
|
||||
"Save a UTF-8 signature and normalize mixed line endings");
|
||||
draft.stage(0,"after");
|
||||
check(draft.save() && readFile(file)=="\xef\xbb\xbf" "after", "Edit normally after the first save");
|
||||
|
||||
const auto ansiFile=file.parent_path()/L"windows1252.txt";
|
||||
TextDocument ansiDraft({});
|
||||
ansiDraft.stage(0,"caf\xc3\xa9\n");
|
||||
check(ansiDraft.saveNew(ansiFile,{TextEncoding::windows1252,false,TextLineEnding::crlf}),
|
||||
"Save a draft in Windows-1252");
|
||||
check(readFile(ansiFile)=="caf\xe9\r\n" && ansiDraft.readPage(0)=="caf\xc3\xa9\r\n",
|
||||
"Round-trip Windows-1252 text and CRLF");
|
||||
TextDocument ansiReader(ansiFile,false,TextEncoding::windows1252);
|
||||
check(ansiReader.readPage(0)=="caf\xc3\xa9\r\n", "Open an existing file with an explicit code page");
|
||||
|
||||
const auto unicodeFile=file.parent_path()/L"utf16be.txt";
|
||||
TextDocument unicodeDraft({});
|
||||
unicodeDraft.stage(0,"a\n");
|
||||
check(unicodeDraft.saveNew(unicodeFile,{TextEncoding::utf16be,true,TextLineEnding::cr}),
|
||||
"Save a UTF-16 draft with a signature");
|
||||
TextDocument unicodeReader(unicodeFile,false);
|
||||
check(readFile(unicodeFile)==std::string("\xfe\xff\0a\0\r",6) && unicodeReader.readPage(0)=="a\r",
|
||||
"Detect the UTF-16 signature and read CR line endings");
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
@@ -151,6 +190,7 @@ int main()
|
||||
editsAcrossPages(fixture.directory / L"pages.txt");
|
||||
unicodeBoundaries(fixture.directory / L"unicode.txt");
|
||||
rejectExternalReplacement(fixture.directory / L"external.txt");
|
||||
saveDraft(fixture.directory / L"created.txt");
|
||||
sparseFile(fixture.directory / L"5gib.log");
|
||||
std::cout << "Files text document regressions passed.\n";
|
||||
}
|
||||
|
||||
+294
-182
@@ -7,6 +7,8 @@
|
||||
#include <commctrl.h>
|
||||
#include <iostream>
|
||||
#include <cmath>
|
||||
#include "input_pause.h"
|
||||
#include "settings_ui.h"
|
||||
static int settingsCloseChoice = IDCANCEL;
|
||||
static int settingsClosePrompts = 0;
|
||||
static void CALLBACK answerSettingsClose(HWND, UINT, UINT_PTR, DWORD)
|
||||
@@ -27,6 +29,45 @@ LRESULT CALLBACK countControlMoves(HWND w, UINT message, WPARAM wp, LPARAM lp, U
|
||||
}
|
||||
namespace ks {
|
||||
struct InputRegressionAccess {
|
||||
static LRESULT CALLBACK probeInput(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR context) {
|
||||
auto &app = *reinterpret_cast<App *>(context);
|
||||
static bool queuedSnippet = false;
|
||||
// Queue a real expansion just before TrackPopupMenu returns the pause command.
|
||||
if (msg == WM_EXITMENULOOP && app.inputState == App::InputState::Active)
|
||||
queuedSnippet = app.queueSnippet(w, 0, 2, w);
|
||||
if (msg == ProbeTrayIcon) return trayIconMatchesInput(app.trayBaseIcon(16, 16), wp != 0);
|
||||
if (msg != ProbeInputState) return DefSubclassProc(w, msg, wp, lp);
|
||||
// Also exercise settings/layout updates that would normally re-register shortcuts.
|
||||
if (wp && app.inputState == App::InputState::Paused) {
|
||||
app.applySettings(app.settings);
|
||||
app.reloadLayouts();
|
||||
app.dispatch(Toggle);
|
||||
app.pasteEntry(L"fixture", false);
|
||||
const auto version = app.inputVersion.load();
|
||||
KBDLLHOOKSTRUCT key{};
|
||||
key.vkCode = 'A';
|
||||
if (app.handleKeyboard(key, true, 0) || app.inputVersion != version) return 0;
|
||||
const std::string status = R"({"action":"status"})";
|
||||
const auto response = app.lanCommand(Bytes(status.begin(), status.end()));
|
||||
if (std::string(response.begin(), response.end()).find("Input processing paused") == std::string::npos)
|
||||
return 0;
|
||||
}
|
||||
const bool bound = app.isHotkey(VK_F22, MOD_CONTROL | MOD_SHIFT);
|
||||
if (app.inputState == App::InputState::Active && app.keyboardHook && app.mouseHook &&
|
||||
app.filesHotkeyId && bound) return 1;
|
||||
if (app.inputState == App::InputState::Paused && !app.keyboardHook && !app.mouseHook &&
|
||||
!app.filesHotkeyId && !bound && !app.busy && app.snippetPending == -1 &&
|
||||
!app.snippetTyping && queuedSnippet && !app.transformAttempt) return 2;
|
||||
return 0;
|
||||
}
|
||||
static void CALLBACK installProbe(HWND, UINT, UINT_PTR timer, DWORD) {
|
||||
auto app = App::current;
|
||||
if (app && app->window && SetWindowSubclass(app->window, probeInput, 1, reinterpret_cast<DWORD_PTR>(app))) {
|
||||
KillTimer(app->window, 5); // Keep the input fixture independent of update checks.
|
||||
SetTimer(app->window, 2, 60000, nullptr);
|
||||
KillTimer(nullptr, timer);
|
||||
}
|
||||
}
|
||||
static int snippetChoice(App &a, const std::vector<Snippet> &snippets) {
|
||||
a.settings.snippets=snippets; a.settings.autoCorrect=false; a.busy=false;
|
||||
a.snippetPending=-1; a.typingTarget=nullptr; a.snippetTyping=false;
|
||||
@@ -169,6 +210,20 @@ struct InputRegressionAccess {
|
||||
};
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
if (argc == 2 && std::string(argv[1]) == "--input-pause") return testInputPause();
|
||||
if (argc == 2 && std::string(argv[1]) == "--input-pause-resident") {
|
||||
// The driver copies this binary alone into a fresh fixture folder.
|
||||
auto folder = std::filesystem::path(ks::executable()).parent_path();
|
||||
if (!folder.filename().wstring().starts_with(L"KSwitcher-input-pause-")) return 1;
|
||||
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
ks::App app(GetModuleHandleW(nullptr), false, folder / L"data");
|
||||
app.settings.toggle = L"Ctrl+Shift+F22";
|
||||
app.settings.filesHotkey = L"Ctrl+Shift+F23";
|
||||
app.settings.snippets = {{L";t", L"fixture"}};
|
||||
app.settings.history = app.settings.autoCorrect = app.settings.autostart = false;
|
||||
SetTimer(nullptr, 0, 10, ks::InputRegressionAccess::installProbe);
|
||||
return app.execute();
|
||||
}
|
||||
if (argc == 2 && std::string(argv[1]) == "--update-check") {
|
||||
try {
|
||||
auto result = ks::runUpdate(false, {});
|
||||
@@ -807,50 +862,44 @@ int main(int argc, char **argv) {
|
||||
ks::showSettings(app,false);
|
||||
{
|
||||
auto settings = app.settingsWindow;
|
||||
auto tabs = GetDlgItem(settings, 260);
|
||||
auto capture = GetDlgItem(settings, 737);
|
||||
auto events = GetDlgItem(settings, 733);
|
||||
auto visible = [&](int id) { return (GetWindowLongPtrW(GetDlgItem(settings, id), GWL_STYLE) & WS_VISIBLE) != 0; };
|
||||
auto selectPage = [&](int index) {
|
||||
TabCtrl_SetCurSel(tabs, index);
|
||||
NMHDR changed{tabs, 260, TCN_SELCHANGE};
|
||||
SendMessageW(settings, WM_NOTIFY, 260, reinterpret_cast<LPARAM>(&changed));
|
||||
};
|
||||
RECT lastTab{}, tabClient{};
|
||||
GetClientRect(tabs, &tabClient);
|
||||
require(TabCtrl_GetItemCount(tabs) == 10 && TabCtrl_GetItemRect(tabs, 9, &lastTab) &&
|
||||
lastTab.right <= tabClient.right, "all Settings tabs fit in one row");
|
||||
auto navigation = settingsNavigation(settings);
|
||||
auto pane = settingsViewport(settings);
|
||||
auto capture = GetDlgItem(pane, 737);
|
||||
auto events = GetDlgItem(pane, 733);
|
||||
auto visible = [&](int id) { return (GetWindowLongPtrW(GetDlgItem(pane, id), GWL_STYLE) & WS_VISIBLE) != 0; };
|
||||
auto selectPage = [&](int index) { selectSettingsPage(settings, index); };
|
||||
require(TreeView_GetCount(navigation) == 18, "all Settings sections are listed");
|
||||
selectPage(3);
|
||||
require(visible(257) && !visible(301), "OCR options are in Clipboard");
|
||||
selectPage(6);
|
||||
require(visible(258) && !visible(262), "Sync has its own tab");
|
||||
require(visible(271) && !visible(262), "Sync opens the embedded OpenBao page");
|
||||
selectPage(7);
|
||||
require(visible(262) && !visible(258), "Computers has its own tab");
|
||||
require(!visible(262) && !visible(271), "Computers parent hides embedded controls");
|
||||
selectPage(10);
|
||||
require(visible(262), "Manage computers shows the embedded panel");
|
||||
selectPage(8);
|
||||
require(visible(208) && visible(256), "logging controls are in Diagnostics");
|
||||
selectPage(4);
|
||||
require(visible(301) && visible(303) && visible(318), "Snippets has an inline editor and its own Save button");
|
||||
require(visible(301) && visible(303) && visible(320) && !GetDlgItem(pane, 318),
|
||||
"Snippets uses the inline editor and the shared Save button");
|
||||
const bool awake = app.settings.awake;
|
||||
SendDlgItemMessageW(settings, 205, BM_SETCHECK, awake ? BST_UNCHECKED : BST_CHECKED, 0);
|
||||
SendDlgItemMessageW(pane, 205, BM_SETCHECK, awake ? BST_UNCHECKED : BST_CHECKED, 0);
|
||||
SendMessageW(settings, WM_COMMAND, 310, 0);
|
||||
SetDlgItemTextW(settings, 302, L";inline-fixture");
|
||||
SetDlgItemTextW(settings, 303, L"inline snippet");
|
||||
SetDlgItemTextW(pane, 302, L";inline-fixture");
|
||||
SetDlgItemTextW(pane, 303, L"inline snippet");
|
||||
selectPage(0);
|
||||
selectPage(4);
|
||||
SendMessageW(settings, WM_COMMAND, 318, 0);
|
||||
wchar_t replacement[64]{};
|
||||
GetDlgItemTextW(pane, 303, replacement, std::size(replacement));
|
||||
require(app.settings.awake == awake && IsWindowEnabled(GetDlgItem(settings, IDOK)) &&
|
||||
std::any_of(app.settings.snippets.begin(), app.settings.snippets.end(), [](const ks::Snippet &snippet) {
|
||||
return snippet.trigger == L";inline-fixture" && snippet.text == L"inline snippet";
|
||||
}), "saving inline snippets preserves the unsaved settings draft across tab changes");
|
||||
SendDlgItemMessageW(settings, 205, BM_SETCHECK, awake ? BST_CHECKED : BST_UNCHECKED, 0);
|
||||
std::wstring(replacement) == L"inline snippet",
|
||||
"changing sections preserves the unsaved settings and snippet drafts");
|
||||
SendDlgItemMessageW(pane, 205, BM_SETCHECK, awake ? BST_CHECKED : BST_UNCHECKED, 0);
|
||||
SendMessageW(settings, WM_COMMAND, 311, 0);
|
||||
SendMessageW(settings, WM_COMMAND, 318, 0);
|
||||
selectPage(0);
|
||||
require(!(GetWindowLongPtrW(capture, GWL_STYLE) & WS_VISIBLE),
|
||||
"mouse detection is hidden on General");
|
||||
TabCtrl_SetCurSel(tabs, 5);
|
||||
NMHDR changed{tabs, 260, TCN_SELCHANGE};
|
||||
SendMessageW(settings, WM_NOTIFY, 260, reinterpret_cast<LPARAM>(&changed));
|
||||
selectPage(5);
|
||||
require(GetWindowLongPtrW(capture, GWL_STYLE) & WS_VISIBLE,
|
||||
"mouse detection is visible on Mouse");
|
||||
RECT suggestedSettings{};
|
||||
@@ -864,7 +913,7 @@ int main(int argc, char **argv) {
|
||||
!(GetWindowLongPtrW(events, GWL_STYLE) & WS_HSCROLL),
|
||||
"a DPI resize keeps both settings and the action table free of unnecessary scrollbars");
|
||||
RECT profilesBounds{}, eventsBounds{};
|
||||
require(GetWindowRect(GetDlgItem(settings, 731), &profilesBounds) &&
|
||||
require(GetWindowRect(GetDlgItem(pane, 731), &profilesBounds) &&
|
||||
GetWindowRect(events, &eventsBounds) &&
|
||||
profilesBounds.top == eventsBounds.top && profilesBounds.bottom == eventsBounds.bottom &&
|
||||
profilesBounds.right - profilesBounds.left == eventsBounds.right - eventsBounds.left,
|
||||
@@ -874,14 +923,14 @@ int main(int argc, char **argv) {
|
||||
require(editor && SendDlgItemMessageW(editor, 734, CB_GETCOUNT, 0, 0) == 8,
|
||||
"Global actions do not include inheritance");
|
||||
SendMessageW(editor, WM_COMMAND, IDCANCEL, 0);
|
||||
require(!GetDlgItem(settings, 741) && !GetDlgItem(settings, 732) && !GetDlgItem(settings, 745),
|
||||
require(!GetDlgItem(pane, 741) && !GetDlgItem(pane, 732) && !GetDlgItem(pane, 745),
|
||||
"applications are chosen in the action editor only");
|
||||
for (auto message : {WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_XBUTTONUP})
|
||||
SendMessageW(capture, message, MAKEWPARAM(0, XBUTTON2), 0);
|
||||
require(ListView_GetNextItem(events, -1, LVNI_SELECTED) == 4,
|
||||
"mouse button capture selects the second side button");
|
||||
wchar_t detected[100]{};
|
||||
GetDlgItemTextW(settings, 738, detected, 100);
|
||||
GetDlgItemTextW(pane, 738, detected, 100);
|
||||
require(std::wstring(detected) == L"Window event: XButton2 | Presses: 2",
|
||||
"detection shows the last button and counts repeated presses");
|
||||
SendMessageW(capture, WM_MBUTTONDBLCLK, 0, 0);
|
||||
@@ -911,7 +960,7 @@ int main(int argc, char **argv) {
|
||||
SendDlgItemMessageW(editor, 747, ks::CaptureHotkeyMessage, VK_TAB, MOD_CONTROL);
|
||||
require(!GetDlgItem(editor, 748), "the action editor has no application list");
|
||||
SendMessageW(editor, WM_COMMAND, IDOK, 0);
|
||||
const auto profiles = GetDlgItem(settings, 731);
|
||||
const auto profiles = GetDlgItem(pane, 731);
|
||||
require(ListView_GetItemCount(profiles) == 1 &&
|
||||
IsWindowEnabled(GetDlgItem(settings, IDOK)), "adding a mouse binding enables Save");
|
||||
wchar_t action[80]{};
|
||||
@@ -1001,23 +1050,15 @@ int main(int argc, char **argv) {
|
||||
"profile row bounds are available");
|
||||
const int nameWidth = ListView_GetColumnWidth(profiles, 1);
|
||||
const int rowCenter = (profileRow.top + profileRow.bottom) / 2;
|
||||
int checkboxX = -1;
|
||||
for (int x = nameWidth; x < profileRow.right; ++x)
|
||||
{
|
||||
LVHITTESTINFO hit{};
|
||||
hit.pt = {x, rowCenter};
|
||||
if (ListView_HitTest(profiles, &hit) == 1 && (hit.flags & LVHT_ONITEMSTATEICON))
|
||||
{
|
||||
checkboxX = x;
|
||||
break;
|
||||
}
|
||||
}
|
||||
require(checkboxX >= nameWidth && checkboxX < nameWidth + ListView_GetColumnWidth(profiles, 0) &&
|
||||
ListView_GetCheckState(profiles, 1),
|
||||
"the enabled checkbox is hit-testable in the second column");
|
||||
const int checkboxX = nameWidth + ListView_GetColumnWidth(profiles, 0) / 2;
|
||||
require(ListView_GetCheckState(profiles, 1), "the new profile is enabled");
|
||||
SendMessageW(profiles, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(checkboxX, rowCenter));
|
||||
SendMessageW(profiles, WM_LBUTTONUP, 0, MAKELPARAM(checkboxX, rowCenter));
|
||||
require(!ListView_GetCheckState(profiles, 1), "clicking the row checkbox disables its profile");
|
||||
require(!ListView_GetCheckState(profiles, 1), "clicking the centered checkbox disables its profile");
|
||||
SendMessageW(profiles, WM_KEYDOWN, VK_SPACE, 0);
|
||||
require(ListView_GetCheckState(profiles, 1), "Space toggles the focused profile");
|
||||
SendMessageW(profiles, WM_KEYDOWN, VK_SPACE, 0);
|
||||
require(!ListView_GetCheckState(profiles, 1), "Space restores the disabled profile");
|
||||
ListView_SetItemState(profiles, 0, LVIS_SELECTED, LVIS_SELECTED);
|
||||
SendMessageW(profiles, WM_LBUTTONDBLCLK, MK_LBUTTON, MAKELPARAM(nameWidth / 2, rowCenter));
|
||||
profileDialog = FindWindowW(L"KSwitcher.MouseProfileName", nullptr);
|
||||
@@ -1050,19 +1091,19 @@ int main(int argc, char **argv) {
|
||||
{
|
||||
auto window = app.settingsWindow;
|
||||
auto previous = app.settings;
|
||||
TabCtrl_SetCurSel(GetDlgItem(window,260),3);
|
||||
selectSettingsPage(window, 3);
|
||||
app.settings.awake = !previous.awake;
|
||||
app.settings.maxItems = previous.maxItems + 1;
|
||||
SendMessageW(window,ks::ConfigSettingsDownloaded,0,0);
|
||||
wchar_t count[32]{};
|
||||
GetDlgItemTextW(window,240,count,32);
|
||||
GetDlgItemTextW(settingsViewport(window), 240,count,32);
|
||||
require(app.settingsWindow == window &&
|
||||
SendDlgItemMessageW(window,205,BM_GETCHECK,0,0) == (app.settings.awake ? BST_CHECKED : BST_UNCHECKED) &&
|
||||
std::stoi(count) == app.settings.maxItems && TabCtrl_GetCurSel(GetDlgItem(window,260)) == 3,
|
||||
SendDlgItemMessageW(settingsViewport(window), 205,BM_GETCHECK,0,0) == (app.settings.awake ? BST_CHECKED : BST_UNCHECKED) &&
|
||||
std::stoi(count) == app.settings.maxItems && TreeView_GetSelection(settingsNavigation(window)) == settingsSection(settingsNavigation(window), 3),
|
||||
"download refreshes existing settings controls while preserving window and active tab");
|
||||
app.settings = previous;
|
||||
SendMessageW(window,ks::ConfigSettingsDownloaded,0,0);
|
||||
TabCtrl_SetCurSel(GetDlgItem(window,260),0);
|
||||
selectSettingsPage(window, 0);
|
||||
auto timer = SetTimer(nullptr, 0, 10, answerSettingsClose);
|
||||
require(timer != 0, "settings close prompt responder");
|
||||
SendMessageW(app.settingsWindow, WM_CLOSE, 0, 0);
|
||||
@@ -1070,17 +1111,17 @@ int main(int argc, char **argv) {
|
||||
"unchanged settings close without prompting");
|
||||
ks::showSettings(app,false);
|
||||
auto settingsWindow = app.settingsWindow;
|
||||
auto initial = SendDlgItemMessageW(settingsWindow,205,BM_GETCHECK,0,0);
|
||||
SendDlgItemMessageW(settingsWindow,205,BM_SETCHECK,!initial,0);
|
||||
auto initial = SendDlgItemMessageW(settingsViewport(settingsWindow), 205,BM_GETCHECK,0,0);
|
||||
SendDlgItemMessageW(settingsViewport(settingsWindow), 205,BM_SETCHECK,!initial,0);
|
||||
SendMessageW(settingsWindow, WM_CLOSE, 0, 0);
|
||||
require(IsWindow(settingsWindow) && settingsClosePrompts == 1,
|
||||
"cancel close preserves changed settings");
|
||||
SendDlgItemMessageW(settingsWindow,205,BM_SETCHECK,initial,0);
|
||||
SendDlgItemMessageW(settingsViewport(settingsWindow), 205,BM_SETCHECK,initial,0);
|
||||
SendMessageW(settingsWindow, WM_CLOSE, 0, 0);
|
||||
require(!app.settingsWindow && settingsClosePrompts == 1,
|
||||
"reverted settings close without prompting");
|
||||
ks::showSettings(app,false);
|
||||
SetDlgItemTextW(app.settingsWindow,240,L"invalid");
|
||||
SetDlgItemTextW(settingsViewport(app.settingsWindow), 240,L"invalid");
|
||||
settingsCloseChoice = IDNO;
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
require(!app.settingsWindow && settingsClosePrompts == 2,
|
||||
@@ -1091,7 +1132,7 @@ int main(int argc, char **argv) {
|
||||
app.settings.undo = app.settings.clipboard = app.settings.screenshot = L"";
|
||||
app.settings.direct.assign(app.layouts.size(), L"");
|
||||
ks::showSettings(app,false);
|
||||
SendDlgItemMessageW(app.settingsWindow,208,BM_SETCHECK,
|
||||
SendDlgItemMessageW(settingsViewport(app.settingsWindow), 208,BM_SETCHECK,
|
||||
originalSettings.writeLog ? BST_UNCHECKED : BST_CHECKED,0);
|
||||
settingsCloseChoice = IDYES;
|
||||
SendMessageW(app.settingsWindow,WM_CLOSE,0,0);
|
||||
@@ -1105,21 +1146,21 @@ int main(int argc, char **argv) {
|
||||
settingsCloseChoice = IDCANCEL;
|
||||
ks::showSettings(app,false);
|
||||
}
|
||||
require(GetDlgItem(app.settingsWindow,258)!=nullptr,"sync available without local opt-in");
|
||||
require(GetDlgItem(settingsViewport(app.settingsWindow), 271)!=nullptr,"OpenBao available without local opt-in");
|
||||
// Mnemonics only target visible controls; show without taking foreground focus.
|
||||
ShowWindow(app.settingsWindow,SW_SHOWNOACTIVATE);
|
||||
auto previousActive=SetActiveWindow(app.settingsWindow);
|
||||
auto awakeBefore=SendDlgItemMessageW(app.settingsWindow,205,BM_GETCHECK,0,0);
|
||||
MSG accessKey{}; accessKey.hwnd=GetDlgItem(app.settingsWindow,201);
|
||||
auto awakeBefore=SendDlgItemMessageW(settingsViewport(app.settingsWindow), 205,BM_GETCHECK,0,0);
|
||||
MSG accessKey{}; accessKey.hwnd=GetDlgItem(settingsViewport(app.settingsWindow), 201);
|
||||
accessKey.message=WM_SYSCHAR; accessKey.wParam=L'k'; accessKey.lParam=1LL<<29;
|
||||
require(IsDialogMessageW(app.settingsWindow,&accessKey),"Alt+K is handled as a dialog access key");
|
||||
MSG dispatched{};
|
||||
while(PeekMessageW(&dispatched,nullptr,0,0,PM_REMOVE)) { TranslateMessage(&dispatched); DispatchMessageW(&dispatched); }
|
||||
require(SendDlgItemMessageW(app.settingsWindow,205,BM_GETCHECK,0,0)!=awakeBefore,
|
||||
require(SendDlgItemMessageW(settingsViewport(app.settingsWindow), 205,BM_GETCHECK,0,0)!=awakeBefore,
|
||||
"Alt+K toggles Keep screen awake");
|
||||
IsDialogMessageW(app.settingsWindow,&accessKey);
|
||||
while(PeekMessageW(&dispatched,nullptr,0,0,PM_REMOVE)) { TranslateMessage(&dispatched); DispatchMessageW(&dispatched); }
|
||||
require(SendDlgItemMessageW(app.settingsWindow,205,BM_GETCHECK,0,0)==awakeBefore,
|
||||
require(SendDlgItemMessageW(settingsViewport(app.settingsWindow), 205,BM_GETCHECK,0,0)==awakeBefore,
|
||||
"repeated access key restores checkbox state");
|
||||
ShowWindow(app.settingsWindow,SW_HIDE);
|
||||
SetActiveWindow(previousActive);
|
||||
@@ -1127,25 +1168,33 @@ int main(int argc, char **argv) {
|
||||
DestroyWindow(app.settingsWindow);
|
||||
ks::saveSyncConfig(app.data,ks::SyncConfig{});
|
||||
ks::showSettings(app,false);
|
||||
require(GetDlgItem(app.settingsWindow,258)!=nullptr,"sync button available after local opt-in");
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,258,0);
|
||||
auto syncWindow=FindWindowW(L"KSwitcher.Sync",nullptr);
|
||||
require(syncWindow!=nullptr,"private sync dialog opens");
|
||||
ShowWindow(syncWindow,SW_HIDE);
|
||||
selectSettingsPage(app.settingsWindow, 6);
|
||||
const auto tree = settingsNavigation(app.settingsWindow);
|
||||
require(TreeView_GetSelection(tree) == settingsSection(tree, 17), "Sync opens its OpenBao child");
|
||||
auto syncWindow = GetDlgItem(settingsViewport(app.settingsWindow), 271);
|
||||
require(syncWindow && (GetWindowLongPtrW(syncWindow,GWL_STYLE)&WS_VISIBLE) &&
|
||||
!FindWindowW(L"KSwitcher.Sync",nullptr), "OpenBao is embedded in the Settings window");
|
||||
require((GetWindowLongPtrW(GetDlgItem(syncWindow,604),GWL_STYLE)&ES_PASSWORD)!=0,
|
||||
"sync password is masked");
|
||||
require(!IsWindowEnabled(app.settingsWindow),"sync dialog owns settings interaction");
|
||||
for(int id:{602,603,604,605,606,607,610,611,612,613,IDOK})
|
||||
require(IsWindowEnabled(app.settingsWindow),"OpenBao allows switching to other settings pages");
|
||||
for(int id:{602,603,604,605,606,607,610,611,612,613,614})
|
||||
require(!IsWindowEnabled(GetDlgItem(syncWindow,id)),"disabled synchronization disables dependent controls");
|
||||
require(IsWindowEnabled(GetDlgItem(syncWindow,601)) && IsWindowEnabled(GetDlgItem(syncWindow,609)) &&
|
||||
IsWindowEnabled(GetDlgItem(syncWindow,IDCANCEL)),"enable, forget password and close remain available");
|
||||
require(IsWindowEnabled(GetDlgItem(syncWindow,601)) && IsWindowEnabled(GetDlgItem(syncWindow,609)),
|
||||
"enable and forget password remain available");
|
||||
SendMessageW(syncWindow,WM_COMMAND,612,0);
|
||||
require(!FindWindowW(L"KSwitcher.SyncConflicts",nullptr),"disabled conflict action is ignored");
|
||||
SendDlgItemMessageW(syncWindow,601,BM_SETCHECK,BST_CHECKED,0);
|
||||
SendMessageW(syncWindow,WM_COMMAND,MAKEWPARAM(601,BN_CLICKED),0);
|
||||
for(int id:{602,603,604,605,606,607,610,611,613,IDOK})
|
||||
for(int id:{602,603,604,605,606,607,610,611,613,614})
|
||||
require(IsWindowEnabled(GetDlgItem(syncWindow,id)),"enabling synchronization immediately enables connection controls");
|
||||
require(!ks::loadSyncConfig(app.data).enabled,"checking enable alone does not connect or persist");
|
||||
SetDlgItemTextW(syncWindow, 602, L"https://draft.example.test");
|
||||
selectSettingsPage(app.settingsWindow, 0);
|
||||
selectSettingsPage(app.settingsWindow, 17);
|
||||
wchar_t draftServer[64]{};
|
||||
GetDlgItemTextW(syncWindow, 602, draftServer, std::size(draftServer));
|
||||
require(std::wstring_view(draftServer) == L"https://draft.example.test",
|
||||
"switching sections preserves the OpenBao draft");
|
||||
auto enabledSync=ks::loadSyncConfig(app.data);
|
||||
enabledSync.enabled=true;
|
||||
enabledSync.server=L"https://sync.example.test";
|
||||
@@ -1171,10 +1220,10 @@ int main(int argc, char **argv) {
|
||||
"conflict controls fit dialog");
|
||||
}
|
||||
SendMessageW(conflictsWindow,WM_COMMAND,623,0);
|
||||
require(!IsWindowEnabled(syncWindow),"conflict dialog owns sync interaction");
|
||||
require(!IsWindowEnabled(app.settingsWindow),"conflict dialog owns settings interaction");
|
||||
SendMessageW(conflictsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
require(IsWindowEnabled(syncWindow),"closing conflict dialog restores sync window");
|
||||
for(int id:{601,602,603,604,605,606,607,608,609,610,611,612,613,IDOK,IDCANCEL}) {
|
||||
require(IsWindowEnabled(app.settingsWindow),"closing conflict dialog restores Settings");
|
||||
for(int id:{601,602,603,604,605,606,607,608,609,610,611,612,613,614}) {
|
||||
RECT control{},client{};
|
||||
GetWindowRect(GetDlgItem(syncWindow,id),&control);
|
||||
MapWindowPoints(nullptr,syncWindow,reinterpret_cast<POINT*>(&control),2);
|
||||
@@ -1184,12 +1233,11 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
SendDlgItemMessageW(syncWindow,601,BM_SETCHECK,BST_UNCHECKED,0);
|
||||
SendMessageW(syncWindow,WM_COMMAND,MAKEWPARAM(601,BN_CLICKED),0);
|
||||
require(IsWindowEnabled(GetDlgItem(syncWindow,IDOK)),"Save remains available to persist disabling sync");
|
||||
SendMessageW(syncWindow,WM_COMMAND,IDOK,0);
|
||||
require(IsWindowEnabled(GetDlgItem(syncWindow,614)),"Save remains available to persist disabling sync");
|
||||
SendMessageW(syncWindow,WM_COMMAND,614,0);
|
||||
require(!ks::loadSyncConfig(app.data).enabled,"saving disabled sync does not enable network access");
|
||||
require(!IsWindowEnabled(GetDlgItem(syncWindow,IDOK)),"Save disables after disabled state is persisted");
|
||||
SendMessageW(syncWindow,WM_COMMAND,IDCANCEL,0);
|
||||
require(IsWindowEnabled(app.settingsWindow),"closing sync restores parent");
|
||||
require(!IsWindowEnabled(GetDlgItem(syncWindow,614)),"Save disables after disabled state is persisted");
|
||||
selectSettingsPage(app.settingsWindow, 0);
|
||||
require(ks::InputRegressionAccess::staleSync(app,false),"in-flight sync cannot overwrite newer local edits");
|
||||
require(ks::InputRegressionAccess::staleSync(app,true),"disconnect discards in-flight downloaded profile");
|
||||
require(ks::InputRegressionAccess::idleUndo(app),"idle cleanup retains available/busy Undo and frees expired Undo");
|
||||
@@ -1197,85 +1245,36 @@ int main(int argc, char **argv) {
|
||||
require(ks::InputRegressionAccess::completedSync(app,mode),
|
||||
"completed, failed and invalid sync release buffers but preserve conflict choices");
|
||||
require(ks::InputRegressionAccess::syncBackoff(app),"saving settings preserves authentication error backoff");
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,255,0);
|
||||
auto autoOptions=FindWindowW(L"KSwitcher.AutoOptions",nullptr);
|
||||
require(autoOptions!=nullptr,"auto-correction options open");
|
||||
ShowWindow(autoOptions,SW_HIDE);
|
||||
selectSettingsPage(app.settingsWindow, 14);
|
||||
auto autoOptions = settingsViewport(app.settingsWindow);
|
||||
for (int id : {411, 412, 413})
|
||||
{
|
||||
require((GetWindowLongPtrW(autoOptions,GWL_STYLE)&WS_THICKFRAME)!=0,
|
||||
"auto-correction dialog supports resizing");
|
||||
RECT original{}, before[3]{}, after[3]{}, buttonBefore{}, buttonAfter{};
|
||||
GetWindowRect(autoOptions,&original);
|
||||
// Use a client size above the scrolling baseline at every DPI.
|
||||
UINT dpi=GetDpiForWindow(autoOptions);
|
||||
SetWindowPos(autoOptions,nullptr,0,0,MulDiv(800,dpi,96),MulDiv(1100,dpi,96),
|
||||
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
RECT baseline{}; GetWindowRect(autoOptions,&baseline);
|
||||
RECT clientBefore{}; GetClientRect(autoOptions,&clientBefore);
|
||||
for(int i=0;i<3;++i) GetWindowRect(GetDlgItem(autoOptions,411+i),&before[i]);
|
||||
GetWindowRect(GetDlgItem(autoOptions,IDOK),&buttonBefore);
|
||||
SetWindowPos(autoOptions,nullptr,0,0,baseline.right-baseline.left+240,
|
||||
baseline.bottom-baseline.top+120,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
RECT clientAfter{}; GetClientRect(autoOptions,&clientAfter);
|
||||
// Windows can constrain oversized windows to the current desktop.
|
||||
// Check layout against the actual available client space.
|
||||
int extraBeforeX=std::max(0,int(clientBefore.right)-MulDiv(560,dpi,96));
|
||||
int extraAfterX=std::max(0,int(clientAfter.right)-MulDiv(560,dpi,96));
|
||||
int extraY=std::max(0,int(clientAfter.bottom)-MulDiv(880,dpi,96))-
|
||||
std::max(0,int(clientBefore.bottom)-MulDiv(880,dpi,96));
|
||||
for(int i=0;i<3;++i) {
|
||||
GetWindowRect(GetDlgItem(autoOptions,411+i),&after[i]);
|
||||
int extraX=(extraAfterX*(i+1)/3-extraAfterX*i/3)-
|
||||
(extraBeforeX*(i+1)/3-extraBeforeX*i/3);
|
||||
require(after[i].right-after[i].left==before[i].right-before[i].left+extraX &&
|
||||
after[i].bottom-after[i].top==before[i].bottom-before[i].top+extraY,
|
||||
"dictionary columns share extra width and receive extra height");
|
||||
}
|
||||
GetWindowRect(GetDlgItem(autoOptions,IDOK),&buttonAfter);
|
||||
require(buttonAfter.left-buttonBefore.left==extraAfterX-extraBeforeX && buttonAfter.top-buttonBefore.top==extraY,
|
||||
"auto-correction buttons follow bottom-right corner");
|
||||
require(after[0].right<after[1].left && after[1].right<after[2].left &&
|
||||
after[2].bottom<buttonAfter.top,
|
||||
"resized dictionary fields and footer do not overlap");
|
||||
SetWindowPos(autoOptions,nullptr,0,0,original.right-original.left,original.bottom-original.top,
|
||||
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
}
|
||||
for(int id:{411,412,413}) {
|
||||
RECT control{},client{};
|
||||
GetWindowRect(GetDlgItem(autoOptions,id),&control);
|
||||
MapWindowPoints(nullptr,autoOptions,reinterpret_cast<POINT*>(&control),2);
|
||||
GetClientRect(autoOptions,&client);
|
||||
require(control.left>=0&&control.top>=0&&control.right<=client.right&&control.bottom<=client.bottom,
|
||||
"personal dictionary field fits options window");
|
||||
const auto field = GetDlgItem(autoOptions, id);
|
||||
RECT bounds{};
|
||||
GetWindowRect(field, &bounds);
|
||||
require((GetWindowLongPtrW(field, GWL_STYLE) & WS_VISIBLE) &&
|
||||
bounds.bottom - bounds.top >= MulDiv(72, GetDpiForWindow(field), 96),
|
||||
"all personal dictionary fields use tall editors on their own page");
|
||||
}
|
||||
SetDlgItemTextW(autoOptions,412,L"Релізик\r\nрелізик, словечко");
|
||||
SetDlgItemTextW(autoOptions,416,L" Првиіт = Привіт\r\nhelo=hello\r\n Мамамила = Мама мила ");
|
||||
SendDlgItemMessageW(autoOptions,414,BM_SETCHECK,BST_CHECKED,0);
|
||||
SendDlgItemMessageW(autoOptions,415,BM_SETCHECK,BST_CHECKED,0);
|
||||
SendMessageW(autoOptions,WM_COMMAND,IDOK,0);
|
||||
require(!IsWindow(autoOptions),"personal words accepted without file editing");
|
||||
{
|
||||
auto timer = SetTimer(nullptr,0,10,answerSettingsClose);
|
||||
auto before = settingsClosePrompts;
|
||||
SendMessageW(app.settingsWindow,WM_CLOSE,0,0);
|
||||
KillTimer(nullptr,timer);
|
||||
require(app.settingsWindow && settingsClosePrompts == before + 1,
|
||||
"accepted personal dictionary edits trigger unsaved settings warning");
|
||||
}
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,255,0);
|
||||
autoOptions=FindWindowW(L"KSwitcher.AutoOptions",nullptr);
|
||||
ShowWindow(autoOptions,SW_HIDE);
|
||||
selectSettingsPage(app.settingsWindow, 0);
|
||||
selectSettingsPage(app.settingsWindow, 14);
|
||||
wchar_t personalWords[128]{};
|
||||
GetDlgItemTextW(autoOptions,412,personalWords,128);
|
||||
require(std::wstring(personalWords)==L"релізик, словечко",
|
||||
"personal dictionary normalizes case, newlines and duplicate words");
|
||||
wchar_t pairs[128]{};
|
||||
GetDlgItemTextW(autoOptions,416,pairs,128);
|
||||
require(std::wstring(pairs)==L"helo=hello\r\nмамамила=мама мила\r\nпрвиіт=привіт\r\n" &&
|
||||
SendDlgItemMessageW(autoOptions,414,BM_GETCHECK,0,0)==BST_CHECKED &&
|
||||
SendDlgItemMessageW(autoOptions,415,BM_GETCHECK,0,0)==BST_CHECKED,
|
||||
"typo options and normalized replacement pairs survive reopening");
|
||||
SendMessageW(autoOptions,WM_COMMAND,IDCANCEL,0);
|
||||
GetDlgItemTextW(autoOptions, 412, personalWords, std::size(personalWords));
|
||||
require(std::wstring(personalWords) == L"Релізик\r\nрелізик, словечко",
|
||||
"personal dictionary draft survives switching pages");
|
||||
{
|
||||
auto timer = SetTimer(nullptr, 0, 10, answerSettingsClose);
|
||||
auto before = settingsClosePrompts;
|
||||
SendMessageW(app.settingsWindow, WM_CLOSE, 0, 0);
|
||||
KillTimer(nullptr, timer);
|
||||
require(app.settingsWindow && settingsClosePrompts == before + 1,
|
||||
"inline correction edits trigger the unsaved settings warning");
|
||||
}
|
||||
selectSettingsPage(app.settingsWindow, 0);
|
||||
if (!app.history) app.history=std::make_unique<ks::History>(temp/L"history-layout");
|
||||
ks::showHistory(app,false);
|
||||
auto history=app.historyWindow;
|
||||
@@ -1366,14 +1365,14 @@ int main(int argc, char **argv) {
|
||||
require(EqualRect(&listBefore,&(listAfter=childRect(102))),"DPI refresh preserves history list geometry");
|
||||
}
|
||||
auto settings=app.settingsWindow;
|
||||
require(SendDlgItemMessageW(settings,209,BM_GETCHECK,0,0)==BST_UNCHECKED,"automatic screenshot editor checkbox defaults off");
|
||||
require(SendDlgItemMessageW(settingsViewport(settings), 209,BM_GETCHECK,0,0)==BST_UNCHECKED,"automatic screenshot editor checkbox defaults off");
|
||||
require(settings&&!IsWindowVisible(settings),"settings layout tested without changing user focus");
|
||||
for(auto pair:{std::pair{209,215},std::pair{209,207},std::pair{209,220},std::pair{209,232},std::pair{207,215},std::pair{207,232},std::pair{207,220},std::pair{232,230},std::pair{230,231},std::pair{231,253}}) {
|
||||
// Controls on different settings tabs intentionally share the page area.
|
||||
if (!(GetWindowLongPtrW(GetDlgItem(settings,pair.first),GWL_STYLE)&WS_VISIBLE) ||
|
||||
!(GetWindowLongPtrW(GetDlgItem(settings,pair.second),GWL_STYLE)&WS_VISIBLE)) continue;
|
||||
if (!(GetWindowLongPtrW(GetDlgItem(settingsViewport(settings),pair.first),GWL_STYLE)&WS_VISIBLE) ||
|
||||
!(GetWindowLongPtrW(GetDlgItem(settingsViewport(settings),pair.second),GWL_STYLE)&WS_VISIBLE)) continue;
|
||||
RECT first{},second{},overlap{};
|
||||
GetWindowRect(GetDlgItem(settings,pair.first),&first); GetWindowRect(GetDlgItem(settings,pair.second),&second);
|
||||
GetWindowRect(GetDlgItem(settingsViewport(settings),pair.first),&first); GetWindowRect(GetDlgItem(settingsViewport(settings),pair.second),&second);
|
||||
require(!IntersectRect(&overlap,&first,&second),"capture hotkey and layout controls do not overlap");
|
||||
}
|
||||
RECT frame{},client{},cancel{};
|
||||
@@ -1385,48 +1384,161 @@ int main(int argc, char **argv) {
|
||||
std::cout << "Hidden Settings layout checked at " << dpi << " DPI\n";
|
||||
GetWindowRect(GetDlgItem(settings,IDCANCEL),&cancel);
|
||||
require(cancel.right-cancel.left==MulDiv(100,dpi,96),"controls use actual window DPI");
|
||||
auto pane = settingsViewport(settings);
|
||||
selectSettingsPage(settings, 2);
|
||||
for (int width : {800, 620, 800})
|
||||
{
|
||||
SetWindowPos(settings, nullptr, 0, 0, MulDiv(width, dpi, 96), MulDiv(540, dpi, 96),
|
||||
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
RECT viewport{};
|
||||
GetClientRect(pane, &viewport);
|
||||
const int margin = MulDiv(24, dpi, 96);
|
||||
for (int id = 210; id <= 216; ++id)
|
||||
{
|
||||
RECT field{};
|
||||
GetWindowRect(GetDlgItem(pane, id), &field);
|
||||
MapWindowPoints(nullptr, pane, reinterpret_cast<POINT *>(&field), 2);
|
||||
require(field.left == MulDiv(width == 620 ? 24 : 230, dpi, 96) &&
|
||||
field.right <= viewport.right - margin + 1 && field.right > field.left,
|
||||
"shortcut fields fit inside the viewport in both layouts");
|
||||
}
|
||||
require(!(GetWindowLongPtrW(pane, GWL_STYLE) & WS_HSCROLL),
|
||||
"shortcut fields do not require horizontal scrolling");
|
||||
}
|
||||
auto fieldBounds = [&](int id)
|
||||
{
|
||||
RECT rect{};
|
||||
GetWindowRect(GetDlgItem(pane, id), &rect);
|
||||
MapWindowPoints(nullptr, pane, reinterpret_cast<POINT *>(&rect), 2);
|
||||
return rect;
|
||||
};
|
||||
auto fitsPane = [&](const RECT &rect)
|
||||
{
|
||||
RECT viewport{};
|
||||
GetClientRect(pane, &viewport);
|
||||
return rect.left >= 0 && rect.left < rect.right && rect.right <= viewport.right &&
|
||||
!(GetWindowLongPtrW(pane, GWL_STYLE) & WS_HSCROLL);
|
||||
};
|
||||
for (int width : {800, 620})
|
||||
{
|
||||
SetWindowPos(settings, nullptr, 0, 0, MulDiv(width, dpi, 96), MulDiv(600, dpi, 96),
|
||||
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
selectSettingsPage(settings, 3);
|
||||
for (int id : {240, 241, 242, 243})
|
||||
require(fitsPane(fieldBounds(id)), "clipboard fields fit inside the pane");
|
||||
selectSettingsPage(settings, 13);
|
||||
const auto first = fieldBounds(404), second = fieldBounds(405);
|
||||
require(fitsPane(first) && fitsPane(second) && first.bottom < second.top &&
|
||||
std::abs((first.bottom - first.top) - (second.bottom - second.top)) <= MulDiv(1, dpi, 96) &&
|
||||
second.bottom >= MulDiv(320, dpi, 96),
|
||||
"exception lists equally fill the available height");
|
||||
LOGFONTW captionFont{}, editFont{};
|
||||
const auto edit = GetDlgItem(pane, 404);
|
||||
const auto caption = GetWindow(edit, GW_HWNDPREV);
|
||||
GetObjectW(reinterpret_cast<HFONT>(SendMessageW(caption, WM_GETFONT, 0, 0)), sizeof(captionFont), &captionFont);
|
||||
GetObjectW(reinterpret_cast<HFONT>(SendMessageW(edit, WM_GETFONT, 0, 0)), sizeof(editFont), &editFont);
|
||||
require(captionFont.lfWeight == FW_SEMIBOLD && editFont.lfWeight == FW_NORMAL,
|
||||
"field captions use semibold while input text stays regular");
|
||||
}
|
||||
selectSettingsPage(settings, 14);
|
||||
for (int height : {470, 600, 700})
|
||||
{
|
||||
SetWindowPos(settings, nullptr, 0, 0, MulDiv(700, dpi, 96), MulDiv(height, dpi, 96),
|
||||
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
const auto english = fieldBounds(411), ukrainian = fieldBounds(412), russian = fieldBounds(413);
|
||||
const LONG heights[] = {english.bottom - english.top, ukrainian.bottom - ukrainian.top,
|
||||
russian.bottom - russian.top};
|
||||
const auto [minHeight, maxHeight] = std::minmax_element(std::begin(heights), std::end(heights));
|
||||
RECT viewport{};
|
||||
GetClientRect(pane, &viewport);
|
||||
require(fitsPane(english) && fitsPane(ukrainian) && fitsPane(russian) &&
|
||||
*minHeight >= MulDiv(72, dpi, 96) && *maxHeight - *minHeight <= MulDiv(1, dpi, 96),
|
||||
"personal dictionary fields share the viewport height equally");
|
||||
if (height == 470)
|
||||
require(GetWindowLongPtrW(pane, GWL_STYLE) & WS_VSCROLL,
|
||||
"personal dictionary fields keep their minimum height in a short viewport");
|
||||
else
|
||||
require(std::abs(viewport.bottom - russian.bottom - MulDiv(24, dpi, 96)) <= MulDiv(1, dpi, 96) &&
|
||||
!(GetWindowLongPtrW(pane, GWL_STYLE) & WS_VSCROLL),
|
||||
"personal dictionary fields fill the viewport down to the bottom margin");
|
||||
}
|
||||
auto controlsFit = [&](HWND parent)
|
||||
{
|
||||
RECT viewport{};
|
||||
GetClientRect(parent, &viewport);
|
||||
require(!(GetWindowLongPtrW(parent, GWL_STYLE) & WS_HSCROLL),
|
||||
"settings page does not need horizontal scrolling");
|
||||
for (HWND child = GetWindow(parent, GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
|
||||
{
|
||||
if (!(GetWindowLongPtrW(child, GWL_STYLE) & WS_VISIBLE)) continue;
|
||||
RECT bounds{};
|
||||
GetWindowRect(child, &bounds);
|
||||
MapWindowPoints(nullptr, parent, reinterpret_cast<POINT *>(&bounds), 2);
|
||||
require(bounds.left >= 0 && bounds.right <= viewport.right,
|
||||
"settings control fits the visible pane width");
|
||||
}
|
||||
};
|
||||
for (const auto &[width, widenSidebar] : {std::pair{800, false}, {620, false}, {620, true}})
|
||||
{
|
||||
SetWindowPos(settings, nullptr, 0, 0, MulDiv(width, dpi, 96), MulDiv(540, dpi, 96),
|
||||
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
if (widenSidebar)
|
||||
for (int step = 0; step < 24; ++step)
|
||||
SendMessageW(GetDlgItem(settings, 270), WM_KEYDOWN, VK_RIGHT, 0);
|
||||
for (int page = 0; page < 18; ++page)
|
||||
{
|
||||
selectSettingsPage(settings, page);
|
||||
controlsFit(pane);
|
||||
if (page == 10) controlsFit(GetDlgItem(pane, 262));
|
||||
if (page == 17) controlsFit(GetDlgItem(pane, 271));
|
||||
}
|
||||
}
|
||||
selectSettingsPage(settings, 0);
|
||||
SetWindowPos(settings,nullptr,0,0,480,360,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
GetWindowRect(GetDlgItem(settings, IDCANCEL), &cancel);
|
||||
SCROLLINFO scroll{sizeof(scroll),SIF_ALL};
|
||||
GetScrollInfo(settings,SB_VERT,&scroll);
|
||||
GetScrollInfo(pane,SB_VERT,&scroll);
|
||||
require(scroll.nMax+1>(int)scroll.nPage,"small settings window has vertical scrolling");
|
||||
GetScrollInfo(settings,SB_HORZ,&scroll);
|
||||
require(scroll.nMax+1>(int)scroll.nPage,"small settings window has horizontal scrolling");
|
||||
require(!(GetWindowLongPtrW(pane, GWL_STYLE) & WS_HSCROLL),
|
||||
"small settings window needs only vertical scrolling");
|
||||
int controlMoves = 0;
|
||||
auto trackedControl = GetDlgItem(settings,201);
|
||||
auto trackedControl = GetDlgItem(pane, 201);
|
||||
SetWindowSubclass(trackedControl,countControlMoves,99,(DWORD_PTR)&controlMoves);
|
||||
SendMessageW(settings,WM_VSCROLL,SB_TOP,0);
|
||||
SendMessageW(settings,WM_HSCROLL,SB_LEFT,0);
|
||||
SendMessageW(pane,WM_VSCROLL,SB_TOP,0);
|
||||
SendMessageW(pane,WM_HSCROLL,SB_LEFT,0);
|
||||
controlMoves=0;
|
||||
ValidateRect(settings,nullptr);
|
||||
SendMessageW(settings,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA),0);
|
||||
SendMessageW(settings,WM_TIMER,ks::ScrollFrameTimer,0);
|
||||
require(controlMoves==0 && !GetUpdateRect(settings,nullptr,FALSE),"wheel at top does not move controls or erase the window");
|
||||
SendMessageW(settings,WM_MOUSEWHEEL,MAKEWPARAM(0,WORD(short(-WHEEL_DELTA/2))),0);
|
||||
SendMessageW(settings,WM_TIMER,ks::ScrollFrameTimer,0);
|
||||
ValidateRect(pane,nullptr);
|
||||
SendMessageW(pane,WM_MOUSEWHEEL,MAKEWPARAM(0,WHEEL_DELTA),0);
|
||||
SendMessageW(pane,WM_TIMER,ks::ScrollFrameTimer,0);
|
||||
require(controlMoves==0 && !GetUpdateRect(pane,nullptr,FALSE),"wheel at top does not move controls or erase the window");
|
||||
SendMessageW(pane,WM_MOUSEWHEEL,MAKEWPARAM(0,WORD(short(-WHEEL_DELTA/2))),0);
|
||||
SendMessageW(pane,WM_TIMER,ks::ScrollFrameTimer,0);
|
||||
require(controlMoves==0,"partial wheel step does not rearrange controls");
|
||||
SendMessageW(settings,WM_MOUSEWHEEL,MAKEWPARAM(0,WORD(short(-WHEEL_DELTA/2))),0);
|
||||
SendMessageW(pane,WM_MOUSEWHEEL,MAKEWPARAM(0,WORD(short(-WHEEL_DELTA/2))),0);
|
||||
require(controlMoves==0,"wheel changes wait for the shared frame timer");
|
||||
SendMessageW(settings,WM_TIMER,ks::ScrollFrameTimer,0);
|
||||
SendMessageW(pane,WM_TIMER,ks::ScrollFrameTimer,0);
|
||||
require(controlMoves==1,"wheel scroll batches each control movement once");
|
||||
SendMessageW(settings,WM_VSCROLL,SB_BOTTOM,0);
|
||||
SendMessageW(settings,WM_HSCROLL,SB_RIGHT,0);
|
||||
SendMessageW(pane,WM_VSCROLL,SB_BOTTOM,0);
|
||||
SendMessageW(pane,WM_HSCROLL,SB_RIGHT,0);
|
||||
controlMoves=0;
|
||||
SendMessageW(settings,WM_MOUSEWHEEL,MAKEWPARAM(0,-WHEEL_DELTA),0);
|
||||
SendMessageW(settings,WM_MOUSEHWHEEL,MAKEWPARAM(0,WHEEL_DELTA),0);
|
||||
SendMessageW(settings,WM_TIMER,ks::ScrollFrameTimer,0);
|
||||
SendMessageW(pane,WM_MOUSEWHEEL,MAKEWPARAM(0,-WHEEL_DELTA),0);
|
||||
SendMessageW(pane,WM_MOUSEHWHEEL,MAKEWPARAM(0,WHEEL_DELTA),0);
|
||||
SendMessageW(pane,WM_TIMER,ks::ScrollFrameTimer,0);
|
||||
require(controlMoves==0,"wheel at bottom and right boundaries does not rearrange controls");
|
||||
require((GetWindowLongPtrW(settings,GWL_STYLE)&WS_CLIPCHILDREN)!=0,"parent background excludes child controls");
|
||||
RemoveWindowSubclass(trackedControl,countControlMoves,99);
|
||||
RECT cancelAfterScroll{};
|
||||
GetWindowRect(GetDlgItem(settings, IDCANCEL), &cancelAfterScroll);
|
||||
require(EqualRect(&cancel, &cancelAfterScroll), "the footer stays anchored while the page scrolls");
|
||||
GetClientRect(settings,&client);
|
||||
GetWindowRect(GetDlgItem(settings,IDCANCEL),&cancel);
|
||||
MapWindowPoints(nullptr,settings,(POINT*)&cancel,2);
|
||||
require(cancel.left>=0&&cancel.top>=0&&cancel.right<=client.right&&cancel.bottom<=client.bottom,"bottom actions reachable by scrolling");
|
||||
SendMessageW(settings,WM_VSCROLL,SB_TOP,0);
|
||||
SendMessageW(settings,WM_HSCROLL,SB_LEFT,0);
|
||||
SendMessageW(GetDlgItem(settings,IDCANCEL),WM_SETFOCUS,0,0);
|
||||
GetWindowRect(GetDlgItem(settings,IDCANCEL),&cancel);
|
||||
MapWindowPoints(nullptr,settings,(POINT*)&cancel,2);
|
||||
require(cancel.left>=0&&cancel.top>=0&&cancel.right<=client.right&&cancel.bottom<=client.bottom,"keyboard focus reveals off-screen action");
|
||||
require(cancel.left>=0&&cancel.top>=0&&cancel.right<=client.right&&cancel.bottom<=client.bottom,"footer actions stay reachable while the page scrolls");
|
||||
SendMessageW(pane,WM_VSCROLL,SB_TOP,0);
|
||||
SendMessageW(pane,WM_HSCROLL,SB_LEFT,0);
|
||||
SendMessageW(GetDlgItem(pane, 205), WM_SETFOCUS, 0, 0);
|
||||
GetScrollInfo(pane, SB_VERT, &scroll);
|
||||
require(scroll.nPos > 0, "keyboard focus reveals an off-screen setting");
|
||||
SetWindowPos(settings,nullptr,-20000,-20000,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SendMessageW(settings,WM_DISPLAYCHANGE,0,0);
|
||||
GetWindowRect(settings,&frame);
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
#include "app.h"
|
||||
#include "input_pause.h"
|
||||
#include <iostream>
|
||||
|
||||
namespace {
|
||||
void require(bool result, const char *message)
|
||||
{
|
||||
if (!result) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
template<class Predicate> void until(Predicate ready, const char *message)
|
||||
{
|
||||
auto deadline = GetTickCount64() + 4000;
|
||||
while (!ready()) {
|
||||
require(GetTickCount64() < deadline, message);
|
||||
Sleep(10);
|
||||
}
|
||||
}
|
||||
|
||||
HWND childWindow(DWORD pid, const wchar_t *type)
|
||||
{
|
||||
HWND w{};
|
||||
while ((w = FindWindowExW(nullptr, w, type, nullptr))) {
|
||||
DWORD owner{};
|
||||
GetWindowThreadProcessId(w, &owner);
|
||||
if (owner == pid) return w;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
DWORD_PTR query(HWND w, UINT msg, WPARAM wp = 0)
|
||||
{
|
||||
DWORD_PTR result{};
|
||||
require(SendMessageTimeoutW(w, msg, wp, 0, SMTO_ABORTIFHUNG | SMTO_ERRORONEXIT, 2000, &result),
|
||||
"test resident did not respond");
|
||||
return result;
|
||||
}
|
||||
|
||||
void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected)
|
||||
{
|
||||
require(PostMessageW(resident, ks::TrayMessage, 0, WM_CONTEXTMENU), "cannot open tray menu");
|
||||
HWND popup{};
|
||||
until([&] { popup = childWindow(pid, L"#32768"); return popup && IsWindowVisible(popup); },
|
||||
"tray menu did not open");
|
||||
const auto menu = reinterpret_cast<HMENU>(query(popup, MN_GETHMENU));
|
||||
wchar_t label[100]{};
|
||||
require(GetMenuStringW(menu, 0, label, std::size(label), MF_BYPOSITION) &&
|
||||
std::wstring_view(label).starts_with(expected), "incorrect input state in tray menu");
|
||||
require(PostMessageW(popup, WM_CHAR, L'i', 0), "cannot select input menu item");
|
||||
until([&] { return !IsWindow(popup); }, "tray action did not close menu");
|
||||
query(resident, WM_NULL);
|
||||
}
|
||||
}
|
||||
|
||||
bool trayIconMatchesInput(HICON icon, bool active)
|
||||
{
|
||||
HDC dc = CreateCompatibleDC(nullptr);
|
||||
HBITMAP bitmap = CreateBitmap(16, 16, 1, 32, nullptr);
|
||||
bool matches = false;
|
||||
if (dc && bitmap) {
|
||||
const auto previous = SelectObject(dc, bitmap);
|
||||
if (icon && DrawIconEx(dc, 0, 0, icon, 16, 16, 0, nullptr, DI_NORMAL)) {
|
||||
const auto tile = GetPixel(dc, 2, 8);
|
||||
const auto white = RGB(255, 255, 255);
|
||||
const auto gap = GetPixel(dc, 8, 8);
|
||||
// The active keycap is purple. The pause glyph has two white strokes with a gap.
|
||||
matches = active ? GetBValue(tile) > GetRValue(tile) + 70 :
|
||||
GetPixel(dc, 5, 8) == white && GetPixel(dc, 10, 8) == white &&
|
||||
GetRValue(gap) < 160 && std::abs(GetBValue(gap) - GetRValue(gap)) < 32;
|
||||
}
|
||||
SelectObject(dc, previous);
|
||||
}
|
||||
if (bitmap) DeleteObject(bitmap);
|
||||
if (dc) DeleteDC(dc);
|
||||
return matches;
|
||||
}
|
||||
|
||||
int testInputPause()
|
||||
{
|
||||
auto name = L"KSwitcher-input-pause-" + ks::newSnippetId();
|
||||
const auto folder = std::filesystem::temp_directory_path() / name;
|
||||
PROCESS_INFORMATION child{};
|
||||
HWND resident{};
|
||||
int result = 1;
|
||||
bool created = false;
|
||||
try {
|
||||
// Never switch the user's visible desktop or direct a command at their resident.
|
||||
const auto desktop = CreateDesktopW(name.c_str(), nullptr, nullptr, 0, GENERIC_ALL, nullptr);
|
||||
require(desktop && SetThreadDesktop(desktop), "cannot use private desktop");
|
||||
created = std::filesystem::create_directory(folder);
|
||||
require(created, "cannot create fixture directory");
|
||||
const auto fixture = folder / L"KSwitcherInputTests.exe";
|
||||
std::filesystem::copy_file(ks::executable(), fixture);
|
||||
auto command = L"\"" + fixture.wstring() + L"\" --input-pause-resident";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
startup.lpDesktop = name.data();
|
||||
require(CreateProcessW(fixture.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
|
||||
nullptr, folder.c_str(), &startup, &child), "cannot start test resident");
|
||||
until([&] {
|
||||
resident = childWindow(child.dwProcessId, L"KSwitcher.Main");
|
||||
return resident && query(resident, ProbeInputState) == 1;
|
||||
}, "resident did not start with both hooks and shortcuts");
|
||||
require(query(resident, ProbeTrayIcon, TRUE), "active tray icon missing at startup");
|
||||
constexpr UINT mods = MOD_CONTROL | MOD_SHIFT;
|
||||
require(!RegisterHotKey(nullptr, 1, mods, VK_F23) && GetLastError() == ERROR_HOTKEY_ALREADY_REGISTERED,
|
||||
"Files shortcut should be owned by resident before pause");
|
||||
chooseInputAction(resident, child.dwProcessId, L"Pause &input processing");
|
||||
until([&] { return query(resident, ProbeInputState) == 2; },
|
||||
"pause did not release both hooks and bindings and cancel the queued snippet");
|
||||
require(query(resident, ProbeTrayIcon), "pause bars missing after pause");
|
||||
require(RegisterHotKey(nullptr, 1, mods, VK_F23), "another process could not acquire Files shortcut");
|
||||
require(query(resident, ProbeInputState, 1) == 2, "settings, layout reload or IPC restarted input");
|
||||
chooseInputAction(resident, child.dwProcessId, L"Resume &input processing");
|
||||
require(query(resident, ProbeInputState) == 2, "Files conflict partially resumed input");
|
||||
require(query(resident, ProbeTrayIcon), "Files shortcut conflict cleared the pause icon");
|
||||
require(UnregisterHotKey(nullptr, 1), "cannot release Files shortcut");
|
||||
require(RegisterHotKey(nullptr, 2, mods, VK_F22), "cannot occupy hook shortcut during pause");
|
||||
chooseInputAction(resident, child.dwProcessId, L"Resume &input processing");
|
||||
require(query(resident, ProbeInputState) == 2, "hook shortcut conflict partially resumed input");
|
||||
require(query(resident, ProbeTrayIcon), "hook shortcut conflict cleared the pause icon");
|
||||
require(RegisterHotKey(nullptr, 1, mods, VK_F23), "failed resume leaked Files registration");
|
||||
UnregisterHotKey(nullptr, 1);
|
||||
UnregisterHotKey(nullptr, 2);
|
||||
chooseInputAction(resident, child.dwProcessId, L"Resume &input processing");
|
||||
require(query(resident, ProbeInputState) == 1, "resume did not restore both hooks and shortcuts");
|
||||
require(query(resident, ProbeTrayIcon, TRUE), "active tray icon missing after resume");
|
||||
require(!RegisterHotKey(nullptr, 1, mods, VK_F23) && GetLastError() == ERROR_HOTKEY_ALREADY_REGISTERED,
|
||||
"resident did not reclaim Files shortcut");
|
||||
std::cout << "Tray pause/resume, hooks, settings reload, cross-process ownership and conflict rollback passed.\n";
|
||||
result = 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::cerr << e.what() << '\n';
|
||||
}
|
||||
if (child.hProcess) {
|
||||
if (resident) PostMessageW(resident, WM_CLOSE, 0, 0);
|
||||
if (WaitForSingleObject(child.hProcess, 2000) != WAIT_OBJECT_0) {
|
||||
TerminateProcess(child.hProcess, 1);
|
||||
WaitForSingleObject(child.hProcess, 2000);
|
||||
result = 1;
|
||||
}
|
||||
CloseHandle(child.hThread);
|
||||
CloseHandle(child.hProcess);
|
||||
}
|
||||
std::error_code error;
|
||||
if (created) std::filesystem::remove_all(folder, error);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
|
||||
inline constexpr UINT ProbeInputState = WM_APP + 200;
|
||||
inline constexpr UINT ProbeTrayIcon = WM_APP + 201;
|
||||
bool trayIconMatchesInput(HICON icon, bool active);
|
||||
int testInputPause();
|
||||
+187
-3
@@ -14,6 +14,7 @@ struct InputRegressionAccess
|
||||
{
|
||||
return app.snippetPopup && IsWindowVisible(app.snippetPopup);
|
||||
}
|
||||
static size_t suggestionCount(const App &app) { return app.snippetMatches.size(); }
|
||||
static bool suggestionsNearCaret(const App &app)
|
||||
{
|
||||
GUITHREADINFO info{sizeof(info)};
|
||||
@@ -42,6 +43,10 @@ struct InputRegressionAccess
|
||||
++*reinterpret_cast<int *>(context);
|
||||
return DefSubclassProc(window, message, wp, lp);
|
||||
}, 1, reinterpret_cast<DWORD_PTR>(&hideCount));
|
||||
expireRun(app);
|
||||
}
|
||||
static void expireRun(App &app)
|
||||
{
|
||||
std::lock_guard lock(app.stateMutex);
|
||||
app.run.at = GetTickCount64() - 2500;
|
||||
}
|
||||
@@ -65,6 +70,13 @@ bool conversionOnly = false;
|
||||
bool typosOnly = false;
|
||||
int pasteBehavior = 0;
|
||||
int enterPresses = 0;
|
||||
bool observeLiteralSequence = false;
|
||||
ULONGLONG literalTextAt{}, literalEnterAt{};
|
||||
std::wstring literalTextBeforeEnter;
|
||||
bool observeMacros = false, moveFocusOnMacro = false;
|
||||
bool rightAltAndCtrl = false, rightShift = false;
|
||||
bool typeDuringMacros = false;
|
||||
ULONGLONG macroStart{}, macroEnd{};
|
||||
int copyFailuresRemaining = 0, copyRequests = 0;
|
||||
int droppedSelectionKeys = 0;
|
||||
bool trimCopiedSpaces = false;
|
||||
@@ -84,6 +96,18 @@ LRESULT CALLBACK forwardingHook(int code, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||||
{
|
||||
if (observeMacros && (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) && wp == VK_F8)
|
||||
{
|
||||
macroStart = GetTickCount64();
|
||||
rightAltAndCtrl = (GetKeyState(VK_RMENU) & 0x8000) && (GetKeyState(VK_RCONTROL) & 0x8000);
|
||||
if (moveFocusOnMacro) SetFocus(host);
|
||||
return 0;
|
||||
}
|
||||
if (observeMacros && macroStart && message == WM_KEYDOWN && wp == VK_LEFT)
|
||||
{
|
||||
macroEnd = GetTickCount64();
|
||||
rightShift = (GetKeyState(VK_RSHIFT) & 0x8000) != 0;
|
||||
}
|
||||
if (message == WM_KEYDOWN && wp == VK_LEFT && droppedSelectionKeys > 0 &&
|
||||
(GetKeyState(VK_SHIFT) & 0x8000))
|
||||
{
|
||||
@@ -167,7 +191,19 @@ LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_P
|
||||
if (pasteBehavior == 2) SendMessageW(w, EM_REPLACESEL, TRUE, (LPARAM)L"other!");
|
||||
return 0;
|
||||
}
|
||||
if (message == WM_KEYDOWN && wp == VK_RETURN) ++enterPresses;
|
||||
if (observeLiteralSequence && message == WM_CHAR && wp == L'l' && !enterPresses)
|
||||
literalTextAt = GetTickCount64();
|
||||
if (message == WM_KEYDOWN && wp == VK_RETURN)
|
||||
{
|
||||
if (observeLiteralSequence && !enterPresses)
|
||||
{
|
||||
literalEnterAt = GetTickCount64();
|
||||
wchar_t before[128]{};
|
||||
GetWindowTextW(w, before, std::size(before));
|
||||
literalTextBeforeEnter = before;
|
||||
}
|
||||
++enterPresses;
|
||||
}
|
||||
return DefSubclassProc(w, message, wp, lp);
|
||||
}
|
||||
int stage = 0, ru = -1, en = -1;
|
||||
@@ -233,7 +269,14 @@ void typeKeys(std::initializer_list<WORD> keys)
|
||||
inputs.push_back(input);
|
||||
}
|
||||
require(SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT)) == inputs.size(),
|
||||
"snippet autocomplete keyboard input submitted");
|
||||
"snippet keyboard input submitted");
|
||||
}
|
||||
void expandMacroSnippet(const wchar_t *replacement)
|
||||
{
|
||||
app->settings.snippets = {{L";zmtest", replacement}};
|
||||
prepare(L"prefix ;zmtest", false);
|
||||
record(L";zmtest");
|
||||
app->transform(0, 0, 0, field);
|
||||
}
|
||||
void finish()
|
||||
{
|
||||
@@ -268,6 +311,11 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
throw std::runtime_error("Native integration timed out");
|
||||
if (app->busy)
|
||||
{
|
||||
if (typeDuringMacros && ks::InputRegressionAccess::deferring(*app))
|
||||
{
|
||||
typeDuringMacros = false;
|
||||
typeKeys({VK_SPACE, 'X'});
|
||||
}
|
||||
if (typeDuringCorrection && ks::InputRegressionAccess::deferring(*app))
|
||||
{
|
||||
typeDuringCorrection = false;
|
||||
@@ -693,10 +741,28 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case 73:
|
||||
require(enterPresses == 1 && text() == L"prefix ;qz\r\n" &&
|
||||
!ks::InputRegressionAccess::suggestionsVisible(*app),
|
||||
"Enter without arrow navigation reaches the editor");
|
||||
"Enter reaches the editor while multiple suggestions await navigation");
|
||||
prepare(L"prefix ", false);
|
||||
typeKeys({VK_OEM_1, 'Q', 'Z', VK_OEM_MINUS, 'S'});
|
||||
stage = 75;
|
||||
break;
|
||||
case 75:
|
||||
require(ks::InputRegressionAccess::suggestionsVisible(*app) &&
|
||||
ks::InputRegressionAccess::suggestionCount(*app) == 1,
|
||||
"a filtered prefix leaves one visible suggestion");
|
||||
enterPresses = 0;
|
||||
typeKeys({VK_RETURN});
|
||||
break;
|
||||
case 76:
|
||||
require(text() == L"prefix second" && enterPresses == 0 &&
|
||||
!ks::InputRegressionAccess::suggestionsVisible(*app),
|
||||
"Enter accepts the only suggestion without arrows or forwarding the key");
|
||||
require(ks::readClipboard(app->window).text() == sentinel,
|
||||
"accepting a single suggestion restores the clipboard");
|
||||
app->resetInput();
|
||||
SetFocus(host);
|
||||
typeKeys({VK_OEM_1});
|
||||
stage = 74;
|
||||
break;
|
||||
case 74:
|
||||
if (ks::InputRegressionAccess::findingSuggestionCaret(*app))
|
||||
@@ -865,6 +931,118 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
require(enterPresses == 0, "unverified snippet never submits Enter even without logging");
|
||||
require(ks::readClipboard(app->window).text() == sentinel, "rejected snippet restores clipboard");
|
||||
pasteBehavior = 0;
|
||||
stage = 80;
|
||||
break;
|
||||
case 80:
|
||||
if (!captured) saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
|
||||
captured = true;
|
||||
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
|
||||
app->settings.autoCorrect = false;
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
observeMacros = true;
|
||||
typeDuringMacros = true;
|
||||
expandMacroSnippet(L"left{cursor}right{{ctrlr}}+{{altr}}+{{F8}}{pause:150}{{shiftr}}+{{left}}{enter}");
|
||||
break;
|
||||
case 81:
|
||||
require(rightAltAndCtrl && rightShift && ks::modifiersReleased(),
|
||||
"snippet chords press the specified right modifiers and release them");
|
||||
require(macroStart && macroEnd >= macroStart + 140, "snippet pause separates actual keyboard events");
|
||||
require(text() == L"prefix lef\r\n xright",
|
||||
"snippet macros start at the cursor marker and finish before buffered typing");
|
||||
require(ks::readClipboard(app->window).text() == sentinel, "snippet macros restore the clipboard");
|
||||
expandMacroSnippet(L"left{cursor}right{{ctrl}}+{{V}}");
|
||||
break;
|
||||
case 82:
|
||||
require(text() == L"prefix left" + sentinel + L"right", "a snippet paste chord uses the user's clipboard");
|
||||
enterPresses = 0;
|
||||
macroStart = 0;
|
||||
moveFocusOnMacro = true;
|
||||
expandMacroSnippet(L"done{{F8}}{pause:250}{enter}");
|
||||
break;
|
||||
case 83:
|
||||
require(macroStart && GetFocus() == host && text() == L"prefix done" && enterPresses == 0,
|
||||
"snippet macros stop when focus moves to a different control");
|
||||
observeMacros = false;
|
||||
moveFocusOnMacro = false;
|
||||
expandMacroSnippet(L"left{pause:50}{enter}{enter}right{cursor}!");
|
||||
stage = 92;
|
||||
break;
|
||||
case 92:
|
||||
require(text() == L"prefix left\r\n\r\nright!" && enterPresses == 2,
|
||||
"actions between text segments run before the next segment");
|
||||
require(LOWORD(SendMessageW(field, EM_GETSEL, 0, 0)) == GetWindowTextLengthW(field) - 1,
|
||||
"the cursor marker works in the final text segment");
|
||||
require(ks::readClipboard(app->window).text() == sentinel,
|
||||
"each verified snippet segment restores the clipboard");
|
||||
finish();
|
||||
break;
|
||||
case 93:
|
||||
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
|
||||
captured = true;
|
||||
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
|
||||
app->settings.autoCorrect = false;
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
require(ks::lower(ks::processName(host)) == L"chatgpt",
|
||||
"literal macro fixture runs under the Codex executable name");
|
||||
observeLiteralSequence = true;
|
||||
expandMacroSnippet(L"$example-skill{pause:500}{enter}{enter}{enter} Draft text{cursor}");
|
||||
break;
|
||||
case 94:
|
||||
require(text() == L"prefix $example-skill\r\n\r\n\r\n Draft text" && enterPresses == 3,
|
||||
"three Enter markers send three keys before the tail without requiring a suggestion");
|
||||
require(literalTextBeforeEnter == L"prefix $example-skill" && literalTextAt &&
|
||||
literalEnterAt >= literalTextAt + 475,
|
||||
"the first Enter follows the typed prefix and the configured 500 ms pause");
|
||||
require(ks::readClipboard(app->window).text() == sentinel,
|
||||
"literal snippet actions restore the clipboard");
|
||||
finish();
|
||||
break;
|
||||
case 84:
|
||||
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
|
||||
captured = true;
|
||||
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
|
||||
app->settings.snippets = {{L";r", L"rider ."}, {L"[g", L"expanded"}};
|
||||
app->settings.autoCorrect = false;
|
||||
ActivateKeyboardLayout(app->layouts[ru].handle, 0);
|
||||
prepare(L"", false);
|
||||
typeKeys({'G', 'J', 'L', 'L', 'T', VK_OEM_1, 'R'});
|
||||
break;
|
||||
case 85:
|
||||
require(text() == L"поддежк", "layout variant does not expand at the end of a word");
|
||||
prepare(L"поддека", false);
|
||||
SendMessageW(field, EM_SETSEL, 5, 5);
|
||||
typeKeys({VK_OEM_1, 'R'});
|
||||
break;
|
||||
case 86:
|
||||
require(text() == L"поддежкка", "layout variant does not expand at a caret inside existing text");
|
||||
require(LOWORD(SendMessageW(field, EM_GETSEL, 0, 0)) == 7,
|
||||
"skipping expansion restores the caret before the rest of the word");
|
||||
prepare(L"", false);
|
||||
typeKeys({'G', 'J', 'L', 'L', 'T'});
|
||||
break;
|
||||
case 87:
|
||||
require(text() == L"подде", "editor received the first part of the word");
|
||||
ks::InputRegressionAccess::expireRun(*app);
|
||||
typeKeys({VK_OEM_1, 'R'});
|
||||
break;
|
||||
case 88:
|
||||
require(text() == L"поддежк", "layout variant does not expand after the typing buffer expires");
|
||||
prepare(L"prefix (", false);
|
||||
typeKeys({VK_OEM_1, 'R'});
|
||||
break;
|
||||
case 89:
|
||||
require(text() == L"prefix (rider .", "layout variant expands after punctuation");
|
||||
prepare(L"token_", false);
|
||||
typeKeys({VK_OEM_4, 'G'});
|
||||
break;
|
||||
case 90:
|
||||
require(text() == L"token_хп", "word boundary also applies to other trigger prefixes");
|
||||
prepare(L"", false);
|
||||
typeKeys({VK_OEM_4, 'G'});
|
||||
break;
|
||||
case 91:
|
||||
require(text() == L"expanded", "another layout variant expands at the start of the field");
|
||||
require(ks::readClipboard(app->window).text() == sentinel, "word boundary check restores the clipboard");
|
||||
finish();
|
||||
break;
|
||||
case 20:
|
||||
@@ -1182,6 +1360,12 @@ int main(int argc, char **argv)
|
||||
stage = 64;
|
||||
if (argc > 1 && std::string(argv[1]) == "--snippet-autocomplete")
|
||||
stage = 66;
|
||||
if (argc > 1 && std::string(argv[1]) == "--snippet-macros")
|
||||
stage = 80;
|
||||
if (argc > 1 && std::string(argv[1]) == "--snippet-literal-keys")
|
||||
stage = 93;
|
||||
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
|
||||
stage = 84;
|
||||
SetTimer(host, 1, 100, nullptr);
|
||||
auto forwarding = SetWindowsHookExW(WH_KEYBOARD_LL,forwardingHook,GetModuleHandleW(nullptr),0);
|
||||
require(forwarding!=nullptr,"downstream forwarding fixture installed before application hook");
|
||||
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user