Compare commits
74
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
edb259e6bb | ||
|
|
9e287c3a1d | ||
|
|
5eda68a7a2 | ||
|
|
6cbb0639a1 | ||
|
|
2a6f9c7841 | ||
|
|
94b22fdd52 | ||
|
|
0d293429df | ||
|
|
83a099ab25 | ||
|
|
dfa2e38a0a | ||
|
|
24905e8ced | ||
|
|
b28a1f2e4d | ||
|
|
fde74c1a51 | ||
|
|
81fbe6a216 | ||
|
|
f1e5b2b772 | ||
|
|
e9e8b2099e | ||
|
|
dbb1fe166e | ||
|
|
98de2dc010 | ||
|
|
696f48209d | ||
|
|
5fae129ec0 | ||
|
|
870ad6c2b3 | ||
|
|
15b251e7fb | ||
|
|
ee9b953533 | ||
|
|
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 |
No files matched your search
+62
-8
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.111 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.7.4 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
@@ -10,7 +10,8 @@ add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
|
||||
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-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)
|
||||
@@ -26,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,12 +48,32 @@ foreach(utilityTarget StayHere StayHereTest)
|
||||
endif()
|
||||
endforeach()
|
||||
add_library(kscore src/lan_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp)
|
||||
target_sources(kscore PRIVATE src/drive_snapshot.cpp src/google_drive.cpp)
|
||||
foreach(field IN ITEMS ID SECRET)
|
||||
set(KS_GOOGLE_CLIENT_${field} "$ENV{KSWITCHER_GOOGLE_CLIENT_${field}}")
|
||||
if(NOT KS_GOOGLE_CLIENT_${field} MATCHES "^[A-Za-z0-9_.-]*$")
|
||||
message(FATAL_ERROR "Invalid Google OAuth client configuration.")
|
||||
endif()
|
||||
endforeach()
|
||||
configure_file(cmake/google_drive_oauth_config.h.in generated/google_drive_oauth_config.h @ONLY)
|
||||
target_link_libraries(KSwitcherFiles PRIVATE kscore)
|
||||
target_include_directories(kscore PUBLIC src PRIVATE vendor)
|
||||
target_include_directories(kscore PUBLIC src PRIVATE vendor "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||
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")
|
||||
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_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 dwmapi)
|
||||
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"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-history.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-screenshot.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-help.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-donate.ico")
|
||||
set_property(SOURCE resources/help.rc APPEND PROPERTY OBJECT_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/help-guide.md"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/README.md"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/FILES-UI.md"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/LAN-PREVIEW.md")
|
||||
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc resources/help.rc)
|
||||
target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
|
||||
target_link_libraries(KSwitcher PRIVATE kscore)
|
||||
add_executable(KSwitcherConfig WIN32 src/config_main.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
@@ -83,7 +104,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 resources/help.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)
|
||||
@@ -142,6 +163,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)
|
||||
@@ -160,6 +188,11 @@ 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
|
||||
@@ -205,8 +238,10 @@ else()
|
||||
endif()
|
||||
add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests)
|
||||
add_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout)
|
||||
add_test(NAME google-drive-settings-page COMMAND KSwitcherChatProfileTests --google-drive-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)
|
||||
@@ -261,7 +296,15 @@ add_test(NAME utilities-regressions COMMAND KSwitcherUtilitiesTests)
|
||||
add_test(NAME stayhere-lifecycle COMMAND powershell -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/stayhere.ps1" -Executable "$<TARGET_FILE:StayHereTest>")
|
||||
add_test(NAME scroll-regressions COMMAND KSwitcherScrollTests)
|
||||
add_test(NAME input-regressions COMMAND KSwitcherInputTests)
|
||||
add_dependencies(KSwitcherInputTests KSwitcherScreenshot)
|
||||
add_test(NAME clipboard-history-layout COMMAND KSwitcherInputTests --history-layout)
|
||||
set_tests_properties(clipboard-history-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
|
||||
add_test(NAME offline-help-window COMMAND KSwitcherInputTests --help-layout)
|
||||
set_tests_properties(offline-help-window PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
|
||||
add_test(NAME tray-input-pause COMMAND KSwitcherInputTests --input-pause)
|
||||
add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests)
|
||||
add_test(NAME screenshot-editor-layout COMMAND KSwitcherScreenshotUITests --layout-only)
|
||||
set_tests_properties(screenshot-editor-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
|
||||
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>")
|
||||
set_tests_properties(native-regressions PROPERTIES WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
@@ -288,3 +331,14 @@ else()
|
||||
target_link_options(KSwitcherSettingsMergeTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME settings-save-merge COMMAND KSwitcherSettingsMergeTests)
|
||||
|
||||
add_executable(KSwitcherDriveTests tests/drive_snapshot.cpp)
|
||||
target_include_directories(KSwitcherDriveTests PRIVATE vendor)
|
||||
target_link_libraries(KSwitcherDriveTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherDriveTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherDriveTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherDriveTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME google-drive-backup COMMAND KSwitcherDriveTests)
|
||||
+159
-18
@@ -29,14 +29,81 @@ 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, спочатку скопіюй його до локальної папки.
|
||||
Після успішного відкриття локального файла через Windows його шлях
|
||||
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
|
||||
його курсор приховано. При виборі
|
||||
з історії у командний рядок підставляється команда, яка повторює відкриття.
|
||||
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
|
||||
елемент через Windows.
|
||||
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
|
||||
@@ -49,7 +116,11 @@ Warning і початковий фокус на No.
|
||||
керують панеллю, коли список підказок закритий.
|
||||
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
|
||||
командний рядок порожній.
|
||||
Ctrl+← і Ctrl+→ зміщують розділювач видимих панелей на ширину одного символу.
|
||||
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
|
||||
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
|
||||
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
|
||||
курсора він мав інше оформлення.
|
||||
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
|
||||
текст із буфера обміну в позицію курсора або замінюють виділення.
|
||||
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
|
||||
@@ -58,12 +129,19 @@ Warning і початковий фокус на No.
|
||||
Enter передає порожній рядок у термінал.
|
||||
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
|
||||
командного рядка й виконують відповідну дію за тими самими правилами.
|
||||
Локальна команда запускається в папці активної панелі, яку показано
|
||||
перед командним рядком. Після перемикання панелі або переходу до іншої
|
||||
папки наступна команда використовує нову папку навіть у вже відкритому
|
||||
PowerShell. Якщо команда змінює папку (наприклад, через `cd`), панель
|
||||
переходить до неї, якщо користувач за цей час не змінив її розташування.
|
||||
Під час запуску термінала область виводу має темне тло, поки WebView2
|
||||
готує сторінку.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
- Під час набору локальної команди над полем з’являються підказки PowerShell.
|
||||
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
|
||||
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
|
||||
та шляхи відносно робочої папки термінала або активної панелі до запуску
|
||||
термінала. Після `cd ` список пропонує папки,
|
||||
та шляхи відносно робочої папки активної панелі.
|
||||
Після `cd ` список пропонує папки,
|
||||
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
|
||||
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
|
||||
Enter вставляє виділену, а клік вставляє підказку під вказівником.
|
||||
@@ -128,16 +206,26 @@ Warning і початковий фокус на No.
|
||||
|
||||
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
|
||||
курсора командного рядка або замінює виділення. Подвійні лапки додаються
|
||||
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
|
||||
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
|
||||
відкритої в активній панелі.
|
||||
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
|
||||
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу
|
||||
активна панель показує «Loading folder…» і зберігає попередній список до
|
||||
завершення сканування. Після переходу оновлюються шлях і список цієї панелі
|
||||
та командний рядок. Сусідня панель не перемальовується через цей перехід.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
|
||||
панелі показує «Reading» з лічильником прочитаних файлів і папок та
|
||||
підказкою [Esc].
|
||||
До завершення читання панель зберігає попередній список. Escape зупиняє
|
||||
сканування активної панелі й відкриває прочитану частину папки. Якщо
|
||||
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
|
||||
повторює сканування, щоб отримати повний список. Після переходу
|
||||
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
|
||||
панель не перемальовується через цей перехід.
|
||||
Якщо надійшов новіший запит, результат попереднього
|
||||
сканування пропускається. Після підтвердження UAC очікування списку
|
||||
від підвищеного процесу теж відбувається у фоні.
|
||||
- Якщо Windows відмовляє у правах для F5, F6, F7 або F8 на локальних
|
||||
дисках, Files пропонує повторити операцію з правами адміністратора.
|
||||
Після підтвердження UAC допоміжний процес обробляє захищені елементи
|
||||
поточної операції. Відмова в діалозі або в UAC зупиняє операцію.
|
||||
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
|
||||
зберігаються для наявних елементів, а підраховані через F3 розміри папок
|
||||
скидаються. F2 також виконує цю дію.
|
||||
@@ -215,11 +303,18 @@ Warning і початковий фокус на No.
|
||||
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
|
||||
Помилка збереження залишає відкритим редактор зі змінами.
|
||||
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
|
||||
у порядку їх відкриття. Коли відкрито лише 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` у клітинках.
|
||||
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
|
||||
@@ -236,13 +331,28 @@ Warning і початковий фокус на No.
|
||||
перерендерюється зі збереженням позиції прокрутки.
|
||||
Вебпосилання 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. Файл завантажується у тимчасову копію
|
||||
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
|
||||
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
|
||||
@@ -319,6 +429,21 @@ Warning і початковий фокус на No.
|
||||
|
||||
## Панелі
|
||||
|
||||
- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук
|
||||
файлів у поточній локальній папці та її підпапках. Поле приймає повне
|
||||
ім’я або маску без урахування регістру. `*` відповідає довільній
|
||||
послідовності символів, `?` — одному символу. Приховані та системні
|
||||
елементи можна включити прапорцем. Пошук не обходить junction та інші
|
||||
посилання на каталоги. Esc під час пошуку зупиняє обхід і показує знайдене.
|
||||
Результати відкриваються в тій самій панелі з відносними шляхами.
|
||||
Enter або подвійний клік відкриває папку й ставить курсор на файл.
|
||||
Esc у результатах повертає вихідну папку, курсор і позначки.
|
||||
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
|
||||
або поточним файлом, використовуючи папку іншої панелі як призначення.
|
||||
F8 і Shift+Delete використовують звичайні підтвердження. Успішно
|
||||
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
|
||||
з тією самою маскою й видимістю прихованих файлів.
|
||||
|
||||
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
|
||||
у відкритих локальних папках. Фокус залишається там, де був, а курсор
|
||||
лишається на поточному елементі, якщо той ще існує.
|
||||
@@ -354,11 +479,27 @@ Warning і початковий фокус на No.
|
||||
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
|
||||
|
||||
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
|
||||
Розділювач Size проходить по одній вертикалі в заголовку та списку, а праві краї підпису й значень вирівняні.
|
||||
|
||||
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
|
||||
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
|
||||
останні відвідані локальні папки. Повторний візит підіймає один запис
|
||||
угору, порядок зберігається після перезапуску. Enter або клік відкриває
|
||||
шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис.
|
||||
|
||||
- У локальному заголовку кнопки ← та → переходять назад і вперед
|
||||
в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..`
|
||||
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
|
||||
а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі.
|
||||
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
|
||||
трикрапка відкриває прихованих предків, а права — приховані папки
|
||||
попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L
|
||||
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
|
||||
а Esc повертає до тих самих панелей і курсора.
|
||||
|
||||
- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі.
|
||||
|
||||
## Спільні елементи діалогів
|
||||
|
||||
|
||||
+37
-22
@@ -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, confirm, then click **Save** in Settings. 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, choose **Remove**, then click **Save** 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,19 +38,21 @@ 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.
|
||||
The computer list and pairing controls are on the left, the monitor grid and
|
||||
input sharing are on the right, and file, log and help actions are below.
|
||||
In wide windows, the computer list and monitor layout grow side by side.
|
||||
In narrow windows, they stack above Diagnostic logs. The list identifies
|
||||
offline pairs, and Connection help appears below the input sharing controls.
|
||||
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.
|
||||
Enable discovery and click **Save** on each PC to make peers visible.
|
||||
Select each other, generate one code, and enter it on both. Click **Pair**, then
|
||||
**Apply** or **Save** on each PC within two minutes. Use **Apply** to keep the pairing status visible. Spaces, hyphens and uppercase hex are accepted.
|
||||
4. Pair each physical input source with every destination it must control. For
|
||||
unrestricted control from any PC, pair every pair of PCs. Drag monitors into
|
||||
neighboring grid cells and arrange the same physical layout relative to each
|
||||
local PC. For A → B → C, A sees B at (1,0), C at (2,0); B sees A at (-1,0),
|
||||
C at (1,0). Enable input sharing on all PCs. The button controls all pairs,
|
||||
independently of the selected list item. Positions save immediately.
|
||||
C at (1,0). Enable input sharing and click **Save** on all PCs to apply sharing
|
||||
and the monitor layout. The input sharing setting covers all pairs.
|
||||
5. Stop MWB or another mouse/keyboard router on both computers before trying
|
||||
KSwitcher input sharing, to avoid two tools forwarding the same events.
|
||||
6. Wait for the authenticated input connection. Move the cursor through the
|
||||
@@ -59,6 +62,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.
|
||||
@@ -105,8 +114,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**.
|
||||
|
||||
@@ -114,18 +114,20 @@ Run `build/KSwitcher.exe`, or extract `dist/KSwitcher-win-x64.zip` and run the e
|
||||
The build also refreshes the release copy in `build/release/`. Exit KSwitcher before rebuilding.
|
||||
The application lives in the notification area. Right-click its icon for Settings, Snippets and history.
|
||||
Double-click the tray icon to open Settings, the bold default menu item.
|
||||
Closing Settings with unsaved changes (including accepted auto-correction or OCR options)
|
||||
asks whether to save, discard changes, or keep editing. Unchanged settings close without a prompt.
|
||||
**Apply** and **Save** at the bottom of Settings commit the pending edits across every page,
|
||||
including Mouse, Manage computers and OpenBao. **Apply** keeps the current page open.
|
||||
**Save** closes Settings. With pending edits, **Cancel** or closing the window asks whether
|
||||
to discard them or keep editing. When there are no pending edits, **Close** exits without a prompt.
|
||||
If saving fails, the window stays open with your edits intact.
|
||||
Settings displays **No unsaved settings** when the draft matches the saved settings. If **Start with Windows** is enabled, **Save** remains available to recheck the autostart path.
|
||||
The Computers window applies and saves network changes immediately, separately from Settings.
|
||||
Pairing shows the target computer and remaining wait time; enter the same code and click **Pair** on both PCs.
|
||||
Enable discovery and click **Save** on each PC before looking for peers. Enter the same code and
|
||||
click **Pair**, then **Apply** or **Save**, on both PCs. Use **Apply** to watch the target and
|
||||
remaining wait time without closing Settings.
|
||||
The code stays visible for copying or retry until the pair is saved. A saved pair still requires input sharing to be enabled on both PCs.
|
||||
Input automatically tries direct TCP, reverse TCP (after 1.5 seconds), and encrypted UDP over discovery (after 5 seconds).
|
||||
Both PCs need an updated build for all fallback methods. The connection status identifies the selected transport.
|
||||
If attempts remain unsuccessful for 15 seconds, **Connection help** explains checks and provides copyable administrator PowerShell commands for the running executable on that PC. Run each PC's own command locally; rules allow only the local subnet. Commands are never executed automatically.
|
||||
**Unsaved changes — click Save to apply** appears for pending edits, including accepted
|
||||
chat-language, auto-correction and OCR changes. Cancelling a child dialog or restoring
|
||||
The Settings footer shows pending edits, including accepted chat-language, auto-correction and OCR changes. Cancelling a child dialog or restoring
|
||||
the original values clears its pending changes. Snippets saved in their own window
|
||||
remain saved independently; the Settings indicator reflects any other pending edits.
|
||||
Menus support access keys: press the underlined letter while the menu is open (for example,
|
||||
@@ -185,10 +187,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
|
||||
@@ -201,6 +203,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
|
||||
@@ -411,8 +435,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
|
||||
@@ -433,9 +458,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**
|
||||
@@ -461,10 +486,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
|
||||
@@ -473,14 +499,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 підказки відкриваються біля текстового курсора. Якщо редактор не
|
||||
надає його позицію, введіть повний тригер для розгортання сніпета.
|
||||
@@ -491,15 +519,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
|
||||
@@ -516,12 +564,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
|
||||
@@ -538,12 +586,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
|
||||
@@ -564,13 +610,13 @@ Scopes are saved with snippets and included in manual import/export and synchron
|
||||
retry recognition. Requires a Windows OCR language installed for the user profile; automatic
|
||||
failures are logged quietly. OCR sidecars count toward the history size limit and are removed
|
||||
with their images.
|
||||
- Optional Tesseract 5 support is available in **Settings → OCR options…**. Windows OCR remains
|
||||
- Optional Tesseract 5 support is available in **Settings → Clipboard → Image text recognition**. Windows OCR remains
|
||||
the default and has no Tesseract dependency. Install the 64-bit Tesseract 5 Windows package
|
||||
separately, then enable it and choose language codes such as `ukr+eng+rus`. Leave the executable
|
||||
path blank to detect a standard installation, or select `tesseract.exe`; its neighboring
|
||||
`libtesseract-5.dll`, dependencies and `tessdata` language files are required. **Check installation**
|
||||
validates the selected models. **Download Tesseract…** opens the Windows installer page in your
|
||||
browser. No packages or models are downloaded automatically.
|
||||
browser. Use **Apply** or **Save** in Settings to commit OCR changes.
|
||||
Tesseract processes screenshots locally in memory with a 30-second recognition deadline.
|
||||
Changing engine, executable path or languages refreshes cached image text in the background.
|
||||
- History exclusion flags and excluded processes, pause/resume, count/size limits.
|
||||
@@ -664,9 +710,57 @@ This is a working native implementation, not a claim of complete UI/release pari
|
||||
The Windows focus/injection rules still apply: an unelevated process cannot edit an elevated app.
|
||||
Conversion is cancelled rather than pasting into a different window or replacing unverified recent text.
|
||||
|
||||
## Google Drive settings backup
|
||||
|
||||
Open **Settings → Sync → Google Drive** and choose **Connect** to authorize
|
||||
KSwitcher in your browser. To sync between PCs, check **Use Google Drive for
|
||||
automatic synchronization**, then click **Apply** or **Save**. On the first
|
||||
PC, choose **Upload local settings to sync profile** to create the initial
|
||||
profile. On the other PCs, connect to the same account, enable Google Drive
|
||||
sync and choose **Sync now**. The resident syncs at startup, every ten minutes
|
||||
and after saving. Independent changes merge, and concurrent edits to the same
|
||||
setting can be reviewed under **Resolve individual conflicts**.
|
||||
|
||||
Each PC uses one automatic provider. Enabling Google Drive turns off OpenBao
|
||||
sync and keeps its connection details. Enabling OpenBao turns off Google Drive
|
||||
sync. Manual Google Drive backups remain available with either provider.
|
||||
Turn off Google Drive sync and apply the change before switching Google
|
||||
accounts or disconnecting.
|
||||
|
||||
**Back up saved settings** adds a copy of your last applied settings to the
|
||||
backup list. The list shows the backup date, source and size, newest first.
|
||||
Use **Load older backups** to see more when available. Select a row and choose
|
||||
**Restore selected backup** to load that copy into the draft after confirmation. Review the result
|
||||
and choose **Apply** or **Save**. **Disconnect** removes the refresh token from
|
||||
Windows Credential Manager and leaves existing backups in Google Drive.
|
||||
The automatic sync profile is separate from manual backup history. Applying
|
||||
a manual restore makes it a local change that the active provider can sync.
|
||||
|
||||
Backups include layouts, shortcuts, snippets, compatible language and mouse
|
||||
profiles, personal dictionaries and clipboard history preferences. Windows
|
||||
autostart, diagnostic logging, credentials, paired computer state, clipboard
|
||||
contents, screenshots and local executable paths stay on the computer.
|
||||
Install any Windows layouts used by the backup before restoring. Each backup
|
||||
is limited to 2 MiB.
|
||||
|
||||
The Win32 app can read KSwitcher-New's `kswitcher-drive-backup-v1` snapshots
|
||||
when both builds have access to the same Google application's private Drive
|
||||
folder. Win32 imports supported settings and keeps destination values for
|
||||
fields absent from the backup. Preview-only settings such as the theme and
|
||||
disabled snippets have no Win32 equivalent. Win32 writes its own versioned
|
||||
snapshot, which KSwitcher-New does not import.
|
||||
|
||||
To enable the page in a build, supply `KSWITCHER_GOOGLE_CLIENT_ID` and
|
||||
`KSWITCHER_GOOGLE_CLIENT_SECRET` in the build environment before running
|
||||
`build.ps1` or configuring CMake. Use a Google OAuth **Desktop app** client
|
||||
with the Drive API enabled. Use the same authorized Google application as
|
||||
KSwitcher-New for access to its existing backups. The browser flow uses
|
||||
PKCE and requests the `drive.appdata` scope. Builds without both values
|
||||
show the page with its actions disabled.
|
||||
|
||||
## 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.
|
||||
@@ -678,23 +772,22 @@ 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.
|
||||
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.
|
||||
Check **Enable synchronization**, enter the connection details and click **Save** at the bottom of
|
||||
Settings. Use **Sync now** on the OpenBao page to start an immediate sync with the saved connection.
|
||||
To disable synchronization and keep the saved password, uncheck **Enable synchronization** and click
|
||||
**Save**.
|
||||
**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
|
||||
profile. HTTPS certificate validation is mandatory and redirects are refused. Login tokens are
|
||||
kept in memory for one sync attempt, with best-effort self-revocation afterwards. Configure bounded
|
||||
token lifetimes on the server as well (for example a 5-minute default and 10-minute maximum).
|
||||
**Disconnect / forget password** disables synchronization and removes the current connection's
|
||||
Choose **Disconnect / forget password**, then click **Save** to disable synchronization and remove the current connection's
|
||||
saved credential. A request already sent to the server may still complete; its downloaded settings
|
||||
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, **Sync now** 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.
|
||||
@@ -703,7 +796,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 pending edits to shared settings 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
|
||||
@@ -742,8 +835,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**. 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
|
||||
@@ -832,7 +925,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
|
||||
@@ -999,8 +1092,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
|
||||
|
||||
@@ -1028,7 +1120,7 @@ History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc**
|
||||
|
||||
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 helpers exit after 30 seconds, and closing the history host stops its helpers. 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.
|
||||
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.
|
||||
|
||||
|
||||
+248
-2
@@ -1,5 +1,251 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.7.4 — 2026-11-25
|
||||
|
||||
- **Settings → Sync → Google Drive** supports automatic synchronization and a dated list of manual backups. Only one automatic provider is active per PC. Restore a selected backup into the Settings draft and review it before pressing **Apply** or **Save**.
|
||||
- **Help → User guide** opens a searchable offline guide with the current keyboard shortcuts and built-in manuals. The tray also has **Help → About KSwitcher** and a separate coffee icon for **Donate via Monobank**.
|
||||
- Clipboard history, the screenshot editor and Help have distinct window and taskbar icons. Clipboard history and the screenshot editor use the Settings palette. OCR is a child page under **Clipboard**, and clipboard exclusions can be added using the window picker.
|
||||
- The editors on **Custom replacements**, **Snippets** and **Mouse** use the available window height. The computer list, monitor layout and action rows on **Manage computers** are aligned.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Settings → Sync → Google Drive** підтримує автосинхронізацію та список ручних резервних копій із датами. На кожному ПК активний лише один автоматичний провайдер. Вибрана копія завантажується в чернетку, яку можна переглянути перед **Apply** або **Save**.
|
||||
- **Help → User guide** відкриває офлайн-довідку з пошуком, поточними гарячими клавішами та вбудованими посібниками. У треї також є **Help → About KSwitcher** і чашка біля окремого пункту **Donate via Monobank**.
|
||||
- Історія буфера, редактор скріншотів і довідка мають окремі значки вікон і панелі завдань. Історія та редактор використовують палітру Settings. OCR винесено на дочірню сторінку **Clipboard**, а програми до винятків буфера можна додавати через приціл.
|
||||
- Редактори **Custom replacements**, **Snippets** і **Mouse** розтягуються за висотою вікна. На **Manage computers** вирівняно список ПК, схему моніторів і ряди дій.
|
||||
|
||||
## v0.7.3 — 2026-11-24
|
||||
|
||||
- **Apply** commits pending edits across Settings and keeps the current page open. **Save** commits the same edits and closes Settings. **Close** appears when the draft is clean. **Cancel** asks before discarding pending edits.
|
||||
- Mouse actions, discovery, pairing, monitor positions, input sharing, trusted clients, diagnostic log permissions and the OpenBao connection are part of the Settings draft. For new LAN pairs, enter the same code and choose **Pair**, then **Apply** or **Save**, on both PCs. Use **Sync now** to synchronize with a saved OpenBao connection.
|
||||
- Settings and the diagnostic log viewer follow the Windows accent and contrast settings.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Apply** зберігає правки всіх розділів Settings і залишає поточну сторінку відкритою. **Save** зберігає ті самі правки й закриває Settings. За відсутності незбережених правок доступна кнопка **Close**. **Cancel** запитує підтвердження перед відкиданням чернетки.
|
||||
- Дії миші, пошук комп’ютерів, сполучення, розташування моніторів, спільний ввід, довірені клієнти, дозвіл на завантаження журналів і підключення OpenBao входять до чернетки Settings. Для нового сполучення введіть однаковий код і натисніть **Pair**, а тоді **Apply** або **Save** на обох ПК. **Sync now** запускає синхронізацію зі збереженим підключенням OpenBao.
|
||||
- Settings і переглядач діагностичних журналів враховують акцентний колір і параметри контрастності Windows.
|
||||
|
||||
## 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.
|
||||
@@ -450,8 +696,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 @@
|
||||
dbc8fd01ed92849bab4516d83e6b51defaca6984d9fa2ff8bccd7cf84760a552 KSwitcher-win-x64.zip
|
||||
0209951cbe8c5a202dba12a807895ce7146dc6640f96704f6a4aa9afaa4fd3af KSwitcher-win-x64.zip
|
||||
+74
-74
@@ -1,166 +1,166 @@
|
||||
{
|
||||
"version": "0.6.111",
|
||||
"version": "0.7.4",
|
||||
"schema": 1,
|
||||
"files": [
|
||||
{
|
||||
"size": 2479104,
|
||||
"path": "KSwitcher.exe",
|
||||
"sha256": "6b4df34f75dc159b98bb1b442f611faa69d7b0a4c77264c07516394396dcce5d"
|
||||
"size": 3082752,
|
||||
"sha256": "31a41c6ecc3387fc9f2b3f228ed64fa916d723654c02dc19bbbb558f94def4b8",
|
||||
"path": "KSwitcher.exe"
|
||||
},
|
||||
{
|
||||
"size": 2458112,
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"sha256": "83fc9cde793bb447d750328fafa8305a866bc8de54803c230b31a45a026e50bb"
|
||||
"size": 2832384,
|
||||
"sha256": "b993c050a96215aa63be97e9f05764ead13fcaf4b68fbb99f3d2f9a7d49a629a",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
},
|
||||
{
|
||||
"size": 3060224,
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"sha256": "5b392de89d073ca5a873133fa2fc35fde44332126ef6e1817a1a87ceb90bb7ae"
|
||||
"size": 3187712,
|
||||
"sha256": "eff5921b9067e0f4805c83d3cea10ddaa32b0b4e29f408b71b1004f78754afb9",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
},
|
||||
{
|
||||
"size": 4214272,
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"sha256": "f6ea287774d81d6c28e4dbba87d201d831f958f4cfe9fbd002b7d6a54e287b3c"
|
||||
"size": 4409344,
|
||||
"sha256": "569d016d1eff9519cd33aa848723cea0365cbebe9333ed390245d098c4074d8e",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
},
|
||||
{
|
||||
"size": 194912,
|
||||
"path": "WebView2Loader.dll",
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"path": "WebView2Loader.dll"
|
||||
},
|
||||
{
|
||||
"size": 1103,
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"path": "terminal/addon-fit-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 1521,
|
||||
"path": "terminal/addon-fit.js",
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"path": "terminal/addon-fit.js"
|
||||
},
|
||||
{
|
||||
"size": 527,
|
||||
"path": "terminal/index.html",
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"path": "terminal/index.html"
|
||||
},
|
||||
{
|
||||
"size": 1073,
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"path": "terminal/markdown-it-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 100786,
|
||||
"path": "terminal/markdown-it.js",
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"path": "terminal/markdown-it.js"
|
||||
},
|
||||
{
|
||||
"size": 3530,
|
||||
"path": "terminal/markdown.html",
|
||||
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
|
||||
"size": 3599,
|
||||
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
|
||||
"path": "terminal/markdown.html"
|
||||
},
|
||||
{
|
||||
"size": 14987,
|
||||
"path": "terminal/markdown.js",
|
||||
"sha256": "5d1e824df1c3570877e985de0cfaae3f2984ceef7fe23bf4c5ade3c890a93223"
|
||||
"size": 17575,
|
||||
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
|
||||
"path": "terminal/markdown.js"
|
||||
},
|
||||
{
|
||||
"size": 1089,
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"path": "terminal/mermaid-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 5537838,
|
||||
"path": "terminal/mermaid.js",
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"path": "terminal/mermaid.js"
|
||||
},
|
||||
{
|
||||
"size": 5033,
|
||||
"path": "terminal/terminal.js",
|
||||
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a"
|
||||
"size": 5065,
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
|
||||
"path": "terminal/terminal.js"
|
||||
},
|
||||
{
|
||||
"size": 1261,
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"path": "terminal/xterm-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 7112,
|
||||
"path": "terminal/xterm.css",
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"path": "terminal/xterm.css"
|
||||
},
|
||||
{
|
||||
"size": 488663,
|
||||
"path": "terminal/xterm.js",
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"path": "terminal/xterm.js"
|
||||
},
|
||||
{
|
||||
"size": 4401,
|
||||
"path": "LICENSE",
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"path": "LICENSE"
|
||||
},
|
||||
{
|
||||
"size": 1096,
|
||||
"path": "json-LICENSE.txt",
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"path": "json-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 883,
|
||||
"path": "files-text-license.txt",
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"path": "files-text-license.txt"
|
||||
},
|
||||
{
|
||||
"size": 95289,
|
||||
"path": "README.md",
|
||||
"sha256": "fcbd14b6190dc2a3575a4bc4be7229540c647022cb038d33ec4ac22176c67a9e"
|
||||
"size": 105515,
|
||||
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01",
|
||||
"path": "README.md"
|
||||
},
|
||||
{
|
||||
"size": 11577,
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
|
||||
"size": 12804,
|
||||
"sha256": "f5bfc48e44af14dd6c45f56f689b4034ef1f7bdaca02f9d15ebc32af387366cf",
|
||||
"path": "LAN-PREVIEW.md"
|
||||
},
|
||||
{
|
||||
"size": 732485,
|
||||
"path": "dictionaries/en.txt",
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"path": "dictionaries/en.txt"
|
||||
},
|
||||
{
|
||||
"size": 20566,
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
|
||||
},
|
||||
{
|
||||
"size": 2265,
|
||||
"path": "dictionaries/README.md",
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"path": "dictionaries/README.md"
|
||||
},
|
||||
{
|
||||
"size": 1109134,
|
||||
"path": "dictionaries/ru.txt",
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"path": "dictionaries/ru.txt"
|
||||
},
|
||||
{
|
||||
"size": 1280,
|
||||
"path": "dictionaries/sources.json",
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"path": "dictionaries/sources.json"
|
||||
},
|
||||
{
|
||||
"size": 940799,
|
||||
"path": "dictionaries/uk.txt",
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"path": "dictionaries/uk.txt"
|
||||
},
|
||||
{
|
||||
"size": 993,
|
||||
"path": "tools/README.txt",
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"path": "tools/README.txt"
|
||||
},
|
||||
{
|
||||
"size": 133120,
|
||||
"path": "tools/StayHere.exe",
|
||||
"sha256": "a2e34f817ecdc88b870d5e93418d8364a5fe8af81496b364e10b0f6587492e0d"
|
||||
"sha256": "ba891b6cc5d35d26520fa9ad34e136124e90ed10e0cff2f25dedadd0b48fb88e",
|
||||
"path": "tools/StayHere.exe"
|
||||
},
|
||||
{
|
||||
"size": 2796,
|
||||
"path": "tools/StayHere-README.md",
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"path": "tools/StayHere-README.md"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -15,14 +15,19 @@ Set-Content -LiteralPath (Join-Path (Split-Path $executablePath) '.local-dev') -
|
||||
Push-Location $root
|
||||
try {
|
||||
$common = @('-std=c++20','-Os','-DNDEBUG','-DUNICODE','-D_UNICODE','-DWIN32_LEAN_AND_MEAN','-DNOMINMAX','-D_WIN32_WINNT=0x0A00','-Wall','-Wextra','-Wno-missing-field-initializers','-Isrc','-Ivendor','-ffunction-sections','-fdata-sections')
|
||||
$libs = @('-lws2_32','-lbcrypt','-liphlpapi','-lwinhttp','-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore')
|
||||
$libs = @('-lws2_32','-lbcrypt','-liphlpapi','-lwinhttp','-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore','-ldwmapi')
|
||||
$utilityDirectory = Join-Path (Split-Path $executablePath) 'tools'
|
||||
New-Item -ItemType Directory -Force $utilityDirectory,build/release/tools | Out-Null
|
||||
$stayHere = Join-Path $utilityDirectory 'StayHere.exe'
|
||||
& $compiler @common -Werror -mwindows -municode -static -s utilities/StayHere/main.cpp -luser32 -lshell32 -lgdi32 -lwtsapi32 -o $stayHere
|
||||
if ($LASTEXITCODE) { throw 'StayHere build failed' }
|
||||
Copy-Item -LiteralPath $stayHere -Destination build/release/tools/StayHere.exe -Force
|
||||
foreach ($name in @('lan_files','lan_channel','lan_input','lan','lan_pairing','core','platform','autostart','autocorrect','storage','sync','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) {
|
||||
$filesBuild = Join-Path $outDir 'files-cmake'
|
||||
& cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel
|
||||
if ($LASTEXITCODE) { throw 'CMake configuration failed' }
|
||||
$common += "-I$(Join-Path $filesBuild 'generated')"
|
||||
$driveObjects = @('build/drive_snapshot.o','build/google_drive.o')
|
||||
foreach ($name in @('lan_files','lan_channel','lan_input','lan','lan_pairing','core','platform','autostart','autocorrect','storage','sync','drive_snapshot','google_drive','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) {
|
||||
& $compiler @common -c "src/$name.cpp" -o "build/$name.o"
|
||||
if ($LASTEXITCODE) { throw "Compilation failed: $name" }
|
||||
}
|
||||
@@ -32,14 +37,16 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Configurator UI compilation failed' }
|
||||
& windres --codepage=65001 resources/app.rc -O coff -o build/app-res.o
|
||||
if ($LASTEXITCODE) { throw 'Resource compilation failed' }
|
||||
& windres --codepage=65001 resources/help.rc -O coff -o build/help-res.o
|
||||
if ($LASTEXITCODE) { throw 'Help resource compilation failed' }
|
||||
& windres --codepage=65001 -DKS_SCREENSHOT_RESOURCES resources/app.rc -O coff -o build/screenshot-res.o
|
||||
if ($LASTEXITCODE) { throw 'Screenshot resource compilation failed' }
|
||||
New-Item -ItemType Directory -Force build/release | Out-Null
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' 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_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o @libs -o $executablePath
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' 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 @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o build/help-res.o @libs -o $executablePath
|
||||
if ($LASTEXITCODE) { throw 'Link failed' }
|
||||
Copy-Item -LiteralPath $executablePath -Destination build/release/KSwitcher.exe -Force
|
||||
$configPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Config.exe'
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' 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/storage.o build/sync.o build/ocr.o build/configuration.o build/config_main.o build/ui-config.o build/app-res.o @libs -o $configPath
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' 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/storage.o build/sync.o @driveObjects build/ocr.o build/configuration.o build/config_main.o build/ui-config.o build/app-res.o @libs -o $configPath
|
||||
if ($LASTEXITCODE) { throw 'Configurator link failed' }
|
||||
Copy-Item -LiteralPath $configPath -Destination build/release/KSwitcher.Config.exe -Force
|
||||
$screenshotPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Screenshot.exe'
|
||||
@@ -47,9 +54,6 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Screenshot link failed' }
|
||||
Copy-Item -LiteralPath $screenshotPath -Destination build/release/KSwitcher.Screenshot.exe -Force
|
||||
$filesPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Files.exe'
|
||||
$filesBuild = Join-Path $outDir 'files-cmake'
|
||||
& cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel
|
||||
if ($LASTEXITCODE) { throw 'File manager configuration failed' }
|
||||
& cmake --build $filesBuild --target KSwitcherFiles --parallel 8
|
||||
if ($LASTEXITCODE) { throw 'File manager build failed' }
|
||||
Copy-Item -LiteralPath (Join-Path $filesBuild 'KSwitcher.Files.exe') -Destination $filesPath -Force
|
||||
@@ -63,10 +67,14 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Files text test build failed' }
|
||||
& (Join-Path $filesBuild 'KSwitcherFilesTextTests.exe')
|
||||
if ($LASTEXITCODE) { throw 'Files text tests failed' }
|
||||
& $compiler @common -Werror tests/settings_merge.cpp build/sync.o build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
|
||||
& $compiler @common -Werror tests/settings_merge.cpp build/sync.o @driveObjects build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Settings merge test build failed' }
|
||||
& .\build\KSwitcherSettingsMergeTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Settings merge tests failed' }
|
||||
& $compiler @common -Werror tests/drive_snapshot.cpp build/sync.o @driveObjects build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherDriveTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Google Drive snapshot test build failed' }
|
||||
& .\build\KSwitcherDriveTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Google Drive snapshot tests failed' }
|
||||
& $compiler @common -Werror tests/lan_clipboard.cpp build/lan_channel.o build/lan_pairing.o build/core.o build/platform.o @libs -static -s -o build/KSwitcherLanClipboardTests.exe
|
||||
if ($LASTEXITCODE) { throw 'LAN clipboard test build failed' }
|
||||
& .\build\KSwitcherLanClipboardTests.exe
|
||||
@@ -95,7 +103,7 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Dictionary test build failed' }
|
||||
& .\build\KSwitcherDictionaryTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Dictionary tests failed' }
|
||||
& $compiler @common tests/sync.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/storage.o build/sync.o build/ocr.o @libs -static -s -o build/KSwitcherSyncTests.exe
|
||||
& $compiler @common tests/sync.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/storage.o build/sync.o @driveObjects build/ocr.o @libs -static -s -o build/KSwitcherSyncTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Sync test build failed' }
|
||||
& .\build\KSwitcherSyncTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Sync tests failed' }
|
||||
@@ -103,18 +111,24 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Scroll test build failed' }
|
||||
& .\build\KSwitcherScrollTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Scroll tests failed' }
|
||||
& $compiler @common tests/tests.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 @libs -static -s -o build/KSwitcherTests.exe
|
||||
& $compiler @common tests/tests.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 @driveObjects build/ocr.o build/richtext.o build/update.o @libs -static -s -o build/KSwitcherTests.exe
|
||||
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 @driveObjects 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 build/help-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' }
|
||||
& $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
|
||||
& .\build\KSwitcherInputTests.exe --help-layout
|
||||
if ($LASTEXITCODE) { throw 'Offline help test 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 @driveObjects 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
|
||||
if ($LASTEXITCODE) { throw 'Chat profile tests failed' }
|
||||
& .\build\KSwitcherChatProfileTests.exe --google-drive-layout
|
||||
if ($LASTEXITCODE) { throw 'Google Drive Settings test failed' }
|
||||
& $compiler @common tests/screenshot_ui.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/ocr.o build/screenshot-res.o @libs -static -s -o build/KSwitcherScreenshotUITests.exe
|
||||
if ($LASTEXITCODE) { throw 'Screenshot UI test build failed' }
|
||||
& .\build\KSwitcherScreenshotUITests.exe
|
||||
@@ -135,7 +149,7 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Updater progress UI tests failed' }
|
||||
}
|
||||
if ($Far) {
|
||||
& $compiler @common tests/far_snippets.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 -mwindows -municode -static -s -o build/KSwitcherFarSnippetTests.exe
|
||||
& $compiler @common tests/far_snippets.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 @driveObjects 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 -mwindows -municode -static -s -o build/KSwitcherFarSnippetTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Far snippet test build failed' }
|
||||
$fixture = Start-Process -FilePath (Join-Path $outDir 'KSwitcherFarSnippetTests.exe') -WindowStyle Hidden -Wait -PassThru
|
||||
Get-Content -LiteralPath (Join-Path $outDir 'far-snippets.log')
|
||||
@@ -161,14 +175,14 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Image capture test build failed' }
|
||||
& $captureTest
|
||||
if ($LASTEXITCODE) { throw 'Image capture tests failed' }
|
||||
& $compiler @common tests/integration.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/KSwitcherIntegration.exe
|
||||
& $compiler @common tests/integration.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 @driveObjects 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/KSwitcherIntegration.exe
|
||||
if ($LASTEXITCODE) { throw 'Integration test build failed' }
|
||||
& .\build\KSwitcherIntegration.exe
|
||||
if ($LASTEXITCODE) { throw 'Integration tests failed' }
|
||||
}
|
||||
if ($Ocr) {
|
||||
$ocrTest = Join-Path (Split-Path $executablePath) 'KSwitcherOcrTests.exe'
|
||||
& $compiler @common tests/ocr.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 $ocrTest
|
||||
& $compiler @common tests/ocr.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 @driveObjects 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 $ocrTest
|
||||
if ($LASTEXITCODE) { throw 'OCR test build failed' }
|
||||
& $ocrTest
|
||||
if ($LASTEXITCODE) { throw 'OCR tests failed' }
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
#pragma once
|
||||
#define KS_GOOGLE_CLIENT_ID "@KS_GOOGLE_CLIENT_ID@"
|
||||
#define KS_GOOGLE_CLIENT_SECRET "@KS_GOOGLE_CLIENT_SECRET@"
|
||||
+8
-3
@@ -2,6 +2,11 @@
|
||||
#include <windows.h>
|
||||
#include "resource.h"
|
||||
IDI_KSWITCHER ICON "kswitcher.ico"
|
||||
IDI_KSWITCHER_PAUSED ICON "kswitcher-paused.ico"
|
||||
IDI_KSWITCHER_HISTORY ICON "kswitcher-history.ico"
|
||||
IDI_KSWITCHER_SCREENSHOT ICON "kswitcher-screenshot.ico"
|
||||
IDI_KSWITCHER_HELP ICON "kswitcher-help.ico"
|
||||
IDI_KSWITCHER_DONATE ICON "kswitcher-donate.ico"
|
||||
#ifdef KS_SCREENSHOT_RESOURCES
|
||||
IDI_SCREENSHOT_QUESTION ICON "icons/question.ico"
|
||||
IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
@@ -9,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
201 RCDATA "update.ps1"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 0,6,111,0
|
||||
PRODUCTVERSION 0,6,111,0
|
||||
FILEVERSION 0,7,4,0
|
||||
PRODUCTVERSION 0,7,4,0
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
BEGIN
|
||||
@@ -20,7 +25,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
||||
VALUE "ProductName", "KSwitcher"
|
||||
VALUE "FileVersion", "0.6.111"
|
||||
VALUE "FileVersion", "0.7.4"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
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"
|
||||
|
||||
@@ -50,6 +51,41 @@ 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"
|
||||
@@ -60,6 +96,7 @@ BEGIN
|
||||
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
|
||||
|
||||
@@ -167,6 +204,14 @@ BEGIN
|
||||
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
|
||||
@@ -307,3 +352,83 @@ 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
|
||||
|
||||
116 DIALOGEX 0, 0, 300, 98
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Find files"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "File &name or mask", 483, 16, 18, 268, 12
|
||||
FAR_EDIT(480, 0, 16, 32, 268, 15)
|
||||
AUTOCHECKBOX "Include &hidden and system files", 481, 16, 53, 268, 12
|
||||
LTEXT "", 482, 10, 69, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Find", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 68, 73, 80, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 73, 80, 17
|
||||
END
|
||||
|
||||
117 DIALOGEX 0, 0, 290, 83
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Go to folder"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Folder &path (Tab completes)", 486, 16, 18, 258, 12
|
||||
FAR_EDIT(485, 0, 16, 32, 258, 15)
|
||||
LTEXT "", 487, 10, 54, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
|
||||
END
|
||||
@@ -0,0 +1,63 @@
|
||||
# Getting started
|
||||
|
||||
KSwitcher runs in the Windows notification area. Right-click the KSwitcher icon to open Settings, Clipboard history, Capture screen region, Files, Snippets, Keyboard shortcuts, Tools, Help and other commands. Windows may place the icon under Show hidden icons.
|
||||
|
||||
Use Keyboard shortcuts in this help window to see the shortcuts currently configured on this PC. To change them, open Settings → Shortcuts, select a field, press the desired combination and choose Apply or Save.
|
||||
|
||||
Choose a topic on the left or search the guide. The detailed manuals are part of the application and can be read offline.
|
||||
|
||||
# Keyboard and correction
|
||||
|
||||
KSwitcher can switch between installed layouts, convert text typed in the wrong layout, change case, transliterate and undo a recent transformation. Apply a text shortcut to selected text or let KSwitcher work with the recent text detected in the active application. KSwitcher skips transformations when it cannot verify the target or text.
|
||||
|
||||
Settings → Languages controls layout order and application or chat profiles. The layouts themselves are installed through Windows. Application and chat rules can narrow the layouts cycled for a particular context.
|
||||
|
||||
Settings → General → Correction options controls automatic correction. Its child pages cover offline dictionaries, exceptions, personal dictionaries, word boundaries and custom replacements. For a custom replacement, put one typo=correction pair per line.
|
||||
|
||||
# Clipboard history and OCR
|
||||
|
||||
Open Clipboard history from the tray or its configured shortcut. Search the list, filter it by computer or select Pinned only. Choose an entry and press Enter to paste, Shift+Enter for plain text, Ctrl+P to pin or unpin, Delete to remove it or Ctrl+O to open the full entry. Ctrl+1 through Ctrl+9 paste entries by position.
|
||||
|
||||
Open an image in the screenshot editor or use Copy text from image (OCR) in the context menu. Image text can also be searched once recognized. Settings → Clipboard controls recording, size limits and excluded apps. Settings → Clipboard → Image text recognition controls Windows OCR or optional local Tesseract.
|
||||
|
||||
Clear history deletes saved entries, including pinned ones, after confirmation. Use Pause clipboard history in the tray to suspend recording temporarily.
|
||||
|
||||
# Screenshots and annotations
|
||||
|
||||
Choose Capture screen region from the tray or use the configured shortcut. Drag around the area to capture. The capture is copied, and Settings can open the editor automatically. You can also open an image from Clipboard history.
|
||||
|
||||
The editor offers pointer selection, numbered markers, arrows, straight lines, shapes, pencil strokes, highlighting, text, color and undo/redo. Pick a mark with the pointer to edit its geometry or text. Line style, arrowheads and pencil smoothing are available below the toolbar.
|
||||
|
||||
Copy sends the annotated screenshot to the clipboard. Save exports a full-resolution PNG. Ctrl+Shift+S chooses another file. Ctrl+mouse wheel zooms, Ctrl+0 fits the image and the middle mouse button pans.
|
||||
|
||||
# Snippets and mouse profiles
|
||||
|
||||
In Settings → Snippets, add a trigger and its replacement text. Restrict it to specific applications when needed. Insert macro or marker opens the available insertions. The detailed manual describes autocomplete, cursor markers and supported macros.
|
||||
|
||||
In Settings → Mouse, create a profile for one or more applications and assign actions to mouse events. The Global profile is the fallback. Use Test mouse buttons here to check what the device reports.
|
||||
|
||||
# Settings, backup and sync
|
||||
|
||||
Use Apply to save edits and keep Settings open, or Save to save and close. Import loads settings for review before applying them. Export writes settings to a file.
|
||||
|
||||
Under Settings → Sync, configure OpenBao or Google Drive. A PC uses one automatic provider at a time. Use Sync now for an immediate sync and Resolve individual conflicts to review conflicting changes when available.
|
||||
|
||||
Manual Google Drive copies are separate from the auto-sync profile. Back up saved settings creates a dated copy. Restore selected backup loads that copy into the Settings draft. Review it before applying, especially if automatic sync is on. Google Drive features require a build with OAuth configured.
|
||||
|
||||
# Paired computers
|
||||
|
||||
Open Settings → Computers → Manage computers. Enable discovery on both PCs and use the same pairing code to connect them. Drag the monitors into position and enable input sharing to move the pointer across shared edges. Each PC can control whether its paired computers may download diagnostic logs.
|
||||
|
||||
The paired computers manual explains discovery, trust, sharing, file operations and troubleshooting in more detail.
|
||||
|
||||
# KSwitcher Files
|
||||
|
||||
Choose Files from the tray. Use the two file panels to browse, move and copy files. The manual covers local and remote locations, FTP, the viewer and editor, comparisons, search, dialogs, the integrated terminal and keyboard operation.
|
||||
|
||||
# Tray, updates and diagnostics
|
||||
|
||||
Use the tray menu to pause or resume input processing, keep the display awake, pause clipboard history, open the data folder, check for updates or exit. Tools lists supported portable utilities placed in the tools folder.
|
||||
|
||||
If a shortcut stops working, check whether input processing is paused and whether another application owns the binding. If a paired PC is missing, check discovery and access on both computers. Settings → Diagnostics and View log in the tray provide logs. Settings → MCP displays management integration settings.
|
||||
|
||||
Donate via Monobank opens the project's donation jar in the browser. Choose Help → About KSwitcher to see the running version.
|
||||
@@ -0,0 +1,6 @@
|
||||
#include <windows.h>
|
||||
#include "resource.h"
|
||||
IDR_HELP_GUIDE RCDATA "help-guide.md"
|
||||
IDR_HELP_MANUAL RCDATA "../README.md"
|
||||
IDR_HELP_FILES RCDATA "../FILES-UI.md"
|
||||
IDR_HELP_COMPUTERS RCDATA "../LAN-PREVIEW.md"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 20 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
@@ -3,4 +3,14 @@
|
||||
#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 IDI_KSWITCHER_HISTORY 107
|
||||
#define IDI_KSWITCHER_SCREENSHOT 108
|
||||
#define IDI_KSWITCHER_HELP 109
|
||||
#define IDI_KSWITCHER_DONATE 110
|
||||
#define IDC_SCREENSHOT_PENCIL 500
|
||||
#define IDR_HELP_GUIDE 600
|
||||
#define IDR_HELP_MANUAL 601
|
||||
#define IDR_HELP_FILES 602
|
||||
#define IDR_HELP_COMPUTERS 603
|
||||
@@ -34,6 +34,7 @@ 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>
|
||||
@@ -51,6 +52,5 @@ figure { margin: 1em 0; }
|
||||
</nav>
|
||||
<main></main>
|
||||
<script src="markdown-it.js"></script>
|
||||
<script src="mermaid.js"></script>
|
||||
<script src="markdown.js"></script>
|
||||
</html>
|
||||
@@ -15,16 +15,34 @@ 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' ||
|
||||
@@ -36,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, {});
|
||||
@@ -67,10 +88,13 @@ function relativeResource(path) {
|
||||
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
|
||||
}
|
||||
|
||||
function renderContent(text) {
|
||||
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');
|
||||
template.innerHTML = markdown.render(text);
|
||||
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) ||
|
||||
@@ -79,6 +103,12 @@ function renderContent(text) {
|
||||
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]) {
|
||||
@@ -217,13 +247,14 @@ 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 }) {
|
||||
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;
|
||||
renderContent(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.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
||||
@@ -237,15 +268,21 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -255,6 +292,17 @@ async function render({ text, fragment, scroll, title, keepPosition }) {
|
||||
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;
|
||||
@@ -282,7 +330,7 @@ document.addEventListener('keydown', event => {
|
||||
event.preventDefault();
|
||||
} else if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
|
||||
event.preventDefault();
|
||||
send('cycle');
|
||||
send('cycle', {reverse: event.shiftKey});
|
||||
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
|
||||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
@@ -303,6 +351,10 @@ bridge.addEventListener('message', ({ data }) => {
|
||||
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');
|
||||
|
||||
@@ -3,6 +3,7 @@ const terminal = new Terminal({
|
||||
fontFamily: 'Consolas, monospace',
|
||||
fontSize: 16,
|
||||
cursorBlink: false,
|
||||
cursorInactiveStyle: 'none',
|
||||
disableStdin: true,
|
||||
theme: { background: '#181818', foreground: '#e8e8e8' },
|
||||
});
|
||||
|
||||
+538
-124
File diff suppressed because it is too large.
Load diff
@@ -36,7 +36,7 @@ struct LastTransform
|
||||
class App
|
||||
{
|
||||
public:
|
||||
HWND window{}, historyWindow{}, settingsWindow{}, snippetsWindow{};
|
||||
HWND window{}, historyWindow{}, settingsWindow{}, snippetsWindow{}, helpWindow{};
|
||||
HWND historyService{}; // Non-null only in the short-lived history UI process.
|
||||
bool isolateHistory{};
|
||||
unsigned historyEntryWindows{};
|
||||
@@ -81,7 +81,7 @@ class App
|
||||
void trayMenu();
|
||||
void addTray();
|
||||
bool registerHotkeys(const Settings &, bool rollback = false);
|
||||
void applySettings(const Settings &);
|
||||
void applySettings(const Settings &, const Bytes &supplement = {});
|
||||
void reloadLayouts();
|
||||
void clearHistory();
|
||||
void openHistoryProcess();
|
||||
@@ -105,11 +105,19 @@ class App
|
||||
|
||||
private:
|
||||
friend struct InputRegressionAccess;
|
||||
friend void commitConfigurationSupplement(App &, const Bytes &);
|
||||
void releaseIdleMemory(ULONGLONG now);
|
||||
void applySettings(const Settings &, bool validateOcrInstallation);
|
||||
void applySettings(const Settings &, bool validateOcrInstallation, const std::function<void()> &commit = {});
|
||||
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{};
|
||||
@@ -151,6 +159,7 @@ class App
|
||||
ULONGLONG nextSync{}, syncRetryAfter{};
|
||||
SyncResult syncResult;
|
||||
SyncConfig syncConnection;
|
||||
std::string syncDriveKey;
|
||||
SyncConfig conflictConnection;
|
||||
std::vector<SyncConflict> pendingSyncConflicts;
|
||||
Bytes syncSnapshot;
|
||||
@@ -161,14 +170,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;
|
||||
@@ -220,5 +233,6 @@ void showSettings(App &, bool visible = true);
|
||||
void showLogs(App &);
|
||||
void showSnippets(App &);
|
||||
void showShortcuts(App &);
|
||||
void showHelp(App &);
|
||||
void showEntry(App &, const std::wstring &);
|
||||
} // namespace ks
|
||||
+20
-13
@@ -9,7 +9,7 @@ std::wstring App::syncCommand(int action, const std::vector<SyncChoice> &choices
|
||||
if (action == 0) return syncStatus;
|
||||
if (syncRunning) return L"Synchronization is already running.";
|
||||
auto c = loadSyncConfig(data);
|
||||
if (!c.enabled) return syncStatus = L"Synchronization is disabled.";
|
||||
if (!automaticSyncEnabled(c)) return syncStatus = L"Synchronization is disabled.";
|
||||
validateSyncConfig(c);
|
||||
if (action == 4 && (c != conflictConnection || choices.empty()))
|
||||
throw std::runtime_error("Connection changed or no choices selected. Sync again.");
|
||||
@@ -17,28 +17,33 @@ std::wstring App::syncCommand(int action, const std::vector<SyncChoice> &choices
|
||||
syncRetryAfter = 0; // Explicit retries may bypass the automatic error backoff.
|
||||
if (syncWorker.joinable()) syncWorker.join();
|
||||
syncConnection = c;
|
||||
const auto driveKey = syncDriveKey = c.driveEnabled ? googleDriveCredentialKey() : std::string{};
|
||||
syncSnapshot = encodeSettings(settings);
|
||||
auto snapshot = settings;
|
||||
auto availableLayouts = layouts;
|
||||
syncRunning = true;
|
||||
syncDone = false;
|
||||
syncStatus = action == 2 ? L"Downloading remote settings from OpenBao..." :
|
||||
action == 3 ? L"Uploading local settings to OpenBao..." : L"Connecting to OpenBao...";
|
||||
const auto providerName = std::wstring(automaticSyncProviderName(c));
|
||||
syncStatus = action == 2 ? L"Downloading remote settings from " + providerName + L"..." :
|
||||
action == 3 ? L"Uploading local settings to " + providerName + L"..." : L"Connecting to " + providerName + L"...";
|
||||
nextSync = GetTickCount64() + SyncIntervalMs;
|
||||
try
|
||||
{
|
||||
syncWorker = std::thread([this, c, snapshot, availableLayouts, action, choices] {
|
||||
syncWorker = std::thread([this, c, snapshot, availableLayouts, action, choices, driveKey] {
|
||||
SyncResult result;
|
||||
try
|
||||
{
|
||||
auto provider = makeSyncProvider(c);
|
||||
// An explicit choice also repairs a missing/corrupt local baseline.
|
||||
auto base = action == 1 || action == 4 ? loadSyncBase(data, c) : Bytes{};
|
||||
result = synchronize(*provider, base, sharedSyncSettings(snapshot),
|
||||
const bool keepLayouts = c.enabled && c.keepLocalLayouts;
|
||||
auto base = action == 1 || action == 4 ? loadSyncBase(data, c, driveKey) : Bytes{};
|
||||
result = synchronize(*provider, base, c.driveEnabled ? sharedDriveSettings(snapshot) : sharedSyncSettings(snapshot),
|
||||
action == 2 ? SyncAction::Download : action == 3 ? SyncAction::Upload : SyncAction::Automatic,
|
||||
[&](const Bytes &b) { restoreSyncSettings(b, snapshot, availableLayouts, c.keepLocalLayouts); }, choices,
|
||||
c.keepLocalLayouts);
|
||||
if (result.success && c.keepLocalLayouts)
|
||||
[&](const Bytes &b) {
|
||||
if (c.driveEnabled) restoreSharedDriveSettings(b, snapshot, availableLayouts);
|
||||
else restoreSyncSettings(b, snapshot, availableLayouts, keepLayouts);
|
||||
}, choices, keepLayouts);
|
||||
if (result.success && keepLayouts)
|
||||
result.status += L" Partial sync: this PC's layouts and their shortcuts were kept; server layouts were preserved.";
|
||||
}
|
||||
catch (const nlohmann::json::exception &) { result.status = L"Invalid sync data or server response."; }
|
||||
@@ -69,13 +74,15 @@ void App::pollSync()
|
||||
syncStatus = result.status;
|
||||
if (result.success)
|
||||
{
|
||||
if (loadSyncConfig(data) != syncConnection || encodeSettings(settings) != snapshot)
|
||||
if (loadSyncConfig(data) != syncConnection || encodeSettings(settings) != snapshot ||
|
||||
(syncConnection.driveEnabled && googleDriveCredentialKey() != syncDriveKey))
|
||||
{
|
||||
syncStatus = L"Local settings or connection changed during sync. Checking again shortly.";
|
||||
nextSync = GetTickCount64() + 2000;
|
||||
return;
|
||||
}
|
||||
auto next = restoreSyncSettings(result.settings, settings, layouts, syncConnection.keepLocalLayouts);
|
||||
auto next = syncConnection.driveEnabled ? restoreSharedDriveSettings(result.settings, settings, layouts) :
|
||||
restoreSyncSettings(result.settings, settings, layouts, syncConnection.keepLocalLayouts);
|
||||
if (encodeSettings(next) != snapshot)
|
||||
{
|
||||
atomicWrite(data / L"settings-before-sync.bin", protect(snapshot));
|
||||
@@ -85,7 +92,7 @@ void App::pollSync()
|
||||
}
|
||||
else syncStatus += result.conflicts.empty() ? L" This PC's settings are already up to date; no local changes needed." :
|
||||
L" No local settings were changed; conflicts still need your choice.";
|
||||
saveSyncBase(data, syncConnection, result.base.empty() ? result.settings : result.base);
|
||||
saveSyncBase(data, syncConnection, result.base.empty() ? result.settings : result.base, syncDriveKey);
|
||||
if (result.downloaded)
|
||||
{
|
||||
if (settingsWindow) SendMessageW(settingsWindow, ConfigSettingsDownloaded, 0, 0);
|
||||
@@ -108,7 +115,7 @@ void App::pollSync()
|
||||
if (!syncRunning && GetTickCount64() >= nextSync)
|
||||
{
|
||||
nextSync = GetTickCount64() + SyncIntervalMs;
|
||||
if (loadSyncConfig(data).enabled) syncCommand(1);
|
||||
if (automaticSyncEnabled(loadSyncConfig(data))) syncCommand(1);
|
||||
}
|
||||
}
|
||||
catch (const nlohmann::json::exception &) { syncStatus = L"Invalid local sync configuration or cached profile."; nextSync = GetTickCount64() + SyncIntervalMs; }
|
||||
|
||||
+14
-6
@@ -107,7 +107,7 @@ App::~App()
|
||||
if (window) DestroyWindow(window);
|
||||
current = nullptr;
|
||||
}
|
||||
void App::applySettings(const Settings &next)
|
||||
void App::applySettings(const Settings &next, const Bytes &supplement)
|
||||
{
|
||||
validateSettings(next);
|
||||
auto before = encodeSettings(settings), after = encodeSettings(next);
|
||||
@@ -115,15 +115,22 @@ void App::applySettings(const Settings &next)
|
||||
Bytes payload(sizeof(length));
|
||||
memcpy(payload.data(), &length, sizeof(length));
|
||||
payload.insert(payload.end(), before.begin(), before.end());
|
||||
if (!supplement.empty())
|
||||
{
|
||||
DWORD length = (DWORD)after.size();
|
||||
auto first = reinterpret_cast<const unsigned char *>(&length);
|
||||
payload.insert(payload.end(), first, first + sizeof(length));
|
||||
}
|
||||
payload.insert(payload.end(), after.begin(), after.end());
|
||||
payload.insert(payload.end(), supplement.begin(), supplement.end());
|
||||
Bytes saved;
|
||||
try {saved=request(*this,ConfigSave,payload);}
|
||||
try {saved=request(*this,supplement.empty() ? ConfigSave : ConfigSaveDraft,payload);}
|
||||
catch(const std::exception &error){
|
||||
if(!std::string(error.what()).starts_with("Settings conflict: "))throw;
|
||||
auto text=wide(error.what())+L"\n\nThese settings changed both here and in KSwitcher.\nKeep your edits for these settings? Other changes will be preserved.\n\nNo leaves this window open with all your edits.";
|
||||
if(MessageBoxW(settingsWindow?settingsWindow:snippetsWindow,text.c_str(),L"Save conflicting settings",MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2)!=IDYES)
|
||||
throw std::runtime_error("Not saved. Your edits are still in this window.");
|
||||
saved=request(*this,ConfigSaveEdited,payload);
|
||||
saved=request(*this,supplement.empty() ? ConfigSaveEdited : ConfigSaveEditedDraft,payload);
|
||||
}
|
||||
settings=decodeSettings(saved,layouts);
|
||||
}
|
||||
@@ -229,16 +236,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;
|
||||
|
||||
+47
-4
@@ -40,6 +40,34 @@ void launchConfiguration(App &app, bool snippets, bool logs)
|
||||
CloseHandle(process.hProcess);
|
||||
(void)app;
|
||||
}
|
||||
void commitConfigurationSupplement(App &app, const Bytes &supplement)
|
||||
{
|
||||
const auto draft = nlohmann::json::parse(supplement);
|
||||
auto commitLan = [&] {
|
||||
if (!draft.contains("lan")) return;
|
||||
const auto command = nlohmann::json{{"action", "applySettings"}, {"draft", draft.at("lan")}}.dump();
|
||||
app.lanCommand(Bytes(command.begin(), command.end()));
|
||||
};
|
||||
if (draft.contains("sync"))
|
||||
{
|
||||
const auto &sync = draft.at("sync");
|
||||
const auto config = decodeSyncConfig(sync.at("config").get<Bytes>());
|
||||
const auto previous = loadSyncConfig(app.data);
|
||||
if (previous != decodeSyncConfig(sync.at("base").get<Bytes>()))
|
||||
throw std::runtime_error("The synchronization connection changed. Reopen Settings to edit the current connection.");
|
||||
const bool switching = previous.enabled != config.enabled || previous.driveEnabled != config.driveEnabled;
|
||||
if (switching && app.syncRunning)
|
||||
throw std::runtime_error("Wait for the current synchronization to finish before changing providers.");
|
||||
applySyncConnection(app.data, config, sync.at("password").get<Bytes>(), sync.at("forget").get<bool>(), commitLan);
|
||||
if (switching)
|
||||
{
|
||||
app.pendingSyncConflicts.clear();
|
||||
app.syncRetryAfter = 0;
|
||||
app.syncStatus = automaticSyncEnabled(config) ? L"Waiting to synchronize." : L"Synchronization is disabled.";
|
||||
}
|
||||
}
|
||||
else commitLan();
|
||||
}
|
||||
LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &message)
|
||||
{
|
||||
const bool filesPeers = message.dwData == FilesLanPeers;
|
||||
@@ -99,6 +127,8 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
||||
}
|
||||
case ConfigSave:
|
||||
case ConfigSaveEdited:
|
||||
case ConfigSaveDraft:
|
||||
case ConfigSaveEditedDraft:
|
||||
{
|
||||
if (app.busy) throw std::runtime_error("Wait for the current text operation to finish.");
|
||||
if (message.cbData < sizeof(DWORD)) throw std::runtime_error("Invalid settings request.");
|
||||
@@ -106,10 +136,23 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
||||
memcpy(&length, message.lpData, sizeof(length));
|
||||
if (length > message.cbData - sizeof(length)) throw std::runtime_error("Invalid settings snapshot.");
|
||||
auto begin = static_cast<const unsigned char *>(message.lpData) + sizeof(length);
|
||||
Bytes next(begin + length, static_cast<const unsigned char *>(message.lpData) + message.cbData);
|
||||
if (next.empty()) throw std::runtime_error("Empty settings request.");
|
||||
auto merged=mergeConfigurationSettings(Bytes(begin,begin+length),next,encodeSettings(app.settings),message.dwData==ConfigSaveEdited);
|
||||
app.applySettings(decodeSettings(merged, app.layouts));
|
||||
const auto end = static_cast<const unsigned char *>(message.lpData) + message.cbData;
|
||||
auto next = begin + length;
|
||||
auto nextEnd = end;
|
||||
const bool hasDraft = message.dwData == ConfigSaveDraft || message.dwData == ConfigSaveEditedDraft;
|
||||
if (hasDraft)
|
||||
{
|
||||
DWORD nextLength{};
|
||||
if (end - next < sizeof(nextLength)) throw std::runtime_error("Invalid settings draft.");
|
||||
memcpy(&nextLength, next, sizeof(nextLength));
|
||||
next += sizeof(nextLength);
|
||||
if (nextLength >= end - next) throw std::runtime_error("Invalid settings draft.");
|
||||
nextEnd = next + nextLength;
|
||||
}
|
||||
if (next == nextEnd) throw std::runtime_error("Empty settings request.");
|
||||
auto merged = mergeConfigurationSettings(Bytes(begin, begin + length), Bytes(next, nextEnd),
|
||||
encodeSettings(app.settings), message.dwData == ConfigSaveEdited || message.dwData == ConfigSaveEditedDraft);
|
||||
app.applySettings(decodeSettings(merged, app.layouts), Bytes(nextEnd, end));
|
||||
reply = encodeSettings(app.settings);
|
||||
break;
|
||||
}
|
||||
|
||||
+2
-1
@@ -9,9 +9,10 @@ inline constexpr ULONG_PTR ConfigRead = 0x4b530100, ConfigSave = ConfigRead + 1,
|
||||
ConfigCapture = ConfigRead + 4, ConfigLogs = ConfigRead + 5,
|
||||
ConfigReply = ConfigRead + 6, ConfigClearLog = ConfigRead + 7,
|
||||
ConfigSync = ConfigRead + 8, ConfigSyncConflicts = ConfigRead + 9,
|
||||
ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigEnd = FilesLanPeers + 1;
|
||||
ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigSaveDraft = FilesLanPeersReply + 1, ConfigSaveEditedDraft = ConfigSaveDraft + 1, ConfigEnd = ConfigSaveEditedDraft + 1;
|
||||
inline constexpr size_t ConfigLimit = 8 * 1024 * 1024;
|
||||
bool configurationPeer(HWND, const wchar_t *filename);
|
||||
void commitConfigurationSupplement(App &, const Bytes &);
|
||||
void launchConfiguration(App &, bool snippets = false, bool logs = false);
|
||||
LRESULT configurationRequest(App &, HWND sender, const COPYDATASTRUCT &);
|
||||
}
|
||||
+170
-60
@@ -319,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()
|
||||
@@ -377,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)
|
||||
@@ -423,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;
|
||||
|
||||
+11
-1
@@ -5,6 +5,7 @@
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
#include <windows.h>
|
||||
|
||||
@@ -42,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{};
|
||||
|
||||
@@ -0,0 +1,495 @@
|
||||
#include "google_drive.h"
|
||||
#include "sync.h"
|
||||
#include "mouse_buttons.h"
|
||||
#include "json.hpp"
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
#include <tuple>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Json = nlohmann::json;
|
||||
constexpr auto NativeFormat = "kswitcher-win32-drive-backup-v1";
|
||||
constexpr auto PreviewFormat = "kswitcher-drive-backup-v1";
|
||||
|
||||
// Select fields explicitly so changes to native serialization cannot expand the backup.
|
||||
constexpr const char *PortableFields[] = {
|
||||
"convertLastWord", "switchSystemLayout", "autoCorrectLayout", "autoCorrectReplace", "autoCorrectTypos",
|
||||
"autoCorrectReplacements", "autoCorrectMaxRank", "autoCorrectMinLength", "autoCorrectPrefixChars",
|
||||
"autoCorrectSuffixChars", "autoCorrectLanguages", "autoCorrectNever", "autoCorrectExcludedApps",
|
||||
"autoCorrectWords", "preventScreenLock", "toggleHotkey", "caseHotkey", "translitHotkey", "undoHotkey",
|
||||
"clipboardHotkey", "screenshotHotkey", "filesHotkey", "screenshotAutoOpenEditor", "historyEnabled",
|
||||
"maxItems", "maxTotalMegabytes", "maxImageMegabytes", "excludedApps", "useTesseract", "tesseractLanguages",
|
||||
"layouts", "layoutHotkeys", "chatCycles", "appLanguageSets", "snippets", "mouseBindings",
|
||||
"mouseProfileApplications", "disabledMouseProfiles", "customMouseEvents"
|
||||
};
|
||||
|
||||
Bytes bytes(const Json &object)
|
||||
{
|
||||
const auto text = object.dump();
|
||||
return {text.begin(), text.end()};
|
||||
}
|
||||
|
||||
Json portableFields(const Json &source)
|
||||
{
|
||||
auto result = Json::object();
|
||||
for (const auto *key : PortableFields)
|
||||
if (source.contains(key)) result[key] = source.at(key);
|
||||
return result;
|
||||
}
|
||||
|
||||
bool machineLocalMouseAction(const Json &binding)
|
||||
{
|
||||
if (!binding.is_object() || binding.value("action", "") != "Launch application") return false;
|
||||
return binding.at("executable").get<std::string>().find_first_of("\\/:") != std::string::npos;
|
||||
}
|
||||
|
||||
void excludeMousePaths(Json &settings)
|
||||
{
|
||||
if (!settings.contains("mouseBindings")) return;
|
||||
auto &profiles = settings.at("mouseBindings");
|
||||
if (!profiles.is_object()) throw std::runtime_error("Invalid mouse profiles.");
|
||||
for (auto &bindings : profiles)
|
||||
{
|
||||
if (!bindings.is_object()) throw std::runtime_error("Invalid mouse actions.");
|
||||
for (auto action = bindings.begin(); action != bindings.end();)
|
||||
{
|
||||
if (machineLocalMouseAction(*action)) action = bindings.erase(action);
|
||||
else ++action;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void preserveMousePaths(Json &settings, const Json &local)
|
||||
{
|
||||
if (!settings.contains("mouseBindings")) return;
|
||||
for (const auto &[profile, bindings] : local.at("mouseBindings").items())
|
||||
for (const auto &[event, action] : bindings.items())
|
||||
{
|
||||
if (!machineLocalMouseAction(action)) continue;
|
||||
settings["mouseBindings"][profile][event] = action;
|
||||
if (!settings.contains("mouseProfileApplications") ||
|
||||
!settings.at("mouseProfileApplications").is_object())
|
||||
throw std::runtime_error("Invalid mouse profile applications.");
|
||||
auto &scopes = settings.at("mouseProfileApplications");
|
||||
if (local.at("mouseProfileApplications").contains(profile))
|
||||
scopes[profile] = local.at("mouseProfileApplications").at(profile);
|
||||
else scopes.erase(profile);
|
||||
if (local.at("customMouseEvents").contains(event) && !settings.at("customMouseEvents").contains(event))
|
||||
settings["customMouseEvents"][event] = local.at("customMouseEvents").at(event);
|
||||
auto &disabled = settings.at("disabledMouseProfiles");
|
||||
if (!disabled.is_array()) throw std::runtime_error("Invalid disabled mouse profiles.");
|
||||
const bool wasDisabled = std::find(local.at("disabledMouseProfiles").begin(),
|
||||
local.at("disabledMouseProfiles").end(), profile) != local.at("disabledMouseProfiles").end();
|
||||
const auto entry = std::find(disabled.begin(), disabled.end(), profile);
|
||||
if (wasDisabled && entry == disabled.end()) disabled.push_back(profile);
|
||||
if (!wasDisabled && entry != disabled.end()) disabled.erase(entry);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> list(const Json &value)
|
||||
{
|
||||
if (value.is_array()) return value.get<std::vector<std::string>>();
|
||||
auto input = wide(value.get<std::string>());
|
||||
std::replace(input.begin(), input.end(), L',', L' ');
|
||||
std::wistringstream stream(input);
|
||||
std::vector<std::string> result;
|
||||
for (std::wstring item; stream >> item;) result.push_back(utf8(item));
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string layoutId(const Json &value)
|
||||
{
|
||||
auto id = utf8(lower(wide(value.get<std::string>())));
|
||||
if (id == "english" || id == "en" || id == "us" || id == "00000409") return "win:04090409";
|
||||
if (id == "ukrainian" || id == "uk" || id == "ua" || id == "00000422") return "win:04220422";
|
||||
if (id == "russian" || id == "ru" || id == "00000419") return "win:04190419";
|
||||
if (id == "00000809") return "win:08090809";
|
||||
return id;
|
||||
}
|
||||
|
||||
Json layoutList(const Json &value)
|
||||
{
|
||||
auto result = Json::array();
|
||||
for (const auto &id : list(value)) result.push_back(layoutId(id));
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string appName(const Json &value)
|
||||
{
|
||||
return utf8(snippetAppName(wide(value.get<std::string>())));
|
||||
}
|
||||
|
||||
void previewLayouts(const Json &options, Json &result)
|
||||
{
|
||||
if (options.contains("layouts"))
|
||||
{
|
||||
auto &cycle = result["layouts"] = Json::array();
|
||||
auto &keys = result["layoutHotkeys"] = Json::array();
|
||||
for (const auto &row : options.at("layouts").get<Json::array_t>())
|
||||
{
|
||||
auto id = layoutId(row.at("layout"));
|
||||
if (row.value("included", true)) cycle.push_back(id);
|
||||
keys.push_back({{"layoutId", id}, {"hotkey", row.value("shortcut", "")}});
|
||||
}
|
||||
}
|
||||
else if (options.contains("legacySettings"))
|
||||
{
|
||||
const auto &legacy = options.at("legacySettings");
|
||||
if (legacy.contains("layouts")) result["layouts"] = layoutList(legacy.at("layouts"));
|
||||
if (legacy.contains("layoutHotkeys"))
|
||||
{
|
||||
auto &keys = result["layoutHotkeys"] = Json::array();
|
||||
for (const auto &row : legacy.at("layoutHotkeys").get<Json::array_t>())
|
||||
keys.push_back({{"layoutId", layoutId(row.at("layoutId"))}, {"hotkey", row.at("hotkey").get<std::string>()}});
|
||||
}
|
||||
}
|
||||
|
||||
if (options.contains("appLanguages"))
|
||||
{
|
||||
auto &profiles = result["appLanguageSets"] = Json::object();
|
||||
for (const auto &row : options.at("appLanguages").get<Json::array_t>())
|
||||
{
|
||||
auto app = appName(row.at("app"));
|
||||
auto cycle = layoutList(row.at("languages"));
|
||||
if (!app.empty() && !cycle.empty())
|
||||
profiles[app] = {{"applications", Json::array({app})}, {"languages", cycle}};
|
||||
}
|
||||
}
|
||||
if (options.contains("chatLanguages"))
|
||||
{
|
||||
auto &profiles = result["chatCycles"] = Json::object();
|
||||
for (const auto &row : options.at("chatLanguages").get<Json::array_t>())
|
||||
{
|
||||
auto app = appName(row.at("app"));
|
||||
auto contact = row.at("contact").get<std::string>();
|
||||
auto cycle = layoutList(row.at("languages"));
|
||||
if ((app == "telegram" || app == "telegram-web" || app == "ms-teams" || app == "viber") &&
|
||||
!contact.empty() && !cycle.empty())
|
||||
profiles[app + "\n" + contact] = cycle;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void previewSnippets(const Json &settings, const Json &options, Json &result)
|
||||
{
|
||||
using SnippetKey = std::tuple<std::string, std::string, std::set<std::string>>;
|
||||
auto keyFor = [](const Json &row)
|
||||
{
|
||||
std::set<std::string> apps;
|
||||
if (row.contains("apps") && row.value("scoped", true))
|
||||
for (const auto &app : list(row.at("apps"))) apps.insert(appName(app));
|
||||
return SnippetKey{row.at("trigger").get<std::string>(), row.at("replacement").get<std::string>(), std::move(apps)};
|
||||
};
|
||||
const auto optionRows = options.value("snippets", Json::array()).get<Json::array_t>();
|
||||
std::map<SnippetKey, std::string> ids;
|
||||
for (const auto &row : optionRows)
|
||||
if (row.value("enabled", false) && row.contains("id"))
|
||||
ids.emplace(keyFor(row), row.at("id").get<std::string>());
|
||||
Json::array_t rows;
|
||||
if (settings.contains("snippets") && !settings.at("snippets").is_null())
|
||||
rows = settings.at("snippets").get<Json::array_t>();
|
||||
else if (options.contains("snippets"))
|
||||
rows = optionRows;
|
||||
else if (settings.contains("snippet"))
|
||||
rows.push_back(settings.at("snippet"));
|
||||
else
|
||||
return;
|
||||
auto &snippets = result["snippets"] = Json::array();
|
||||
for (const auto &row : rows)
|
||||
{
|
||||
if (!row.value("enabled", false)) continue;
|
||||
auto key = keyFor(row);
|
||||
const auto &[trigger, replacement, apps] = key;
|
||||
Json item{{"trigger", trigger}, {"text", replacement}};
|
||||
if (!apps.empty()) item["apps"] = apps;
|
||||
if (row.value("scoped", false) && (!item.contains("apps") || item.at("apps").empty()))
|
||||
throw std::runtime_error("A scoped snippet needs an application.");
|
||||
if (row.contains("id")) item["id"] = row.at("id").get<std::string>();
|
||||
else if (const auto id = ids.find(key); id != ids.end()) item["id"] = id->second;
|
||||
snippets.push_back(std::move(item));
|
||||
}
|
||||
}
|
||||
|
||||
void previewMouse(const Json &settings, const Json &options, Json &result)
|
||||
{
|
||||
if (!options.contains("mouseProfiles") && !options.contains("mouseActions") &&
|
||||
!options.contains("mouseEvents") && !settings.contains("mouse")) return;
|
||||
|
||||
auto &bindings = result["mouseBindings"] = Json::object();
|
||||
auto &scopes = result["mouseProfileApplications"] = Json::object();
|
||||
auto &disabled = result["disabledMouseProfiles"] = Json::array();
|
||||
auto &custom = result["customMouseEvents"] = Json::object();
|
||||
constexpr const char *events[] = {"Left click", "Right click", "Middle click", "First side button",
|
||||
"Second side button", "Left double-click", "Right double-click", "Middle double-click",
|
||||
"Wheel up", "Wheel down", "Wheel left", "Wheel right"};
|
||||
static_assert(std::size(events) == std::size(MouseEvents));
|
||||
std::map<std::string, std::string> signals, profiles{{"*", "*"}, {"default", "*"}};
|
||||
for (size_t i = 0; i < std::size(events); ++i) signals[events[i]] = utf8(MouseEvents[i]);
|
||||
|
||||
for (const auto &row : options.value("mouseEvents", Json::array()).get<Json::array_t>())
|
||||
{
|
||||
auto signal = row.value("signal", "");
|
||||
if (!signals.contains(signal) || !signal.starts_with("Wheel ")) continue;
|
||||
auto name = row.at("name").get<std::string>();
|
||||
custom[signal] = name;
|
||||
signals[name] = signal;
|
||||
}
|
||||
for (const auto &row : options.value("mouseProfiles", Json::array()).get<Json::array_t>())
|
||||
{
|
||||
auto id = row.at("id").get<std::string>();
|
||||
auto name = row.at("name").get<std::string>();
|
||||
auto apps = list(row.value("apps", Json("")));
|
||||
for (auto &app : apps) app = appName(app);
|
||||
if (id == "*" || (id == "default" && apps.empty())) continue;
|
||||
if (id == name && !id.starts_with("name:") && apps.empty() &&
|
||||
row.value("enabled", true) && validMouseApplication(wide(id)))
|
||||
{
|
||||
profiles[id] = id;
|
||||
continue;
|
||||
}
|
||||
auto profile = "name:" + name;
|
||||
profiles[id] = profile;
|
||||
bindings[profile] = Json::object();
|
||||
scopes[profile] = apps;
|
||||
if (!row.value("enabled", true)) disabled.push_back(profile);
|
||||
}
|
||||
auto add = [&](const std::string &profile, const std::string &event, const Json &row)
|
||||
{
|
||||
constexpr const char *actions[] = {"Unassigned", "Shortcut", "Back", "Forward", "VolumeUp",
|
||||
"VolumeDown", "Mute", "Launch"};
|
||||
static_assert(std::size(actions) == std::size(MouseActions));
|
||||
auto name = row.at("action").get<std::string>();
|
||||
auto match = std::find(std::begin(actions), std::end(actions), name);
|
||||
if (match == std::end(actions)) throw std::runtime_error("Unknown mouse action.");
|
||||
const auto type = static_cast<MouseActionType>(match - std::begin(actions));
|
||||
Json binding{{"action", utf8(MouseActions[static_cast<size_t>(type)])}};
|
||||
if (type == MouseActionType::Shortcut) binding["shortcut"] = row.at("shortcut").get<std::string>();
|
||||
if (type == MouseActionType::Launch) binding["executable"] = row.at("executable").get<std::string>();
|
||||
if (isMouseVolumeStep(type)) binding["volumeStep"] = row.value("step", Json(DefaultMouseVolumeStep));
|
||||
auto apps = list(row.value("apps", Json("")));
|
||||
for (auto &app : apps) app = appName(app);
|
||||
if (!apps.empty() && !profile.starts_with("name:")) binding["applications"] = apps;
|
||||
if (event.starts_with("Wheel ") && !custom.contains(event)) custom[event] = event;
|
||||
if (!machineLocalMouseAction(binding)) bindings[profile][event] = std::move(binding);
|
||||
};
|
||||
const auto rows = options.value("mouseActions", Json::array()).get<Json::array_t>();
|
||||
for (const auto &row : rows)
|
||||
{
|
||||
auto event = row.at("event").get<std::string>();
|
||||
if (signals.contains(event)) add(profiles.at(row.at("profile").get<std::string>()), signals.at(event), row);
|
||||
}
|
||||
const auto mouse = settings.value("mouse", Json::object());
|
||||
if (rows.empty() && mouse.value("enabled", false))
|
||||
{
|
||||
add("*", "XButton1", {{"action", mouse.value("default_action", "Unassigned")}});
|
||||
auto app = appName(mouse.value("application", ""));
|
||||
if (!app.empty()) add(app, "XButton1", {{"action", mouse.value("application_action", "Unassigned")}});
|
||||
}
|
||||
}
|
||||
|
||||
Json previewFields(const Json &profile, const Json &local)
|
||||
{
|
||||
const auto &options = profile.at("options");
|
||||
const auto &settings = profile.at("settings");
|
||||
if (!options.is_object() || !settings.is_object() || (options.empty() && settings.empty()))
|
||||
throw std::runtime_error("Invalid preview profile.");
|
||||
auto result = Json::object();
|
||||
constexpr std::pair<const char *, const char *> fields[] = {
|
||||
{"general.conversion.recent", "convertLastWord"}, {"general.conversion.switchLayout", "switchSystemLayout"},
|
||||
{"general.correction.maxRank", "autoCorrectMaxRank"}, {"general.correction.minLength", "autoCorrectMinLength"},
|
||||
{"general.correction.prefix", "autoCorrectPrefixChars"}, {"general.correction.suffix", "autoCorrectSuffixChars"},
|
||||
{"general.correction.autoReplace", "autoCorrectReplace"}, {"general.correction.autoTypos", "autoCorrectTypos"},
|
||||
{"general.integration.awake", "preventScreenLock"},
|
||||
{"shortcuts.key-bindings.toggle", "toggleHotkey"}, {"shortcuts.key-bindings.case", "caseHotkey"},
|
||||
{"shortcuts.key-bindings.transliterate", "translitHotkey"}, {"shortcuts.key-bindings.undo", "undoHotkey"},
|
||||
{"shortcuts.key-bindings.clipboard", "clipboardHotkey"}, {"shortcuts.key-bindings.capture", "screenshotHotkey"},
|
||||
{"shortcuts.key-bindings.files", "filesHotkey"}, {"shortcuts.capture.openEditor", "screenshotAutoOpenEditor"},
|
||||
{"clipboard.history.record", "historyEnabled"}, {"clipboard.history.items", "maxItems"},
|
||||
{"clipboard.history.capacity", "maxTotalMegabytes"}, {"clipboard.history.perItem", "maxImageMegabytes"},
|
||||
{"clipboard.ocr.useTesseract", "useTesseract"}, {"clipboard.ocr.tesseractLanguages", "tesseractLanguages"}
|
||||
};
|
||||
for (const auto &[from, to] : fields)
|
||||
if (options.contains(from)) result[to] = options.at(from);
|
||||
for (const auto &[from, to] : {std::pair{"general.correction.dictionaryLanguages", "autoCorrectLanguages"},
|
||||
{"general.correction.autoExcluded", "autoCorrectExcludedApps"}, {"clipboard.history.excluded", "excludedApps"}})
|
||||
if (options.contains(from)) result[to] = list(options.at(from));
|
||||
if (options.contains("general.correction.autoReplacements"))
|
||||
{
|
||||
auto &pairs = result["autoCorrectReplacements"] = Json::object();
|
||||
std::istringstream lines(options.at("general.correction.autoReplacements").get<std::string>());
|
||||
for (std::string line; std::getline(lines, line);)
|
||||
{
|
||||
auto split = line.find('=');
|
||||
if (line.find_first_not_of(" \t\r") == line.npos) continue;
|
||||
if (split == line.npos) throw std::runtime_error("Invalid automatic replacement.");
|
||||
auto trim = [](std::string text)
|
||||
{
|
||||
const auto first = text.find_first_not_of(" \t\r");
|
||||
return first == text.npos ? std::string{} :
|
||||
text.substr(first, text.find_last_not_of(" \t\r") - first + 1);
|
||||
};
|
||||
if (!pairs.emplace(trim(line.substr(0, split)), trim(line.substr(split + 1))).second)
|
||||
throw std::runtime_error("Duplicate automatic replacement.");
|
||||
}
|
||||
}
|
||||
if (settings.contains("autocorrect")) result["autoCorrectLayout"] = settings.at("autocorrect");
|
||||
const auto dictionary = settings.value("personal_dictionary", Json::object());
|
||||
auto words = local.at("autoCorrectWords");
|
||||
bool hasWords = false;
|
||||
for (const auto &[key, language] : {std::pair{"en", "english"}, {"uk", "ukrainian"}, {"ru", "russian"}})
|
||||
{
|
||||
const std::string field = std::string("general.correction.words.") + key;
|
||||
if (options.contains(field)) words[key] = list(options.at(field));
|
||||
else if (dictionary.contains(language)) words[key] = dictionary.at(language).get<std::vector<std::string>>();
|
||||
else continue;
|
||||
hasWords = true;
|
||||
}
|
||||
if (hasWords) result["autoCorrectWords"] = std::move(words);
|
||||
if (options.contains("general.correction.autoNever"))
|
||||
result["autoCorrectNever"] = list(options.at("general.correction.autoNever"));
|
||||
else if (dictionary.contains("never")) result["autoCorrectNever"] = list(dictionary.at("never"));
|
||||
previewLayouts(options, result);
|
||||
previewSnippets(settings, options, result);
|
||||
previewMouse(settings, options, result);
|
||||
if (result.empty()) throw std::runtime_error("No supported preview settings.");
|
||||
return result;
|
||||
}
|
||||
|
||||
void checkLayouts(const Json &fields, const std::vector<Layout> &layouts)
|
||||
{
|
||||
auto check = [&](const std::string &id)
|
||||
{
|
||||
const auto w = wide(id);
|
||||
if (std::none_of(layouts.begin(), layouts.end(), [&](const auto &layout) { return layout.id == w; }))
|
||||
throw std::runtime_error("Install the keyboard layouts used by this backup in Windows, then try restoring again.");
|
||||
};
|
||||
if (fields.contains("layouts"))
|
||||
for (const auto &id : fields.at("layouts").get<std::vector<std::string>>()) check(id);
|
||||
if (fields.contains("layoutHotkeys"))
|
||||
for (const auto &binding : fields.at("layoutHotkeys").get<Json::array_t>())
|
||||
if (!binding.at("hotkey").get<std::string>().empty()) check(binding.at("layoutId").get<std::string>());
|
||||
}
|
||||
|
||||
void allowRestoredSnippets(Json &settings)
|
||||
{
|
||||
std::set<std::string> ids;
|
||||
for (const auto &item : settings.at("snippets").get<Json::array_t>())
|
||||
{
|
||||
auto id = item.value("id", "");
|
||||
if (id.empty() && (!item.contains("apps") || item.at("apps").empty()))
|
||||
id = utf8(snippetId({wide(item.at("trigger").get<std::string>()), {}, {}, {}}));
|
||||
if (!id.empty()) ids.insert(std::move(id));
|
||||
}
|
||||
auto tombstones = settings.at("snippetTombstones").get<std::vector<std::string>>();
|
||||
std::erase_if(tombstones, [&](const auto &id) { return ids.contains(id); });
|
||||
settings["snippetTombstones"] = std::move(tombstones);
|
||||
}
|
||||
|
||||
Json mergeDriveFields(Json fields, const Json &original)
|
||||
{
|
||||
excludeMousePaths(fields);
|
||||
auto local = original;
|
||||
local.update(fields);
|
||||
if (local.contains("filesHotkey") && local.at("filesHotkey").is_null()) local.erase("filesHotkey");
|
||||
if (fields.contains("mouseBindings")) preserveMousePaths(local, original);
|
||||
if (fields.contains("snippets")) allowRestoredSnippets(local);
|
||||
return local;
|
||||
}
|
||||
}
|
||||
|
||||
Bytes sharedDriveSettings(const Settings &saved)
|
||||
{
|
||||
const auto source = Json::parse(sharedSyncSettings(saved));
|
||||
auto profile = portableFields(source);
|
||||
excludeMousePaths(profile);
|
||||
auto &bindings = profile.at("mouseBindings");
|
||||
for (auto it = bindings.begin(); it != bindings.end();)
|
||||
// Named profiles can retain their application scope without actions.
|
||||
if (it->empty() && !isNamedMouseProfile(wide(it.key()))) it = bindings.erase(it);
|
||||
else ++it;
|
||||
if (!profile.contains("filesHotkey")) profile["filesHotkey"] = nullptr;
|
||||
for (const auto *field : {"format", "schemaVersion", "snippetTombstones"}) profile[field] = source.at(field);
|
||||
return bytes(profile);
|
||||
}
|
||||
|
||||
Settings restoreSharedDriveSettings(const Bytes &shared, const Settings &local, const std::vector<Layout> &layouts)
|
||||
{
|
||||
const auto source = Json::parse(shared);
|
||||
if (!source.is_object() || source.value("format", "") != "kswitcher-settings" ||
|
||||
source.value("schemaVersion", 0) != 1 || source.size() != std::size(PortableFields) + 3 ||
|
||||
!source.contains("snippetTombstones"))
|
||||
throw std::runtime_error("Invalid Google Drive synchronization profile.");
|
||||
auto fields = portableFields(source);
|
||||
if (fields.size() != std::size(PortableFields))
|
||||
throw std::runtime_error("Incomplete Google Drive synchronization profile.");
|
||||
fields["snippetTombstones"] = source.at("snippetTombstones");
|
||||
checkLayouts(fields, layouts);
|
||||
return decodeSettings(bytes(mergeDriveFields(std::move(fields), Json::parse(encodeSettings(local)))), layouts);
|
||||
}
|
||||
|
||||
Bytes encodeDriveBackup(const Settings &saved)
|
||||
{
|
||||
auto profile = portableFields(Json::parse(encodeSettings(saved)));
|
||||
if (!profile.contains("filesHotkey")) profile["filesHotkey"] = nullptr;
|
||||
excludeMousePaths(profile);
|
||||
auto result = bytes({{"format", NativeFormat}, {"settings", std::move(profile)}});
|
||||
if (result.size() > GoogleDriveBackupLimit) throw std::runtime_error("Saved settings exceed the 2 MiB backup limit.");
|
||||
return result;
|
||||
}
|
||||
|
||||
Settings restoreDriveBackup(const Bytes &backup, const Settings &draft, const std::vector<Layout> &layouts)
|
||||
{
|
||||
if (backup.size() > GoogleDriveBackupLimit) throw std::runtime_error("This Drive backup exceeds the 2 MiB limit.");
|
||||
// Limit nesting before the parser allocates a tree from downloaded data.
|
||||
const auto document = Json::parse(backup, [](int depth, Json::parse_event_t, Json &)
|
||||
{
|
||||
if (depth > 32) throw std::runtime_error("This Drive backup is corrupt.");
|
||||
return true;
|
||||
}, false);
|
||||
if (!document.is_object() || !document.contains("format") || !document.at("format").is_string())
|
||||
throw std::runtime_error("This Drive backup is corrupt.");
|
||||
const auto format = document.at("format").get<std::string>();
|
||||
if (format != NativeFormat && format != PreviewFormat)
|
||||
throw std::runtime_error("This Drive backup format is unsupported.");
|
||||
|
||||
const auto original = Json::parse(encodeSettings(draft));
|
||||
auto local = original;
|
||||
Json fields;
|
||||
try
|
||||
{
|
||||
if (format == NativeFormat)
|
||||
{
|
||||
const auto &source = document.at("settings");
|
||||
if (!source.is_object()) throw std::runtime_error("Invalid settings.");
|
||||
for (const auto *key : PortableFields)
|
||||
if (!source.contains(key)) throw std::runtime_error("Incomplete settings.");
|
||||
fields = portableFields(source);
|
||||
}
|
||||
else fields = previewFields(document.at("profile"), local);
|
||||
local = mergeDriveFields(fields, original);
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
throw std::runtime_error("This Drive backup contains invalid settings.");
|
||||
}
|
||||
try
|
||||
{
|
||||
checkLayouts(fields, layouts);
|
||||
}
|
||||
catch (const Json::exception &)
|
||||
{
|
||||
throw std::runtime_error("This Drive backup contains invalid layouts or shortcuts.");
|
||||
}
|
||||
try
|
||||
{
|
||||
return decodeSettings(bytes(local), layouts);
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
throw std::runtime_error("This Drive backup contains settings that are invalid or conflict with this PC's settings.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -159,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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
constexpr int findMask=480, findHidden=481, findFooter=482, findLabel=483;
|
||||
|
||||
INT_PTR CALLBACK findFilesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_DRAWITEM)
|
||||
{
|
||||
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
|
||||
return TRUE;
|
||||
}
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Find files ",false,{findFooter}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
const auto &options=*reinterpret_cast<Panel::FindOptions *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,findLabel);
|
||||
for(const auto id:{IDOK,IDCANCEL})
|
||||
{
|
||||
const auto button=GetDlgItem(dialog,id);
|
||||
SetWindowPos(button,nullptr,0,0,farDialogButtonWidth(button),textHeight,
|
||||
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
}
|
||||
layoutDialogButtons(dialog,findFooter,{IDOK,IDCANCEL});
|
||||
installFarCheckbox(GetDlgItem(dialog,findHidden),FarCheckboxSurface::gray);
|
||||
SendDlgItemMessageW(dialog,findMask,EM_SETLIMITTEXT,255,0);
|
||||
SetDlgItemTextW(dialog,findMask,options.mask.c_str());
|
||||
CheckDlgButton(dialog,findHidden,options.includeHidden?BST_CHECKED:BST_UNCHECKED);
|
||||
SetFocus(GetDlgItem(dialog,findMask));
|
||||
SendDlgItemMessageW(dialog,findMask,EM_SETSEL,0,-1);
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
|
||||
{
|
||||
auto &options=*reinterpret_cast<Panel::FindOptions *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
wchar_t mask[256]{};
|
||||
GetDlgItemTextW(dialog,findMask,mask,static_cast<int>(std::size(mask)));
|
||||
if(std::wstring_view(mask).find_first_of(L"/\\:")!=std::wstring_view::npos)
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a file name or mask without a path.",L"Find files");
|
||||
SetFocus(GetDlgItem(dialog,findMask));
|
||||
return TRUE;
|
||||
}
|
||||
options.mask=*mask?mask:L"*";
|
||||
options.includeHidden=IsDlgButtonChecked(dialog,findHidden)==BST_CHECKED;
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void startFileSearch(Panel &panel,Panel::FindOptions options)
|
||||
{
|
||||
if(panel.scanRequest) return;
|
||||
cancelFolderSizes(panel);
|
||||
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
|
||||
startDirectoryScan(panel);
|
||||
}
|
||||
|
||||
void findLocalFiles(HWND owner,Panel &panel)
|
||||
{
|
||||
if(panel.peer || panel.ftp || panel.directory.empty())
|
||||
{
|
||||
setStatus(L"Find files requires a local folder.");
|
||||
return;
|
||||
}
|
||||
if(panel.scanRequest)
|
||||
{
|
||||
setStatus(L"Wait for the current scan to finish.");
|
||||
return;
|
||||
}
|
||||
auto options=panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
|
||||
findFilesDialog,reinterpret_cast<LPARAM>(&options))!=IDOK) return;
|
||||
startFileSearch(panel,std::move(options));
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
bool matchesFileMask(std::wstring_view name,std::wstring_view mask)
|
||||
{
|
||||
size_t fileIndex=0, maskIndex=0, star=mask.npos, afterStar=0;
|
||||
while(fileIndex<name.size())
|
||||
{
|
||||
if(maskIndex<mask.size() && mask[maskIndex]==L'*')
|
||||
{
|
||||
star=maskIndex++;
|
||||
afterStar=fileIndex;
|
||||
}
|
||||
else if(maskIndex<mask.size() &&
|
||||
(mask[maskIndex]==L'?' || CompareStringOrdinal(name.data()+fileIndex,1,
|
||||
mask.data()+maskIndex,1,TRUE)==CSTR_EQUAL))
|
||||
{
|
||||
++fileIndex;
|
||||
++maskIndex;
|
||||
}
|
||||
else if(star!=mask.npos)
|
||||
{
|
||||
maskIndex=star+1;
|
||||
fileIndex=++afterStar;
|
||||
}
|
||||
else return false;
|
||||
}
|
||||
return mask.find_first_not_of(L'*',maskIndex)==mask.npos;
|
||||
}
|
||||
|
||||
std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &request,
|
||||
std::atomic_size_t &entriesRead,std::stop_token stop)
|
||||
{
|
||||
auto result=std::make_unique<Panel::ScanResult>();
|
||||
FilesConnection local(nullptr);
|
||||
std::vector<fs::path> pending{request.directory};
|
||||
size_t visited=0;
|
||||
while(!pending.empty() && !stop.stop_requested())
|
||||
{
|
||||
const auto directory=std::move(pending.back());
|
||||
pending.pop_back();
|
||||
try
|
||||
{
|
||||
listFiles(local,directory,[&](const fs::path &path,const FileInfo &entry)
|
||||
{
|
||||
if(stop.stop_requested()) return false;
|
||||
entriesRead.store(++visited,std::memory_order_relaxed);
|
||||
if(!request.find->includeHidden && (entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)))
|
||||
return true;
|
||||
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
|
||||
{
|
||||
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
|
||||
}
|
||||
else if(matchesFileMask(path.filename().native(),request.find->mask))
|
||||
{
|
||||
result->files.push_back(path);
|
||||
result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size});
|
||||
result->timestamps.emplace(path,entry.modified);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
catch(const std::system_error &)
|
||||
{
|
||||
if(directory==request.directory)
|
||||
{
|
||||
result->failure=L"Cannot search folder: "+directory.native();
|
||||
return result;
|
||||
}
|
||||
result->error=ERROR_PARTIAL_COPY;
|
||||
}
|
||||
}
|
||||
if(stop.stop_requested()) result->error=ERROR_CANCELLED;
|
||||
result->opened=true;
|
||||
std::sort(result->files.begin(),result->files.end());
|
||||
return result;
|
||||
}
|
||||
@@ -27,25 +27,18 @@ bool saveFolderShortcuts(const FolderShortcuts &shortcuts)
|
||||
{"name",ks::utf8(entry.peerName)},{"title",ks::utf8(entry.title)}});
|
||||
groups.push_back(std::move(rows));
|
||||
}
|
||||
const auto data=groups.dump();
|
||||
return data.size()<=1024*1024 &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
return writeFilesJsonPreference(folderShortcutsKey,groups);
|
||||
}
|
||||
catch(const std::exception &){return false;}
|
||||
}
|
||||
|
||||
void loadFolderShortcuts()
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>1024*1024) return;
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return;
|
||||
const auto saved=readFilesJsonPreference(folderShortcutsKey);
|
||||
if(!saved) return;
|
||||
try
|
||||
{
|
||||
const auto groups=Json::parse(data.begin(),data.begin()+bytes);
|
||||
const auto &groups=*saved;
|
||||
if(!groups.is_array() || groups.size()!=folderShortcuts.size()) return;
|
||||
FolderShortcuts loaded;
|
||||
for(size_t digit=0;digit<loaded.size();++digit)
|
||||
@@ -152,7 +145,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))
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+1638
-350
File diff suppressed because it is too large.
Load diff
+97
-7
@@ -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 };
|
||||
@@ -89,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;
|
||||
@@ -163,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);
|
||||
}
|
||||
@@ -409,6 +418,20 @@ 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;
|
||||
@@ -420,7 +443,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
{
|
||||
title=optionsTitles[page];
|
||||
if(markdown) title=L"Markdown";
|
||||
else if(section>=0 && !textOptionsPage(page))
|
||||
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";
|
||||
@@ -451,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)
|
||||
{
|
||||
@@ -524,8 +549,9 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
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)
|
||||
@@ -562,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") ||
|
||||
@@ -611,6 +640,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
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)
|
||||
@@ -701,6 +735,28 @@ 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)
|
||||
{
|
||||
@@ -773,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);
|
||||
@@ -823,12 +884,22 @@ 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"");
|
||||
@@ -856,6 +927,14 @@ 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)
|
||||
@@ -918,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());
|
||||
@@ -938,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);
|
||||
@@ -972,6 +1060,7 @@ 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;
|
||||
@@ -987,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());
|
||||
@@ -1010,7 +1100,7 @@ void runOptions(HWND owner,int page)
|
||||
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
|
||||
const DWORD initial=static_cast<DWORD>((page<<8)|1);
|
||||
const auto saved=preference(optionsLocationKey,initial);
|
||||
draft.location=(saved>>8)<=allOptions?saved: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());
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
|
||||
bool localNavigationAvailable(const Panel &panel)
|
||||
{
|
||||
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.directory.empty();
|
||||
}
|
||||
|
||||
enum class PathAction { back, forward, up, edit, ancestors, previous, folder };
|
||||
|
||||
void navigateLocal(Panel &panel,const fs::path &path,std::optional<size_t> position={})
|
||||
{
|
||||
if(path.empty() || sameLocalFolder(path,panel.directory)) return;
|
||||
closePanelSearch();
|
||||
openOn(panel,path,true,{},{},{},{},position);
|
||||
}
|
||||
|
||||
void navigateLocalHistory(Panel &panel,int direction)
|
||||
{
|
||||
if(const auto next=panel.navigation.neighbor(direction))
|
||||
navigateLocal(panel,panel.navigation.history[*next],next);
|
||||
}
|
||||
|
||||
struct PathPart
|
||||
{
|
||||
PathAction action{};
|
||||
std::wstring label;
|
||||
fs::path target;
|
||||
std::vector<fs::path> hidden;
|
||||
RECT rect{};
|
||||
bool current{}, dim{}, enabled=true;
|
||||
};
|
||||
|
||||
std::wstring pathSegmentLabel(const fs::path &path)
|
||||
{
|
||||
return panelParentPath(path,true).empty()?path.native():path.filename().native();
|
||||
}
|
||||
|
||||
LONG segmentWidth(const fs::path &path)
|
||||
{
|
||||
return static_cast<LONG>(pathSegmentLabel(path).size()+2)*cellWidth;
|
||||
}
|
||||
|
||||
std::vector<PathPart> localPathParts(const Panel &panel,RECT bounds)
|
||||
{
|
||||
const LONG total=bounds.right-bounds.left;
|
||||
if(total<=0) return {};
|
||||
const LONG width=std::max(1L,std::min(2L*cellWidth,total/7));
|
||||
std::vector<PathPart> parts;
|
||||
const auto add=[&](PathPart part,LONG length)
|
||||
{
|
||||
if(length<=0 || bounds.left>=bounds.right) return;
|
||||
part.rect={bounds.left,bounds.top,std::min(bounds.right,bounds.left+length),bounds.bottom};
|
||||
bounds.left=part.rect.right;
|
||||
parts.push_back(std::move(part));
|
||||
};
|
||||
const auto parent=panelParentPath(panel.directory,true);
|
||||
add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width);
|
||||
add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width);
|
||||
add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width);
|
||||
add({.action=PathAction::edit,.label=L"✎"},width);
|
||||
|
||||
std::vector<fs::path> ancestors, previous;
|
||||
for(auto path=parent;!path.empty();path=panelParentPath(path,true)) ancestors.push_back(path);
|
||||
std::reverse(ancestors.begin(),ancestors.end());
|
||||
if(inLocalBranch(panel.directory,panel.navigation.previousBranch))
|
||||
{
|
||||
for(auto path=panel.navigation.previousBranch;!sameLocalFolder(path,panel.directory);
|
||||
path=panelParentPath(path,true))
|
||||
previous.push_back(path);
|
||||
std::reverse(previous.begin(),previous.end());
|
||||
}
|
||||
|
||||
const LONG room=bounds.right-bounds.left;
|
||||
LONG required=segmentWidth(panel.directory);
|
||||
for(const auto &path:ancestors) required+=segmentWidth(path);
|
||||
for(const auto &path:previous) required+=segmentWidth(path);
|
||||
size_t firstAncestor=0,visiblePrevious=previous.size();
|
||||
LONG currentWidth=segmentWidth(panel.directory);
|
||||
if(required>room)
|
||||
{
|
||||
const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0);
|
||||
currentWidth=std::min(currentWidth,std::max(1L,room-reserved));
|
||||
LONG remaining=room-currentWidth-reserved;
|
||||
firstAncestor=ancestors.size();
|
||||
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1]))
|
||||
remaining-=segmentWidth(ancestors[--firstAncestor]);
|
||||
visiblePrevious=0;
|
||||
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious]))
|
||||
remaining-=segmentWidth(previous[visiblePrevious++]);
|
||||
}
|
||||
|
||||
if(firstAncestor)
|
||||
add({.action=PathAction::ancestors,.label=L"…",
|
||||
.hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width);
|
||||
for(size_t i=firstAncestor;i<ancestors.size();++i)
|
||||
add({.action=PathAction::folder,.label=pathSegmentLabel(ancestors[i]),.target=ancestors[i]},
|
||||
segmentWidth(ancestors[i]));
|
||||
add({.action=PathAction::edit,.label=pathSegmentLabel(panel.directory),.current=true},currentWidth);
|
||||
for(size_t i=0;i<visiblePrevious;++i)
|
||||
add({.action=PathAction::folder,.label=pathSegmentLabel(previous[i]),.target=previous[i],.dim=true},
|
||||
segmentWidth(previous[i]));
|
||||
if(visiblePrevious<previous.size())
|
||||
add({.action=PathAction::previous,.label=L"…",
|
||||
.hidden={previous.begin()+visiblePrevious,previous.end()},.dim=true},width);
|
||||
return parts;
|
||||
}
|
||||
|
||||
void paintLocalPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel)
|
||||
{
|
||||
const int saved=SaveDC(dc);
|
||||
SelectObject(dc,mono);
|
||||
SetBkMode(dc,TRANSPARENT);
|
||||
for(const auto &part:localPathParts(panel,bounds))
|
||||
{
|
||||
const bool current=activePanel && part.current;
|
||||
FillRect(dc,&part.rect,current?teal:blue);
|
||||
SetTextColor(dc,!part.enabled || part.dim?RGB(160,170,190):colors[current?Text:Frame]);
|
||||
auto text=part.rect;
|
||||
DrawTextW(dc,part.label.c_str(),static_cast<int>(part.label.size()),&text,
|
||||
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
}
|
||||
if(saved) RestoreDC(dc,saved);
|
||||
}
|
||||
|
||||
constexpr int addressField=485,addressLabel=486,addressFooter=487;
|
||||
|
||||
struct PathPrompt
|
||||
{
|
||||
fs::path base, result;
|
||||
std::wstring completionInput;
|
||||
std::future<std::wstring> completion;
|
||||
};
|
||||
|
||||
constexpr UINT addressComplete=WM_APP+29;
|
||||
constexpr UINT_PTR addressCompletionTimer=1;
|
||||
|
||||
fs::path enteredPanelPath(const fs::path &base,std::wstring text)
|
||||
{
|
||||
if(text.size()>=2 && text.front()==L'"' && text.back()==L'"')
|
||||
text=text.substr(1,text.size()-2);
|
||||
return fs::path(text).is_absolute()?fs::path(std::move(text)):base/fs::path(std::move(text));
|
||||
}
|
||||
|
||||
std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text)
|
||||
{
|
||||
const auto path=enteredPanelPath(base,text);
|
||||
const auto directory=path.has_filename()?path.parent_path():path;
|
||||
const auto prefix=path.filename().native();
|
||||
fs::path best;
|
||||
std::error_code error;
|
||||
for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error))
|
||||
{
|
||||
const auto name=it->path().filename().native();
|
||||
if(name.size()<prefix.size() || (!prefix.empty() && CompareStringOrdinal(name.data(),
|
||||
static_cast<int>(prefix.size()),prefix.data(),static_cast<int>(prefix.size()),TRUE)!=CSTR_EQUAL))
|
||||
continue;
|
||||
std::error_code typeError;
|
||||
if(it->is_directory(typeError) && (best.empty() || it->path()<best)) best=it->path();
|
||||
}
|
||||
return best.empty()?std::wstring{}:best.native()+L"\\";
|
||||
}
|
||||
|
||||
LRESULT CALLBACK addressFieldKeys(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_GETDLGCODE)
|
||||
{
|
||||
const auto *key=reinterpret_cast<const MSG *>(lp);
|
||||
if(key && key->wParam==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000))
|
||||
return DefSubclassProc(field,message,wp,lp)|DLGC_WANTTAB;
|
||||
}
|
||||
if(message==WM_KEYDOWN && wp==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000))
|
||||
{
|
||||
SendMessageW(GetParent(field),addressComplete,0,0);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_CHAR && wp==VK_TAB) return 0;
|
||||
return DefSubclassProc(field,message,wp,lp);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_DRAWITEM)
|
||||
{
|
||||
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
|
||||
return TRUE;
|
||||
}
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Go to folder ",false,{addressFooter}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,addressLabel);
|
||||
layoutDialogButtons(dialog,addressFooter,{IDOK,IDCANCEL});
|
||||
const auto field=GetDlgItem(dialog,addressField);
|
||||
SendMessageW(field,EM_SETLIMITTEXT,32767,0);
|
||||
SetWindowTextW(field,(prompt.base/fs::path{}).c_str());
|
||||
SetWindowSubclass(field,addressFieldKeys,4,0);
|
||||
SetFocus(field);
|
||||
SendMessageW(field,EM_SETSEL,0,-1);
|
||||
return FALSE;
|
||||
}
|
||||
if(message==addressComplete)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(prompt.completion.valid()) return TRUE;
|
||||
prompt.completionInput=shortcutField(dialog,addressField);
|
||||
std::packaged_task<std::wstring()> task([base=prompt.base,text=prompt.completionInput]
|
||||
{
|
||||
return panelPathCompletion(base,text);
|
||||
});
|
||||
if(!SetTimer(dialog,addressCompletionTimer,30,nullptr)) return TRUE;
|
||||
prompt.completion=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_TIMER && wp==addressCompletionTimer)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!prompt.completion.valid() ||
|
||||
prompt.completion.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE;
|
||||
KillTimer(dialog,addressCompletionTimer);
|
||||
try
|
||||
{
|
||||
const auto value=prompt.completion.get();
|
||||
if(!value.empty() && shortcutField(dialog,addressField)==prompt.completionInput)
|
||||
{
|
||||
const auto field=GetDlgItem(dialog,addressField);
|
||||
SetWindowTextW(field,value.c_str());
|
||||
SendMessageW(field,EM_SETSEL,value.size(),value.size());
|
||||
SendMessageW(field,EM_SCROLLCARET,0,0);
|
||||
}
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField)).lexically_normal();
|
||||
if(!path.is_absolute())
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a folder path.",L"Go to folder");
|
||||
return TRUE;
|
||||
}
|
||||
if(!path.has_filename() && path.has_relative_path()) path=path.parent_path();
|
||||
prompt.result=std::move(path);
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void editPanelPath(Panel &panel)
|
||||
{
|
||||
PathPrompt prompt{panel.directory};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(117),GetParent(panel.list),
|
||||
editPathDialog,reinterpret_cast<LPARAM>(&prompt))==IDOK)
|
||||
navigateLocal(panel,prompt.result);
|
||||
}
|
||||
|
||||
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs::path> paths,RECT anchor,bool recent=false)
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
commandPicker=false;
|
||||
pickerPanel=side;
|
||||
folderPicker=FolderPicker{caption,std::move(paths),recent};
|
||||
SendMessageW(picker,LB_RESETCONTENT,0,0);
|
||||
size_t longest=wcslen(caption);
|
||||
for(const auto &path:folderPicker->paths)
|
||||
{
|
||||
longest=std::max(longest,path.native().size());
|
||||
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(path.c_str()));
|
||||
}
|
||||
RECT client{};
|
||||
GetClientRect(owner,&client);
|
||||
const int inset=dialogFrameMetrics(GetDpiForWindow(owner)).content();
|
||||
const int width=std::max(1,std::min(static_cast<int>(client.right)-2*inset,static_cast<int>(longest+3)*cellWidth));
|
||||
const int x=std::clamp(static_cast<int>(anchor.left),inset,std::max(inset,static_cast<int>(client.right)-width-inset));
|
||||
const int y=anchor.bottom+inset;
|
||||
const int row=std::max(1,static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0)));
|
||||
RECT input{};
|
||||
GetWindowRect(terminalInput,&input);
|
||||
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&input),2);
|
||||
const int bottom=std::min(client.bottom,input.top);
|
||||
const int shown=std::clamp((bottom-y-inset)/row,1,static_cast<int>(folderPicker->paths.size()));
|
||||
showFramedList(picker,pickerFrame,x,y,width,row*shown,inset);
|
||||
SendMessageW(picker,LB_SETCURSEL,0,0);
|
||||
SetFocus(picker);
|
||||
}
|
||||
|
||||
void showRecentFolders(int side)
|
||||
{
|
||||
auto paths=readRecentFolders();
|
||||
if(paths.empty())
|
||||
{
|
||||
setStatus(L"No recent local folders.");
|
||||
return;
|
||||
}
|
||||
const auto owner=GetParent(picker);
|
||||
RECT anchor{};
|
||||
GetWindowRect(panels[side].path,&anchor);
|
||||
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&anchor),2);
|
||||
showFolderPicker(owner,side,L"Recent folders",std::move(paths),anchor,true);
|
||||
}
|
||||
|
||||
void showHiddenPathParts(HWND window,int side,const PathPart &part)
|
||||
{
|
||||
const auto owner=GetParent(window);
|
||||
auto anchor=part.rect;
|
||||
MapWindowPoints(window,owner,reinterpret_cast<POINT*>(&anchor),2);
|
||||
showFolderPicker(owner,side,part.action==PathAction::ancestors?L"Parent folders":L"Previous path",
|
||||
part.hidden,anchor);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_LBUTTONDOWN)
|
||||
{
|
||||
SetCapture(window);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_LBUTTONUP && GetCapture()==window)
|
||||
{
|
||||
ReleaseCapture();
|
||||
const int index=GetDlgCtrlID(window)-142;
|
||||
if(index<0 || index>=2) return 0;
|
||||
auto &panel=panels[index];
|
||||
if(!localNavigationAvailable(panel))
|
||||
{
|
||||
selectPanelEdge(panel,true);
|
||||
return 0;
|
||||
}
|
||||
activatePanel(index);
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
const auto parts=localPathParts(panel,bounds);
|
||||
for(const auto &part:parts)
|
||||
{
|
||||
if(!part.enabled || !PtInRect(&part.rect,mouse)) continue;
|
||||
switch(part.action)
|
||||
{
|
||||
case PathAction::back: navigateLocalHistory(panel,-1); break;
|
||||
case PathAction::forward: navigateLocalHistory(panel,1); break;
|
||||
case PathAction::up: case PathAction::folder: navigateLocal(panel,part.target); break;
|
||||
case PathAction::edit: editPanelPath(panel); break;
|
||||
case PathAction::ancestors: case PathAction::previous: showHiddenPathParts(window,index,part); break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(window,message,wp,lp);
|
||||
}
|
||||
|
||||
bool handleLocalPathKey(HWND owner,const MSG &message)
|
||||
{
|
||||
if(!commandLineAvailable(owner) || terminalVisible || !localNavigationAvailable(panels[active]) ||
|
||||
(message.hwnd!=terminalInput && message.hwnd!=panels[active].list) ||
|
||||
((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return false;
|
||||
auto &panel=panels[active];
|
||||
if(message.message==WM_KEYDOWN && message.wParam=='L' &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000))
|
||||
{
|
||||
if(!(message.lParam&(1LL<<30))) editPanelPath(panel);
|
||||
return true;
|
||||
}
|
||||
if(message.message!=WM_SYSKEYDOWN || !(message.lParam&(1LL<<29)) ||
|
||||
(GetKeyState(VK_CONTROL)&0x8000)) return false;
|
||||
if(message.wParam==VK_UP)
|
||||
navigateLocal(panel,panelParentPath(panel.directory,true));
|
||||
else if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT)
|
||||
navigateLocalHistory(panel,message.wParam==VK_LEFT?-1:1);
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
constexpr wchar_t recentFoldersKey[]=L"RecentFolders";
|
||||
constexpr size_t recentFoldersLimit=100;
|
||||
|
||||
std::vector<fs::path> readRecentFolders()
|
||||
{
|
||||
const auto saved=readFilesJsonPreference(recentFoldersKey);
|
||||
std::vector<fs::path> folders;
|
||||
if(!saved || !saved->is_array()) return folders;
|
||||
for(const auto &entry:*saved)
|
||||
{
|
||||
if(!entry.is_string()) continue;
|
||||
const auto path=filePath(entry);
|
||||
if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos) continue;
|
||||
if(std::none_of(folders.begin(),folders.end(),[&](const auto &known){return sameLocalFolder(path,known);}))
|
||||
folders.push_back(path);
|
||||
if(folders.size()==recentFoldersLimit) break;
|
||||
}
|
||||
return folders;
|
||||
}
|
||||
|
||||
bool updateRecentFolders(const fs::path &path,bool remember)
|
||||
{
|
||||
const Handle lock{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.RecentFolders")};
|
||||
if(!lock.value) return false;
|
||||
const auto wait=WaitForSingleObject(lock.value,100);
|
||||
if(wait!=WAIT_OBJECT_0 && wait!=WAIT_ABANDONED) return false;
|
||||
bool saved=false;
|
||||
try
|
||||
{
|
||||
auto folders=readRecentFolders();
|
||||
std::erase_if(folders,[&](const auto &known){return sameLocalFolder(path,known);});
|
||||
if(remember) folders.insert(folders.begin(),path);
|
||||
if(folders.size()>recentFoldersLimit) folders.resize(recentFoldersLimit);
|
||||
auto data=Json::array();
|
||||
for(const auto &folder:folders) data.push_back(ks::utf8(folder.native()));
|
||||
saved=writeFilesJsonPreference(recentFoldersKey,data);
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
ReleaseMutex(lock.value);
|
||||
return saved;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
constexpr DWORD maxFilesJsonBytes=1024*1024;
|
||||
|
||||
std::optional<Json> readFilesJsonPreference(const wchar_t *key)
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>maxFilesJsonBytes) return {};
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return {};
|
||||
try {return Json::parse(data.begin(),data.begin()+bytes);}
|
||||
catch(const std::exception &) {return {};}
|
||||
}
|
||||
|
||||
bool writeFilesJsonPreference(const wchar_t *key,const Json &value)
|
||||
{
|
||||
try
|
||||
{
|
||||
const auto data=value.dump();
|
||||
return data.size()<=maxFilesJsonBytes &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
}
|
||||
catch(const std::exception &) {return false;}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
+402
-134
@@ -14,7 +14,6 @@
|
||||
#include <commctrl.h>
|
||||
#include <shellapi.h>
|
||||
#include <shlobj.h>
|
||||
#include <propkey.h>
|
||||
#include <atomic>
|
||||
#include <windowsx.h>
|
||||
#include <commdlg.h>
|
||||
@@ -582,12 +581,59 @@ INT_PTR CALLBACK searchDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM l
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
RemoteTextSource lanTextSource(const lan::FilesPeer &peer)
|
||||
{
|
||||
return {peer.id,peer.name,
|
||||
[peer](const std::filesystem::path &original,const std::filesystem::path &cache,
|
||||
bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit)
|
||||
{
|
||||
lan::FilesConnection source(&peer),target;
|
||||
const auto info=source.call(lan::fileRequest("stat",original));
|
||||
lan::checkFileReply(info);
|
||||
const bool canCommit=info.value("editCommit",false);
|
||||
const bool readOnly=info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY;
|
||||
if(edit && !canCommit)
|
||||
throw std::runtime_error("Update KSwitcher on the remote computer to edit this file.");
|
||||
if(edit && readOnly) throw std::runtime_error("The remote file is read-only.");
|
||||
const RemoteTextRevision revision{info.at("size"),info.at("modified"),canCommit && !readOnly};
|
||||
if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview.");
|
||||
try
|
||||
{
|
||||
lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress);
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
target.call({{"action","abort"}});
|
||||
throw;
|
||||
}
|
||||
return revision;
|
||||
},
|
||||
[peer](const std::filesystem::path &original,const std::filesystem::path &cache,
|
||||
const RemoteTextRevision &revision)
|
||||
{
|
||||
lan::FilesConnection source,target(&peer);
|
||||
const auto info=source.call(lan::fileRequest("stat",cache));
|
||||
lan::checkFileReply(info);
|
||||
const RemoteTextRevision local{info.at("size"),info.at("modified"),revision.editable};
|
||||
const lan::FileRevision expected{revision.size,revision.modified};
|
||||
try { lan::streamFile(source,target,"Files editor",cache,original,local.size,local.modified,true,false,{},&expected); }
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(error.code().value()==ERROR_FILE_INVALID)
|
||||
throw std::runtime_error("The remote file changed since it was opened. Your edits are still in the editor.");
|
||||
throw;
|
||||
}
|
||||
return local;
|
||||
}};
|
||||
}
|
||||
|
||||
struct RemoteTextFile
|
||||
{
|
||||
lan::FilesPeer peer;
|
||||
RemoteTextSource source;
|
||||
std::filesystem::path original,cache;
|
||||
lan::FileRevision revision{};
|
||||
bool editable{};
|
||||
RemoteTextRevision revision{};
|
||||
|
||||
RemoteTextFile(const RemoteTextSource &backend,const std::filesystem::path &path):source(backend),original(path) {}
|
||||
|
||||
~RemoteTextFile()
|
||||
{
|
||||
@@ -597,57 +643,22 @@ struct RemoteTextFile
|
||||
std::filesystem::remove(cache.parent_path(),ignored);
|
||||
}
|
||||
|
||||
static lan::FileRevision stat(lan::FilesConnection &host,const std::filesystem::path &path)
|
||||
{
|
||||
const auto reply=host.call(lan::fileRequest("stat",path));
|
||||
lan::checkFileReply(reply);
|
||||
return {reply.at("size").get<uint64_t>(),reply.at("modified").get<uint64_t>()};
|
||||
}
|
||||
|
||||
void download(bool edit,const lan::FileProgress &progress,uint64_t sizeLimit=UINT64_MAX)
|
||||
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
|
||||
throw std::runtime_error("Cannot create a temporary directory for the LAN file.");
|
||||
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
|
||||
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
|
||||
if(!std::filesystem::create_directory(directory))
|
||||
throw std::runtime_error("Cannot create a temporary directory for the LAN file.");
|
||||
cache=directory/original.filename();
|
||||
lan::FilesConnection source(&peer),target;
|
||||
const auto info=source.call(lan::fileRequest("stat",original));
|
||||
lan::checkFileReply(info);
|
||||
editable=info.value("editCommit",false) &&
|
||||
!(info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY);
|
||||
if(edit && !info.value("editCommit",false))
|
||||
throw std::runtime_error("Update KSwitcher on the remote computer to edit this file.");
|
||||
if(edit && (info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY))
|
||||
throw std::runtime_error("The remote file is read-only.");
|
||||
revision={info.at("size"),info.at("modified")};
|
||||
if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview.");
|
||||
try
|
||||
{
|
||||
lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress);
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
target.call({{"action","abort"}});
|
||||
throw;
|
||||
}
|
||||
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
|
||||
cache=directory/L"content";
|
||||
revision=source.download(original,cache,edit,progress,sizeLimit);
|
||||
}
|
||||
|
||||
void upload()
|
||||
{
|
||||
lan::FilesConnection source,target(&peer);
|
||||
const auto local=stat(source,cache);
|
||||
try { lan::streamFile(source,target,"Files editor",cache,original,local.size,local.modified,true,false,{},&revision); }
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(error.code().value()==ERROR_FILE_INVALID)
|
||||
throw std::runtime_error("The remote file changed since it was opened. Your edits are still in the editor.");
|
||||
throw;
|
||||
}
|
||||
revision=local;
|
||||
revision=source.upload(original,cache,revision);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -688,7 +699,7 @@ std::filesystem::path markdownTarget(const std::filesystem::path &document,std::
|
||||
return (document.parent_path()/relative).lexically_normal();
|
||||
}
|
||||
|
||||
std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer *peer,
|
||||
std::string markdownImage(const std::filesystem::path &path,const RemoteTextSource *backend,
|
||||
const std::shared_ptr<std::atomic<bool>> &cancel)
|
||||
{
|
||||
auto extension=path.extension().wstring();
|
||||
@@ -702,10 +713,10 @@ std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer
|
||||
constexpr uint64_t limit=16*1024*1024;
|
||||
auto source=path;
|
||||
std::optional<RemoteTextFile> fetched;
|
||||
if(peer)
|
||||
if(backend)
|
||||
{
|
||||
if(*cancel) return {};
|
||||
fetched.emplace(RemoteTextFile{*peer,path});
|
||||
fetched.emplace(*backend,path);
|
||||
fetched->download(false,[&](uint64_t,uint64_t){return !*cancel;},limit);
|
||||
source=fetched->cache;
|
||||
}
|
||||
@@ -728,14 +739,19 @@ std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer
|
||||
class TextWindow
|
||||
{
|
||||
public:
|
||||
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer,
|
||||
std::string_view fragment)
|
||||
: original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend,
|
||||
std::string_view fragment,TextOpenOptions options)
|
||||
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
search{dialogs}, previewFragment(fragment)
|
||||
{
|
||||
if (peer) remote=std::make_unique<RemoteTextFile>(RemoteTextFile{*peer,original});
|
||||
else document=std::make_unique<TextDocument>(original,edit);
|
||||
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
|
||||
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
|
||||
if(options.encoding!=TextEncoding::automatic)
|
||||
{
|
||||
newFormat.encoding=options.encoding;
|
||||
newFormat.bom=options.encoding==TextEncoding::utf16le || options.encoding==TextEncoding::utf16be;
|
||||
}
|
||||
for (int index = 0; index < GetLexerCount(); ++index)
|
||||
{
|
||||
char name[128]{};
|
||||
@@ -764,6 +780,9 @@ private:
|
||||
std::unique_ptr<TextDocument> document;
|
||||
std::wstring filename;
|
||||
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
|
||||
bool draft{};
|
||||
TextSaveFormat newFormat;
|
||||
std::filesystem::path pendingSavePath;
|
||||
HICON smallIcon{},largeIcon{};
|
||||
TextPreferences prefs;
|
||||
TextWindowFont filesFont;
|
||||
@@ -786,7 +805,7 @@ private:
|
||||
bool uploadPending{};
|
||||
bool switchAfterSave{};
|
||||
FilesTerminalView preview;
|
||||
bool previewWanted{}, previewVisible{};
|
||||
bool previewWanted{}, previewVisible{}, previewRetried{};
|
||||
ULONGLONG previewDeadline{};
|
||||
ULONGLONG nextFileCheck{};
|
||||
struct FileStamp
|
||||
@@ -796,6 +815,16 @@ private:
|
||||
bool operator==(const FileStamp &) const = default;
|
||||
};
|
||||
std::optional<FileStamp> previewStamp;
|
||||
struct MarkdownTask
|
||||
{
|
||||
uint64_t revision;
|
||||
size_t line,column;
|
||||
bool checked;
|
||||
};
|
||||
std::string previewText;
|
||||
uint64_t previewRevision{};
|
||||
std::optional<MarkdownTask> pendingTask;
|
||||
std::optional<size_t> taskOffset;
|
||||
std::string previewFragment;
|
||||
struct PreviewLocation
|
||||
{
|
||||
@@ -838,6 +867,7 @@ private:
|
||||
static constexpr UINT openPreviewLink = WM_APP + 3;
|
||||
static constexpr UINT previewRendered = WM_APP + 4;
|
||||
static constexpr UINT cycleWindow = WM_APP + 5;
|
||||
static constexpr UINT savePreviewTask = WM_APP + 6;
|
||||
|
||||
LRESULT send(UINT message, WPARAM wparam = 0, LPARAM lparam = 0) const
|
||||
{
|
||||
@@ -856,6 +886,9 @@ private:
|
||||
bool dirty() const { return stagedDirty || (!busy() && uploadPending) || currentChanged(); }
|
||||
bool busy() const { return saving.valid(); }
|
||||
void invalidate() const { InvalidateRect(window, nullptr, FALSE); }
|
||||
RECT statusBounds() const;
|
||||
void invalidateStatus() const;
|
||||
void invalidateHints() const;
|
||||
|
||||
void initializeDocument();
|
||||
void finishOpen();
|
||||
@@ -884,11 +917,15 @@ private:
|
||||
bool needsSave() const;
|
||||
bool canPreview() const;
|
||||
void updatePreview();
|
||||
bool startPreviewBrowser();
|
||||
void stopPreview(bool refresh=true,bool keepBrowser=false);
|
||||
void renderPreview(bool keepPosition=false);
|
||||
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
|
||||
std::optional<FileStamp> previewFileStamp() const;
|
||||
void refreshPreview();
|
||||
void startMarkdownTask();
|
||||
void finishMarkdownTask();
|
||||
void reportMarkdownTask(uint64_t revision,bool saved);
|
||||
void cancelPreviewImages();
|
||||
void previewMessage(const std::wstring &value);
|
||||
void navigatePreview(PreviewLink request);
|
||||
@@ -1342,22 +1379,25 @@ void TextWindow::finishOpen()
|
||||
void TextWindow::saveFile(bool closeWhenDone)
|
||||
{
|
||||
if (busy() || !edit) return;
|
||||
auto destination=original;
|
||||
if(draft && !search.style.saveOptions(window,destination,newFormat)) return;
|
||||
stagePage();
|
||||
if (!stagedDirty && !uploadPending)
|
||||
if (!draft && !stagedDirty && !uploadPending)
|
||||
{
|
||||
if (closeWhenDone) DestroyWindow(window);
|
||||
else if (std::exchange(switchAfterSave, false)) changeMode();
|
||||
return;
|
||||
}
|
||||
pendingCaret = send(SCI_GETCURRENTPOS);
|
||||
if(draft) pendingSavePath=destination;
|
||||
closeAfterSave = closeWhenDone;
|
||||
if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer.");
|
||||
send(SCI_SETREADONLY, TRUE);
|
||||
try
|
||||
{
|
||||
saving=std::async(std::launch::async,[this]
|
||||
saving=std::async(std::launch::async,[this,destination=std::move(destination)]
|
||||
{
|
||||
const auto reopened=document->save();
|
||||
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
|
||||
if(remote)
|
||||
{
|
||||
uploadPending=true;
|
||||
@@ -1380,10 +1420,23 @@ void TextWindow::finishSave()
|
||||
{
|
||||
if (!busy() || saving.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready) return;
|
||||
KillTimer(window, saveTimer);
|
||||
if(taskOffset)
|
||||
{
|
||||
finishMarkdownTask();
|
||||
return;
|
||||
}
|
||||
send(SCI_SETREADONLY, !edit);
|
||||
const auto change = std::exchange(switchAfterSave, false);
|
||||
const auto reopened = saving.get();
|
||||
stagedDirty = false;
|
||||
const bool created=std::exchange(draft,false);
|
||||
if(created)
|
||||
{
|
||||
original=std::move(pendingSavePath);
|
||||
filename=original.filename().wstring();
|
||||
navigationHistory.clear();
|
||||
updateTitle();
|
||||
}
|
||||
if (!reopened)
|
||||
{
|
||||
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
|
||||
@@ -1392,6 +1445,12 @@ void TextWindow::finishSave()
|
||||
}
|
||||
if (closeAfterSave) { DestroyWindow(window); return; }
|
||||
if (change) { changeMode(); return; }
|
||||
if(created)
|
||||
{
|
||||
initializeDocument();
|
||||
send(SCI_GOTOPOS,std::min<LRESULT>(pendingCaret,send(SCI_GETLENGTH)));
|
||||
return;
|
||||
}
|
||||
if (pageTotal == 1 && document->pages() == 1)
|
||||
{
|
||||
fileSize = document->size();
|
||||
@@ -1408,7 +1467,7 @@ void TextWindow::requestClose()
|
||||
if (busy()) return;
|
||||
if (needsSave())
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window);
|
||||
const auto answer = search.style.confirmSave(window,draft);
|
||||
if (answer == IDCANCEL) return;
|
||||
if (answer == IDYES) { saveFile(true); return; }
|
||||
if (answer != IDNO) return;
|
||||
@@ -1424,9 +1483,10 @@ bool TextWindow::needsSave() const
|
||||
void TextWindow::toggleMode()
|
||||
{
|
||||
if (busy() || navigation.valid()) return;
|
||||
if(draft) return;
|
||||
if (edit && needsSave())
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window);
|
||||
const auto answer = search.style.confirmSave(window,false);
|
||||
if (answer == IDYES)
|
||||
{
|
||||
switchAfterSave = true;
|
||||
@@ -1438,7 +1498,7 @@ void TextWindow::toggleMode()
|
||||
// The local LAN cache may already contain changes from a failed upload.
|
||||
if (uploadPending)
|
||||
{
|
||||
auto refreshed = std::make_unique<RemoteTextFile>(RemoteTextFile{remote->peer,original});
|
||||
auto refreshed = std::make_unique<RemoteTextFile>(remote->source,original);
|
||||
refreshed->download(false,{});
|
||||
auto replacement = std::make_unique<TextDocument>(refreshed->cache,false);
|
||||
document.reset();
|
||||
@@ -1452,7 +1512,7 @@ void TextWindow::toggleMode()
|
||||
|
||||
void TextWindow::changeMode()
|
||||
{
|
||||
if (!edit && remote && !remote->editable)
|
||||
if (!edit && remote && !remote->revision.editable)
|
||||
throw std::runtime_error("The remote file does not support editing.");
|
||||
auto replacement = std::make_unique<TextDocument>(remote ? remote->cache : original, !edit);
|
||||
const auto caret = send(SCI_GETCURRENTPOS);
|
||||
@@ -1476,7 +1536,7 @@ void TextWindow::changeMode()
|
||||
void TextWindow::updateTitle()
|
||||
{
|
||||
const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") +
|
||||
(remote ? remote->peer.name + L" · " : std::wstring{}) + original.wstring();
|
||||
(remote ? remote->source.name + L" · " : std::wstring{}) + original.wstring();
|
||||
SetWindowTextW(window,title.c_str());
|
||||
}
|
||||
|
||||
@@ -1496,23 +1556,19 @@ void TextWindow::updateIcons(UINT dpi)
|
||||
set(largeIcon,ICON_BIG,SM_CXICON,SM_CYICON);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void setFileWindowTaskbar(HWND window,int iconResource,const wchar_t *identity)
|
||||
{
|
||||
setWindowTaskbarIdentity(window, iconResource, identity);
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
void TextWindow::updateTaskbarGroup(bool closing)
|
||||
{
|
||||
auto icon=closing?std::wstring{}:executable()+L",-"+std::to_wstring(edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER);
|
||||
auto identity=std::wstring(edit?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
|
||||
IPropertyStore *properties{};
|
||||
if(FAILED(SHGetPropertyStoreForWindow(window,IID_PPV_ARGS(&properties)))) return;
|
||||
PROPVARIANT value{};
|
||||
if(!closing)
|
||||
{
|
||||
value.vt=VT_LPWSTR;
|
||||
value.pwszVal=icon.data();
|
||||
}
|
||||
properties->SetValue(PKEY_AppUserModel_RelaunchIconResource,value);
|
||||
if(!closing) value.pwszVal=identity.data();
|
||||
// Setting the group ID tells Explorer to refresh the taskbar button.
|
||||
properties->SetValue(PKEY_AppUserModel_ID,value);
|
||||
properties->Release();
|
||||
setFileWindowTaskbar(window,edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER,closing?nullptr:
|
||||
edit?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
|
||||
}
|
||||
|
||||
bool TextWindow::canPreview() const
|
||||
@@ -1528,14 +1584,21 @@ void TextWindow::updatePreview()
|
||||
return;
|
||||
}
|
||||
previewWanted=true;
|
||||
previewDeadline=GetTickCount64()+8000;
|
||||
previewRetried=false;
|
||||
previewStamp=previewFileStamp();
|
||||
nextFileCheck=GetTickCount64()+350;
|
||||
cancelImages=std::make_shared<std::atomic<bool>>(false);
|
||||
if(!SetTimer(window,previewTimer,50,nullptr)) { stopPreview(); return; }
|
||||
if(preview.initialized()) renderPreview();
|
||||
else if(!preview.create(window,[this](const auto &value){previewMessage(value);},
|
||||
[this]{PostMessageW(window,previewFailed,0,0);},true,[this](UINT key)
|
||||
else if(!startPreviewBrowser()) { stopPreview(); return; }
|
||||
layout();
|
||||
}
|
||||
|
||||
bool TextWindow::startPreviewBrowser()
|
||||
{
|
||||
previewDeadline=GetTickCount64()+8000;
|
||||
return preview.create(window,[this](const auto &value){previewMessage(value);},
|
||||
[this]{previewDeadline=GetTickCount64()+300;},true,[this](UINT key)
|
||||
{
|
||||
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
|
||||
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
|
||||
@@ -1547,7 +1610,7 @@ void TextWindow::updatePreview()
|
||||
}
|
||||
if(ctrl && !alt && key==VK_TAB)
|
||||
{
|
||||
PostMessageW(window,cycleWindow,0,0);
|
||||
PostMessageW(window,cycleWindow,(GetKeyState(VK_SHIFT)&0x8000)!=0,0);
|
||||
return true;
|
||||
}
|
||||
if(key==VK_BROWSER_BACK || key==VK_BROWSER_FORWARD || (alt && (key==VK_LEFT || key==VK_RIGHT)))
|
||||
@@ -1558,9 +1621,7 @@ void TextWindow::updatePreview()
|
||||
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
|
||||
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0);
|
||||
return true;
|
||||
}))
|
||||
stopPreview();
|
||||
layout();
|
||||
});
|
||||
}
|
||||
|
||||
void TextWindow::stopPreview(bool refresh,bool keepBrowser)
|
||||
@@ -1568,6 +1629,9 @@ void TextWindow::stopPreview(bool refresh,bool keepBrowser)
|
||||
KillTimer(window,previewTimer);
|
||||
previewWanted=previewVisible=false;
|
||||
previewStamp.reset();
|
||||
++previewRevision;
|
||||
previewText.clear();
|
||||
pendingTask.reset();
|
||||
cancelPreviewImages();
|
||||
previewLinks.clear();
|
||||
if(keepBrowser && preview.initialized()) preview.post(L"{\"action\":\"clear\"}");
|
||||
@@ -1620,11 +1684,12 @@ void TextWindow::renderPreview(bool keepPosition)
|
||||
{
|
||||
applyMarkdownPreferences(loadTextPreferences().markdown);
|
||||
previewDeadline=GetTickCount64()+30000;
|
||||
std::string text;
|
||||
previewText.clear();
|
||||
for(uint64_t index=0;index<document->pages();++index)
|
||||
text+=document->readPage(index);
|
||||
previewText+=document->readPage(index);
|
||||
if(!remote) document->releaseReadHandle();
|
||||
nlohmann::json message{{"action","render"},{"text",std::move(text)},
|
||||
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
|
||||
{"canSave",!remote || remote->revision.editable},
|
||||
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
|
||||
{"keepPosition",keepPosition}};
|
||||
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
|
||||
@@ -1641,7 +1706,7 @@ void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences
|
||||
|
||||
void TextWindow::refreshPreview()
|
||||
{
|
||||
if(remote || !previewVisible || navigation.valid() || GetTickCount64()<nextFileCheck) return;
|
||||
if(remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
|
||||
nextFileCheck=GetTickCount64()+350;
|
||||
const auto stamp=previewFileStamp();
|
||||
if(!stamp || stamp==previewStamp) return;
|
||||
@@ -1665,6 +1730,121 @@ void TextWindow::refreshPreview()
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::reportMarkdownTask(uint64_t revision,bool saved)
|
||||
{
|
||||
preview.post(wide(nlohmann::json{{"action","task-result"},{"revision",revision},{"saved",saved}}.dump()));
|
||||
}
|
||||
|
||||
void TextWindow::startMarkdownTask()
|
||||
{
|
||||
const auto task=std::exchange(pendingTask,{});
|
||||
if(!task) return;
|
||||
if(!previewVisible || edit || busy() || navigation.valid() || task->revision!=previewRevision ||
|
||||
(remote && !remote->revision.editable))
|
||||
{
|
||||
reportMarkdownTask(task->revision,false);
|
||||
return;
|
||||
}
|
||||
size_t lineStart=0;
|
||||
const auto reject=[&]{reportMarkdownTask(task->revision,false);};
|
||||
for(size_t line=0;line<task->line;++line)
|
||||
{
|
||||
const auto end=previewText.find_first_of("\r\n",lineStart);
|
||||
if(end==previewText.npos) { reject(); return; }
|
||||
lineStart=end+1;
|
||||
if(previewText[end]=='\r' && lineStart<previewText.size() && previewText[lineStart]=='\n') ++lineStart;
|
||||
}
|
||||
if(!task->column || task->column>=previewText.size()-lineStart) { reject(); return; }
|
||||
const auto offset=lineStart+task->column;
|
||||
const auto lineEnd=previewText.find_first_of("\r\n",lineStart);
|
||||
if((lineEnd!=previewText.npos && offset>=lineEnd) || offset+1>=previewText.size() ||
|
||||
previewText[offset-1]!='[' || previewText[offset+1]!=']' ||
|
||||
(previewText[offset]!=' ' && previewText[offset]!='x' && previewText[offset]!='X'))
|
||||
{
|
||||
reject();
|
||||
return;
|
||||
}
|
||||
const auto next=task->checked?'x':' ';
|
||||
if((previewText[offset]!=' ')==task->checked) { reportMarkdownTask(task->revision,true); return; }
|
||||
if(!SetTimer(window,saveTimer,75,nullptr)) { reject(); return; }
|
||||
const auto encoding=document->encoding();
|
||||
try
|
||||
{
|
||||
saving=std::async(std::launch::async,[this,expected=previewText,offset,next,encoding]
|
||||
{
|
||||
const auto path=remote?remote->cache:original;
|
||||
std::filesystem::path candidate;
|
||||
struct RemoveCandidate
|
||||
{
|
||||
std::filesystem::path &path;
|
||||
~RemoveCandidate(){if(!path.empty()){std::error_code ec;std::filesystem::remove(path,ec);}}
|
||||
} cleanup{candidate};
|
||||
if(remote)
|
||||
{
|
||||
const auto stage=path.parent_path()/(path.filename()==L"content"?L"task-update":L"content");
|
||||
std::filesystem::copy_file(path,stage);
|
||||
candidate=stage;
|
||||
}
|
||||
TextDocument fresh(remote?candidate:path,true,encoding);
|
||||
if(fresh.size()>TextDocument::editLimit)
|
||||
throw std::runtime_error("The Markdown file grew outside KSwitcher.");
|
||||
size_t start=0;
|
||||
for(uint64_t index=0;index<fresh.pages();++index)
|
||||
{
|
||||
auto text=fresh.readPage(index);
|
||||
if(std::string_view(expected).substr(start,text.size())!=text)
|
||||
throw std::runtime_error("The Markdown text changed outside KSwitcher.");
|
||||
const auto end=start+text.size();
|
||||
if(offset>=start && offset<end)
|
||||
{
|
||||
text[offset-start]=next;
|
||||
fresh.stage(index,text);
|
||||
}
|
||||
start=end;
|
||||
}
|
||||
if(start!=expected.size()) throw std::runtime_error("The Markdown text changed outside KSwitcher.");
|
||||
fresh.save();
|
||||
if(remote)
|
||||
{
|
||||
remote->revision=remote->source.upload(original,candidate,remote->revision);
|
||||
remote->cache.swap(candidate);
|
||||
}
|
||||
return next=='x';
|
||||
});
|
||||
taskOffset=offset;
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
KillTimer(window,saveTimer);
|
||||
reject();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::finishMarkdownTask()
|
||||
{
|
||||
const auto offset=*std::exchange(taskOffset,{});
|
||||
const auto revision=previewRevision;
|
||||
bool checked{};
|
||||
try {checked=saving.get();}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
reportMarkdownTask(revision,false);
|
||||
search.style.message(window,(L"Could not save the Markdown checkbox. "+wide(error.what())).c_str());
|
||||
return;
|
||||
}
|
||||
if(offset<previewText.size()) previewText[offset]=checked?'x':' ';
|
||||
reportMarkdownTask(revision,true);
|
||||
const auto encoding=document->encoding();
|
||||
document=std::make_unique<TextDocument>(remote?remote->cache:original,false,encoding);
|
||||
loadPage(std::min(page,document->pages()-1));
|
||||
if(!remote)
|
||||
{
|
||||
previewStamp=previewFileStamp();
|
||||
document->releaseReadHandle();
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::previewMessage(const std::wstring &value)
|
||||
{
|
||||
if(!previewWanted) return;
|
||||
@@ -1679,7 +1859,7 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
const auto action=message.at("action").get<std::string>();
|
||||
if(action=="cycle")
|
||||
{
|
||||
PostMessageW(window,cycleWindow,0,0);
|
||||
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
|
||||
return;
|
||||
}
|
||||
if(action=="failed")
|
||||
@@ -1692,6 +1872,16 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
PostMessageW(window,previewRendered,0,0);
|
||||
return;
|
||||
}
|
||||
if(action=="save-task")
|
||||
{
|
||||
if(!pendingTask && !busy())
|
||||
{
|
||||
pendingTask=MarkdownTask{message.at("revision"),message.at("line"),message.at("column"),
|
||||
message.at("checked")};
|
||||
PostMessageW(window,savePreviewTask,0,0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Defer transitions until WebView2 returns from its event callback.
|
||||
if(action=="edit" || action=="close")
|
||||
{
|
||||
@@ -1742,11 +1932,13 @@ void TextWindow::syncNavigation()
|
||||
|
||||
void TextWindow::navigatePreview(PreviewLink request)
|
||||
{
|
||||
if(edit || navigation.valid() || navigationHistory.empty()) return;
|
||||
if(edit || busy() || pendingTask || navigation.valid() || navigationHistory.empty()) return;
|
||||
if(request.newWindow)
|
||||
{
|
||||
openTextWindow(window,request.target.path,false,search.style,remote?&remote->peer:nullptr,
|
||||
request.target.fragment,true);
|
||||
if(remote)
|
||||
openRemoteTextWindow(window,request.target.path,false,search.style,remote->source,request.target.fragment,true);
|
||||
else
|
||||
openTextWindow(window,request.target.path,false,search.style,nullptr,request.target.fragment,true);
|
||||
return;
|
||||
}
|
||||
if((request.direction<0 && navigationIndex==0) ||
|
||||
@@ -1762,13 +1954,13 @@ void TextWindow::navigatePreview(PreviewLink request)
|
||||
if(destination.path==original || !remote) { showLocation(nullptr); return; }
|
||||
auto cancel=std::make_shared<std::atomic<bool>>(false);
|
||||
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task(
|
||||
[peer=remote->peer,path=destination.path,cancel] {
|
||||
auto file=std::make_unique<RemoteTextFile>(RemoteTextFile{peer,path});
|
||||
[backend=remote->source,path=destination.path,cancel] {
|
||||
auto file=std::make_unique<RemoteTextFile>(backend,path);
|
||||
file->download(false,[cancel](uint64_t,uint64_t){return !*cancel;});
|
||||
return file;
|
||||
});
|
||||
if(!SetTimer(window,navigationTimer,75,nullptr))
|
||||
throw std::runtime_error("Cannot start the LAN navigation timer.");
|
||||
throw std::runtime_error("Cannot start the remote navigation timer.");
|
||||
try
|
||||
{
|
||||
auto result=task.get_future();
|
||||
@@ -1826,6 +2018,13 @@ void TextWindow::pollImages()
|
||||
refreshPreview();
|
||||
if(!previewVisible && GetTickCount64()>=previewDeadline)
|
||||
{
|
||||
if(!preview.initialized() && !previewRetried)
|
||||
{
|
||||
// The previous window's WebView2 process may still be shutting down.
|
||||
previewRetried=true;
|
||||
preview.close();
|
||||
if(startPreviewBrowser()) return;
|
||||
}
|
||||
stopPreview();
|
||||
return;
|
||||
}
|
||||
@@ -1842,8 +2041,8 @@ void TextWindow::pollImages()
|
||||
activeImage=std::move(imageQueue.front());
|
||||
imageQueue.pop_front();
|
||||
std::packaged_task<std::string()> task(
|
||||
[path=activeImage.path,peer=remote?std::optional(remote->peer):std::nullopt,cancel=cancelImages] {
|
||||
return markdownImage(path,peer?&*peer:nullptr,cancel);
|
||||
[path=activeImage.path,backend=remote?std::optional(remote->source):std::nullopt,cancel=cancelImages] {
|
||||
return markdownImage(path,backend?&*backend:nullptr,cancel);
|
||||
});
|
||||
image=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
@@ -1861,6 +2060,58 @@ void TextWindow::layout()
|
||||
invalidate();
|
||||
}
|
||||
|
||||
RECT TextWindow::statusBounds() const
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
bounds.top=chromeHeight();
|
||||
bounds.bottom=2*bounds.top;
|
||||
return bounds;
|
||||
}
|
||||
|
||||
void TextWindow::invalidateStatus() const
|
||||
{
|
||||
const auto bounds=statusBounds();
|
||||
InvalidateRect(window,&bounds,FALSE);
|
||||
}
|
||||
|
||||
void TextWindow::invalidateHints() const
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
bounds.top=std::max(0L,bounds.bottom-chromeHeight());
|
||||
InvalidateRect(window,&bounds,FALSE);
|
||||
}
|
||||
|
||||
void drawEditorStatus(HDC dc,RECT bounds,HFONT font,COLORREF background,COLORREF foreground,
|
||||
int inset,const std::wstring &status)
|
||||
{
|
||||
const auto width=bounds.right-bounds.left,height=bounds.bottom-bounds.top;
|
||||
if(width<=0 || height<=0) return;
|
||||
const auto memory=CreateCompatibleDC(dc);
|
||||
const auto bitmap=memory?CreateCompatibleBitmap(dc,width,height):nullptr;
|
||||
const auto target=bitmap?memory:dc;
|
||||
const auto oldBitmap=bitmap?SelectObject(memory,bitmap):nullptr;
|
||||
const auto oldFont=SelectObject(target,font);
|
||||
auto row=bitmap?RECT{0,0,width,height}:bounds;
|
||||
SetDCBrushColor(target,background);
|
||||
FillRect(target,&row,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
SetBkMode(target,TRANSPARENT);
|
||||
SetTextColor(target,foreground);
|
||||
row.left+=inset;
|
||||
row.right-=inset;
|
||||
if(row.left<row.right)
|
||||
DrawTextW(target,status.c_str(),-1,&row,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
SelectObject(target,oldFont);
|
||||
if(bitmap)
|
||||
{
|
||||
BitBlt(dc,bounds.left,bounds.top,width,height,memory,0,0,SRCCOPY);
|
||||
SelectObject(memory,oldBitmap);
|
||||
DeleteObject(bitmap);
|
||||
}
|
||||
if(memory) DeleteDC(memory);
|
||||
}
|
||||
|
||||
void TextWindow::paint()
|
||||
{
|
||||
PAINTSTRUCT paint{};
|
||||
@@ -1870,12 +2121,12 @@ void TextWindow::paint()
|
||||
const auto row = chromeHeight();
|
||||
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
SetDCBrushColor(dc, color(TextColor::background));
|
||||
FillRect(dc, &client, brush);
|
||||
const RECT body{0,2*row,client.right,std::max<LONG>(2*row,client.bottom-row)};
|
||||
FillRect(dc, &body, brush);
|
||||
SetDCBrushColor(dc, color(TextColor::chromebg));
|
||||
RECT menuBar{0, 0, client.right, row};
|
||||
RECT top{0, row, client.right, 2 * row};
|
||||
const RECT top=statusBounds();
|
||||
RECT bottom{0, client.bottom - row, client.right, client.bottom};
|
||||
FillRect(dc, &top, brush);
|
||||
FillRect(dc, &bottom, brush);
|
||||
FillRect(dc, &menuBar, brush);
|
||||
const auto chromeFont = createChromeFont();
|
||||
@@ -1904,27 +2155,27 @@ void TextWindow::paint()
|
||||
}
|
||||
SetTextColor(dc, color(TextColor::chrome));
|
||||
bottom.left += scale(7);
|
||||
const auto position = send(SCI_GETCURRENTPOS);
|
||||
const auto line = send(SCI_LINEFROMPOSITION, position) + 1;
|
||||
const auto column = send(SCI_GETCOLUMN, position) + 1;
|
||||
const auto displayLanguage = textLanguageLabel(language);
|
||||
auto status = filename + (edit ? L" (Edit)" : L" (View)") + (dirty() ? L" *" : L"") +
|
||||
L" │ " + (document?document->encodingName():L"Loading…") + L" │ " + displayLanguage +
|
||||
L" │ Ln " + std::to_wstring(line) + L":" + std::to_wstring(column);
|
||||
if (pageTotal > 1)
|
||||
status += L" │ Page " + std::to_wstring(page + 1) + L"/" + std::to_wstring(pageTotal) +
|
||||
L" @ " + std::to_wstring(pageOffset);
|
||||
status += L" │ " + std::to_wstring(fileSize) + L" B";
|
||||
RECT statusPaint{};
|
||||
if(IntersectRect(&statusPaint,&top,&paint.rcPaint))
|
||||
{
|
||||
const auto position=send(SCI_GETCURRENTPOS);
|
||||
const auto line=send(SCI_LINEFROMPOSITION,position)+1;
|
||||
const auto column=send(SCI_GETCOLUMN,position)+1;
|
||||
auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+
|
||||
L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+
|
||||
L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column);
|
||||
if(pageTotal>1)
|
||||
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
|
||||
L" @ "+std::to_wstring(pageOffset);
|
||||
status+=L" │ "+std::to_wstring(fileSize)+L" B";
|
||||
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
|
||||
}
|
||||
const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" :
|
||||
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
|
||||
previewVisible ? L"F6 Edit Ctrl+W Close" :
|
||||
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
|
||||
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
|
||||
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
|
||||
top.left += scale(12);
|
||||
top.right -= scale(12);
|
||||
if (top.left < top.right)
|
||||
DrawTextW(dc, status.c_str(), -1, &top, format | DT_RIGHT);
|
||||
DrawTextW(dc, hints, -1, &bottom, format);
|
||||
SelectObject(dc, previous);
|
||||
DeleteObject(chromeFont);
|
||||
@@ -2044,6 +2295,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
case SCN_MODIFIED:
|
||||
if (notice.modificationType & SC_MOD_INSERTCHECK)
|
||||
{
|
||||
const auto hadWarning=insertRejected;
|
||||
if (send(SCI_GETLENGTH) + notice.length > static_cast<LRESULT>(TextDocument::editLimit))
|
||||
{
|
||||
send(SCI_CHANGEINSERTION, 0, reinterpret_cast<LPARAM>(""));
|
||||
@@ -2051,6 +2303,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
MessageBeep(MB_ICONWARNING);
|
||||
}
|
||||
else insertRejected = false;
|
||||
if(hadWarning!=insertRejected) invalidateHints();
|
||||
}
|
||||
if (notice.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
|
||||
{
|
||||
@@ -2058,8 +2311,8 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
undoBytes += static_cast<size_t>(notice.length) + 64;
|
||||
if (undoBytes >= 32 * TextDocument::pageBytes)
|
||||
PostMessageW(window, trimUndo, 0, 0);
|
||||
invalidateStatus();
|
||||
}
|
||||
invalidate();
|
||||
break;
|
||||
case SCN_CHARADDED:
|
||||
if (edit && prefs.autoIndent && (notice.ch == '\n' || (notice.ch == '\r' && send(SCI_GETEOLMODE) == SC_EOL_CR)))
|
||||
@@ -2079,7 +2332,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
case SCN_UPDATEUI:
|
||||
case SCN_SAVEPOINTREACHED:
|
||||
case SCN_SAVEPOINTLEFT:
|
||||
invalidate();
|
||||
invalidateStatus();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -2188,7 +2441,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
self->applyPreferences();
|
||||
self->send(SCI_SETREADONLY,TRUE);
|
||||
if(!SetTimer(window,openTimer,75,nullptr))
|
||||
throw std::runtime_error("Cannot start the LAN file timer.");
|
||||
throw std::runtime_error("Cannot start the remote file timer.");
|
||||
self->opening=std::async(std::launch::async,[state=self.get()]
|
||||
{
|
||||
state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;});
|
||||
@@ -2213,7 +2466,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
}
|
||||
case WM_SETFOCUS: self->focusContent(); return 0;
|
||||
case cycleWindow: cycleTextWindows(window); return 0;
|
||||
case cycleWindow: cycleTextWindows(window,wparam!=0); return 0;
|
||||
case WM_KEYDOWN:
|
||||
if(self->previewWanted && !self->previewVisible)
|
||||
{
|
||||
@@ -2224,6 +2477,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
}
|
||||
break;
|
||||
case previewFailed: self->stopPreview(); return 0;
|
||||
case savePreviewTask: self->startMarkdownTask(); return 0;
|
||||
case previewRendered:
|
||||
if(self->previewWanted)
|
||||
{
|
||||
@@ -2412,7 +2666,7 @@ void textWindowOwnerClosed()
|
||||
if(textWindows.empty()) PostQuitMessage(0);
|
||||
}
|
||||
|
||||
bool cycleTextWindows(HWND current)
|
||||
bool cycleTextWindows(HWND current,bool reverse)
|
||||
{
|
||||
if(!current || (current!=filesOwner && !textWindows.contains(current))) return false;
|
||||
std::vector<HWND> windows;
|
||||
@@ -2422,17 +2676,18 @@ bool cycleTextWindows(HWND current)
|
||||
if(windows.size()<2) return false;
|
||||
const auto from=std::find(windows.begin(),windows.end(),current);
|
||||
if(from==windows.end()) return false;
|
||||
auto to=std::next(from);
|
||||
if(to==windows.end()) to=windows.begin();
|
||||
if(IsIconic(*to)) ShowWindow(*to,SW_RESTORE);
|
||||
SetForegroundWindow(*to);
|
||||
if(*to!=filesOwner) SendMessageW(*to,WM_SETFOCUS,0,0);
|
||||
const auto index=static_cast<size_t>(from-windows.begin());
|
||||
const auto step=reverse?windows.size()-1:1;
|
||||
const auto target=windows[(index+step)%windows.size()];
|
||||
if(IsIconic(target)) ShowWindow(target,SW_RESTORE);
|
||||
SetForegroundWindow(target);
|
||||
if(target!=filesOwner) SendMessageW(target,WM_SETFOCUS,0,0);
|
||||
return true;
|
||||
}
|
||||
|
||||
HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *peer)
|
||||
HWND findOpenDocument(const std::filesystem::path &path,std::string_view id)
|
||||
{
|
||||
const auto identity=documentIdentity(path,peer?peer->id:"");
|
||||
const auto identity=documentIdentity(path,id);
|
||||
struct Search
|
||||
{
|
||||
COPYDATASTRUCT query;
|
||||
@@ -2456,16 +2711,16 @@ HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *pe
|
||||
return search.match;
|
||||
}
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow)
|
||||
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(!textWindows.contains(owner)) filesOwner=owner;
|
||||
std::error_code error;
|
||||
const auto identity=peer?path.lexically_normal():std::filesystem::weakly_canonical(path,error);
|
||||
const auto identity=backend?path.lexically_normal():std::filesystem::weakly_canonical(path,error);
|
||||
const auto &original=error?path:identity;
|
||||
if(const auto existing=newWindow?nullptr:findOpenDocument(original,peer))
|
||||
if(const auto existing=newWindow?nullptr:findOpenDocument(original,backend?backend->id:""))
|
||||
{
|
||||
if(dialogs.confirmExisting(owner) && IsWindow(existing))
|
||||
{
|
||||
@@ -2489,9 +2744,9 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
|
||||
}();
|
||||
if(!registered) throw std::runtime_error("Cannot register the text window.");
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment);
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,backend,fragment,options);
|
||||
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
|
||||
(peer?peer->name+L" · ":std::wstring{})+path.wstring();
|
||||
(backend?backend->name+L" · ":std::wstring{})+path.wstring();
|
||||
RECT bounds{};
|
||||
GetWindowRect(owner,&bounds);
|
||||
const auto window=CreateWindowExW(WS_EX_APPWINDOW,windowClass,title.c_str(),
|
||||
@@ -2503,4 +2758,17 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
}
|
||||
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
|
||||
}
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow,TextOpenOptions options)
|
||||
{
|
||||
const auto backend=peer?std::optional(lanTextSource(*peer)):std::nullopt;
|
||||
openTextWindowImpl(owner,path,edit,dialogs,backend?&*backend:nullptr,fragment,newWindow,options);
|
||||
}
|
||||
|
||||
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource &source,std::string_view fragment,bool newWindow)
|
||||
{
|
||||
openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,{});
|
||||
}
|
||||
}
|
||||
+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);
|
||||
}
|
||||
@@ -0,0 +1,679 @@
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <bcrypt.h>
|
||||
#include <wincrypt.h>
|
||||
#include <wincred.h>
|
||||
#include <shellapi.h>
|
||||
#include <objbase.h>
|
||||
#include "google_drive.h"
|
||||
#include "sync.h"
|
||||
#include "google_drive_oauth.h"
|
||||
#include "http_handle.h"
|
||||
#include "json.hpp"
|
||||
#if __has_include("google_drive_oauth_config.h")
|
||||
#include "google_drive_oauth_config.h"
|
||||
#endif
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <initializer_list>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Json = nlohmann::json;
|
||||
constexpr std::string_view Scope = "https://www.googleapis.com/auth/drive.appdata";
|
||||
constexpr auto TokenHost = L"oauth2.googleapis.com";
|
||||
constexpr auto DriveHost = L"www.googleapis.com";
|
||||
constexpr auto NativeName = "kswitcher-win32-settings.json";
|
||||
constexpr auto PreviewName = "kswitcher-settings.json";
|
||||
constexpr auto SyncName = "kswitcher-win32-sync-v1.json";
|
||||
constexpr auto Reconnect = "Google Drive needs authorization again. Reconnect your Google account.";
|
||||
constexpr auto Network = "Could not reach Google Drive. Check your connection and try again.";
|
||||
|
||||
#ifdef KS_GOOGLE_CLIENT_ID
|
||||
constexpr std::string_view ClientId = KS_GOOGLE_CLIENT_ID, ClientSecret = KS_GOOGLE_CLIENT_SECRET;
|
||||
#else
|
||||
constexpr std::string_view ClientId, ClientSecret;
|
||||
#endif
|
||||
|
||||
void requireConfiguration()
|
||||
{
|
||||
if (!googleDriveConfigured()) throw std::runtime_error("Google Drive is unavailable in this build.");
|
||||
}
|
||||
|
||||
std::wstring credentialName()
|
||||
{
|
||||
return L"KSwitcher.GoogleDrive/" + wide(std::string(ClientId));
|
||||
}
|
||||
|
||||
std::string refreshToken()
|
||||
{
|
||||
PCREDENTIALW raw{};
|
||||
if (!CredReadW(credentialName().c_str(), CRED_TYPE_GENERIC, 0, &raw))
|
||||
{
|
||||
if (GetLastError() == ERROR_NOT_FOUND) return {};
|
||||
throw std::runtime_error("Could not read the Google Drive connection from Windows Credential Manager.");
|
||||
}
|
||||
struct Credential
|
||||
{
|
||||
PCREDENTIALW value;
|
||||
~Credential()
|
||||
{
|
||||
if (value->CredentialBlobSize) SecureZeroMemory(value->CredentialBlob, value->CredentialBlobSize);
|
||||
CredFree(value);
|
||||
}
|
||||
} credential{raw};
|
||||
if (!raw->CredentialBlobSize) return {};
|
||||
return {reinterpret_cast<const char *>(raw->CredentialBlob), raw->CredentialBlobSize};
|
||||
}
|
||||
|
||||
void saveRefreshToken(std::string &token)
|
||||
{
|
||||
if (token.empty() || token.size() > CRED_MAX_CREDENTIAL_BLOB_SIZE)
|
||||
throw std::runtime_error("Google did not return a usable offline connection. Reconnect and allow access.");
|
||||
auto target = credentialName();
|
||||
CREDENTIALW credential{};
|
||||
credential.Type = CRED_TYPE_GENERIC;
|
||||
credential.TargetName = target.data();
|
||||
credential.CredentialBlobSize = static_cast<DWORD>(token.size());
|
||||
credential.CredentialBlob = reinterpret_cast<LPBYTE>(token.data());
|
||||
credential.Persist = CRED_PERSIST_LOCAL_MACHINE;
|
||||
if (!CredWriteW(&credential, 0))
|
||||
throw std::runtime_error("Could not save the Google Drive connection in Windows Credential Manager.");
|
||||
}
|
||||
|
||||
std::string urlEncode(std::string_view value)
|
||||
{
|
||||
constexpr char hex[] = "0123456789ABCDEF";
|
||||
std::string result;
|
||||
for (unsigned char c : value)
|
||||
{
|
||||
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
|
||||
c == '-' || c == '_' || c == '.' || c == '~') result += static_cast<char>(c);
|
||||
else
|
||||
{
|
||||
result += '%';
|
||||
result += hex[c >> 4];
|
||||
result += hex[c & 15];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string form(std::initializer_list<std::pair<std::string_view, std::string_view>> fields)
|
||||
{
|
||||
std::string result;
|
||||
for (const auto &[key, value] : fields)
|
||||
{
|
||||
if (!result.empty()) result += '&';
|
||||
result += key;
|
||||
result += '=';
|
||||
result += urlEncode(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<std::string> urlDecode(std::string_view value)
|
||||
{
|
||||
auto digit = [](char c)
|
||||
{
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
};
|
||||
std::string result;
|
||||
while (!value.empty())
|
||||
{
|
||||
const char c = value.front();
|
||||
value.remove_prefix(1);
|
||||
if (c != '%') result += (c == '+' ? ' ' : c);
|
||||
else
|
||||
{
|
||||
if (value.size() < 2 || digit(value[0]) < 0 || digit(value[1]) < 0) return {};
|
||||
result += static_cast<char>(digit(value[0]) * 16 + digit(value[1]));
|
||||
value.remove_prefix(2);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string base64Url(const std::array<unsigned char, 32> &data)
|
||||
{
|
||||
std::array<char, 45> encoded{};
|
||||
DWORD length = static_cast<DWORD>(encoded.size());
|
||||
if (!CryptBinaryToStringA(data.data(), static_cast<DWORD>(data.size()),
|
||||
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, encoded.data(), &length))
|
||||
throw std::runtime_error("Could not start a secure Google connection.");
|
||||
std::string result(encoded.data(), length);
|
||||
for (char &c : result)
|
||||
{
|
||||
if (c == '/') c = '_';
|
||||
if (c == '+') c = '-';
|
||||
}
|
||||
result.resize(result.find('='));
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string randomParameter()
|
||||
{
|
||||
std::array<unsigned char, 32> data{};
|
||||
if (BCryptGenRandom(nullptr, data.data(), static_cast<ULONG>(data.size()), BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0)
|
||||
throw std::runtime_error("Could not start a secure Google connection.");
|
||||
return base64Url(data);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
std::string google_drive_oauth::challengeFor(const std::string &verifier)
|
||||
{
|
||||
BCRYPT_ALG_HANDLE algorithm{};
|
||||
if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0)
|
||||
throw std::runtime_error("Could not start a secure Google connection.");
|
||||
std::array<unsigned char, 32> hash{};
|
||||
const auto status = BCryptHash(algorithm, nullptr, 0,
|
||||
reinterpret_cast<PUCHAR>(const_cast<char *>(verifier.data())), static_cast<ULONG>(verifier.size()),
|
||||
hash.data(), static_cast<ULONG>(hash.size()));
|
||||
BCryptCloseAlgorithmProvider(algorithm, 0);
|
||||
if (status < 0) throw std::runtime_error("Could not start a secure Google connection.");
|
||||
return base64Url(hash);
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
struct HttpResponse { DWORD status{}; Bytes body; };
|
||||
|
||||
HttpResponse https(const wchar_t *host, const wchar_t *method, const std::wstring &path,
|
||||
const std::wstring &headers, std::string &payload, size_t limit)
|
||||
{
|
||||
HttpHandle session{WinHttpOpen(L"KSwitcher Google Drive/1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
|
||||
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)};
|
||||
if (!session.h || !WinHttpSetTimeouts(session.h, 5000, 5000, 10000, 10000))
|
||||
throw std::runtime_error(Network);
|
||||
HttpHandle connection{WinHttpConnect(session.h, host, INTERNET_DEFAULT_HTTPS_PORT, 0)};
|
||||
HttpHandle request{connection.h ? WinHttpOpenRequest(connection.h, method, path.c_str(), nullptr,
|
||||
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr};
|
||||
DWORD redirects = WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
|
||||
DWORD disable = WINHTTP_DISABLE_COOKIES | WINHTTP_DISABLE_AUTHENTICATION;
|
||||
if (!request.h ||
|
||||
!WinHttpSetOption(request.h, WINHTTP_OPTION_REDIRECT_POLICY, &redirects, sizeof(redirects)) ||
|
||||
!WinHttpSetOption(request.h, WINHTTP_OPTION_DISABLE_FEATURE, &disable, sizeof(disable)) ||
|
||||
!WinHttpSendRequest(request.h, headers.c_str(), static_cast<DWORD>(headers.size()),
|
||||
payload.empty() ? WINHTTP_NO_REQUEST_DATA : payload.data(), static_cast<DWORD>(payload.size()),
|
||||
static_cast<DWORD>(payload.size()), 0) ||
|
||||
!WinHttpReceiveResponse(request.h, nullptr))
|
||||
throw std::runtime_error(Network);
|
||||
HttpResponse response;
|
||||
DWORD length = sizeof(response.status);
|
||||
if (!WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
|
||||
WINHTTP_HEADER_NAME_BY_INDEX, &response.status, &length, WINHTTP_NO_HEADER_INDEX))
|
||||
throw std::runtime_error(Network);
|
||||
if (response.status < 200 || response.status >= 300) return response;
|
||||
const auto deadline = GetTickCount64() + 30000;
|
||||
for (;;)
|
||||
{
|
||||
unsigned char buffer[8192];
|
||||
DWORD count{};
|
||||
if (GetTickCount64() >= deadline || !WinHttpReadData(request.h, buffer, sizeof(buffer), &count))
|
||||
throw std::runtime_error(Network);
|
||||
if (!count) return response;
|
||||
if (count > limit - response.body.size())
|
||||
throw std::runtime_error(limit == GoogleDriveBackupLimit ? "This Drive backup exceeds the 2 MiB limit." :
|
||||
"Google returned an oversized response.");
|
||||
response.body.insert(response.body.end(), buffer, buffer + count);
|
||||
}
|
||||
}
|
||||
|
||||
struct ClearString
|
||||
{
|
||||
std::string &value;
|
||||
~ClearString() { if (!value.empty()) SecureZeroMemory(value.data(), value.size()); }
|
||||
};
|
||||
|
||||
struct Tokens { std::string access, refresh; };
|
||||
|
||||
Tokens requestTokens(std::string payload)
|
||||
{
|
||||
ClearString clear{payload};
|
||||
payload += "&" + form({{"client_id", ClientId}, {"client_secret", ClientSecret}});
|
||||
auto response = https(TokenHost, L"POST", L"/token", L"Content-Type: application/x-www-form-urlencoded\r\n",
|
||||
payload, 64 * 1024);
|
||||
if (response.status == 400 || response.status == 401 || response.status == 403)
|
||||
throw std::runtime_error(Reconnect);
|
||||
if (response.status < 200 || response.status >= 300)
|
||||
throw std::runtime_error("Google could not authorize the connection. Try again.");
|
||||
const auto data = Json::parse(response.body, nullptr, false);
|
||||
if (!response.body.empty()) SecureZeroMemory(response.body.data(), response.body.size());
|
||||
try
|
||||
{
|
||||
Tokens tokens{data.at("access_token").get<std::string>(), data.value("refresh_token", "")};
|
||||
if (tokens.access.empty() || tokens.access.find_first_not_of(
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~+/=") != std::string::npos)
|
||||
throw std::runtime_error("Invalid Google access token.");
|
||||
return tokens;
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
throw std::runtime_error("Google returned an invalid authorization response.");
|
||||
}
|
||||
}
|
||||
|
||||
struct Winsock
|
||||
{
|
||||
Winsock()
|
||||
{
|
||||
WSADATA data{};
|
||||
if (WSAStartup(MAKEWORD(2, 2), &data)) throw std::runtime_error("Could not open a local sign-in callback.");
|
||||
}
|
||||
~Winsock() { WSACleanup(); }
|
||||
};
|
||||
|
||||
struct Socket
|
||||
{
|
||||
SOCKET handle;
|
||||
~Socket() { if (handle != INVALID_SOCKET) closesocket(handle); }
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
std::optional<std::string> google_drive_oauth::callbackCode(std::string_view request, std::string_view state)
|
||||
{
|
||||
constexpr std::string_view prefix = "GET /oauth/callback?";
|
||||
const auto end = request.find(' ', prefix.size());
|
||||
if (!request.starts_with(prefix) || end == std::string_view::npos) return {};
|
||||
auto query = request.substr(prefix.size(), end - prefix.size());
|
||||
std::optional<std::string> returnedState, code;
|
||||
bool denied = false;
|
||||
while (!query.empty())
|
||||
{
|
||||
const auto next = query.find('&');
|
||||
const auto entry = query.substr(0, next);
|
||||
const auto equals = entry.find('=');
|
||||
if (equals != std::string_view::npos)
|
||||
{
|
||||
const auto key = entry.substr(0, equals);
|
||||
const auto value = entry.substr(equals + 1);
|
||||
if (key == "state")
|
||||
{
|
||||
if (returnedState) return {};
|
||||
returnedState = urlDecode(value);
|
||||
if (!returnedState) return {};
|
||||
}
|
||||
if (key == "code")
|
||||
{
|
||||
if (code) return {};
|
||||
code = urlDecode(value);
|
||||
if (!code) return {};
|
||||
}
|
||||
if (key == "error") denied = true;
|
||||
}
|
||||
if (next == std::string_view::npos) break;
|
||||
query.remove_prefix(next + 1);
|
||||
}
|
||||
if (!returnedState || *returnedState != state) return {};
|
||||
return denied ? std::string{} : code.value_or("");
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
void checkCanceled(std::stop_token stop)
|
||||
{
|
||||
if (stop.stop_requested()) throw std::runtime_error("Google sign-in was canceled.");
|
||||
}
|
||||
|
||||
std::optional<std::string> readCallback(SOCKET socket, std::string_view state, std::stop_token stop)
|
||||
{
|
||||
const DWORD timeout = 200;
|
||||
const auto timeoutValue = reinterpret_cast<const char *>(&timeout);
|
||||
if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, timeoutValue, sizeof(timeout)) ||
|
||||
setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, timeoutValue, sizeof(timeout))) return {};
|
||||
const auto deadline = GetTickCount64() + 2000;
|
||||
std::string request;
|
||||
for (;;)
|
||||
{
|
||||
checkCanceled(stop);
|
||||
if (GetTickCount64() >= deadline || request.size() >= 8192) return {};
|
||||
char buffer[1024];
|
||||
const auto count = recv(socket, buffer, static_cast<int>(sizeof(buffer)), 0);
|
||||
if (count <= 0) return {};
|
||||
request.append(buffer, count);
|
||||
if (request.find("\r\n") != request.npos) break;
|
||||
}
|
||||
auto code = google_drive_oauth::callbackCode(request.substr(0, request.find("\r\n")), state);
|
||||
const std::string message = !code ? "This sign-in response did not match KSwitcher." :
|
||||
code->empty() ? "Google sign-in was canceled. Return to KSwitcher." : "Return to KSwitcher to finish signing in.";
|
||||
const std::string reply = std::string(code ? "HTTP/1.1 200 OK" : "HTTP/1.1 400 Bad Request") +
|
||||
"\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer"
|
||||
"\r\nConnection: close\r\nContent-Length: " + std::to_string(message.size()) + "\r\n\r\n" + message;
|
||||
send(socket, reply.data(), static_cast<int>(reply.size()), 0);
|
||||
return code;
|
||||
}
|
||||
|
||||
std::string waitForCode(SOCKET listener, const std::string &state, std::stop_token stop)
|
||||
{
|
||||
const auto deadline = GetTickCount64() + 120000;
|
||||
while (GetTickCount64() < deadline)
|
||||
{
|
||||
checkCanceled(stop);
|
||||
fd_set readable;
|
||||
FD_ZERO(&readable);
|
||||
FD_SET(listener, &readable);
|
||||
timeval interval{0, 200000};
|
||||
const int ready = select(0, &readable, nullptr, nullptr, &interval);
|
||||
if (!ready) continue;
|
||||
Socket peer{ready == SOCKET_ERROR ? INVALID_SOCKET : accept(listener, nullptr, nullptr)};
|
||||
if (peer.handle == INVALID_SOCKET) throw std::runtime_error("Could not receive the Google sign-in response.");
|
||||
const auto code = readCallback(peer.handle, state, stop);
|
||||
if (!code) continue;
|
||||
if (code->empty()) throw std::runtime_error("Google sign-in was declined or canceled.");
|
||||
return *code;
|
||||
}
|
||||
throw std::runtime_error("Google sign-in timed out. Connect again to retry.");
|
||||
}
|
||||
|
||||
void checkDrive(DWORD status)
|
||||
{
|
||||
if (status == 401) throw std::runtime_error(Reconnect);
|
||||
if (status == 403) throw std::runtime_error("Google Drive denied access. Reconnect or check your account's access.");
|
||||
if (status == 404) throw std::runtime_error("The requested file is no longer available on Google Drive.");
|
||||
if (status == 412) throw std::runtime_error("The Google Drive profile changed on another PC. Sync again.");
|
||||
if (status < 200 || status >= 300) throw std::runtime_error("Google Drive could not complete the request. Try again.");
|
||||
}
|
||||
|
||||
HttpResponse driveRequest(const wchar_t *method, const std::string &path, const std::string &access,
|
||||
const std::wstring &contentType = {}, std::string payload = {}, size_t limit = 64 * 1024,
|
||||
const std::wstring &additionalHeaders = {})
|
||||
{
|
||||
auto response = https(DriveHost, method, wide(path), L"Authorization: Bearer " + wide(access) + L"\r\n" +
|
||||
(contentType.empty() ? L"" : L"Content-Type: " + contentType + L"\r\n") + additionalHeaders, payload, limit);
|
||||
checkDrive(response.status);
|
||||
return response;
|
||||
}
|
||||
|
||||
std::string accessToken()
|
||||
{
|
||||
requireConfiguration();
|
||||
auto refresh = refreshToken();
|
||||
ClearString clear{refresh};
|
||||
if (refresh.empty()) throw std::runtime_error(Reconnect);
|
||||
return requestTokens(form({{"grant_type", "refresh_token"}, {"refresh_token", refresh}})).access;
|
||||
}
|
||||
|
||||
struct DriveFile { std::string id; std::wstring created; };
|
||||
|
||||
DriveFile driveFile(const Json &file)
|
||||
{
|
||||
DriveFile result{file.at("id").get<std::string>(), wide(file.at("createdTime").get<std::string>())};
|
||||
if (result.id.empty() || result.created.empty()) throw std::runtime_error("Incomplete backup metadata.");
|
||||
return result;
|
||||
}
|
||||
|
||||
Json driveFilePage(const std::string &access, const std::string &filter, size_t count,
|
||||
std::string_view page, std::string_view fields)
|
||||
{
|
||||
const auto query = form({{"spaces", "appDataFolder"}, {"pageSize", std::to_string(count)},
|
||||
{"orderBy", "createdTime desc"}, {"q", filter}, {"fields", fields}});
|
||||
const auto response = driveRequest(L"GET", "/drive/v3/files?" + query +
|
||||
(page.empty() ? "" : "&pageToken=" + urlEncode(page)), access);
|
||||
auto data = Json::parse(response.body, nullptr, false);
|
||||
if (!data.is_object() || !data.contains("files") || !data.at("files").is_array() ||
|
||||
data.value("incompleteSearch", false))
|
||||
throw std::runtime_error("Google Drive returned an unreadable file list.");
|
||||
return data;
|
||||
}
|
||||
|
||||
std::vector<DriveFile> matchingFiles(const std::string &access, const std::string &filter, size_t count)
|
||||
{
|
||||
std::vector<DriveFile> matches;
|
||||
std::string page;
|
||||
// Drive can return an empty page with a continuation token.
|
||||
for (int i = 0; i < 20; ++i)
|
||||
{
|
||||
const auto data = driveFilePage(access, filter, count, page, "nextPageToken,incompleteSearch,files(id,createdTime)");
|
||||
try
|
||||
{
|
||||
const auto &files = data.at("files").get_ref<const Json::array_t &>();
|
||||
for (const auto &file : files)
|
||||
{
|
||||
matches.push_back(driveFile(file));
|
||||
if (matches.size() == count) return matches;
|
||||
}
|
||||
page = data.value("nextPageToken", "");
|
||||
if (page.empty()) return matches;
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
throw std::runtime_error("Google Drive returned an unreadable backup list.");
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("Google Drive did not finish listing backups. Try again.");
|
||||
}
|
||||
|
||||
DriveFile createDriveFile(const std::string &access, const std::string &name, const std::string &settings)
|
||||
{
|
||||
if (settings.size() > GoogleDriveBackupLimit) throw std::runtime_error("Settings exceed the 2 MiB Drive limit.");
|
||||
const auto boundary = randomParameter();
|
||||
const auto metadata = Json{{"name", name}, {"parents", Json::array({"appDataFolder"})}}.dump();
|
||||
auto payload = "--" + boundary + "\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n" +
|
||||
metadata + "\r\n--" + boundary + "\r\nContent-Type: application/json\r\n\r\n" +
|
||||
settings + "\r\n--" + boundary + "--\r\n";
|
||||
const auto response = driveRequest(L"POST", "/upload/drive/v3/files?uploadType=multipart&fields=id%2CcreatedTime",
|
||||
access, L"multipart/related; boundary=" + wide(boundary), std::move(payload));
|
||||
try { return driveFile(Json::parse(response.body, nullptr, false)); }
|
||||
catch (const std::exception &) { throw std::runtime_error("Google Drive did not confirm the upload."); }
|
||||
}
|
||||
|
||||
class GoogleDriveSync final : public SyncProvider
|
||||
{
|
||||
std::string access, name;
|
||||
std::string file;
|
||||
std::wstring etag;
|
||||
uint64_t revision{};
|
||||
|
||||
std::string findProfile()
|
||||
{
|
||||
auto files = matchingFiles(access, "name = '" + name + "'", 2);
|
||||
if (files.size() > 1) throw std::runtime_error("Multiple Google Drive sync profiles were found. Automatic sync is paused.");
|
||||
return files.empty() ? std::string{} : urlEncode(files.front().id);
|
||||
}
|
||||
std::wstring revisionTag()
|
||||
{
|
||||
// Drive v2 exposes the ETag and enforces it on the media PUT.
|
||||
const auto meta = driveRequest(L"GET", "/drive/v2/files/" + file + "?fields=etag", access);
|
||||
const auto tag = Json::parse(meta.body).at("etag").get<std::string>();
|
||||
if (tag.size() < 3 || tag.size() > 1024 || tag.front() != '"' || tag.back() != '"' ||
|
||||
tag.find_first_of("\r\n") != tag.npos)
|
||||
throw std::runtime_error("Google Drive returned an invalid sync revision.");
|
||||
return wide(tag);
|
||||
}
|
||||
|
||||
public:
|
||||
GoogleDriveSync(std::string token, std::string profileName) : access(std::move(token)), name(std::move(profileName)) {}
|
||||
~GoogleDriveSync() override { ClearString clear{access}; }
|
||||
|
||||
SyncDocument read() override
|
||||
{
|
||||
file = findProfile();
|
||||
if (file.empty())
|
||||
{
|
||||
etag.clear();
|
||||
revision = 0;
|
||||
return {};
|
||||
}
|
||||
for (int attempt = 0; attempt < 3; ++attempt)
|
||||
{
|
||||
const auto before = revisionTag();
|
||||
const auto media = driveRequest(L"GET", "/drive/v3/files/" + file + "?alt=media",
|
||||
access, {}, {}, GoogleDriveBackupLimit);
|
||||
etag = revisionTag();
|
||||
if (before != etag) continue;
|
||||
const auto profile = Json::parse(media.body, [](int depth, Json::parse_event_t, Json &)
|
||||
{
|
||||
if (depth > 32) throw std::runtime_error("Invalid Google Drive synchronization profile.");
|
||||
return true;
|
||||
});
|
||||
if (profile.value("format", "") != "kswitcher-drive-sync-v1" ||
|
||||
!profile.at("revision").is_number_unsigned())
|
||||
throw std::runtime_error("Unsupported Google Drive synchronization profile.");
|
||||
revision = profile.at("revision").get<uint64_t>();
|
||||
if (!revision || revision == UINT64_MAX) throw std::runtime_error("Invalid Google Drive sync revision.");
|
||||
const auto settings = profile.at("settings").dump();
|
||||
return {revision, Bytes(settings.begin(), settings.end())};
|
||||
}
|
||||
throw std::runtime_error("The Google Drive profile changed during download. Sync again.");
|
||||
}
|
||||
|
||||
uint64_t write(const Bytes &settings, uint64_t expectedRevision) override
|
||||
{
|
||||
if (revision != expectedRevision) throw std::runtime_error("The Google Drive profile changed. Sync again.");
|
||||
const auto body = Json{{"format", "kswitcher-drive-sync-v1"}, {"revision", revision + 1},
|
||||
{"settings", Json::parse(settings)}}.dump();
|
||||
if (body.size() > GoogleDriveBackupLimit) throw std::runtime_error("Settings exceed the 2 MiB Drive limit.");
|
||||
if (!revision)
|
||||
{
|
||||
if (!findProfile().empty()) throw std::runtime_error("Google Drive already has a sync profile. Sync again.");
|
||||
createDriveFile(access, name, body);
|
||||
findProfile();
|
||||
}
|
||||
else
|
||||
{
|
||||
driveRequest(L"PUT", "/upload/drive/v2/files/" + file + "?uploadType=media&fields=id", access,
|
||||
L"application/json", body, 64 * 1024, L"If-Match: " + etag + L"\r\n");
|
||||
}
|
||||
return ++revision;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
bool googleDriveConfigured()
|
||||
{
|
||||
return !ClientId.empty() && !ClientSecret.empty();
|
||||
}
|
||||
|
||||
bool googleDriveConnected()
|
||||
{
|
||||
if (!googleDriveConfigured()) return false;
|
||||
auto token = refreshToken();
|
||||
ClearString clear{token};
|
||||
return !token.empty();
|
||||
}
|
||||
|
||||
std::string googleDriveCredentialKey()
|
||||
{
|
||||
auto token = refreshToken();
|
||||
ClearString clear{token};
|
||||
return token.empty() ? std::string{} : google_drive_oauth::challengeFor(token);
|
||||
}
|
||||
|
||||
std::unique_ptr<SyncProvider> makeGoogleDriveSyncProvider()
|
||||
{
|
||||
return std::make_unique<GoogleDriveSync>(accessToken(), SyncName);
|
||||
}
|
||||
|
||||
void connectGoogleDrive(std::stop_token stop)
|
||||
{
|
||||
requireConfiguration();
|
||||
checkCanceled(stop);
|
||||
Winsock winsock;
|
||||
Socket listener{socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)};
|
||||
sockaddr_in address{};
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
int length = sizeof(address);
|
||||
const BOOL exclusive = TRUE;
|
||||
if (listener.handle == INVALID_SOCKET ||
|
||||
setsockopt(listener.handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<const char *>(&exclusive), sizeof(exclusive)) ||
|
||||
bind(listener.handle, reinterpret_cast<const sockaddr *>(&address), length) ||
|
||||
listen(listener.handle, SOMAXCONN) ||
|
||||
getsockname(listener.handle, reinterpret_cast<sockaddr *>(&address), &length))
|
||||
throw std::runtime_error("Could not open a local sign-in callback.");
|
||||
const auto redirect = "http://127.0.0.1:" + std::to_string(ntohs(address.sin_port)) + "/oauth/callback";
|
||||
const auto state = randomParameter();
|
||||
const auto verifier = randomParameter();
|
||||
const auto url = wide("https://accounts.google.com/o/oauth2/v2/auth?" + form({
|
||||
{"client_id", ClientId}, {"redirect_uri", redirect}, {"response_type", "code"}, {"scope", Scope},
|
||||
{"access_type", "offline"}, {"prompt", "consent select_account"}, {"state", state},
|
||||
{"code_challenge", google_drive_oauth::challengeFor(verifier)}, {"code_challenge_method", "S256"}}));
|
||||
const auto initialized = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
|
||||
const auto opened = ShellExecuteW(nullptr, L"open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
|
||||
if (SUCCEEDED(initialized)) CoUninitialize();
|
||||
if (reinterpret_cast<INT_PTR>(opened) <= 32)
|
||||
throw std::runtime_error("Could not open the system browser.");
|
||||
auto code = waitForCode(listener.handle, state, stop);
|
||||
ClearString clearCode{code};
|
||||
checkCanceled(stop);
|
||||
auto tokens = requestTokens(form({{"grant_type", "authorization_code"}, {"code", code},
|
||||
{"redirect_uri", redirect}, {"code_verifier", verifier}}));
|
||||
ClearString clearAccess{tokens.access}, clearRefresh{tokens.refresh};
|
||||
checkCanceled(stop);
|
||||
saveRefreshToken(tokens.refresh);
|
||||
}
|
||||
|
||||
void disconnectGoogleDrive()
|
||||
{
|
||||
requireConfiguration();
|
||||
if (!CredDeleteW(credentialName().c_str(), CRED_TYPE_GENERIC, 0) && GetLastError() != ERROR_NOT_FOUND)
|
||||
throw std::runtime_error("Could not remove the Google Drive connection from Windows Credential Manager.");
|
||||
}
|
||||
|
||||
GoogleDriveBackupPage listGoogleDriveBackups(std::string_view page)
|
||||
{
|
||||
auto access = accessToken();
|
||||
ClearString clear{access};
|
||||
const auto filter = std::string("name = '") + PreviewName + "' or name = '" + NativeName + "'";
|
||||
std::string token(page);
|
||||
// An empty page with a continuation token can occur before the end.
|
||||
for (int attempt = 0; attempt < 20; ++attempt)
|
||||
{
|
||||
const auto data = driveFilePage(access, filter, 50, token,
|
||||
"nextPageToken,incompleteSearch,files(id,createdTime,name,size)");
|
||||
GoogleDriveBackupPage result;
|
||||
try
|
||||
{
|
||||
result.nextPage = data.value("nextPageToken", "");
|
||||
for (const auto &file : data.at("files"))
|
||||
{
|
||||
auto info = driveFile(file);
|
||||
const auto name = file.at("name").get<std::string>();
|
||||
if (name != NativeName && name != PreviewName) continue;
|
||||
std::optional<uint64_t> size;
|
||||
if (file.contains("size"))
|
||||
{
|
||||
const auto value = file.at("size").get<std::string>();
|
||||
uint64_t parsed{};
|
||||
const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), parsed);
|
||||
if (error == std::errc{} && end == value.data() + value.size()) size = parsed;
|
||||
}
|
||||
result.backups.push_back({std::move(info.id), std::move(info.created), size, name == PreviewName});
|
||||
}
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
throw std::runtime_error("Google Drive returned an unreadable backup list.");
|
||||
}
|
||||
if (!result.backups.empty() || result.nextPage.empty()) return result;
|
||||
token = std::move(result.nextPage);
|
||||
}
|
||||
throw std::runtime_error("Google Drive did not finish listing backups. Try again.");
|
||||
}
|
||||
|
||||
GoogleDriveBackupInfo uploadGoogleDriveBackup(const Bytes &settings)
|
||||
{
|
||||
auto access = accessToken();
|
||||
ClearString clear{access};
|
||||
auto file = createDriveFile(access, NativeName, {settings.begin(), settings.end()});
|
||||
return {std::move(file.id), std::move(file.created), settings.size(), false};
|
||||
}
|
||||
|
||||
Bytes fetchGoogleDriveBackup(std::string_view id)
|
||||
{
|
||||
if (id.empty()) throw std::runtime_error("Select a Google Drive backup to restore.");
|
||||
auto access = accessToken();
|
||||
ClearString clear{access};
|
||||
auto response = driveRequest(L"GET", "/drive/v3/files/" + urlEncode(id) + "?alt=media",
|
||||
access, {}, {}, GoogleDriveBackupLimit);
|
||||
return std::move(response.body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
#include "storage.h"
|
||||
#include <memory>
|
||||
#include <stop_token>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
class SyncProvider;
|
||||
inline constexpr size_t GoogleDriveBackupLimit = 2 * 1024 * 1024;
|
||||
|
||||
Bytes encodeDriveBackup(const Settings &saved);
|
||||
Settings restoreDriveBackup(const Bytes &, const Settings &draft, const std::vector<Layout> &);
|
||||
Bytes sharedDriveSettings(const Settings &);
|
||||
Settings restoreSharedDriveSettings(const Bytes &, const Settings &, const std::vector<Layout> &);
|
||||
std::string googleDriveCredentialKey();
|
||||
std::unique_ptr<SyncProvider> makeGoogleDriveSyncProvider();
|
||||
|
||||
bool googleDriveConfigured();
|
||||
bool googleDriveConnected();
|
||||
void connectGoogleDrive(std::stop_token);
|
||||
void disconnectGoogleDrive();
|
||||
struct GoogleDriveBackupInfo
|
||||
{
|
||||
std::string id;
|
||||
std::wstring created;
|
||||
std::optional<uint64_t> size;
|
||||
bool preview{};
|
||||
};
|
||||
struct GoogleDriveBackupPage
|
||||
{
|
||||
std::vector<GoogleDriveBackupInfo> backups;
|
||||
std::string nextPage;
|
||||
};
|
||||
GoogleDriveBackupPage listGoogleDriveBackups(std::string_view page = {});
|
||||
GoogleDriveBackupInfo uploadGoogleDriveBackup(const Bytes &);
|
||||
Bytes fetchGoogleDriveBackup(std::string_view id);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::google_drive_oauth
|
||||
{
|
||||
std::string challengeFor(const std::string &verifier);
|
||||
// nullopt ignores unrelated requests. An empty code is a rejected authorization.
|
||||
std::optional<std::string> callbackCode(std::string_view request, std::string_view state);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
#include <winhttp.h>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
struct HttpHandle
|
||||
{
|
||||
explicit HttpHandle(HINTERNET handle) : h(handle) {}
|
||||
HttpHandle(const HttpHandle &) = delete;
|
||||
HttpHandle &operator=(const HttpHandle &) = delete;
|
||||
~HttpHandle() { if (h) WinHttpCloseHandle(h); }
|
||||
HINTERNET h;
|
||||
};
|
||||
}
|
||||
+303
-39
@@ -9,6 +9,7 @@
|
||||
#include "lan_layout.h"
|
||||
#include "lan_network.h"
|
||||
#include "lan_wake.h"
|
||||
#include "lan_clients.h"
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
@@ -110,7 +111,14 @@ void lan::wakeFilesPeer(const std::string &id)
|
||||
|
||||
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;
|
||||
@@ -127,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};
|
||||
@@ -139,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))
|
||||
{
|
||||
@@ -165,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)
|
||||
@@ -183,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();
|
||||
@@ -212,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()
|
||||
@@ -219,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)
|
||||
@@ -241,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)
|
||||
{
|
||||
@@ -267,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;
|
||||
@@ -278,19 +429,23 @@ 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;
|
||||
const auto &key=trusted[other].at("key");
|
||||
const auto challenge=heartbeat(id,other,epoch,session);
|
||||
@@ -352,7 +507,7 @@ struct LanService::Impl
|
||||
auto previous=trusted;auto previousPositions=positions;
|
||||
trusted[other]={{"name",peer.name},{"key",pending->derived}};
|
||||
try {lan::fillPositions(positions,trusted,inputPeer,inputEdge);save();} catch(...) {trusted=std::move(previous);positions=std::move(previousPositions);throw;}
|
||||
layoutChanged=true;peer.verified=now; status="Pair saved automatically. Arrange the monitors, then enable input sharing on both PCs.";
|
||||
layoutChanged=true;peer.verified=now; status="Pair saved. Arrange the monitors, then enable input sharing and click Apply or Save on both PCs.";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -408,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;
|
||||
}
|
||||
@@ -431,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){
|
||||
@@ -447,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)
|
||||
@@ -461,25 +629,117 @@ 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();
|
||||
}
|
||||
void removePeerState(const std::string &peer)
|
||||
{
|
||||
std::erase_if(incomingFiles, [&](const auto &file) { return file.peer == peer; });
|
||||
if (logDownload && logDownload->peer == peer) logDownload.reset();
|
||||
if (pending && pending->peer == peer) pending.reset();
|
||||
}
|
||||
void applySettings(const Json &draft)
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
const auto before = std::tuple{enabled, shareInput, shareLogs, inputEdge, trusted, positions};
|
||||
const bool discovery = draft.value("enabled", enabled);
|
||||
const auto forgotten = draft.value("forget", Json::object());
|
||||
auto nextTrusted = trusted;
|
||||
for (const auto &[peer, ignored] : forgotten.items()) nextTrusted.erase(peer);
|
||||
const bool nextInput = !nextTrusted.empty() && draft.value("shareInput", shareInput);
|
||||
if (draft.value("shareInput", false) && (!discovery || nextTrusted.empty()))
|
||||
throw std::runtime_error("Enable discovery and select a paired KSwitcher first.");
|
||||
auto nextPositions = positions;
|
||||
const auto moved = draft.value("positions", Json::object());
|
||||
for (const auto &[peer, cell] : moved.items())
|
||||
{
|
||||
if (!nextTrusted.contains(peer)) throw std::runtime_error("Pair this computer before arranging it.");
|
||||
nextPositions[peer] = cell;
|
||||
}
|
||||
lan::fillPositions(nextPositions, nextTrusted, inputPeer, inputEdge);
|
||||
int edge = moved.contains(inputPeer) ? lan::cellEdge(nextPositions.at(inputPeer)) : -1;
|
||||
|
||||
std::unique_ptr<lan::Pairing> nextPair;
|
||||
if (draft.contains("pair"))
|
||||
{
|
||||
const auto &pair = draft.at("pair");
|
||||
auto peer = pair.at("peer").get<std::string>();
|
||||
if (!enabled || !discovery || !peers.contains(peer) || !peers.at(peer).present(GetTickCount64()))
|
||||
throw std::runtime_error("Select an available KSwitcher computer first.");
|
||||
if (!nextTrusted.contains(peer) && nextTrusted.size() >= 64)
|
||||
throw std::runtime_error("Remove an old pair before adding another computer.");
|
||||
nextPair = std::make_unique<lan::Pairing>(id, peer, pair.at("code").get<std::string>(), GetTickCount64());
|
||||
}
|
||||
const bool discoveryChanged = discovery != enabled;
|
||||
const bool routerChanged = discoveryChanged || nextInput != shareInput ||
|
||||
nextPositions != positions || nextTrusted != trusted;
|
||||
const bool nextLogs = draft.value("shareLogs", shareLogs);
|
||||
const bool saveLan = routerChanged || nextLogs != shareLogs;
|
||||
const bool hadFile = saveLan && std::filesystem::exists(path);
|
||||
enabled = discovery;
|
||||
shareInput = nextInput;
|
||||
shareLogs = nextLogs;
|
||||
if (edge >= 0) inputEdge = edge;
|
||||
positions = std::move(nextPositions);
|
||||
trusted = std::move(nextTrusted);
|
||||
auto current = std::tie(enabled, shareInput, shareLogs, inputEdge, trusted, positions);
|
||||
bool written = false;
|
||||
try
|
||||
{
|
||||
if (saveLan) { save(); written = true; }
|
||||
if (draft.contains("clients")) clients.apply(draft.at("clients"));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
current = before;
|
||||
if (written)
|
||||
{
|
||||
if (hadFile) save();
|
||||
else std::filesystem::remove(path);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
for (const auto &[peer, ignored] : forgotten.items()) removePeerState(peer);
|
||||
if (std::get<2>(before) && !shareLogs)
|
||||
for (const auto &[peer, entry] : trusted.items()) transfers->cancel(peer, "log-reply-");
|
||||
if (nextPair)
|
||||
{
|
||||
pending = std::move(nextPair);
|
||||
status = "Waiting for the same code on the other KSwitcher (2 minutes)...";
|
||||
}
|
||||
if (routerChanged) configureRouter();
|
||||
lock.unlock();
|
||||
if (discoveryChanged && discovery) start();
|
||||
if (discoveryChanged && !discovery)
|
||||
{
|
||||
stop();
|
||||
status = "Disabled. No discovery sockets or worker thread.";
|
||||
}
|
||||
}
|
||||
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 == "inspectClient" || action == "trustClient" || action == "removeClient")
|
||||
return encoded(clients.settings(action, j));
|
||||
if (action == "applySettings")
|
||||
{
|
||||
applySettings(j.at("draft"));
|
||||
return encoded(Json::object());
|
||||
}
|
||||
if(action=="enable")
|
||||
{
|
||||
stop();
|
||||
@@ -503,8 +763,7 @@ struct LanService::Impl
|
||||
{
|
||||
auto peer=j.at("peer").get<std::string>();
|
||||
const auto checkPeer = [&] {
|
||||
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
|
||||
now-peers.at(peer).verified>=lan::PeerLifetime)
|
||||
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.");
|
||||
@@ -574,7 +833,6 @@ struct LanService::Impl
|
||||
found=findFile();
|
||||
}
|
||||
if(found!=incomingFiles.end()) incomingFiles.erase(found);
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
|
||||
}
|
||||
if(action=="position")
|
||||
{
|
||||
@@ -620,16 +878,13 @@ struct LanService::Impl
|
||||
auto peer=j.at("peer").get<std::string>();auto oldTrusted=trusted;auto oldPositions=positions;bool oldSharing=shareInput;
|
||||
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();
|
||||
removePeerState(peer);
|
||||
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();
|
||||
@@ -649,7 +904,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))
|
||||
@@ -657,9 +912,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);
|
||||
@@ -681,7 +937,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,278 @@
|
||||
#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(); }
|
||||
private:
|
||||
static void editClient(Json &entries, const std::string &action, const Json &request)
|
||||
{
|
||||
const auto path = wide(request.at("path").get<std::string>());
|
||||
if (action == "trustClient")
|
||||
{
|
||||
ClientImage image(path);
|
||||
if (request.contains("sha256") &&
|
||||
(request.at("sha256") != image.digest || _wcsicmp(image.path.c_str(), path.c_str())))
|
||||
throw std::runtime_error("The executable changed. Add it again before saving.");
|
||||
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());
|
||||
});
|
||||
}
|
||||
}
|
||||
void save(const Json &entries) const
|
||||
{
|
||||
const auto text = entries.dump();
|
||||
atomicWrite(store, protect(Bytes(text.begin(), text.end())));
|
||||
}
|
||||
public:
|
||||
Json settings(const std::string &action, const Json &request) const
|
||||
{
|
||||
std::lock_guard lock(storeMutex);
|
||||
if (action == "inspectClient")
|
||||
{
|
||||
ClientImage image(wide(request.at("path").get<std::string>()));
|
||||
return {{"path", utf8(image.path)}, {"sha256", image.digest}};
|
||||
}
|
||||
auto entries = clients();
|
||||
if (action == "trustedClients") return entries;
|
||||
editClient(entries, action, request);
|
||||
save(entries);
|
||||
return entries;
|
||||
}
|
||||
void apply(const Json &changes) const
|
||||
{
|
||||
std::lock_guard lock(storeMutex);
|
||||
auto entries = clients();
|
||||
for (const auto &change : changes)
|
||||
if (change.at("action") == "removeClient") editClient(entries, "removeClient", change);
|
||||
for (const auto &change : changes)
|
||||
if (change.at("action") == "trustClient") editClient(entries, "trustClient", change);
|
||||
save(entries);
|
||||
}
|
||||
};
|
||||
}
|
||||
+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);
|
||||
|
||||
+1
-1
@@ -361,7 +361,7 @@ std::filesystem::path tesseractExecutable(const Settings &s)
|
||||
for (auto relative : {L"Tesseract-OCR/tesseract.exe", L"Programs/Tesseract-OCR/tesseract.exe"})
|
||||
if (std::filesystem::is_regular_file(root / relative)) return root / relative;
|
||||
}
|
||||
throw std::runtime_error("Tesseract was not found. Install the optional 64-bit Tesseract 5 package or select tesseract.exe in OCR options.");
|
||||
throw std::runtime_error("Tesseract was not found. Install the optional 64-bit Tesseract 5 package or select tesseract.exe in Clipboard > Image text recognition.");
|
||||
}
|
||||
std::wstring ocrProfile(const Settings &s)
|
||||
{
|
||||
|
||||
+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 {};
|
||||
|
||||
+68
-20
@@ -12,6 +12,7 @@
|
||||
#include <set>
|
||||
#include <shellapi.h>
|
||||
#include <shlobj.h>
|
||||
#include <propkey.h>
|
||||
#include <exdisp.h>
|
||||
#include <shldisp.h>
|
||||
#include <tlhelp32.h>
|
||||
@@ -166,6 +167,35 @@ void showRequestedWindow(HWND window)
|
||||
if (!IsWindowVisible(window))
|
||||
ShowWindow(window, SW_SHOW);
|
||||
}
|
||||
void setWindowResourceIcons(HWND window, HINSTANCE instance, int iconResource)
|
||||
{
|
||||
const auto dpi = GetDpiForWindow(window);
|
||||
for (int kind : {ICON_SMALL, ICON_BIG})
|
||||
{
|
||||
const bool small = kind == ICON_SMALL;
|
||||
const auto icon = LoadImageW(instance, MAKEINTRESOURCEW(iconResource), IMAGE_ICON,
|
||||
GetSystemMetricsForDpi(small ? SM_CXSMICON : SM_CXICON, dpi),
|
||||
GetSystemMetricsForDpi(small ? SM_CYSMICON : SM_CYICON, dpi), LR_SHARED);
|
||||
if (icon) SendMessageW(window, WM_SETICON, kind, reinterpret_cast<LPARAM>(icon));
|
||||
}
|
||||
}
|
||||
void setWindowTaskbarIdentity(HWND window, int iconResource, const wchar_t *identity)
|
||||
{
|
||||
auto icon = identity ? executable() + L",-" + std::to_wstring(iconResource) : std::wstring{};
|
||||
auto group = identity ? std::wstring(identity) : std::wstring{};
|
||||
Microsoft::WRL::ComPtr<IPropertyStore> properties;
|
||||
if (FAILED(SHGetPropertyStoreForWindow(window, IID_PPV_ARGS(&properties)))) return;
|
||||
PROPVARIANT value{};
|
||||
if (identity)
|
||||
{
|
||||
value.vt = VT_LPWSTR;
|
||||
value.pwszVal = icon.data();
|
||||
}
|
||||
properties->SetValue(PKEY_AppUserModel_RelaunchIconResource, value);
|
||||
if (identity) value.pwszVal = group.data();
|
||||
// Set the group ID last so Explorer refreshes the taskbar button.
|
||||
properties->SetValue(PKEY_AppUserModel_ID, value);
|
||||
}
|
||||
void showMenuAccessKeys(HMENU menu)
|
||||
{
|
||||
// Mouse-opened popups ignore the owner's keyboard-cue state.
|
||||
@@ -349,14 +379,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 +426,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 +526,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)
|
||||
{
|
||||
|
||||
+6
-1
@@ -43,6 +43,8 @@ bool switchWindowLayout(HWND, HKL, const std::function<bool()> &valid);
|
||||
bool activateWindow(HWND);
|
||||
void showRequestedWindow(HWND);
|
||||
void showMenuAccessKeys(HMENU);
|
||||
void setWindowResourceIcons(HWND window, HINSTANCE instance, int iconResource);
|
||||
void setWindowTaskbarIdentity(HWND window, int iconResource, const wchar_t *identity);
|
||||
bool ownsClipboard(HWND);
|
||||
bool webViewDescendant(DWORD owner, DWORD host,
|
||||
const std::function<std::optional<std::pair<DWORD, std::wstring>>(DWORD)> &read);
|
||||
@@ -50,12 +52,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{};
|
||||
|
||||
+152
-71
@@ -1,6 +1,7 @@
|
||||
#include "screenshot.h"
|
||||
#include "stroke_improvement.h"
|
||||
#include "ocr.h"
|
||||
#include "ui_palette.h"
|
||||
#include "../resources/resource.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@@ -55,6 +56,9 @@ bool confirmScreenshotClose(HWND owner)
|
||||
return SUCCEEDED(result) && button==IDYES;
|
||||
}
|
||||
constexpr int ToolIds[]{27,10,11,22,23,24,25,36,37,38,21,19,26,20,12,18,13};
|
||||
constexpr int EditorStatus = 50, EditorZoom = 51;
|
||||
constexpr int EditorOptionsTop = 44, EditorPanelHeight = 118, EditorFooterHeight = 30;
|
||||
constexpr int EditorToolDividers[]{50, 357, 464, 502};
|
||||
struct Surface
|
||||
{
|
||||
HDC dc = CreateCompatibleDC(nullptr);
|
||||
@@ -209,7 +213,8 @@ struct Capture
|
||||
int zoomWheelDelta=0;
|
||||
std::vector<Mark> marks;
|
||||
ScreenshotHistory history;
|
||||
HWND editor{}, inlineText{};
|
||||
HWND editor{}, inlineText{}, tooltips{};
|
||||
WindowPalette palette;
|
||||
HFONT inlineFont{};
|
||||
Mark textDraft{};
|
||||
int textIndex=-1;
|
||||
@@ -222,7 +227,7 @@ struct Capture
|
||||
std::vector<Mark> beforeDrag;
|
||||
HFONT font{};
|
||||
HICON toolIcons[3][15]{};
|
||||
int iconSize{};
|
||||
int iconSize{}, fontDpi{};
|
||||
HCURSOR pencilCursor{};
|
||||
HCURSOR drawingCursors[std::size(CursorTools)]{};
|
||||
int pencilCursorSize{};
|
||||
@@ -268,10 +273,22 @@ struct Capture
|
||||
EnableWindow(GetDlgItem(editor,18),history.canRedo());
|
||||
}
|
||||
};
|
||||
void setEditorStatus(Capture &c, std::wstring text)
|
||||
{
|
||||
if (text == c.statusText) return;
|
||||
c.statusText = std::move(text);
|
||||
const auto status = GetDlgItem(c.editor, EditorStatus);
|
||||
SetWindowTextW(status, c.statusText.c_str());
|
||||
if (c.tooltips && status)
|
||||
{
|
||||
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND, c.editor, reinterpret_cast<UINT_PTR>(status)};
|
||||
tool.lpszText = c.statusText.data();
|
||||
SendMessageW(c.tooltips, TTM_UPDATETIPTEXTW, 0, reinterpret_cast<LPARAM>(&tool));
|
||||
}
|
||||
}
|
||||
void updateStatus(Capture &c)
|
||||
{
|
||||
auto status=GetDlgItem(c.editor,50);
|
||||
if(!status) return;
|
||||
if (!GetDlgItem(c.editor, EditorStatus)) return;
|
||||
std::wstring text;
|
||||
auto part=c.dragging?c.part:c.hoveredPart;
|
||||
if(c.hoveredTool && !c.dragging) {
|
||||
@@ -301,13 +318,11 @@ void updateStatus(Capture &c)
|
||||
else if(c.shape==ScreenshotShape::Arc) text=L"Arc (U): drag to draw a half ellipse | Handles = resize / rotate | V = pointer";
|
||||
else if(c.arrow) text=L"Drag to draw | Ctrl+drag over objects = linked connector | V = pointer";
|
||||
else text=L"Number (N): click to add | V = select and edit | Ctrl+C = copy screenshot";
|
||||
text=L"Zoom: "+std::to_wstring(int(std::lround(100.0*(c.view.right-c.view.left)/c.image->width)))+
|
||||
L"% (Ctrl +/- / wheel; Ctrl+0: fit; middle drag: pan) | "+text;
|
||||
if(text!=c.statusText) {
|
||||
c.statusText=std::move(text);
|
||||
SendMessageW(status,SB_SETTEXTW,0,(LPARAM)c.statusText.c_str());
|
||||
SendMessageW(status,SB_SETTIPTEXTW,0,(LPARAM)c.statusText.c_str());
|
||||
}
|
||||
const auto zoom = L"Zoom " + std::to_wstring(MulDiv(c.view.right - c.view.left, 100, c.image->width)) + L"%";
|
||||
wchar_t current[32]{};
|
||||
GetDlgItemTextW(c.editor, EditorZoom, current, std::size(current));
|
||||
if (zoom != current) SetDlgItemTextW(c.editor, EditorZoom, zoom.c_str());
|
||||
setEditorStatus(c, std::move(text));
|
||||
}
|
||||
RECT region(POINT a, POINT b)
|
||||
{
|
||||
@@ -781,39 +796,48 @@ void layout(HWND w, Capture &c)
|
||||
c.toolIcons[variant][i]=(HICON)LoadImageW(c.app.instance,MAKEINTRESOURCEW(i<9?300+variant*10+i:400+variant*10+i-9),IMAGE_ICON,iconSize,iconSize,0);
|
||||
}
|
||||
}
|
||||
if (c.font) DeleteObject(c.font);
|
||||
c.font = CreateFontW(-MulDiv(14,dpi,96),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,
|
||||
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI");
|
||||
c.unit = std::max(1, MulDiv(44, dpi, 96));
|
||||
auto status=GetDlgItem(w,50);
|
||||
SendMessageW(status,WM_SETFONT,(WPARAM)c.font,TRUE);
|
||||
SendMessageW(status,WM_SIZE,0,0);
|
||||
RECT statusRect{}; GetWindowRect(status,&statusRect);
|
||||
c.statusHeight=statusRect.bottom-statusRect.top;
|
||||
r.bottom-=c.statusHeight;
|
||||
const int positions[]{8,44,80,116,152,188,224,260,296,332,368,404,440,476,524,560,608};
|
||||
static_assert(std::size(positions)==std::size(ToolIds));
|
||||
for (size_t i = 0; i < std::size(ToolIds); ++i)
|
||||
HFONT previousFont{};
|
||||
const bool fontChanged = dpi != c.fontDpi || !c.font;
|
||||
if (fontChanged)
|
||||
{
|
||||
SendMessageW(GetDlgItem(w,ToolIds[i]),WM_SETFONT,(WPARAM)c.font,TRUE);
|
||||
MoveWindow(GetDlgItem(w,ToolIds[i]),MulDiv(positions[i],dpi,96),MulDiv(6,dpi,96),
|
||||
MulDiv(32,dpi,96),MulDiv(32,dpi,96),TRUE);
|
||||
c.fontDpi = dpi;
|
||||
previousFont = c.font;
|
||||
c.font = CreateFontW(-MulDiv(14,dpi,96),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,
|
||||
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI");
|
||||
}
|
||||
SendDlgItemMessageW(w,28,WM_SETFONT,(WPARAM)c.font,TRUE);
|
||||
MoveWindow(GetDlgItem(w,28),MulDiv(648,dpi,96),MulDiv(6,dpi,96),
|
||||
MulDiv(78,dpi,96),MulDiv(32,dpi,96),TRUE);
|
||||
c.panelHeight=c.unit+MulDiv(80,dpi,96);
|
||||
for(int id:{30,31,32,33,34,35,41,42,43,44}) SendDlgItemMessageW(w,id,WM_SETFONT,(WPARAM)c.font,TRUE);
|
||||
MoveWindow(GetDlgItem(w,42),MulDiv(12,dpi,96),c.unit+MulDiv(44,dpi,96),MulDiv(128,dpi,96),MulDiv(24,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,41),MulDiv(142,dpi,96),c.unit+MulDiv(40,dpi,96),MulDiv(200,dpi,96),MulDiv(30,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,43),MulDiv(350,dpi,96),c.unit+MulDiv(44,dpi,96),MulDiv(150,dpi,96),MulDiv(24,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,44),MulDiv(516,dpi,96),c.unit+MulDiv(40,dpi,96),MulDiv(210,dpi,96),MulDiv(30,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,32),MulDiv(12,dpi,96),c.unit+MulDiv(6,dpi,96),MulDiv(64,dpi,96),MulDiv(24,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,30),MulDiv(80,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(150,dpi,96),MulDiv(180,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,33),MulDiv(248,dpi,96),c.unit+MulDiv(6,dpi,96),MulDiv(40,dpi,96),MulDiv(24,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,31),MulDiv(294,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(170,dpi,96),MulDiv(180,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,34),MulDiv(480,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(28,dpi,96),MulDiv(28,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,35),MulDiv(516,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(28,dpi,96),MulDiv(28,dpi,96),TRUE);
|
||||
const auto dip = [dpi](int n) { return MulDiv(n, dpi, 96); };
|
||||
if (fontChanged) SendMessageW(c.tooltips, TTM_SETMAXTIPWIDTH, 0, dip(530));
|
||||
const auto place = [&](int id, int x, int y, int width, int height)
|
||||
{
|
||||
const auto child = GetDlgItem(w, id);
|
||||
if (fontChanged || reinterpret_cast<HFONT>(SendMessageW(child, WM_GETFONT, 0, 0)) != c.font)
|
||||
SendMessageW(child, WM_SETFONT, reinterpret_cast<WPARAM>(c.font), TRUE);
|
||||
MoveWindow(child, x, y, width, height, TRUE);
|
||||
};
|
||||
c.unit = std::max(1, dip(44));
|
||||
c.statusHeight = dip(EditorFooterHeight);
|
||||
r.bottom -= c.statusHeight;
|
||||
place(EditorZoom, dip(16), r.bottom + 1, dip(89), c.statusHeight - 1);
|
||||
place(EditorStatus, dip(120), r.bottom + 1, std::max(0, static_cast<int>(r.right) - dip(136)), c.statusHeight - 1);
|
||||
const int positions[]{14,52,86,120,154,188,222,256,290,324,362,396,430,468,506,540};
|
||||
static_assert(std::size(positions) + 1 == std::size(ToolIds));
|
||||
for (size_t i = 0; i < std::size(positions); ++i)
|
||||
place(ToolIds[i], dip(positions[i]), dip(6), dip(32), dip(32));
|
||||
const int copyLeft = std::max(dip(580), static_cast<int>(r.right) - dip(168));
|
||||
place(13, copyLeft, dip(6), dip(66), dip(32));
|
||||
place(28, copyLeft + dip(76), dip(6), dip(76), dip(32));
|
||||
c.panelHeight = dip(EditorPanelHeight);
|
||||
place(32, dip(16), dip(53), dip(62), dip(26));
|
||||
place(30, dip(80), dip(51), dip(150), dip(180));
|
||||
place(33, dip(246), dip(53), dip(40), dip(26));
|
||||
place(31, dip(288), dip(51), dip(170), dip(180));
|
||||
place(34, dip(470), dip(50), dip(28), dip(28));
|
||||
place(35, dip(506), dip(50), dip(28), dip(28));
|
||||
place(42, dip(16), dip(84), dip(122), dip(26));
|
||||
place(41, dip(140), dip(82), dip(198), dip(30));
|
||||
place(43, dip(350), dip(84), dip(154), dip(26));
|
||||
place(44, dip(514), dip(82), dip(208), dip(29));
|
||||
if (previousFont) DeleteObject(previousFont);
|
||||
syncLineOptions(w,c);
|
||||
c.canvas={0,c.panelHeight,r.right,std::max(LONG(c.panelHeight+1),r.bottom)};
|
||||
double ratio = c.zoom*std::min({1.0, double(std::max(1L,r.right-16))/c.image->width,
|
||||
@@ -1015,8 +1039,11 @@ void drawTool(const DRAWITEMSTRUCT &item, const Capture &c)
|
||||
POINT mouse; GetCursorPos(&mouse); ScreenToClient(item.hwndItem,&mouse);
|
||||
bool hover=PtInRect(&r,mouse) && !disabled;
|
||||
bool pressed=item.itemState&ODS_SELECTED;
|
||||
FillRect(dc,&r,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
|
||||
COLORREF fill=pressed?RGB(219,234,254):active?RGB(239,246,255):hover?RGB(241,245,249):RGB(255,255,255);
|
||||
const bool option = item.CtlID == 34 || item.CtlID == 35;
|
||||
FillRect(dc, &r, option ? c.palette.brush() : GetSysColorBrush(COLOR_WINDOW));
|
||||
const COLORREF fill = c.palette.highContrast ? GetSysColor(active || pressed ? COLOR_HIGHLIGHT : COLOR_WINDOW) :
|
||||
pressed ? RGB(219,234,254) : active ? RGB(232,242,254) : hover ? RGB(241,245,249) :
|
||||
option ? c.palette.color() : GetSysColor(COLOR_WINDOW);
|
||||
auto brush=CreateSolidBrush(fill);
|
||||
auto pen=CreatePen(PS_SOLID,1,fill);
|
||||
auto oldPen=SelectObject(dc,pen),oldBrush=SelectObject(dc,brush);
|
||||
@@ -1028,14 +1055,36 @@ void drawTool(const DRAWITEMSTRUCT &item, const Capture &c)
|
||||
if(item.CtlID==36 || item.CtlID==37 || item.CtlID==38) {
|
||||
int cx=(r.left+r.right)/2,cy=(r.top+r.bottom)/2,s=c.iconSize/2;
|
||||
auto trianglePen=CreatePen(PS_SOLID,std::max(1,MulDiv(2,GetDpiForWindow(item.hwndItem),96)),
|
||||
disabled?RGB(148,163,184):active?RGB(37,99,235):RGB(51,65,85));
|
||||
c.palette.highContrast ? GetSysColor(disabled ? COLOR_GRAYTEXT :
|
||||
active || pressed ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT) :
|
||||
disabled ? RGB(148,163,184) : active ? RGB(37,99,235) : RGB(51,65,85));
|
||||
auto previous=SelectObject(dc,trianglePen);
|
||||
if(item.CtlID==38) Arc(dc,cx-s,cy-s,cx+s,cy+3*s,cx+s,cy+s,cx-s,cy+s);
|
||||
else if(item.CtlID==36) { POINT vertices[]{{cx,cy-s},{cx+s,cy+s},{cx-s,cy+s},{cx,cy-s}}; Polyline(dc,vertices,4); }
|
||||
else { POINT vertices[]{{cx-s/2,cy-s},{cx+s/2,cy-s},{cx+s,cy+s},{cx-s,cy+s},{cx-s/2,cy-s}}; Polyline(dc,vertices,5); }
|
||||
SelectObject(dc,previous); DeleteObject(trianglePen);
|
||||
}
|
||||
if(icon) DrawIconEx(dc,(r.right-c.iconSize)/2,(r.bottom-c.iconSize)/2,icon,c.iconSize,c.iconSize,0,nullptr,DI_NORMAL);
|
||||
const auto foreground = GetSysColor(disabled ? COLOR_GRAYTEXT : c.palette.highContrast && (active || pressed) ?
|
||||
COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
|
||||
const auto dpi = GetDpiForWindow(item.hwndItem);
|
||||
const int iconX = item.CtlID == 13 ? MulDiv(7, dpi, 96) : (r.right - c.iconSize) / 2;
|
||||
const int iconY = (r.bottom - c.iconSize) / 2;
|
||||
if (icon && c.palette.highContrast && item.CtlID != 27)
|
||||
{
|
||||
const auto brush = CreateSolidBrush(foreground);
|
||||
DrawStateW(dc, brush, nullptr, reinterpret_cast<LPARAM>(icon), 0, iconX, iconY, c.iconSize, c.iconSize, DST_ICON | DSS_MONO);
|
||||
DeleteObject(brush);
|
||||
}
|
||||
else if (icon) DrawIconEx(dc, iconX, iconY, icon, c.iconSize, c.iconSize, 0, nullptr, DI_NORMAL);
|
||||
if (item.CtlID == 13)
|
||||
{
|
||||
const SavedDc saved(dc);
|
||||
SelectObject(dc, c.font);
|
||||
SetBkMode(dc, TRANSPARENT);
|
||||
SetTextColor(dc, foreground);
|
||||
RECT label{MulDiv(30, dpi, 96), r.top, r.right, r.bottom};
|
||||
DrawTextW(dc, L"Copy", -1, &label, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX);
|
||||
}
|
||||
if(item.CtlID==20) {
|
||||
auto color=c.selected>=0?c.marks[c.selected].color:c.currentColor;
|
||||
auto swatch=CreateSolidBrush(color);
|
||||
@@ -1096,6 +1145,7 @@ void save(HWND w, Capture &c, bool saveAs=false,
|
||||
{
|
||||
if(!saveAs && !c.savedPath.empty()) {
|
||||
saveToFile(w,c,c.savedPath);
|
||||
setEditorStatus(c, L"Saved: " + c.savedPath.wstring());
|
||||
return;
|
||||
}
|
||||
wchar_t filename[32768]{};
|
||||
@@ -1125,8 +1175,7 @@ void save(HWND w, Capture &c, bool saveAs=false,
|
||||
if(lower(std::filesystem::path(filename).extension().wstring())!=L".png")
|
||||
throw std::runtime_error("Choose a filename ending in .png for the screenshot");
|
||||
saveToFile(w,c,filename);
|
||||
c.statusText=L"Saved: "+c.savedPath.wstring();
|
||||
SendDlgItemMessageW(w,50,SB_SETTEXTW,0,(LPARAM)c.statusText.c_str());
|
||||
setEditorStatus(c, L"Saved: " + c.savedPath.wstring());
|
||||
}
|
||||
void edit(HWND w, Capture &c)
|
||||
{
|
||||
@@ -1151,10 +1200,14 @@ void edit(HWND w, Capture &c)
|
||||
SetWindowLongPtrW(w,GWL_STYLE,WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN);
|
||||
auto title=L"KSwitcher — Screenshot #"+std::to_wstring(nextEditorIndex++);
|
||||
SetWindowTextW(w,localBuildTitle(title).c_str());
|
||||
INITCOMMONCONTROLSEX statusControls{sizeof(statusControls),ICC_BAR_CLASSES};
|
||||
InitCommonControlsEx(&statusControls);
|
||||
CreateWindowExW(0,STATUSCLASSNAMEW,L"",WS_CHILD|WS_VISIBLE|SBARS_TOOLTIPS,
|
||||
0,0,0,0,w,(HMENU)50,c.app.instance,nullptr);
|
||||
setWindowResourceIcons(w, c.app.instance, IDI_KSWITCHER_SCREENSHOT);
|
||||
setWindowTaskbarIdentity(w, IDI_KSWITCHER_SCREENSHOT, L"HrynCo.KSwitcher.ScreenshotEditor");
|
||||
c.palette.refresh();
|
||||
for (int id : {EditorStatus, EditorZoom})
|
||||
CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | SS_CENTERIMAGE | SS_ENDELLIPSIS | SS_NOTIFY,
|
||||
0, 0, 0, 0, w, reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)), c.app.instance, nullptr);
|
||||
INITCOMMONCONTROLSEX bars{sizeof(bars), ICC_BAR_CLASSES};
|
||||
InitCommonControlsEx(&bars);
|
||||
const wchar_t *labels[]{L"Pointer (V): select and edit objects", L"Number (N)", L"Arrow (A); Ctrl+drag between objects to link", L"Straight line (L); Ctrl+drag between objects to link", L"Rectangle (R)", L"Circle (O)", L"Ellipse (E)", L"Triangle (G): drag to draw; drag each vertex to reshape", L"Trapezoid (B): drag to draw", L"Arc (U): drag to draw a half ellipse; use handles to resize or rotate", L"Freehand line (F); Shift for 45-degree steps; move >50 px off line to turn; Ctrl to draw over objects", L"Highlight (H); Ctrl+drag to paint over an object",
|
||||
L"Text (T); double-click or F2 to edit", L"Color — selected object and new objects", L"Undo (Ctrl+Z)", L"Redo (Ctrl+Y / Ctrl+Shift+Z)", L"Copy (Ctrl+C)"};
|
||||
static_assert(std::size(labels)==std::size(ToolIds));
|
||||
@@ -1163,11 +1216,19 @@ void edit(HWND w, Capture &c)
|
||||
SetWindowSubclass(saveButton,toolHover,1,0);
|
||||
auto tips=CreateWindowExW(WS_EX_TOPMOST,TOOLTIPS_CLASSW,nullptr,WS_POPUP|TTS_ALWAYSTIP|TTS_NOPREFIX,
|
||||
CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,w,nullptr,c.app.instance,nullptr);
|
||||
c.tooltips = tips;
|
||||
for (int id : {EditorStatus, EditorZoom})
|
||||
{
|
||||
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, w,
|
||||
reinterpret_cast<UINT_PTR>(GetDlgItem(w, id))};
|
||||
tool.lpszText = const_cast<wchar_t *>(id == EditorZoom ?
|
||||
L"Ctrl+wheel or Ctrl+plus/minus to zoom. Ctrl+0 to fit. Middle-drag to pan." : L"");
|
||||
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
|
||||
}
|
||||
for (size_t i=0;i<std::size(ToolIds);++i)
|
||||
{
|
||||
auto button = CreateWindowW(L"BUTTON",labels[i],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,
|
||||
0,0,0,0,w,(HMENU)(INT_PTR)ToolIds[i],c.app.instance,nullptr);
|
||||
SendMessageW(button, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE);
|
||||
SetWindowSubclass(button,toolHover,1,0);
|
||||
TOOLINFOW tool{sizeof(tool)};
|
||||
tool.uFlags=TTF_IDISHWND|TTF_SUBCLASS; tool.hwnd=w; tool.uId=(UINT_PTR)button;
|
||||
@@ -1175,8 +1236,8 @@ void edit(HWND w, Capture &c)
|
||||
SendMessageW(tips,TTM_ADDTOOLW,0,(LPARAM)&tool);
|
||||
}
|
||||
SendMessageW(GetDlgItem(w,21),BM_SETCHECK,BST_CHECKED,0);
|
||||
CreateWindowW(L"STATIC",L"Line style",WS_CHILD|WS_VISIBLE,0,0,0,0,w,(HMENU)32,c.app.instance,nullptr);
|
||||
CreateWindowW(L"STATIC",L"Ends",WS_CHILD|WS_VISIBLE,0,0,0,0,w,(HMENU)33,c.app.instance,nullptr);
|
||||
CreateWindowW(L"STATIC",L"Line style",WS_CHILD|WS_VISIBLE|SS_CENTERIMAGE,0,0,0,0,w,(HMENU)32,c.app.instance,nullptr);
|
||||
CreateWindowW(L"STATIC",L"Ends",WS_CHILD|WS_VISIBLE|SS_CENTERIMAGE,0,0,0,0,w,(HMENU)33,c.app.instance,nullptr);
|
||||
for(int id:{30,31}) CreateWindowW(L"COMBOBOX",L"",WS_CHILD|WS_VISIBLE|CBS_DROPDOWNLIST|WS_VSCROLL,
|
||||
0,0,0,0,w,(HMENU)(INT_PTR)id,c.app.instance,nullptr);
|
||||
for(auto text:{L"Solid",L"Dotted",L"Dashed",L"Dash-dot"}) SendDlgItemMessageW(w,30,CB_ADDSTRING,0,(LPARAM)text);
|
||||
@@ -1191,12 +1252,11 @@ void edit(HWND w, Capture &c)
|
||||
SetWindowSubclass(labelButton,toolHover,1,0);
|
||||
fontTip.uId=(UINT_PTR)labelButton; fontTip.lpszText=const_cast<wchar_t *>(L"Arrow label (F2 / double-click); drag label to reposition");
|
||||
SendMessageW(tips,TTM_ADDTOOLW,0,(LPARAM)&fontTip);
|
||||
INITCOMMONCONTROLSEX sliders{sizeof(sliders),ICC_BAR_CLASSES}; InitCommonControlsEx(&sliders);
|
||||
CreateWindowW(TRACKBAR_CLASSW,L"Pencil smoothing",WS_CHILD|WS_VISIBLE|WS_TABSTOP|TBS_NOTICKS,
|
||||
0,0,0,0,w,(HMENU)41,c.app.instance,nullptr);
|
||||
SendDlgItemMessageW(w,41,TBM_SETRANGE,TRUE,MAKELPARAM(0,100));
|
||||
SendDlgItemMessageW(w,41,TBM_SETPAGESIZE,0,10);
|
||||
for(int id:{42,43}) CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE,0,0,0,0,w,(HMENU)(INT_PTR)id,c.app.instance,nullptr);
|
||||
for(int id:{42,43}) CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE|SS_CENTERIMAGE,0,0,0,0,w,(HMENU)(INT_PTR)id,c.app.instance,nullptr);
|
||||
CreateWindowW(L"BUTTON",L"Apply to all strokes",WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_PUSHBUTTON,
|
||||
0,0,0,0,w,(HMENU)44,c.app.instance,nullptr);
|
||||
c.syncHistory();
|
||||
@@ -1261,8 +1321,20 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if((wp>=10 && wp<=13) || (wp>=18 && wp<=27) || wp==34 || wp==35 || wp==36 || wp==37 || wp==38) { drawTool(*reinterpret_cast<DRAWITEMSTRUCT *>(lp),*c); return TRUE; }
|
||||
break;
|
||||
case WM_CTLCOLORSTATIC:
|
||||
SetBkColor((HDC)wp,RGB(255,255,255)); SetTextColor((HDC)wp,RGB(51,65,85));
|
||||
return (LRESULT)GetStockObject(WHITE_BRUSH);
|
||||
{
|
||||
const auto dc = reinterpret_cast<HDC>(wp);
|
||||
const int id = GetDlgCtrlID(reinterpret_cast<HWND>(lp));
|
||||
SetBkColor(dc, c->palette.color());
|
||||
SetTextColor(dc, id == EditorZoom ? GetSysColor(COLOR_WINDOWTEXT) : c->palette.secondaryText());
|
||||
return reinterpret_cast<LRESULT>(c->palette.brush());
|
||||
}
|
||||
case WM_SYSCOLORCHANGE: case WM_SETTINGCHANGE: case WM_DWMCOLORIZATIONCOLORCHANGED:
|
||||
if (c->editing)
|
||||
{
|
||||
c->palette.refresh(msg == WM_DWMCOLORIZATIONCOLORCHANGED ? std::optional<DWORD>(wp) : std::nullopt);
|
||||
RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN);
|
||||
}
|
||||
break;
|
||||
case WM_ERASEBKGND: return 1;
|
||||
case WM_SETCURSOR:
|
||||
if ((HWND)wp==w && LOWORD(lp)==HTCLIENT) { captureCursor(w,*c); return TRUE; }
|
||||
@@ -1802,6 +1874,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
auto r=reinterpret_cast<RECT *>(lp);
|
||||
SetWindowPos(w,nullptr,r->left,r->top,r->right-r->left,r->bottom-r->top,SWP_NOZORDER);
|
||||
setWindowResourceIcons(w, c->app.instance, IDI_KSWITCHER_SCREENSHOT);
|
||||
layout(w,*c); positionInlineText(*c);
|
||||
}
|
||||
return 0;
|
||||
@@ -1840,18 +1913,22 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
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)));
|
||||
auto divider=CreatePen(PS_SOLID,1,RGB(226,232,240));
|
||||
auto previous=SelectObject(buffer,divider);
|
||||
MoveToEx(buffer,0,c->panelHeight-1,nullptr); LineTo(buffer,client.right,c->panelHeight-1);
|
||||
int dpi=GetDpiForWindow(w);
|
||||
for(int x:{440,524}) {
|
||||
MoveToEx(buffer,MulDiv(x,dpi,96),MulDiv(13,dpi,96),nullptr);
|
||||
LineTo(buffer,MulDiv(x,dpi,96),MulDiv(31,dpi,96));
|
||||
}
|
||||
SelectObject(buffer,previous); DeleteObject(divider);
|
||||
const auto dpi = GetDpiForWindow(w);
|
||||
const auto dip = [dpi](int n) { return MulDiv(n, dpi, 96); };
|
||||
const RECT toolbar{0, 0, client.right, dip(EditorOptionsTop)};
|
||||
const RECT options{0, toolbar.bottom, client.right, c->panelHeight};
|
||||
const RECT footer{0, c->canvas.bottom, client.right, client.bottom};
|
||||
FillRect(buffer, &toolbar, GetSysColorBrush(COLOR_WINDOW));
|
||||
FillRect(buffer, &options, c->palette.brush());
|
||||
FillRect(buffer, &footer, c->palette.brush());
|
||||
fillSurface(buffer, c->canvas, c->palette.highContrast ? GetSysColor(COLOR_APPWORKSPACE) : RGB(224, 232, 239));
|
||||
const auto edge = c->palette.edge();
|
||||
fillSurface(buffer, {0, options.top, client.right, options.top + 1}, edge);
|
||||
fillSurface(buffer, {0, options.bottom - 1, client.right, options.bottom}, edge);
|
||||
fillSurface(buffer, {0, footer.top, client.right, footer.top + 1}, edge);
|
||||
fillSurface(buffer, {dip(108), footer.top + dip(7), dip(108) + 1, footer.bottom - dip(7)}, edge);
|
||||
for (int x : EditorToolDividers)
|
||||
fillSurface(buffer, {dip(x), dip(13), dip(x) + 1, dip(31)}, edge);
|
||||
const auto preview=shapePreview(*c);
|
||||
const auto *previewMark=c->dragging && c->part==MarkPart::None?
|
||||
((c->highlight || c->freehand)?&c->stroke:&preview):nullptr;
|
||||
@@ -1898,6 +1975,10 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
const SavedDc savedCanvas(buffer);
|
||||
IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom);
|
||||
auto frame = c->view;
|
||||
InflateRect(&frame, 1, 1);
|
||||
SetDCBrushColor(buffer, c->palette.highContrast ? GetSysColor(COLOR_WINDOWTEXT) : RGB(155, 174, 191));
|
||||
FrameRect(buffer, &frame, reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
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);
|
||||
|
||||
@@ -50,13 +50,12 @@ 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);
|
||||
}
|
||||
if(argc==5 && std::wstring_view(argv[1])==L"--history-image-worker") {
|
||||
HANDLE handles[3]{};
|
||||
for(int i=0;i<3;++i)
|
||||
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);
|
||||
@@ -64,6 +63,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
||||
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]);
|
||||
|
||||
+165
-142
@@ -703,26 +703,99 @@ struct ImageWorkerHandle
|
||||
if(value) CloseHandle(std::exchange(value,nullptr));
|
||||
}
|
||||
};
|
||||
template <typename Control>
|
||||
struct ImageWorkerView
|
||||
{
|
||||
ImageWorkerControl *control{};
|
||||
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;
|
||||
ImageWorkerHandle mapping, requestReady, responseReady, process;
|
||||
ImageWorkerView view;
|
||||
|
||||
~HistoryImageWorker() { stop(); }
|
||||
void stop();
|
||||
void start();
|
||||
ImageWorkerChannel<ImageWorkerControl> channel;
|
||||
int perform(const std::filesystem::path &, const std::function<bool()> &);
|
||||
};
|
||||
struct ClipboardSnapshotControl
|
||||
{
|
||||
DWORD sequence;
|
||||
char captureError[256];
|
||||
};
|
||||
}
|
||||
|
||||
struct HistoryImageWorkers
|
||||
@@ -778,84 +851,91 @@ void History::reload()
|
||||
std::lock_guard lock(mutex_);
|
||||
loadIndex();
|
||||
}
|
||||
void ClipboardSnapshot::cleanup() noexcept
|
||||
struct ClipboardSnapshot::Helper
|
||||
{
|
||||
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();
|
||||
}
|
||||
ClipboardSnapshot::~ClipboardSnapshot() { cleanup(); }
|
||||
DWORD ClipboardSnapshot::run(bool restore, DWORD sequence)
|
||||
ImageWorkerChannel<ClipboardSnapshotControl> channel;
|
||||
};
|
||||
ClipboardSnapshot::ClipboardSnapshot() = default;
|
||||
ClipboardSnapshot::~ClipboardSnapshot() = default;
|
||||
DWORD ClipboardSnapshot::capture(HWND window, DWORD sequence)
|
||||
{
|
||||
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;
|
||||
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)
|
||||
@@ -917,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)
|
||||
@@ -1163,61 +1241,6 @@ void History::clear()
|
||||
}
|
||||
namespace
|
||||
{
|
||||
void HistoryImageWorker::stop()
|
||||
{
|
||||
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 HistoryImageWorker::start()
|
||||
{
|
||||
SECURITY_ATTRIBUTES security{sizeof(security),nullptr,TRUE};
|
||||
mapping.value=CreateFileMappingW(INVALID_HANDLE_VALUE,&security,PAGE_READWRITE,0,sizeof(ImageWorkerControl),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 history OCR worker channel");
|
||||
view.control=static_cast<ImageWorkerControl *>(MapViewOfFile(mapping.value,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)));
|
||||
if(!view.control) throw std::runtime_error("Cannot map history OCR worker channel");
|
||||
|
||||
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 history OCR worker startup");
|
||||
struct Attributes
|
||||
{
|
||||
LPPROC_THREAD_ATTRIBUTE_LIST value;
|
||||
~Attributes() { DeleteProcThreadAttributeList(value); }
|
||||
} cleanup{attributes};
|
||||
HANDLE inherited[]{mapping.value,requestReady.value,responseReady.value};
|
||||
if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr))
|
||||
throw std::runtime_error("Cannot configure history OCR worker startup");
|
||||
|
||||
const auto helper=std::filesystem::path(executable()).parent_path()/L"KSwitcher.Screenshot.exe";
|
||||
auto command=L"\""+helper.wstring()+L"\" --history-image-worker";
|
||||
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 history OCR helper")));
|
||||
process.value=child.hProcess;
|
||||
CloseHandle(child.hThread);
|
||||
for(const auto handle:inherited) SetHandleInformation(handle,HANDLE_FLAG_INHERIT,0);
|
||||
}
|
||||
|
||||
int HistoryImageWorker::perform(const std::filesystem::path &request,const std::function<bool()> &cancelled)
|
||||
{
|
||||
std::unique_lock lock(mutex,std::defer_lock);
|
||||
@@ -1234,42 +1257,42 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
|
||||
{
|
||||
for(int attempt=0;attempt<2;++attempt)
|
||||
{
|
||||
if(!process.value || WaitForSingleObject(process.value,0)!=WAIT_TIMEOUT)
|
||||
if(!channel.process.value || WaitForSingleObject(channel.process.value,0)!=WAIT_TIMEOUT)
|
||||
{
|
||||
stop();
|
||||
start();
|
||||
channel.stop();
|
||||
channel.open();
|
||||
channel.start(L"--history-image-worker");
|
||||
}
|
||||
checkCancelled();
|
||||
std::copy(path.begin(),path.end(),view.control->request);
|
||||
view.control->request[path.size()]=L'\0';
|
||||
if(!SetEvent(requestReady.value)) throw std::runtime_error("Cannot request history OCR");
|
||||
HANDLE signals[]{responseReady.value,process.value};
|
||||
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=WaitForMultipleObjects(2,signals,FALSE,100);
|
||||
const auto wait=channel.waitForResponse(100);
|
||||
if(wait==WAIT_OBJECT_0)
|
||||
{
|
||||
checkCancelled();
|
||||
return view.control->result;
|
||||
return channel.view.control->result;
|
||||
}
|
||||
if(wait==WAIT_OBJECT_0+1)
|
||||
{
|
||||
DWORD code{};
|
||||
if(GetExitCodeProcess(process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
|
||||
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");
|
||||
}
|
||||
stop();
|
||||
channel.stop();
|
||||
}
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
// The child must stop writing before the request and response files are cleaned up.
|
||||
stop();
|
||||
channel.stop();
|
||||
throw;
|
||||
}
|
||||
throw std::runtime_error("History OCR helper did not accept the request");
|
||||
@@ -1278,7 +1301,7 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
|
||||
|
||||
int runHistoryImageWorker(HANDLE mapping,HANDLE requestReady,HANDLE responseReady)
|
||||
{
|
||||
ImageWorkerView view{static_cast<ImageWorkerControl *>(
|
||||
ImageWorkerView<ImageWorkerControl> view{static_cast<ImageWorkerControl *>(
|
||||
MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)))};
|
||||
if(!view.control) return 1;
|
||||
for(;;)
|
||||
|
||||
+6
-7
@@ -58,20 +58,19 @@ bool sameClipboardImage(const Clip &, const Clip &);
|
||||
int runImageHistoryCapture(const std::filesystem::path &request);
|
||||
int runHistoryOcr(const std::filesystem::path &request);
|
||||
int runHistoryImageWorker(HANDLE mapping, HANDLE requestReady, HANDLE responseReady);
|
||||
// Image backups stay encrypted on disk and are read/written only by a short-lived helper.
|
||||
// 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
|
||||
+109
-18
@@ -1,7 +1,8 @@
|
||||
#include "sync.h"
|
||||
#include "google_drive.h"
|
||||
#include "http_handle.h"
|
||||
#include "mouse_buttons.h"
|
||||
#include "json.hpp"
|
||||
#include <winhttp.h>
|
||||
#include <wincred.h>
|
||||
#include <set>
|
||||
#include <algorithm>
|
||||
@@ -16,9 +17,11 @@ Bytes bytes(const Json &j) { auto s = j.dump(); return {s.begin(), s.end()}; }
|
||||
Json parse(const Bytes &b) { return Json::parse(b.begin(), b.end()); }
|
||||
Json configJson(const SyncConfig &c)
|
||||
{
|
||||
return {{"enabled", c.enabled}, {"provider", utf8(c.provider)}, {"server", utf8(c.server)},
|
||||
Json result{{"enabled", c.enabled}, {"provider", utf8(c.provider)}, {"server", utf8(c.server)},
|
||||
{"mount", utf8(c.mount)}, {"path", utf8(c.path)}, {"authMount", utf8(c.authMount)},
|
||||
{"username", utf8(c.username)}, {"keepLocalLayouts", c.keepLocalLayouts}};
|
||||
if (c.driveEnabled) result["driveEnabled"] = true;
|
||||
return result;
|
||||
}
|
||||
std::wstring credentialName(const SyncConfig &c)
|
||||
{
|
||||
@@ -30,11 +33,6 @@ bool safePath(const std::wstring &s)
|
||||
s.find(L"//") != s.npos) return false;
|
||||
return s.find_first_not_of(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-/") == s.npos;
|
||||
}
|
||||
struct HttpHandle
|
||||
{
|
||||
HINTERNET h{};
|
||||
~HttpHandle() { if (h) WinHttpCloseHandle(h); }
|
||||
};
|
||||
class OpenBao final : public SyncProvider
|
||||
{
|
||||
SyncConfig config;
|
||||
@@ -156,12 +154,20 @@ class OpenBao final : public SyncProvider
|
||||
};
|
||||
}
|
||||
bool syncVisible(const std::filesystem::path &root) { return std::filesystem::exists(root / L"sync.json"); }
|
||||
bool automaticSyncEnabled(const SyncConfig &c) { return c.enabled || c.driveEnabled; }
|
||||
std::wstring_view automaticSyncProviderName(const SyncConfig &c) { return c.driveEnabled ? L"Google Drive" : L"OpenBao"; }
|
||||
SyncConfig loadSyncConfig(const std::filesystem::path &root)
|
||||
{
|
||||
return syncVisible(root) ? decodeSyncConfig(readFile(root / L"sync.json", 16384)) : SyncConfig{};
|
||||
}
|
||||
Bytes encodeSyncConfig(const SyncConfig &config) { return bytes(configJson(config)); }
|
||||
SyncConfig decodeSyncConfig(const Bytes &encoded)
|
||||
{
|
||||
SyncConfig c;
|
||||
if (!syncVisible(root)) return c;
|
||||
auto j = parse(readFile(root / L"sync.json", 16384));
|
||||
auto j = parse(encoded);
|
||||
c.enabled = j.value("enabled", false);
|
||||
c.driveEnabled = j.value("driveEnabled", false);
|
||||
if (c.enabled && c.driveEnabled) throw std::runtime_error("Choose only one automatic synchronization provider.");
|
||||
c.keepLocalLayouts = j.value("keepLocalLayouts", false);
|
||||
c.provider = wide(j.value("provider", "openbao"));
|
||||
c.server = wide(j.value("server", ""));
|
||||
@@ -171,7 +177,7 @@ SyncConfig loadSyncConfig(const std::filesystem::path &root)
|
||||
c.username = wide(j.value("username", ""));
|
||||
return c;
|
||||
}
|
||||
void validateSyncConfig(const SyncConfig &c)
|
||||
static void validateOpenBaoConfig(const SyncConfig &c)
|
||||
{
|
||||
if (c.provider != L"openbao") throw std::runtime_error("Unsupported sync provider.");
|
||||
URL_COMPONENTS url{sizeof(url)};
|
||||
@@ -188,14 +194,23 @@ void validateSyncConfig(const SyncConfig &c)
|
||||
if (credentialName(c).size() > CRED_MAX_GENERIC_TARGET_NAME_LENGTH)
|
||||
throw std::runtime_error("Sync connection name is too long.");
|
||||
}
|
||||
void validateSyncConfig(const SyncConfig &c)
|
||||
{
|
||||
if (c.enabled && c.driveEnabled) throw std::runtime_error("Choose only one automatic synchronization provider.");
|
||||
if (c.driveEnabled)
|
||||
{
|
||||
if (!googleDriveConnected()) throw std::runtime_error("Connect Google Drive before enabling automatic synchronization.");
|
||||
}
|
||||
else validateOpenBaoConfig(c);
|
||||
}
|
||||
void saveSyncConfig(const std::filesystem::path &root, const SyncConfig &c)
|
||||
{
|
||||
if (c.enabled) validateSyncConfig(c);
|
||||
if (automaticSyncEnabled(c)) validateSyncConfig(c);
|
||||
atomicWrite(root / L"sync.json", bytes(configJson(c)));
|
||||
}
|
||||
void saveSyncPassword(const SyncConfig &c, const std::wstring &password)
|
||||
{
|
||||
validateSyncConfig(c);
|
||||
validateOpenBaoConfig(c);
|
||||
auto secret = utf8(password);
|
||||
if (secret.empty() || secret.size() > CRED_MAX_CREDENTIAL_BLOB_SIZE) throw std::runtime_error("Password is empty or too long.");
|
||||
auto target = credentialName(c);
|
||||
@@ -212,8 +227,73 @@ void forgetSyncPassword(const SyncConfig &c)
|
||||
if (!CredDeleteW(credentialName(c).c_str(), CRED_TYPE_GENERIC, 0) && GetLastError() != ERROR_NOT_FOUND)
|
||||
throw std::runtime_error("Cannot remove saved sync password.");
|
||||
}
|
||||
void applySyncConnection(const std::filesystem::path &root, const SyncConfig &config,
|
||||
const Bytes &protectedPassword, bool forgetPassword, const std::function<void()> &commit)
|
||||
{
|
||||
const auto path = root / L"sync.json";
|
||||
const auto previousFile = syncVisible(root) ? std::optional{readFile(path, 16384)} : std::nullopt;
|
||||
const auto credentialConfig = forgetPassword && previousFile ? decodeSyncConfig(*previousFile) : config;
|
||||
const bool editCredential = forgetPassword || !protectedPassword.empty();
|
||||
PCREDENTIALW previousCredential{};
|
||||
struct Cleanup
|
||||
{
|
||||
PCREDENTIALW &credential;
|
||||
~Cleanup()
|
||||
{
|
||||
if (!credential) return;
|
||||
SecureZeroMemory(credential->CredentialBlob, credential->CredentialBlobSize);
|
||||
CredFree(credential);
|
||||
}
|
||||
} cleanup{previousCredential};
|
||||
if (editCredential &&
|
||||
!CredReadW(credentialName(credentialConfig).c_str(), CRED_TYPE_GENERIC, 0, &previousCredential) &&
|
||||
GetLastError() != ERROR_NOT_FOUND)
|
||||
throw std::runtime_error("Cannot read the saved Windows credential.");
|
||||
|
||||
saveSyncConfig(root, config);
|
||||
bool credentialChanged = false;
|
||||
try
|
||||
{
|
||||
if (forgetPassword) forgetSyncPassword(credentialConfig);
|
||||
else if (!protectedPassword.empty())
|
||||
{
|
||||
auto secret = unprotect(protectedPassword);
|
||||
std::wstring password;
|
||||
try
|
||||
{
|
||||
if (secret.size() % sizeof(wchar_t)) throw std::runtime_error("Invalid Windows credential.");
|
||||
password.resize(secret.size() / sizeof(wchar_t));
|
||||
memcpy(password.data(), secret.data(), secret.size());
|
||||
saveSyncPassword(config, password);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t));
|
||||
SecureZeroMemory(secret.data(), secret.size());
|
||||
throw;
|
||||
}
|
||||
SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t));
|
||||
SecureZeroMemory(secret.data(), secret.size());
|
||||
}
|
||||
credentialChanged = editCredential;
|
||||
commit();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
if (previousFile) atomicWrite(path, *previousFile);
|
||||
else std::filesystem::remove(path);
|
||||
if (credentialChanged)
|
||||
{
|
||||
if (!previousCredential) forgetSyncPassword(credentialConfig);
|
||||
else if (!CredWriteW(previousCredential, 0))
|
||||
throw std::runtime_error("Cannot restore the previous Windows credential.");
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
std::unique_ptr<SyncProvider> makeSyncProvider(const SyncConfig &c, SyncTransport transport)
|
||||
{
|
||||
if (c.driveEnabled) return makeGoogleDriveSyncProvider();
|
||||
return std::make_unique<OpenBao>(c, std::move(transport));
|
||||
}
|
||||
namespace {
|
||||
@@ -366,17 +446,28 @@ std::wstring syncValueText(const Bytes &data)
|
||||
if (tombstone(j)) return L"(deleted)";
|
||||
return wide(j.is_string() ? j.get<std::string>() : j.dump(2));
|
||||
}
|
||||
Bytes loadSyncBase(const std::filesystem::path &root, const SyncConfig &c)
|
||||
namespace
|
||||
{
|
||||
auto path = root / L"sync-base.bin";
|
||||
std::filesystem::path syncBasePath(const std::filesystem::path &root, const SyncConfig &c)
|
||||
{
|
||||
return root / (c.driveEnabled ? L"sync-google-drive-base.bin" : L"sync-base.bin");
|
||||
}
|
||||
Json syncBaseConnection(const SyncConfig &c, std::string_view driveKey)
|
||||
{
|
||||
return c.driveEnabled ? Json{{"provider", "google-drive"}, {"credential", driveKey}} : configJson(c);
|
||||
}
|
||||
}
|
||||
Bytes loadSyncBase(const std::filesystem::path &root, const SyncConfig &c, std::string_view driveKey)
|
||||
{
|
||||
auto path = syncBasePath(root, c);
|
||||
if (!std::filesystem::exists(path)) return {};
|
||||
auto j = parse(unprotect(readFile(path, Limit + 65536)));
|
||||
auto connection = j.at("connection");
|
||||
if (!connection.contains("keepLocalLayouts")) connection["keepLocalLayouts"] = false;
|
||||
return connection == configJson(c) ? bytes(j.at("settings")) : Bytes{};
|
||||
if (!c.driveEnabled && !connection.contains("keepLocalLayouts")) connection["keepLocalLayouts"] = false;
|
||||
return connection == syncBaseConnection(c, driveKey) ? bytes(j.at("settings")) : Bytes{};
|
||||
}
|
||||
void saveSyncBase(const std::filesystem::path &root, const SyncConfig &c, const Bytes &base)
|
||||
void saveSyncBase(const std::filesystem::path &root, const SyncConfig &c, const Bytes &base, std::string_view driveKey)
|
||||
{
|
||||
atomicWrite(root / L"sync-base.bin", protect(bytes({{"connection", configJson(c)}, {"settings", parse(base)}})));
|
||||
atomicWrite(syncBasePath(root, c), protect(bytes({{"connection", syncBaseConnection(c, driveKey)}, {"settings", parse(base)}})));
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -7,14 +7,21 @@ namespace ks
|
||||
struct SyncConfig
|
||||
{
|
||||
bool enabled{};
|
||||
bool driveEnabled{};
|
||||
bool keepLocalLayouts{};
|
||||
std::wstring provider = L"openbao", server, mount = L"kswitcher",
|
||||
path = L"personal/settings", authMount = L"userpass", username;
|
||||
bool operator==(const SyncConfig &) const = default;
|
||||
};
|
||||
bool automaticSyncEnabled(const SyncConfig &);
|
||||
std::wstring_view automaticSyncProviderName(const SyncConfig &);
|
||||
bool syncVisible(const std::filesystem::path &);
|
||||
SyncConfig loadSyncConfig(const std::filesystem::path &);
|
||||
void saveSyncConfig(const std::filesystem::path &, const SyncConfig &);
|
||||
Bytes encodeSyncConfig(const SyncConfig &);
|
||||
SyncConfig decodeSyncConfig(const Bytes &);
|
||||
void applySyncConnection(const std::filesystem::path &, const SyncConfig &, const Bytes &protectedPassword,
|
||||
bool forgetPassword, const std::function<void()> &commit);
|
||||
void validateSyncConfig(const SyncConfig &);
|
||||
void saveSyncPassword(const SyncConfig &, const std::wstring &);
|
||||
void forgetSyncPassword(const SyncConfig &);
|
||||
@@ -68,6 +75,6 @@ struct SyncResult
|
||||
SyncResult synchronize(SyncProvider &, const Bytes &base, const Bytes &local, SyncAction,
|
||||
const std::function<void(const Bytes &)> &validate = {}, const std::vector<SyncChoice> &choices = {},
|
||||
bool keepLocalLayouts = false);
|
||||
Bytes loadSyncBase(const std::filesystem::path &, const SyncConfig &);
|
||||
void saveSyncBase(const std::filesystem::path &, const SyncConfig &, const Bytes &);
|
||||
Bytes loadSyncBase(const std::filesystem::path &, const SyncConfig &, std::string_view driveKey = {});
|
||||
void saveSyncBase(const std::filesystem::path &, const SyncConfig &, const Bytes &, std::string_view driveKey = {});
|
||||
}
|
||||
+2163
-634
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 || id == ClipboardAppPicker;
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
constexpr int DriveConnect = 620, DriveBackup = 621, DriveRestore = 622, DriveDisconnect = 623, DriveStatus = 624;
|
||||
constexpr int DriveSyncNow = 626, DriveSyncUpload = 627, DriveSyncDownload = 628, DriveSyncConflicts = 629,
|
||||
DriveSyncStatus = 630, DriveList = 631, DriveOlder = 632;
|
||||
constexpr int DriveSettingsWidth = 660, DriveSettingsHeight = 507;
|
||||
constexpr int DriveMargin = 16, DriveButtonWidth = 276, DriveButtonGap = 16;
|
||||
constexpr int DriveLeftButton = (DriveSettingsWidth - 2 * DriveButtonWidth - DriveButtonGap) / 2;
|
||||
constexpr int DriveRightButton = DriveLeftButton + DriveButtonWidth + DriveButtonGap;
|
||||
constexpr int DriveOlderTop = 208, DriveBackupActionsTop = 240;
|
||||
constexpr int DriveSyncTop = 310;
|
||||
enum class DriveAction { Status, Connect, Backup, Restore, Disconnect, Older };
|
||||
struct DriveResult
|
||||
{
|
||||
std::optional<bool> connected;
|
||||
std::optional<GoogleDriveBackupPage> page;
|
||||
std::optional<GoogleDriveBackupInfo> uploaded;
|
||||
std::wstring notice;
|
||||
std::optional<Bytes> backup;
|
||||
std::wstring restoreDate;
|
||||
};
|
||||
struct DriveTask
|
||||
{
|
||||
std::stop_source stop;
|
||||
std::atomic_bool signingIn{};
|
||||
std::mutex mutex;
|
||||
std::optional<DriveResult> result;
|
||||
};
|
||||
struct DriveView
|
||||
{
|
||||
SettingsView *settings;
|
||||
bool configured = googleDriveConfigured(), connected{};
|
||||
DriveAction action = DriveAction::Status;
|
||||
std::shared_ptr<DriveTask> task;
|
||||
std::vector<GoogleDriveBackupInfo> backups;
|
||||
std::string nextPage;
|
||||
std::wstring notice;
|
||||
};
|
||||
|
||||
std::wstring driveBackupTime(const std::wstring &value)
|
||||
{
|
||||
SYSTEMTIME utc{}, local{};
|
||||
const int fields = std::swscanf(value.c_str(), L"%hu-%hu-%huT%hu:%hu:%hu",
|
||||
&utc.wYear, &utc.wMonth, &utc.wDay, &utc.wHour, &utc.wMinute, &utc.wSecond);
|
||||
if (fields != 6 || !SystemTimeToTzSpecificLocalTimeEx(nullptr, &utc, &local)) return value;
|
||||
wchar_t date[128]{}, time[128]{};
|
||||
if (!GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, DATE_SHORTDATE, &local, nullptr, date, std::size(date), nullptr) ||
|
||||
!GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, 0, &local, nullptr, time, std::size(time))) return value;
|
||||
return std::wstring(date) + L" " + time;
|
||||
}
|
||||
|
||||
const GoogleDriveBackupInfo *selectedDriveBackup(HWND w, const DriveView &view)
|
||||
{
|
||||
const auto index = ListView_GetNextItem(GetDlgItem(w, DriveList), -1, LVNI_SELECTED);
|
||||
return index >= 0 && static_cast<size_t>(index) < view.backups.size() ? &view.backups[index] : nullptr;
|
||||
}
|
||||
|
||||
void fitDriveBackupColumns(HWND list)
|
||||
{
|
||||
if (!list) return;
|
||||
RECT client{};
|
||||
GetClientRect(list, &client);
|
||||
const int width = client.right;
|
||||
const int source = std::max(1, width * 34 / 100);
|
||||
const int size = std::min(scale(list, 105), std::max(1, width / 4));
|
||||
ListView_SetColumnWidth(list, 0, std::max(1, width - source - size));
|
||||
ListView_SetColumnWidth(list, 1, source);
|
||||
ListView_SetColumnWidth(list, 2, size);
|
||||
}
|
||||
|
||||
void fillDriveBackupList(HWND w, const DriveView &view, const std::string &selected)
|
||||
{
|
||||
const auto list = GetDlgItem(w, DriveList);
|
||||
SendMessageW(list, WM_SETREDRAW, FALSE, 0);
|
||||
ListView_DeleteAllItems(list);
|
||||
int selection = 0;
|
||||
for (const auto &backup : view.backups)
|
||||
{
|
||||
auto date = driveBackupTime(backup.created);
|
||||
LVITEMW row{LVIF_TEXT, ListView_GetItemCount(list)};
|
||||
row.pszText = date.data();
|
||||
const int index = ListView_InsertItem(list, &row);
|
||||
if (index < 0) break;
|
||||
if (backup.id == selected) selection = index;
|
||||
std::wstring source = backup.preview ? L"KSwitcher-New" : L"KSwitcher Win32";
|
||||
auto size = !backup.size ? L"—" : *backup.size < 1024 ? std::to_wstring(*backup.size) + L" B" :
|
||||
std::to_wstring(*backup.size / 1024 + (*backup.size % 1024 != 0)) + L" KiB";
|
||||
ListView_SetItemText(list, index, 1, source.data());
|
||||
ListView_SetItemText(list, index, 2, size.data());
|
||||
}
|
||||
if (ListView_GetItemCount(list))
|
||||
{
|
||||
ListView_SetItemState(list, selection, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
|
||||
ListView_EnsureVisible(list, selection, FALSE);
|
||||
}
|
||||
fitDriveBackupColumns(list);
|
||||
SendMessageW(list, WM_SETREDRAW, TRUE, 0);
|
||||
InvalidateRect(list, nullptr, TRUE);
|
||||
}
|
||||
|
||||
void updateDriveControls(HWND w, const DriveView &view)
|
||||
{
|
||||
const auto *editor = syncEditor(view.settings->sync);
|
||||
const bool active = editor && editor->initialized && editor->base.driveEnabled;
|
||||
const bool signingIn = view.task && view.task->signingIn;
|
||||
const bool busy = view.task != nullptr;
|
||||
const bool available = view.configured && !busy;
|
||||
EnableWindow(GetDlgItem(w, DriveConnect), (available && !active) || (signingIn && !view.task->stop.stop_requested()));
|
||||
EnableWindow(GetDlgItem(w, DriveBackup), available && view.connected);
|
||||
EnableWindow(GetDlgItem(w, DriveRestore), available && view.connected && selectedDriveBackup(w, view));
|
||||
EnableWindow(GetDlgItem(w, DriveOlder), available && view.connected && !view.nextPage.empty());
|
||||
EnableWindow(GetDlgItem(w, DriveDisconnect), available && view.connected && !active);
|
||||
value(w, DriveConnect, signingIn ? L"Cancel &sign-in" : view.connected ? L"&Reconnect" : L"&Connect");
|
||||
const bool checking = busy && view.action == DriveAction::Status && !view.connected;
|
||||
std::wstring status = checking ? view.notice :
|
||||
!view.configured ? L"Google Drive is unavailable in this build." :
|
||||
view.connected ? L"Google Drive is connected." : L"Google Drive is disconnected.";
|
||||
if (!checking && !view.notice.empty()) status += L"\r\n" + view.notice;
|
||||
if (value(w, DriveStatus) != status) value(w, DriveStatus, status);
|
||||
}
|
||||
|
||||
void updateDriveSyncControls(HWND w, const DriveView &view)
|
||||
{
|
||||
const auto *editor = syncEditor(view.settings->sync);
|
||||
if (!editor || !editor->initialized) return;
|
||||
const bool active = editor->base.driveEnabled;
|
||||
const bool changed = syncDraftChanged(view.settings->sync);
|
||||
EnableWindow(GetDlgItem(w, DriveAutomatic), active || (view.configured && view.connected && !view.task));
|
||||
for (int id : {DriveSyncNow, DriveSyncUpload, DriveSyncDownload, DriveSyncConflicts})
|
||||
EnableWindow(GetDlgItem(w, id), active && !changed && view.connected && !view.task);
|
||||
std::wstring status = changed ? L"Click Apply or Save to change automatic synchronization." :
|
||||
active ? view.settings->app->syncCommand() :
|
||||
editor->base.enabled ? L"Automatic synchronization is using OpenBao." : L"Automatic synchronization is off.";
|
||||
if (active) status += L"\r\nTurn off Google Drive sync before reconnecting or disconnecting.";
|
||||
if (value(w, DriveSyncStatus) != status) value(w, DriveSyncStatus, status);
|
||||
}
|
||||
|
||||
void startDriveTask(HWND w, DriveView &view, DriveAction action)
|
||||
{
|
||||
auto task = std::make_shared<DriveTask>();
|
||||
task->signingIn = action == DriveAction::Connect;
|
||||
const auto path = view.settings->app->data / L"settings.json";
|
||||
const auto layouts = view.settings->app->layouts;
|
||||
const auto *selection = selectedDriveBackup(w, view);
|
||||
const auto backup = action == DriveAction::Restore && selection ? *selection : GoogleDriveBackupInfo{};
|
||||
const auto page = action == DriveAction::Older ? view.nextPage : std::string{};
|
||||
if (!SetTimer(w, 1, 100, nullptr)) throw std::runtime_error("Could not start the Google Drive action.");
|
||||
try
|
||||
{
|
||||
std::thread([task, action, path, layouts, backup, page]
|
||||
{
|
||||
DriveResult result;
|
||||
try
|
||||
{
|
||||
switch (action)
|
||||
{
|
||||
case DriveAction::Status:
|
||||
case DriveAction::Connect:
|
||||
if (action == DriveAction::Connect)
|
||||
{
|
||||
connectGoogleDrive(task->stop.get_token());
|
||||
task->signingIn = false;
|
||||
}
|
||||
result.connected = googleDriveConnected();
|
||||
if (*result.connected)
|
||||
{
|
||||
result.page = listGoogleDriveBackups();
|
||||
if (result.page->backups.empty()) result.notice = L"No Google Drive backups yet.";
|
||||
}
|
||||
break;
|
||||
case DriveAction::Backup:
|
||||
{
|
||||
Settings saved;
|
||||
try { saved = loadSettings(path, layouts); }
|
||||
catch (const std::exception &) { throw std::runtime_error("Could not read the saved KSwitcher settings."); }
|
||||
result.uploaded = uploadGoogleDriveBackup(encodeDriveBackup(saved));
|
||||
result.notice = L"Saved settings backed up to Google Drive.";
|
||||
break;
|
||||
}
|
||||
case DriveAction::Restore:
|
||||
result.backup = fetchGoogleDriveBackup(backup.id);
|
||||
result.restoreDate = driveBackupTime(backup.created);
|
||||
break;
|
||||
case DriveAction::Older:
|
||||
result.page = listGoogleDriveBackups(page);
|
||||
break;
|
||||
case DriveAction::Disconnect:
|
||||
disconnectGoogleDrive();
|
||||
result.connected = false;
|
||||
result.notice = L"Disconnected. Backups are still in Google Drive.";
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (const std::runtime_error &error) { result.notice = wide(error.what()); }
|
||||
catch (const std::exception &) { result.notice = L"The Google Drive operation could not finish."; }
|
||||
std::lock_guard lock(task->mutex);
|
||||
task->result.emplace(std::move(result));
|
||||
}).detach();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
KillTimer(w, 1);
|
||||
throw;
|
||||
}
|
||||
view.task = std::move(task);
|
||||
view.action = action;
|
||||
switch (action)
|
||||
{
|
||||
case DriveAction::Status: view.notice = L"Checking the Google Drive connection…"; break;
|
||||
case DriveAction::Connect: view.notice = L"Complete Google sign-in in your browser."; break;
|
||||
case DriveAction::Backup: view.notice = L"Backing up saved settings…"; break;
|
||||
case DriveAction::Restore: view.notice = L"Downloading the selected backup…"; break;
|
||||
case DriveAction::Disconnect: view.notice = L"Disconnecting from Google Drive…"; break;
|
||||
case DriveAction::Older: view.notice = L"Loading older backups…"; break;
|
||||
}
|
||||
updateDriveControls(w, view);
|
||||
updateDriveSyncControls(w, view);
|
||||
}
|
||||
|
||||
void restoreDriveDraft(HWND root, SettingsView &settings, const Bytes &backup)
|
||||
{
|
||||
Settings draft;
|
||||
try
|
||||
{
|
||||
draft = collectSettings(&settings);
|
||||
mergeSnippetDraft(settings.viewport, &settings.snippets, draft);
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
throw std::runtime_error("Correct invalid edits in Settings before restoring the backup.");
|
||||
}
|
||||
auto restored = restoreDriveBackup(backup, draft, settings.app->layouts);
|
||||
settings.draft = std::move(restored);
|
||||
settings.snippets.snippets = settings.draft.snippets;
|
||||
settings.snippets.selection = -1;
|
||||
fillSnippets(settings.viewport, &settings.snippets);
|
||||
fillSettings(root, &settings);
|
||||
}
|
||||
|
||||
void finishDriveTask(HWND w, DriveView &view)
|
||||
{
|
||||
const auto root = GetAncestor(w, GA_ROOT);
|
||||
auto task = view.task;
|
||||
if (!task) return;
|
||||
DriveResult result;
|
||||
{
|
||||
std::lock_guard lock(task->mutex);
|
||||
if (!task->result)
|
||||
{
|
||||
if (view.action == DriveAction::Connect && !task->signingIn)
|
||||
{
|
||||
view.connected = true;
|
||||
view.notice = L"Loading Google Drive backups…";
|
||||
updateDriveControls(w, view);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (task->result->backup && (!IsWindowEnabled(root) || !IsWindowVisible(w))) return;
|
||||
result = std::move(*task->result);
|
||||
}
|
||||
KillTimer(w, 1);
|
||||
view.task.reset();
|
||||
const auto *previous = selectedDriveBackup(w, view);
|
||||
auto selection = previous ? previous->id : std::string{};
|
||||
bool listChanged = false;
|
||||
if (result.connected)
|
||||
{
|
||||
view.connected = *result.connected;
|
||||
if (!view.connected || view.action == DriveAction::Connect)
|
||||
{
|
||||
view.backups.clear();
|
||||
view.nextPage.clear();
|
||||
selection.clear();
|
||||
listChanged = true;
|
||||
}
|
||||
}
|
||||
if (result.page)
|
||||
{
|
||||
view.nextPage = std::move(result.page->nextPage);
|
||||
if (view.action == DriveAction::Older)
|
||||
{
|
||||
for (auto &backup : result.page->backups)
|
||||
if (std::none_of(view.backups.begin(), view.backups.end(),
|
||||
[&](const auto &known) { return known.id == backup.id; }))
|
||||
view.backups.push_back(std::move(backup));
|
||||
}
|
||||
else view.backups = std::move(result.page->backups);
|
||||
listChanged = true;
|
||||
}
|
||||
if (result.uploaded)
|
||||
{
|
||||
selection = result.uploaded->id;
|
||||
view.backups.insert(view.backups.begin(), std::move(*result.uploaded));
|
||||
listChanged = true;
|
||||
}
|
||||
if (listChanged) fillDriveBackupList(w, view, selection);
|
||||
view.notice = std::move(result.notice);
|
||||
if (result.backup)
|
||||
{
|
||||
std::wstring prompt = L"Load the Google Drive backup from " + result.restoreDate +
|
||||
L" into Settings? It will replace unapplied edits to the settings included in the backup. Use Apply or Save to make the restored settings active.";
|
||||
const auto *editor = syncEditor(view.settings->sync);
|
||||
if (editor && automaticSyncEnabled(syncFields(view.settings->sync)))
|
||||
prompt += L"\n\nAutomatic synchronization can send applied settings to the active provider and other PCs.";
|
||||
const auto accepted = MessageBoxW(root, prompt.c_str(),
|
||||
L"Restore settings from Google Drive", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) == IDYES;
|
||||
if (!IsWindow(w)) return;
|
||||
if (accepted)
|
||||
{
|
||||
restoreDriveDraft(root, *view.settings, *result.backup);
|
||||
view.notice = L"Backup loaded into Settings. Click Apply or Save to use it.";
|
||||
}
|
||||
else view.notice = L"Restore canceled.";
|
||||
}
|
||||
updateDriveControls(w, view);
|
||||
updateDriveSyncControls(w, view);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK driveSettingsProc(HWND w, UINT message, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if (message == WM_SIZE)
|
||||
{
|
||||
arrangeWindow(w);
|
||||
fitDriveBackupColumns(GetDlgItem(w, DriveList));
|
||||
}
|
||||
auto *view = reinterpret_cast<DriveView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
if (!view) return DefWindowProcW(w, message, wp, lp);
|
||||
try
|
||||
{
|
||||
switch (message)
|
||||
{
|
||||
case WM_PAINT: paintSettingsMatches(w); return 0;
|
||||
case WM_CTLCOLORSTATIC: return SendMessageW(GetParent(w), message, wp, lp);
|
||||
case WM_SHOWWINDOW:
|
||||
if (wp)
|
||||
{
|
||||
const auto sync = view->settings->sync;
|
||||
if (const auto *editor = syncEditor(sync); editor && !editor->initialized) reloadSyncEditor(sync);
|
||||
updateDriveControls(w, *view);
|
||||
updateDriveSyncControls(w, *view);
|
||||
if (!view->task && view->configured) startDriveTask(w, *view, DriveAction::Status);
|
||||
SetTimer(w, 2, 1000, nullptr);
|
||||
}
|
||||
else KillTimer(w, 2);
|
||||
break;
|
||||
case WM_TIMER:
|
||||
if (wp == 1) finishDriveTask(w, *view);
|
||||
if (wp == 2)
|
||||
{
|
||||
updateDriveControls(w, *view);
|
||||
updateDriveSyncControls(w, *view);
|
||||
}
|
||||
return 0;
|
||||
case WM_NOTIFY:
|
||||
{
|
||||
const auto ¬ice = *reinterpret_cast<const NMHDR *>(lp);
|
||||
if (notice.idFrom == DriveList && notice.code == LVN_ITEMCHANGED)
|
||||
updateDriveControls(w, *view);
|
||||
break;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
{
|
||||
const auto id = LOWORD(wp);
|
||||
if (HIWORD(wp) == BN_CLICKED && id >= DriveAutomatic && id <= DriveSyncConflicts &&
|
||||
IsWindowEnabled(GetDlgItem(w, id)))
|
||||
{
|
||||
const auto sync = view->settings->sync;
|
||||
if (id == DriveAutomatic)
|
||||
{
|
||||
if (checked(w, id)) check(sync, 601, false);
|
||||
if (auto *editor = syncEditor(sync))
|
||||
{
|
||||
editor->actionError = false;
|
||||
updateSyncControls(sync, *editor);
|
||||
}
|
||||
updateDriveSyncControls(w, *view);
|
||||
refreshSyncFooter(sync);
|
||||
}
|
||||
else if (id == DriveSyncConflicts) showSyncConflicts(w, *view->settings->app, DriveSyncStatus);
|
||||
else
|
||||
{
|
||||
if (id != DriveSyncNow && MessageBoxW(GetAncestor(w, GA_ROOT),
|
||||
id == DriveSyncUpload ? L"Replace the Google Drive synchronization profile with this PC's saved shared settings?" :
|
||||
L"Replace this PC's shared settings with the Google Drive synchronization profile? Save any edits first.",
|
||||
L"Google Drive synchronization", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) != IDYES)
|
||||
return 0;
|
||||
value(w, DriveSyncStatus, view->settings->app->syncCommand(
|
||||
id == DriveSyncUpload ? 3 : id == DriveSyncDownload ? 2 : 1));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (((id < DriveConnect || id > DriveDisconnect) && id != DriveOlder) || HIWORD(wp) != BN_CLICKED ||
|
||||
!IsWindowEnabled(GetDlgItem(w, id))) break;
|
||||
if (view->task)
|
||||
{
|
||||
if (!view->task->signingIn) return 0;
|
||||
view->task->stop.request_stop();
|
||||
view->notice = L"Canceling Google sign-in…";
|
||||
updateDriveControls(w, *view);
|
||||
return 0;
|
||||
}
|
||||
const auto action = id == DriveOlder ? DriveAction::Older : id == DriveConnect ? DriveAction::Connect : id == DriveBackup ? DriveAction::Backup :
|
||||
id == DriveRestore ? DriveAction::Restore : DriveAction::Disconnect;
|
||||
startDriveTask(w, *view, action);
|
||||
return 0;
|
||||
}
|
||||
case WM_NCDESTROY:
|
||||
KillTimer(w, 1);
|
||||
KillTimer(w, 2);
|
||||
if (view->task) view->task->stop.request_stop();
|
||||
delete windowLayoutState(w);
|
||||
RemovePropW(w, L"WindowLayout");
|
||||
RemovePropW(w, L"Font");
|
||||
delete view;
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
view->notice = dynamic_cast<const std::runtime_error *>(&error) ? wide(error.what()) :
|
||||
L"The Google Drive operation could not finish.";
|
||||
updateDriveControls(w, *view);
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcW(w, message, wp, lp);
|
||||
}
|
||||
|
||||
HWND createDriveSettings(HWND pane, SettingsView &settings)
|
||||
{
|
||||
WNDCLASSW panel{};
|
||||
panel.hInstance = settings.app->instance;
|
||||
panel.lpfnWndProc = driveSettingsProc;
|
||||
panel.lpszClassName = L"KSwitcher.GoogleDrive";
|
||||
panel.hCursor = LoadCursorW(nullptr, IDC_ARROW);
|
||||
panel.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
|
||||
RegisterClassW(&panel);
|
||||
const HWND w = CreateWindowExW(WS_EX_CONTROLPARENT, panel.lpszClassName, L"", WS_CHILD | WS_CLIPCHILDREN,
|
||||
0, 0, scale(pane, DriveSettingsWidth), scale(pane, DriveSettingsHeight), pane, nullptr, panel.hInstance, nullptr);
|
||||
if (!w) throw std::runtime_error("Cannot create Google Drive settings.");
|
||||
auto *view = new DriveView{&settings};
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(view));
|
||||
SetPropW(w, L"Font", GetPropW(pane, L"Font"));
|
||||
auto *layout = new WindowLayout{DriveSettingsWidth, DriveSettingsHeight, 0, 0, true, true};
|
||||
SetPropW(w, L"WindowLayout", layout);
|
||||
constexpr int left = DriveMargin, width = DriveSettingsWidth - 2 * left;
|
||||
settingsGroupLabel(w, L"Backup and restore", left, 14, width);
|
||||
label(w, L"Apply or Save your edits before backing them up.", left, 40, width);
|
||||
edit(w, DriveStatus, left, 63, width, 42, ES_MULTILINE | ES_READONLY | WS_VSCROLL);
|
||||
const auto list = control(w, WC_LISTVIEWW, L"Google Drive backups", WS_TABSTOP | WS_BORDER | LVS_REPORT |
|
||||
LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, DriveList, left, 112, width, 90);
|
||||
ListView_SetExtendedListViewStyle(list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP);
|
||||
int columnIndex = 0;
|
||||
for (const auto *title : {L"Backup date", L"Source", L"Size"})
|
||||
{
|
||||
LVCOLUMNW column{LVCF_TEXT | LVCF_FMT};
|
||||
column.pszText = const_cast<wchar_t *>(title);
|
||||
column.fmt = columnIndex == 2 ? LVCFMT_RIGHT : LVCFMT_LEFT;
|
||||
ListView_InsertColumn(list, columnIndex++, &column);
|
||||
}
|
||||
fitDriveBackupColumns(list);
|
||||
button(w, L"Load &older backups", DriveOlder, DriveLeftButton, DriveOlderTop, DriveButtonWidth);
|
||||
button(w, L"&Connect", DriveConnect, DriveLeftButton, DriveBackupActionsTop, DriveButtonWidth);
|
||||
button(w, L"Back &up saved settings", DriveBackup, DriveLeftButton, DriveBackupActionsTop + 31, DriveButtonWidth);
|
||||
button(w, L"&Restore selected backup", DriveRestore, DriveRightButton, DriveBackupActionsTop, DriveButtonWidth);
|
||||
button(w, L"&Disconnect", DriveDisconnect, DriveRightButton, DriveBackupActionsTop + 31, DriveButtonWidth);
|
||||
settingsGroupLabel(w, L"Automatic synchronization", left, DriveSyncTop, width);
|
||||
checkbox(w, L"&Use Google Drive for automatic synchronization", DriveAutomatic, left, DriveSyncTop + 27, width);
|
||||
edit(w, DriveSyncStatus, left, DriveSyncTop + 54, width, 52, ES_MULTILINE | ES_READONLY | WS_VSCROLL);
|
||||
button(w, L"S&ync now", DriveSyncNow, DriveLeftButton, DriveSyncTop + 113, DriveButtonWidth);
|
||||
button(w, L"D&ownload sync profile", DriveSyncDownload, DriveRightButton, DriveSyncTop + 113, DriveButtonWidth);
|
||||
button(w, L"U&pload local settings to sync profile", DriveSyncUpload, DriveLeftButton, DriveSyncTop + 144, DriveButtonWidth);
|
||||
button(w, L"Resolve individual con&flicts…", DriveSyncConflicts, DriveRightButton, DriveSyncTop + 144, DriveButtonWidth);
|
||||
for (int id : {DriveAutomatic, DriveSyncNow, DriveSyncUpload, DriveSyncDownload, DriveSyncConflicts})
|
||||
EnableWindow(GetDlgItem(w, id), FALSE);
|
||||
captureSettingsGeometry(*layout, 0, w);
|
||||
layout->arranging = false;
|
||||
updateDriveControls(w, *view);
|
||||
return w;
|
||||
}
|
||||
|
||||
int fitDriveSettings(HWND panel, int width, int height)
|
||||
{
|
||||
auto &layout = *windowLayoutState(panel);
|
||||
layout.width = 1;
|
||||
const int minimumHeight = fitSettingsColumns(layout, 0, layout.controls.size(), width,
|
||||
{DriveMargin, DriveSettingsWidth - DriveMargin});
|
||||
const int extra = std::max(0, height - minimumHeight);
|
||||
const int buttonWidth = std::clamp((width - 2 * DriveMargin - DriveButtonGap) / 2, 1, DriveButtonWidth);
|
||||
const int firstButton = (width - 2 * buttonWidth - DriveButtonGap) / 2;
|
||||
for (size_t i = 0; i < layout.controls.size(); ++i)
|
||||
{
|
||||
auto &[child, bounds] = layout.controls[i];
|
||||
const auto &original = layout.originalControls[i].bounds;
|
||||
const int id = GetDlgCtrlID(child);
|
||||
if (original.top >= DriveOlderTop) OffsetRect(&bounds, 0, extra);
|
||||
if (id == DriveList) bounds.bottom += extra;
|
||||
if (id == DriveStatus || id == DriveSyncStatus || id == DriveList) bounds.right = width - DriveMargin;
|
||||
if (id == DriveOlder)
|
||||
{
|
||||
bounds.left = (width - buttonWidth) / 2;
|
||||
bounds.right = bounds.left + buttonWidth;
|
||||
}
|
||||
if ((id >= DriveConnect && id <= DriveDisconnect) || (id >= DriveSyncNow && id <= DriveSyncConflicts))
|
||||
{
|
||||
bounds.left = firstButton + (original.left == DriveRightButton ? buttonWidth + DriveButtonGap : 0);
|
||||
bounds.right = bounds.left + buttonWidth;
|
||||
}
|
||||
}
|
||||
layout.height = minimumHeight + extra;
|
||||
return layout.height;
|
||||
}
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
namespace
|
||||
{
|
||||
constexpr int HelpSearch = 810, HelpTopics = 811, HelpTitle = 812, HelpBody = 813;
|
||||
constexpr int HelpRail = 268, HelpFooter = 56, HelpHeader = 66;
|
||||
constexpr int ShortcutTopic = 0, GuideRoot = 1, GettingStarted = 2;
|
||||
|
||||
struct HelpTopic
|
||||
{
|
||||
std::wstring title, text;
|
||||
int parent = -1;
|
||||
};
|
||||
|
||||
struct HelpView
|
||||
{
|
||||
App *app;
|
||||
WindowPalette palette;
|
||||
std::vector<HelpTopic> topics;
|
||||
HFONT heading{};
|
||||
UINT dpi{};
|
||||
int selected{};
|
||||
bool rebuilding{};
|
||||
};
|
||||
|
||||
std::wstring helpShortcuts(const App &app)
|
||||
{
|
||||
const auto &s = app.settings;
|
||||
std::wstring text;
|
||||
const auto add = [&](std::wstring_view label, std::wstring_view shortcut)
|
||||
{
|
||||
text += label;
|
||||
text += L": ";
|
||||
text += shortcut.empty() ? L"Unassigned" : shortcut;
|
||||
text += L"\r\n";
|
||||
};
|
||||
add(L"Next layout", s.toggle);
|
||||
add(L"Change case", s.casing);
|
||||
add(L"Transliterate", s.translit);
|
||||
add(L"Undo", s.undo);
|
||||
add(L"Clipboard history", s.clipboard);
|
||||
add(L"Screen capture", s.screenshot);
|
||||
add(L"Open KSwitcher Files", s.filesHotkey.value_or(L""));
|
||||
for (size_t i = 0; i < std::min(app.layouts.size(), s.direct.size()); ++i)
|
||||
if (!s.direct[i].empty()) add(app.layouts[i].name, s.direct[i]);
|
||||
text += L"\r\nChange these bindings in Settings → Shortcuts.\r\n\r\n"
|
||||
L"Clipboard history\r\nEnter to paste, Shift+Enter for plain text, Ctrl+1 through Ctrl+9 for quick paste, "
|
||||
L"Ctrl+P to pin, Delete to remove, Ctrl+O to open, Escape to close.\r\n\r\n"
|
||||
L"Screenshot editor\r\nCtrl+C to copy, Ctrl+S to save, Ctrl+Shift+S to save as, "
|
||||
L"Ctrl+Z to undo, Ctrl+Y to redo and Ctrl+0 to fit the image.";
|
||||
return text;
|
||||
}
|
||||
|
||||
std::wstring helpText(std::wstring line)
|
||||
{
|
||||
for (const std::wstring_view marker : {L"**", L"`"})
|
||||
for (size_t at = line.find(marker); at != std::wstring::npos; at = line.find(marker, at))
|
||||
line.erase(at, marker.size());
|
||||
for (size_t at = 0; (at = line.find(L"](", at)) != std::wstring::npos;)
|
||||
{
|
||||
const auto open = line.rfind(L'[', at), end = line.find(L')', at + 2);
|
||||
if (open == std::wstring::npos || end == std::wstring::npos) break;
|
||||
line.erase(at, end - at + 1);
|
||||
line.erase(open, 1);
|
||||
at = open;
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
void addHelpDocument(HelpView &view, int resource, std::wstring title, std::wstring introduction)
|
||||
{
|
||||
const int root = static_cast<int>(view.topics.size());
|
||||
view.topics.push_back({std::move(title), std::move(introduction)});
|
||||
const auto instance = view.app->instance;
|
||||
HRSRC found = FindResourceW(instance, MAKEINTRESOURCEW(resource), RT_RCDATA);
|
||||
HGLOBAL loaded = found ? LoadResource(instance, found) : nullptr;
|
||||
const auto *bytes = loaded ? static_cast<const char *>(LockResource(loaded)) : nullptr;
|
||||
if (!bytes) return;
|
||||
std::wistringstream input(wide(std::string(bytes, SizeofResource(instance, found))));
|
||||
std::array<int, 7> ancestors;
|
||||
ancestors.fill(root);
|
||||
int topic = root;
|
||||
bool inCode = false;
|
||||
for (std::wstring line; std::getline(input, line);)
|
||||
{
|
||||
if (line.ends_with(L'\r')) line.pop_back();
|
||||
if (line.starts_with(L"```"))
|
||||
{
|
||||
inCode = !inCode;
|
||||
continue;
|
||||
}
|
||||
const auto depth = line.find_first_not_of(L'#');
|
||||
if (!inCode && depth > 0 && depth < ancestors.size() && line[depth] == L' ')
|
||||
{
|
||||
const auto title = helpText(line.substr(depth + 1));
|
||||
if (depth == 1 && resource != IDR_HELP_GUIDE) continue;
|
||||
topic = static_cast<int>(view.topics.size());
|
||||
view.topics.push_back({title, {}, ancestors[depth - 1]});
|
||||
std::fill(ancestors.begin() + depth, ancestors.end(), topic);
|
||||
continue;
|
||||
}
|
||||
if (!inCode && (line.starts_with(L"![") || line.starts_with(L"[![") || line.starts_with(L"<")))
|
||||
continue;
|
||||
auto &text = view.topics[topic].text;
|
||||
if (text.empty() && line.empty()) continue;
|
||||
text += inCode ? line : helpText(std::move(line));
|
||||
text += L"\r\n";
|
||||
}
|
||||
}
|
||||
|
||||
void showHelpTopic(HWND w, HelpView &view, int index)
|
||||
{
|
||||
view.selected = index;
|
||||
const auto &topic = view.topics[index];
|
||||
value(w, HelpTitle, topic.title);
|
||||
value(w, HelpBody, index == ShortcutTopic ? helpShortcuts(*view.app) : topic.text);
|
||||
SendDlgItemMessageW(w, HelpBody, EM_SETSEL, 0, 0);
|
||||
SendDlgItemMessageW(w, HelpBody, EM_SCROLLCARET, 0, 0);
|
||||
}
|
||||
|
||||
void fillHelpTopics(HWND w, HelpView &view)
|
||||
{
|
||||
const auto tree = GetDlgItem(w, HelpTopics);
|
||||
const auto query = lower(value(w, HelpSearch));
|
||||
std::vector<HTREEITEM> nodes(view.topics.size());
|
||||
HTREEITEM selected{};
|
||||
view.rebuilding = true;
|
||||
SendMessageW(tree, WM_SETREDRAW, FALSE, 0);
|
||||
TreeView_DeleteAllItems(tree);
|
||||
for (size_t i = 0; i < view.topics.size(); ++i)
|
||||
{
|
||||
const auto &topic = view.topics[i];
|
||||
if (!query.empty() && lower(topic.title).find(query) == std::wstring::npos &&
|
||||
lower(topic.text).find(query) == std::wstring::npos) continue;
|
||||
TVINSERTSTRUCTW node{};
|
||||
node.hParent = query.empty() && topic.parent >= 0 ? nodes[topic.parent] : TVI_ROOT;
|
||||
node.hInsertAfter = TVI_LAST;
|
||||
node.item.mask = TVIF_TEXT | TVIF_PARAM;
|
||||
node.item.pszText = const_cast<wchar_t *>(topic.title.c_str());
|
||||
node.item.lParam = static_cast<LPARAM>(i);
|
||||
nodes[i] = TreeView_InsertItem(tree, &node);
|
||||
if (!selected || static_cast<int>(i) == view.selected) selected = nodes[i];
|
||||
}
|
||||
if (query.empty()) TreeView_Expand(tree, nodes[GuideRoot], TVE_EXPAND);
|
||||
SendMessageW(tree, WM_SETREDRAW, TRUE, 0);
|
||||
view.rebuilding = false;
|
||||
if (selected) TreeView_SelectItem(tree, selected);
|
||||
else
|
||||
{
|
||||
value(w, HelpTitle, L"No matching topics");
|
||||
value(w, HelpBody, L"Try another word or clear the search to see all topics.");
|
||||
}
|
||||
InvalidateRect(tree, nullptr, TRUE);
|
||||
}
|
||||
|
||||
void layoutHelp(HWND w, HelpView &view)
|
||||
{
|
||||
if (!GetDlgItem(w, HelpBody)) return;
|
||||
RECT r{};
|
||||
GetClientRect(w, &r);
|
||||
const int rail = scale(w, HelpRail), header = scale(w, HelpHeader);
|
||||
const int footer = std::max(header, static_cast<int>(r.bottom) - scale(w, HelpFooter));
|
||||
const int pad = scale(w, 18), content = rail + pad;
|
||||
const auto place = [&](int id, int left, int top, int right, int bottom)
|
||||
{
|
||||
SetWindowPos(GetDlgItem(w, id), nullptr, left, top, std::max(0, right - left),
|
||||
std::max(0, bottom - top), SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
};
|
||||
place(HelpSearch, pad, scale(w, 19), rail - pad, scale(w, 45));
|
||||
place(HelpTopics, pad, scale(w, 57), rail - pad, footer - pad);
|
||||
place(HelpTitle, content, scale(w, 13), r.right - pad, scale(w, 55));
|
||||
place(HelpBody, content, header + pad, r.right - pad, footer - scale(w, 10));
|
||||
place(IDCANCEL, r.right - pad - scale(w, 100), footer + scale(w, 14), r.right - pad, r.bottom - scale(w, 14));
|
||||
const auto dpi = GetDpiForWindow(w);
|
||||
if (view.dpi != dpi || !view.heading)
|
||||
{
|
||||
setWindowResourceIcons(w, view.app->instance, IDI_KSWITCHER_HELP);
|
||||
const auto old = view.heading;
|
||||
view.heading = headingFont(w);
|
||||
view.dpi = dpi;
|
||||
if (old) DeleteObject(old);
|
||||
}
|
||||
SendDlgItemMessageW(w, HelpTitle, WM_SETFONT, reinterpret_cast<WPARAM>(view.heading), TRUE);
|
||||
InvalidateRect(w, nullptr, FALSE);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK helpProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
auto *view = reinterpret_cast<HelpView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
if (msg == WM_NCCREATE)
|
||||
{
|
||||
const auto *creation = reinterpret_cast<const CREATESTRUCTW *>(lp);
|
||||
view = new HelpView{static_cast<App *>(creation->lpCreateParams)};
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(view));
|
||||
return TRUE;
|
||||
}
|
||||
if (!view) return DefWindowProcW(w, msg, wp, lp);
|
||||
switch (msg)
|
||||
{
|
||||
case WM_SIZE:
|
||||
if (wp != SIZE_MINIMIZED) layoutHelp(w, *view);
|
||||
return 0;
|
||||
case WM_GETMINMAXINFO:
|
||||
{
|
||||
RECT frame{}, client{};
|
||||
GetWindowRect(w, &frame);
|
||||
GetClientRect(w, &client);
|
||||
const RECT work = workArea(frame);
|
||||
auto &limits = *reinterpret_cast<MINMAXINFO *>(lp);
|
||||
limits.ptMinTrackSize.x = std::min(work.right - work.left, scale(w, 600) + frame.right - frame.left - client.right);
|
||||
limits.ptMinTrackSize.y = std::min(work.bottom - work.top, scale(w, 310) + frame.bottom - frame.top - client.bottom);
|
||||
return 0;
|
||||
}
|
||||
case WM_SETTINGCHANGE: case WM_SYSCOLORCHANGE: case WM_DWMCOLORIZATIONCOLORCHANGED:
|
||||
view->palette.refresh(msg == WM_DWMCOLORIZATIONCOLORCHANGED ? std::optional<DWORD>(wp) : std::nullopt);
|
||||
TreeView_SetBkColor(GetDlgItem(w, HelpTopics), view->palette.color());
|
||||
TreeView_SetTextColor(GetDlgItem(w, HelpTopics), GetSysColor(COLOR_WINDOWTEXT));
|
||||
RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN);
|
||||
break;
|
||||
case WM_ERASEBKGND: return 1;
|
||||
case WM_PAINT:
|
||||
{
|
||||
PAINTSTRUCT paint{};
|
||||
HDC dc = BeginPaint(w, &paint);
|
||||
RECT r{};
|
||||
GetClientRect(w, &r);
|
||||
const int rail = scale(w, HelpRail), footer = r.bottom - scale(w, HelpFooter);
|
||||
const RECT sidebar{0, 0, rail, footer}, actions{0, footer, r.right, r.bottom};
|
||||
FillRect(dc, &paint.rcPaint, GetSysColorBrush(COLOR_WINDOW));
|
||||
FillRect(dc, &sidebar, view->palette.brush());
|
||||
FillRect(dc, &actions, view->palette.brush());
|
||||
fillSurface(dc, {rail, 0, rail + 1, footer}, view->palette.edge());
|
||||
fillSurface(dc, {rail + 1, scale(w, HelpHeader), r.right, scale(w, HelpHeader) + 1}, view->palette.edge());
|
||||
fillSurface(dc, {0, footer, r.right, footer + 1}, view->palette.edge());
|
||||
EndPaint(w, &paint);
|
||||
return 0;
|
||||
}
|
||||
case WM_CTLCOLORSTATIC:
|
||||
{
|
||||
const auto dc = reinterpret_cast<HDC>(wp);
|
||||
SetTextColor(dc, GetSysColor(COLOR_WINDOWTEXT));
|
||||
SetBkColor(dc, GetSysColor(COLOR_WINDOW));
|
||||
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_WINDOW));
|
||||
}
|
||||
case WM_NOTIFY:
|
||||
{
|
||||
const auto ¬ice = *reinterpret_cast<const NMHDR *>(lp);
|
||||
if (notice.idFrom == HelpTopics && notice.code == TVN_SELCHANGEDW && !view->rebuilding)
|
||||
{
|
||||
const auto &item = reinterpret_cast<const NMTREEVIEWW *>(lp)->itemNew;
|
||||
if (item.hItem) showHelpTopic(w, *view, static_cast<int>(item.lParam));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
if (LOWORD(wp) == HelpSearch && HIWORD(wp) == EN_CHANGE) fillHelpTopics(w, *view);
|
||||
if (LOWORD(wp) == IDCANCEL) DestroyWindow(w);
|
||||
return 0;
|
||||
case WM_NCDESTROY:
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||
view->app->helpWindow = nullptr;
|
||||
if (view->heading) DeleteObject(view->heading);
|
||||
disposeFont(w);
|
||||
delete view;
|
||||
break;
|
||||
}
|
||||
return DefWindowProcW(w, msg, wp, lp);
|
||||
}
|
||||
|
||||
void openHelp(App &app, int topic)
|
||||
{
|
||||
if (!app.helpWindow)
|
||||
{
|
||||
const auto w = makeWindow(app, L"KSwitcher.Help", L"KSwitcher Help", helpProc, 910, 615, WS_THICKFRAME);
|
||||
app.helpWindow = w;
|
||||
setWindowTaskbarIdentity(w, IDI_KSWITCHER_HELP, L"HrynCo.KSwitcher.Help");
|
||||
auto &view = *reinterpret_cast<HelpView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
view.topics = {{L"Keyboard shortcuts", L"Current shortcut bindings and keyboard controls"}};
|
||||
addHelpDocument(view, IDR_HELP_GUIDE, L"Using KSwitcher", L"Choose an area to learn how to use it.\r\n");
|
||||
addHelpDocument(view, IDR_HELP_MANUAL, L"KSwitcher manual", L"Detailed documentation for the main application.\r\n");
|
||||
addHelpDocument(view, IDR_HELP_FILES, L"Files manual (Українська)", L"Докладний посібник з KSwitcher Files.\r\n");
|
||||
addHelpDocument(view, IDR_HELP_COMPUTERS, L"Paired computers manual", L"Detailed documentation for discovery, pairing and LAN features.\r\n");
|
||||
|
||||
auto search = edit(w, HelpSearch, 0, 0, 0);
|
||||
SendMessageW(search, EM_SETLIMITTEXT, 120, 0);
|
||||
SendMessageW(search, EM_SETCUEBANNER, TRUE, reinterpret_cast<LPARAM>(L"Search help"));
|
||||
INITCOMMONCONTROLSEX classes{sizeof(classes), ICC_TREEVIEW_CLASSES};
|
||||
InitCommonControlsEx(&classes);
|
||||
control(w, WC_TREEVIEWW, L"Help topics", WS_TABSTOP | TVS_HASBUTTONS | TVS_LINESATROOT |
|
||||
TVS_SHOWSELALWAYS | TVS_FULLROWSELECT | TVS_NOHSCROLL, HelpTopics, 0, 0, 0, 0);
|
||||
control(w, L"STATIC", L"", SS_CENTERIMAGE | SS_ENDELLIPSIS, HelpTitle, 0, 0, 0, 0);
|
||||
auto body = edit(w, HelpBody, 0, 0, 0, 0, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL);
|
||||
SendMessageW(body, EM_SETLIMITTEXT, 1024 * 1024, 0);
|
||||
button(w, L"&Close", IDCANCEL, 0, 0);
|
||||
SendMessageW(w, WM_SYSCOLORCHANGE, 0, 0);
|
||||
layoutHelp(w, view);
|
||||
}
|
||||
const auto w = app.helpWindow;
|
||||
auto &view = *reinterpret_cast<HelpView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
view.selected = topic < static_cast<int>(view.topics.size()) ? topic : GuideRoot;
|
||||
if (value(w, HelpSearch).empty()) fillHelpTopics(w, view);
|
||||
else value(w, HelpSearch, L"");
|
||||
if (IsIconic(w)) ShowWindow(w, SW_RESTORE);
|
||||
else showRequestedWindow(w);
|
||||
activateWindow(w);
|
||||
SetFocus(GetDlgItem(w, HelpTopics));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void showHelp(App &app) { openHelp(app, GettingStarted); }
|
||||
void showShortcuts(App &app) { openHelp(app, ShortcutTopic); }
|
||||
+373
-117
@@ -1,41 +1,175 @@
|
||||
// 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();
|
||||
nlohmann::json saved, draft = nlohmann::json::object();
|
||||
std::vector<std::string> ids;
|
||||
std::wstring error;
|
||||
std::wstring layoutError;
|
||||
std::string dragPeer;POINT dragStart{},dragPoint{};bool dragMoved{};
|
||||
std::string gridState;
|
||||
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)
|
||||
{
|
||||
auto text=request.dump(); auto reply=app.lanCommand(Bytes(text.begin(),text.end()));
|
||||
return nlohmann::json::parse(reply);
|
||||
}
|
||||
void stageLanValue(LanView &v, const char *key, const nlohmann::json &value)
|
||||
{
|
||||
if (value == v.saved.at(key)) v.draft.erase(key);
|
||||
else v.draft[key] = value;
|
||||
}
|
||||
void refreshLanFooter(LanView &v)
|
||||
{
|
||||
updateSettingsState(v.owner, reinterpret_cast<SettingsView *>(GetWindowLongPtrW(v.owner, GWLP_USERDATA)));
|
||||
}
|
||||
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
|
||||
{
|
||||
LanView *lan{};
|
||||
nlohmann::json entries, saved;
|
||||
};
|
||||
void refreshLanClients(HWND window, LanClientsView &view)
|
||||
{
|
||||
view.entries = view.saved;
|
||||
for (const auto &change : view.lan->draft.value("clients", nlohmann::json::object()))
|
||||
{
|
||||
const auto &path = change.at("path");
|
||||
std::erase_if(view.entries.get_ref<nlohmann::json::array_t &>(),
|
||||
[&](const auto &entry) { return entry.at("path") == path; });
|
||||
if (change.at("action") == "trustClient") view.entries.push_back(change);
|
||||
}
|
||||
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)
|
||||
{
|
||||
const auto entry = lanRequest(*view->lan->app, {{"action", "inspectClient"}, {"path", utf8(path.wstring())}});
|
||||
const auto canonical = entry.at("path").get<std::string>();
|
||||
const auto key = utf8(lower(wide(canonical)));
|
||||
auto &changes = view->lan->draft["clients"];
|
||||
if (std::find(view->saved.begin(), view->saved.end(), entry) == view->saved.end())
|
||||
changes[key] = {{"action", "trustClient"}, {"path", canonical}, {"sha256", entry.at("sha256")}};
|
||||
else if (changes.is_object()) changes.erase(key);
|
||||
if (changes.empty()) view->lan->draft.erase("clients");
|
||||
refreshLanFooter(*view->lan);
|
||||
refreshLanClients(window, *view);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (id == 734 && index >= 0 && size_t(index) < view->entries.size())
|
||||
{
|
||||
const auto path = view->entries[size_t(index)].at("path").get<std::string>();
|
||||
const auto key = utf8(lower(wide(path)));
|
||||
auto &changes = view->lan->draft["clients"];
|
||||
if (std::any_of(view->saved.begin(), view->saved.end(), [&](const auto &entry) { return entry.at("path") == path; }))
|
||||
changes[key] = {{"action", "removeClient"}, {"path", path}};
|
||||
else changes.erase(key);
|
||||
if (changes.empty()) view->lan->draft.erase("clients");
|
||||
refreshLanFooter(*view->lan);
|
||||
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, LanView &lan)
|
||||
{
|
||||
auto window = makeWindow(*lan.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{&lan};
|
||||
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"After updating an executable, add it again and click Apply or Save in Settings.", 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
|
||||
{
|
||||
view->saved = lanRequest(*lan.app, {{"action", "trustedClients"}});
|
||||
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,18 +201,30 @@ 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();
|
||||
}
|
||||
}
|
||||
auto selected=selectedLan(w,v);
|
||||
auto next=lanRequest(*v.app,{{"action","status"}});
|
||||
v.saved = next;
|
||||
for (const auto *key : {"enabled", "shareInput", "shareLogs"})
|
||||
if (v.draft.contains(key)) next[key] = v.draft.at(key);
|
||||
next["positions"].update(v.draft.value("positions", nlohmann::json::object()));
|
||||
const auto forgotten = v.draft.value("forget", nlohmann::json::object());
|
||||
for (const auto &[peer, ignored] : forgotten.items())
|
||||
{
|
||||
next["positions"].erase(peer);
|
||||
for (auto &entry : next["peers"])
|
||||
if (entry.at("id") == peer) entry["paired"] = false;
|
||||
}
|
||||
if (next["positions"].empty()) next["shareInput"] = false;
|
||||
if(selected.empty())
|
||||
{
|
||||
std::string onlyPaired;size_t pairedCount=0;
|
||||
@@ -91,8 +237,11 @@ void refreshLan(HWND w,LanView &v)
|
||||
for(const auto &peer:next["peers"])
|
||||
{
|
||||
auto id=peer.at("id").get<std::string>();ids.push_back(id);
|
||||
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""));
|
||||
const bool online = peer.value("online", false);
|
||||
const bool paired = peer.value("paired", false);
|
||||
const auto state = paired ? (online ? L"Paired · online" : L"Paired · offline") :
|
||||
(online ? L"Available to pair" : L"Offline");
|
||||
rows.push_back(wide(peer.at("name").get<std::string>()) + L" [" + wide(id.substr(0,8)) + L"] — " + state);
|
||||
}
|
||||
// Presence/challenge refreshes must not repaint or reset the pairing list.
|
||||
if(v.ids!=ids||v.rows!=rows)
|
||||
@@ -117,18 +266,28 @@ void refreshLan(HWND w,LanView &v)
|
||||
v.snapshot=std::move(next);
|
||||
bool enabled=v.snapshot.at("enabled"), pending=v.snapshot.at("pending"), online=false, paired=false;
|
||||
for(const auto &peer:v.snapshot["peers"]) if(peer.at("id")==selected) {online=peer.at("online");paired=peer.at("paired");}
|
||||
value(w,701,enabled ? L"&Disable discovery" : L"&Enable discovery");
|
||||
value(w,709,L"This KSwitcher: "+wide(v.snapshot.at("name").get<std::string>())+L" ["+wide(v.snapshot.at("id").get<std::string>().substr(0,8))+L"]");
|
||||
bool reflow = false;
|
||||
auto setStatus = [&](int id, const std::wstring &text)
|
||||
{
|
||||
if (value(w, id) == text) return;
|
||||
value(w, id, text);
|
||||
reflow = true;
|
||||
};
|
||||
setStatus(701,enabled ? L"&Disable discovery" : L"&Enable discovery");
|
||||
setStatus(709,L"This PC: "+wide(v.snapshot.at("name").get<std::string>())+L" ["+wide(v.snapshot.at("id").get<std::string>().substr(0,8))+L"]");
|
||||
auto pairingStatus=wide(v.snapshot.at("status").get<std::string>());
|
||||
if(pending)
|
||||
{
|
||||
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 on the other PC.";
|
||||
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair, then Apply or Save on the other PC.";
|
||||
}
|
||||
value(w,708,v.error.empty() ? pairingStatus : v.error);
|
||||
value(w,705,pending ? L"Waiting..." : L"&Pair");
|
||||
if (v.draft.contains("enabled"))
|
||||
pairingStatus = enabled ? L"Click Apply or Save to enable discovery." : L"Click Apply or Save to disable discovery.";
|
||||
if (v.draft.contains("pair")) pairingStatus = L"Click Apply or Save to start pairing on this PC.";
|
||||
setStatus(708,v.error.empty() ? pairingStatus : v.error);
|
||||
setStatus(705,pending ? L"Waiting..." : L"&Pair");
|
||||
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.";
|
||||
@@ -139,53 +298,87 @@ void refreshLan(HWND w,LanView &v)
|
||||
!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);
|
||||
setStatus(710,forgotten.contains(selected) ? L"Click Apply or Save to remove this pair." : peerStatus);
|
||||
EnableWindow(GetDlgItem(w,705),v.saved.at("enabled").get<bool>()&&enabled&&online&&!pending&&!v.draft.contains("pair")&&!forgotten.contains(selected)&&!paired);
|
||||
EnableWindow(GetDlgItem(w,706),pending || v.draft.contains("pair"));
|
||||
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);
|
||||
for(int id:{703,704}) EnableWindow(GetDlgItem(w,id),enabled&&!pending&&!paired);
|
||||
if (value(w, 731) != v.logMessage)
|
||||
{
|
||||
value(w, 731, v.logMessage);
|
||||
ShowWindow(GetDlgItem(w, 731), v.logMessage.empty() ? SW_HIDE : SW_SHOWNA);
|
||||
reflow = true;
|
||||
}
|
||||
for(int id:{703,704}) EnableWindow(GetDlgItem(w,id),v.saved.at("enabled").get<bool>()&&enabled&&!pending&&!v.draft.contains("pair")&&!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);}
|
||||
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);
|
||||
if(mode==2)inputStatus=L"Mouse and keyboard control the OTHER PC. Ctrl+Alt+Esc returns here.";
|
||||
else if(mode==3)inputStatus=L"This PC is controlled remotely. Local physical input takes control back.";
|
||||
value(w,718,inputStatus);
|
||||
value(w,722,v.snapshot.value("inputNeedsHelp",false)?L"Connection failed — &help":L"Connection &help");
|
||||
if (v.draft.contains("shareInput"))
|
||||
inputStatus = L"Click Apply or Save to apply input sharing changes.";
|
||||
setStatus(718,v.layoutError.empty() ? inputStatus : v.layoutError);
|
||||
setStatus(722,v.snapshot.value("inputNeedsHelp",false)?L"Connection failed — &help":L"Connection &help");
|
||||
if (reflow && IsWindowVisible(w))
|
||||
{
|
||||
arrangeWindow(GetParent(w));
|
||||
arrangeWindow(w);
|
||||
}
|
||||
}
|
||||
#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);
|
||||
@@ -193,112 +386,175 @@ 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==701) lanRequest(*v->app,{{"action","enable"},{"enabled",!v->snapshot.value("enabled",false)}});
|
||||
v->layoutError.clear();
|
||||
if(id==722){showLanHelp(v->owner,*v->app);return 0;}
|
||||
if(id==735){showLanClients(v->owner,*v);return 0;}
|
||||
if(id==701) stageLanValue(*v,"enabled",!v->snapshot.value("enabled",false));
|
||||
if(id==704)
|
||||
{
|
||||
auto code=lanRequest(*v->app,{{"action","code"}}).at("code").get<std::string>();
|
||||
std::string grouped; for(size_t i=0;i<code.size();++i) {if(i&&i%4==0) grouped+='-';grouped+=code[i];}
|
||||
value(w,703,wide(grouped)); SetFocus(GetDlgItem(w,703)); SendDlgItemMessageW(w,703,EM_SETSEL,0,-1);
|
||||
}
|
||||
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)
|
||||
if(id==705) v->draft["pair"] = {{"peer",peer},{"code",lan::normalizeCode(utf8(value(w,703)))}};
|
||||
if(id==701 && v->snapshot.value("enabled",false))
|
||||
{
|
||||
auto file=pickLanFile(w,false);
|
||||
if(!file.empty())
|
||||
v->draft.erase("pair");
|
||||
if (v->draft.value("shareInput", false)) v->draft.erase("shareInput");
|
||||
}
|
||||
if(id==706 && !v->draft.erase("pair")) lanRequest(*v->app,{{"action","cancel"}});
|
||||
if(id==707)
|
||||
{
|
||||
v->draft["forget"][peer] = true;
|
||||
if (v->draft.contains("positions"))
|
||||
{
|
||||
lanRequest(*v->app,{{"action","sendFile"},{"peer",peer},{"path",utf8(file.wstring())}});
|
||||
v->transferMessage.clear();
|
||||
v->draft["positions"].erase(peer);
|
||||
if (v->draft["positions"].empty()) v->draft.erase("positions");
|
||||
}
|
||||
if (v->snapshot["positions"].size() == 1) v->draft.erase("shareInput");
|
||||
}
|
||||
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}});
|
||||
}
|
||||
if(id==716)lanRequest(*v->app,{{"action","input"},{"enabled",false}});
|
||||
if(id==729)stageLanValue(*v,"shareLogs",checked(w,729));
|
||||
if(id==715 || id==716) stageLanValue(*v,"shareInput",id==715);
|
||||
refreshLanFooter(*v);
|
||||
refreshLan(w,*v); return 0;
|
||||
}
|
||||
}
|
||||
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 = 341, LanLayoutLeft = 375, LanLayoutWidth = 341;
|
||||
constexpr int LanEditorsTop = 98, LanEditorsHeight = 134, LanEditorsBottom = LanEditorsTop + LanEditorsHeight;
|
||||
constexpr int LanActionHeight = 28, LanCodeTop = LanEditorsBottom + 66, LanActionsTop = LanCodeTop + LanActionHeight + 8;
|
||||
constexpr int LanDiagnosticsTop = 420, LanStackWidth = 640;
|
||||
constexpr int LanSettingsWidth = LanLayoutLeft + LanLayoutWidth + LanPadding, LanSettingsHeight = 540;
|
||||
HWND createLanSettings(HWND pane, App &app)
|
||||
{
|
||||
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,730,498,0,false);
|
||||
windowLayoutState(w)->fixedClient=true;
|
||||
SetWindowLongPtrW(w,GWLP_HWNDPARENT,(LONG_PTR)parent);
|
||||
auto v=new LanView{parent,&app};SetWindowLongPtrW(w,GWLP_USERDATA,(LONG_PTR)v);
|
||||
label(w,L"Changes save automatically.",16,12,698);
|
||||
control(w,L"STATIC",L"",0,709,16,35,698,22);
|
||||
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 = LanActionHeight;
|
||||
constexpr int discoveryWidth = (pairingWidth - gap) / 2;
|
||||
settingsGroupLabel(w, L"Computers and 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"Discovered and paired computers", WS_TABSTOP | WS_VSCROLL | WS_BORDER | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT,
|
||||
702, left, LanEditorsTop, pairingWidth, LanEditorsHeight);
|
||||
control(w, L"STATIC", L"", 0, 710, left, LanEditorsBottom + 8, pairingWidth, 33);
|
||||
constexpr int codeTop = LanCodeTop, actionTop = LanActionsTop;
|
||||
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, codeTop - 24, 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);
|
||||
|
||||
button(w,L"&Enable discovery",701,16,62,164);
|
||||
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,16,98,332,70);
|
||||
control(w,L"STATIC",L"",0,710,16,173,332,36);
|
||||
label(w,L"Same pairing c&ode on both computers",16,211,332);
|
||||
edit(w,703,16,234,189);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
|
||||
button(w,L"&Generate code",704,213,234,135);
|
||||
button(w,L"&Pair",705,16,268,76);
|
||||
button(w,L"Cancel &pairing",706,100,268,125);
|
||||
button(w,L"&Forget pair",707,233,268,115);
|
||||
control(w,L"STATIC",L"Use one code on both PCs. Select each other and click Pair on both.",0,0,16,302,332,37);
|
||||
control(w,L"STATIC",L"",0,708,16,344,332,53);
|
||||
|
||||
constexpr int right=366,rightWidth=348,gridTop=92,gridHeight=185;
|
||||
label(w,L"Arrange your computers",right,65,rightWidth);
|
||||
constexpr int inputButtonWidth = (rightWidth - gap) / 2;
|
||||
settingsGroupLabel(w, L"Monitor layout and input sharing", right, 14, rightWidth);
|
||||
control(w, L"STATIC", L"Drag monitors or use arrow keys. The pointer crosses shared edges.", 0, 719, right, 39, rightWidth, 50);
|
||||
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 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,283,rightWidth,37);
|
||||
button(w,L"Enable &input sharing",715,right,323,172);
|
||||
button(w,L"&Stop input sharing",716,546,323,168);
|
||||
control(w,L"STATIC",L"",0,718,right,357,rightWidth,40);
|
||||
scale(w,right),scale(w,LanEditorsTop),scale(w,rightWidth),scale(w,LanEditorsHeight),w,reinterpret_cast<HMENU>(721),app.instance,v);
|
||||
windowLayoutState(w)->controls.push_back({grid,{right,LanEditorsTop,right+rightWidth,LanEditorsBottom}});
|
||||
control(w, L"STATIC", L"", 0, 718, right, LanEditorsBottom + 8, rightWidth, 42);
|
||||
button(w, L"Enable &input sharing", 715, right, codeTop, inputButtonWidth);
|
||||
button(w, L"&Stop input sharing", 716, right + inputButtonWidth + gap, codeTop, inputButtonWidth);
|
||||
button(w, L"Connection &help", 722, right, actionTop, 232);
|
||||
|
||||
button(w,L"Send file…",726,16,403,168);
|
||||
button(w,L"Incoming files…",730,192,403,168);
|
||||
button(w,L"Download log…",727,368,403,168);
|
||||
button(w,L"Previous log…",728,544,403,170);
|
||||
control(w,L"STATIC",L"",0,731,16,436,698,20);
|
||||
checkbox(w,L"Allow paired computers to download diagnostic logs",729,16,464,418);
|
||||
button(w,L"Connection &help",722,444,460,162);
|
||||
button(w,L"&Close",IDCANCEL,614,460,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);}
|
||||
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;
|
||||
}
|
||||
|
||||
void alignLanActionRows(WindowLayout &layout, size_t footer, size_t end)
|
||||
{
|
||||
for (int row : {LanCodeTop, LanActionsTop})
|
||||
{
|
||||
LONG top = 0, height = 0;
|
||||
std::array<LONG, 2> previousBottom{};
|
||||
for (size_t i = 0; i < footer; ++i)
|
||||
{
|
||||
const auto &original = layout.originalControls[i].bounds;
|
||||
if (original.top != row) continue;
|
||||
const auto &bounds = layout.controls[i].second;
|
||||
const int column = original.left >= LanLayoutLeft;
|
||||
top = std::max(top, bounds.top);
|
||||
height = std::max(height, bounds.bottom - bounds.top);
|
||||
previousBottom[column] = std::max(previousBottom[column], bounds.bottom);
|
||||
}
|
||||
const LONG bottom = top + height;
|
||||
for (size_t i = 0; i < footer; ++i)
|
||||
{
|
||||
const auto &original = layout.originalControls[i].bounds;
|
||||
auto &bounds = layout.controls[i].second;
|
||||
if (original.top == row)
|
||||
{
|
||||
bounds.top = top;
|
||||
bounds.bottom = bottom;
|
||||
}
|
||||
else if (original.top > row)
|
||||
OffsetRect(&bounds, 0, bottom - previousBottom[original.left >= LanLayoutLeft]);
|
||||
}
|
||||
}
|
||||
LONG contentBottom = 0;
|
||||
for (size_t i = 0; i < footer; ++i) contentBottom = std::max(contentBottom, layout.controls[i].second.bottom);
|
||||
const LONG footerShift = std::max(0L, contentBottom + 12 - layout.controls[footer].second.top);
|
||||
for (size_t i = footer; i < end; ++i) OffsetRect(&layout.controls[i].second, 0, footerShift);
|
||||
layout.height += footerShift;
|
||||
}
|
||||
|
||||
int fitLanSettings(HWND panel, int width, int height)
|
||||
{
|
||||
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, LanStackWidth, 0, 0, true});
|
||||
const auto footer = std::find_if(layout.originalControls.begin(), layout.originalControls.end(),
|
||||
[](const auto &item) { return item.bounds.top >= LanDiagnosticsTop; }) - layout.originalControls.begin();
|
||||
const bool stacked = width < LanStackWidth;
|
||||
if (!stacked) alignLanActionRows(layout, footer, end);
|
||||
const int extra = std::max(0, height - layout.height);
|
||||
stretchSettingsEditors(layout, 0, footer, extra, {702, 721}, stacked);
|
||||
for (size_t i = footer; i < end; ++i) OffsetRect(&layout.controls[i].second, 0, extra);
|
||||
return layout.height;
|
||||
}
|
||||
+48
-17
@@ -15,8 +15,18 @@ LanGridMetrics lanGridMetrics(HWND w,const LanView &v)
|
||||
}
|
||||
void moveLanMonitor(HWND parent,LanView &v,const std::string &peer,int x,int y)
|
||||
{
|
||||
try{lanRequest(*v.app,{{"action","position"},{"peer",peer},{"x",x},{"y",y}});v.error.clear();}
|
||||
catch(const std::exception &e){v.error=wide(e.what());}
|
||||
try
|
||||
{
|
||||
lan::validateCell(v.snapshot.at("positions"), peer, x, y);
|
||||
auto &positions = v.draft["positions"];
|
||||
auto cell = nlohmann::json::array({x,y});
|
||||
if (v.saved.at("positions").at(peer) != cell) positions[peer] = cell;
|
||||
else if (positions.is_object()) positions.erase(peer);
|
||||
if (positions.empty()) v.draft.erase("positions");
|
||||
v.layoutError.clear();
|
||||
refreshLanFooter(v);
|
||||
}
|
||||
catch(const std::exception &e){v.layoutError=wide(e.what());}
|
||||
refreshLan(parent,v);
|
||||
}
|
||||
LRESULT CALLBACK lanGridProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
@@ -63,40 +73,61 @@ LRESULT CALLBACK lanGridProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
if(msg==WM_PAINT){
|
||||
PAINTSTRUCT ps{};auto target=BeginPaint(w,&ps);RECT bounds{};GetClientRect(w,&bounds);
|
||||
auto dc=CreateCompatibleDC(target);auto bitmap=CreateCompatibleBitmap(target,std::max(1L,bounds.right),std::max(1L,bounds.bottom));auto oldBitmap=SelectObject(dc,bitmap);
|
||||
auto fill=CreateSolidBrush(RGB(247,249,251));FillRect(dc,&bounds,fill);DeleteObject(fill);
|
||||
const auto *settings = reinterpret_cast<SettingsView *>(GetWindowLongPtrW(v->owner, GWLP_USERDATA));
|
||||
const bool highContrast = settings && settings->palette.highContrast;
|
||||
if (highContrast) FillRect(dc, &bounds, GetSysColorBrush(COLOR_WINDOW));
|
||||
else
|
||||
{
|
||||
const auto fill = CreateSolidBrush(RGB(245, 248, 251));
|
||||
FillRect(dc, &bounds, fill);
|
||||
DeleteObject(fill);
|
||||
}
|
||||
auto oldFont=SelectObject(dc,GetPropW(parent,L"Font"));SetBkMode(dc,TRANSPARENT);
|
||||
auto gridPen=CreatePen(PS_DOT,1,RGB(214,222,230));auto oldPen=SelectObject(dc,gridPen);auto oldBrush=SelectObject(dc,GetStockObject(NULL_BRUSH));
|
||||
auto gridPen=CreatePen(PS_DOT,1,highContrast ? GetSysColor(COLOR_WINDOWTEXT) : RGB(194,207,222));auto oldPen=SelectObject(dc,gridPen);auto oldBrush=SelectObject(dc,GetStockObject(NULL_BRUSH));
|
||||
auto g=lanGridMetrics(w,*v);
|
||||
for(int x=g.left;x<=g.right+1;++x){int at=(x-g.left)*g.width/(g.right-g.left+1);MoveToEx(dc,at,0,nullptr);LineTo(dc,at,g.height);}
|
||||
for(int y=g.top;y<=g.bottom+1;++y){int at=(y-g.top)*g.height/(g.bottom-g.top+1);MoveToEx(dc,0,at,nullptr);LineTo(dc,g.width,at);}
|
||||
auto selected=selectedLan(parent,*v);
|
||||
auto draw=[&](const std::string &id,const std::wstring &name,int x,int y,bool local){
|
||||
auto cell=g.cell(x,y);int margin=scale(w,8),cellWidth=cell.right-cell.left;
|
||||
auto draw=[&](const std::string &id,const std::wstring &name,int x,int y,bool local,bool online){
|
||||
const auto cell=g.cell(x,y);
|
||||
const int cellWidth=cell.right-cell.left, cellHeight=cell.bottom-cell.top;
|
||||
TEXTMETRICW metrics{};GetTextMetricsW(dc,&metrics);
|
||||
RECT title{cell.left+scale(w,3),cell.bottom-scale(w,3)-metrics.tmHeight,cell.right-scale(w,3),cell.bottom-scale(w,3)};
|
||||
int top=cell.top+scale(w,4),height=std::min(scale(w,36),int(title.top)-top-scale(w,8));
|
||||
int width=std::min({scale(w,110),cellWidth-2*margin,height*2});
|
||||
const int labelGap=scale(w,8);
|
||||
const int height=std::min(scale(w,38),cellHeight-static_cast<int>(metrics.tmHeight)-labelGap-scale(w,4));
|
||||
const int width=std::min({scale(w,92),cellWidth-scale(w,16),height*2});
|
||||
if(width<8||height<8)return;
|
||||
int left=(cell.left+cell.right-width)/2;
|
||||
const int left=(cell.left+cell.right-width)/2;
|
||||
const int top=cell.top+(cellHeight-height-labelGap-metrics.tmHeight)/2;
|
||||
const int labelTop=top+height+labelGap;
|
||||
RECT title{cell.left+scale(w,5),labelTop,cell.right-scale(w,5),labelTop+metrics.tmHeight};
|
||||
bool active=!local&&v->snapshot.value("shareInput",false)&&v->snapshot.value("controlMode",0)!=0&&v->snapshot.value("controlPeer",std::string{})==id;
|
||||
COLORREF color=id==selected?RGB(0,105,190):active?RGB(30,130,90):RGB(105,120,133);
|
||||
const COLORREF color=highContrast ? GetSysColor(COLOR_WINDOWTEXT) :
|
||||
id==selected?RGB(0,91,166):active?RGB(22,105,72):RGB(79,97,115);
|
||||
auto pen=CreatePen(PS_SOLID,scale(w,2),color);SelectObject(dc,pen);
|
||||
auto brush=CreateSolidBrush(local?RGB(220,237,252):RGB(255,255,255));SelectObject(dc,brush);
|
||||
auto brush=CreateSolidBrush(highContrast ? GetSysColor(COLOR_WINDOW) : local?RGB(222,236,250):RGB(255,255,255));SelectObject(dc,brush);
|
||||
RoundRect(dc,left,top,left+width,top+height,scale(w,4),scale(w,4));SelectObject(dc,GetStockObject(NULL_BRUSH));DeleteObject(brush);
|
||||
int center=left+width/2;MoveToEx(dc,center,top+height,nullptr);LineTo(dc,center,top+height+scale(w,5));
|
||||
MoveToEx(dc,center-scale(w,12),top+height+scale(w,5),nullptr);LineTo(dc,center+scale(w,12),top+height+scale(w,5));
|
||||
RECT screen{left+scale(w,3),top+scale(w,2),left+width-scale(w,3),top+height-scale(w,2)};SetTextColor(dc,color);
|
||||
const wchar_t *caption=local?L"Local":active?L"Active":L"Paired";
|
||||
const wchar_t *caption=local?L"This PC":active?L"Active":online?L"Paired":L"Offline";
|
||||
if(height>=metrics.tmHeight+scale(w,4))DrawTextW(dc,caption,-1,&screen,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS);
|
||||
SetTextColor(dc,RGB(30,40,50));
|
||||
SetTextColor(dc,GetSysColor(COLOR_WINDOWTEXT));
|
||||
DrawTextW(dc,name.c_str(),-1,&title,DT_CENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
if(id==selected){RECT outline{cell.left+scale(w,2),cell.top+scale(w,2),cell.right-scale(w,2),cell.bottom-scale(w,2)};if(GetFocus()==w)DrawFocusRect(dc,&outline);}
|
||||
if(id==selected)
|
||||
{
|
||||
RECT outline{cell.left+scale(w,3),std::max<LONG>(cell.top+1,top-scale(w,3)),
|
||||
cell.right-scale(w,3),std::min(cell.bottom-1,title.bottom+scale(w,3))};
|
||||
auto border = CreateSolidBrush(highContrast ? GetSysColor(COLOR_HIGHLIGHT) : RGB(0,91,166));
|
||||
FrameRect(dc, &outline, border);
|
||||
DeleteObject(border);
|
||||
if(GetFocus()==w) { InflateRect(&outline,-scale(w,2),-scale(w,2)); DrawFocusRect(dc,&outline); }
|
||||
}
|
||||
SelectObject(dc,gridPen);DeleteObject(pen);
|
||||
};
|
||||
draw("",wide(v->snapshot.value("name",std::string("This PC"))),0,0,true);
|
||||
draw("",wide(v->snapshot.value("name",std::string("This PC"))),0,0,true,true);
|
||||
for(const auto &peer:v->snapshot.value("peers",nlohmann::json::array())){
|
||||
auto id=peer.at("id").get<std::string>();auto positions=v->snapshot.value("positions",nlohmann::json::object());
|
||||
if(positions.contains(id))draw(id,wide(peer.at("name").get<std::string>()),positions[id][0],positions[id][1],false);
|
||||
if(positions.contains(id))draw(id,wide(peer.at("name").get<std::string>()),positions[id][0],positions[id][1],false,peer.value("online",false));
|
||||
}
|
||||
if(v->dragMoved&&!v->dragPeer.empty()){
|
||||
auto point=g.point(v->dragPoint);auto r=g.cell(point.x,point.y);bool valid=true;
|
||||
|
||||
+38
-4
@@ -6,6 +6,7 @@ constexpr int LogChoice = 601, LogRows = 602, LogRefresh = 603, LogStatus = 604,
|
||||
LogDetails = 611, LogReset = 612;
|
||||
struct LogViewState
|
||||
{
|
||||
WindowPalette palette;
|
||||
std::vector<OperationLogRow> rows;
|
||||
std::vector<size_t> visible;
|
||||
int sortColumn = 0;
|
||||
@@ -185,13 +186,47 @@ LRESULT CALLBACK logProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (msg == WM_NCCREATE)
|
||||
{
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)((CREATESTRUCTW *)lp)->lpCreateParams);
|
||||
SetPropW(w, L"LogViewState", new LogViewState);
|
||||
auto *state = new LogViewState;
|
||||
state->palette.refresh();
|
||||
SetPropW(w, L"LogViewState", state);
|
||||
return TRUE;
|
||||
}
|
||||
if (!app)
|
||||
auto *state = logState(w);
|
||||
if (!app || !state)
|
||||
return DefWindowProcW(w, msg, wp, lp);
|
||||
switch (msg)
|
||||
{
|
||||
case WM_SETTINGCHANGE:
|
||||
case WM_SYSCOLORCHANGE:
|
||||
case WM_DWMCOLORIZATIONCOLORCHANGED:
|
||||
state->palette.refresh(msg == WM_DWMCOLORIZATIONCOLORCHANGED
|
||||
? std::optional<DWORD>{static_cast<DWORD>(wp)} : std::nullopt);
|
||||
RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN);
|
||||
if (msg == WM_DWMCOLORIZATIONCOLORCHANGED) return 0;
|
||||
break;
|
||||
case WM_ERASEBKGND:
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(w, &client);
|
||||
FillRect(reinterpret_cast<HDC>(wp), &client, state->palette.brush());
|
||||
return 1;
|
||||
}
|
||||
case WM_CTLCOLORBTN:
|
||||
if (GetDlgCtrlID(reinterpret_cast<HWND>(lp)) != LogProblems) break;
|
||||
[[fallthrough]];
|
||||
case WM_CTLCOLORSTATIC:
|
||||
{
|
||||
const auto dc = reinterpret_cast<HDC>(wp);
|
||||
SetTextColor(dc, GetSysColor(COLOR_WINDOWTEXT));
|
||||
if (GetDlgCtrlID(reinterpret_cast<HWND>(lp)) == LogDetails)
|
||||
{
|
||||
SetBkColor(dc, GetSysColor(COLOR_WINDOW));
|
||||
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_WINDOW));
|
||||
}
|
||||
SetBkColor(dc, state->palette.color());
|
||||
SetBkMode(dc, TRANSPARENT);
|
||||
return reinterpret_cast<LRESULT>(state->palette.brush());
|
||||
}
|
||||
case WM_COMMAND:
|
||||
if ((LOWORD(wp) == LogRefresh && HIWORD(wp) == BN_CLICKED) ||
|
||||
(LOWORD(wp) == LogChoice && HIWORD(wp) == CBN_SELCHANGE))
|
||||
@@ -251,7 +286,6 @@ LRESULT CALLBACK logProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
showLogDetails(w);
|
||||
if (((NMHDR *)lp)->code == LVN_COLUMNCLICK)
|
||||
{
|
||||
auto *state = logState(w);
|
||||
int column = ((NMLISTVIEW *)lp)->iSubItem;
|
||||
state->descending = state->sortColumn == column ? !state->descending : false;
|
||||
state->sortColumn = column;
|
||||
@@ -282,7 +316,7 @@ LRESULT CALLBACK logProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
resizeForDpi(w, wp, lp);
|
||||
return 0;
|
||||
case WM_NCDESTROY:
|
||||
delete logState(w);
|
||||
delete state;
|
||||
RemovePropW(w, L"LogViewState");
|
||||
app->logWindow = nullptr;
|
||||
disposeFont(w);
|
||||
|
||||
+154
-56
@@ -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 || item.CtlID == ClipboardAppPicker)
|
||||
{
|
||||
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);
|
||||
@@ -405,7 +480,7 @@ void browseActionApplication(HWND w, MouseProfileEditor &editor)
|
||||
addActionApplication(w, editor);
|
||||
}
|
||||
|
||||
void saveMouseAction(HWND w, MouseActionEditor &editor)
|
||||
void stageMouseAction(HWND w, MouseActionEditor &editor)
|
||||
{
|
||||
const auto choice = SendDlgItemMessageW(w, 734, CB_GETCURSEL, 0, 0);
|
||||
if (choice == CB_ERR) throw std::runtime_error("Choose an action.");
|
||||
@@ -482,7 +557,7 @@ LRESULT CALLBACK mouseActionEditorProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
return 0;
|
||||
}
|
||||
case IDOK:
|
||||
saveMouseAction(w, *editor);
|
||||
stageMouseAction(w, *editor);
|
||||
DestroyWindow(w);
|
||||
return 0;
|
||||
case IDCANCEL:
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -551,7 +626,7 @@ void showMouseActionEditor(HWND parent, SettingsView &view, int event)
|
||||
SendMessageW(spin, UDM_SETRANGE32, 1, MaxEditedMouseVolumeStep);
|
||||
SetDlgItemInt(w, MouseVolumeStepField,
|
||||
action && isMouseVolumeStep(action->type) ? action->volumeStep : DefaultMouseVolumeStep, FALSE);
|
||||
button(w, L"&Apply", IDOK, 248, 154, 100);
|
||||
button(w, L"&Use action", IDOK, 248, 154, 100);
|
||||
button(w, L"Cancel", IDCANCEL, 362, 154, 100);
|
||||
SendDlgItemMessageW(w, 734, CB_SETCURSEL, action ? static_cast<int>(action->type) + application : 0, 0);
|
||||
if (action && action->type == MouseActionType::Shortcut) value(w, 747, action->shortcut.format());
|
||||
@@ -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,20 +871,15 @@ 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);
|
||||
control(w, L"BUTTON", renaming ? L"&Rename" : L"&Add", WS_TABSTOP | BS_DEFPUSHBUTTON, IDOK, 248, 251, 100, 28);
|
||||
button(w, L"Cancel", IDCANCEL, 362, 251, 100);
|
||||
EnableWindow(owner, FALSE);
|
||||
showRequestedWindow(w);
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
#include <dwmapi.h>
|
||||
#include <optional>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline void fillSurface(HDC dc, const RECT &bounds, COLORREF color)
|
||||
{
|
||||
SetDCBrushColor(dc, color);
|
||||
FillRect(dc, &bounds, reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
class WindowPalette
|
||||
{
|
||||
public:
|
||||
WindowPalette() = default;
|
||||
WindowPalette(const WindowPalette &) = delete;
|
||||
WindowPalette &operator=(const WindowPalette &) = delete;
|
||||
~WindowPalette() { if (brush_) DeleteObject(brush_); }
|
||||
|
||||
void refresh(std::optional<DWORD> colorization = std::nullopt)
|
||||
{
|
||||
HIGHCONTRASTW contrast{sizeof(contrast)};
|
||||
highContrast = SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0) &&
|
||||
(contrast.dwFlags & HCF_HIGHCONTRASTON);
|
||||
const auto background = GetSysColor(COLOR_WINDOW);
|
||||
if (brush_) DeleteObject(brush_);
|
||||
brush_ = nullptr;
|
||||
if (highContrast) return;
|
||||
|
||||
DWORD argb{};
|
||||
BOOL opaque{};
|
||||
if (!colorization && SUCCEEDED(DwmGetColorizationColor(&argb, &opaque)))
|
||||
colorization = argb;
|
||||
const auto accent = colorization ? RGB(*colorization >> 16, *colorization >> 8, *colorization)
|
||||
: GetSysColor(COLOR_HIGHLIGHT);
|
||||
// Keep system window text readable even with a saturated accent.
|
||||
const auto tint = [](int base, int accentChannel) { return (base * 92 + accentChannel * 8 + 50) / 100; };
|
||||
color_ = RGB(tint(GetRValue(background), GetRValue(accent)),
|
||||
tint(GetGValue(background), GetGValue(accent)),
|
||||
tint(GetBValue(background), GetBValue(accent)));
|
||||
brush_ = CreateSolidBrush(color_);
|
||||
}
|
||||
|
||||
COLORREF color() const { return brush_ ? color_ : GetSysColor(COLOR_WINDOW); }
|
||||
HBRUSH brush() const { return brush_ ? brush_ : GetSysColorBrush(COLOR_WINDOW); }
|
||||
COLORREF edge() const { return highContrast ? GetSysColor(COLOR_WINDOWTEXT) : RGB(200, 213, 222); }
|
||||
COLORREF secondaryText() const { return highContrast ? GetSysColor(COLOR_WINDOWTEXT) : RGB(70, 91, 112); }
|
||||
bool highContrast{};
|
||||
|
||||
private:
|
||||
COLORREF color_{};
|
||||
HBRUSH brush_{};
|
||||
};
|
||||
} // namespace ks
|
||||
+185
-88
@@ -1,29 +1,52 @@
|
||||
#include "ui_sync_conflicts.inl"
|
||||
struct SyncView { HWND parent; App *app; bool actionError{}; };
|
||||
void updateSyncControls(HWND w, App &app)
|
||||
constexpr int SyncNow = 614;
|
||||
struct SyncView
|
||||
{
|
||||
bool enabled = checked(w, 601);
|
||||
bool savedEnabled = loadSyncConfig(app.data).enabled;
|
||||
for (int id : {602, 603, 604, 605, 606, 607, 610, 611, 613})
|
||||
App *app;
|
||||
bool initialized{}, actionError{}, forgetPassword{};
|
||||
SyncConfig base;
|
||||
};
|
||||
SyncView *syncEditor(HWND w)
|
||||
{
|
||||
return w ? reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA)) : nullptr;
|
||||
}
|
||||
SettingsView &syncSettingsView(HWND w)
|
||||
{
|
||||
return *reinterpret_cast<SettingsView *>(GetWindowLongPtrW(GetAncestor(w, GA_ROOT), GWLP_USERDATA));
|
||||
}
|
||||
SyncConfig syncFields(HWND w);
|
||||
bool syncDraftChanged(HWND w)
|
||||
{
|
||||
auto *view = syncEditor(w);
|
||||
return view && view->initialized && (view->forgetPassword ||
|
||||
GetWindowTextLengthW(GetDlgItem(w, 604)) != 0 || syncFields(w) != view->base);
|
||||
}
|
||||
void refreshSyncFooter(HWND w)
|
||||
{
|
||||
const auto root = GetAncestor(w, GA_ROOT);
|
||||
updateSettingsState(root, reinterpret_cast<SettingsView *>(GetWindowLongPtrW(root, GWLP_USERDATA)));
|
||||
}
|
||||
void updateSyncControls(HWND w, SyncView &view)
|
||||
{
|
||||
const bool enabled = checked(w, 601);
|
||||
const bool changed = syncDraftChanged(w);
|
||||
for (int id : {602, 603, 604, 605, 606, 607, 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");
|
||||
std::wstring status;
|
||||
if (!enabled)
|
||||
status = savedEnabled ? L"Click Save 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.";
|
||||
else
|
||||
status = app.syncCommand();
|
||||
auto *view = reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
if ((!view || !view->actionError) && value(w, 608) != status) value(w, 608, status);
|
||||
for (int id : {610, 611, 612, SyncNow})
|
||||
EnableWindow(GetDlgItem(w, id), view.base.enabled && !changed);
|
||||
EnableWindow(GetDlgItem(w, 609), view.base.enabled || !view.base.server.empty());
|
||||
value(w, 609, view.forgetPassword ? L"Keep saved &password" : L"Disconnect / &forget password");
|
||||
if (view.actionError) return;
|
||||
const auto status = changed ? L"Click Apply or Save in Settings to apply connection changes." :
|
||||
view.base.enabled ? view.app->syncCommand() :
|
||||
view.base.driveEnabled ? L"Automatic synchronization is using Google Drive." : L"Synchronization is disabled.";
|
||||
if (value(w, 608) != status) value(w, 608, status);
|
||||
}
|
||||
SyncConfig syncFields(HWND w)
|
||||
{
|
||||
SyncConfig c;
|
||||
auto c = reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA))->base;
|
||||
c.enabled = checked(w, 601);
|
||||
c.driveEnabled = checked(syncSettingsView(w).drive, DriveAutomatic);
|
||||
c.keepLocalLayouts = checked(w, 613);
|
||||
c.server = value(w, 602);
|
||||
while (!c.server.empty() && c.server.back() == L'/') c.server.pop_back();
|
||||
@@ -31,72 +54,116 @@ SyncConfig syncFields(HWND w)
|
||||
c.path = value(w, 606); c.authMount = value(w, 607);
|
||||
return c;
|
||||
}
|
||||
nlohmann::json collectSyncDraft(HWND w)
|
||||
{
|
||||
auto &view = *reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
auto config = syncFields(w);
|
||||
if (automaticSyncEnabled(config)) validateSyncConfig(config);
|
||||
Bytes protectedPassword;
|
||||
if (config.enabled && !view.forgetPassword)
|
||||
{
|
||||
auto password = value(w, 604);
|
||||
Bytes plain;
|
||||
struct ClearPassword
|
||||
{
|
||||
std::wstring &password;
|
||||
Bytes &plain;
|
||||
~ClearPassword()
|
||||
{
|
||||
SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t));
|
||||
SecureZeroMemory(plain.data(), plain.size());
|
||||
}
|
||||
} clear{password, plain};
|
||||
const auto first = reinterpret_cast<const unsigned char *>(password.data());
|
||||
plain.assign(first, first + password.size() * sizeof(wchar_t));
|
||||
if (!plain.empty()) protectedPassword = protect(plain);
|
||||
}
|
||||
return {{"config", encodeSyncConfig(config)}, {"base", encodeSyncConfig(view.base)},
|
||||
{"password", protectedPassword}, {"forget", view.forgetPassword}};
|
||||
}
|
||||
void reloadSyncEditor(HWND w)
|
||||
{
|
||||
if (!w) return;
|
||||
auto &view = *reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
view.initialized = false;
|
||||
view.forgetPassword = view.actionError = false;
|
||||
value(w, 604, L"");
|
||||
const auto &c = view.base = loadSyncConfig(view.app->data);
|
||||
check(w, 601, c.enabled); check(w, 613, c.keepLocalLayouts);
|
||||
const auto drive = syncSettingsView(w).drive;
|
||||
if (drive) check(drive, DriveAutomatic, c.driveEnabled);
|
||||
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);
|
||||
view.initialized = true;
|
||||
updateSyncControls(w, view);
|
||||
}
|
||||
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) reloadSyncEditor(w);
|
||||
else updateSyncControls(w, *v);
|
||||
SetTimer(w, 1, 1000, nullptr);
|
||||
}
|
||||
}
|
||||
if (msg == WM_TIMER)
|
||||
{
|
||||
updateSyncControls(w, *v->app);
|
||||
updateSyncControls(w, *v);
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_COMMAND)
|
||||
{
|
||||
int id = LOWORD(wp);
|
||||
if (id == 601 && HIWORD(wp) == BN_CLICKED)
|
||||
if ((id == 601 || id == 613 || (id >= 602 && id <= 607)) && v->initialized)
|
||||
{
|
||||
if (HIWORD(wp) != (id == 601 || id == 613 ? BN_CLICKED : EN_CHANGE)) return 0;
|
||||
if (id == 601 && checked(w, 601))
|
||||
{
|
||||
v->forgetPassword = false;
|
||||
const auto drive = syncSettingsView(w).drive;
|
||||
if (drive) check(drive, DriveAutomatic, false);
|
||||
}
|
||||
v->actionError = false;
|
||||
updateSyncControls(w, *v->app);
|
||||
updateSyncControls(w, *v);
|
||||
refreshSyncFooter(w);
|
||||
return 0;
|
||||
}
|
||||
if ((id == IDOK || id == 610 || id == 611 || id == 612) &&
|
||||
if ((id == SyncNow || id == 610 || id == 611 || id == 612 || id == 609) &&
|
||||
!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;
|
||||
auto c = loadSyncConfig(v->app->data);
|
||||
c.enabled = false;
|
||||
saveSyncConfig(v->app->data, c);
|
||||
forgetSyncPassword(c);
|
||||
check(w, 601, false);
|
||||
value(w, 604, L"");
|
||||
updateSyncControls(w, *v->app);
|
||||
value(w, 608, L"Disabled. Saved password removed. An in-flight server request may still finish.");
|
||||
KillTimer(w, 1);
|
||||
v->forgetPassword = !v->forgetPassword;
|
||||
check(w, 601, v->forgetPassword ? false : v->base.enabled);
|
||||
if (checked(w, 601))
|
||||
{
|
||||
const auto drive = syncSettingsView(w).drive;
|
||||
if (drive) check(drive, DriveAutomatic, false);
|
||||
}
|
||||
updateSyncControls(w, *v);
|
||||
refreshSyncFooter(w);
|
||||
return 0;
|
||||
}
|
||||
if (id == IDOK || id == 610 || id == 611)
|
||||
if (id == SyncNow || id == 610 || id == 611)
|
||||
{
|
||||
v->actionError = false;
|
||||
if (!checked(w, 601))
|
||||
{
|
||||
if (id != IDOK) return 0;
|
||||
auto c = loadSyncConfig(v->app->data);
|
||||
c.enabled = false;
|
||||
saveSyncConfig(v->app->data, c);
|
||||
value(w, 604, L"");
|
||||
updateSyncControls(w, *v->app);
|
||||
return 0;
|
||||
}
|
||||
if (id != IDOK && MessageBoxW(w, id == 610 ?
|
||||
if (id != SyncNow && 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;
|
||||
auto c = syncFields(w);
|
||||
if (c.enabled) validateSyncConfig(c);
|
||||
auto password = value(w, 604);
|
||||
try { if (!password.empty()) saveSyncPassword(c, password); }
|
||||
catch (...) { SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t)); throw; }
|
||||
SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t));
|
||||
value(w, 604, L"");
|
||||
saveSyncConfig(v->app->data, c);
|
||||
value(w, 608, v->app->syncCommand(id == 610 ? 2 : id == 611 ? 3 : 1));
|
||||
updateSyncControls(w, *v->app);
|
||||
updateSyncControls(w, *v);
|
||||
SetTimer(w, 1, 1000, nullptr);
|
||||
return 0;
|
||||
}
|
||||
@@ -111,44 +178,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"S&ync now", SyncNow, 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, SyncNow})
|
||||
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;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ struct SyncConflictView
|
||||
{
|
||||
HWND parent;
|
||||
App *app;
|
||||
int statusControl;
|
||||
std::vector<SyncConflict> conflicts;
|
||||
std::map<size_t, bool> choices;
|
||||
};
|
||||
@@ -40,8 +41,8 @@ LRESULT CALLBACK syncConflictsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
std::vector<SyncChoice> choices;
|
||||
for (const auto &[index, local] : v->choices) choices.push_back({v->conflicts.at(index), local});
|
||||
auto status = v->app->syncCommand(4, choices);
|
||||
value(v->parent, 608, status);
|
||||
if (status != L"Connecting to OpenBao...") throw std::runtime_error(utf8(status));
|
||||
value(v->parent, v->statusControl, status);
|
||||
if (!status.starts_with(L"Connecting to ")) throw std::runtime_error(utf8(status));
|
||||
DestroyWindow(w); return 0;
|
||||
}
|
||||
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
|
||||
@@ -51,18 +52,20 @@ 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);
|
||||
}
|
||||
void showSyncConflicts(HWND parent, App &app)
|
||||
void showSyncConflicts(HWND parent, App &app, int statusControl = 608)
|
||||
{
|
||||
auto conflicts = decodeSyncConflicts(app.syncConflictData());
|
||||
if (conflicts.empty()) { value(parent, 608, L"No pending conflicts. Run Sync to check for changes."); return; }
|
||||
if (conflicts.empty()) { value(parent, statusControl, 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);
|
||||
auto *v = new SyncConflictView{parent, &app, std::move(conflicts), {}};
|
||||
SetWindowLongPtrW(w, GWLP_HWNDPARENT, reinterpret_cast<LONG_PTR>(owner));
|
||||
auto *v = new SyncConflictView{parent, &app, statusControl, 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);
|
||||
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | WS_BORDER, 620, 18, 48, 760, 130);
|
||||
@@ -76,5 +79,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.111";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.7.4";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
+1046
-151
File diff suppressed because it is too large.
Load diff
@@ -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 6
|
||||
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'
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
#include "google_drive.h"
|
||||
#include "google_drive_oauth.h"
|
||||
#include "sync.h"
|
||||
#include "mouse_buttons.h"
|
||||
#include "json.hpp"
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace ks;
|
||||
using Json = nlohmann::json;
|
||||
|
||||
void check(bool condition, const char *message)
|
||||
{
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
Bytes bytes(std::string_view text) { return {text.begin(), text.end()}; }
|
||||
|
||||
const std::vector<Layout> Layouts{{{}, L"win:04090409"}, {{}, L"win:04220422"}};
|
||||
|
||||
void oauthProtocol()
|
||||
{
|
||||
using namespace google_drive_oauth;
|
||||
check(challengeFor("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") ==
|
||||
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "PKCE challenge differs from the RFC 7636 vector");
|
||||
check(callbackCode("GET /oauth/callback?state=right&code=a%2Bb HTTP/1.1", "right") == "a+b",
|
||||
"loopback rejected a correctly encoded authorization code");
|
||||
check(callbackCode("GET /oauth/callback?state=right&error=access_denied HTTP/1.1", "right") == "",
|
||||
"loopback did not report denied consent");
|
||||
for (const auto *request : {"GET /oauth/callback?state=other&code=x HTTP/1.1",
|
||||
"GET /oauth/callback?state=right&state=right&code=x HTTP/1.1",
|
||||
"GET /oauth/callback?state=right&code=%X1 HTTP/1.1",
|
||||
"GET /favicon.ico?state=right&code=x HTTP/1.1"})
|
||||
check(!callbackCode(request, "right"), "loopback accepted an unrelated or malformed request");
|
||||
}
|
||||
|
||||
void nativeBackup()
|
||||
{
|
||||
auto saved = decodeSettings({}, Layouts);
|
||||
saved.toggle = L"Ctrl+Alt+F10";
|
||||
saved.filesHotkey = L"";
|
||||
saved.direct[0] = L"Ctrl+F9";
|
||||
saved.snippets = {{L";hi", L"Hello", L"restored-snippet", {L"notepad"}}};
|
||||
saved.autoWords[L"en"] = {L"foobar"};
|
||||
saved.appLanguageSets[L"Editor"] = {{L"win:04220422"}, {L"notepad"}};
|
||||
saved.mouseBindings[GlobalMouseProfile][L"XButton1"] = {MouseActionType::Back};
|
||||
saved.mouseBindings[L"edge"][L"XButton1"] = {MouseActionType::Launch, {}, L"C:\\source-private\\secret.exe"};
|
||||
saved.mouseBindings[L"edge"][L"XButton2"] = {MouseActionType::Launch, {}, L"calc.exe"};
|
||||
saved.tesseractPath = L"C:\\private\\ocr.exe";
|
||||
saved.snippetTombstones = {L"source-tombstone"};
|
||||
saved.autostart = saved.elevatedAutostart = saved.writeLog = true;
|
||||
|
||||
auto destination = decodeSettings({}, Layouts);
|
||||
destination.toggle = L"Ctrl+Alt+F11";
|
||||
destination.tesseractPath = L"D:\\local\\ocr.exe";
|
||||
destination.writeLog = true;
|
||||
destination.snippetTombstones = {L"restored-snippet", L"destination-tombstone"};
|
||||
destination.mouseBindings[L"edge"][L"XButton1"] = {MouseActionType::Launch, {}, L"D:\\local\\tool.exe"};
|
||||
|
||||
const auto backup = encodeDriveBackup(saved);
|
||||
auto envelope = Json::parse(backup);
|
||||
const auto &stored = envelope.at("settings");
|
||||
for (auto key : {"writeLog", "startWithSystem", "autostartAsAdministrator", "tesseractPath", "snippetTombstones"})
|
||||
check(!stored.contains(key), "machine-specific field in native backup");
|
||||
check(!stored.at("mouseBindings").at("edge").contains("XButton1"), "local executable path in native backup");
|
||||
envelope["settings"]["openBaoPassword"] = "fake-provider-password";
|
||||
envelope["settings"]["tesseractPath"] = "C:\\injected\\ocr.exe";
|
||||
envelope["settings"]["mouseBindings"]["edge"]["XButton1"] = {{"action", "Launch application"},
|
||||
{"executable", "C:\\injected\\other.exe"}};
|
||||
const auto restored = restoreDriveBackup(bytes(envelope.dump()), destination, Layouts);
|
||||
check(restored.toggle == saved.toggle && restored.filesHotkey == L"" && restored.direct == saved.direct,
|
||||
"saved shortcuts failed to restore");
|
||||
check(restored.snippets.size() == 1 && restored.snippets[0].id == L"restored-snippet" &&
|
||||
restored.snippets[0].apps == std::vector<std::wstring>{L"notepad"}, "saved snippet failed to restore");
|
||||
check(restored.snippetTombstones == std::vector<std::wstring>{L"destination-tombstone"},
|
||||
"restore did not resurrect the snippet while preserving unrelated tombstones");
|
||||
check(restored.autoWords == saved.autoWords && restored.appLanguageSets == saved.appLanguageSets,
|
||||
"saved dictionary or language profile failed to restore");
|
||||
const auto &mouse = restored.mouseBindings.at(L"edge");
|
||||
check(mouse.at(L"XButton1").executable == L"D:\\local\\tool.exe" && mouse.at(L"XButton2").executable == L"calc.exe",
|
||||
"local mouse action or portable executable name failed to survive restore");
|
||||
check(restored.tesseractPath == destination.tesseractPath && restored.writeLog &&
|
||||
!restored.autostart && !restored.elevatedAutostart, "restore overwrote local preferences");
|
||||
check(destination.toggle == L"Ctrl+Alt+F11" && destination.snippets.empty(), "restore mutated its input draft");
|
||||
}
|
||||
|
||||
void automaticDriveProfile()
|
||||
{
|
||||
auto saved = decodeSettings({}, Layouts);
|
||||
saved.autostart = saved.writeLog = true;
|
||||
saved.tesseractPath = L"C:\\private\\ocr.exe";
|
||||
saved.mouseBindings[L"edge"][L"XButton1"] = {MouseActionType::Launch, {}, L"C:\\private\\tool.exe"};
|
||||
saved.snippetTombstones = {L"deleted-fixture"};
|
||||
auto local = saved, remote = saved;
|
||||
local.toggle = L"Ctrl+Alt+F10";
|
||||
local.autoWords[L"en"] = {L"localword"};
|
||||
remote.toggle = L"Ctrl+Alt+F11";
|
||||
remote.snippets = {{L";remote", L"Remote text", L"remote-id", {}}};
|
||||
const auto base = sharedDriveSettings(saved);
|
||||
const auto profile = Json::parse(base);
|
||||
check(!profile.contains("startWithSystem") && !profile.contains("writeLog") &&
|
||||
!profile.contains("tesseractPath") && profile.at("mouseBindings").empty(), "local data in Drive sync profile");
|
||||
const auto result = mergeSyncProfile(base, sharedDriveSettings(local), sharedDriveSettings(remote));
|
||||
check(result.conflicts.size() == 1 && result.conflicts.front().key == "/toggleHotkey",
|
||||
"Drive sync did not preserve concurrent changes to the same preference");
|
||||
for (const auto &payload : {result.local, result.remote})
|
||||
{
|
||||
const auto merged = restoreSharedDriveSettings(payload, saved, Layouts);
|
||||
check(merged.autostart && merged.writeLog && merged.tesseractPath == saved.tesseractPath &&
|
||||
merged.mouseBindings == saved.mouseBindings, "Drive sync overwrote local settings");
|
||||
check(merged.snippets.size() == 1 && merged.autoWords.at(L"en") == std::vector<std::wstring>{L"localword"} &&
|
||||
merged.snippetTombstones == saved.snippetTombstones, "Drive sync did not merge portable changes");
|
||||
}
|
||||
}
|
||||
|
||||
// Envelope and profile fields emitted by KSwitcher-New at 6a8d71d.
|
||||
constexpr auto PreviewSample = R"json({
|
||||
"format": "kswitcher-drive-backup-v1",
|
||||
"profile": {
|
||||
"settings": {
|
||||
"autocorrect": true,
|
||||
"mouse": {"enabled": false, "default_action": "Unassigned", "application": "", "application_action": "Unassigned"},
|
||||
"snippet": {"enabled": false, "trigger": "", "replacement": ""},
|
||||
"snippets": [{"enabled": true, "trigger": ";mail", "replacement": "Hello {cursor}", "apps": ["notepad"], "template": true}],
|
||||
"personal_dictionary": {"english": ["foobar"], "ukrainian": [], "never": ["skip"]}
|
||||
},
|
||||
"options": {
|
||||
"layouts": [{"id": "us", "layout": "English", "included": true, "shortcut": "Ctrl+F9"},
|
||||
{"id": "ua", "layout": "win:04220422", "included": true, "shortcut": ""}],
|
||||
"appLanguages": [{"id": "editor", "app": "notepad.exe", "languages": "win:04220422\nEnglish"}],
|
||||
"chatLanguages": [{"id": "chat", "app": "telegram.exe", "contact": "Example", "languages": "English"}],
|
||||
"snippets": [{"id": "preview-uuid", "enabled": true, "trigger": ";mail", "replacement": "Hello {cursor}", "scoped": true, "apps": "notePAD.exe"}],
|
||||
"mouseProfiles": [{"id": "*", "name": "Global", "enabled": true, "apps": ""},
|
||||
{"id": "editor", "name": "Editor mouse", "enabled": true, "apps": "notepad.exe"},
|
||||
{"id": "chrome", "name": "chrome", "enabled": true, "apps": ""}],
|
||||
"mouseActions": [{"id": "wheel", "profile": "editor", "event": "Wheel up", "action": "VolumeUp", "step": 7},
|
||||
{"id": "back", "profile": "chrome", "event": "First side button", "action": "Back"}],
|
||||
"mouseEvents": [{"id": "wheel-up", "name": "Scroll up", "signal": "Wheel up"}],
|
||||
"shortcuts.key-bindings.toggle": "Ctrl+Alt+F10",
|
||||
"general.correction.autoReplacements": "teh=the",
|
||||
"appearance.color-scheme.scheme": "dark"
|
||||
}
|
||||
}
|
||||
})json";
|
||||
|
||||
void previewBackup()
|
||||
{
|
||||
auto destination = decodeSettings({}, Layouts);
|
||||
destination.clipboard = L"Ctrl+F8";
|
||||
destination.tesseractPath = L"D:\\local\\ocr.exe";
|
||||
destination.autoWords[L"ru"] = {L"слово"};
|
||||
auto restored = restoreDriveBackup(bytes(PreviewSample), destination, Layouts);
|
||||
check(restored.autoCorrect && restored.toggle == L"Ctrl+Alt+F10" && restored.direct[0] == L"Ctrl+F9",
|
||||
"preview layout or shortcut mapping failed");
|
||||
check(restored.snippets.size() == 1 && restored.snippets[0].id == L"preview-uuid" &&
|
||||
restored.snippets[0].apps == std::vector<std::wstring>{L"notepad"} &&
|
||||
restored.snippets[0].text == L"Hello {cursor}", "preview snippet mapping failed");
|
||||
check(restored.autoWords.at(L"en").front() == L"foobar" && restored.autoNever.front() == L"skip" &&
|
||||
restored.autoReplacements.at(L"teh") == L"the" && restored.autoWords.at(L"ru") == destination.autoWords.at(L"ru"),
|
||||
"preview personal dictionary mapping or retention failed");
|
||||
check(restored.appLanguageSets.at(L"notepad").languages.size() == 2 &&
|
||||
restored.chatCycles.at(L"telegram\nExample").front() == L"win:04090409", "preview language profiles failed");
|
||||
check(restored.mouseProfileApplications.at(L"name:Editor mouse").contains(L"notepad") &&
|
||||
restored.mouseBindings.at(L"name:Editor mouse").at(L"Wheel up").volumeStep == 7 &&
|
||||
restored.customMouseEvents.at(L"Wheel up") == L"Scroll up" &&
|
||||
restored.mouseBindings.at(L"chrome").at(L"XButton1").type == MouseActionType::Back, "preview mouse mapping failed");
|
||||
check(restored.clipboard == destination.clipboard && restored.tesseractPath == destination.tesseractPath,
|
||||
"preview settings overwritten despite being absent from backup");
|
||||
}
|
||||
|
||||
void rejects(const Bytes &backup, std::string_view expected, const std::vector<Layout> &layouts = Layouts)
|
||||
{
|
||||
try { restoreDriveBackup(backup, decodeSettings({}, layouts), layouts); }
|
||||
catch (const std::runtime_error &error)
|
||||
{
|
||||
check(std::string_view(error.what()).find(expected) != std::string_view::npos, "unexpected restore error");
|
||||
return;
|
||||
}
|
||||
throw std::runtime_error("invalid backup was accepted");
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try
|
||||
{
|
||||
oauthProtocol();
|
||||
nativeBackup();
|
||||
automaticDriveProfile();
|
||||
previewBackup();
|
||||
rejects(bytes("not json"), "corrupt");
|
||||
rejects(bytes(R"({"format":"other"})"), "unsupported");
|
||||
rejects(bytes(R"({"format":"kswitcher-win32-drive-backup-v1","settings":{}})"), "invalid");
|
||||
rejects(Bytes(GoogleDriveBackupLimit + 1, 'a'), "2 MiB");
|
||||
rejects(bytes(PreviewSample), "Install the keyboard layouts", {});
|
||||
auto malformed = Json::parse(PreviewSample);
|
||||
malformed["profile"]["options"]["shortcuts.key-bindings.toggle"] = "not a shortcut";
|
||||
rejects(bytes(malformed.dump()), "invalid or conflict");
|
||||
std::cout << "Google Drive backup tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -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}");
|
||||
|
||||
+220
-21
@@ -3,6 +3,7 @@ param(
|
||||
[Parameter(Mandatory)][string]$Fixture,
|
||||
[switch]$SystemOpenOnly,
|
||||
[switch]$TerminalOnly,
|
||||
[int]$ScanEntries = 0,
|
||||
[string]$Node='node'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -12,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)]
|
||||
@@ -27,6 +32,22 @@ public static class FilesActivationUi {
|
||||
[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);
|
||||
@@ -35,6 +56,7 @@ public static class FilesActivationUi {
|
||||
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);
|
||||
@@ -86,6 +108,19 @@ 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) {
|
||||
@@ -172,7 +207,7 @@ $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
|
||||
@@ -214,6 +249,18 @@ try {
|
||||
$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
|
||||
@@ -221,6 +268,13 @@ try {
|
||||
$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 }
|
||||
@@ -231,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
|
||||
@@ -271,11 +368,55 @@ 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}'},
|
||||
@@ -319,6 +460,34 @@ try {
|
||||
([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)
|
||||
@@ -329,26 +498,29 @@ try {
|
||||
!(Read-Text $inputBox)
|
||||
}
|
||||
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
|
||||
Select-Row $left '[Test folder]'
|
||||
# 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 = [Windows.Forms.Clipboard]::GetDataObject()
|
||||
$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' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $nativeDraft
|
||||
(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' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $webviewDraft
|
||||
(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.'}
|
||||
@@ -356,22 +528,26 @@ try {
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
foreach($key in '^c','^{INSERT}') {
|
||||
[Windows.Forms.Clipboard]::SetText($webviewDraft)
|
||||
# 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" {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $outputSelection
|
||||
[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' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq 'Test folder'
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq 'Test folder'
|
||||
}
|
||||
} finally {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
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.'
|
||||
@@ -396,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]" }
|
||||
@@ -477,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 {
|
||||
@@ -490,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() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
+111
-16
@@ -1,6 +1,7 @@
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe",
|
||||
[switch]$OfflineWake,
|
||||
[switch]$FtpProfiles,
|
||||
[string]$Screenshot
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -21,6 +22,7 @@ public static class FilesDriveShortcutTest {
|
||||
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) {
|
||||
@@ -35,38 +37,119 @@ 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 ($OfflineWake) {
|
||||
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)
|
||||
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 'Recent folders' -or
|
||||
$rows[$row + 2] -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 { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 }
|
||||
[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 + 2)
|
||||
}
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 }
|
||||
[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($picker, $dc, 2)) { throw 'Could not render drive picker.' }
|
||||
if (![FilesDriveShortcutTest]::PrintWindow($list, $dc, 2)) { throw "FTP rows failed to render in panel $side." }
|
||||
} finally { $graphics.ReleaseHdc($dc) }
|
||||
return $bitmap
|
||||
} 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)
|
||||
@@ -137,5 +220,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()
|
||||
}
|
||||
}
|
||||
@@ -54,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);
|
||||
@@ -115,6 +117,18 @@ 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' }
|
||||
@@ -187,7 +201,7 @@ try {
|
||||
|
||||
~~~mermaid
|
||||
flowchart TD
|
||||
A[Render target] --> B[Result]
|
||||
A[Render target] -->|Transition| B[Result]
|
||||
~~~
|
||||
|
||||
~~~mermaid
|
||||
@@ -202,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')
|
||||
@@ -233,6 +249,30 @@ 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'
|
||||
@@ -274,7 +314,18 @@ const value = 42;
|
||||
[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.'
|
||||
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Checking a task modified the read-only file.' }
|
||||
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'
|
||||
@@ -328,8 +379,19 @@ const value = 42;
|
||||
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.'
|
||||
@@ -380,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
|
||||
@@ -424,6 +487,8 @@ const value = 42;
|
||||
$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) {
|
||||
|
||||
@@ -3,7 +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 = ['terminal-enter', 'terminal-copy', 'terminal-select-output'].includes(scenario);
|
||||
const terminalScenario = scenario.startsWith('terminal-');
|
||||
let socket;
|
||||
const pending = new Map();
|
||||
let sequence = 0;
|
||||
@@ -69,7 +69,10 @@ await new Promise((resolve, reject) => {
|
||||
});
|
||||
|
||||
try {
|
||||
if (scenario === 'terminal-select-output') {
|
||||
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;
|
||||
@@ -82,6 +85,8 @@ try {
|
||||
})()`), '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 }
|
||||
@@ -112,6 +117,14 @@ try {
|
||||
'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);
|
||||
@@ -120,14 +133,59 @@ try {
|
||||
await waitFor(() => evaluate(`document.querySelector('img[alt="Missing image"]')?.title === 'Image unavailable'`),
|
||||
'missing image feedback');
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => box.checked)`), [false, true]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [true, false]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return 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';
|
||||
@@ -209,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) }
|
||||
|
||||
+110
-10
@@ -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,6 +271,8 @@ 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))
|
||||
@@ -267,6 +284,73 @@ try {
|
||||
[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 })) {
|
||||
@@ -290,12 +374,27 @@ try {
|
||||
Write-Output 'Verified folder navigation repaints only the panel that changes directories.'
|
||||
}
|
||||
$clicks=if(!$KeyboardCursorOnly){
|
||||
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
|
||||
@(@{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
|
||||
@@ -303,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
|
||||
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user