Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3dd4edeb2c | ||
|
|
edb259e6bb | ||
|
|
9e287c3a1d | ||
|
|
5eda68a7a2 | ||
|
|
6cbb0639a1 | ||
|
|
2a6f9c7841 | ||
|
|
94b22fdd52 | ||
|
|
0d293429df | ||
|
|
83a099ab25 | ||
|
|
dfa2e38a0a | ||
|
|
24905e8ced | ||
|
|
b28a1f2e4d | ||
|
|
fde74c1a51 | ||
|
|
81fbe6a216 | ||
|
|
f1e5b2b772 | ||
|
|
e9e8b2099e | ||
|
|
dbb1fe166e | ||
|
|
98de2dc010 | ||
|
|
696f48209d | ||
|
|
5fae129ec0 | ||
|
|
870ad6c2b3 | ||
|
|
15b251e7fb |
No files matched your search
+46
-5
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.7.3 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.7.4 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
@@ -26,6 +26,11 @@ add_custom_target(check-files-search-arrow
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>"
|
||||
DEPENDS KSwitcherFiles
|
||||
VERBATIM)
|
||||
add_custom_target(check-files-quick-view
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_quick_view.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>"
|
||||
DEPENDS KSwitcherFiles
|
||||
VERBATIM)
|
||||
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet)
|
||||
if(MSVC)
|
||||
@@ -48,15 +53,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 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")
|
||||
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)
|
||||
"${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)
|
||||
@@ -87,7 +109,7 @@ if(MSVC)
|
||||
else()
|
||||
target_link_options(KSwitcherFarSnippetTests PRIVATE -municode -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
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)
|
||||
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)
|
||||
@@ -221,6 +243,7 @@ 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)
|
||||
@@ -278,8 +301,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}")
|
||||
@@ -306,3 +336,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)
|
||||
+37
-1
@@ -429,6 +429,21 @@ Warning і початковий фокус на No.
|
||||
|
||||
## Панелі
|
||||
|
||||
- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук
|
||||
файлів у поточній локальній папці та її підпапках. Поле приймає повне
|
||||
ім’я або маску без урахування регістру. `*` відповідає довільній
|
||||
послідовності символів, `?` — одному символу. Приховані та системні
|
||||
елементи можна включити прапорцем. Пошук не обходить junction та інші
|
||||
посилання на каталоги. Esc під час пошуку зупиняє обхід і показує знайдене.
|
||||
Результати відкриваються в тій самій панелі з відносними шляхами.
|
||||
Enter або подвійний клік відкриває папку й ставить курсор на файл.
|
||||
Esc у результатах повертає вихідну папку, курсор і позначки.
|
||||
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
|
||||
або поточним файлом, використовуючи папку іншої панелі як призначення.
|
||||
F8 і Shift+Delete використовують звичайні підтвердження. Успішно
|
||||
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
|
||||
з тією самою маскою й видимістю прихованих файлів.
|
||||
|
||||
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
|
||||
у відкритих локальних папках. Фокус залишається там, де був, а курсор
|
||||
лишається на поточному елементі, якщо той ще існує.
|
||||
@@ -469,7 +484,28 @@ Warning і початковий фокус на No.
|
||||
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
|
||||
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
|
||||
тексту й Markdown у сусідній панелі. Перегляд слідує за курсором активної
|
||||
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
|
||||
Під час перегляду файлові операції з призначенням у сусідній панелі
|
||||
пропонують спершу закрити Quick View.
|
||||
|
||||
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
|
||||
останні відвідані локальні папки. Повторний візит підіймає один запис
|
||||
угору, порядок зберігається після перезапуску. Enter або клік відкриває
|
||||
шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис.
|
||||
|
||||
- У локальному заголовку кнопки ← та → переходять назад і вперед
|
||||
в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..`
|
||||
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
|
||||
а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі.
|
||||
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
|
||||
трикрапка відкриває прихованих предків, а права — приховані папки
|
||||
попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L
|
||||
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
|
||||
а Esc повертає до тих самих панелей і курсора.
|
||||
|
||||
- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі.
|
||||
|
||||
## Спільні елементи діалогів
|
||||
|
||||
|
||||
+3
-2
@@ -40,8 +40,9 @@ the local resident process running and log downloads enabled on the remote PC.
|
||||
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.
|
||||
Only running LAN-enabled KSwitcher instances appear, not generic network devices.
|
||||
In wide windows, Pairing and Input sharing appear side by side. In narrow
|
||||
windows, they stack above Diagnostic logs. Connection help is under Input sharing.
|
||||
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.
|
||||
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
|
||||
|
||||
@@ -610,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.
|
||||
@@ -710,6 +710,54 @@ 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)
|
||||
|
||||
Open **Settings → Sync → OpenBao**. Synchronization remains disabled
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
# 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.
|
||||
|
||||
@@ -1 +1 @@
|
||||
64914772013a5cd30a1065c2ecd3c55f7ed92aa26172ddfc914c4fc5ecfa1710 KSwitcher-win-x64.zip
|
||||
0209951cbe8c5a202dba12a807895ce7146dc6640f96704f6a4aa9afaa4fd3af KSwitcher-win-x64.zip
|
||||
+72
-72
@@ -1,166 +1,166 @@
|
||||
{
|
||||
"version": "0.7.3",
|
||||
"version": "0.7.4",
|
||||
"schema": 1,
|
||||
"files": [
|
||||
{
|
||||
"path": "KSwitcher.exe",
|
||||
"size": 6045773,
|
||||
"sha256": "920fbc0f3d5ec8a7e99b5ebe859a53d459444f0bdc351a029ceff904861b7a52"
|
||||
"size": 3082752,
|
||||
"sha256": "31a41c6ecc3387fc9f2b3f228ed64fa916d723654c02dc19bbbb558f94def4b8",
|
||||
"path": "KSwitcher.exe"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"size": 6153758,
|
||||
"sha256": "74c18b8f199e1b40379c80426185a34977d6304adbf84cc67ba5a67d0e71c0f3"
|
||||
"size": 2832384,
|
||||
"sha256": "b993c050a96215aa63be97e9f05764ead13fcaf4b68fbb99f3d2f9a7d49a629a",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"size": 5790537,
|
||||
"sha256": "55d755ac25b980bc931d9cd4167ae83a0ca799060428672018b18ccfab8eaf34"
|
||||
"size": 3187712,
|
||||
"sha256": "eff5921b9067e0f4805c83d3cea10ddaa32b0b4e29f408b71b1004f78754afb9",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
},
|
||||
{
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"size": 9488877,
|
||||
"sha256": "7024d127e42125963c77d2acd7eacc9fc5d01a14c3061b09800c9a55e8e66548"
|
||||
"size": 4409344,
|
||||
"sha256": "569d016d1eff9519cd33aa848723cea0365cbebe9333ed390245d098c4074d8e",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
},
|
||||
{
|
||||
"path": "WebView2Loader.dll",
|
||||
"size": 194912,
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"path": "WebView2Loader.dll"
|
||||
},
|
||||
{
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"size": 1103,
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"path": "terminal/addon-fit-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "terminal/addon-fit.js",
|
||||
"size": 1521,
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"path": "terminal/addon-fit.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/index.html",
|
||||
"size": 527,
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"path": "terminal/index.html"
|
||||
},
|
||||
{
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"size": 1073,
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"path": "terminal/markdown-it-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "terminal/markdown-it.js",
|
||||
"size": 100786,
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"path": "terminal/markdown-it.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/markdown.html",
|
||||
"size": 3599,
|
||||
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094"
|
||||
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
|
||||
"path": "terminal/markdown.html"
|
||||
},
|
||||
{
|
||||
"path": "terminal/markdown.js",
|
||||
"size": 17575,
|
||||
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8"
|
||||
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
|
||||
"path": "terminal/markdown.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"size": 1089,
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"path": "terminal/mermaid-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "terminal/mermaid.js",
|
||||
"size": 5537838,
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"path": "terminal/mermaid.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/terminal.js",
|
||||
"size": 5065,
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
|
||||
"path": "terminal/terminal.js"
|
||||
},
|
||||
{
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"size": 1261,
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"path": "terminal/xterm-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "terminal/xterm.css",
|
||||
"size": 7112,
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"path": "terminal/xterm.css"
|
||||
},
|
||||
{
|
||||
"path": "terminal/xterm.js",
|
||||
"size": 488663,
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"path": "terminal/xterm.js"
|
||||
},
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"size": 4401,
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"path": "LICENSE"
|
||||
},
|
||||
{
|
||||
"path": "json-LICENSE.txt",
|
||||
"size": 1096,
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"path": "json-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"path": "files-text-license.txt",
|
||||
"size": 883,
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"path": "files-text-license.txt"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"size": 101399,
|
||||
"sha256": "e22bf65e81befdcc3b3b12803f3e9c2fdfa5c81eb5f3736a6077dd30a8abf74b"
|
||||
"size": 105515,
|
||||
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01",
|
||||
"path": "README.md"
|
||||
},
|
||||
{
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"size": 12550,
|
||||
"sha256": "391567369ae742c252ebe01811c67c729f0e884ba2aef200e9e087bcd8017c2f"
|
||||
"size": 12804,
|
||||
"sha256": "f5bfc48e44af14dd6c45f56f689b4034ef1f7bdaca02f9d15ebc32af387366cf",
|
||||
"path": "LAN-PREVIEW.md"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/en.txt",
|
||||
"size": 732485,
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"path": "dictionaries/en.txt"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"size": 20566,
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/README.md",
|
||||
"size": 2265,
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"path": "dictionaries/README.md"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/ru.txt",
|
||||
"size": 1109134,
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"path": "dictionaries/ru.txt"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/sources.json",
|
||||
"size": 1280,
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"path": "dictionaries/sources.json"
|
||||
},
|
||||
{
|
||||
"path": "dictionaries/uk.txt",
|
||||
"size": 940799,
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"path": "dictionaries/uk.txt"
|
||||
},
|
||||
{
|
||||
"path": "tools/README.txt",
|
||||
"size": 993,
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"path": "tools/README.txt"
|
||||
},
|
||||
{
|
||||
"path": "tools/StayHere.exe",
|
||||
"size": 540583,
|
||||
"sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c"
|
||||
"size": 133120,
|
||||
"sha256": "ba891b6cc5d35d26520fa9ad34e136124e90ed10e0cff2f25dedadd0b48fb88e",
|
||||
"path": "tools/StayHere.exe"
|
||||
},
|
||||
{
|
||||
"path": "tools/StayHere-README.md",
|
||||
"size": 2796,
|
||||
"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,20 +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 tests/input_pause.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe
|
||||
& $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' }
|
||||
& .\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 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
|
||||
& $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
|
||||
@@ -137,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')
|
||||
@@ -163,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@"
|
||||
+7
-3
@@ -3,6 +3,10 @@
|
||||
#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"
|
||||
@@ -10,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
201 RCDATA "update.ps1"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 0,7,3,0
|
||||
PRODUCTVERSION 0,7,3,0
|
||||
FILEVERSION 0,7,4,0
|
||||
PRODUCTVERSION 0,7,4,0
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
BEGIN
|
||||
@@ -21,7 +25,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
||||
VALUE "ProductName", "KSwitcher"
|
||||
VALUE "FileVersion", "0.7.3"
|
||||
VALUE "FileVersion", "0.7.4"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
@@ -407,3 +407,28 @@ 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: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
@@ -5,4 +5,12 @@
|
||||
#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
|
||||
@@ -10,6 +10,10 @@
|
||||
body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
|
||||
main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); }
|
||||
nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; }
|
||||
:root.quick-view body { padding: 8px 12px; }
|
||||
:root.quick-view nav { display: none; }
|
||||
:root.quick-view main > :first-child { margin-block-start: 0; }
|
||||
:root.quick-view h1 { font-size: 1.4em; }
|
||||
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
|
||||
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
|
||||
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
|
||||
|
||||
@@ -247,12 +247,13 @@ searchPrevious.addEventListener('click', () => stepSearch(-1));
|
||||
searchNext.addEventListener('click', () => stepSearch(1));
|
||||
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
|
||||
|
||||
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave }) {
|
||||
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact }) {
|
||||
const current = ++generation;
|
||||
if (keepPosition) scroll = window.scrollY;
|
||||
else closeSearch();
|
||||
document.documentElement.classList.remove('rendered');
|
||||
document.title = title;
|
||||
document.documentElement.classList.toggle('quick-view', Boolean(compact));
|
||||
previewRevision = revision;
|
||||
renderContent(text, canSave);
|
||||
const headings = new Set();
|
||||
@@ -264,7 +265,7 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
|
||||
headings.add(id);
|
||||
}
|
||||
images = Array.from(content.querySelectorAll('img[data-path]'));
|
||||
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
|
||||
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current, revision }));
|
||||
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
|
||||
for (const [index, block] of blocks.entries()) {
|
||||
try {
|
||||
@@ -289,7 +290,7 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
|
||||
restorePosition({ fragment, scroll });
|
||||
document.documentElement.classList.add('rendered');
|
||||
if (!search.hidden) updateSearch(false);
|
||||
send('rendered');
|
||||
send('rendered', { revision });
|
||||
}
|
||||
|
||||
content.addEventListener('change', ({ target }) => {
|
||||
@@ -350,7 +351,7 @@ bridge.addEventListener('message', ({ data }) => {
|
||||
document.documentElement.classList.remove('rendered');
|
||||
content.replaceChildren();
|
||||
}
|
||||
if (message.action === 'render') void render(message).catch(() => send('failed'));
|
||||
if (message.action === 'render') void render(message).catch(() => send('failed', { revision: message.revision }));
|
||||
if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) {
|
||||
if (!message.saved) pendingTask.target.checked = !pendingTask.checked;
|
||||
pendingTask = undefined;
|
||||
|
||||
+74
-31
@@ -6,6 +6,7 @@
|
||||
#include "lan_clipboard_image.h"
|
||||
#include "lan_files.h"
|
||||
#include "configuration.h"
|
||||
#include "google_drive.h"
|
||||
#include "diagnostics.h"
|
||||
#include "paste_probe.h"
|
||||
#include "utilities.h"
|
||||
@@ -143,7 +144,8 @@ ULONG_PTR snippetReplayMarker()
|
||||
return reinterpret_cast<ULONG_PTR>(&marker);
|
||||
}
|
||||
constexpr int OpenFiles = 25, FilesHotkeyFirst = 0x4B10, FilesHotkeySecond = 0x4B11;
|
||||
constexpr int ToggleInputProcessing = 26;
|
||||
constexpr int ToggleInputProcessing = 26, DonateViaMonobank = 27, OpenHelp = 28, OpenAbout = 16;
|
||||
constexpr wchar_t MonobankDonationUrl[] = L"https://send.monobank.ua/jar/88h2TddKfS";
|
||||
constexpr int ShortcutProbeId = FilesHotkeySecond + 1;
|
||||
constexpr UINT_PTR PauseDrainTimer = 23;
|
||||
|
||||
@@ -806,6 +808,7 @@ App::App(HINSTANCE h, bool test, const std::filesystem::path &dataRoot, HWND ser
|
||||
App::~App()
|
||||
{
|
||||
releaseInputHooks();
|
||||
if (helpWindow) DestroyWindow(helpWindow);
|
||||
if (snippetPopup) DestroyWindow(snippetPopup);
|
||||
lanService.reset();
|
||||
stopBrowserChatMonitor();
|
||||
@@ -940,46 +943,60 @@ constexpr UINT TrayInputPulseMs = 450;
|
||||
|
||||
namespace
|
||||
{
|
||||
HICON trayInputIcon(HICON base, int width, int height, uint32_t color)
|
||||
HBITMAP trayIconBitmap(HICON base, int width, int height, void **data = nullptr)
|
||||
{
|
||||
if (!base || width < 8 || height < 8) return nullptr;
|
||||
if (!base || width < 1 || height < 1) return nullptr;
|
||||
BITMAPINFO bitmapInfo{};
|
||||
bitmapInfo.bmiHeader = {sizeof(BITMAPINFOHEADER), width, -height, 1, 32, BI_RGB};
|
||||
void *bits{};
|
||||
HBITMAP bitmap = CreateDIBSection(nullptr, &bitmapInfo, DIB_RGB_COLORS, &bits, nullptr, 0);
|
||||
if (!bitmap) return nullptr;
|
||||
HDC dc = CreateCompatibleDC(nullptr);
|
||||
HICON icon{};
|
||||
BOOL drawn = FALSE;
|
||||
if (dc)
|
||||
{
|
||||
auto previous = SelectObject(dc, bitmap);
|
||||
auto pixels = static_cast<uint32_t *>(bits);
|
||||
std::fill_n(pixels, size_t(width) * height, 0);
|
||||
if (DrawIconEx(dc, 0, 0, base, width, height, 0, nullptr, DI_NORMAL))
|
||||
{
|
||||
GdiFlush();
|
||||
const int radius = std::max(3, MulDiv(std::min(width, height), 3, 16));
|
||||
const int cx = width - 1 - radius, cy = height - 1 - radius;
|
||||
for (int y = -radius; y <= radius; ++y)
|
||||
for (int x = -radius; x <= radius; ++x)
|
||||
{
|
||||
const int distance = x * x + y * y;
|
||||
if (distance <= radius * radius)
|
||||
pixels[(cy + y) * width + cx + x] = distance <= (radius - 1) * (radius - 1)
|
||||
? color : 0xff242424;
|
||||
}
|
||||
// The 32-bit DIB supplies the transparency. The fallback mask is initialized as well.
|
||||
std::vector<unsigned char> maskBits(size_t((width + 15) / 16) * 2 * height);
|
||||
if (auto mask = CreateBitmap(width, height, 1, 1, maskBits.data()))
|
||||
{
|
||||
ICONINFO info{TRUE, 0, 0, mask, bitmap};
|
||||
icon = CreateIconIndirect(&info);
|
||||
DeleteObject(mask);
|
||||
}
|
||||
}
|
||||
std::fill_n(static_cast<uint32_t *>(bits), size_t(width) * height, 0);
|
||||
drawn = DrawIconEx(dc, 0, 0, base, width, height, 0, nullptr, DI_NORMAL);
|
||||
GdiFlush();
|
||||
SelectObject(dc, previous);
|
||||
DeleteDC(dc);
|
||||
}
|
||||
if (drawn)
|
||||
{
|
||||
if (data) *data = bits;
|
||||
return bitmap;
|
||||
}
|
||||
DeleteObject(bitmap);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HICON trayInputIcon(HICON base, int width, int height, uint32_t color)
|
||||
{
|
||||
if (width < 8 || height < 8) return nullptr;
|
||||
void *bits{};
|
||||
const auto bitmap = trayIconBitmap(base, width, height, &bits);
|
||||
if (!bitmap) return nullptr;
|
||||
auto pixels = static_cast<uint32_t *>(bits);
|
||||
const int radius = std::max(3, MulDiv(std::min(width, height), 3, 16));
|
||||
const int cx = width - 1 - radius, cy = height - 1 - radius;
|
||||
for (int y = -radius; y <= radius; ++y)
|
||||
for (int x = -radius; x <= radius; ++x)
|
||||
{
|
||||
const int distance = x * x + y * y;
|
||||
if (distance <= radius * radius)
|
||||
pixels[(cy + y) * width + cx + x] = distance <= (radius - 1) * (radius - 1)
|
||||
? color : 0xff242424;
|
||||
}
|
||||
// The 32-bit DIB supplies the transparency. The fallback mask is initialized as well.
|
||||
std::vector<unsigned char> maskBits(size_t((width + 15) / 16) * 2 * height);
|
||||
HICON icon{};
|
||||
if (auto mask = CreateBitmap(width, height, 1, 1, maskBits.data()))
|
||||
{
|
||||
ICONINFO info{TRUE, 0, 0, mask, bitmap};
|
||||
icon = CreateIconIndirect(&info);
|
||||
DeleteObject(mask);
|
||||
}
|
||||
DeleteObject(bitmap);
|
||||
return icon;
|
||||
}
|
||||
@@ -3055,8 +3072,9 @@ void App::captureHistory()
|
||||
return;
|
||||
auto owner = GetClipboardOwner();
|
||||
auto app = processName(owner ? owner : GetForegroundWindow());
|
||||
const auto appKey = lower(app);
|
||||
for (auto &name : config.excluded)
|
||||
if (lower(name) == lower(app))
|
||||
if (snippetAppName(name) == appKey)
|
||||
return;
|
||||
if(!config.history){
|
||||
auto clip=readClipboard(window,(size_t)config.maxImageMiB*1024*1024,ClipboardRead::All,sequence);
|
||||
@@ -3237,7 +3255,22 @@ void App::trayMenu()
|
||||
updateRunning ? L"&Update (checking / preparing…)" :
|
||||
availableUpdate.empty() ? L"&Update" : L"&Update (new version available)");
|
||||
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
|
||||
AppendMenuW(menu, MF_STRING, 16, L"&About KSwitcher");
|
||||
AppendMenuW(menu, MF_STRING, DonateViaMonobank, L"&Donate via Monobank");
|
||||
const int iconSize = MulDiv(16, GetDpiForWindow(window), 96);
|
||||
const auto donateIcon = static_cast<HICON>(LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER_DONATE),
|
||||
IMAGE_ICON, iconSize, iconSize, LR_SHARED));
|
||||
const auto donateBitmap = trayIconBitmap(donateIcon, iconSize, iconSize);
|
||||
if (donateBitmap)
|
||||
{
|
||||
MENUITEMINFOW item{sizeof(item), MIIM_BITMAP};
|
||||
item.hbmpItem = donateBitmap;
|
||||
SetMenuItemInfoW(menu, DonateViaMonobank, FALSE, &item);
|
||||
}
|
||||
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
|
||||
HMENU help = CreatePopupMenu();
|
||||
AppendMenuW(help, MF_STRING, OpenHelp, L"&User guide");
|
||||
AppendMenuW(help, MF_STRING, OpenAbout, L"&About KSwitcher");
|
||||
AppendMenuW(menu, MF_POPUP, reinterpret_cast<UINT_PTR>(help), L"H&elp");
|
||||
AppendMenuW(menu, MF_STRING, 17, L"E&xit");
|
||||
POINT pt{};
|
||||
GetCursorPos(&pt);
|
||||
@@ -3246,6 +3279,7 @@ void App::trayMenu()
|
||||
showMenuAccessKeys(menu);
|
||||
int cmd = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_RIGHTBUTTON, pt.x, pt.y, 0, window, nullptr);
|
||||
DestroyMenu(menu);
|
||||
if (donateBitmap) DeleteObject(donateBitmap);
|
||||
PostMessageW(window, WM_NULL, 0, 0);
|
||||
try
|
||||
{
|
||||
@@ -3296,7 +3330,14 @@ void App::trayMenu()
|
||||
case 15:
|
||||
ShellExecuteW(window, L"open", data.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
|
||||
break;
|
||||
case 16:
|
||||
case OpenHelp:
|
||||
showHelp(*this);
|
||||
break;
|
||||
case DonateViaMonobank:
|
||||
if (reinterpret_cast<INT_PTR>(ShellExecuteW(window, L"open", MonobankDonationUrl, nullptr, nullptr, SW_SHOWNORMAL)) <= 32)
|
||||
throw std::runtime_error("Could not open the Monobank donation page.");
|
||||
break;
|
||||
case OpenAbout:
|
||||
MessageBoxW(window,
|
||||
(std::wstring(L"KSwitcher ") + AppVersion + L"\nNative C++ / Win32 keyboard and clipboard utility\n\nBased on "
|
||||
L"Typlo by bitcodepro. MIT license.\nHistory is encrypted for your Windows "
|
||||
@@ -3862,6 +3903,8 @@ int App::execute()
|
||||
continue;
|
||||
if (logWindow && IsDialogMessageW(logWindow, &msg))
|
||||
continue;
|
||||
if (helpWindow && IsDialogMessageW(helpWindow, &msg))
|
||||
continue;
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
|
||||
@@ -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{};
|
||||
@@ -105,6 +105,7 @@ class App
|
||||
|
||||
private:
|
||||
friend struct InputRegressionAccess;
|
||||
friend void commitConfigurationSupplement(App &, const Bytes &);
|
||||
void releaseIdleMemory(ULONGLONG now);
|
||||
void applySettings(const Settings &, bool validateOcrInstallation, const std::function<void()> &commit = {});
|
||||
void checkAutostartPath();
|
||||
@@ -158,6 +159,7 @@ class App
|
||||
ULONGLONG nextSync{}, syncRetryAfter{};
|
||||
SyncResult syncResult;
|
||||
SyncConfig syncConnection;
|
||||
std::string syncDriveKey;
|
||||
SyncConfig conflictConnection;
|
||||
std::vector<SyncConflict> pendingSyncConflicts;
|
||||
Bytes syncSnapshot;
|
||||
@@ -231,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; }
|
||||
|
||||
+12
-2
@@ -52,9 +52,19 @@ void commitConfigurationSupplement(App &app, const Bytes &supplement)
|
||||
{
|
||||
const auto &sync = draft.at("sync");
|
||||
const auto config = decodeSyncConfig(sync.at("config").get<Bytes>());
|
||||
if (loadSyncConfig(app.data) != decodeSyncConfig(sync.at("base").get<Bytes>()))
|
||||
throw std::runtime_error("The OpenBao connection changed. Reopen Settings to edit the current connection.");
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
+446
-53
File diff suppressed because it is too large.
Load diff
@@ -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;}
|
||||
}
|
||||
+200
-62
@@ -14,7 +14,6 @@
|
||||
#include <commctrl.h>
|
||||
#include <shellapi.h>
|
||||
#include <shlobj.h>
|
||||
#include <propkey.h>
|
||||
#include <atomic>
|
||||
#include <windowsx.h>
|
||||
#include <commdlg.h>
|
||||
@@ -741,13 +740,13 @@ class TextWindow
|
||||
{
|
||||
public:
|
||||
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend,
|
||||
std::string_view fragment,TextOpenOptions options)
|
||||
std::string_view fragment,TextOpenOptions options,bool quickView=false)
|
||||
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
edit(editable), draft(options.draft), embedded(quickView), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
search{dialogs}, previewFragment(fragment)
|
||||
{
|
||||
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
|
||||
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
|
||||
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
|
||||
if(options.encoding!=TextEncoding::automatic)
|
||||
{
|
||||
newFormat.encoding=options.encoding;
|
||||
@@ -773,6 +772,7 @@ public:
|
||||
HWND window{}, editor{};
|
||||
bool handleKey(const MSG &message);
|
||||
void goToFragment(std::string_view fragment);
|
||||
void previewFile(const std::filesystem::path &path);
|
||||
std::filesystem::path original;
|
||||
const std::string peerId;
|
||||
|
||||
@@ -781,7 +781,7 @@ private:
|
||||
std::unique_ptr<TextDocument> document;
|
||||
std::wstring filename;
|
||||
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
|
||||
bool draft{};
|
||||
bool draft{}, embedded{};
|
||||
TextSaveFormat newFormat;
|
||||
std::filesystem::path pendingSavePath;
|
||||
HICON smallIcon{},largeIcon{};
|
||||
@@ -863,6 +863,20 @@ private:
|
||||
static constexpr UINT_PTR openTimer = 2;
|
||||
static constexpr UINT_PTR previewTimer = 3;
|
||||
static constexpr UINT_PTR navigationTimer = 4;
|
||||
static constexpr UINT_PTR quickViewTimer = 5;
|
||||
struct QuickDocument
|
||||
{
|
||||
std::unique_ptr<TextDocument> document;
|
||||
std::string firstPage;
|
||||
std::optional<std::string> markdown;
|
||||
};
|
||||
std::future<QuickDocument> quickLoading;
|
||||
std::filesystem::path quickPath;
|
||||
uint64_t quickRequest{}, quickReading{};
|
||||
ULONGLONG quickReadyAt{};
|
||||
std::wstring quickError;
|
||||
std::optional<std::string> quickMarkdown;
|
||||
void pollQuickView();
|
||||
static constexpr UINT trimUndo = WM_APP + 1;
|
||||
static constexpr UINT previewFailed = WM_APP + 2;
|
||||
static constexpr UINT openPreviewLink = WM_APP + 3;
|
||||
@@ -891,7 +905,7 @@ private:
|
||||
void invalidateStatus() const;
|
||||
void invalidateHints() const;
|
||||
|
||||
void initializeDocument();
|
||||
void initializeDocument(std::optional<std::string> firstPage={});
|
||||
void finishOpen();
|
||||
void createMenu();
|
||||
void releaseMenu();
|
||||
@@ -907,7 +921,7 @@ private:
|
||||
void updateLineNumberMargin();
|
||||
void applyLineEnding();
|
||||
void installLexer();
|
||||
void loadPage(uint64_t index);
|
||||
void loadPage(uint64_t index,std::optional<std::string> cached={});
|
||||
void stagePage();
|
||||
void go(uint64_t index);
|
||||
void saveFile(bool closeWhenDone);
|
||||
@@ -1207,7 +1221,7 @@ void TextWindow::reloadPreferences()
|
||||
if (!fontChanged && profile == prefs) return;
|
||||
prefs = std::move(profile);
|
||||
filesFont = font;
|
||||
if (fontChanged)
|
||||
if (fontChanged && !embedded)
|
||||
{
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
@@ -1295,9 +1309,9 @@ void TextWindow::applyLineEnding()
|
||||
send(SCI_SETEOLMODE, choices[prefs.lineEnding]);
|
||||
}
|
||||
|
||||
void TextWindow::loadPage(uint64_t index)
|
||||
void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
|
||||
{
|
||||
auto data = document->readPage(index);
|
||||
auto data=cached?std::move(*cached):document->readPage(index);
|
||||
const auto offset = document->boundary(index);
|
||||
page = index;
|
||||
pageOffset = offset;
|
||||
@@ -1345,19 +1359,99 @@ void TextWindow::go(uint64_t index)
|
||||
loadPage(index);
|
||||
}
|
||||
|
||||
void TextWindow::initializeDocument()
|
||||
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
|
||||
{
|
||||
automatic=detectLanguage(original,document->readPage(0));
|
||||
if(!firstPage) firstPage=document->readPage(0);
|
||||
automatic=detectLanguage(original,*firstPage);
|
||||
language=automatic;
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
if(!embedded)
|
||||
{
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
|
||||
}
|
||||
installLexer();
|
||||
loadPage(0);
|
||||
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
|
||||
loadPage(0,std::move(firstPage));
|
||||
updatePreview();
|
||||
}
|
||||
|
||||
std::string readMarkdownDocument(TextDocument &document)
|
||||
{
|
||||
std::string text;
|
||||
for(uint64_t index=0;index<document.pages();++index) text+=document.readPage(index);
|
||||
return text;
|
||||
}
|
||||
|
||||
void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
{
|
||||
if(path==quickPath) return;
|
||||
quickPath=path;
|
||||
++quickRequest;
|
||||
quickReadyAt=GetTickCount64()+80;
|
||||
stopPreview(false,true);
|
||||
document.reset();
|
||||
quickMarkdown.reset();
|
||||
quickError.clear();
|
||||
layout();
|
||||
SetTimer(window,quickViewTimer,30,nullptr);
|
||||
}
|
||||
|
||||
void TextWindow::pollQuickView()
|
||||
{
|
||||
if(quickLoading.valid())
|
||||
{
|
||||
if(quickLoading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
const bool current=quickRequest==quickReading;
|
||||
try
|
||||
{
|
||||
auto loaded=quickLoading.get();
|
||||
if(current)
|
||||
{
|
||||
original=quickPath;
|
||||
filename=original.filename().wstring();
|
||||
document=std::move(loaded.document);
|
||||
quickMarkdown=std::move(loaded.markdown);
|
||||
initializeDocument(std::move(loaded.firstPage));
|
||||
}
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(current)
|
||||
{
|
||||
quickError=wide(error.what());
|
||||
document.reset();
|
||||
layout();
|
||||
}
|
||||
}
|
||||
if(current)
|
||||
{
|
||||
KillTimer(window,quickViewTimer);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if(quickPath.empty())
|
||||
{
|
||||
KillTimer(window,quickViewTimer);
|
||||
return;
|
||||
}
|
||||
if(GetTickCount64()<quickReadyAt) return;
|
||||
quickReading=quickRequest;
|
||||
std::packaged_task<QuickDocument()> task([path=quickPath] {
|
||||
auto source=std::make_unique<TextDocument>(path,false);
|
||||
auto first=source->readPage(0);
|
||||
if(first.find('\0')!=std::string::npos)
|
||||
throw std::runtime_error("Binary preview is unavailable.");
|
||||
std::optional<std::string> markdown;
|
||||
if(source->size()<=TextDocument::editLimit && detectLanguage(path,first).lexer=="markdown")
|
||||
markdown=readMarkdownDocument(*source);
|
||||
source->releaseReadHandle();
|
||||
return QuickDocument{std::move(source),std::move(first),std::move(markdown)};
|
||||
});
|
||||
quickLoading=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
}
|
||||
|
||||
void TextWindow::finishOpen()
|
||||
{
|
||||
if(!opening.valid() || opening.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready) return;
|
||||
@@ -1561,21 +1655,7 @@ void TextWindow::updateIcons(UINT dpi)
|
||||
|
||||
void setFileWindowTaskbar(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{};
|
||||
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();
|
||||
// Setting the group ID tells Explorer to refresh the taskbar button.
|
||||
properties->SetValue(PKEY_AppUserModel_ID,value);
|
||||
properties->Release();
|
||||
setWindowTaskbarIdentity(window, iconResource, identity);
|
||||
}
|
||||
|
||||
namespace
|
||||
@@ -1617,6 +1697,12 @@ bool TextWindow::startPreviewBrowser()
|
||||
{
|
||||
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
|
||||
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
|
||||
if(embedded)
|
||||
{
|
||||
if(!ctrl || alt || key!='Q') return false;
|
||||
PostMessageW(GetParent(window),quickViewToggleMessage,0,0);
|
||||
return true;
|
||||
}
|
||||
if(!alt && ((ctrl && key=='F') || key==VK_F3))
|
||||
{
|
||||
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
|
||||
@@ -1699,12 +1785,10 @@ void TextWindow::renderPreview(bool keepPosition)
|
||||
{
|
||||
applyMarkdownPreferences(loadTextPreferences().markdown);
|
||||
previewDeadline=GetTickCount64()+30000;
|
||||
previewText.clear();
|
||||
for(uint64_t index=0;index<document->pages();++index)
|
||||
previewText+=document->readPage(index);
|
||||
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
|
||||
if(!remote) document->releaseReadHandle();
|
||||
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
|
||||
{"canSave",!remote || remote->revision.editable},
|
||||
{"canSave",!embedded && (!remote || remote->revision.editable)},{"compact",embedded},
|
||||
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
|
||||
{"keepPosition",keepPosition}};
|
||||
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
|
||||
@@ -1721,7 +1805,7 @@ void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences
|
||||
|
||||
void TextWindow::refreshPreview()
|
||||
{
|
||||
if(remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
|
||||
if(embedded || remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
|
||||
nextFileCheck=GetTickCount64()+350;
|
||||
const auto stamp=previewFileStamp();
|
||||
if(!stamp || stamp==previewStamp) return;
|
||||
@@ -1877,14 +1961,17 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
|
||||
return;
|
||||
}
|
||||
if(embedded && action!="image" && action!="rendered" && action!="failed") return;
|
||||
const auto revision=message.value("revision",previewRevision);
|
||||
if(embedded && revision!=previewRevision) return;
|
||||
if(action=="failed")
|
||||
{
|
||||
PostMessageW(window,previewFailed,0,0);
|
||||
PostMessageW(window,previewFailed,static_cast<WPARAM>(revision),0);
|
||||
return;
|
||||
}
|
||||
if(action=="rendered")
|
||||
{
|
||||
PostMessageW(window,previewRendered,0,0);
|
||||
PostMessageW(window,previewRendered,static_cast<WPARAM>(revision),0);
|
||||
return;
|
||||
}
|
||||
if(action=="save-task")
|
||||
@@ -2069,8 +2156,10 @@ void TextWindow::layout()
|
||||
RECT area{};
|
||||
GetClientRect(window, &area);
|
||||
const auto row = chromeHeight();
|
||||
MoveWindow(editor, 0, 2 * row, area.right, std::max(0L, area.bottom - 3 * row), TRUE);
|
||||
preview.layout({0,2*row,area.right,std::max<LONG>(2*row,area.bottom-row)},previewWanted);
|
||||
const int top=embedded?row:2*row;
|
||||
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
|
||||
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
|
||||
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
|
||||
ShowWindow(editor,document && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
invalidate();
|
||||
}
|
||||
@@ -2136,6 +2225,24 @@ void TextWindow::paint()
|
||||
const auto row = chromeHeight();
|
||||
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
SetDCBrushColor(dc, color(TextColor::background));
|
||||
if(embedded)
|
||||
{
|
||||
FillRect(dc,&client,brush);
|
||||
auto font=filesFont.font;
|
||||
font.lfHeight=-MulDiv(filesFont.tenthsOfPoint,GetDpiForWindow(window),720);
|
||||
const auto chromeFont=CreateFontIndirectW(&font);
|
||||
std::wstring label=L"Quick View";
|
||||
if(!quickPath.empty()) label+=L" · "+quickPath.filename().native();
|
||||
if(!quickError.empty()) label+=L" · "+quickError;
|
||||
else if(quickPath.empty()) label+=L" · Select a local text file";
|
||||
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
|
||||
else if(!previewVisible && pageTotal>1) label+=L" · First page";
|
||||
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
|
||||
color(TextColor::chrome),scale(6),label);
|
||||
if(chromeFont) DeleteObject(chromeFont);
|
||||
EndPaint(window,&paint);
|
||||
return;
|
||||
}
|
||||
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));
|
||||
@@ -2354,6 +2461,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
|
||||
bool TextWindow::handleKey(const MSG &message)
|
||||
{
|
||||
if(embedded) return false;
|
||||
const auto key = message.wParam;
|
||||
if (message.hwnd != editor) return false;
|
||||
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
|
||||
@@ -2402,7 +2510,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
const auto &state=*static_cast<const std::shared_ptr<TextWindow> *>(create->lpCreateParams);
|
||||
state->window=window;
|
||||
textWindows.emplace(window,state);
|
||||
textWindowOrder.push_back(window);
|
||||
if(!state->embedded) textWindowOrder.push_back(window);
|
||||
}
|
||||
const auto found=textWindows.find(window);
|
||||
if(found==textWindows.end()) return DefWindowProcW(window,message,wparam,lparam);
|
||||
@@ -2443,7 +2551,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
MSG key{child,msg,wp,lp};
|
||||
if(state->handleKey(key)) return 0;
|
||||
}
|
||||
if(msg==WM_XBUTTONUP && !state->edit)
|
||||
if(msg==WM_XBUTTONUP && !state->edit && !state->embedded)
|
||||
{
|
||||
SendMessageW(state->window,WM_COMMAND,
|
||||
GET_XBUTTON_WPARAM(wp)==XBUTTON1?historyBack:historyForward,0);
|
||||
@@ -2462,9 +2570,13 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;});
|
||||
});
|
||||
}
|
||||
else if(self->embedded) self->applyPreferences();
|
||||
else self->initializeDocument();
|
||||
self->updateIcons(GetDpiForWindow(window));
|
||||
self->updateTaskbarGroup();
|
||||
if(!self->embedded)
|
||||
{
|
||||
self->updateIcons(GetDpiForWindow(window));
|
||||
self->updateTaskbarGroup();
|
||||
}
|
||||
self->layout();
|
||||
return 0;
|
||||
case WM_ERASEBKGND: return 1;
|
||||
@@ -2480,10 +2592,10 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
self->layout();
|
||||
return 0;
|
||||
}
|
||||
case WM_SETFOCUS: self->focusContent(); return 0;
|
||||
case WM_SETFOCUS: if(!self->embedded) self->focusContent(); return 0;
|
||||
case cycleWindow: cycleTextWindows(window,wparam!=0); return 0;
|
||||
case WM_KEYDOWN:
|
||||
if(self->previewWanted && !self->previewVisible)
|
||||
if(!self->embedded && self->previewWanted && !self->previewVisible)
|
||||
{
|
||||
if(wparam==VK_F6) self->toggleMode();
|
||||
if(wparam==VK_ESCAPE || wparam==VK_F10 ||
|
||||
@@ -2491,13 +2603,15 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case previewFailed: self->stopPreview(); return 0;
|
||||
case previewFailed:
|
||||
if(!self->embedded || !wparam || wparam==self->previewRevision) self->stopPreview();
|
||||
return 0;
|
||||
case savePreviewTask: self->startMarkdownTask(); return 0;
|
||||
case previewRendered:
|
||||
if(self->previewWanted)
|
||||
if(self->previewWanted && (!self->embedded || wparam==self->previewRevision))
|
||||
{
|
||||
self->previewVisible=true;
|
||||
self->syncNavigation();
|
||||
if(!self->embedded) self->syncNavigation();
|
||||
self->layout();
|
||||
if(GetForegroundWindow()==window) self->focusContent();
|
||||
}
|
||||
@@ -2526,6 +2640,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
if(self->embedded) return 0;
|
||||
if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600);
|
||||
else self->command(LOWORD(wparam));
|
||||
return 0;
|
||||
@@ -2541,6 +2656,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
if (wparam == openTimer) self->finishOpen();
|
||||
if (wparam == previewTimer) self->pollImages();
|
||||
if (wparam == navigationTimer) self->finishNavigation();
|
||||
if (wparam == quickViewTimer) self->pollQuickView();
|
||||
return 0;
|
||||
case trimUndo:
|
||||
if (self->undoBytes >= 32 * TextDocument::pageBytes)
|
||||
@@ -2553,7 +2669,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
if(self->cancelNavigation) *self->cancelNavigation=true;
|
||||
self->updateTaskbarGroup(true);
|
||||
if(!self->embedded) self->updateTaskbarGroup(true);
|
||||
self->stopPreview(false);
|
||||
self->releaseMenu();
|
||||
return 0;
|
||||
@@ -2567,7 +2683,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
self->search.style.message(window, wide(error.what()).c_str());
|
||||
if(self->embedded) self->quickError=wide(error.what());
|
||||
else self->search.style.message(window, wide(error.what()).c_str());
|
||||
self->invalidate();
|
||||
return message == WM_CREATE ? -1 : 0;
|
||||
}
|
||||
@@ -2726,6 +2843,37 @@ HWND findOpenDocument(const std::filesystem::path &path,std::string_view id)
|
||||
return search.match;
|
||||
}
|
||||
|
||||
bool registerTextWindowClass(HINSTANCE instance)
|
||||
{
|
||||
static const bool registered=[instance]
|
||||
{
|
||||
WNDCLASSW type{};
|
||||
type.hInstance=instance;
|
||||
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
|
||||
type.hIcon=LoadIconW(instance,MAKEINTRESOURCEW(1));
|
||||
type.lpfnWndProc=TextWindow::procedure;
|
||||
type.lpszClassName=windowClass;
|
||||
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
|
||||
}();
|
||||
return registered;
|
||||
}
|
||||
|
||||
HWND createQuickView(HWND owner,TextDialogs dialogs)
|
||||
{
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
if(!registerTextWindowClass(instance)) return nullptr;
|
||||
auto state=std::make_shared<TextWindow>(std::filesystem::path{},false,dialogs,nullptr,
|
||||
std::string_view{},TextOpenOptions{},true);
|
||||
return CreateWindowExW(0,windowClass,L"Quick View",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
|
||||
0,0,0,0,owner,reinterpret_cast<HMENU>(158),instance,&state);
|
||||
}
|
||||
|
||||
void previewQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
{
|
||||
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
|
||||
preview->second->previewFile(path);
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
@@ -2748,17 +2896,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
|
||||
}
|
||||
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
static const bool registered=[instance]
|
||||
{
|
||||
WNDCLASSW type{};
|
||||
type.hInstance=instance;
|
||||
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
|
||||
type.hIcon=LoadIconW(instance,MAKEINTRESOURCEW(1));
|
||||
type.lpfnWndProc=TextWindow::procedure;
|
||||
type.lpszClassName=windowClass;
|
||||
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
|
||||
}();
|
||||
if(!registered) throw std::runtime_error("Cannot register the text window.");
|
||||
if(!registerTextWindowClass(instance)) throw std::runtime_error("Cannot register the text window.");
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,backend,fragment,options);
|
||||
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
|
||||
(backend?backend->name+L" · ":std::wstring{})+path.wstring();
|
||||
|
||||
@@ -80,6 +80,10 @@ struct RemoteTextSource
|
||||
const RemoteTextRevision &)> upload;
|
||||
};
|
||||
|
||||
inline constexpr UINT quickViewToggleMessage=WM_APP+31;
|
||||
HWND createQuickView(HWND owner,TextDialogs dialogs);
|
||||
void previewQuickViewFile(HWND window,const std::filesystem::path &path);
|
||||
|
||||
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,
|
||||
TextOpenOptions options={});
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
+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)
|
||||
{
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
+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);
|
||||
|
||||
+39
-16
@@ -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,6 +154,8 @@ 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{};
|
||||
@@ -166,6 +166,8 @@ SyncConfig decodeSyncConfig(const Bytes &encoded)
|
||||
SyncConfig c;
|
||||
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", ""));
|
||||
@@ -175,7 +177,7 @@ SyncConfig decodeSyncConfig(const Bytes &encoded)
|
||||
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)};
|
||||
@@ -192,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);
|
||||
@@ -282,6 +293,7 @@ void applySyncConnection(const std::filesystem::path &root, const SyncConfig &co
|
||||
}
|
||||
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 {
|
||||
@@ -434,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)}})));
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -7,11 +7,14 @@ 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 &);
|
||||
@@ -72,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 = {});
|
||||
}
|
||||
+337
-210
@@ -9,17 +9,21 @@
|
||||
#include "richtext.h"
|
||||
#include "ui_geometry.h"
|
||||
#include "diagnostics.h"
|
||||
#include "google_drive.h"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <commctrl.h>
|
||||
#include <commdlg.h>
|
||||
#include <dwmapi.h>
|
||||
#include <cwchar>
|
||||
#include "ui_palette.h"
|
||||
#include <map>
|
||||
#include <richedit.h>
|
||||
#include <set>
|
||||
#include <shellapi.h>
|
||||
#include <shlobj.h>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <wrl/client.h>
|
||||
|
||||
namespace ks
|
||||
@@ -37,6 +41,15 @@ HFONT font(HWND w, int size = 14, int weight = FW_NORMAL)
|
||||
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH,
|
||||
L"Segoe UI");
|
||||
}
|
||||
HFONT headingFont(HWND w)
|
||||
{
|
||||
return font(w, 27, FW_SEMIBOLD);
|
||||
}
|
||||
#ifndef KS_CONFIG_APP
|
||||
constexpr int HistoryHeading = 119, HistoryDescription = 120, HistoryHeaderHeight = 73;
|
||||
constexpr int HistoryWidth = 760, HistoryHeight = 530, HistoryMargin = 24, HistoryFooterTop = 482;
|
||||
void setHistoryHeadingFont(HWND w);
|
||||
#endif
|
||||
struct WindowLayout
|
||||
{
|
||||
int width{}, height{}, x{}, y{};
|
||||
@@ -132,8 +145,10 @@ void arrangeWindow(HWND w)
|
||||
for (const auto &[child, r] : layout->controls)
|
||||
{
|
||||
int id = GetDlgCtrlID(child);
|
||||
const bool bottom = (id >= 110 && id <= 114) || id == 116 ||
|
||||
child == layout->bottomLeft || child == layout->bottomRight;
|
||||
RECT next{scale(w, r.left) - layout->x,
|
||||
scale(w, r.top) - layout->y + ((id >= 110 && id <= 114) || id == 116 ? extraHeight : 0)};
|
||||
scale(w, r.top) - layout->y + (bottom ? extraHeight : 0)};
|
||||
next.right = next.left + scale(w, r.right - r.left) + (id == 101 || id == 102 ? extraWidth : 0);
|
||||
next.bottom = next.top + scale(w, r.bottom - r.top) + (id == 102 ? extraHeight : 0);
|
||||
if (child == layout->stretch)
|
||||
@@ -146,8 +161,7 @@ void arrangeWindow(HWND w)
|
||||
next.right += extraWidth;
|
||||
OffsetRect(&next, 0, extraHeight);
|
||||
}
|
||||
if (child == layout->bottomLeft || child == layout->bottomRight)
|
||||
OffsetRect(&next, child == layout->bottomRight ? extraWidth : 0, extraHeight);
|
||||
if (child == layout->bottomRight) OffsetRect(&next, extraWidth, 0);
|
||||
RECT current{}; GetWindowRect(child, ¤t);
|
||||
MapWindowPoints(nullptr, w, reinterpret_cast<POINT *>(¤t), 2);
|
||||
if (!EqualRect(¤t, &next)) moves.push_back({child, next});
|
||||
@@ -155,7 +169,7 @@ void arrangeWindow(HWND w)
|
||||
if (!moves.empty())
|
||||
{
|
||||
applyWindowMoves(moves);
|
||||
if (layout->childViewport) InvalidateRect(w, nullptr, TRUE);
|
||||
if (layout->childViewport || layout->history) InvalidateRect(w, nullptr, TRUE);
|
||||
}
|
||||
if (layout->rowCombo)
|
||||
{
|
||||
@@ -515,9 +529,15 @@ void resizeForDpi(HWND w, WPARAM wp, LPARAM lp)
|
||||
SetPropW(w, L"Dpi", (HANDLE)(UINT_PTR)next);
|
||||
if (old)
|
||||
DeleteObject(old);
|
||||
// layoutProc consumes WM_DPICHANGED, so owner-drawn rows must be resized here.
|
||||
#ifndef KS_CONFIG_APP
|
||||
// layoutProc consumes WM_DPICHANGED, so restore the history typography here.
|
||||
if (layout && layout->history)
|
||||
{
|
||||
setHistoryHeadingFont(w);
|
||||
setWindowResourceIcons(w, reinterpret_cast<HINSTANCE>(GetWindowLongPtrW(w, GWLP_HINSTANCE)), IDI_KSWITCHER_HISTORY);
|
||||
SendDlgItemMessageW(w, 102, LB_SETITEMHEIGHT, 0, scale(w, 88));
|
||||
}
|
||||
#endif
|
||||
fitToMonitor(w, *(RECT *)lp);
|
||||
if (layout && layout->fixedClient)
|
||||
{
|
||||
@@ -572,6 +592,8 @@ struct PreviewResult
|
||||
struct HistoryView
|
||||
{
|
||||
App *app{};
|
||||
WindowPalette palette;
|
||||
HFONT heading{};
|
||||
std::vector<Entry> items;
|
||||
std::wstring rememberedSelection, rememberedTop;
|
||||
uint64_t generation{};
|
||||
@@ -584,6 +606,37 @@ struct HistoryView
|
||||
bool closed{};
|
||||
bool selectFirstOnResults{};
|
||||
};
|
||||
void setHistoryHeadingFont(HWND w)
|
||||
{
|
||||
auto *v = reinterpret_cast<HistoryView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
const auto replacement = headingFont(w);
|
||||
SendDlgItemMessageW(w, HistoryHeading, WM_SETFONT, reinterpret_cast<WPARAM>(replacement), TRUE);
|
||||
if (v->heading) DeleteObject(v->heading);
|
||||
v->heading = replacement;
|
||||
}
|
||||
void paintHistory(HWND w, const HistoryView &v, HDC dc)
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(w, &client);
|
||||
FillRect(dc, &client, GetSysColorBrush(COLOR_WINDOW));
|
||||
const auto &layout = *windowLayoutState(w);
|
||||
const int header = scale(w, HistoryHeaderHeight) - layout.y;
|
||||
const int extraHeight = std::max(0, static_cast<int>(client.bottom) - scale(w, HistoryHeight));
|
||||
const int footer = scale(w, HistoryFooterTop) + extraHeight - layout.y;
|
||||
const RECT actions{0, footer, client.right, client.bottom};
|
||||
FillRect(dc, &actions, v.palette.brush());
|
||||
fillSurface(dc, {0, header - 1, client.right, header}, v.palette.edge());
|
||||
fillSurface(dc, {0, footer, client.right, footer + 1}, v.palette.edge());
|
||||
if (const auto list = GetDlgItem(w, 102))
|
||||
{
|
||||
RECT bounds{};
|
||||
GetWindowRect(list, &bounds);
|
||||
MapWindowPoints(nullptr, w, reinterpret_cast<POINT *>(&bounds), 2);
|
||||
InflateRect(&bounds, 1, 1);
|
||||
SetDCBrushColor(dc, v.palette.edge());
|
||||
FrameRect(dc, &bounds, reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
}
|
||||
bool selectedImage(HWND w, HistoryView *v)
|
||||
{
|
||||
int i=(int)SendDlgItemMessageW(w,102,LB_GETCURSEL,0,0);
|
||||
@@ -769,7 +822,9 @@ void drawHistoryRow(HWND w, HistoryView *v, const DRAWITEMSTRUCT &draw)
|
||||
}
|
||||
else
|
||||
{
|
||||
FrameRect(dc, &icon, GetSysColorBrush(selected ? COLOR_HIGHLIGHTTEXT : COLOR_3DSHADOW));
|
||||
if (!selected && !v->palette.highContrast) FillRect(dc, &icon, v->palette.brush());
|
||||
SetDCBrushColor(dc, selected ? GetSysColor(COLOR_HIGHLIGHTTEXT) : v->palette.edge());
|
||||
FrameRect(dc, &icon, reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
const wchar_t *glyph = entry.image ? L"▧" : entry.files ? L"≡" : L"Aa";
|
||||
DrawTextW(dc, glyph, -1, &icon, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
|
||||
if (entry.image)
|
||||
@@ -822,7 +877,8 @@ void drawHistoryRow(HWND w, HistoryView *v, const DRAWITEMSTRUCT &draw)
|
||||
if (!formatted)
|
||||
DrawTextW(dc, text.c_str(), -1, &title, DT_WORDBREAK | DT_END_ELLIPSIS | DT_NOPREFIX);
|
||||
RECT detail{title.left, box.bottom - scale(w, 26), title.right, box.bottom - scale(w, 8)};
|
||||
SetTextColor(dc, GetSysColor(selected ? COLOR_HIGHLIGHTTEXT : COLOR_GRAYTEXT));
|
||||
SetTextColor(dc, selected ? GetSysColor(COLOR_HIGHLIGHTTEXT) : v->palette.secondaryText());
|
||||
if (!selected) fillSurface(dc, {box.left, box.bottom - 1, box.right, box.bottom}, v->palette.edge());
|
||||
auto subtitle = (entry.pinned ? L"★ " : L"") + std::to_wstring(draw.itemID + 1) + L" · " + entry.app + L" · " + (entry.computer.empty()?L"This computer":entry.computerName);
|
||||
DrawTextW(dc, subtitle.c_str(), -1, &detail, DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX);
|
||||
if (draw.itemState & ODS_FOCUS)
|
||||
@@ -896,6 +952,31 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
switch (msg)
|
||||
{
|
||||
case WM_SETTINGCHANGE: case WM_SYSCOLORCHANGE: case WM_DWMCOLORIZATIONCOLORCHANGED:
|
||||
v->palette.refresh(msg == WM_DWMCOLORIZATIONCOLORCHANGED ? std::optional<DWORD>(wp) : std::nullopt);
|
||||
RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN);
|
||||
break;
|
||||
case WM_SIZE:
|
||||
InvalidateRect(w, nullptr, FALSE);
|
||||
return 0;
|
||||
case WM_ERASEBKGND:
|
||||
return 1;
|
||||
case WM_PAINT:
|
||||
{
|
||||
PAINTSTRUCT paint{};
|
||||
const auto dc = BeginPaint(w, &paint);
|
||||
if (windowLayoutState(w)) paintHistory(w, *v, dc);
|
||||
EndPaint(w, &paint);
|
||||
return 0;
|
||||
}
|
||||
case WM_CTLCOLORSTATIC:
|
||||
{
|
||||
const auto dc = reinterpret_cast<HDC>(wp);
|
||||
SetTextColor(dc, GetDlgCtrlID(reinterpret_cast<HWND>(lp)) == HistoryDescription ?
|
||||
v->palette.secondaryText() : GetSysColor(COLOR_WINDOWTEXT));
|
||||
SetBkMode(dc, TRANSPARENT);
|
||||
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_WINDOW));
|
||||
}
|
||||
case ScrollActivity:
|
||||
if((HWND)wp==GetDlgItem(w,102)) {
|
||||
v->scrolling=lp!=0;
|
||||
@@ -1110,6 +1191,7 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
case WM_NCDESTROY:
|
||||
v->previewActive->store(false);
|
||||
if (v->heading) DeleteObject(v->heading);
|
||||
disposeFont(w);
|
||||
v->app->historyWindow = nullptr;
|
||||
delete v;
|
||||
@@ -1127,11 +1209,17 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
#ifndef KS_RESIDENT_APP
|
||||
constexpr int LanguagesPage = 1, ShortcutsPage = 2, ClipboardPage = 3, SnippetsPage = 4, MousePage = 5;
|
||||
constexpr int ExceptionsPage = 13, PersonalDictionariesPage = 14, WordBoundariesPage = 15, SnippetMacros = 320;
|
||||
constexpr int CustomReplacementsPage = 16;
|
||||
constexpr int ClipboardExcludedApps = 243, ClipboardAppName = 244, ClipboardAddApp = 245,
|
||||
ClipboardRemoveApp = 246, ClipboardAppPicker = 247;
|
||||
constexpr UINT AppWindowPicked = WM_APP + 78;
|
||||
constexpr int SettingsNavigation = 260, SettingsStatus = 261, SettingsViewport = 264, SettingsApply = 272;
|
||||
constexpr int SettingsBrand = 265, SettingsHeading = 266, SettingsDescription = 267, SettingsGroup = 268;
|
||||
constexpr int SettingsSearch = 269, GeneralPage = 0, ComputersPage = 7, ManageComputersPage = 10, CorrectionPage = 11;
|
||||
constexpr int SyncPage = 6, OpenBaoPage = 17, SettingsSyncPanel = 271;
|
||||
constexpr int SyncPage = 6, OpenBaoPage = 17, GoogleDrivePage = 18, SettingsSyncPanel = 271;
|
||||
constexpr int OcrUseTesseract = 501, OcrExecutable = 502, OcrLanguages = 503, OcrBrowse = 504,
|
||||
OcrCheck = 505, OcrStatus = 506, OcrDownload = 507;
|
||||
constexpr int DriveAutomatic = 625;
|
||||
constexpr UINT CollapseSettingsGroupMessage = WM_APP + 188;
|
||||
constexpr int SettingsSidebarWidth = 214, SettingsHeaderHeight = 82, SettingsFooterHeight = 76;
|
||||
constexpr int SettingsNavigationIndent = 16;
|
||||
@@ -1148,10 +1236,10 @@ constexpr struct SettingsSection
|
||||
{"general", L"General", L"Configure text conversion and how KSwitcher runs on Windows."},
|
||||
{"languages", L"Languages", L"Order layouts from top to bottom and override the cycle for individual chats or apps."},
|
||||
{"shortcuts", L"Shortcuts", L"Click a shortcut field and press the desired keys. Backspace or Delete clears it."},
|
||||
{"clipboard", L"Clipboard", L"Configure clipboard history, storage limits and text recognition."},
|
||||
{"clipboard", L"Clipboard", L"Configure clipboard history, storage limits and excluded applications."},
|
||||
{"snippets", L"Snippets", L"Create text expansions and choose which applications can use them."},
|
||||
{"mouse", L"Mouse", L"Manage profiles, assign actions and test your mouse buttons."},
|
||||
{"sync", L"Sync", L"Back up and synchronize settings through OpenBao."},
|
||||
{"sync", L"Sync", L"Choose a provider to back up or synchronize your settings."},
|
||||
{"computers", L"Computers", L"Share mouse and keyboard with paired computers."},
|
||||
{"diagnostics", L"Diagnostics", L"Manage diagnostic logging and view recent operations."},
|
||||
{"mcp", L"MCP", L"Connect Codex to KSwitcher to read diagnostic logs."},
|
||||
@@ -1163,6 +1251,8 @@ constexpr struct SettingsSection
|
||||
{"word-boundaries", L"Word boundaries", L"Choose which punctuation KSwitcher keeps before and after a corrected word.", CorrectionPage},
|
||||
{"custom-replacements", L"Custom replacements", L"Define your own corrections, which take priority over dictionary suggestions.", CorrectionPage},
|
||||
{"openbao", L"OpenBao", L"Connect to OpenBao and synchronize your saved settings.", SyncPage},
|
||||
{"google-drive", L"Google Drive", L"Synchronize settings across PCs or manage manual backups.", SyncPage},
|
||||
{"ocr", L"Image text recognition", L"Choose Windows OCR or Tesseract. Recognition runs on this computer.", ClipboardPage},
|
||||
};
|
||||
constexpr wchar_t SettingsWindowFile[] = L"configurator-window.json";
|
||||
struct SettingsWindowState
|
||||
@@ -1229,46 +1319,6 @@ struct SnippetView
|
||||
HWND pickerOutline{};
|
||||
bool filling{};
|
||||
};
|
||||
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); }
|
||||
bool highContrast{};
|
||||
|
||||
private:
|
||||
COLORREF color_{};
|
||||
HBRUSH brush_{};
|
||||
};
|
||||
struct SettingsView
|
||||
{
|
||||
App *app{};
|
||||
@@ -1284,7 +1334,7 @@ struct SettingsView
|
||||
};
|
||||
std::array<Page, std::size(settingsSections)> pages;
|
||||
int selectedPage = -1;
|
||||
HWND viewport{}, navigation{}, search{}, heading{}, description{}, brand{}, lan{}, sync{}, splitter{};
|
||||
HWND viewport{}, navigation{}, search{}, heading{}, description{}, brand{}, lan{}, sync{}, drive{}, splitter{};
|
||||
int sidebarWidth = SettingsSidebarWidth;
|
||||
std::optional<int> splitterDragOffset;
|
||||
bool splitterHovered{};
|
||||
@@ -1303,6 +1353,7 @@ struct SettingsView
|
||||
unsigned mouseEvents{}, rawMouseEvents{};
|
||||
bool rawMouseRegistered{};
|
||||
SnippetView snippets;
|
||||
HWND clipboardPickerOutline{};
|
||||
};
|
||||
void saveSettingsWindowState(HWND w, const SettingsView &v)
|
||||
{
|
||||
@@ -1340,6 +1391,7 @@ void snippetWindowPicked(HWND w, WPARAM target, LPARAM phase);
|
||||
bool snippetDraftChanged(HWND, SnippetView *);
|
||||
bool mergeSnippetDraft(HWND, SnippetView *, Settings &);
|
||||
void refreshSnippetDraft(HWND, SnippetView *);
|
||||
void fillSnippets(HWND, SnippetView *);
|
||||
void updateSettingsState(HWND w, SettingsView *v);
|
||||
bool matchesSettingsSearch(const SettingsView &v, const std::wstring &text)
|
||||
{
|
||||
@@ -1391,6 +1443,7 @@ void repaintSettingsMatches(const SettingsView &v)
|
||||
InvalidateRect(v.viewport, nullptr, TRUE);
|
||||
if (v.lan) InvalidateRect(v.lan, nullptr, TRUE);
|
||||
if (v.sync) InvalidateRect(v.sync, nullptr, TRUE);
|
||||
if (v.drive) InvalidateRect(v.drive, nullptr, TRUE);
|
||||
}
|
||||
LRESULT CALLBACK settingsViewportProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
@@ -1562,11 +1615,11 @@ void setSettingsFonts(HWND w, SettingsView &v, UINT dpi)
|
||||
if (old) DeleteObject(old);
|
||||
old = replacement;
|
||||
};
|
||||
assign(v.heading, font(w, 27, FW_SEMIBOLD), v.headingFont);
|
||||
assign(v.heading, headingFont(w), v.headingFont);
|
||||
assign(v.brand, font(w, 18, FW_SEMIBOLD), v.brandFont);
|
||||
HFONT group = font(w, 15, FW_SEMIBOLD);
|
||||
HFONT field = font(w, 14, FW_SEMIBOLD);
|
||||
for (HWND pane : {v.viewport, v.lan, v.sync})
|
||||
for (HWND pane : {v.viewport, v.lan, v.sync, v.drive})
|
||||
if (pane)
|
||||
{
|
||||
SetPropW(pane, L"Font", GetPropW(w, L"Font"));
|
||||
@@ -1655,6 +1708,7 @@ struct SettingsColumns
|
||||
int secondLeft = 0, firstRight = 0, footerTop = 0, wrapAt = 0;
|
||||
int compactListHeight = 0;
|
||||
int sharedHeaderEnd = 0;
|
||||
bool fillWidth = false;
|
||||
};
|
||||
int fitSettingsColumns(WindowLayout &layout, size_t first, size_t end, int width, SettingsColumns grid)
|
||||
{
|
||||
@@ -1683,7 +1737,7 @@ int fitSettingsColumns(WindowLayout &layout, size_t first, size_t end, int width
|
||||
const int available = right - grid.left;
|
||||
const int size = grid.right - grid.left;
|
||||
if (!stacked || !twoColumns || sharedHeader)
|
||||
return grid.left + MulDiv(x - grid.left, std::min(size, available), size);
|
||||
return grid.left + MulDiv(x - grid.left, grid.fillWidth ? available : std::min(size, available), size);
|
||||
return grid.left + MulDiv(x - sourceLeft, available, sourceRight - sourceLeft);
|
||||
};
|
||||
std::stable_sort(items.begin(), items.end(), [&](size_t left, size_t right)
|
||||
@@ -1749,8 +1803,36 @@ int fitSettingsColumns(WindowLayout &layout, size_t first, size_t end, int width
|
||||
}
|
||||
return bottom + 20;
|
||||
}
|
||||
int fitLanSettings(HWND panel, int width);
|
||||
int fitLanSettings(HWND panel, int width, int height);
|
||||
int fitSyncSettings(HWND panel, int width);
|
||||
int fitDriveSettings(HWND panel, int width, int height);
|
||||
void stretchSettingsEditors(WindowLayout &layout, size_t first, size_t end, int extra,
|
||||
std::initializer_list<int> editors, bool stacked)
|
||||
{
|
||||
if (extra <= 0) return;
|
||||
int remaining = extra, count = static_cast<int>(editors.size());
|
||||
for (int id : editors)
|
||||
{
|
||||
const int growth = stacked ? remaining / count : extra;
|
||||
remaining -= growth;
|
||||
--count;
|
||||
for (size_t i = first; i < end; ++i)
|
||||
{
|
||||
auto &[child, bounds] = layout.controls[i];
|
||||
if (GetDlgCtrlID(child) != id) continue;
|
||||
const auto editor = bounds;
|
||||
bounds.bottom += growth;
|
||||
for (size_t j = first; j < end; ++j)
|
||||
{
|
||||
auto &below = layout.controls[j].second;
|
||||
if (below.top >= editor.bottom && (stacked || (below.left >= editor.left && below.left < editor.right)))
|
||||
OffsetRect(&below, 0, growth);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
layout.height += extra;
|
||||
}
|
||||
void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height)
|
||||
{
|
||||
const auto &v = *reinterpret_cast<SettingsView *>(GetWindowLongPtrW(GetParent(pane), GWLP_USERDATA));
|
||||
@@ -1759,11 +1841,13 @@ void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height)
|
||||
auto fit = [&](int pixels)
|
||||
{
|
||||
const int available = std::max(1, pixels * 96 / static_cast<int>(dpi));
|
||||
if (v.selectedPage == ManageComputersPage || v.selectedPage == OpenBaoPage)
|
||||
if (v.selectedPage == ManageComputersPage || v.selectedPage == OpenBaoPage || v.selectedPage == GoogleDrivePage)
|
||||
{
|
||||
const int panelWidth = std::max(1, available - 16);
|
||||
const int panelHeight = v.selectedPage == ManageComputersPage ? fitLanSettings(v.lan, panelWidth) :
|
||||
fitSyncSettings(v.sync, panelWidth);
|
||||
const int panelAreaHeight = std::max(1, height * 96 / static_cast<int>(dpi) - 15);
|
||||
const int panelHeight = v.selectedPage == ManageComputersPage ? fitLanSettings(v.lan, panelWidth, panelAreaHeight) :
|
||||
v.selectedPage == OpenBaoPage ? fitSyncSettings(v.sync, panelWidth) :
|
||||
fitDriveSettings(v.drive, panelWidth, panelAreaHeight);
|
||||
layout.controls[page.first].second = {8, 7, 8 + panelWidth, 7 + panelHeight};
|
||||
layout.height = panelHeight + 15;
|
||||
return;
|
||||
@@ -1777,6 +1861,13 @@ void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height)
|
||||
case WordBoundariesPage: grid = {24, 684, 362, 346, 90, 500}; break;
|
||||
}
|
||||
layout.height = fitSettingsColumns(layout, page.first, page.end, available, grid);
|
||||
const int extra = height * 96 / static_cast<int>(dpi) - layout.height;
|
||||
if (v.selectedPage == SnippetsPage)
|
||||
stretchSettingsEditors(layout, page.first, page.end, extra, {301, 303}, available < grid.wrapAt);
|
||||
if (v.selectedPage == MousePage)
|
||||
stretchSettingsEditors(layout, page.first, page.end, extra, {731, 733}, available < grid.wrapAt);
|
||||
if (v.selectedPage == CustomReplacementsPage)
|
||||
stretchSettingsEditors(layout, page.first, page.end, extra, {416}, false);
|
||||
};
|
||||
fit(width);
|
||||
if (scale(pane, layout.height) > height)
|
||||
@@ -1848,9 +1939,14 @@ void reflowClipboard(HWND pane, WindowLayout &layout, int width, int height)
|
||||
const int captionHeight = settingsCaptionHeight(layout.controls[first + 9].first, contentWidth);
|
||||
layout.controls[first + 9].second = {left, y, right, y + captionHeight};
|
||||
y += captionHeight + 4;
|
||||
layout.controls[first + 10].second = {left, y, right, y + 25};
|
||||
y += 35;
|
||||
layout.controls[first + 11].second = {left, y, actionRight, y + 28};
|
||||
const int listHeight = std::max(100, height * 96 / static_cast<int>(dpi) - y - 56);
|
||||
layout.controls[first + 10].second = {left, y, right, y + listHeight};
|
||||
y += listHeight + 8;
|
||||
const int pickerLeft = right - 32, removeLeft = pickerLeft - 84, addLeft = removeLeft - 68;
|
||||
layout.controls[first + 11].second = {left, y + 1, addLeft - 6, y + 26};
|
||||
layout.controls[first + 12].second = {addLeft, y, removeLeft - 6, y + 28};
|
||||
layout.controls[first + 13].second = {removeLeft, y, pickerLeft - 6, y + 28};
|
||||
layout.controls[first + 14].second = {pickerLeft, y, right, y + 28};
|
||||
layout.height = y + 48;
|
||||
};
|
||||
fit(width);
|
||||
@@ -1914,12 +2010,8 @@ void paintSettings(HWND w, const SettingsView &v)
|
||||
RECT rail{0, 0, sidebar, footer}, actions{0, footer, client.right, client.bottom};
|
||||
FillRect(dc, &rail, v.palette.brush());
|
||||
FillRect(dc, &actions, v.palette.brush());
|
||||
SetDCBrushColor(dc, v.palette.highContrast ? GetSysColor(COLOR_WINDOWTEXT) : RGB(200, 213, 222));
|
||||
auto border = reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
RECT footerEdge{0, footer, client.right, footer + 1};
|
||||
RECT headingEdge{sidebar + scale(w, SettingsSplitterWidth), header - 1, client.right, header};
|
||||
FillRect(dc, &footerEdge, border);
|
||||
FillRect(dc, &headingEdge, border);
|
||||
fillSurface(dc, {0, footer, client.right, footer + 1}, v.palette.edge());
|
||||
fillSurface(dc, {sidebar + scale(w, SettingsSplitterWidth), header - 1, client.right, header}, v.palette.edge());
|
||||
auto icon = LoadIconW(v.app->instance, MAKEINTRESOURCEW(IDI_KSWITCHER));
|
||||
DrawIconEx(dc, scale(w, 17), scale(w, 18), icon, scale(w, 28), scale(w, 28), 0, nullptr, DI_NORMAL);
|
||||
EndPaint(w, &paint);
|
||||
@@ -2173,7 +2265,7 @@ void indexSettingsControl(SettingsView &v, int page, HWND child)
|
||||
case 231: aliases = L"hotkey keyboard shortcut"; break;
|
||||
case 240: aliases = L"max maximum count history limit"; break;
|
||||
case 241: case 242: aliases = L"size storage history limit"; break;
|
||||
case 257: aliases = L"text recognition Tesseract"; break;
|
||||
case OcrUseTesseract: case OcrExecutable: case OcrLanguages: aliases = L"OCR text recognition Tesseract"; break;
|
||||
case 411: case 412: case 413: aliases = L"personal dictionary words"; break;
|
||||
case 701: aliases = L"LAN network discover devices computers"; break;
|
||||
case 704: aliases = L"pairing connection code"; break;
|
||||
@@ -2432,6 +2524,7 @@ void resizeSettingsForDpi(HWND w, int previousDpi, int nextDpi)
|
||||
arrangeWindow(v.viewport);
|
||||
if (v.lan) arrangeWindow(v.lan);
|
||||
if (v.sync) arrangeWindow(v.sync);
|
||||
if (v.drive) arrangeWindow(v.drive);
|
||||
if (previousDpi != nextDpi) scaleMouseTableColumns(w, previousDpi, nextDpi);
|
||||
}
|
||||
void collectLayout(SettingsView *v)
|
||||
@@ -2477,6 +2570,42 @@ void fillLayouts(SettingsView *v)
|
||||
}
|
||||
void fillCorrectionOptions(HWND w, const Settings &draft);
|
||||
void collectCorrectionOptions(HWND w, Settings &draft);
|
||||
void collectOcrOptions(HWND pane, Settings &draft)
|
||||
{
|
||||
draft.useTesseract = checked(pane, OcrUseTesseract);
|
||||
draft.tesseractPath = value(pane, OcrExecutable);
|
||||
draft.tesseractLanguages = value(pane, OcrLanguages);
|
||||
}
|
||||
void updateClipboardAppButtons(HWND pane)
|
||||
{
|
||||
EnableWindow(GetDlgItem(pane, ClipboardAddApp), !snippetAppName(value(pane, ClipboardAppName)).empty());
|
||||
EnableWindow(GetDlgItem(pane, ClipboardRemoveApp),
|
||||
SendDlgItemMessageW(pane, ClipboardExcludedApps, LB_GETCURSEL, 0, 0) != LB_ERR);
|
||||
}
|
||||
void fillClipboardApps(SettingsView &view, int selected = -1)
|
||||
{
|
||||
const auto list = GetDlgItem(view.viewport, ClipboardExcludedApps);
|
||||
SendMessageW(list, LB_RESETCONTENT, 0, 0);
|
||||
for (const auto &name : view.draft.excluded)
|
||||
SendMessageW(list, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(name.c_str()));
|
||||
if (selected >= 0 && !view.draft.excluded.empty())
|
||||
SendMessageW(list, LB_SETCURSEL, std::min(selected, static_cast<int>(view.draft.excluded.size()) - 1), 0);
|
||||
updateClipboardAppButtons(view.viewport);
|
||||
}
|
||||
void addClipboardApp(SettingsView &view, std::wstring name)
|
||||
{
|
||||
name = snippetAppName(std::move(name));
|
||||
if (name.empty()) return;
|
||||
if (name.size() > 260 || name.find_first_of(L"\\/:*?\"<>|,\r\n") != name.npos)
|
||||
throw std::runtime_error("Enter one process name, such as chrome.exe.");
|
||||
auto &apps = view.draft.excluded;
|
||||
const auto existing = std::find_if(apps.begin(), apps.end(),
|
||||
[&](const auto &app) { return snippetAppName(app) == name; });
|
||||
const auto row = static_cast<int>(existing - apps.begin());
|
||||
if (existing == apps.end()) apps.push_back(std::move(name));
|
||||
value(view.viewport, ClipboardAppName, L"");
|
||||
fillClipboardApps(view, row);
|
||||
}
|
||||
void fillSettings(HWND root, SettingsView *v)
|
||||
{
|
||||
HWND w = v->viewport;
|
||||
@@ -2501,14 +2630,12 @@ void fillSettings(HWND root, SettingsView *v)
|
||||
value(w, 240, std::to_wstring(s.maxItems));
|
||||
value(w, 241, std::to_wstring(s.maxMiB));
|
||||
value(w, 242, std::to_wstring(s.maxImageMiB));
|
||||
std::wstring excluded;
|
||||
for (auto &name : s.excluded)
|
||||
{
|
||||
if (!excluded.empty())
|
||||
excluded += L", ";
|
||||
excluded += name;
|
||||
}
|
||||
value(w, 243, excluded);
|
||||
value(w, ClipboardAppName, L"");
|
||||
fillClipboardApps(*v);
|
||||
check(w, OcrUseTesseract, s.useTesseract);
|
||||
value(w, OcrExecutable, s.tesseractPath);
|
||||
value(w, OcrLanguages, s.tesseractLanguages);
|
||||
value(w, OcrStatus, L"");
|
||||
v->order.clear();
|
||||
for (auto &id : s.cycle)
|
||||
for (int i = 0; i < (int)v->app->layouts.size(); ++i)
|
||||
@@ -2559,15 +2686,6 @@ Settings collectSettings(SettingsView *v)
|
||||
s.maxItems = integer(w, 240);
|
||||
s.maxMiB = integer(w, 241);
|
||||
s.maxImageMiB = integer(w, 242);
|
||||
s.excluded.clear();
|
||||
std::wistringstream input(value(w, 243));
|
||||
std::wstring item;
|
||||
while (std::getline(input, item, L','))
|
||||
{
|
||||
auto first = item.find_first_not_of(L" \t"), last = item.find_last_not_of(L" \t");
|
||||
if (first != item.npos)
|
||||
s.excluded.push_back(item.substr(first, last - first + 1));
|
||||
}
|
||||
std::vector<std::wstring> cycle;
|
||||
for (int i : v->order)
|
||||
{
|
||||
@@ -2577,6 +2695,7 @@ Settings collectSettings(SettingsView *v)
|
||||
}
|
||||
s.cycle = cycle;
|
||||
collectCorrectionOptions(w, s);
|
||||
collectOcrOptions(w, s);
|
||||
validateSettings(s);
|
||||
return s;
|
||||
}
|
||||
@@ -2701,101 +2820,53 @@ void fillCorrectionOptions(HWND w, const Settings &draft)
|
||||
check(w, 415, draft.autoTypos);
|
||||
value(w, 416, correctionPairs(draft));
|
||||
}
|
||||
struct OcrOptionsView { HWND parent; SettingsView *settings; };
|
||||
Settings ocrDraft(HWND w, OcrOptionsView *v)
|
||||
void handleOcrAction(HWND root, SettingsView &view, int id)
|
||||
{
|
||||
auto draft = v->settings->draft;
|
||||
draft.useTesseract = checked(w, 501);
|
||||
draft.tesseractPath = value(w, 502);
|
||||
draft.tesseractLanguages = value(w, 503);
|
||||
validateSettings(draft);
|
||||
return draft;
|
||||
}
|
||||
LRESULT CALLBACK ocrOptionsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
auto *v = reinterpret_cast<OcrOptionsView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
if (!v) return DefWindowProcW(w, msg, wp, lp);
|
||||
if (msg == WM_COMMAND)
|
||||
const auto pane = view.viewport;
|
||||
if (id == OcrDownload)
|
||||
{
|
||||
int id = LOWORD(wp);
|
||||
try
|
||||
{
|
||||
if (id == 507)
|
||||
{
|
||||
if ((INT_PTR)ShellExecuteW(w, L"open", L"https://github.com/UB-Mannheim/tesseract/wiki#tesseract-installer-for-windows",
|
||||
nullptr, nullptr, SW_SHOWNORMAL) <= 32)
|
||||
throw std::runtime_error("Could not open the Tesseract download page in your browser");
|
||||
return 0;
|
||||
}
|
||||
if (id == 504)
|
||||
{
|
||||
wchar_t path[32768]{};
|
||||
OPENFILENAMEW picker{sizeof(picker)};
|
||||
picker.hwndOwner = w; picker.lpstrFile = path; picker.nMaxFile = std::size(path);
|
||||
picker.lpstrFilter = L"Tesseract executable (tesseract.exe)\0tesseract.exe\0Executables\0*.exe\0";
|
||||
picker.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
|
||||
if (GetOpenFileNameW(&picker)) value(w, 502, path);
|
||||
return 0;
|
||||
}
|
||||
if (id == 505 || id == IDOK)
|
||||
{
|
||||
auto draft = ocrDraft(w, v);
|
||||
if (id == 505)
|
||||
{
|
||||
draft.useTesseract = true;
|
||||
validateTesseract(draft);
|
||||
SetDlgItemTextW(w, 506, (L"Ready: " + draft.tesseractLanguages).c_str());
|
||||
return 0;
|
||||
}
|
||||
validateTesseract(draft);
|
||||
v->settings->draft.useTesseract = draft.useTesseract;
|
||||
v->settings->draft.tesseractPath = draft.tesseractPath;
|
||||
v->settings->draft.tesseractLanguages = draft.tesseractLanguages;
|
||||
DestroyWindow(w);
|
||||
return 0;
|
||||
}
|
||||
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
|
||||
}
|
||||
catch (const std::exception &e) { error(w, e); return 0; }
|
||||
if ((INT_PTR)ShellExecuteW(root, L"open", L"https://github.com/UB-Mannheim/tesseract/wiki#tesseract-installer-for-windows",
|
||||
nullptr, nullptr, SW_SHOWNORMAL) <= 32)
|
||||
throw std::runtime_error("Could not open the Tesseract download page in your browser.");
|
||||
}
|
||||
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
|
||||
if (msg == WM_NCDESTROY)
|
||||
else if (id == OcrBrowse)
|
||||
{
|
||||
EnableWindow(v->parent, TRUE);
|
||||
SetForegroundWindow(v->parent);
|
||||
disposeFont(w); delete v;
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||
wchar_t path[32768]{};
|
||||
OPENFILENAMEW picker{sizeof(picker)};
|
||||
picker.hwndOwner = root;
|
||||
picker.lpstrFile = path;
|
||||
picker.nMaxFile = std::size(path);
|
||||
picker.lpstrFilter = L"Tesseract executable (tesseract.exe)\0tesseract.exe\0Executables\0*.exe\0";
|
||||
picker.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
|
||||
if (GetOpenFileNameW(&picker)) value(pane, OcrExecutable, path);
|
||||
}
|
||||
else if (id == OcrCheck)
|
||||
{
|
||||
value(pane, OcrStatus, L"");
|
||||
auto draft = view.draft;
|
||||
collectOcrOptions(pane, draft);
|
||||
draft.useTesseract = true;
|
||||
validateSettings(draft);
|
||||
validateTesseract(draft);
|
||||
value(pane, OcrStatus, L"Ready: " + draft.tesseractLanguages);
|
||||
}
|
||||
return DefWindowProcW(w, msg, wp, lp);
|
||||
}
|
||||
void showOcrOptions(HWND parent, SettingsView *v)
|
||||
void createOcrSettings(HWND pane)
|
||||
{
|
||||
HWND w = makeWindow(*v->app, L"KSwitcher.OcrOptions", L"Image text recognition", ocrOptionsProc, 640, 450);
|
||||
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)new OcrOptionsView{parent, v});
|
||||
label(w, L"Windows OCR is used by default. Recognition stays on this computer.", 18, 16, 600);
|
||||
checkbox(w, L"&Use optional Tesseract 5 instead of Windows OCR", 501, 18, 48, 600);
|
||||
check(w, 501, v->draft.useTesseract);
|
||||
label(w, L"Tesseract executable (blank = detect installed location)", 18, 90, 600);
|
||||
edit(w, 502, 18, 118, 484);
|
||||
value(w, 502, v->draft.tesseractPath);
|
||||
button(w, L"&Browse…", 504, 514, 117, 106);
|
||||
label(w, L"Languages used together (for example ukr+eng+rus)", 18, 160, 600);
|
||||
edit(w, 503, 18, 188, 602);
|
||||
value(w, 503, v->draft.tesseractLanguages);
|
||||
button(w, L"Check &installation", 505, 18, 228, 180);
|
||||
control(w, L"STATIC", L"", 0, 506, 212, 232, 408, 24);
|
||||
button(w, L"&Download Tesseract…", 507, 18, 266, 180);
|
||||
label(w, L"Opens the Windows installer page in your browser.", 212, 270, 408);
|
||||
label(w, L"Changing the engine or languages reprocesses saved images in the background.", 18, 314, 602);
|
||||
label(w, L"Click OK here, then Save in Settings to apply. No downloads are automatic.", 18, 344, 602);
|
||||
button(w, L"&OK", IDOK, 406, 390, 100);
|
||||
button(w, L"&Cancel", IDCANCEL, 520, 390, 100);
|
||||
EnableWindow(parent, FALSE);
|
||||
showRequestedWindow(w); SetForegroundWindow(w);
|
||||
checkbox(pane, L"&Use optional Tesseract 5 instead of Windows OCR", OcrUseTesseract, 24, 68, 660);
|
||||
label(pane, L"Tesseract executable (blank = detect installed location)", 24, 111, 660);
|
||||
edit(pane, OcrExecutable, 24, 137, 540);
|
||||
button(pane, L"&Browse…", OcrBrowse, 576, 136, 108);
|
||||
label(pane, L"Languages used together (for example ukr+eng+rus)", 24, 185, 660);
|
||||
edit(pane, OcrLanguages, 24, 211, 660);
|
||||
button(pane, L"Check &installation", OcrCheck, 24, 252, 190);
|
||||
control(pane, L"STATIC", L"", 0, OcrStatus, 228, 255, 456, 24);
|
||||
button(pane, L"&Download Tesseract…", OcrDownload, 24, 289, 190);
|
||||
label(pane, L"Changing the engine or languages reprocesses saved images in the background.", 24, 337, 660);
|
||||
}
|
||||
#include "ui_sync.inl"
|
||||
#include "ui_lan.inl"
|
||||
#include "ui_google_drive.inl"
|
||||
bool settingsChanged(SettingsView *v)
|
||||
{
|
||||
try
|
||||
@@ -2868,7 +2939,10 @@ void applySettingsDraft(HWND w, SettingsView *v, bool keepOpen)
|
||||
if (lanEdited) lan->draft.clear();
|
||||
v->draft = v->app->settings;
|
||||
fillSettings(w, v);
|
||||
refreshSnippetDraft(v->viewport, &v->snippets);
|
||||
v->snippets.snippets = v->snippets.saved = v->draft.snippets;
|
||||
if (v->snippets.selection >= static_cast<int>(v->snippets.snippets.size())) v->snippets.selection = -1;
|
||||
fillSnippets(v->viewport, &v->snippets);
|
||||
updateSettingsState(w, v);
|
||||
if (syncEdited) reloadSyncEditor(v->sync);
|
||||
if (lanEdited) refreshLan(v->lan, *lan);
|
||||
}
|
||||
@@ -2932,10 +3006,19 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
paintSettings(w, *v);
|
||||
return 0;
|
||||
case AppWindowPicked:
|
||||
snippetWindowPicked(v->viewport, wp, lp);
|
||||
if (v->selectedPage == ClipboardPage)
|
||||
{
|
||||
if (lp == 1 && wp)
|
||||
{
|
||||
addClipboardApp(*v, processName(reinterpret_cast<HWND>(wp)));
|
||||
updateSettingsState(w, v);
|
||||
}
|
||||
}
|
||||
else if (v->selectedPage == SnippetsPage) snippetWindowPicked(v->viewport, wp, lp);
|
||||
return 0;
|
||||
case WM_DRAWITEM:
|
||||
if (wp == AppWindowPickerIcon || wp == AddMouseProfile || wp == RenameMouseProfile || wp == DeleteMouseProfile || wp == AddMouseEvent)
|
||||
if (wp == AppWindowPickerIcon || wp == ClipboardAppPicker || wp == AddMouseProfile ||
|
||||
wp == RenameMouseProfile || wp == DeleteMouseProfile || wp == AddMouseEvent)
|
||||
{
|
||||
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
|
||||
return TRUE;
|
||||
@@ -2951,8 +3034,8 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
SetBkColor(dc, GetSysColor(COLOR_WINDOW));
|
||||
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_WINDOW));
|
||||
}
|
||||
SetTextColor(dc, !v->palette.highContrast && (child == v->description || GetDlgCtrlID(child) == SettingsStatus)
|
||||
? RGB(70, 91, 112) : GetSysColor(COLOR_WINDOWTEXT));
|
||||
SetTextColor(dc, child == v->description || GetDlgCtrlID(child) == SettingsStatus ?
|
||||
v->palette.secondaryText() : GetSysColor(COLOR_WINDOWTEXT));
|
||||
SetBkMode(dc, TRANSPARENT);
|
||||
return reinterpret_cast<LRESULT>(child == v->brand || GetDlgCtrlID(child) == SettingsStatus
|
||||
? v->palette.brush() : GetSysColorBrush(COLOR_WINDOW));
|
||||
@@ -3051,6 +3134,38 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
SettingsStateRefresh refresh{w};
|
||||
HWND pane = v->viewport;
|
||||
if ((id == OcrUseTesseract && HIWORD(wp) == BN_CLICKED) ||
|
||||
((id == OcrExecutable || id == OcrLanguages) && HIWORD(wp) == EN_CHANGE))
|
||||
{
|
||||
value(pane, OcrStatus, L"");
|
||||
return 0;
|
||||
}
|
||||
if ((id == OcrBrowse || id == OcrCheck || id == OcrDownload) && HIWORD(wp) == BN_CLICKED)
|
||||
{
|
||||
handleOcrAction(w, *v, id);
|
||||
return 0;
|
||||
}
|
||||
if ((id == ClipboardAppName && HIWORD(wp) == EN_CHANGE) ||
|
||||
(id == ClipboardExcludedApps && HIWORD(wp) == LBN_SELCHANGE))
|
||||
{
|
||||
updateClipboardAppButtons(pane);
|
||||
return 0;
|
||||
}
|
||||
if (id == ClipboardAddApp && HIWORD(wp) == BN_CLICKED)
|
||||
{
|
||||
addClipboardApp(*v, value(pane, ClipboardAppName));
|
||||
return 0;
|
||||
}
|
||||
if (id == ClipboardRemoveApp && HIWORD(wp) == BN_CLICKED)
|
||||
{
|
||||
const auto row = SendDlgItemMessageW(pane, ClipboardExcludedApps, LB_GETCURSEL, 0, 0);
|
||||
if (row != LB_ERR && static_cast<size_t>(row) < v->draft.excluded.size())
|
||||
{
|
||||
v->draft.excluded.erase(v->draft.excluded.begin() + row);
|
||||
fillClipboardApps(*v, static_cast<int>(row));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (id == 282 && HIWORD(wp) == BN_CLICKED)
|
||||
{
|
||||
writeClipboard(w, textClip(value(pane, 281)));
|
||||
@@ -3071,7 +3186,6 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
showLogs(*v->app);
|
||||
return 0;
|
||||
}
|
||||
if (id == 257) { showOcrOptions(w, v); return 0; }
|
||||
if (id == 263) { collectLayout(v); showAppLanguages(w, v); return 0; }
|
||||
if (handleMouseBindings(w, *v, wp)) return 0;
|
||||
if (id == 259) { collectLayout(v); showChatLanguages(w, v); return 0; }
|
||||
@@ -3703,32 +3817,43 @@ void showHistory(App &app, bool visible)
|
||||
app.pasteTarget = foreground;
|
||||
if (!app.historyWindow)
|
||||
{
|
||||
HWND w = makeWindow(app, L"KSwitcher.History", L"Clipboard history", historyProc, 760, 500);
|
||||
HWND w = makeWindow(app, L"KSwitcher.History", L"Clipboard history", historyProc, HistoryWidth, HistoryHeight);
|
||||
app.historyWindow = w;
|
||||
windowLayoutState(w)->history = true;
|
||||
setWindowResourceIcons(w, app.instance, IDI_KSWITCHER_HISTORY);
|
||||
setWindowTaskbarIdentity(w, IDI_KSWITCHER_HISTORY, L"HrynCo.KSwitcher.ClipboardHistory");
|
||||
auto &layout = *windowLayoutState(w);
|
||||
layout.history = true;
|
||||
auto *v = reinterpret_cast<HistoryView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
v->palette.refresh();
|
||||
control(w, L"STATIC", L"Clipboard history", SS_CENTERIMAGE, HistoryHeading, HistoryMargin, 12, 310, 34);
|
||||
setHistoryHeadingFont(w);
|
||||
control(w, L"STATIC", L"Enter to paste. Shift+Enter to paste as plain text.",
|
||||
SS_CENTERIMAGE, HistoryDescription, HistoryMargin, 46, 420, 19);
|
||||
auto filter = control(w, L"BUTTON", L"★ Pinned only", WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
117, 16, 38, 112, 25);
|
||||
117, HistoryMargin, 95, 112, 25);
|
||||
SendMessageW(filter, BM_SETCHECK, app.historyPinnedOnly ? BST_CHECKED : BST_UNCHECKED, 0);
|
||||
auto computers = control(w,L"BUTTON",app.historyComputers.empty()?L" Computers: All ▾":L" Computers: Selected ▾",
|
||||
WS_TABSTOP | BS_PUSHBUTTON | BS_LEFT,118,136,36,180,28);
|
||||
(void)computers;
|
||||
label(w, L"&Search clipboard history", 328, 12, 400);
|
||||
edit(w, 101, 328, 38, 416);
|
||||
control(w, L"BUTTON", app.historyComputers.empty() ? L" Computers: All ▾" : L" Computers: Selected ▾",
|
||||
WS_TABSTOP | BS_PUSHBUTTON | BS_LEFT, 118, 144, 94, 178, 28);
|
||||
control(w, L"STATIC", L"&Search clipboard history", SS_CENTERIMAGE, 0, 336, 76, 400, 18);
|
||||
edit(w, 101, 336, 95, HistoryWidth - HistoryMargin - 336);
|
||||
constexpr int listTop = 132, actionTop = HistoryFooterTop + 10;
|
||||
auto list = control(w, L"LISTBOX", L"",
|
||||
WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER |
|
||||
WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT |
|
||||
LBS_OWNERDRAWFIXED | LBS_HASSTRINGS,
|
||||
102, 16, 76, 728, 360);
|
||||
102, HistoryMargin, listTop, HistoryWidth - 2 * HistoryMargin, HistoryFooterTop - 12 - listTop);
|
||||
SendMessageW(list, LB_SETITEMHEIGHT, 0, scale(w, 88));
|
||||
button(w, L"&Paste", 110, 16, 452, 90);
|
||||
button(w, L"Plain &text", 111, 114, 452, 100);
|
||||
button(w, L"P&in / unpin", 112, 222, 452, 110);
|
||||
button(w, L"&Delete", 113, 340, 452, 90);
|
||||
button(w, L"&Open item", 114, 438, 452, 100);
|
||||
button(w, L"Clear &history…", 116, 546, 452, 150);
|
||||
button(w, L"&Paste", 110, HistoryMargin, actionTop, 90);
|
||||
button(w, L"Plain &text", 111, 122, actionTop, 100);
|
||||
button(w, L"P&in / unpin", 112, 230, actionTop, 110);
|
||||
button(w, L"&Delete", 113, 348, actionTop, 90);
|
||||
button(w, L"&Open item", 114, 446, actionTop, 100);
|
||||
constexpr int clearWidth = 148;
|
||||
button(w, L"Clear &history…", 116, HistoryWidth - HistoryMargin - clearWidth, actionTop, clearWidth);
|
||||
layout.bottomRight = GetDlgItem(w, 116);
|
||||
arrangeWindow(w);
|
||||
SetWindowSubclass(list, historyKey, 1, (DWORD_PTR)w);
|
||||
SetWindowSubclass(GetDlgItem(w, 101), historyKey, 1, (DWORD_PTR)w);
|
||||
if (app.historyService) {
|
||||
auto *v = (HistoryView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||||
v->rememberedSelection = app.historySelection;
|
||||
v->rememberedTop = app.historyTop;
|
||||
SetDlgItemTextW(w, 101, app.historyQuery.c_str());
|
||||
@@ -3883,9 +4008,14 @@ void showSettings(App &app, bool visible)
|
||||
label(pane, L"Per item MiB", 484, 176, 180);
|
||||
edit(pane, 242, 484, 204, 200);
|
||||
button(pane, L"Clear &history...", 254, 24, 258, 200);
|
||||
label(pane, L"Exclude applications (process names, comma-separated)", 24, 330, 660);
|
||||
edit(pane, 243, 24, 362, 660);
|
||||
button(pane, L"OCR op&tions...", 257, 24, 394, 200);
|
||||
label(pane, L"Exclude applications from clipboard history", 24, 330, 660);
|
||||
control(pane, L"LISTBOX", L"Excluded applications", WS_TABSTOP | WS_BORDER | WS_VSCROLL |
|
||||
LBS_NOTIFY | LBS_NOINTEGRALHEIGHT, ClipboardExcludedApps, 24, 362, 660, 100);
|
||||
const auto clipboardApp = edit(pane, ClipboardAppName, 24, 472, 460);
|
||||
SendMessageW(clipboardApp, EM_SETCUEBANNER, TRUE, reinterpret_cast<LPARAM>(L"Process name, for example chrome.exe"));
|
||||
button(pane, L"&Add", ClipboardAddApp, 490, 471, 62);
|
||||
button(pane, L"&Remove", ClipboardRemoveApp, 558, 471, 78);
|
||||
createAppWindowPicker(pane, ClipboardAppPicker, 652, 471, 32, v->clipboardPickerOutline, createButtonTooltips(pane));
|
||||
page();
|
||||
|
||||
v->snippets = {&app, app.settings.snippets, app.settings.snippets};
|
||||
@@ -3971,6 +4101,15 @@ void showSettings(App &app, bool visible)
|
||||
indexSettingsControl(*v, OpenBaoPage, child);
|
||||
page();
|
||||
|
||||
v->drive = createDriveSettings(pane, *v);
|
||||
layout->controls.push_back({v->drive, {8, 55, 8 + DriveSettingsWidth, 55 + DriveSettingsHeight}});
|
||||
for (HWND child = GetWindow(v->drive, GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
|
||||
indexSettingsControl(*v, GoogleDrivePage, child);
|
||||
page();
|
||||
|
||||
createOcrSettings(pane);
|
||||
page();
|
||||
|
||||
v->splitter = control(w, L"STATIC", L"Resize navigation pane", SS_NOTIFY | WS_TABSTOP,
|
||||
SettingsSplitter, 0, 0, 0, 0);
|
||||
SetWindowSubclass(v->splitter, settingsSplitterProc, 1, reinterpret_cast<DWORD_PTR>(v));
|
||||
@@ -4024,19 +4163,7 @@ void showSettings(App &app, bool) { launchConfiguration(app); }
|
||||
void showSnippets(App &app) { launchConfiguration(app, true); }
|
||||
#endif
|
||||
#ifndef KS_CONFIG_APP
|
||||
void showShortcuts(App &app)
|
||||
{
|
||||
auto &s = app.settings;
|
||||
std::wstring text = L"Next layout: " + s.toggle + L"\nChange case: " + s.casing + L"\nTransliterate: " +
|
||||
s.translit + L"\nUndo: " + s.undo + L"\nClipboard history: " + s.clipboard +
|
||||
L"\nScreen capture: " + s.screenshot + L"\nOpen KSwitcher Files: " + s.filesHotkey.value_or(L"") + L"\n";
|
||||
for (size_t i = 0; i < std::min(app.layouts.size(), s.direct.size()); ++i)
|
||||
if (!s.direct[i].empty())
|
||||
text += L"\n" + app.layouts[i].name + L": " + s.direct[i];
|
||||
text += L"\n\nHistory: Enter to paste, Shift+Enter for plain text,\nCtrl+1…9 to paste, Ctrl+P to pin, "
|
||||
L"Delete to remove,\nCtrl+O to open the full item, Escape to close.";
|
||||
MessageBoxW(app.window, text.c_str(), L"Keyboard shortcuts", MB_OK);
|
||||
}
|
||||
#include "ui_help.inl"
|
||||
void showEntry(App &app, const std::wstring &id)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -192,7 +192,7 @@ void addButtonTooltip(HWND tips, HWND owner, int id, const wchar_t *text)
|
||||
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;
|
||||
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));
|
||||
|
||||
@@ -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); }
|
||||
+94
-34
@@ -7,6 +7,7 @@ struct LanView
|
||||
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;
|
||||
@@ -236,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)
|
||||
@@ -262,8 +266,15 @@ 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)
|
||||
{
|
||||
@@ -275,8 +286,8 @@ void refreshLan(HWND w,LanView &v)
|
||||
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.";
|
||||
value(w,708,v.error.empty() ? pairingStatus : v.error);
|
||||
value(w,705,pending ? L"Waiting..." : L"&Pair");
|
||||
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.";
|
||||
@@ -287,7 +298,7 @@ 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,forgotten.contains(selected) ? L"Click Apply or Save to remove this pair." : peerStatus);
|
||||
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);
|
||||
@@ -301,8 +312,7 @@ void refreshLan(HWND w,LanView &v)
|
||||
{
|
||||
value(w, 731, v.logMessage);
|
||||
ShowWindow(GetDlgItem(w, 731), v.logMessage.empty() ? SW_HIDE : SW_SHOWNA);
|
||||
arrangeWindow(GetParent(w));
|
||||
arrangeWindow(w);
|
||||
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());
|
||||
@@ -310,8 +320,6 @@ void refreshLan(HWND w,LanView &v)
|
||||
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." :
|
||||
@@ -323,8 +331,13 @@ void refreshLan(HWND w,LanView &v)
|
||||
else if(mode==3)inputStatus=L"This PC is controlled remotely. Local physical input takes control back.";
|
||||
if (v.draft.contains("shareInput"))
|
||||
inputStatus = L"Click Apply or Save to apply input sharing changes.";
|
||||
value(w,718,inputStatus);
|
||||
value(w,722,v.snapshot.value("inputNeedsHelp",false)?L"Connection failed — &help":L"Connection &help");
|
||||
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)
|
||||
@@ -373,6 +386,7 @@ 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();
|
||||
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));
|
||||
@@ -419,9 +433,11 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
catch(const std::exception &e) {v->error=wide(e.what());value(w,708,v->error);}
|
||||
return DefWindowProcW(w,msg,wp,lp);
|
||||
}
|
||||
constexpr int LanPadding = 16, LanPairingWidth = 332, LanLayoutLeft = 366, LanLayoutWidth = 348;
|
||||
constexpr int LanDiagnosticsTop = 364;
|
||||
constexpr int LanSettingsWidth = LanLayoutLeft + LanLayoutWidth + LanPadding, LanSettingsHeight = 506;
|
||||
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)
|
||||
{
|
||||
WNDCLASSW panel{};
|
||||
@@ -441,19 +457,19 @@ HWND createLanSettings(HWND pane, App &app)
|
||||
auto layout = new WindowLayout{LanSettingsWidth, LanSettingsHeight, 0, 0, true, true};
|
||||
SetPropW(w, L"WindowLayout", layout);
|
||||
constexpr int left = LanPadding, pairingWidth = LanPairingWidth, right = LanLayoutLeft, rightWidth = LanLayoutWidth;
|
||||
constexpr int gap = 10, rowHeight = 28;
|
||||
constexpr int gap = 10, rowHeight = LanActionHeight;
|
||||
constexpr int discoveryWidth = (pairingWidth - gap) / 2;
|
||||
settingsGroupLabel(w, L"Pairing", left, 14, pairingWidth);
|
||||
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"", WS_TABSTOP | WS_VSCROLL | WS_BORDER | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT,
|
||||
702, left, 98, pairingWidth, 70);
|
||||
control(w, L"STATIC", L"", 0, 710, left, 173, pairingWidth, 33);
|
||||
constexpr int codeTop = 235, actionTop = codeTop + rowHeight + 8;
|
||||
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, 211, pairingWidth);
|
||||
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);
|
||||
@@ -462,17 +478,17 @@ HWND createLanSettings(HWND pane, App &app)
|
||||
button(w, L"&Forget pair", 707, left + 2 * actionStep, actionTop, actionWidth);
|
||||
control(w, L"STATIC", L"", 0, 708, left, actionTop + rowHeight + 5, pairingWidth, 42);
|
||||
|
||||
constexpr int gridTop = 43, gridHeight = 151, inputButtonWidth = (rightWidth - gap) / 2;
|
||||
settingsGroupLabel(w, L"Input sharing", right, 14, rightWidth);
|
||||
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, 200, rightWidth, 35);
|
||||
button(w, L"Enable &input sharing", 715, right, 240, inputButtonWidth);
|
||||
button(w, L"&Stop input sharing", 716, right + inputButtonWidth + gap, 240, inputButtonWidth);
|
||||
control(w, L"STATIC", L"", 0, 718, right, 274, rightWidth, 38);
|
||||
button(w, L"Connection &help", 722, right, 317, 232);
|
||||
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);
|
||||
|
||||
constexpr int fullWidth = right + rightWidth - left;
|
||||
constexpr int logButtonWidth = (fullWidth - gap) / 2;
|
||||
@@ -487,7 +503,44 @@ HWND createLanSettings(HWND pane, App &app)
|
||||
return w;
|
||||
}
|
||||
|
||||
int fitLanSettings(HWND panel, int width)
|
||||
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;
|
||||
@@ -495,6 +548,13 @@ int fitLanSettings(HWND panel, int width)
|
||||
const auto end = layout.controls.size() - (GetWindowTextLengthW(GetDlgItem(panel, 731)) ? 0 : 1);
|
||||
layout.height = fitSettingsColumns(layout, 0, end, width,
|
||||
{LanPadding, LanLayoutLeft + LanLayoutWidth, LanLayoutLeft, LanPadding + LanPairingWidth,
|
||||
LanDiagnosticsTop, 640});
|
||||
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;
|
||||
}
|
||||
+38
-17
@@ -23,10 +23,10 @@ void moveLanMonitor(HWND parent,LanView &v,const std::string &peer,int x,int 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.error.clear();
|
||||
v.layoutError.clear();
|
||||
refreshLanFooter(v);
|
||||
}
|
||||
catch(const std::exception &e){v.error=wide(e.what());}
|
||||
catch(const std::exception &e){v.layoutError=wide(e.what());}
|
||||
refreshLan(parent,v);
|
||||
}
|
||||
LRESULT CALLBACK lanGridProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
@@ -73,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;
|
||||
|
||||
@@ -378,7 +378,7 @@ void drawActionApplicationIcon(HWND editor, const DRAWITEMSTRUCT &item)
|
||||
FrameRect(item.hDC, &folder, ink);
|
||||
FillRect(item.hDC, &tab, ink);
|
||||
}
|
||||
else if (item.CtlID == AppWindowPickerIcon)
|
||||
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};
|
||||
|
||||
@@ -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
|
||||
+26
-4
@@ -6,10 +6,18 @@ struct SyncView
|
||||
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 = w ? reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA)) : nullptr;
|
||||
auto *view = syncEditor(w);
|
||||
return view && view->initialized && (view->forgetPassword ||
|
||||
GetWindowTextLengthW(GetDlgItem(w, 604)) != 0 || syncFields(w) != view->base);
|
||||
}
|
||||
@@ -30,13 +38,15 @@ void updateSyncControls(HWND w, SyncView &view)
|
||||
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() : L"Synchronization is disabled.";
|
||||
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)
|
||||
{
|
||||
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();
|
||||
@@ -48,7 +58,7 @@ nlohmann::json collectSyncDraft(HWND w)
|
||||
{
|
||||
auto &view = *reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
auto config = syncFields(w);
|
||||
if (config.enabled) validateSyncConfig(config);
|
||||
if (automaticSyncEnabled(config)) validateSyncConfig(config);
|
||||
Bytes protectedPassword;
|
||||
if (config.enabled && !view.forgetPassword)
|
||||
{
|
||||
@@ -80,6 +90,8 @@ void reloadSyncEditor(HWND w)
|
||||
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;
|
||||
@@ -115,7 +127,12 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
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;
|
||||
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);
|
||||
refreshSyncFooter(w);
|
||||
@@ -129,6 +146,11 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
v->actionError = false;
|
||||
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;
|
||||
|
||||
@@ -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; }
|
||||
@@ -57,14 +58,14 @@ LRESULT CALLBACK syncConflictsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
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, reinterpret_cast<LONG_PTR>(owner));
|
||||
auto *v = new SyncConflictView{parent, &app, std::move(conflicts), {}};
|
||||
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);
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.7.3";
|
||||
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;
|
||||
|
||||
+311
-20
@@ -3,6 +3,7 @@
|
||||
#include "ocr.h"
|
||||
#include "screenshot.h"
|
||||
#include "lan_pairing.h"
|
||||
#include "google_drive.h"
|
||||
#include "settings_ui.h"
|
||||
#include <iostream>
|
||||
#include <commctrl.h>
|
||||
@@ -25,6 +26,138 @@ void require(bool ok, const char *message)
|
||||
if (!ok) throw std::runtime_error(message);
|
||||
++passed;
|
||||
}
|
||||
void captureSettingsFixture(HWND window, const wchar_t *filename)
|
||||
{
|
||||
RedrawWindow(window, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
RECT area{};
|
||||
GetClientRect(window, &area);
|
||||
const auto dc = GetDC(window);
|
||||
const auto capture = ks::screenshotClip(dc, area.right, area.bottom, {});
|
||||
ReleaseDC(window, dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / filename,
|
||||
ks::encodePng(ks::decodeImage(capture)));
|
||||
}
|
||||
void googleDriveWindowChecks(const std::filesystem::path &root)
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, root);
|
||||
ks::showSettings(app);
|
||||
const auto settings = app.settingsWindow;
|
||||
const auto pane = settingsViewport(settings);
|
||||
const auto navigation = settingsNavigation(settings);
|
||||
const auto driveItem = settingsSection(navigation, 18);
|
||||
const auto baoItem = settingsSection(navigation, 17);
|
||||
require(driveItem && baoItem && TreeView_GetParent(navigation, driveItem) == settingsSection(navigation, 6) &&
|
||||
TreeView_GetParent(navigation, baoItem) == settingsSection(navigation, 6),
|
||||
"Google Drive and OpenBao are siblings under Sync");
|
||||
selectSettingsPage(settings, 18);
|
||||
const auto drive = FindWindowExW(pane, nullptr, L"KSwitcher.GoogleDrive", nullptr);
|
||||
require(drive && IsWindowVisible(drive) && !IsWindowVisible(GetDlgItem(pane, 271)),
|
||||
"Google Drive opens inside Settings and hides OpenBao");
|
||||
RECT panelBounds{};
|
||||
GetWindowRect(drive, &panelBounds);
|
||||
for (int id : {620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632})
|
||||
{
|
||||
const auto control = GetDlgItem(drive, id);
|
||||
RECT bounds{};
|
||||
require(IsWindowVisible(control) && GetWindowRect(control, &bounds) &&
|
||||
bounds.left >= panelBounds.left && bounds.top >= panelBounds.top &&
|
||||
bounds.right <= panelBounds.right && bounds.bottom <= panelBounds.bottom,
|
||||
"Google Drive controls fit inside the rendered panel");
|
||||
}
|
||||
if (!ks::googleDriveConfigured())
|
||||
{
|
||||
wchar_t status[160]{};
|
||||
GetDlgItemTextW(drive, 624, status, std::size(status));
|
||||
require(std::wstring_view(status).find(L"unavailable in this build") != std::wstring_view::npos,
|
||||
"unconfigured OAuth build shows its status");
|
||||
for (int id : {620, 621, 622, 623})
|
||||
require(!IsWindowEnabled(GetDlgItem(drive, id)), "unconfigured OAuth actions are disabled");
|
||||
}
|
||||
const auto dips = [dpi = GetDpiForWindow(settings)](int value) { return MulDiv(value, dpi, 96); };
|
||||
const auto resize = [&](int width, int height)
|
||||
{
|
||||
SetWindowPos(settings, nullptr, 0, 0, dips(width), dips(height), SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
|
||||
};
|
||||
const auto boundsOf = [](HWND window)
|
||||
{
|
||||
RECT bounds{};
|
||||
GetWindowRect(window, &bounds);
|
||||
return bounds;
|
||||
};
|
||||
const auto backupStatus = GetDlgItem(drive, 624);
|
||||
const auto syncStatus = GetDlgItem(drive, 630);
|
||||
const auto backupList = GetDlgItem(drive, 631);
|
||||
require((GetWindowLongPtrW(backupList, GWL_STYLE) & LVS_TYPEMASK) == LVS_REPORT &&
|
||||
Header_GetItemCount(ListView_GetHeader(backupList)) == 3,
|
||||
"backup history is a native report list with three columns");
|
||||
int columnIndex = 0;
|
||||
for (const auto *expected : {L"Backup date", L"Source", L"Size"})
|
||||
{
|
||||
wchar_t caption[48]{};
|
||||
LVCOLUMNW column{LVCF_TEXT};
|
||||
column.pszText = caption;
|
||||
column.cchTextMax = std::size(caption);
|
||||
require(ListView_GetColumn(backupList, columnIndex++, &column) && std::wstring_view(caption) == expected,
|
||||
"the backup history columns identify the date, source and size");
|
||||
}
|
||||
const auto lastButton = GetDlgItem(drive, 629);
|
||||
resize(980, 650);
|
||||
const auto originalStatus = boundsOf(backupStatus);
|
||||
const auto originalSyncStatus = boundsOf(syncStatus);
|
||||
const auto originalList = boundsOf(backupList);
|
||||
resize(1100, 850);
|
||||
const auto expandedStatus = boundsOf(backupStatus);
|
||||
const auto expandedSyncStatus = boundsOf(syncStatus);
|
||||
const auto expandedList = boundsOf(backupList);
|
||||
require((expandedList.bottom - expandedList.top) - (originalList.bottom - originalList.top) >= dips(40) &&
|
||||
std::abs((expandedStatus.bottom - expandedStatus.top) - (originalStatus.bottom - originalStatus.top)) <= dips(1) &&
|
||||
std::abs((expandedSyncStatus.bottom - expandedSyncStatus.top) -
|
||||
(originalSyncStatus.bottom - originalSyncStatus.top)) <= dips(1),
|
||||
"raising the window grows the backup list while keeping status fields compact");
|
||||
const auto expandedPanel = boundsOf(drive);
|
||||
const auto bottom = boundsOf(lastButton).bottom;
|
||||
require(expandedPanel.bottom - bottom >= dips(18) && expandedPanel.bottom - bottom <= dips(22) &&
|
||||
boundsOf(pane).bottom - bottom <= dips(35), "the action block stays against the viewport bottom");
|
||||
for (const auto &status : {expandedStatus, expandedList, expandedSyncStatus})
|
||||
require(std::abs((expandedPanel.right - status.right) - (status.left - expandedPanel.left)) <= dips(2),
|
||||
"the status fields and backup list stretch to the right margin");
|
||||
for (const auto &[first, second] : {std::pair{620, 622}, {621, 623}, {626, 628}, {627, 629}})
|
||||
{
|
||||
const auto left = boundsOf(GetDlgItem(drive, first)), right = boundsOf(GetDlgItem(drive, second));
|
||||
require(std::abs((left.left + right.right) - (expandedPanel.left + expandedPanel.right)) <= dips(2) &&
|
||||
left.right < right.left, "each action row is horizontally centered");
|
||||
}
|
||||
resize(640, 460);
|
||||
const auto compactList = boundsOf(backupList);
|
||||
require(compactList.bottom - compactList.top >= dips(89) &&
|
||||
(GetWindowLongPtrW(pane, GWL_STYLE) & WS_VSCROLL), "short windows keep a usable backup list and scroll");
|
||||
SendMessageW(pane, WM_VSCROLL, SB_BOTTOM, 0);
|
||||
require(boundsOf(lastButton).bottom <= boundsOf(pane).bottom, "bottom actions remain reachable by scrolling");
|
||||
resize(1100, 850);
|
||||
captureSettingsFixture(settings, L"settings-google-drive.png");
|
||||
selectSettingsPage(settings, 17);
|
||||
const auto openBao = GetDlgItem(pane, 271);
|
||||
require(!IsWindowVisible(drive) && IsWindowVisible(openBao), "OpenBao is still accessible");
|
||||
require(!IsWindowEnabled(GetDlgItem(settings, SettingsApply)) &&
|
||||
!std::filesystem::exists(root / L"settings.json"), "navigation leaves the settings draft and disk clean");
|
||||
|
||||
const auto openBaoToggle = GetDlgItem(openBao, 601);
|
||||
const auto driveToggle = GetDlgItem(drive, 625);
|
||||
SendMessageW(openBaoToggle, BM_CLICK, 0, 0);
|
||||
require(IsDlgButtonChecked(openBao, 601) == BST_CHECKED && IsDlgButtonChecked(drive, 625) == BST_UNCHECKED,
|
||||
"choosing OpenBao leaves Drive automatic sync off");
|
||||
selectSettingsPage(settings, 18);
|
||||
// Exercise the provider selector without depending on a Google credential.
|
||||
EnableWindow(driveToggle, TRUE);
|
||||
SendMessageW(driveToggle, BM_CLICK, 0, 0);
|
||||
require(IsDlgButtonChecked(drive, 625) == BST_CHECKED && IsDlgButtonChecked(openBao, 601) == BST_UNCHECKED,
|
||||
"choosing Drive clears OpenBao in the same draft");
|
||||
selectSettingsPage(settings, 17);
|
||||
SendMessageW(openBaoToggle, BM_CLICK, 0, 0);
|
||||
require(IsDlgButtonChecked(openBao, 601) == BST_CHECKED && IsDlgButtonChecked(drive, 625) == BST_UNCHECKED &&
|
||||
!ks::syncVisible(root), "switching back clears Drive and leaves the saved provider intact until Apply");
|
||||
DestroyWindow(settings);
|
||||
}
|
||||
void settingsWindowStateChecks(const std::filesystem::path &root)
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, root);
|
||||
@@ -121,6 +254,87 @@ std::wstring pickTestApplication(HWND picker, bool cancel = false)
|
||||
DestroyWindow(target);
|
||||
return pickedApp;
|
||||
}
|
||||
void settingsEditorResizeChecks(const std::filesystem::path &root)
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, root);
|
||||
app.settings.toggle = app.settings.casing = app.settings.translit = app.settings.undo = L"";
|
||||
app.settings.clipboard = app.settings.screenshot = L"";
|
||||
app.settings.filesHotkey = L"";
|
||||
app.settings.direct.assign(app.layouts.size(), L"");
|
||||
ks::showSettings(app);
|
||||
const auto settings = app.settingsWindow;
|
||||
const auto pane = settingsViewport(settings);
|
||||
const auto dips = [dpi = GetDpiForWindow(settings)](int n) { return MulDiv(n, dpi, 96); };
|
||||
const auto resize = [&](int height, int width = 1000)
|
||||
{
|
||||
SetWindowPos(settings, nullptr, 0, 0, dips(width), dips(height), SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
|
||||
};
|
||||
const auto bounds = [](HWND window)
|
||||
{
|
||||
RECT result{};
|
||||
GetWindowRect(window, &result);
|
||||
return result;
|
||||
};
|
||||
const auto field = [&](int id) { return bounds(GetDlgItem(pane, id)); };
|
||||
const auto grows = [&](int page, int first, int second, int action)
|
||||
{
|
||||
selectSettingsPage(settings, page);
|
||||
resize(610);
|
||||
const auto before = field(first), otherBefore = field(second);
|
||||
resize(760);
|
||||
const auto after = field(first), otherAfter = field(second);
|
||||
require(after.bottom - after.top - (before.bottom - before.top) >= dips(125),
|
||||
"primary editor grows with the window");
|
||||
if (second)
|
||||
require(otherAfter.bottom - otherAfter.top - (otherBefore.bottom - otherBefore.top) >= dips(125),
|
||||
"second editor grows with the window");
|
||||
const auto bottom = action ? field(action).bottom : after.bottom;
|
||||
require(bounds(pane).bottom - bottom <= dips(30) && bottom <= bounds(pane).bottom,
|
||||
"the last editor or action row stays near the bottom");
|
||||
};
|
||||
grows(16, 416, 0, 0);
|
||||
captureSettingsFixture(settings, L"settings-custom-replacements.png");
|
||||
grows(4, 301, 303, 320);
|
||||
require(std::abs(field(310).top - field(320).top) <= dips(2), "snippet actions share the bottom row");
|
||||
captureSettingsFixture(settings, L"settings-snippets-responsive.png");
|
||||
grows(5, 731, 733, 739);
|
||||
require(field(737).top >= field(731).bottom && field(740).top >= field(733).bottom,
|
||||
"mouse test controls stay below the stretched lists");
|
||||
captureSettingsFixture(settings, L"settings-mouse-responsive.png");
|
||||
resize(760, 635);
|
||||
require(field(731).bottom <= field(733).top, "narrow Mouse layout still stacks without overlap");
|
||||
resize(760);
|
||||
|
||||
selectSettingsPage(settings, 19);
|
||||
const auto ocrLanguage = app.settings.tesseractLanguages == L"eng" ? L"ukr" : L"eng";
|
||||
SetDlgItemTextW(pane, 503, ocrLanguage);
|
||||
selectSettingsPage(settings, 3);
|
||||
const HWND list = GetDlgItem(pane, 243);
|
||||
const auto count = [&] { return SendMessageW(list, LB_GETCOUNT, 0, 0); };
|
||||
const auto initial = count();
|
||||
SetDlgItemTextW(pane, 244, L"Clipboard-Fixture.exe");
|
||||
SendDlgItemMessageW(pane, 245, BM_CLICK, 0, 0);
|
||||
require(count() == initial + 1 && IsWindowEnabled(GetDlgItem(settings, SettingsApply)),
|
||||
"manual clipboard exclusions update the Settings draft");
|
||||
SetDlgItemTextW(pane, 244, L"clipboard-fixture");
|
||||
SendDlgItemMessageW(pane, 245, BM_CLICK, 0, 0);
|
||||
require(count() == initial + 1, "process names with and without .exe are deduplicated");
|
||||
SendDlgItemMessageW(pane, 246, BM_CLICK, 0, 0);
|
||||
require(count() == initial, "remove deletes the selected exclusion");
|
||||
const auto picked = ks::snippetAppName(pickTestApplication(GetDlgItem(pane, 247)));
|
||||
require(count() == initial + 1 && app.settings.excluded.size() == static_cast<size_t>(initial),
|
||||
"the shared crosshair adds a draft exclusion");
|
||||
SendMessageW(settings, WM_COMMAND, SettingsApply, 0);
|
||||
const auto saved = ks::loadSettings(root / L"settings.json", app.layouts);
|
||||
require(app.settings.excluded.back() == picked && saved.excluded == app.settings.excluded,
|
||||
"applying persists the picked exclusion through normal Settings");
|
||||
require(app.settings.tesseractLanguages == ocrLanguage && saved.tesseractLanguages == ocrLanguage,
|
||||
"Apply persists the OCR draft from another Settings page");
|
||||
captureSettingsFixture(settings, L"settings-clipboard-exclusions.png");
|
||||
selectSettingsPage(settings, 19);
|
||||
captureSettingsFixture(settings, L"settings-image-text-recognition.png");
|
||||
DestroyWindow(settings);
|
||||
}
|
||||
void lanWindowLayoutChecks(const std::filesystem::path &root)
|
||||
{
|
||||
const std::string peer(32,'b');
|
||||
@@ -172,9 +386,9 @@ void lanWindowLayoutChecks(const std::filesystem::path &root)
|
||||
std::abs((currentLog.right - currentLog.left) - (previousLog.right - previousLog.left)) <= 1 &&
|
||||
currentLog.left == permission.left && std::abs(previousLog.right - permission.right) <= 1,
|
||||
"diagnostic logs have a separate full-width group with equal actions");
|
||||
const int gap = MulDiv(10, dpi, 96);
|
||||
const int gap = generate.left - code.right;
|
||||
require(code.top == generate.top && code.bottom == generate.bottom &&
|
||||
std::abs(generate.left - code.right - gap) <= 1, "code input and Generate code share the same row");
|
||||
gap > 0, "code input and Generate code share the same row");
|
||||
require(pair.top == cancel.top && cancel.top == forget.top &&
|
||||
pair.bottom == cancel.bottom && cancel.bottom == forget.bottom &&
|
||||
std::abs((pair.right - pair.left) - (cancel.right - cancel.left)) <= 1 &&
|
||||
@@ -188,6 +402,70 @@ void lanWindowLayoutChecks(const std::filesystem::path &root)
|
||||
ReleaseDC(lan,dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-compact-layout.png",
|
||||
ks::encodePng(ks::decodeImage(screenshot)));
|
||||
const auto settings = app.settingsWindow;
|
||||
const auto pane = settingsViewport(settings);
|
||||
const auto resize = [&](int width, int height) {
|
||||
SetWindowPos(settings, nullptr, 0, 0, MulDiv(width, dpi, 96), MulDiv(height, dpi, 96),
|
||||
SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
|
||||
};
|
||||
const auto originalList = boundsFor(702);
|
||||
const auto originalGrid = boundsFor(721);
|
||||
resize(1140, 830);
|
||||
const auto actionRowsAlign = [&] {
|
||||
const auto codeRow = boundsFor(703);
|
||||
const auto pairRow = boundsFor(705);
|
||||
for (int id : {704, 715, 716})
|
||||
{
|
||||
const auto control = boundsFor(id);
|
||||
require(control.top == codeRow.top && control.bottom == codeRow.bottom,
|
||||
"pairing code and input-sharing controls align horizontally");
|
||||
}
|
||||
for (int id : {706, 707, 722})
|
||||
{
|
||||
const auto control = boundsFor(id);
|
||||
require(control.top == pairRow.top && control.bottom == pairRow.bottom,
|
||||
"pairing actions and connection help align horizontally");
|
||||
}
|
||||
};
|
||||
actionRowsAlign();
|
||||
const auto wideList = boundsFor(702), wideGrid = boundsFor(721);
|
||||
const auto wideLog = boundsFor(728);
|
||||
RECT viewport{};
|
||||
GetWindowRect(pane, &viewport);
|
||||
require(wideList.top == wideGrid.top && wideList.bottom == wideGrid.bottom &&
|
||||
wideList.bottom - wideList.top > originalList.bottom - originalList.top &&
|
||||
wideGrid.right - wideGrid.left > originalGrid.right - originalGrid.left,
|
||||
"the two device work areas align and grow on a wide, tall window");
|
||||
require(viewport.right - wideGrid.right <= MulDiv(30, dpi, 96) &&
|
||||
wideLog.bottom <= viewport.bottom && viewport.bottom - wideLog.bottom <= MulDiv(33, dpi, 96),
|
||||
"monitor layout reaches the right margin and diagnostics sit near the bottom");
|
||||
wchar_t peerRow[128]{};
|
||||
SendDlgItemMessageW(lan, 702, LB_GETTEXT, 0, reinterpret_cast<LPARAM>(peerRow));
|
||||
require(std::wstring_view(peerRow).find(L"Paired · offline") != std::wstring_view::npos,
|
||||
"the computer row identifies an offline pairing");
|
||||
captureSettingsFixture(settings, L"settings-manage-computers.png");
|
||||
wchar_t inputStatus[256]{};
|
||||
GetDlgItemTextW(lan, 718, inputStatus, std::size(inputStatus));
|
||||
SetDlgItemTextW(lan, 718,
|
||||
L"The selected computer is offline. Check its network connection and enable discovery. "
|
||||
L"If it still does not appear, open Connection help and check the Windows firewall on both computers.");
|
||||
resize(1090, 830);
|
||||
actionRowsAlign();
|
||||
require(boundsFor(718).bottom < boundsFor(715).top && boundsFor(722).bottom < boundsFor(729).top,
|
||||
"wrapped connection status keeps its space and diagnostics stay below the action rows");
|
||||
SetDlgItemTextW(lan, 718, inputStatus);
|
||||
resize(635, 610);
|
||||
const auto narrowList = boundsFor(702), narrowGrid = boundsFor(721);
|
||||
require(narrowList.bottom < narrowGrid.top && narrowList.left == narrowGrid.left &&
|
||||
std::abs(narrowList.right - narrowGrid.right) <= 1 &&
|
||||
(GetWindowLongPtrW(pane, GWL_STYLE) & WS_VSCROLL),
|
||||
"narrow windows stack the computer list and monitor layout");
|
||||
captureSettingsFixture(settings, L"settings-manage-computers-narrow.png");
|
||||
SendMessageW(pane, WM_VSCROLL, SB_BOTTOM, 0);
|
||||
GetWindowRect(pane, &viewport);
|
||||
require(boundsFor(728).bottom <= viewport.bottom &&
|
||||
!(GetWindowLongPtrW(pane, GWL_STYLE) & WS_HSCROLL),
|
||||
"diagnostics remain reachable vertically in a narrow window");
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
std::cout<<"Computers layout verified at "<<dpi<<" DPI.\n";
|
||||
}
|
||||
@@ -470,6 +748,14 @@ int main(int argc,char **argv)
|
||||
auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-chat-tests-" + std::to_wstring(GetCurrentProcessId()));
|
||||
try
|
||||
{
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--google-drive-layout")
|
||||
{
|
||||
googleDriveWindowChecks(root);
|
||||
std::filesystem::remove_all(root);
|
||||
CoUninitialize();
|
||||
std::cout << "PASS Google Drive Settings (" << passed << " checks)\n";
|
||||
return 0;
|
||||
}
|
||||
if(argc==2 && std::string_view(argv[1])=="--lan-layout")
|
||||
{
|
||||
lanWindowLayoutChecks(root);
|
||||
@@ -496,6 +782,7 @@ int main(int argc,char **argv)
|
||||
}
|
||||
contextChecks();
|
||||
settingsWindowStateChecks(root / L"window-state");
|
||||
settingsEditorResizeChecks(root / L"responsive-editors");
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, root);
|
||||
require(!app.layouts.empty(), "installed layouts available");
|
||||
@@ -533,23 +820,25 @@ int main(int argc,char **argv)
|
||||
require(saveEnabled(),"invalid text remains an unsaved edit");
|
||||
SetDlgItemTextW(settingsViewport(parent),240,originalLimit);
|
||||
require(!saveEnabled(),"restoring valid original text clears dirty state");
|
||||
SendMessageW(parent,WM_COMMAND,257,0);
|
||||
HWND ocr=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
|
||||
require(ocr!=nullptr,"OCR preferences open");
|
||||
wchar_t languages[128]{}; GetDlgItemTextW(ocr,503,languages,128);
|
||||
SetDlgItemTextW(ocr,503,L"eng");
|
||||
SendMessageW(ocr,WM_COMMAND,IDCANCEL,0);
|
||||
require(!saveEnabled(),"cancelled child changes leave Settings clean");
|
||||
SendMessageW(parent,WM_COMMAND,257,0);
|
||||
ocr=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
|
||||
SetDlgItemTextW(ocr,503,std::wstring(languages)==L"eng"?L"ukr":L"eng");
|
||||
SendMessageW(ocr,WM_COMMAND,IDOK,0);
|
||||
require(!IsWindow(ocr) && saveEnabled(),"accepted OCR edits enable parent Save");
|
||||
SendMessageW(parent,WM_COMMAND,257,0);
|
||||
ocr=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
|
||||
SetDlgItemTextW(ocr,503,languages);
|
||||
SendMessageW(ocr,WM_COMMAND,IDOK,0);
|
||||
require(!saveEnabled(),"reverting OCR draft in child clears parent dirty state");
|
||||
selectSettingsPage(parent, 19);
|
||||
const auto ocrPane = settingsViewport(parent);
|
||||
require(IsWindowVisible(GetDlgItem(ocrPane, 501)) && IsWindowVisible(GetDlgItem(ocrPane, 503)) &&
|
||||
IsWindowVisible(GetDlgItem(ocrPane, 505)) && IsWindowEnabled(parent) &&
|
||||
!findTestWindow(L"KSwitcher.OcrOptions", nullptr), "OCR preferences open inline");
|
||||
wchar_t languages[128]{};
|
||||
GetDlgItemTextW(ocrPane, 503, languages, std::size(languages));
|
||||
const auto replacement = std::wstring_view(languages) == L"eng" ? L"ukr" : L"eng";
|
||||
SetDlgItemTextW(ocrPane, 503, replacement);
|
||||
selectSettingsPage(parent, 3);
|
||||
require(saveEnabled() && app.settings.tesseractLanguages == languages &&
|
||||
IsWindowVisible(GetDlgItem(ocrPane, 243)) && !IsWindowVisible(GetDlgItem(ocrPane, 503)) &&
|
||||
!GetDlgItem(ocrPane, 257), "Clipboard stays selectable and the unsaved OCR draft survives navigation");
|
||||
selectSettingsPage(parent, 19);
|
||||
wchar_t draftLanguages[128]{};
|
||||
GetDlgItemTextW(ocrPane, 503, draftLanguages, std::size(draftLanguages));
|
||||
require(std::wstring_view(draftLanguages) == replacement, "returning to OCR shows the unsaved edit");
|
||||
SetDlgItemTextW(ocrPane, 503, languages);
|
||||
require(!saveEnabled(), "reverting the OCR draft clears the dirty state");
|
||||
const auto correction = settingsViewport(parent);
|
||||
require(!GetDlgItem(correction, 255), "General no longer has a correction options button");
|
||||
selectSettingsPage(parent, 16);
|
||||
@@ -565,11 +854,13 @@ int main(int argc,char **argv)
|
||||
SendMessageW(GetDlgItem(correction, 414), BM_CLICK, 0, 0);
|
||||
require(!saveEnabled(), "reverting an inline correction edit disables Save");
|
||||
HWND navigation = settingsNavigation(parent);
|
||||
constexpr int sections = 18;
|
||||
constexpr int sections = 20;
|
||||
require(navigation && TreeView_GetCount(navigation) == sections &&
|
||||
TreeView_GetParent(navigation, settingsSection(navigation, 10)) == settingsSection(navigation, 7) &&
|
||||
TreeView_GetParent(navigation, settingsSection(navigation, 11)) == settingsSection(navigation, 0),
|
||||
"correction and computer settings are nested under their sections");
|
||||
require(TreeView_GetParent(navigation, settingsSection(navigation, 19)) == settingsSection(navigation, 3),
|
||||
"image text recognition is nested under Clipboard");
|
||||
for (int section = 12; section <= 16; ++section)
|
||||
require(TreeView_GetParent(navigation, settingsSection(navigation, section)) == settingsSection(navigation, 11),
|
||||
"each correction subsection belongs to the correction branch");
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,8 @@ try {
|
||||
Open-Picker $side
|
||||
$rows = @(Read-Picker)
|
||||
$row = [Array]::IndexOf($rows, 'FTP')
|
||||
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'KSwitcher LAN') {
|
||||
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)
|
||||
@@ -98,12 +99,14 @@ try {
|
||||
[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 + 1)
|
||||
$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 }
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe"
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class FilesQuickViewProbe {
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr parent, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-Until([scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 100; $attempt++) {
|
||||
if (& $Condition) { return }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
throw "Timed out waiting for: $Condition"
|
||||
}
|
||||
|
||||
$exe = (Resolve-Path $Executable).Path
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
|
||||
$saved = @{}
|
||||
foreach ($name in $names) {
|
||||
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
|
||||
}
|
||||
$fixture = [IO.Directory]::CreateTempSubdirectory('ks-files-quick-view-')
|
||||
try {
|
||||
$left = $fixture.CreateSubdirectory('left')
|
||||
$right = $fixture.CreateSubdirectory('right')
|
||||
$document = Join-Path $left.FullName 'preview.txt'
|
||||
[IO.File]::WriteAllText($document, 'Quick View fixture')
|
||||
$key.SetValue('LeftWide', 1, 'DWord')
|
||||
$key.SetValue('RightWide', 1, 'DWord')
|
||||
$key.SetValue('LeftPath', $left.FullName, 'String')
|
||||
$key.SetValue('RightPath', $right.FullName, 'String')
|
||||
$key.SetValue('LeftCursor', $document, 'String')
|
||||
$key.DeleteValue('RightCursor', $false)
|
||||
$key.DeleteValue('WindowPlacement', $false)
|
||||
|
||||
$process = Start-Process -FilePath $exe -PassThru
|
||||
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
$window = $process.MainWindowHandle
|
||||
Wait-Until { [FilesQuickViewProbe]::Activate($window) }
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
$leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102)
|
||||
$rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103)
|
||||
$rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141)
|
||||
$rightPath = [FilesQuickViewProbe]::GetDlgItem($window, 143)
|
||||
if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) {
|
||||
throw 'Expected both file panels in the test window.'
|
||||
}
|
||||
Wait-Until { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) }
|
||||
$keyboard.SendKeys('^q')
|
||||
Wait-Until {
|
||||
$hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158)
|
||||
$hostWindow -ne [IntPtr]::Zero -and [FilesQuickViewProbe]::IsWindowVisible($hostWindow)
|
||||
}
|
||||
foreach ($control in $rightList, $rightHeading, $rightPath) {
|
||||
if ([FilesQuickViewProbe]::IsWindowVisible($control)) {
|
||||
throw 'A file panel control can draw over the Quick View content.'
|
||||
}
|
||||
}
|
||||
if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' }
|
||||
|
||||
$keyboard.SendKeys('^q')
|
||||
Wait-Until { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero }
|
||||
foreach ($control in $rightList, $rightHeading, $rightPath) {
|
||||
if (![FilesQuickViewProbe]::IsWindowVisible($control)) {
|
||||
throw 'A file panel control remained hidden after closing Quick View.'
|
||||
}
|
||||
}
|
||||
'Quick View hides the covered list and chrome, then restores the same controls.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() }
|
||||
}
|
||||
foreach ($name in $names) {
|
||||
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
|
||||
else { $key.DeleteValue($name, $false) }
|
||||
}
|
||||
$key.Dispose()
|
||||
$path = [IO.Path]::GetFullPath($fixture.FullName)
|
||||
if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and
|
||||
[IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) {
|
||||
[IO.Directory]::Delete($path, $true)
|
||||
}
|
||||
}
|
||||
+209
-91
@@ -9,6 +9,7 @@
|
||||
#include <cmath>
|
||||
#include "input_pause.h"
|
||||
#include "settings_ui.h"
|
||||
#include "../resources/resource.h"
|
||||
static int settingsCloseChoice = IDNO;
|
||||
static int settingsClosePrompts = 0;
|
||||
static void CALLBACK answerSettingsClose(HWND, UINT, UINT_PTR, DWORD)
|
||||
@@ -29,6 +30,15 @@ LRESULT CALLBACK countControlMoves(HWND w, UINT message, WPARAM wp, LPARAM lp, U
|
||||
}
|
||||
namespace ks {
|
||||
struct InputRegressionAccess {
|
||||
static void finishHistoryPreviews(App &app)
|
||||
{
|
||||
std::deque<std::function<void()>> jobs;
|
||||
{
|
||||
std::lock_guard lock(app.jobsMutex);
|
||||
jobs.swap(app.jobs);
|
||||
}
|
||||
for (const auto &job : jobs) job();
|
||||
}
|
||||
static LRESULT CALLBACK probeInput(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR context) {
|
||||
auto &app = *reinterpret_cast<App *>(context);
|
||||
static bool queuedSnippet = false;
|
||||
@@ -209,6 +219,133 @@ struct InputRegressionAccess {
|
||||
}
|
||||
};
|
||||
}
|
||||
template<class Require>
|
||||
static void historyLayoutChecks(ks::App &app, const std::filesystem::path &temp, Require require,
|
||||
bool capturePreview = false)
|
||||
{
|
||||
if (!app.history) app.history=std::make_unique<ks::History>(temp/L"history-layout");
|
||||
ks::showHistory(app,false);
|
||||
auto history=app.historyWindow;
|
||||
require(history&&!IsWindowVisible(history),"history layout tested without changing focus");
|
||||
const auto historyIcon = reinterpret_cast<HICON>(SendMessageW(history, WM_GETICON, ICON_BIG, 0));
|
||||
require(historyIcon && historyIcon != LoadIconW(app.instance, MAKEINTRESOURCEW(IDI_KSWITCHER)) &&
|
||||
SendMessageW(history, WM_GETICON, ICON_SMALL, 0),
|
||||
"clipboard history supplies separate taskbar and caption icons");
|
||||
require(!GetDlgItem(history,105),"history creates no RichEdit control before formatted content is displayed");
|
||||
{
|
||||
app.history=std::make_unique<ks::History>(temp/L"history-search");
|
||||
app.history->add(ks::textClip(L"згенеруй приклад"),L"test",app.settings);
|
||||
app.history->add(ks::textClip(L"unrelated entry"),L"test",app.settings);
|
||||
// This App has no general worker: a search on that queue can never finish.
|
||||
auto originalFocus=GetFocus();
|
||||
auto pumpUntil=[&](int count) {
|
||||
auto deadline=GetTickCount64()+3000;
|
||||
do {
|
||||
MSG message{};
|
||||
while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) {
|
||||
TranslateMessage(&message); DispatchMessageW(&message);
|
||||
}
|
||||
if(SendDlgItemMessageW(history,102,LB_GETCOUNT,0,0)==count) return true;
|
||||
Sleep(5);
|
||||
} while(GetTickCount64()<deadline);
|
||||
return false;
|
||||
};
|
||||
ks::refreshHistory(app);
|
||||
require(pumpUntil(2),"history loads independently of general worker queue");
|
||||
SetDlgItemTextW(history,101,L"згенеруй");
|
||||
require(pumpUntil(1),"typing filters history via debounce without focus change");
|
||||
SetDlgItemTextW(history,101,L"missing query");
|
||||
require(pumpUntil(0),"unmatched search clears history list");
|
||||
SetDlgItemTextW(history,101,L"");
|
||||
require(pumpUntil(2),"clearing search restores history");
|
||||
require(GetFocus()==originalFocus,"history search preserves focus");
|
||||
SendDlgItemMessageW(history,102,LB_SETCURSEL,1,0);
|
||||
ks::refreshHistory(app); // A result may still be in flight when closing.
|
||||
SendDlgItemMessageW(history,101,WM_KEYDOWN,VK_ESCAPE,0);
|
||||
require(!IsWindowVisible(history) && !GetDlgItem(history,105),
|
||||
"Escape closes history and leaves no RichEdit control");
|
||||
SendMessageW(history,WM_TIMER,1,0); // KillTimer cannot retract a posted timer message.
|
||||
require(pumpUntil(0),"closing history releases list strings");
|
||||
auto until=GetTickCount64()+250;
|
||||
while(GetTickCount64()<until) {
|
||||
MSG message{};
|
||||
while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) {
|
||||
TranslateMessage(&message); DispatchMessageW(&message);
|
||||
}
|
||||
Sleep(5);
|
||||
}
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCOUNT,0,0)==0,
|
||||
"late search results do not refill closed history");
|
||||
ks::refreshHistory(app);
|
||||
require(pumpUntil(2),"history reloads after releasing hidden rows");
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==1,
|
||||
"history retains selected record across close and reload");
|
||||
SendMessageW(history,WM_CLOSE,0,0);
|
||||
ks::Pixels screenshot{160,104,ks::Bytes(160 * 104 * 4,255)};
|
||||
for (int y = 0; y < screenshot.height; ++y)
|
||||
for (int x = 0; x < screenshot.width; ++x)
|
||||
{
|
||||
const auto i = (y * screenshot.width + x) * 4;
|
||||
screenshot.bgra[i] = 230 - y;
|
||||
screenshot.bgra[i + 1] = 100 + x / 2;
|
||||
screenshot.bgra[i + 2] = 60 + y;
|
||||
}
|
||||
app.history->add(ks::Clip{{ks::imageDib(screenshot)}},L"screenshot",app.settings);
|
||||
require(app.history->entries().front().image,"new screenshot is the newest history entry");
|
||||
ks::showHistory(app);
|
||||
require(pumpUntil(3),"reopening history loads the new screenshot");
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==0 &&
|
||||
SendDlgItemMessageW(history,102,LB_GETTOPINDEX,0,0)==0,
|
||||
"fresh history invocation selects and reveals newest screenshot instead of saved selection");
|
||||
if (capturePreview)
|
||||
{
|
||||
RedrawWindow(history, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
ks::InputRegressionAccess::finishHistoryPreviews(app);
|
||||
pumpUntil(3);
|
||||
RedrawWindow(history, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
RECT historyClient{};
|
||||
GetClientRect(history, &historyClient);
|
||||
auto dc = GetDC(history);
|
||||
const auto preview = ks::screenshotClip(dc, historyClient.right, historyClient.bottom, {});
|
||||
ReleaseDC(history, dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"clipboard-history.png",
|
||||
ks::encodePng(ks::decodeImage(preview)));
|
||||
}
|
||||
SendDlgItemMessageW(history,102,LB_SETCURSEL,2,0);
|
||||
app.history->add(ks::textClip(L"background clipboard update"),L"test",app.settings);
|
||||
ks::refreshHistory(app);
|
||||
require(pumpUntil(4),"background refresh loads a new item");
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==3,
|
||||
"background refresh preserves the selected record while browsing");
|
||||
ShowWindow(history,SW_HIDE);
|
||||
}
|
||||
auto childRect=[&](int id) { RECT r{}; GetWindowRect(GetDlgItem(history,id),&r); MapWindowPoints(nullptr,history,(POINT*)&r,2); return r; };
|
||||
RECT historyFrame{}; GetWindowRect(history,&historyFrame);
|
||||
auto listBefore=childRect(102),searchBefore=childRect(101),buttonBefore=childRect(110),clearBefore=childRect(116);
|
||||
require(childRect(119).bottom <= childRect(120).top && childRect(120).bottom < searchBefore.top &&
|
||||
searchBefore.bottom < listBefore.top && listBefore.bottom < buttonBefore.top,
|
||||
"history header, filters, results and actions have separate rows");
|
||||
SetWindowPos(history,nullptr,0,0,historyFrame.right-historyFrame.left+120,historyFrame.bottom-historyFrame.top+180,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
auto listAfter=childRect(102),searchAfter=childRect(101),buttonAfter=childRect(110);
|
||||
require(listAfter.right-listBefore.right==120 && listAfter.bottom-listBefore.bottom==180,"history list fills added width and height");
|
||||
require(searchAfter.right-searchBefore.right==120 && searchAfter.top==searchBefore.top,"history search grows horizontally only");
|
||||
require(buttonAfter.top-buttonBefore.top==180 && buttonAfter.bottom-listAfter.bottom==buttonBefore.bottom-listBefore.bottom,"history actions stay below list after resize");
|
||||
const auto clearAfter = childRect(116);
|
||||
require(clearAfter.right - clearBefore.right == 120 && clearAfter.top == buttonAfter.top,
|
||||
"clear history stays at the right edge of the action row");
|
||||
SetWindowPos(history,nullptr,0,0,historyFrame.right-historyFrame.left,historyFrame.bottom-historyFrame.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
require(EqualRect(&listBefore,&(listAfter=childRect(102))),"history resize roundtrip restores geometry");
|
||||
// Reproduce a row height left over from another DPI without changing desktop settings.
|
||||
UINT historyDpi=GetDpiForWindow(history);
|
||||
for (int staleDpi : {96, 144, 192, 240}) {
|
||||
SendDlgItemMessageW(history,102,LB_SETITEMHEIGHT,0,MulDiv(88,staleDpi,96));
|
||||
SendMessageW(history,WM_DPICHANGED,MAKELONG(historyDpi,historyDpi),(LPARAM)&historyFrame);
|
||||
require(SendDlgItemMessageW(history,102,LB_GETITEMHEIGHT,0,0)==MulDiv(88,historyDpi,96),
|
||||
"DPI change updates owner-drawn history row height through layout subclass");
|
||||
require(EqualRect(&listBefore,&(listAfter=childRect(102))),"DPI refresh preserves history list geometry");
|
||||
}
|
||||
DestroyWindow(history);
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
if (argc == 2 && std::string(argv[1]) == "--input-pause") return testInputPause();
|
||||
if (argc == 2 && std::string(argv[1]) == "--input-pause-resident") {
|
||||
@@ -238,6 +375,71 @@ int main(int argc, char **argv) {
|
||||
try {
|
||||
INITCOMMONCONTROLSEX controls{sizeof(controls),ICC_STANDARD_CLASSES|ICC_LISTVIEW_CLASSES};
|
||||
InitCommonControlsEx(&controls);
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--help-layout")
|
||||
{
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, temp);
|
||||
app.settings.clipboard = L"Ctrl+Shift+F10";
|
||||
ks::showHelp(app);
|
||||
const auto window = app.helpWindow;
|
||||
const auto text = [&](int id) {
|
||||
wchar_t buffer[32768]{};
|
||||
GetDlgItemTextW(window, id, buffer, std::size(buffer));
|
||||
return std::wstring(buffer);
|
||||
};
|
||||
require(window && IsWindowVisible(window), "help opens in its own visible window");
|
||||
const auto icon = reinterpret_cast<HICON>(SendMessageW(window, WM_GETICON, ICON_BIG, 0));
|
||||
require(icon && icon != LoadIconW(app.instance, MAKEINTRESOURCEW(IDI_KSWITCHER)) &&
|
||||
SendMessageW(window, WM_GETICON, ICON_SMALL, 0),
|
||||
"help has its own caption and taskbar icons");
|
||||
require(text(812) == L"Getting started" && text(813).find(L"notification area") != std::wstring::npos,
|
||||
"the getting started topic is read from the executable");
|
||||
require(TreeView_GetCount(GetDlgItem(window, 811)) > 45, "the tree includes the embedded manuals");
|
||||
for (int id : {IDR_HELP_GUIDE, IDR_HELP_MANUAL, IDR_HELP_FILES, IDR_HELP_COMPUTERS})
|
||||
require(FindResourceW(app.instance, MAKEINTRESOURCEW(id), RT_RCDATA) != nullptr,
|
||||
"each manual can be opened offline");
|
||||
SetDlgItemTextW(window, 810, L"Google Drive settings backup");
|
||||
require(text(812) == L"Google Drive settings backup" && text(813).find(L"automatic provider") != std::wstring::npos,
|
||||
"search opens the detailed backup and sync topic");
|
||||
SetDlgItemTextW(window, 810, L"zzzz-unused-help-term");
|
||||
require(text(812) == L"No matching topics", "search explains when no topic matches");
|
||||
ks::showShortcuts(app);
|
||||
require(app.helpWindow == window && text(812) == L"Keyboard shortcuts" &&
|
||||
text(813).find(L"Ctrl+Shift+F10") != std::wstring::npos,
|
||||
"the shortcuts command opens the same window with the current bindings");
|
||||
ks::showHelp(app);
|
||||
const auto bounds = [&](int id) {
|
||||
RECT rect{};
|
||||
GetWindowRect(GetDlgItem(window, id), &rect);
|
||||
MapWindowPoints(nullptr, window, reinterpret_cast<POINT *>(&rect), 2);
|
||||
return rect;
|
||||
};
|
||||
const auto tree = bounds(811), body = bounds(813), close = bounds(IDCANCEL);
|
||||
require(tree.right < body.left && body.bottom < close.top, "navigation, reading pane and footer are distinct");
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
RedrawWindow(window, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
auto dc = GetDC(window);
|
||||
const auto preview = ks::screenshotClip(dc, client.right, client.bottom, {});
|
||||
ReleaseDC(window, dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"offline-help.png",
|
||||
ks::encodePng(ks::decodeImage(preview)));
|
||||
SendMessageW(window, WM_COMMAND, IDCANCEL, 0);
|
||||
require(!app.helpWindow && !IsWindow(window), "Close releases the help window");
|
||||
}
|
||||
std::filesystem::remove_all(temp);
|
||||
std::cout << "Passed " << checks << " offline help checks\n";
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--history-layout") {
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, temp);
|
||||
historyLayoutChecks(app, temp, require, true);
|
||||
}
|
||||
std::filesystem::remove_all(temp);
|
||||
std::cout << "Passed " << checks << " clipboard history checks\n";
|
||||
return 0;
|
||||
}
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr),true,temp/L"snippet-scopes");
|
||||
app.window=CreateWindowExW(0,L"STATIC",L"Snippet scope test",0,0,0,0,0,HWND_MESSAGE,nullptr,GetModuleHandleW(nullptr),nullptr);
|
||||
@@ -868,9 +1070,13 @@ int main(int argc, char **argv) {
|
||||
auto events = GetDlgItem(pane, 733);
|
||||
auto visible = [&](int id) { return (GetWindowLongPtrW(GetDlgItem(pane, id), GWL_STYLE) & WS_VISIBLE) != 0; };
|
||||
auto selectPage = [&](int index) { selectSettingsPage(settings, index); };
|
||||
require(TreeView_GetCount(navigation) == 18, "all Settings sections are listed");
|
||||
require(TreeView_GetCount(navigation) == 20, "all Settings sections are listed");
|
||||
selectPage(3);
|
||||
require(visible(257) && !visible(301), "OCR options are in Clipboard");
|
||||
require(visible(243) && !visible(501), "Clipboard lists excluded apps separately from OCR");
|
||||
require(TreeView_GetParent(navigation, settingsSection(navigation, 19)) == settingsSection(navigation, 3),
|
||||
"Image text recognition is a child of Clipboard");
|
||||
selectPage(19);
|
||||
require(visible(501) && !visible(243), "Image text recognition shows OCR options");
|
||||
selectPage(6);
|
||||
require(visible(271) && !visible(262), "Sync opens the embedded OpenBao page");
|
||||
selectPage(7);
|
||||
@@ -1286,95 +1492,7 @@ int main(int argc, char **argv) {
|
||||
"inline correction edits trigger the unsaved settings warning");
|
||||
}
|
||||
selectSettingsPage(app.settingsWindow, 0);
|
||||
if (!app.history) app.history=std::make_unique<ks::History>(temp/L"history-layout");
|
||||
ks::showHistory(app,false);
|
||||
auto history=app.historyWindow;
|
||||
require(history&&!IsWindowVisible(history),"history layout tested without changing focus");
|
||||
require(!GetDlgItem(history,105),"history creates no RichEdit control before formatted content is displayed");
|
||||
{
|
||||
app.history=std::make_unique<ks::History>(temp/L"history-search");
|
||||
app.history->add(ks::textClip(L"згенеруй приклад"),L"test",app.settings);
|
||||
app.history->add(ks::textClip(L"unrelated entry"),L"test",app.settings);
|
||||
// This App has no general worker: a search on that queue can never finish.
|
||||
auto originalFocus=GetFocus();
|
||||
auto pumpUntil=[&](int count) {
|
||||
auto deadline=GetTickCount64()+3000;
|
||||
do {
|
||||
MSG message{};
|
||||
while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) {
|
||||
TranslateMessage(&message); DispatchMessageW(&message);
|
||||
}
|
||||
if(SendDlgItemMessageW(history,102,LB_GETCOUNT,0,0)==count) return true;
|
||||
Sleep(5);
|
||||
} while(GetTickCount64()<deadline);
|
||||
return false;
|
||||
};
|
||||
ks::refreshHistory(app);
|
||||
require(pumpUntil(2),"history loads independently of general worker queue");
|
||||
SetDlgItemTextW(history,101,L"згенеруй");
|
||||
require(pumpUntil(1),"typing filters history via debounce without focus change");
|
||||
SetDlgItemTextW(history,101,L"missing query");
|
||||
require(pumpUntil(0),"unmatched search clears history list");
|
||||
SetDlgItemTextW(history,101,L"");
|
||||
require(pumpUntil(2),"clearing search restores history");
|
||||
require(GetFocus()==originalFocus,"history search preserves focus");
|
||||
SendDlgItemMessageW(history,102,LB_SETCURSEL,1,0);
|
||||
ks::refreshHistory(app); // A result may still be in flight when closing.
|
||||
SendDlgItemMessageW(history,101,WM_KEYDOWN,VK_ESCAPE,0);
|
||||
require(!IsWindowVisible(history) && !GetDlgItem(history,105),
|
||||
"Escape closes history and leaves no RichEdit control");
|
||||
SendMessageW(history,WM_TIMER,1,0); // KillTimer cannot retract a posted timer message.
|
||||
require(pumpUntil(0),"closing history releases list strings");
|
||||
auto until=GetTickCount64()+250;
|
||||
while(GetTickCount64()<until) {
|
||||
MSG message{};
|
||||
while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) {
|
||||
TranslateMessage(&message); DispatchMessageW(&message);
|
||||
}
|
||||
Sleep(5);
|
||||
}
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCOUNT,0,0)==0,
|
||||
"late search results do not refill closed history");
|
||||
ks::refreshHistory(app);
|
||||
require(pumpUntil(2),"history reloads after releasing hidden rows");
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==1,
|
||||
"history retains selected record across close and reload");
|
||||
SendMessageW(history,WM_CLOSE,0,0);
|
||||
ks::Pixels screenshot{2,2,ks::Bytes(16,255)};
|
||||
app.history->add(ks::Clip{{ks::imageDib(screenshot)}},L"screenshot",app.settings);
|
||||
require(app.history->entries().front().image,"new screenshot is the newest history entry");
|
||||
ks::showHistory(app);
|
||||
require(pumpUntil(3),"reopening history loads the new screenshot");
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==0 &&
|
||||
SendDlgItemMessageW(history,102,LB_GETTOPINDEX,0,0)==0,
|
||||
"fresh history invocation selects and reveals newest screenshot instead of saved selection");
|
||||
SendDlgItemMessageW(history,102,LB_SETCURSEL,2,0);
|
||||
app.history->add(ks::textClip(L"background clipboard update"),L"test",app.settings);
|
||||
ks::refreshHistory(app);
|
||||
require(pumpUntil(4),"background refresh loads a new item");
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==3,
|
||||
"background refresh preserves the selected record while browsing");
|
||||
ShowWindow(history,SW_HIDE);
|
||||
}
|
||||
auto childRect=[&](int id) { RECT r{}; GetWindowRect(GetDlgItem(history,id),&r); MapWindowPoints(nullptr,history,(POINT*)&r,2); return r; };
|
||||
RECT historyFrame{}; GetWindowRect(history,&historyFrame);
|
||||
auto listBefore=childRect(102),searchBefore=childRect(101),buttonBefore=childRect(110);
|
||||
SetWindowPos(history,nullptr,0,0,historyFrame.right-historyFrame.left+120,historyFrame.bottom-historyFrame.top+180,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
auto listAfter=childRect(102),searchAfter=childRect(101),buttonAfter=childRect(110);
|
||||
require(listAfter.right-listBefore.right==120 && listAfter.bottom-listBefore.bottom==180,"history list fills added width and height");
|
||||
require(searchAfter.right-searchBefore.right==120 && searchAfter.top==searchBefore.top,"history search grows horizontally only");
|
||||
require(buttonAfter.top-buttonBefore.top==180 && buttonAfter.bottom-listAfter.bottom==buttonBefore.bottom-listBefore.bottom,"history actions stay below list after resize");
|
||||
SetWindowPos(history,nullptr,0,0,historyFrame.right-historyFrame.left,historyFrame.bottom-historyFrame.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
require(EqualRect(&listBefore,&(listAfter=childRect(102))),"history resize roundtrip restores geometry");
|
||||
// Reproduce a row height left over from another DPI without changing desktop settings.
|
||||
UINT historyDpi=GetDpiForWindow(history);
|
||||
for (int staleDpi : {96, 144, 192, 240}) {
|
||||
SendDlgItemMessageW(history,102,LB_SETITEMHEIGHT,0,MulDiv(88,staleDpi,96));
|
||||
SendMessageW(history,WM_DPICHANGED,MAKELONG(historyDpi,historyDpi),(LPARAM)&historyFrame);
|
||||
require(SendDlgItemMessageW(history,102,LB_GETITEMHEIGHT,0,0)==MulDiv(88,historyDpi,96),
|
||||
"DPI change updates owner-drawn history row height through layout subclass");
|
||||
require(EqualRect(&listBefore,&(listAfter=childRect(102))),"DPI refresh preserves history list geometry");
|
||||
}
|
||||
historyLayoutChecks(app, temp, require);
|
||||
auto settings=app.settingsWindow;
|
||||
require(SendDlgItemMessageW(settingsViewport(settings), 209,BM_GETCHECK,0,0)==BST_UNCHECKED,"automatic screenshot editor checkbox defaults off");
|
||||
require(settings&&!IsWindowVisible(settings),"settings layout tested without changing user focus");
|
||||
|
||||
@@ -46,6 +46,30 @@ void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected)
|
||||
wchar_t label[100]{};
|
||||
require(GetMenuStringW(menu, 0, label, std::size(label), MF_BYPOSITION) &&
|
||||
std::wstring_view(label).starts_with(expected), "incorrect input state in tray menu");
|
||||
HMENU help{};
|
||||
MENUITEMINFOW donation{sizeof(donation), MIIM_BITMAP};
|
||||
bool donationSeparated = false;
|
||||
const auto menuTitle = [&](HMENU source, int index) {
|
||||
if (!GetMenuStringW(source, index, label, std::size(label), MF_BYPOSITION)) return std::wstring_view{};
|
||||
const std::wstring_view text(label);
|
||||
return text.substr(0, text.find(L'\t'));
|
||||
};
|
||||
for (int i = 0, count = GetMenuItemCount(menu); i < count; ++i) {
|
||||
const auto title = menuTitle(menu, i);
|
||||
if (title == L"&Donate via Monobank" && i > 0 && i + 1 < count) {
|
||||
donationSeparated = (GetMenuState(menu, i - 1, MF_BYPOSITION) & MF_SEPARATOR) &&
|
||||
(GetMenuState(menu, i + 1, MF_BYPOSITION) & MF_SEPARATOR);
|
||||
GetMenuItemInfoW(menu, i, TRUE, &donation);
|
||||
}
|
||||
if (title == L"H&elp") {
|
||||
help = GetSubMenu(menu, i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
require(donationSeparated && donation.hbmpItem, "tray donation item has an icon and both separators");
|
||||
require(help && GetMenuItemCount(help) == 2 && menuTitle(help, 0) == L"&User guide" &&
|
||||
menuTitle(help, 1) == L"&About KSwitcher",
|
||||
"tray Help submenu contains User guide and About KSwitcher");
|
||||
require(PostMessageW(popup, WM_CHAR, L'i', 0), "cannot select input menu item");
|
||||
until([&] { return !IsWindow(popup); }, "tray action did not close menu");
|
||||
query(resident, WM_NULL);
|
||||
|
||||
+82
-1
@@ -87,7 +87,88 @@ int main(int argc, char **argv)
|
||||
auto window=CreateWindowW(cls.lpszClassName,L"Editor test",WS_POPUP,0,0,320,240,app.window,nullptr,app.instance,&c);
|
||||
auto require=[](bool ok,const char *message){ if(!ok) throw std::runtime_error(message); };
|
||||
require(window!=nullptr,"editor creation");
|
||||
ks::edit(window,c); ShowWindow(window,SW_HIDE);
|
||||
ks::edit(window,c);
|
||||
if (argc > 1 && std::string_view(argv[1]) == "--layout-only")
|
||||
{
|
||||
const auto editorIcon = reinterpret_cast<HICON>(SendMessageW(window, WM_GETICON, ICON_BIG, 0));
|
||||
require(editorIcon && editorIcon != LoadIconW(app.instance, MAKEINTRESOURCEW(IDI_KSWITCHER)) &&
|
||||
SendMessageW(window, WM_GETICON, ICON_SMALL, 0),
|
||||
"screenshot editor supplies separate taskbar and caption icons");
|
||||
const auto dip = [window](int n) { return MulDiv(n, GetDpiForWindow(window), 96); };
|
||||
const auto bounds = [&](int id) {
|
||||
RECT result{};
|
||||
GetWindowRect(GetDlgItem(window, id), &result);
|
||||
MapWindowPoints(nullptr, window, reinterpret_cast<POINT *>(&result), 2);
|
||||
return result;
|
||||
};
|
||||
MINMAXINFO limits{};
|
||||
SendMessageW(window, WM_GETMINMAXINFO, 0, reinterpret_cast<LPARAM>(&limits));
|
||||
const auto checkLayout = [&] {
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
const auto copy = bounds(13), save = bounds(28), undo = bounds(18);
|
||||
const auto zoom = bounds(ks::EditorZoom), hint = bounds(ks::EditorStatus);
|
||||
require(undo.right < copy.left && copy.right < save.left &&
|
||||
save.right <= client.right - dip(15) && copy.top == save.top,
|
||||
"Copy and Save stay together at the right edge of the toolbar");
|
||||
require(bounds(44).bottom < c.canvas.top && c.canvas.bottom < zoom.top &&
|
||||
zoom.right < hint.left && hint.right <= client.right - dip(15),
|
||||
"options, canvas, zoom and contextual hint have distinct bounds");
|
||||
};
|
||||
const UINT flags = SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE;
|
||||
SetWindowPos(window, nullptr, 0, 0, limits.ptMinTrackSize.x, dip(610), flags);
|
||||
checkLayout();
|
||||
const auto narrowSave = bounds(28);
|
||||
SetWindowPos(window, nullptr, 0, 0, dip(1000), dip(660), flags);
|
||||
checkLayout();
|
||||
require(bounds(28).left > narrowSave.left, "primary actions follow the right edge while resizing");
|
||||
c.image = std::make_unique<ks::Surface>(640, 360);
|
||||
ks::fillSurface(c.image->dc, {0, 0, 640, 360}, RGB(255, 255, 255));
|
||||
ks::fillSurface(c.image->dc, {0, 0, 155, 360}, RGB(232, 241, 248));
|
||||
ks::fillSurface(c.image->dc, {155, 0, 640, 62}, RGB(246, 249, 252));
|
||||
{
|
||||
const ks::SavedDc saved(c.image->dc);
|
||||
SelectObject(c.image->dc, c.font);
|
||||
SetBkMode(c.image->dc, TRANSPARENT);
|
||||
SetTextColor(c.image->dc, RGB(28, 52, 76));
|
||||
RECT header{175, 20, 630, 50};
|
||||
DrawTextW(c.image->dc, L"Clipboard history", -1, &header, DT_SINGLELINE | DT_NOPREFIX);
|
||||
}
|
||||
for (int y : {92, 156, 220, 284})
|
||||
{
|
||||
ks::fillSurface(c.image->dc, {175, y, 222, y + 40}, RGB(224, 235, 246));
|
||||
ks::fillSurface(c.image->dc, {239, y + 5, 459, y + 10}, RGB(193, 207, 220));
|
||||
ks::fillSurface(c.image->dc, {239, y + 22, 380, y + 27}, RGB(226, 233, 240));
|
||||
}
|
||||
ks::Mark mark{{165, 78}, {613, 145}, 0};
|
||||
mark.color = RGB(26, 106, 207);
|
||||
mark.shape = ks::ScreenshotShape::Rectangle;
|
||||
c.marks = {mark};
|
||||
ks::layout(window, c);
|
||||
RedrawWindow(window, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
const auto dc = GetDC(window);
|
||||
const auto preview = ks::screenshotClip(dc, client.right, client.bottom, {});
|
||||
const auto footerColor = GetPixel(dc, dip(5), c.canvas.bottom + dip(5));
|
||||
const auto canvasColor = GetPixel(dc, dip(5), c.canvas.top + dip(5));
|
||||
ReleaseDC(window, dc);
|
||||
require(footerColor == c.palette.color(), "footer uses the Settings surface color");
|
||||
if (!c.palette.highContrast)
|
||||
require(canvasColor != footerColor, "image canvas and footer are visually distinct");
|
||||
wchar_t zoomText[32]{};
|
||||
GetDlgItemTextW(window, ks::EditorZoom, zoomText, std::size(zoomText));
|
||||
require(std::wstring_view(zoomText).starts_with(L"Zoom ") && !c.statusText.empty(),
|
||||
"zoom is visible separately from the contextual hint");
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"screenshot-editor.png",
|
||||
ks::encodePng(ks::decodeImage(preview)));
|
||||
DestroyWindow(window);
|
||||
DestroyWindow(app.window);
|
||||
CoUninitialize();
|
||||
std::cout << "Passed screenshot editor layout checks\n";
|
||||
return 0;
|
||||
}
|
||||
ShowWindow(window,SW_HIDE);
|
||||
require(GetWindow(window,GW_OWNER)==nullptr && (GetWindowLongPtrW(window,GWL_EXSTYLE)&WS_EX_APPWINDOW),
|
||||
"editor is an independent Alt+Tab application window");
|
||||
require(GetDlgItem(window,50)!=nullptr && c.statusHeight>0,"status bar is created");
|
||||
|
||||
@@ -60,6 +60,21 @@ int main()
|
||||
saveSyncConfig(root, config);
|
||||
auto rawConfig = parse(readFile(root / L"sync.json", 16384));
|
||||
require(!rawConfig.contains("password") && !rawConfig.contains("token"), "no secrets in config");
|
||||
auto drive = config;
|
||||
drive.enabled = false;
|
||||
drive.driveEnabled = true;
|
||||
require(decodeSyncConfig(encodeSyncConfig(drive)) == drive && automaticSyncEnabled(drive) &&
|
||||
automaticSyncProviderName(drive) == L"Google Drive", "Google Drive selection preserves OpenBao connection fields");
|
||||
auto both = drive;
|
||||
both.enabled = true;
|
||||
rejects([&] { decodeSyncConfig(encodeSyncConfig(both)); }, "reject two automatic providers on read");
|
||||
rejects([&] { saveSyncConfig(root, both); }, "reject two automatic providers on write");
|
||||
const auto oldBase = bytes(Json{{"profile", "openbao"}});
|
||||
const auto driveBase = bytes(Json{{"profile", "google-drive"}});
|
||||
saveSyncBase(root, config, oldBase);
|
||||
saveSyncBase(root, drive, driveBase, "fixture-account");
|
||||
require(loadSyncBase(root, config) == oldBase && loadSyncBase(root, drive, "fixture-account") == driveBase &&
|
||||
loadSyncBase(root, drive, "different-account").empty(), "separate OpenBao and account-specific Drive baselines");
|
||||
Settings local;
|
||||
local.autostart = true; local.elevatedAutostart = true; local.tesseractPath = L"C:\\private\\tesseract.exe";
|
||||
local.history = false;
|
||||
|
||||
+62
-1
@@ -37,9 +37,70 @@ def draw_files_icon(size):
|
||||
return image
|
||||
|
||||
|
||||
def draw_window_icon(kind):
|
||||
scale = 32
|
||||
image = Image.new('RGBA', (32 * scale, 32 * scale))
|
||||
draw = ImageDraw.Draw(image)
|
||||
indigo, white, mint = '#4F46E5', '#FFFFFF', '#5EEAD4'
|
||||
|
||||
def box(left, top, right, bottom, radius, color, outline=None, width=1):
|
||||
draw.rounded_rectangle(tuple(round(v * scale) for v in (left, top, right, bottom)),
|
||||
radius=round(radius * scale), fill=color, outline=outline,
|
||||
width=round(width * scale))
|
||||
|
||||
if kind == 'donate':
|
||||
# The steamed cup and saucer from resources/support/donate-en.svg,
|
||||
# with a thicker stroke to remain legible in the 16 px tray menu.
|
||||
def cup_line(points):
|
||||
draw.line([(round(x * scale), round(y * scale)) for x, y in points],
|
||||
fill=indigo, width=round(2.2 * scale), joint='curve')
|
||||
|
||||
box(18, 13, 28, 21, 4, None, indigo, 2.2)
|
||||
box(6, 12, 22, 25, 5, white, indigo, 2.2)
|
||||
draw.rectangle((6 * scale, 12 * scale, 22 * scale, 17 * scale), fill=white)
|
||||
cup_line([(6.9, 17), (6.9, 12.8), (21.1, 12.8), (21.1, 17)])
|
||||
cup_line([(4, 28), (24, 28)])
|
||||
for x in (10, 14, 18):
|
||||
cup_line([(x, 5), (x, 8)])
|
||||
return image.resize((256, 256), Image.Resampling.LANCZOS)
|
||||
|
||||
box(1, 1, 31, 31, 7, indigo)
|
||||
if kind == 'history':
|
||||
box(8, 8, 24, 26, 3, indigo, white, 2.5)
|
||||
box(11.5, 5.5, 20.5, 11.5, 2, mint)
|
||||
box(12, 14, 20, 16.2, 1.1, white)
|
||||
box(12, 18.5, 18, 20.7, 1.1, white)
|
||||
elif kind == 'screenshot':
|
||||
box(7, 7, 24, 24, 2, indigo, white, 2.5)
|
||||
draw.polygon([(round(x * scale), round(y * scale)) for x, y in
|
||||
[(14, 22), (24, 12), (29, 17), (19, 27), (12, 29)]], fill=indigo)
|
||||
draw.polygon([(round(x * scale), round(y * scale)) for x, y in
|
||||
[(16, 23), (24, 15), (27, 18), (19, 26), (15, 27)]], fill=mint)
|
||||
else:
|
||||
for color, points in (
|
||||
(white, [(5, 8), (11, 8), (16, 11), (21, 8), (27, 8), (27, 23),
|
||||
(21, 23), (16, 26), (11, 23), (5, 23)]),
|
||||
(indigo, [(7.5, 10.5), (11, 10.5), (14.8, 13), (14.8, 22.3),
|
||||
(11.5, 20.5), (7.5, 20.5)]),
|
||||
(indigo, [(17.2, 13), (21, 10.5), (24.5, 10.5), (24.5, 20.5),
|
||||
(20.5, 20.5), (17.2, 22.3)]),
|
||||
):
|
||||
draw.polygon([(round(x * scale), round(y * scale)) for x, y in points], fill=color)
|
||||
box(19, 14, 23, 16, 1, mint)
|
||||
box(19, 17.5, 23, 19.4, 1, mint)
|
||||
return image.resize((256, 256), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--files-only', action='store_true', help='Regenerate only the main Files icon.')
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument('--files-only', action='store_true', help='Regenerate only the main Files icon.')
|
||||
mode.add_argument('--window-icons-only', action='store_true', help='Regenerate the window and tray menu icons.')
|
||||
args = parser.parse_args()
|
||||
if not args.files_only:
|
||||
for kind in ('history', 'screenshot', 'help', 'donate'):
|
||||
draw_window_icon(kind).save(root / f'kswitcher-{kind}.ico', sizes=icon_sizes)
|
||||
if args.window_icons_only:
|
||||
raise SystemExit
|
||||
frames = [draw_files_icon(size) for size, _ in icon_sizes]
|
||||
frames[-1].save(root / 'kswitcher-files.ico', sizes=icon_sizes, append_images=frames[:-1])
|
||||
if args.files_only:
|
||||
|
||||
Reference in new issue
Block a user