diff --git a/CMakeLists.txt b/CMakeLists.txt index 961c86c..df067ad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.7.2 LANGUAGES CXX RC) +project(KSwitcher VERSION 0.7.3 LANGUAGES CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() @@ -51,7 +51,7 @@ add_library(kscore src/lan_files.cpp src/lan_channel.cpp src/lan_input.cpp src/l target_link_libraries(KSwitcherFiles PRIVATE kscore) target_include_directories(kscore PUBLIC src PRIVATE vendor) target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00) -target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore) +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" diff --git a/LAN-PREVIEW.md b/LAN-PREVIEW.md index fdeea2f..89dd299 100644 --- a/LAN-PREVIEW.md +++ b/LAN-PREVIEW.md @@ -9,9 +9,9 @@ with all online paired computers: history and the active clipboard. ## Trusted LAN clients -Open **Settings → Computers → Manage computers → Trusted clients** and choose **Add client…**. Select the Dirlume executable and confirm. Dirlume can list existing LAN pairs, browse their drives, and download regular files using each remote computer’s file-access permissions. Pairing credentials stay in the resident KSwitcher process. +Open **Settings → Computers → Manage computers → Trusted clients** and choose **Add client…**. Select the Dirlume executable, confirm, then click **Save** in Settings. Dirlume can list existing LAN pairs, browse their drives, and download regular files using each remote computer’s file-access permissions. Pairing credentials stay in the resident KSwitcher process. -Select an executable and choose **Remove** to revoke access. Add the executable again after updating it, since KSwitcher checks the approved path and SHA-256 fingerprint. +Select an executable, choose **Remove**, then click **Save** to revoke access. Add the executable again after updating it, since KSwitcher checks the approved path and SHA-256 fingerprint. ## Remote files and diagnostic logs @@ -43,14 +43,15 @@ the local resident process running and log downloads enabled on the remote PC. In wide windows, Pairing and Input sharing appear side by side. In narrow windows, they stack above Diagnostic logs. Connection help is under Input sharing. 3. Match the computer name and instance-ID prefix displayed on the other PC. - Select each other, generate one code, enter that same code on both, then click - Pair on both within two minutes. Spaces, hyphens and uppercase hex are accepted. + Enable discovery and click **Save** on each PC to make peers visible. + Select each other, generate one code, and enter it on both. Click **Pair**, then + **Apply** or **Save** on each PC within two minutes. Use **Apply** to keep the pairing status visible. Spaces, hyphens and uppercase hex are accepted. 4. Pair each physical input source with every destination it must control. For unrestricted control from any PC, pair every pair of PCs. Drag monitors into neighboring grid cells and arrange the same physical layout relative to each local PC. For A → B → C, A sees B at (1,0), C at (2,0); B sees A at (-1,0), - C at (1,0). Enable input sharing on all PCs. The button controls all pairs, - independently of the selected list item. Positions save immediately. + C at (1,0). Enable input sharing and click **Save** on all PCs to apply sharing + and the monitor layout. The input sharing setting covers all pairs. 5. Stop MWB or another mouse/keyboard router on both computers before trying KSwitcher input sharing, to avoid two tools forwarding the same events. 6. Wait for the authenticated input connection. Move the cursor through the diff --git a/README.md b/README.md index c776405..e2800a0 100644 --- a/README.md +++ b/README.md @@ -114,18 +114,20 @@ Run `build/KSwitcher.exe`, or extract `dist/KSwitcher-win-x64.zip` and run the e The build also refreshes the release copy in `build/release/`. Exit KSwitcher before rebuilding. The application lives in the notification area. Right-click its icon for Settings, Snippets and history. Double-click the tray icon to open Settings, the bold default menu item. -Closing Settings with unsaved changes (including accepted auto-correction or OCR options) -asks whether to save, discard changes, or keep editing. Unchanged settings close without a prompt. +**Apply** and **Save** at the bottom of Settings commit the pending edits across every page, +including Mouse, Manage computers and OpenBao. **Apply** keeps the current page open. +**Save** closes Settings. With pending edits, **Cancel** or closing the window asks whether +to discard them or keep editing. When there are no pending edits, **Close** exits without a prompt. If saving fails, the window stays open with your edits intact. Settings displays **No unsaved settings** when the draft matches the saved settings. If **Start with Windows** is enabled, **Save** remains available to recheck the autostart path. -The Computers window applies and saves network changes immediately, separately from Settings. -Pairing shows the target computer and remaining wait time; enter the same code and click **Pair** on both PCs. +Enable discovery and click **Save** on each PC before looking for peers. Enter the same code and +click **Pair**, then **Apply** or **Save**, on both PCs. Use **Apply** to watch the target and +remaining wait time without closing Settings. The code stays visible for copying or retry until the pair is saved. A saved pair still requires input sharing to be enabled on both PCs. Input automatically tries direct TCP, reverse TCP (after 1.5 seconds), and encrypted UDP over discovery (after 5 seconds). Both PCs need an updated build for all fallback methods. The connection status identifies the selected transport. If attempts remain unsuccessful for 15 seconds, **Connection help** explains checks and provides copyable administrator PowerShell commands for the running executable on that PC. Run each PC's own command locally; rules allow only the local subnet. Commands are never executed automatically. -**Unsaved changes — click Save to apply** appears for pending edits, including accepted -chat-language, auto-correction and OCR changes. Cancelling a child dialog or restoring +The Settings footer shows pending edits, including accepted chat-language, auto-correction and OCR changes. Cancelling a child dialog or restoring the original values clears its pending changes. Snippets saved in their own window remain saved independently; the Settings indicator reflects any other pending edits. Menus support access keys: press the underlined letter while the menu is open (for example, @@ -722,23 +724,22 @@ authentication mount (default `userpass`). Use the same profile on each of your administrator-provisioned private access, not public account registration. Non-root namespaces, reverse-proxy URL prefixes, MFA login flows and other providers are not implemented yet. -Enable synchronization and choose **Save and sync** on the OpenBao page. This button saves the -connection settings separately from the main Settings draft. -When synchronization is disabled, connection fields and sync actions are inactive. Check **Enable -synchronization** to make them available. To disable an existing connection, uncheck it and click -**Save connection**. This preserves the saved connection and password without starting a sync request. +Check **Enable synchronization**, enter the connection details and click **Save** at the bottom of +Settings. Use **Sync now** on the OpenBao page to start an immediate sync with the saved connection. +To disable synchronization and keep the saved password, uncheck **Enable synchronization** and click +**Save**. **Disconnect / forget password** remains available while synchronization is disabled. A blank password keeps the existing Windows credential for that server, login mount and username. The password is saved in Windows Credential Manager, not in settings exports, logs or the remote profile. HTTPS certificate validation is mandatory and redirects are refused. Login tokens are kept in memory for one sync attempt, with best-effort self-revocation afterwards. Configure bounded token lifetimes on the server as well (for example a 5-minute default and 10-minute maximum). -**Disconnect / forget password** disables synchronization and removes the current connection's +Choose **Disconnect / forget password**, then click **Save** to disable synchronization and remove the current connection's saved credential. A request already sent to the server may still complete; its downloaded settings will not be applied after the connection changes. Old credentials for other connection identities can be removed in Windows Credential Manager under `KSwitcher.Sync/`. -On the first connection, **Save and sync** merges the existing profiles without +On the first connection, **Sync now** merges the existing profiles without requiring a whole-profile replacement. Independent entries (such as snippets, exclusions and replacement pairs) are combined. Different values for the same setting remain on their respective sides and appear in **Resolve individual conflicts...**; no value is guessed without a common history. @@ -747,7 +748,7 @@ Nonconflicting changes synchronize immediately, and unresolved conflicts survive - **Upload local** creates the remote profile or replaces it with this PC's saved shared settings. - **Download remote** replaces this PC's shared settings with the server profile. - If the server has no profile yet, choose **Upload local** to create it. -- Unsaved edits in Settings are not synchronized. After a successful **Download remote**, the open Settings window refreshes automatically and keeps the selected section. The download confirmation warns that unsaved edits will be discarded. +- Unsaved edits in Settings are not synchronized. After a successful **Download remote**, the open Settings window refreshes automatically and keeps the selected section. The download confirmation warns that pending edits to shared settings will be discarded. - The status distinguishes downloading, downloaded settings, no local changes and failure. HTTP 400 errors identify authentication, download or upload; field errors remain visible until the next action. Once connected, the resident checks at startup, every **10 minutes**, and about two seconds after saving settings, on a separate @@ -787,7 +788,7 @@ Connection details and credentials stay local so you can sign in again after rei Clipboard history, screenshots and dictionary files are never uploaded. Full synchronization identifies missing keyboard layouts by language (when Windows can identify it) and exact ID. Install the same layout variant, or select **Keep this PC's layouts and layout shortcuts** -and click **Save and sync**. This device-local option keeps the entire +and click **Save**. This device-local option keeps the entire local layout cycle and its direct shortcuts unchanged while synchronizing the other shared settings. The server's layout cycle and direct shortcuts are preserved on automatic sync and explicit Upload; Download also keeps the local layout configuration. Later syncs cannot erase missing server layouts diff --git a/Release/README.md b/Release/README.md index 6de9a6f..09e9323 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,17 @@ # Latest Windows release +## v0.7.3 — 2026-11-24 + +- **Apply** commits pending edits across Settings and keeps the current page open. **Save** commits the same edits and closes Settings. **Close** appears when the draft is clean. **Cancel** asks before discarding pending edits. +- Mouse actions, discovery, pairing, monitor positions, input sharing, trusted clients, diagnostic log permissions and the OpenBao connection are part of the Settings draft. For new LAN pairs, enter the same code and choose **Pair**, then **Apply** or **Save**, on both PCs. Use **Sync now** to synchronize with a saved OpenBao connection. +- Settings and the diagnostic log viewer follow the Windows accent and contrast settings. + +**Українською.** + +- **Apply** зберігає правки всіх розділів Settings і залишає поточну сторінку відкритою. **Save** зберігає ті самі правки й закриває Settings. За відсутності незбережених правок доступна кнопка **Close**. **Cancel** запитує підтвердження перед відкиданням чернетки. +- Дії миші, пошук комп’ютерів, сполучення, розташування моніторів, спільний ввід, довірені клієнти, дозвіл на завантаження журналів і підключення OpenBao входять до чернетки Settings. Для нового сполучення введіть однаковий код і натисніть **Pair**, а тоді **Apply** або **Save** на обох ПК. **Sync now** запускає синхронізацію зі збереженим підключенням OpenBao. +- Settings і переглядач діагностичних журналів враховують акцентний колір і параметри контрастності Windows. + ## v0.7.2 — 2026-11-24 Nested entries in the Settings navigation tree have a compact indent that follows Windows display scaling, including when you move Settings between monitors. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index d6b5e80..6a9743e 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -e363ed0f3eaae5b893f05734194bcf3f74f79bd93d373c0be4e631579c6fe8b4 KSwitcher-win-x64.zip +64914772013a5cd30a1065c2ecd3c55f7ed92aa26172ddfc914c4fc5ecfa1710 KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index d1567d4..8741e46 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,166 +1,166 @@ { + "version": "0.7.3", + "schema": 1, "files": [ { - "size": 2431488, - "sha256": "e48f79af357cbf98b993678164ae02a340da0640831d4087fb428dab1dca81ac", - "path": "KSwitcher.exe" + "path": "KSwitcher.exe", + "size": 6045773, + "sha256": "920fbc0f3d5ec8a7e99b5ebe859a53d459444f0bdc351a029ceff904861b7a52" }, { - "size": 2457600, - "sha256": "59b11034a4671c3db921db86138ace31565860363583dc15261252356de2a4f5", - "path": "KSwitcher.Config.exe" + "path": "KSwitcher.Config.exe", + "size": 6153758, + "sha256": "74c18b8f199e1b40379c80426185a34977d6304adbf84cc67ba5a67d0e71c0f3" }, { - "size": 3397632, - "sha256": "d6dbaa721ff896b3ec1c3101dab75b81a63a0c3c1e5c57cfe9d84e52f1d821c7", - "path": "KSwitcher.Screenshot.exe" + "path": "KSwitcher.Screenshot.exe", + "size": 5790537, + "sha256": "55d755ac25b980bc931d9cd4167ae83a0ca799060428672018b18ccfab8eaf34" }, { - "size": 4403712, - "sha256": "69c95a3135878d8974e144ef630ec7cf53df43a61e7243482642fc721b6eadcb", - "path": "KSwitcher.Files.exe" + "path": "KSwitcher.Files.exe", + "size": 9488877, + "sha256": "7024d127e42125963c77d2acd7eacc9fc5d01a14c3061b09800c9a55e8e66548" }, { + "path": "WebView2Loader.dll", "size": 194912, - "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6", - "path": "WebView2Loader.dll" + "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6" }, { + "path": "terminal/addon-fit-LICENSE.txt", "size": 1103, - "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f", - "path": "terminal/addon-fit-LICENSE.txt" + "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f" }, { + "path": "terminal/addon-fit.js", "size": 1521, - "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527", - "path": "terminal/addon-fit.js" + "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527" }, { + "path": "terminal/index.html", "size": 527, - "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef", - "path": "terminal/index.html" + "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef" }, { + "path": "terminal/markdown-it-LICENSE.txt", "size": 1073, - "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473", - "path": "terminal/markdown-it-LICENSE.txt" + "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473" }, { + "path": "terminal/markdown-it.js", "size": 100786, - "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e", - "path": "terminal/markdown-it.js" + "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e" }, { + "path": "terminal/markdown.html", "size": 3599, - "sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094", - "path": "terminal/markdown.html" + "sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094" }, { + "path": "terminal/markdown.js", "size": 17575, - "sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8", - "path": "terminal/markdown.js" + "sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8" }, { + "path": "terminal/mermaid-LICENSE.txt", "size": 1089, - "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", - "path": "terminal/mermaid-LICENSE.txt" + "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80" }, { + "path": "terminal/mermaid.js", "size": 5537838, - "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3", - "path": "terminal/mermaid.js" + "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3" }, { + "path": "terminal/terminal.js", "size": 5065, - "sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b", - "path": "terminal/terminal.js" + "sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b" }, { + "path": "terminal/xterm-LICENSE.txt", "size": 1261, - "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", - "path": "terminal/xterm-LICENSE.txt" + "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd" }, { + "path": "terminal/xterm.css", "size": 7112, - "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6", - "path": "terminal/xterm.css" + "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6" }, { + "path": "terminal/xterm.js", "size": 488663, - "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972", - "path": "terminal/xterm.js" + "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972" }, { + "path": "LICENSE", "size": 4401, - "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", - "path": "LICENSE" + "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c" }, { + "path": "json-LICENSE.txt", "size": 1096, - "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831", - "path": "json-LICENSE.txt" + "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831" }, { + "path": "files-text-license.txt", "size": 883, - "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625", - "path": "files-text-license.txt" + "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625" }, { - "size": 101324, - "sha256": "74e79e56a1ed04a6a617d626aedbf4c0a20e9dc83cd1c42d787244c1b48c5330", - "path": "README.md" + "path": "README.md", + "size": 101399, + "sha256": "e22bf65e81befdcc3b3b12803f3e9c2fdfa5c81eb5f3736a6077dd30a8abf74b" }, { - "size": 12354, - "sha256": "a2521642266d88eb5a2e579b8c514eecb63b0586e09dac2bbeea964df92b2474", - "path": "LAN-PREVIEW.md" + "path": "LAN-PREVIEW.md", + "size": 12550, + "sha256": "391567369ae742c252ebe01811c67c729f0e884ba2aef200e9e087bcd8017c2f" }, { + "path": "dictionaries/en.txt", "size": 732485, - "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9", - "path": "dictionaries/en.txt" + "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9" }, { + "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", "size": 20566, - "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5", - "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt" + "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5" }, { + "path": "dictionaries/README.md", "size": 2265, - "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311", - "path": "dictionaries/README.md" + "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311" }, { + "path": "dictionaries/ru.txt", "size": 1109134, - "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849", - "path": "dictionaries/ru.txt" + "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849" }, { + "path": "dictionaries/sources.json", "size": 1280, - "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408", - "path": "dictionaries/sources.json" + "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408" }, { + "path": "dictionaries/uk.txt", "size": 940799, - "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf", - "path": "dictionaries/uk.txt" + "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf" }, { + "path": "tools/README.txt", "size": 993, - "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", - "path": "tools/README.txt" + "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a" }, { - "size": 134656, - "sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376", - "path": "tools/StayHere.exe" + "path": "tools/StayHere.exe", + "size": 540583, + "sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c" }, { + "path": "tools/StayHere-README.md", "size": 2796, - "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", - "path": "tools/StayHere-README.md" + "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413" } - ], - "schema": 1, - "version": "0.7.2" + ] } diff --git a/resources/app.rc b/resources/app.rc index 28e9022..52e4fcc 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -10,8 +10,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,7,2,0 - PRODUCTVERSION 0,7,2,0 + FILEVERSION 0,7,3,0 + PRODUCTVERSION 0,7,3,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -21,7 +21,7 @@ BEGIN BEGIN VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "ProductName", "KSwitcher" - VALUE "FileVersion", "0.7.2" + VALUE "FileVersion", "0.7.3" END END BLOCK "VarFileInfo" diff --git a/src/app.cpp b/src/app.cpp index c990dec..3335e34 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -1135,9 +1135,10 @@ void App::pollLanInput() // the router entirely, including for already queued network notifications. if (lanService && lanService->tickInput(!busy && !suspended && !hotkeyCapture)) resetLanInput(); } -void App::applySettings(const Settings &requested) +void App::applySettings(const Settings &requested, const Bytes &supplement) { - applySettings(requested, true); + if (supplement.empty()) applySettings(requested, true); + else applySettings(requested, true, [&] { commitConfigurationSupplement(*this, supplement); }); if (settings.autostart && !smoke && !isLocalBuild()) PostMessageW(window, CheckAutostartMessage, 0, 0); } @@ -1189,7 +1190,7 @@ void App::checkAutostartPath() } checkingAutostartPath = false; } -void App::applySettings(const Settings &requested, bool validateOcrInstallation) +void App::applySettings(const Settings &requested, bool validateOcrInstallation, const std::function &commit) { Settings s = requested; std::set present, removed(s.snippetTombstones.begin(), s.snippetTombstones.end()); @@ -1211,11 +1212,15 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation) } predictor.configure(std::filesystem::path(executable()).parent_path() / L"dictionaries", s.autoLanguages); } + const auto path = data / L"settings.json"; + const auto originalFile = commit && std::filesystem::exists(path) ? + std::optional{readFile(path, ConfigLimit)} : std::nullopt; if (inputState == InputState::Active && !registerHotkeys(s)) { registerHotkeys(settings, true); throw std::runtime_error(utf8(registrationWarning)); } + bool settingsWritten = false; try { if (s.autostart != settings.autostart || s.elevatedAutostart != settings.elevatedAutostart) @@ -1223,10 +1228,22 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation) setAutostart(s.autostart, s.elevatedAutostart); autostartChanged = true; } - saveSettings(data / L"settings.json", s); + saveSettings(path, s); + settingsWritten = true; + if (commit) commit(); } catch (...) { + std::exception_ptr rollbackError; + if (settingsWritten) + { + try + { + if (originalFile) atomicWrite(path, *originalFile); + else std::filesystem::remove(path); + } + catch (...) { rollbackError = std::current_exception(); } + } try { if (autostartChanged) @@ -1236,6 +1253,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation) { } if (inputState == InputState::Active) registerHotkeys(settings, true); + if (rollbackError) std::rethrow_exception(rollbackError); throw; } { diff --git a/src/app.h b/src/app.h index 1ed7d5b..051c7cd 100644 --- a/src/app.h +++ b/src/app.h @@ -81,7 +81,7 @@ class App void trayMenu(); void addTray(); bool registerHotkeys(const Settings &, bool rollback = false); - void applySettings(const Settings &); + void applySettings(const Settings &, const Bytes &supplement = {}); void reloadLayouts(); void clearHistory(); void openHistoryProcess(); @@ -106,7 +106,7 @@ class App private: friend struct InputRegressionAccess; void releaseIdleMemory(ULONGLONG now); - void applySettings(const Settings &, bool validateOcrInstallation); + void applySettings(const Settings &, bool validateOcrInstallation, const std::function &commit = {}); void checkAutostartPath(); bool checkingAutostartPath{}; HHOOK keyboardHook{}, mouseHook{}; diff --git a/src/config_main.cpp b/src/config_main.cpp index 43f8204..1b0510c 100644 --- a/src/config_main.cpp +++ b/src/config_main.cpp @@ -107,7 +107,7 @@ App::~App() if (window) DestroyWindow(window); current = nullptr; } -void App::applySettings(const Settings &next) +void App::applySettings(const Settings &next, const Bytes &supplement) { validateSettings(next); auto before = encodeSettings(settings), after = encodeSettings(next); @@ -115,15 +115,22 @@ void App::applySettings(const Settings &next) Bytes payload(sizeof(length)); memcpy(payload.data(), &length, sizeof(length)); payload.insert(payload.end(), before.begin(), before.end()); + if (!supplement.empty()) + { + DWORD length = (DWORD)after.size(); + auto first = reinterpret_cast(&length); + payload.insert(payload.end(), first, first + sizeof(length)); + } payload.insert(payload.end(), after.begin(), after.end()); + payload.insert(payload.end(), supplement.begin(), supplement.end()); Bytes saved; - try {saved=request(*this,ConfigSave,payload);} + try {saved=request(*this,supplement.empty() ? ConfigSave : ConfigSaveDraft,payload);} catch(const std::exception &error){ if(!std::string(error.what()).starts_with("Settings conflict: "))throw; auto text=wide(error.what())+L"\n\nThese settings changed both here and in KSwitcher.\nKeep your edits for these settings? Other changes will be preserved.\n\nNo leaves this window open with all your edits."; if(MessageBoxW(settingsWindow?settingsWindow:snippetsWindow,text.c_str(),L"Save conflicting settings",MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2)!=IDYES) throw std::runtime_error("Not saved. Your edits are still in this window."); - saved=request(*this,ConfigSaveEdited,payload); + saved=request(*this,supplement.empty() ? ConfigSaveEdited : ConfigSaveEditedDraft,payload); } settings=decodeSettings(saved,layouts); } diff --git a/src/configuration.cpp b/src/configuration.cpp index 7dba684..8723984 100644 --- a/src/configuration.cpp +++ b/src/configuration.cpp @@ -40,6 +40,24 @@ void launchConfiguration(App &app, bool snippets, bool logs) CloseHandle(process.hProcess); (void)app; } +void commitConfigurationSupplement(App &app, const Bytes &supplement) +{ + const auto draft = nlohmann::json::parse(supplement); + auto commitLan = [&] { + if (!draft.contains("lan")) return; + const auto command = nlohmann::json{{"action", "applySettings"}, {"draft", draft.at("lan")}}.dump(); + app.lanCommand(Bytes(command.begin(), command.end())); + }; + if (draft.contains("sync")) + { + const auto &sync = draft.at("sync"); + const auto config = decodeSyncConfig(sync.at("config").get()); + if (loadSyncConfig(app.data) != decodeSyncConfig(sync.at("base").get())) + throw std::runtime_error("The OpenBao connection changed. Reopen Settings to edit the current connection."); + applySyncConnection(app.data, config, sync.at("password").get(), sync.at("forget").get(), commitLan); + } + else commitLan(); +} LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &message) { const bool filesPeers = message.dwData == FilesLanPeers; @@ -99,6 +117,8 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag } case ConfigSave: case ConfigSaveEdited: + case ConfigSaveDraft: + case ConfigSaveEditedDraft: { if (app.busy) throw std::runtime_error("Wait for the current text operation to finish."); if (message.cbData < sizeof(DWORD)) throw std::runtime_error("Invalid settings request."); @@ -106,10 +126,23 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag memcpy(&length, message.lpData, sizeof(length)); if (length > message.cbData - sizeof(length)) throw std::runtime_error("Invalid settings snapshot."); auto begin = static_cast(message.lpData) + sizeof(length); - Bytes next(begin + length, static_cast(message.lpData) + message.cbData); - if (next.empty()) throw std::runtime_error("Empty settings request."); - auto merged=mergeConfigurationSettings(Bytes(begin,begin+length),next,encodeSettings(app.settings),message.dwData==ConfigSaveEdited); - app.applySettings(decodeSettings(merged, app.layouts)); + const auto end = static_cast(message.lpData) + message.cbData; + auto next = begin + length; + auto nextEnd = end; + const bool hasDraft = message.dwData == ConfigSaveDraft || message.dwData == ConfigSaveEditedDraft; + if (hasDraft) + { + DWORD nextLength{}; + if (end - next < sizeof(nextLength)) throw std::runtime_error("Invalid settings draft."); + memcpy(&nextLength, next, sizeof(nextLength)); + next += sizeof(nextLength); + if (nextLength >= end - next) throw std::runtime_error("Invalid settings draft."); + nextEnd = next + nextLength; + } + if (next == nextEnd) throw std::runtime_error("Empty settings request."); + auto merged = mergeConfigurationSettings(Bytes(begin, begin + length), Bytes(next, nextEnd), + encodeSettings(app.settings), message.dwData == ConfigSaveEdited || message.dwData == ConfigSaveEditedDraft); + app.applySettings(decodeSettings(merged, app.layouts), Bytes(nextEnd, end)); reply = encodeSettings(app.settings); break; } diff --git a/src/configuration.h b/src/configuration.h index 146c02d..86818a6 100644 --- a/src/configuration.h +++ b/src/configuration.h @@ -9,9 +9,10 @@ inline constexpr ULONG_PTR ConfigRead = 0x4b530100, ConfigSave = ConfigRead + 1, ConfigCapture = ConfigRead + 4, ConfigLogs = ConfigRead + 5, ConfigReply = ConfigRead + 6, ConfigClearLog = ConfigRead + 7, ConfigSync = ConfigRead + 8, ConfigSyncConflicts = ConfigRead + 9, - ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigEnd = FilesLanPeers + 1; + ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigSaveDraft = FilesLanPeersReply + 1, ConfigSaveEditedDraft = ConfigSaveDraft + 1, ConfigEnd = ConfigSaveEditedDraft + 1; inline constexpr size_t ConfigLimit = 8 * 1024 * 1024; bool configurationPeer(HWND, const wchar_t *filename); +void commitConfigurationSupplement(App &, const Bytes &); void launchConfiguration(App &, bool snippets = false, bool logs = false); LRESULT configurationRequest(App &, HWND sender, const COPYDATASTRUCT &); } diff --git a/src/lan.cpp b/src/lan.cpp index aacf66e..364162e 100644 --- a/src/lan.cpp +++ b/src/lan.cpp @@ -507,7 +507,7 @@ struct LanService::Impl auto previous=trusted;auto previousPositions=positions; trusted[other]={{"name",peer.name},{"key",pending->derived}}; try {lan::fillPositions(positions,trusted,inputPeer,inputEdge);save();} catch(...) {trusted=std::move(previous);positions=std::move(previousPositions);throw;} - layoutChanged=true;peer.verified=now; status="Pair saved automatically. Arrange the monitors, then enable input sharing on both PCs."; + layoutChanged=true;peer.verified=now; status="Pair saved. Arrange the monitors, then enable input sharing and click Apply or Save on both PCs."; } } } @@ -644,13 +644,102 @@ struct LanService::Impl if(socket!=INVALID_SOCKET) closesocket(socket); if(winsock) WSACleanup(); } + void removePeerState(const std::string &peer) + { + std::erase_if(incomingFiles, [&](const auto &file) { return file.peer == peer; }); + if (logDownload && logDownload->peer == peer) logDownload.reset(); + if (pending && pending->peer == peer) pending.reset(); + } + void applySettings(const Json &draft) + { + std::unique_lock lock(mutex); + const auto before = std::tuple{enabled, shareInput, shareLogs, inputEdge, trusted, positions}; + const bool discovery = draft.value("enabled", enabled); + const auto forgotten = draft.value("forget", Json::object()); + auto nextTrusted = trusted; + for (const auto &[peer, ignored] : forgotten.items()) nextTrusted.erase(peer); + const bool nextInput = !nextTrusted.empty() && draft.value("shareInput", shareInput); + if (draft.value("shareInput", false) && (!discovery || nextTrusted.empty())) + throw std::runtime_error("Enable discovery and select a paired KSwitcher first."); + auto nextPositions = positions; + const auto moved = draft.value("positions", Json::object()); + for (const auto &[peer, cell] : moved.items()) + { + if (!nextTrusted.contains(peer)) throw std::runtime_error("Pair this computer before arranging it."); + nextPositions[peer] = cell; + } + lan::fillPositions(nextPositions, nextTrusted, inputPeer, inputEdge); + int edge = moved.contains(inputPeer) ? lan::cellEdge(nextPositions.at(inputPeer)) : -1; + + std::unique_ptr nextPair; + if (draft.contains("pair")) + { + const auto &pair = draft.at("pair"); + auto peer = pair.at("peer").get(); + if (!enabled || !discovery || !peers.contains(peer) || !peers.at(peer).present(GetTickCount64())) + throw std::runtime_error("Select an available KSwitcher computer first."); + if (!nextTrusted.contains(peer) && nextTrusted.size() >= 64) + throw std::runtime_error("Remove an old pair before adding another computer."); + nextPair = std::make_unique(id, peer, pair.at("code").get(), GetTickCount64()); + } + const bool discoveryChanged = discovery != enabled; + const bool routerChanged = discoveryChanged || nextInput != shareInput || + nextPositions != positions || nextTrusted != trusted; + const bool nextLogs = draft.value("shareLogs", shareLogs); + const bool saveLan = routerChanged || nextLogs != shareLogs; + const bool hadFile = saveLan && std::filesystem::exists(path); + enabled = discovery; + shareInput = nextInput; + shareLogs = nextLogs; + if (edge >= 0) inputEdge = edge; + positions = std::move(nextPositions); + trusted = std::move(nextTrusted); + auto current = std::tie(enabled, shareInput, shareLogs, inputEdge, trusted, positions); + bool written = false; + try + { + if (saveLan) { save(); written = true; } + if (draft.contains("clients")) clients.apply(draft.at("clients")); + } + catch (...) + { + current = before; + if (written) + { + if (hadFile) save(); + else std::filesystem::remove(path); + } + throw; + } + for (const auto &[peer, ignored] : forgotten.items()) removePeerState(peer); + if (std::get<2>(before) && !shareLogs) + for (const auto &[peer, entry] : trusted.items()) transfers->cancel(peer, "log-reply-"); + if (nextPair) + { + pending = std::move(nextPair); + status = "Waiting for the same code on the other KSwitcher (2 minutes)..."; + } + if (routerChanged) configureRouter(); + lock.unlock(); + if (discoveryChanged && discovery) start(); + if (discoveryChanged && !discovery) + { + stop(); + status = "Disabled. No discovery sockets or worker thread."; + } + } std::mutex commandGate; Bytes command(const Bytes &input) { std::lock_guard commandLock(commandGate); auto j=Json::parse(input); auto action=j.value("action","status"); - if (action == "trustedClients" || action == "trustClient" || action == "removeClient") + if (action == "trustedClients" || action == "inspectClient" || action == "trustClient" || action == "removeClient") return encoded(clients.settings(action, j)); + if (action == "applySettings") + { + applySettings(j.at("draft")); + return encoded(Json::object()); + } if(action=="enable") { stop(); @@ -789,9 +878,7 @@ struct LanService::Impl auto peer=j.at("peer").get();auto oldTrusted=trusted;auto oldPositions=positions;bool oldSharing=shareInput; trusted.erase(peer);positions.erase(peer);if(trusted.empty())shareInput=false; try{save();}catch(...){trusted=std::move(oldTrusted);positions=std::move(oldPositions);shareInput=oldSharing;throw;} - std::erase_if(incomingFiles,[&](const auto &file){return file.peer==peer;}); - if(logDownload && logDownload->peer==peer)logDownload.reset(); - if(pending&&pending->peer==peer)pending.reset(); + removePeerState(peer); configureRouter(); status="Pair removed on this computer."; } diff --git a/src/lan_clients.h b/src/lan_clients.h index 3c44a0e..fbbdc0b 100644 --- a/src/lan_clients.h +++ b/src/lan_clients.h @@ -221,15 +221,16 @@ public: }); } void stop() { if (stopped) SetEvent(stopped.value); if (thread.joinable()) thread.join(); } - Json settings(const std::string &action, const Json &request) const + private: + static void editClient(Json &entries, const std::string &action, const Json &request) { - std::lock_guard lock(storeMutex); - auto entries = clients(); - if (action == "trustedClients") return entries; const auto path = wide(request.at("path").get()); if (action == "trustClient") { ClientImage image(path); + if (request.contains("sha256") && + (request.at("sha256") != image.digest || _wcsicmp(image.path.c_str(), path.c_str()))) + throw std::runtime_error("The executable changed. Add it again before saving."); std::erase_if(entries.get_ref(), [&](const auto &entry) { return !_wcsicmp(wide(entry.at("path").template get()).c_str(), image.path.c_str()); }); @@ -242,9 +243,36 @@ public: return !_wcsicmp(wide(entry.at("path").template get()).c_str(), path.c_str()); }); } + } + void save(const Json &entries) const + { const auto text = entries.dump(); atomicWrite(store, protect(Bytes(text.begin(), text.end()))); + } + public: + Json settings(const std::string &action, const Json &request) const + { + std::lock_guard lock(storeMutex); + if (action == "inspectClient") + { + ClientImage image(wide(request.at("path").get())); + return {{"path", utf8(image.path)}, {"sha256", image.digest}}; + } + auto entries = clients(); + if (action == "trustedClients") return entries; + editClient(entries, action, request); + save(entries); return entries; } + void apply(const Json &changes) const + { + std::lock_guard lock(storeMutex); + auto entries = clients(); + for (const auto &change : changes) + if (change.at("action") == "removeClient") editClient(entries, "removeClient", change); + for (const auto &change : changes) + if (change.at("action") == "trustClient") editClient(entries, "trustClient", change); + save(entries); + } }; } diff --git a/src/sync.cpp b/src/sync.cpp index 51cd4c6..c7cf204 100644 --- a/src/sync.cpp +++ b/src/sync.cpp @@ -157,10 +157,14 @@ class OpenBao final : public SyncProvider } bool syncVisible(const std::filesystem::path &root) { return std::filesystem::exists(root / L"sync.json"); } SyncConfig loadSyncConfig(const std::filesystem::path &root) +{ + return syncVisible(root) ? decodeSyncConfig(readFile(root / L"sync.json", 16384)) : SyncConfig{}; +} +Bytes encodeSyncConfig(const SyncConfig &config) { return bytes(configJson(config)); } +SyncConfig decodeSyncConfig(const Bytes &encoded) { SyncConfig c; - if (!syncVisible(root)) return c; - auto j = parse(readFile(root / L"sync.json", 16384)); + auto j = parse(encoded); c.enabled = j.value("enabled", false); c.keepLocalLayouts = j.value("keepLocalLayouts", false); c.provider = wide(j.value("provider", "openbao")); @@ -212,6 +216,70 @@ void forgetSyncPassword(const SyncConfig &c) if (!CredDeleteW(credentialName(c).c_str(), CRED_TYPE_GENERIC, 0) && GetLastError() != ERROR_NOT_FOUND) throw std::runtime_error("Cannot remove saved sync password."); } +void applySyncConnection(const std::filesystem::path &root, const SyncConfig &config, + const Bytes &protectedPassword, bool forgetPassword, const std::function &commit) +{ + const auto path = root / L"sync.json"; + const auto previousFile = syncVisible(root) ? std::optional{readFile(path, 16384)} : std::nullopt; + const auto credentialConfig = forgetPassword && previousFile ? decodeSyncConfig(*previousFile) : config; + const bool editCredential = forgetPassword || !protectedPassword.empty(); + PCREDENTIALW previousCredential{}; + struct Cleanup + { + PCREDENTIALW &credential; + ~Cleanup() + { + if (!credential) return; + SecureZeroMemory(credential->CredentialBlob, credential->CredentialBlobSize); + CredFree(credential); + } + } cleanup{previousCredential}; + if (editCredential && + !CredReadW(credentialName(credentialConfig).c_str(), CRED_TYPE_GENERIC, 0, &previousCredential) && + GetLastError() != ERROR_NOT_FOUND) + throw std::runtime_error("Cannot read the saved Windows credential."); + + saveSyncConfig(root, config); + bool credentialChanged = false; + try + { + if (forgetPassword) forgetSyncPassword(credentialConfig); + else if (!protectedPassword.empty()) + { + auto secret = unprotect(protectedPassword); + std::wstring password; + try + { + if (secret.size() % sizeof(wchar_t)) throw std::runtime_error("Invalid Windows credential."); + password.resize(secret.size() / sizeof(wchar_t)); + memcpy(password.data(), secret.data(), secret.size()); + saveSyncPassword(config, password); + } + catch (...) + { + SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t)); + SecureZeroMemory(secret.data(), secret.size()); + throw; + } + SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t)); + SecureZeroMemory(secret.data(), secret.size()); + } + credentialChanged = editCredential; + commit(); + } + catch (...) + { + if (previousFile) atomicWrite(path, *previousFile); + else std::filesystem::remove(path); + if (credentialChanged) + { + if (!previousCredential) forgetSyncPassword(credentialConfig); + else if (!CredWriteW(previousCredential, 0)) + throw std::runtime_error("Cannot restore the previous Windows credential."); + } + throw; + } +} std::unique_ptr makeSyncProvider(const SyncConfig &c, SyncTransport transport) { return std::make_unique(c, std::move(transport)); diff --git a/src/sync.h b/src/sync.h index 942609a..a62932f 100644 --- a/src/sync.h +++ b/src/sync.h @@ -15,6 +15,10 @@ struct SyncConfig bool syncVisible(const std::filesystem::path &); SyncConfig loadSyncConfig(const std::filesystem::path &); void saveSyncConfig(const std::filesystem::path &, const SyncConfig &); +Bytes encodeSyncConfig(const SyncConfig &); +SyncConfig decodeSyncConfig(const Bytes &); +void applySyncConnection(const std::filesystem::path &, const SyncConfig &, const Bytes &protectedPassword, + bool forgetPassword, const std::function &commit); void validateSyncConfig(const SyncConfig &); void saveSyncPassword(const SyncConfig &, const std::wstring &); void forgetSyncPassword(const SyncConfig &); diff --git a/src/ui.cpp b/src/ui.cpp index 3bd7453..f5675cb 100644 --- a/src/ui.cpp +++ b/src/ui.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -1127,7 +1128,7 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) constexpr int LanguagesPage = 1, ShortcutsPage = 2, ClipboardPage = 3, SnippetsPage = 4, MousePage = 5; constexpr int ExceptionsPage = 13, PersonalDictionariesPage = 14, WordBoundariesPage = 15, SnippetMacros = 320; constexpr UINT AppWindowPicked = WM_APP + 78; -constexpr int SettingsNavigation = 260, SettingsStatus = 261, SettingsViewport = 264; +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; @@ -1228,6 +1229,46 @@ 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 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{}; @@ -1254,8 +1295,7 @@ struct SettingsView std::vector searchTerms; bool rebuildingNavigation{}, searching{}; HFONT headingFont{}, brandFont{}, groupFont{}, fieldFont{}; - HBRUSH chrome = CreateSolidBrush(RGB(238, 243, 246)); - bool highContrast{}; + WindowPalette palette; bool ready{}, refreshing{}, wasShown{}; std::vector mouseProfiles; std::array mouseProfileChecks{}; @@ -1323,7 +1363,7 @@ void paintSettingsMatches(HWND pane) auto drawMatch = [&](const SettingsView::SearchEntry &entry, bool active) { if (!entry.matched || entry.page != v->selectedPage) return; - SetDCBrushColor(dc, v->highContrast ? GetSysColor(COLOR_HIGHLIGHT) : + SetDCBrushColor(dc, v->palette.highContrast ? GetSysColor(COLOR_HIGHLIGHT) : active ? RGB(7, 97, 83) : RGB(157, 111, 21)); const int stroke = scale(pane, active ? 2 : 1); for (HWND mark : {entry.caption, entry.target == entry.caption ? nullptr : entry.target}) @@ -1386,7 +1426,7 @@ void layoutSettings(HWND w, const SettingsView &v) std::max(1, MulDiv(titleWidth, 96, GetDpiForWindow(w)))); const int header = scale(w, std::max(SettingsHeaderHeight, 60 + descriptionHeight)); const int margin = scale(w, 18), gap = scale(w, 10); - const int slot = std::max(0, (width - 2 * margin - 3 * gap) / 4); + const int slot = std::max(0, (width - 2 * margin - 4 * gap) / 5); const int transferWidth = std::min(scale(w, 112), slot), commitWidth = std::min(scale(w, 100), slot); const int actionTop = footer + scale(w, 34), actionHeight = scale(w, 30); std::vector moves; @@ -1409,6 +1449,7 @@ void layoutSettings(HWND w, const SettingsView &v) move(GetDlgItem(w, SettingsStatus), margin, footer + scale(w, 9), width - 2 * margin, scale(w, 20)); move(GetDlgItem(w, 250), margin, actionTop, transferWidth, actionHeight); move(GetDlgItem(w, 251), margin + transferWidth + gap, actionTop, transferWidth, actionHeight); + move(GetDlgItem(w, SettingsApply), width - margin - 3 * commitWidth - 2 * gap, actionTop, commitWidth, actionHeight); move(GetDlgItem(w, IDOK), width - margin - 2 * commitWidth - gap, actionTop, commitWidth, actionHeight); move(GetDlgItem(w, IDCANCEL), width - margin - commitWidth, actionTop, commitWidth, actionHeight); if (moves.empty()) return; @@ -1495,7 +1536,7 @@ LRESULT CALLBACK settingsSplitterProc(HWND splitter, UINT message, WPARAM wp, LP FillRect(dc, &client, GetSysColorBrush(COLOR_WINDOW)); const bool focused = GetFocus() == splitter; const bool active = v.splitterHovered || v.splitterDragOffset || focused; - SetDCBrushColor(dc, v.highContrast ? GetSysColor(active ? COLOR_HIGHLIGHT : COLOR_WINDOWTEXT) + SetDCBrushColor(dc, v.palette.highContrast ? GetSysColor(active ? COLOR_HIGHLIGHT : COLOR_WINDOWTEXT) : active ? RGB(7, 97, 83) : RGB(200, 213, 222)); auto brush = reinterpret_cast(GetStockObject(DC_BRUSH)); const int x = (client.right - 1) / 2, y = client.bottom / 2; @@ -1850,19 +1891,13 @@ void selectSettingsPage(SettingsView &v, int selected) for (size_t i = page.first; i < page.end; ++i) ShowWindow(layout.controls[i].first, SW_SHOWNA); InvalidateRect(v.viewport, nullptr, TRUE); } -void refreshSettingsColors(HWND w, SettingsView &v) +void refreshSettingsColors(HWND w, SettingsView &v, std::optional colorization = std::nullopt) { - HIGHCONTRASTW settings{sizeof(settings)}; - v.highContrast = SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(settings), &settings, 0) && - (settings.dwFlags & HCF_HIGHCONTRASTON); - TreeView_SetBkColor(v.navigation, v.highContrast ? GetSysColor(COLOR_WINDOW) : RGB(238, 243, 246)); + v.palette.refresh(colorization); + TreeView_SetBkColor(v.navigation, v.palette.color()); TreeView_SetTextColor(v.navigation, GetSysColor(COLOR_WINDOWTEXT)); RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN); } -HBRUSH settingsChromeBrush(const SettingsView &v) -{ - return v.highContrast ? GetSysColorBrush(COLOR_WINDOW) : v.chrome; -} void paintSettings(HWND w, const SettingsView &v) { PAINTSTRUCT paint{}; @@ -1877,9 +1912,9 @@ void paintSettings(HWND w, const SettingsView &v) MapWindowPoints(nullptr, w, reinterpret_cast(&viewport), 2); const int header = viewport.top; RECT rail{0, 0, sidebar, footer}, actions{0, footer, client.right, client.bottom}; - FillRect(dc, &rail, settingsChromeBrush(v)); - FillRect(dc, &actions, settingsChromeBrush(v)); - SetDCBrushColor(dc, v.highContrast ? GetSysColor(COLOR_WINDOWTEXT) : RGB(200, 213, 222)); + 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(GetStockObject(DC_BRUSH)); RECT footerEdge{0, footer, client.right, footer + 1}; RECT headingEdge{sidebar + scale(w, SettingsSplitterWidth), header - 1, client.right, header}; @@ -2774,16 +2809,28 @@ bool settingsChanged(SettingsView *v) return true; } } +LanView *settingsLanView(SettingsView *v) +{ + return v->lan ? reinterpret_cast(GetWindowLongPtrW(v->lan, GWLP_USERDATA)) : nullptr; +} +bool settingsFieldsChanged(SettingsView *v) +{ + const auto *lan = settingsLanView(v); + return (lan && !lan->draft.empty()) || syncDraftChanged(v->sync) || settingsChanged(v); +} void updateSettingsState(HWND w, SettingsView *v) { if (!v || !v->ready || v->filling || v->snippets.filling || v->refreshing) return; v->refreshing = true; - bool changed = settingsChanged(v); - bool snippetsChanged = snippetDraftChanged(v->viewport, &v->snippets); - EnableWindow(GetDlgItem(w, IDOK), changed || snippetsChanged || (v->app->settings.autostart && !isLocalBuild())); - const wchar_t *text = changed ? L"Unsaved settings — click Save to apply." : - snippetsChanged ? L"Unsaved snippets — click Save to apply." : - v->selectedPage == ManageComputersPage ? L"No unsaved settings. Network changes save automatically." : L"No unsaved settings."; + const bool changed = settingsFieldsChanged(v); + const bool snippetsChanged = snippetDraftChanged(v->viewport, &v->snippets); + const bool dirty = changed || snippetsChanged; + EnableWindow(GetDlgItem(w, SettingsApply), dirty); + const auto closeLabel = dirty ? L"&Cancel" : L"&Close"; + if (value(w, IDCANCEL) != closeLabel) value(w, IDCANCEL, closeLabel); + EnableWindow(GetDlgItem(w, IDOK), dirty || (v->app->settings.autostart && !isLocalBuild())); + const wchar_t *text = changed ? L"Unsaved settings — click Apply or Save." : + snippetsChanged ? L"Unsaved snippets — click Apply or Save." : L"No unsaved settings."; if (value(w, SettingsStatus) != text) value(w, SettingsStatus, text); v->refreshing = false; } @@ -2798,37 +2845,39 @@ struct SettingsStateRefresh updateSettingsState(window, reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA))); } }; -void applySettingsDraft(SettingsView *v) +void applySettingsDraft(HWND w, SettingsView *v, bool keepOpen) { if (v->app->busy) throw std::runtime_error("Wait for the current text operation to finish"); auto settings = collectSettings(v); mergeSnippetDraft(v->viewport, &v->snippets, settings); - v->app->applySettings(settings); + nlohmann::json draft = nlohmann::json::object(); + auto *lan = settingsLanView(v); + if (lan && !lan->draft.empty()) draft["lan"] = lan->draft; + if (syncDraftChanged(v->sync)) draft["sync"] = collectSyncDraft(v->sync); + const bool syncEdited = draft.contains("sync"); + const bool lanEdited = draft.contains("lan"); + const auto payload = draft.empty() ? std::string{} : draft.dump(); + v->app->applySettings(settings, Bytes(payload.begin(), payload.end())); + if (!keepOpen) + { + DestroyWindow(w); + return; + } + + if (lanEdited) lan->draft.clear(); + v->draft = v->app->settings; + fillSettings(w, v); + refreshSnippetDraft(v->viewport, &v->snippets); + if (syncEdited) reloadSyncEditor(v->sync); + if (lanEdited) refreshLan(v->lan, *lan); } void closeSettings(HWND w, SettingsView *v) { - if (settingsChanged(v) || snippetDraftChanged(v->viewport, &v->snippets)) - { - int choice = MessageBoxW(w, - L"You have unsaved changes. Save them before closing?\n\n" - L"Yes: save and close.\nNo: discard changes.\nCancel: keep editing.", - L"KSwitcher — Unsaved settings", MB_YESNOCANCEL | MB_ICONWARNING | MB_DEFBUTTON3); - if (choice != IDYES && choice != IDNO) - return; - if (choice == IDYES) - { - try - { - applySettingsDraft(v); - } - catch (const std::exception &e) - { - error(w, e); - return; - } - } - } + if ((settingsFieldsChanged(v) || snippetDraftChanged(v->viewport, &v->snippets)) && + MessageBoxW(w, L"Discard your unsaved changes? Choose No to keep editing and use Apply or Save.", + L"KSwitcher — Unsaved settings", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) != IDYES) + return; DestroyWindow(w); } LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) @@ -2874,6 +2923,9 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) case WM_SETTINGCHANGE: case WM_SYSCOLORCHANGE: refreshSettingsColors(w, *v); break; + case WM_DWMCOLORIZATIONCOLORCHANGED: + refreshSettingsColors(w, *v, static_cast(wp)); + return 0; case WM_ERASEBKGND: return 1; case WM_PAINT: @@ -2899,11 +2951,11 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) SetBkColor(dc, GetSysColor(COLOR_WINDOW)); return reinterpret_cast(GetSysColorBrush(COLOR_WINDOW)); } - SetTextColor(dc, !v->highContrast && (child == v->description || GetDlgCtrlID(child) == SettingsStatus) + SetTextColor(dc, !v->palette.highContrast && (child == v->description || GetDlgCtrlID(child) == SettingsStatus) ? RGB(70, 91, 112) : GetSysColor(COLOR_WINDOWTEXT)); SetBkMode(dc, TRANSPARENT); return reinterpret_cast(child == v->brand || GetDlgCtrlID(child) == SettingsStatus - ? settingsChromeBrush(*v) : GetSysColorBrush(COLOR_WINDOW)); + ? v->palette.brush() : GetSysColorBrush(COLOR_WINDOW)); } case WM_INPUT: readMouseTestInput(w, *v, reinterpret_cast(lp)); @@ -2935,8 +2987,8 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) (data >= static_cast(v->pages.size()) || (data >= 0 && matchesSettingsSearch(*v, settingsSections[data].name)))) { - draw.clrTextBk = v->highContrast ? GetSysColor(COLOR_HIGHLIGHT) : RGB(255, 235, 174); - draw.clrText = v->highContrast ? GetSysColor(COLOR_HIGHLIGHTTEXT) : RGB(83, 52, 8); + draw.clrTextBk = v->palette.highContrast ? GetSysColor(COLOR_HIGHLIGHT) : RGB(255, 235, 174); + draw.clrText = v->palette.highContrast ? GetSysColor(COLOR_HIGHLIGHTTEXT) : RGB(83, 52, 8); } } return CDRF_DODEFAULT; @@ -3041,11 +3093,10 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) } return 0; } - if (id == IDOK) + if (id == SettingsApply || id == IDOK) { - if (!IsWindowEnabled(GetDlgItem(w, IDOK))) return 0; - applySettingsDraft(v); - DestroyWindow(w); + if (!IsWindowEnabled(GetDlgItem(w, id))) return 0; + applySettingsDraft(w, v, id == SettingsApply); return 0; } if (id == IDCANCEL) @@ -3112,7 +3163,6 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) if (icon) DestroyIcon(icon); for (HFONT face : {v->headingFont, v->brandFont, v->groupFont, v->fieldFont}) if (face) DeleteObject(face); - if (v->chrome) DeleteObject(v->chrome); disposeFont(w); v->app->settingsWindow = nullptr; delete v; @@ -3927,8 +3977,9 @@ void showSettings(App &app, bool visible) control(w, L"STATIC", L"No unsaved settings.", SS_ENDELLIPSIS, SettingsStatus, 0, 0, 0, 0); button(w, L"Impo&rt...", 250, 0, 0); button(w, L"&Export...", 251, 0, 0); + button(w, L"&Apply", SettingsApply, 0, 0); button(w, L"&Save", IDOK, 0, 0); - button(w, L"&Cancel", IDCANCEL, 0, 0); + button(w, L"&Close", IDCANCEL, 0, 0); layout->arranging = false; setSettingsFonts(w, *v, GetDpiForWindow(w)); diff --git a/src/ui_lan.inl b/src/ui_lan.inl index 8586c1e..c0720f6 100644 --- a/src/ui_lan.inl +++ b/src/ui_lan.inl @@ -4,6 +4,7 @@ struct LanView HWND owner{}; App *app{}; nlohmann::json snapshot=nlohmann::json::object(); + nlohmann::json saved, draft = nlohmann::json::object(); std::vector ids; std::wstring error; std::string dragPeer;POINT dragStart{},dragPoint{};bool dragMoved{}; @@ -18,6 +19,15 @@ nlohmann::json lanRequest(App &app,const nlohmann::json &request) auto text=request.dump(); auto reply=app.lanCommand(Bytes(text.begin(),text.end())); return nlohmann::json::parse(reply); } +void stageLanValue(LanView &v, const char *key, const nlohmann::json &value) +{ + if (value == v.saved.at(key)) v.draft.erase(key); + else v.draft[key] = value; +} +void refreshLanFooter(LanView &v) +{ + updateSettingsState(v.owner, reinterpret_cast(GetWindowLongPtrW(v.owner, GWLP_USERDATA))); +} std::string selectedLan(HWND w,LanView &v) { auto index=SendDlgItemMessageW(w,702,LB_GETCURSEL,0,0); @@ -40,12 +50,19 @@ std::filesystem::path pickLanFile(HWND owner, bool save, const wchar_t *suggesti struct LanClientsView { - App *app{}; - nlohmann::json entries; + LanView *lan{}; + nlohmann::json entries, saved; }; void refreshLanClients(HWND window, LanClientsView &view) { - view.entries = lanRequest(*view.app, {{"action", "trustedClients"}}); + view.entries = view.saved; + for (const auto &change : view.lan->draft.value("clients", nlohmann::json::object())) + { + const auto &path = change.at("path"); + std::erase_if(view.entries.get_ref(), + [&](const auto &entry) { return entry.at("path") == path; }); + if (change.at("action") == "trustClient") view.entries.push_back(change); + } SendDlgItemMessageW(window, 732, LB_RESETCONTENT, 0, 0); for (const auto &entry : view.entries) { @@ -94,14 +111,29 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp) (L"Allow this application to browse and download files from paired computers?\n\n" + path.wstring()).c_str(), L"Trust a LAN client", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) == IDYES) { - lanRequest(*view->app, {{"action", "trustClient"}, {"path", utf8(path.wstring())}}); + const auto entry = lanRequest(*view->lan->app, {{"action", "inspectClient"}, {"path", utf8(path.wstring())}}); + const auto canonical = entry.at("path").get(); + const auto key = utf8(lower(wide(canonical))); + auto &changes = view->lan->draft["clients"]; + if (std::find(view->saved.begin(), view->saved.end(), entry) == view->saved.end()) + changes[key] = {{"action", "trustClient"}, {"path", canonical}, {"sha256", entry.at("sha256")}}; + else if (changes.is_object()) changes.erase(key); + if (changes.empty()) view->lan->draft.erase("clients"); + refreshLanFooter(*view->lan); refreshLanClients(window, *view); } return 0; } if (id == 734 && index >= 0 && size_t(index) < view->entries.size()) { - lanRequest(*view->app, {{"action", "removeClient"}, {"path", view->entries[size_t(index)].at("path")}}); + const auto path = view->entries[size_t(index)].at("path").get(); + const auto key = utf8(lower(wide(path))); + auto &changes = view->lan->draft["clients"]; + if (std::any_of(view->saved.begin(), view->saved.end(), [&](const auto &entry) { return entry.at("path") == path; })) + changes[key] = {{"action", "removeClient"}, {"path", path}}; + else changes.erase(key); + if (changes.empty()) view->lan->draft.erase("clients"); + refreshLanFooter(*view->lan); refreshLanClients(window, *view); return 0; } @@ -114,20 +146,24 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp) } return DefWindowProcW(window, msg, wp, lp); } -void showLanClients(HWND parent, App &app) +void showLanClients(HWND parent, LanView &lan) { - auto window = makeWindow(app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 280, 0, false); + auto window = makeWindow(*lan.app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 280, 0, false); SetWindowLongPtrW(window, GWLP_HWNDPARENT, reinterpret_cast(parent)); - auto view = new LanClientsView{&app}; + auto view = new LanClientsView{&lan}; SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast(view)); label(window, L"Trusted executables can browse and download files from paired computers.", 16, 14, 578); control(window, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | WS_BORDER | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT, 732, 16, 42, 578, 152); - label(window, L"Add the executable again after updating it.", 16, 202, 578); + label(window, L"After updating an executable, add it again and click Apply or Save in Settings.", 16, 202, 578); button(window, L"&Add client…", 733, 16, 236, 126); button(window, L"&Remove", 734, 150, 236, 110); button(window, L"&Close", IDCANCEL, 494, 236, 100); - try { refreshLanClients(window, *view); } + try + { + view->saved = lanRequest(*lan.app, {{"action", "trustedClients"}}); + refreshLanClients(window, *view); + } catch (...) { DestroyWindow(window); throw; } EnableWindow(parent, FALSE); showRequestedWindow(window); @@ -176,6 +212,18 @@ void refreshLan(HWND w,LanView &v) } auto selected=selectedLan(w,v); auto next=lanRequest(*v.app,{{"action","status"}}); + v.saved = next; + for (const auto *key : {"enabled", "shareInput", "shareLogs"}) + if (v.draft.contains(key)) next[key] = v.draft.at(key); + next["positions"].update(v.draft.value("positions", nlohmann::json::object())); + const auto forgotten = v.draft.value("forget", nlohmann::json::object()); + for (const auto &[peer, ignored] : forgotten.items()) + { + next["positions"].erase(peer); + for (auto &entry : next["peers"]) + if (entry.at("id") == peer) entry["paired"] = false; + } + if (next["positions"].empty()) next["shareInput"] = false; if(selected.empty()) { std::string onlyPaired;size_t pairedCount=0; @@ -222,8 +270,11 @@ void refreshLan(HWND w,LanView &v) std::wstring peerName; for(const auto &peer:v.snapshot["peers"]) if(peer.at("id")==v.snapshot.value("pendingPeer",std::string{}))peerName=wide(peer.at("name").get()); - pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair on the other PC."; + pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair, then Apply or Save on the other PC."; } + 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"); const wchar_t *peerStatus=L"Select the name and ID shown on the other PC."; @@ -236,9 +287,9 @@ void refreshLan(HWND w,LanView &v) !v.snapshot.value("shareInput",false)?L"Pair saved — input disabled here": !online?L"Pair saved — computer offline":L"Pair saved — input not connected"; } - value(w,710,peerStatus); - EnableWindow(GetDlgItem(w,705),enabled&&online&&!pending&&!paired); - EnableWindow(GetDlgItem(w,706),pending); + value(w,710,forgotten.contains(selected) ? L"Click Apply or Save to remove this pair." : peerStatus); + EnableWindow(GetDlgItem(w,705),v.saved.at("enabled").get()&&enabled&&online&&!pending&&!v.draft.contains("pair")&&!forgotten.contains(selected)&&!paired); + EnableWindow(GetDlgItem(w,706),pending || v.draft.contains("pair")); EnableWindow(GetDlgItem(w,707),paired); bool canDownloadLogs=false; for(const auto &peer:v.snapshot["peers"]) @@ -253,7 +304,7 @@ void refreshLan(HWND w,LanView &v) arrangeWindow(GetParent(w)); arrangeWindow(w); } - for(int id:{703,704}) EnableWindow(GetDlgItem(w,id),enabled&&!pending&&!paired); + for(int id:{703,704}) EnableWindow(GetDlgItem(w,id),v.saved.at("enabled").get()&&enabled&&!pending&&!v.draft.contains("pair")&&!paired); auto positions=v.snapshot.value("positions",nlohmann::json::object()); EnableWindow(GetDlgItem(w,715),enabled&&!positions.empty()&&!v.snapshot.value("shareInput",false)); EnableWindow(GetDlgItem(w,716),v.snapshot.value("shareInput",false)); @@ -270,6 +321,8 @@ void refreshLan(HWND w,LanView &v) auto mode=v.snapshot.value("controlMode",0); if(mode==2)inputStatus=L"Mouse and keyboard control the OTHER PC. Ctrl+Alt+Esc returns here."; else if(mode==3)inputStatus=L"This PC is controlled remotely. Local physical input takes control back."; + 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"); } @@ -321,17 +374,31 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp) if(!IsWindowEnabled(GetDlgItem(w,id)))return 0; v->error.clear(); if(id==722){showLanHelp(v->owner,*v->app);return 0;} - if(id==735){showLanClients(v->owner,*v->app);return 0;} - if(id==701) lanRequest(*v->app,{{"action","enable"},{"enabled",!v->snapshot.value("enabled",false)}}); + if(id==735){showLanClients(v->owner,*v);return 0;} + if(id==701) stageLanValue(*v,"enabled",!v->snapshot.value("enabled",false)); if(id==704) { auto code=lanRequest(*v->app,{{"action","code"}}).at("code").get(); std::string grouped; for(size_t i=0;iapp,{{"action","pair"},{"peer",peer},{"code",utf8(value(w,703))}}); - if(id==706) lanRequest(*v->app,{{"action","cancel"}}); - if(id==707) lanRequest(*v->app,{{"action","forget"},{"peer",peer}}); + if(id==705) v->draft["pair"] = {{"peer",peer},{"code",lan::normalizeCode(utf8(value(w,703)))}}; + if(id==701 && v->snapshot.value("enabled",false)) + { + v->draft.erase("pair"); + if (v->draft.value("shareInput", false)) v->draft.erase("shareInput"); + } + if(id==706 && !v->draft.erase("pair")) lanRequest(*v->app,{{"action","cancel"}}); + if(id==707) + { + v->draft["forget"][peer] = true; + if (v->draft.contains("positions")) + { + v->draft["positions"].erase(peer); + if (v->draft["positions"].empty()) v->draft.erase("positions"); + } + if (v->snapshot["positions"].size() == 1) v->draft.erase("shareInput"); + } if(id==727||id==728) { auto destination=pickLanFile(v->owner,true,id==728?L"kswitcher-previous.log":L"kswitcher-remote.log"); @@ -343,12 +410,9 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp) v->logMessage=L"Downloading diagnostic log..."; } } - if(id==729)lanRequest(*v->app,{{"action","shareLogs"},{"enabled",IsDlgButtonChecked(w,729)==BST_CHECKED}}); - if(id==715) - { - lanRequest(*v->app,{{"action","input"},{"enabled",true}}); - } - if(id==716)lanRequest(*v->app,{{"action","input"},{"enabled",false}}); + if(id==729)stageLanValue(*v,"shareLogs",checked(w,729)); + if(id==715 || id==716) stageLanValue(*v,"shareInput",id==715); + refreshLanFooter(*v); refreshLan(w,*v); return 0; } } diff --git a/src/ui_lan_layout.inl b/src/ui_lan_layout.inl index 281c93b..d04a1af 100644 --- a/src/ui_lan_layout.inl +++ b/src/ui_lan_layout.inl @@ -15,7 +15,17 @@ LanGridMetrics lanGridMetrics(HWND w,const LanView &v) } void moveLanMonitor(HWND parent,LanView &v,const std::string &peer,int x,int y) { - try{lanRequest(*v.app,{{"action","position"},{"peer",peer},{"x",x},{"y",y}});v.error.clear();} + try + { + lan::validateCell(v.snapshot.at("positions"), peer, x, y); + auto &positions = v.draft["positions"]; + auto cell = nlohmann::json::array({x,y}); + if (v.saved.at("positions").at(peer) != cell) positions[peer] = cell; + else if (positions.is_object()) positions.erase(peer); + if (positions.empty()) v.draft.erase("positions"); + v.error.clear(); + refreshLanFooter(v); + } catch(const std::exception &e){v.error=wide(e.what());} refreshLan(parent,v); } diff --git a/src/ui_log.inl b/src/ui_log.inl index 316059d..312632c 100644 --- a/src/ui_log.inl +++ b/src/ui_log.inl @@ -6,6 +6,7 @@ constexpr int LogChoice = 601, LogRows = 602, LogRefresh = 603, LogStatus = 604, LogDetails = 611, LogReset = 612; struct LogViewState { + WindowPalette palette; std::vector rows; std::vector visible; int sortColumn = 0; @@ -185,13 +186,47 @@ LRESULT CALLBACK logProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) if (msg == WM_NCCREATE) { SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)((CREATESTRUCTW *)lp)->lpCreateParams); - SetPropW(w, L"LogViewState", new LogViewState); + auto *state = new LogViewState; + state->palette.refresh(); + SetPropW(w, L"LogViewState", state); return TRUE; } - if (!app) + auto *state = logState(w); + if (!app || !state) return DefWindowProcW(w, msg, wp, lp); switch (msg) { + case WM_SETTINGCHANGE: + case WM_SYSCOLORCHANGE: + case WM_DWMCOLORIZATIONCOLORCHANGED: + state->palette.refresh(msg == WM_DWMCOLORIZATIONCOLORCHANGED + ? std::optional{static_cast(wp)} : std::nullopt); + RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN); + if (msg == WM_DWMCOLORIZATIONCOLORCHANGED) return 0; + break; + case WM_ERASEBKGND: + { + RECT client{}; + GetClientRect(w, &client); + FillRect(reinterpret_cast(wp), &client, state->palette.brush()); + return 1; + } + case WM_CTLCOLORBTN: + if (GetDlgCtrlID(reinterpret_cast(lp)) != LogProblems) break; + [[fallthrough]]; + case WM_CTLCOLORSTATIC: + { + const auto dc = reinterpret_cast(wp); + SetTextColor(dc, GetSysColor(COLOR_WINDOWTEXT)); + if (GetDlgCtrlID(reinterpret_cast(lp)) == LogDetails) + { + SetBkColor(dc, GetSysColor(COLOR_WINDOW)); + return reinterpret_cast(GetSysColorBrush(COLOR_WINDOW)); + } + SetBkColor(dc, state->palette.color()); + SetBkMode(dc, TRANSPARENT); + return reinterpret_cast(state->palette.brush()); + } case WM_COMMAND: if ((LOWORD(wp) == LogRefresh && HIWORD(wp) == BN_CLICKED) || (LOWORD(wp) == LogChoice && HIWORD(wp) == CBN_SELCHANGE)) @@ -251,7 +286,6 @@ LRESULT CALLBACK logProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) showLogDetails(w); if (((NMHDR *)lp)->code == LVN_COLUMNCLICK) { - auto *state = logState(w); int column = ((NMLISTVIEW *)lp)->iSubItem; state->descending = state->sortColumn == column ? !state->descending : false; state->sortColumn = column; @@ -282,7 +316,7 @@ LRESULT CALLBACK logProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) resizeForDpi(w, wp, lp); return 0; case WM_NCDESTROY: - delete logState(w); + delete state; RemovePropW(w, L"LogViewState"); app->logWindow = nullptr; disposeFont(w); diff --git a/src/ui_mouse_buttons.inl b/src/ui_mouse_buttons.inl index f135bbd..68167ff 100644 --- a/src/ui_mouse_buttons.inl +++ b/src/ui_mouse_buttons.inl @@ -480,7 +480,7 @@ void browseActionApplication(HWND w, MouseProfileEditor &editor) addActionApplication(w, editor); } -void saveMouseAction(HWND w, MouseActionEditor &editor) +void stageMouseAction(HWND w, MouseActionEditor &editor) { const auto choice = SendDlgItemMessageW(w, 734, CB_GETCURSEL, 0, 0); if (choice == CB_ERR) throw std::runtime_error("Choose an action."); @@ -557,7 +557,7 @@ LRESULT CALLBACK mouseActionEditorProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) return 0; } case IDOK: - saveMouseAction(w, *editor); + stageMouseAction(w, *editor); DestroyWindow(w); return 0; case IDCANCEL: @@ -626,7 +626,7 @@ void showMouseActionEditor(HWND parent, SettingsView &view, int event) SendMessageW(spin, UDM_SETRANGE32, 1, MaxEditedMouseVolumeStep); SetDlgItemInt(w, MouseVolumeStepField, action && isMouseVolumeStep(action->type) ? action->volumeStep : DefaultMouseVolumeStep, FALSE); - button(w, L"&Apply", IDOK, 248, 154, 100); + button(w, L"&Use action", IDOK, 248, 154, 100); button(w, L"Cancel", IDCANCEL, 362, 154, 100); SendDlgItemMessageW(w, 734, CB_SETCURSEL, action ? static_cast(action->type) + application : 0, 0); if (action && action->type == MouseActionType::Shortcut) value(w, 747, action->shortcut.format()); @@ -879,7 +879,7 @@ void showMouseProfileName(HWND owner, SettingsView &view, bool renaming) addButtonTooltip(tips, w, AddActionApp, L"Add application"); addButtonTooltip(tips, w, BrowseActionApp, L"Browse for an executable or shortcut"); fillActionApplications(w, *editor); - control(w, L"BUTTON", renaming ? L"&Apply" : L"&Add", WS_TABSTOP | BS_DEFPUSHBUTTON, IDOK, 248, 251, 100, 28); + control(w, L"BUTTON", renaming ? L"&Rename" : L"&Add", WS_TABSTOP | BS_DEFPUSHBUTTON, IDOK, 248, 251, 100, 28); button(w, L"Cancel", IDCANCEL, 362, 251, 100); EnableWindow(owner, FALSE); showRequestedWindow(w); diff --git a/src/ui_sync.inl b/src/ui_sync.inl index 7f4a1f9..6e60275 100644 --- a/src/ui_sync.inl +++ b/src/ui_sync.inl @@ -1,29 +1,41 @@ #include "ui_sync_conflicts.inl" -constexpr int SyncSave = 614; -struct SyncView { App *app; bool initialized{}, actionError{}; }; -void updateSyncControls(HWND w, App &app) +constexpr int SyncNow = 614; +struct SyncView { - bool enabled = checked(w, 601); - bool savedEnabled = loadSyncConfig(app.data).enabled; - for (int id : {602, 603, 604, 605, 606, 607, 610, 611, 613}) + App *app; + bool initialized{}, actionError{}, forgetPassword{}; + SyncConfig base; +}; +SyncConfig syncFields(HWND w); +bool syncDraftChanged(HWND w) +{ + auto *view = w ? reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA)) : nullptr; + return view && view->initialized && (view->forgetPassword || + GetWindowTextLengthW(GetDlgItem(w, 604)) != 0 || syncFields(w) != view->base); +} +void refreshSyncFooter(HWND w) +{ + const auto root = GetAncestor(w, GA_ROOT); + updateSettingsState(root, reinterpret_cast(GetWindowLongPtrW(root, GWLP_USERDATA))); +} +void updateSyncControls(HWND w, SyncView &view) +{ + const bool enabled = checked(w, 601); + const bool changed = syncDraftChanged(w); + for (int id : {602, 603, 604, 605, 606, 607, 613}) EnableWindow(GetDlgItem(w, id), enabled); - EnableWindow(GetDlgItem(w, 612), enabled && savedEnabled); - EnableWindow(GetDlgItem(w, SyncSave), enabled || savedEnabled); - value(w, SyncSave, enabled ? L"Save and s&ync" : L"S&ave connection"); - std::wstring status; - if (!enabled) - status = savedEnabled ? L"Click Save connection to disable synchronization." : - L"Synchronization is disabled. Enable it above to configure and sync."; - else if (!savedEnabled) - status = L"Configure the connection, then click Save and sync to enable synchronization."; - else - status = app.syncCommand(); - auto *view = reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA)); - if ((!view || !view->actionError) && value(w, 608) != status) value(w, 608, status); + for (int id : {610, 611, 612, SyncNow}) + EnableWindow(GetDlgItem(w, id), view.base.enabled && !changed); + EnableWindow(GetDlgItem(w, 609), view.base.enabled || !view.base.server.empty()); + value(w, 609, view.forgetPassword ? L"Keep saved &password" : L"Disconnect / &forget password"); + if (view.actionError) return; + const auto status = changed ? L"Click Apply or Save in Settings to apply connection changes." : + view.base.enabled ? view.app->syncCommand() : L"Synchronization is disabled."; + if (value(w, 608) != status) value(w, 608, status); } SyncConfig syncFields(HWND w) { - SyncConfig c; + auto c = reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA))->base; c.enabled = checked(w, 601); c.keepLocalLayouts = checked(w, 613); c.server = value(w, 602); @@ -32,6 +44,47 @@ SyncConfig syncFields(HWND w) c.path = value(w, 606); c.authMount = value(w, 607); return c; } +nlohmann::json collectSyncDraft(HWND w) +{ + auto &view = *reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA)); + auto config = syncFields(w); + if (config.enabled) validateSyncConfig(config); + Bytes protectedPassword; + if (config.enabled && !view.forgetPassword) + { + auto password = value(w, 604); + Bytes plain; + struct ClearPassword + { + std::wstring &password; + Bytes &plain; + ~ClearPassword() + { + SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t)); + SecureZeroMemory(plain.data(), plain.size()); + } + } clear{password, plain}; + const auto first = reinterpret_cast(password.data()); + plain.assign(first, first + password.size() * sizeof(wchar_t)); + if (!plain.empty()) protectedPassword = protect(plain); + } + return {{"config", encodeSyncConfig(config)}, {"base", encodeSyncConfig(view.base)}, + {"password", protectedPassword}, {"forget", view.forgetPassword}}; +} +void reloadSyncEditor(HWND w) +{ + if (!w) return; + auto &view = *reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA)); + view.initialized = false; + view.forgetPassword = view.actionError = false; + value(w, 604, L""); + const auto &c = view.base = loadSyncConfig(view.app->data); + check(w, 601, c.enabled); check(w, 613, c.keepLocalLayouts); + value(w, 602, c.server); value(w, 603, c.username); + value(w, 605, c.mount); value(w, 606, c.path); value(w, 607, c.authMount); + view.initialized = true; + updateSyncControls(w, view); +} LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) { if (msg == WM_SIZE) arrangeWindow(w); @@ -46,76 +99,49 @@ LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) if (!wp) KillTimer(w, 1); else { - if (!v->initialized) - { - const auto c = loadSyncConfig(v->app->data); - check(w, 601, c.enabled); check(w, 613, c.keepLocalLayouts); - value(w, 602, c.server); value(w, 603, c.username); - value(w, 605, c.mount); value(w, 606, c.path); value(w, 607, c.authMount); - v->initialized = true; - } - updateSyncControls(w, *v->app); + if (!v->initialized) reloadSyncEditor(w); + else updateSyncControls(w, *v); SetTimer(w, 1, 1000, nullptr); } } if (msg == WM_TIMER) { - updateSyncControls(w, *v->app); + updateSyncControls(w, *v); return 0; } if (msg == WM_COMMAND) { int id = LOWORD(wp); - if (id == 601 && HIWORD(wp) == BN_CLICKED) + if ((id == 601 || id == 613 || (id >= 602 && id <= 607)) && v->initialized) { + if (HIWORD(wp) != (id == 601 || id == 613 ? BN_CLICKED : EN_CHANGE)) return 0; + if (id == 601 && checked(w, 601)) v->forgetPassword = false; v->actionError = false; - updateSyncControls(w, *v->app); + updateSyncControls(w, *v); + refreshSyncFooter(w); return 0; } - if ((id == SyncSave || id == 610 || id == 611 || id == 612) && + if ((id == SyncNow || id == 610 || id == 611 || id == 612 || id == 609) && !IsWindowEnabled(GetDlgItem(w, id))) return 0; if (id == 612) { showSyncConflicts(w, *v->app); return 0; } if (id == 609) { v->actionError = false; - auto c = loadSyncConfig(v->app->data); - c.enabled = false; - saveSyncConfig(v->app->data, c); - forgetSyncPassword(c); - check(w, 601, false); - value(w, 604, L""); - updateSyncControls(w, *v->app); - value(w, 608, L"Disabled. Saved password removed. An in-flight server request may still finish."); - KillTimer(w, 1); + v->forgetPassword = !v->forgetPassword; + check(w, 601, v->forgetPassword ? false : v->base.enabled); + updateSyncControls(w, *v); + refreshSyncFooter(w); return 0; } - if (id == SyncSave || id == 610 || id == 611) + if (id == SyncNow || id == 610 || id == 611) { v->actionError = false; - if (!checked(w, 601)) - { - if (id != SyncSave) return 0; - auto c = loadSyncConfig(v->app->data); - c.enabled = false; - saveSyncConfig(v->app->data, c); - value(w, 604, L""); - updateSyncControls(w, *v->app); - return 0; - } - if (id != SyncSave && MessageBoxW(GetAncestor(w, GA_ROOT), id == 610 ? + if (id != SyncNow && MessageBoxW(GetAncestor(w, GA_ROOT), id == 610 ? L"Replace this PC's shared settings with the remote profile? A local backup will be saved. The open Settings window will refresh automatically; its unsaved edits will be discarded." : L"Replace the remote profile with this PC's saved settings? OpenBao retains older versions according to its retention policy. Unsaved edits are not included.", L"Resolve synchronization", MB_YESNO | MB_ICONWARNING) != IDYES) return 0; - auto c = syncFields(w); - if (c.enabled) validateSyncConfig(c); - auto password = value(w, 604); - try { if (!password.empty()) saveSyncPassword(c, password); } - catch (...) { SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t)); throw; } - SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t)); - value(w, 604, L""); - saveSyncConfig(v->app->data, c); value(w, 608, v->app->syncCommand(id == 610 ? 2 : id == 611 ? 3 : 1)); - updateSyncControls(w, *v->app); + updateSyncControls(w, *v); SetTimer(w, 1, 1000, nullptr); return 0; } @@ -180,13 +206,13 @@ HWND createSyncSettings(HWND pane, App &app) checkbox(w, L"&Keep this PC's layouts and layout shortcuts", 613, left, SyncActionsTop, width); settingsGroupLabel(w, L"Synchronization", left, SyncActionsTop + 38, width); label(w, L"Sync uses saved settings. Download remote refreshes the open Settings window.", left, 360, width); - button(w, L"Save and s&ync", SyncSave, left, 387, 196); + button(w, L"S&ync now", SyncNow, left, 387, 196); button(w, L"&Download remote", 610, 222, 387, 200); button(w, L"&Upload local", 611, 432, 387, 212); edit(w, 608, left, 423, width, 66, ES_MULTILINE | ES_READONLY | WS_VSCROLL | ES_AUTOVSCROLL); button(w, L"Resolve &individual conflicts…", 612, left, 499, SyncColumnWidth); button(w, L"Disconnect / &forget password", 609, SyncRightColumn, 499, SyncColumnWidth); - for (int id : {602, 603, 604, 605, 606, 607, 610, 611, 612, 613, SyncSave}) + for (int id : {602, 603, 604, 605, 606, 607, 610, 611, 612, 613, SyncNow}) EnableWindow(GetDlgItem(w, id), FALSE); captureSettingsGeometry(*layout, 0, w); layout->arranging = false; diff --git a/src/update.h b/src/update.h index 7ac5594..5140f83 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.7.2"; +inline constexpr wchar_t AppVersion[] = L"0.7.3"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; diff --git a/tests/chat_profiles.cpp b/tests/chat_profiles.cpp index 267fa5f..f564161 100644 --- a/tests/chat_profiles.cpp +++ b/tests/chat_profiles.cpp @@ -1,4 +1,5 @@ #include "app.h" +#include "mouse_buttons.h" #include "ocr.h" #include "screenshot.h" #include "lan_pairing.h" @@ -8,6 +9,7 @@ namespace { +constexpr int SettingsApply = 272; HWND findTestWindow(LPCWSTR className, LPCWSTR title) { HWND window=nullptr; @@ -175,8 +177,8 @@ void lanWindowLayoutChecks(const std::filesystem::path &root) std::abs(generate.left - code.right - gap) <= 1, "code input and Generate code share the same row"); require(pair.top == cancel.top && cancel.top == forget.top && pair.bottom == cancel.bottom && cancel.bottom == forget.bottom && - pair.right - pair.left == cancel.right - cancel.left && - cancel.right - cancel.left == forget.right - forget.left && + std::abs((pair.right - pair.left) - (cancel.right - cancel.left)) <= 1 && + std::abs((cancel.right - cancel.left) - (forget.right - forget.left)) <= 1 && pair.left == code.left && std::abs(forget.right - generate.right) <= 1 && std::abs(cancel.left - pair.right - gap) <= 1 && std::abs(forget.left - cancel.right - gap) <= 1, "pairing buttons align with the code row and have equal widths and gaps"); @@ -507,16 +509,25 @@ int main(int argc,char **argv) HWND parent = app.settingsWindow; auto saveEnabled=[&] { return IsWindowEnabled(GetDlgItem(parent,IDOK))!=FALSE; }; auto status=[&] { wchar_t text[256]{}; GetDlgItemTextW(parent,261,text,256); return std::wstring(text); }; - require(!saveEnabled() && status()==L"No unsaved settings.","new Settings shows clean state with Save disabled"); + const auto applyEnabled = [&] { return IsWindowEnabled(GetDlgItem(parent, SettingsApply)) != FALSE; }; + const auto closeCaption = [&] { + wchar_t caption[24]{}; + GetDlgItemTextW(parent, IDCANCEL, caption, std::size(caption)); + return std::wstring(caption); + }; + require(!saveEnabled() && !applyEnabled() && status() == L"No unsaved settings." && closeCaption() == L"&Close", + "new Settings offers Close and disables Save and Apply"); SendMessageW(parent,WM_COMMAND,IDOK,0); require(IsWindow(parent),"Save command with no changes does not apply or close Settings"); bool originalLog=IsDlgButtonChecked(settingsViewport(parent),208)==BST_CHECKED; CheckDlgButton(settingsViewport(parent),208,originalLog?BST_UNCHECKED:BST_CHECKED); SendMessageW(parent,WM_COMMAND,MAKEWPARAM(208,BN_CLICKED),0); - require(saveEnabled() && status().find(L"Unsaved settings") == 0,"checkbox edit immediately marks Settings dirty"); + require(saveEnabled() && applyEnabled() && status().find(L"Unsaved settings") == 0 && closeCaption() == L"&Cancel", + "checkbox edits offer Cancel, Save and Apply"); CheckDlgButton(settingsViewport(parent),208,originalLog?BST_CHECKED:BST_UNCHECKED); SendMessageW(parent,WM_COMMAND,MAKEWPARAM(208,BN_CLICKED),0); - require(!saveEnabled(),"reverting checkbox disables Save again"); + require(!saveEnabled() && !applyEnabled() && closeCaption() == L"&Close", + "reverting the checkbox restores Close"); wchar_t originalLimit[32]{}; GetDlgItemTextW(settingsViewport(parent),240,originalLimit,32); SetDlgItemTextW(settingsViewport(parent),240,L"invalid"); require(saveEnabled(),"invalid text remains an unsaved edit"); @@ -569,6 +580,14 @@ int main(int argc,char **argv) require(config.starts_with(L"[mcp_servers.kswitcher]\r\ncommand = \"") && config.find(L"KSwitcher.Config.exe\"\r\nargs = [\"--mcp\"]") != std::wstring::npos, "MCP section shows a Codex stdio configuration"); + RECT originalFrame{}; + GetWindowRect(parent, &originalFrame); + MONITORINFO captureMonitor{sizeof(captureMonitor)}; + if (GetMonitorInfoW(MonitorFromWindow(parent, MONITOR_DEFAULTTONEAREST), &captureMonitor)) + SetWindowPos(parent, nullptr, originalFrame.left, captureMonitor.rcWork.top, + originalFrame.right - originalFrame.left, + std::min(captureMonitor.rcWork.bottom - captureMonitor.rcWork.top, + LONG(MulDiv(820, GetDpiForWindow(parent), 96))), SWP_NOZORDER | SWP_NOACTIVATE); for (int page = 0; page < sections; ++page) { selectSettingsPage(parent, page); @@ -592,6 +611,9 @@ int main(int argc,char **argv) ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / (L"settings-section-" + std::to_wstring(page) + L".png"), ks::encodePng(ks::decodeImage(clip))); } + SetWindowPos(parent, nullptr, originalFrame.left, originalFrame.top, + originalFrame.right - originalFrame.left, originalFrame.bottom - originalFrame.top, + SWP_NOZORDER | SWP_NOACTIVATE); selectSettingsPage(parent, 11); require(TreeView_GetSelection(navigation) == settingsSection(navigation, 12) && IsWindowVisible(GetDlgItem(correction, 401)), "selecting an empty group opens its first page"); @@ -689,6 +711,29 @@ int main(int argc,char **argv) } RECT repaintClient{}; GetClientRect(parent, &repaintClient); + const auto checkAccent = [&](DWORD argb) + { + SendMessageW(parent, WM_DWMCOLORIZATIONCOLORCHANGED, argb, TRUE); + RedrawWindow(parent, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN); + const auto dc = GetDC(parent); + const auto rail = GetPixel(dc, inset, inset); + const auto footer = GetPixel(dc, inset, repaintClient.bottom - inset); + ReleaseDC(parent, dc); + require(rail != CLR_INVALID && rail == footer && rail == TreeView_GetBkColor(navigation), + "the rendered sidebar, navigation tree and footer use the same background"); + return rail; + }; + HIGHCONTRASTW contrast{sizeof(contrast)}; + SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0); + const bool highContrast = (contrast.dwFlags & HCF_HIGHCONTRASTON) != 0; + const auto warmAccent = checkAccent(0xFFFF4000); + const auto coolAccent = checkAccent(0xFF0040FF); + require(highContrast ? warmAccent == GetSysColor(COLOR_WINDOW) && warmAccent == coolAccent + : GetRValue(warmAccent) > GetRValue(coolAccent) && + GetBValue(warmAccent) < GetBValue(coolAccent), + "open Settings follows Windows accent changes and respects contrast themes"); + SendMessageW(parent, WM_SYSCOLORCHANGE, 0, 0); + RedrawWindow(parent, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN); const auto repaintDc = GetDC(parent); auto repaint = ks::screenshotClip(repaintDc, repaintClient.right, repaintClient.bottom, {}); ReleaseDC(parent, repaintDc); @@ -739,15 +784,13 @@ int main(int argc,char **argv) return color; }; RedrawWindow(pane, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN); - HIGHCONTRASTW contrast{sizeof(contrast)}; - SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0); - if (!(contrast.dwFlags & HCF_HIGHCONTRASTON)) + if (!highContrast) require(outline(profilesLabel) == RGB(7, 97, 83) && outline(eventsLabel) == RGB(157, 111, 21), "the selected result has its own outline within the current page"); SendMessageW(navigation, WM_KEYDOWN, VK_DOWN, 0); require(TreeView_GetSelection(navigation) == eventsResult, "Down selects the next result"); RedrawWindow(pane, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN); - if (!(contrast.dwFlags & HCF_HIGHCONTRASTON)) + if (!highContrast) require(outline(profilesLabel) == RGB(157, 111, 21) && outline(eventsLabel) == RGB(7, 97, 83), "the active outline moves when selecting another result on the same page"); SetWindowTextW(search, L"correction options personal dictionary Ukrainian"); @@ -956,15 +999,37 @@ int main(int argc,char **argv) RECT lanRect{};GetClientRect(lan,&lanRect);HDC lanDc=GetDC(lan); auto lanImage=ks::screenshotClip(lanDc,lanRect.right,lanRect.bottom,{});ReleaseDC(lan,lanDc); ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-pairing.png",ks::encodePng(ks::decodeImage(lanImage))); - require(IsWindowEnabled(parent)&&!saveEnabled(),"opening discovery leaves Settings clean"); - require(status().find(L"Network changes save automatically")!=std::wstring::npos,"Settings explains why network actions do not enable Save"); + require(IsWindowEnabled(parent) && !saveEnabled() && status() == L"No unsaved settings.", + "opening discovery leaves Settings clean"); + SendMessageW(lan, WM_COMMAND, 701, 0); + require(saveEnabled() && !std::filesystem::exists(root / L"lan-pairing.bin"), + "discovery is staged until Save"); + SendMessageW(lan, WM_TIMER, 1, 0); + SendMessageW(lan, WM_COMMAND, 701, 0); + require(!saveEnabled(), "reverting discovery clears its draft"); SendMessageW(parent,WM_COMMAND,IDCANCEL,0); } { ks::lan::Json fixture={{"version",1},{"id",std::string(32,'a')},{"enabled",false},{"inputPeer",std::string(32,'b')},{"inputEdge",1}, {"trusted",{{std::string(32,'b'),{{"name","Test paired KSwitcher"},{"key",std::string(64,'f')}}}}}}; auto text=fixture.dump();ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(text.begin(),text.end()))); - ks::App pairedApp(GetModuleHandleW(nullptr),true,root);ks::showSettings(pairedApp); + ks::App pairedApp(GetModuleHandleW(nullptr), true, root); + const auto settingsPath = root / L"settings.json"; + const auto previousSettings = ks::readFile(settingsPath, 8 * 1024 * 1024); + auto next = pairedApp.settings; + next.writeLog = !next.writeLog; + const auto failedDraft = ks::lan::Json{ + {"lan", {{"positions", {{"missing-peer", ks::lan::Json::array({0, -1})}}}}}, + {"sync", {{"config", ks::encodeSyncConfig({})}, {"base", ks::encodeSyncConfig({})}, + {"password", ks::Bytes{}}, {"forget", false}}}}.dump(); + bool rejected = false; + try { pairedApp.applySettings(next, ks::Bytes(failedDraft.begin(), failedDraft.end())); } + catch (const std::runtime_error &) { rejected = true; } + require(rejected && pairedApp.settings.writeLog != next.writeLog && + ks::readFile(settingsPath, 8 * 1024 * 1024) == previousSettings && !ks::syncVisible(root), + "a rejected LAN change rolls back the general and OpenBao settings"); + + ks::showSettings(pairedApp); HWND lan=showComputerSettings(pairedApp.settingsWindow); require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"single saved pair selected automatically when opening LAN settings"); wchar_t pairState[512]{};GetDlgItemTextW(lan,710,pairState,std::size(pairState)); @@ -975,10 +1040,12 @@ int main(int argc,char **argv) require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"refresh restores single paired selection without a peer list change"); auto grid=GetDlgItem(lan,721); SendMessageW(grid,WM_KEYDOWN,VK_UP,0);SendMessageW(grid,WM_KEYDOWN,VK_LEFT,0); - auto saved=ks::lan::Json::parse(ks::unprotect(ks::readFile(root/L"lan-pairing.bin",256*1024))); - require(saved["positions"][std::string(32,'b')]==ks::lan::Json::array({0,-1}),"keyboard moves monitor above this PC and saves immediately"); + auto window = pairedApp.settingsWindow; + require(IsWindowEnabled(GetDlgItem(window, IDOK)), "moving a monitor enables the global Save button"); + require(ks::lan::Json::parse(ks::unprotect(ks::readFile(root / L"lan-pairing.bin", 256 * 1024))) == fixture, + "moving a monitor leaves the saved configuration intact"); SendMessageW(lan,WM_TIMER,1,0); - require(saved["inputEdge"]==2,"monitor arrangement updates the existing input direction"); + require(!IsWindowEnabled(GetDlgItem(lan,715)),"input cannot start while discovery is disabled"); // Let the native radio-button theme animation finish before visual capture. auto repaintUntil=GetTickCount64()+200; @@ -991,7 +1058,75 @@ int main(int argc,char **argv) RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN); RECT r{};GetClientRect(lan,&r);HDC dc=GetDC(lan);auto screenshot=ks::screenshotClip(dc,r.right,r.bottom,{});ReleaseDC(lan,dc); ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-screen-layout.png",ks::encodePng(ks::decodeImage(screenshot))); - SendMessageW(pairedApp.settingsWindow,WM_COMMAND,IDCANCEL,0); + CheckDlgButton(lan, 729, BST_CHECKED); + SendMessageW(lan, WM_COMMAND, 729, 0); + SendMessageW(lan, WM_TIMER, 1, 0); + require(IsDlgButtonChecked(lan, 729) == BST_CHECKED, "status polling preserves the pending log permission"); + + selectSettingsPage(window, 5); + const auto actions = GetDlgItem(settingsViewport(window), 733); + LVFINDINFOW xButton{LVFI_PARAM}; + xButton.lParam = 3; + const int row = ListView_FindItem(actions, -1, &xButton); + require(row >= 0, "mouse action list contains XButton1"); + ListView_SetItemState(actions, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); + SendMessageW(window, WM_COMMAND, 735, 0); + const auto mouse = findTestWindow(L"KSwitcher.MouseAction", nullptr); + require(mouse != nullptr, "mouse action editor opens"); + SendDlgItemMessageW(mouse, 734, CB_SETCURSEL, static_cast(ks::MouseActionType::Mute), 0); + SendMessageW(mouse, WM_COMMAND, MAKEWPARAM(734, CBN_SELCHANGE), 0); + RedrawWindow(mouse, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); + RECT mouseClient{}; + GetClientRect(mouse, &mouseClient); + auto mouseDc = GetDC(mouse); + const auto mouseCapture = ks::screenshotClip(mouseDc, mouseClient.right, mouseClient.bottom, {}); + ReleaseDC(mouse, mouseDc); + ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"settings-mouse-action.png", + ks::encodePng(ks::decodeImage(mouseCapture))); + SendMessageW(mouse, WM_COMMAND, IDOK, 0); + require(!IsWindow(mouse) && !ks::mouseBinding(pairedApp.settings, ks::GlobalMouseProfile, int(xButton.lParam)), + "Use action accepts the draft without changing the active binding"); + + selectSettingsPage(window, 17); + const auto sync = GetDlgItem(settingsViewport(window), 271); + require(sync && IsWindowVisible(sync), "OpenBao opens inside Settings"); + CheckDlgButton(sync, 601, BST_CHECKED); + SendMessageW(sync, WM_COMMAND, 601, 0); + SetDlgItemTextW(sync, 602, L"https://vault.invalid"); + SetDlgItemTextW(sync, 603, L"fixture"); + require(!ks::syncVisible(root) && !IsWindowEnabled(GetDlgItem(sync, 614)), + "a pending connection neither saves nor starts sync"); + const auto tree = settingsNavigation(window); + const auto selected = TreeView_GetSelection(tree); + SendMessageW(window, WM_COMMAND, SettingsApply, 0); + require(IsWindow(window) && TreeView_GetSelection(tree) == selected && IsWindowVisible(sync), + "Apply keeps the same Settings page open"); + require(!IsWindowEnabled(GetDlgItem(window, SettingsApply)) && + !IsWindowEnabled(GetDlgItem(window, IDOK)) && IsWindowEnabled(GetDlgItem(sync, 614)), + "Apply refreshes the saved baseline and enables actions for the saved OpenBao connection"); + wchar_t closeCaption[24]{}; + GetDlgItemTextW(window, IDCANCEL, closeCaption, std::size(closeCaption)); + require(std::wstring_view(closeCaption) == L"&Close", "Apply restores Close"); + auto saved = ks::lan::Json::parse(ks::unprotect(ks::readFile(root / L"lan-pairing.bin", 256 * 1024))); + require(saved["positions"][std::string(32, 'b')] == ks::lan::Json::array({0, -1}) && + saved["inputEdge"] == 2 && saved["shareLogs"] == true, + "one Apply commits the monitor arrangement and log permission"); + const auto action = ks::mouseBinding(pairedApp.settings, ks::GlobalMouseProfile, int(xButton.lParam)); + require(action && action->type == ks::MouseActionType::Mute, + "the same Apply commits the mouse action"); + require(ks::loadSyncConfig(root).enabled && ks::loadSyncConfig(root).username == L"fixture", + "the same Apply commits the OpenBao connection"); + selectSettingsPage(window, 10); + CheckDlgButton(lan, 729, BST_UNCHECKED); + SendMessageW(lan, WM_COMMAND, 729, 0); + GetDlgItemTextW(window, IDCANCEL, closeCaption, std::size(closeCaption)); + require(std::wstring_view(closeCaption) == L"&Cancel", "editing again after Apply restores Cancel"); + SendMessageW(window, WM_COMMAND, IDOK, 0); + require(!IsWindow(window) && + ks::lan::Json::parse(ks::unprotect(ks::readFile(root / L"lan-pairing.bin", 256 * 1024))) + .at("shareLogs") == false, + "after Apply, Save can commit a new edit and close the window"); + ks::saveSyncConfig(root, {}); } { using J=ks::lan::Json;const std::string b(32,'b'),c(32,'c'); @@ -1005,11 +1140,22 @@ int main(int argc,char **argv) auto point=[&](int column,int row){return MAKELPARAM((2*column+1)*r.right/10,(2*row+1)*r.bottom/6);}; SendMessageW(grid,WM_LBUTTONDOWN,MK_LBUTTON,point(1,1));SendMessageW(grid,WM_MOUSEMOVE,MK_LBUTTON,point(1,0));SendMessageW(grid,WM_LBUTTONUP,0,point(1,0)); auto saved=J::parse(ks::unprotect(ks::readFile(root/L"lan-pairing.bin",256*1024))); - require(saved["positions"][b]==J::array({-1,-1})&&saved["positions"][c]==J::array({1,0}),"drag moves one monitor without moving another paired PC"); + require(saved == fixture, "dragging a monitor leaves the saved layout intact"); RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN); GetClientRect(lan,&r);auto dc=GetDC(lan);auto screenshot=ks::screenshotClip(dc,r.right,r.bottom,{});ReleaseDC(lan,dc); ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-three-computers.png",ks::encodePng(ks::decodeImage(screenshot))); - SendMessageW(layoutApp.settingsWindow,WM_COMMAND,IDCANCEL,0); + const auto wnd = layoutApp.settingsWindow; + const auto discard = SetTimer(wnd, 871, 30, [](HWND window, UINT, UINT_PTR id, DWORD) { + const auto dialog = findTestWindow(L"#32770", L"KSwitcher — Unsaved settings"); + if (!dialog) return; + KillTimer(window, id); + PostMessageW(dialog, WM_COMMAND, IDYES, 0); + }); + require(discard != 0, "can answer the discard confirmation"); + SendMessageW(wnd, WM_COMMAND, IDCANCEL, 0); + require(!IsWindow(wnd) && + J::parse(ks::unprotect(ks::readFile(root / L"lan-pairing.bin", 256 * 1024))) == fixture, + "Cancel discards a staged monitor drag without saving it"); } std::filesystem::remove_all(root); std::cout << "Passed " << passed << " chat profile checks\n"; diff --git a/tests/configuration.ps1 b/tests/configuration.ps1 index a73fad2..fbc413b 100644 --- a/tests/configuration.ps1 +++ b/tests/configuration.ps1 @@ -147,7 +147,7 @@ try { if($prompt -eq [IntPtr]::Zero) { Start-Sleep -Milliseconds 50 } } Assert ($prompt -ne [IntPtr]::Zero) 'cancel asks about unsaved changes' - Click $prompt 7 + Click $prompt 6 Assert ($config.WaitForExit(6000)) 'cancel exits configurator' Assert ((Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json).maxItems -eq 321) 'cancel preserves saved settings' $config=Launch 'KSwitcher.Config.exe' '--snippets' diff --git a/tests/input.cpp b/tests/input.cpp index 5edfe69..28c416e 100644 --- a/tests/input.cpp +++ b/tests/input.cpp @@ -9,7 +9,7 @@ #include #include "input_pause.h" #include "settings_ui.h" -static int settingsCloseChoice = IDCANCEL; +static int settingsCloseChoice = IDNO; static int settingsClosePrompts = 0; static void CALLBACK answerSettingsClose(HWND, UINT, UINT_PTR, DWORD) { @@ -1122,7 +1122,7 @@ int main(int argc, char **argv) { "reverted settings close without prompting"); ks::showSettings(app,false); SetDlgItemTextW(settingsViewport(app.settingsWindow), 240,L"invalid"); - settingsCloseChoice = IDNO; + settingsCloseChoice = IDYES; SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0); require(!app.settingsWindow && settingsClosePrompts == 2, "Cancel button allows discarding invalid edits"); @@ -1134,16 +1134,20 @@ int main(int argc, char **argv) { ks::showSettings(app,false); SendDlgItemMessageW(settingsViewport(app.settingsWindow), 208,BM_SETCHECK, originalSettings.writeLog ? BST_UNCHECKED : BST_CHECKED,0); - settingsCloseChoice = IDYES; - SendMessageW(app.settingsWindow,WM_CLOSE,0,0); + settingsCloseChoice = IDNO; + SendMessageW(app.settingsWindow, WM_CLOSE, 0, 0); + require(app.settingsWindow && settingsClosePrompts == 3 && + app.settings.writeLog == originalSettings.writeLog, + "keeping the editor open on close does not apply the draft"); + SendMessageW(app.settingsWindow, WM_COMMAND, IDOK, 0); require(!app.settingsWindow && settingsClosePrompts == 3 && app.settings.writeLog != originalSettings.writeLog && ks::loadSettings(app.data / L"settings.json",app.layouts).writeLog == app.settings.writeLog, - "Yes saves settings to disk and applies them before closing"); + "the Save button applies and persists the draft before closing"); app.settings = originalSettings; ks::setLoggingEnabled(originalSettings.writeLog); KillTimer(nullptr,timer); - settingsCloseChoice = IDCANCEL; + settingsCloseChoice = IDNO; ks::showSettings(app,false); } require(GetDlgItem(settingsViewport(app.settingsWindow), 271)!=nullptr,"OpenBao available without local opt-in"); @@ -1179,14 +1183,16 @@ int main(int argc, char **argv) { require(IsWindowEnabled(app.settingsWindow),"OpenBao allows switching to other settings pages"); for(int id:{602,603,604,605,606,607,610,611,612,613,614}) require(!IsWindowEnabled(GetDlgItem(syncWindow,id)),"disabled synchronization disables dependent controls"); - require(IsWindowEnabled(GetDlgItem(syncWindow,601)) && IsWindowEnabled(GetDlgItem(syncWindow,609)), - "enable and forget password remain available"); + require(IsWindowEnabled(GetDlgItem(syncWindow, 601)) && !IsWindowEnabled(GetDlgItem(syncWindow, 609)), + "synchronization can be enabled when no connection exists"); SendMessageW(syncWindow,WM_COMMAND,612,0); require(!FindWindowW(L"KSwitcher.SyncConflicts",nullptr),"disabled conflict action is ignored"); SendDlgItemMessageW(syncWindow,601,BM_SETCHECK,BST_CHECKED,0); SendMessageW(syncWindow,WM_COMMAND,MAKEWPARAM(601,BN_CLICKED),0); - for(int id:{602,603,604,605,606,607,610,611,613,614}) - require(IsWindowEnabled(GetDlgItem(syncWindow,id)),"enabling synchronization immediately enables connection controls"); + for (int id : {602, 603, 604, 605, 606, 607, 613}) + require(IsWindowEnabled(GetDlgItem(syncWindow,id)), "enabling synchronization unlocks connection fields"); + for (int id : {610, 611, 612, 614}) + require(!IsWindowEnabled(GetDlgItem(syncWindow,id)), "sync actions require a saved connection"); require(!ks::loadSyncConfig(app.data).enabled,"checking enable alone does not connect or persist"); SetDlgItemTextW(syncWindow, 602, L"https://draft.example.test"); selectSettingsPage(app.settingsWindow, 0); @@ -1195,12 +1201,14 @@ int main(int argc, char **argv) { GetDlgItemTextW(syncWindow, 602, draftServer, std::size(draftServer)); require(std::wstring_view(draftServer) == L"https://draft.example.test", "switching sections preserves the OpenBao draft"); - auto enabledSync=ks::loadSyncConfig(app.data); - enabledSync.enabled=true; - enabledSync.server=L"https://sync.example.test"; - enabledSync.username=L"test"; - ks::saveSyncConfig(app.data,enabledSync); - SendMessageW(syncWindow,WM_COMMAND,MAKEWPARAM(601,BN_CLICKED),0); + SetDlgItemTextW(syncWindow, 603, L"test"); + SendMessageW(app.settingsWindow, WM_COMMAND, IDOK, 0); + require(!app.settingsWindow && ks::loadSyncConfig(app.data).enabled, + "Save commits the staged connection"); + ks::showSettings(app, false); + ShowWindow(app.settingsWindow, SW_SHOWNOACTIVATE); + selectSettingsPage(app.settingsWindow, 17); + syncWindow = GetDlgItem(settingsViewport(app.settingsWindow), 271); ks::InputRegressionAccess::sampleConflicts(app); SendMessageW(syncWindow,WM_COMMAND,612,0); auto conflictsWindow=FindWindowW(L"KSwitcher.SyncConflicts",nullptr); @@ -1233,10 +1241,13 @@ int main(int argc, char **argv) { } SendDlgItemMessageW(syncWindow,601,BM_SETCHECK,BST_UNCHECKED,0); SendMessageW(syncWindow,WM_COMMAND,MAKEWPARAM(601,BN_CLICKED),0); - require(IsWindowEnabled(GetDlgItem(syncWindow,614)),"Save remains available to persist disabling sync"); - SendMessageW(syncWindow,WM_COMMAND,614,0); - require(!ks::loadSyncConfig(app.data).enabled,"saving disabled sync does not enable network access"); - require(!IsWindowEnabled(GetDlgItem(syncWindow,614)),"Save disables after disabled state is persisted"); + require(IsWindowEnabled(GetDlgItem(app.settingsWindow, IDOK)) && + !IsWindowEnabled(GetDlgItem(syncWindow, 614)) && ks::loadSyncConfig(app.data).enabled, + "disabling sync is staged and enables the main Save button"); + SendMessageW(app.settingsWindow, WM_COMMAND, IDOK, 0); + require(!app.settingsWindow && !ks::loadSyncConfig(app.data).enabled, + "the main Save button persists the disabled state"); + ks::showSettings(app, false); selectSettingsPage(app.settingsWindow, 0); require(ks::InputRegressionAccess::staleSync(app,false),"in-flight sync cannot overwrite newer local edits"); require(ks::InputRegressionAccess::staleSync(app,true),"disconnect discards in-flight downloaded profile"); diff --git a/tests/integration.cpp b/tests/integration.cpp index eb7fe70..9ec6b00 100644 --- a/tests/integration.cpp +++ b/tests/integration.cpp @@ -1230,6 +1230,31 @@ int main(int argc, char **argv) GetDlgItem(viewer, 610) && GetDlgItem(viewer, 611), "log viewer exposes program, command, result, problems filter and detail panel"); require(GetDlgItem(viewer, IDCANCEL) != rows, "log rows and Close have different IDs"); + const auto renderedBackground = [&](DWORD colorization) + { + SendMessageW(viewer, WM_DWMCOLORIZATIONCOLORCHANGED, colorization, TRUE); + RedrawWindow(viewer, nullptr, nullptr, RDW_UPDATENOW | RDW_ALLCHILDREN); + RECT client{}; + GetClientRect(viewer, &client); + const int inset = MulDiv(8, GetDpiForWindow(viewer), 96); + const auto dc = GetDC(viewer); + const auto top = GetPixel(dc, inset, inset); + const auto middle = GetPixel(dc, inset, client.bottom / 2); + const auto bottom = GetPixel(dc, inset, client.bottom - inset); + ReleaseDC(viewer, dc); + require(top != CLR_INVALID && top == middle && middle == bottom, + "the full log viewer background shares the same tint"); + return top; + }; + const auto warm = renderedBackground(0xFFFF4000); + const auto cool = renderedBackground(0xFF0040FF); + HIGHCONTRASTW contrast{sizeof(contrast)}; + SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0); + require((contrast.dwFlags & HCF_HIGHCONTRASTON) + ? warm == GetSysColor(COLOR_WINDOW) && warm == cool + : GetRValue(warm) > GetRValue(cool) && GetBValue(warm) < GetBValue(cool), + "the open log viewer follows Windows accent changes and respects contrast themes"); + SendMessageW(viewer, WM_SYSCOLORCHANGE, 0, 0); SetFocus(rows); SendMessageW(viewer, WM_COMMAND, MAKEWPARAM(IDCANCEL, EN_SETFOCUS), (LPARAM)rows); NMHDR clicked{rows, 602, NM_CLICK}; @@ -1250,6 +1275,7 @@ int main(int argc, char **argv) const auto logRoot = ks::dataDirectory(); require(logRoot == std::filesystem::path(ks::executable()).parent_path() / L"data", "clear test uses isolated portable data"); + ks::setLoggingEnabled(true); std::ofstream(logRoot / L"kswitcher.log") << "current-marker\n"; std::ofstream(logRoot / L"kswitcher.log.1") << "previous-marker\n"; ks::diagnosticEvent(L"buffered-before-clear");