Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5de010ee44 | ||
|
|
82292c8a7e | ||
|
|
4fbeb56421 | ||
|
|
e0bfdd9a90 | ||
|
|
9b565dd55e | ||
|
|
346af2256f | ||
|
|
99db99e603 | ||
|
|
63b7b879a3 | ||
|
|
727dc96908 | ||
|
|
ede4ce47c0 | ||
|
|
3b8b8f26fe | ||
|
|
19f1e4531c | ||
|
|
a124e030ab | ||
|
|
c18148a574 | ||
|
|
15197da548 | ||
|
|
66e24b5efc | ||
|
|
178573233b | ||
|
|
4e7a683c47 | ||
|
|
e33387c2d5 | ||
|
|
5de5b791bf | ||
|
|
c109408a98 | ||
|
|
90b2e0841f | ||
|
|
6621a49022 | ||
|
|
a2b88f247c | ||
|
|
684ca1b3cc | ||
|
|
524a836cc0 | ||
|
|
00c9cb0ee4 | ||
|
|
fa2f6d2ce4 | ||
|
|
30e70192dc | ||
|
|
94cab4c112 | ||
|
|
d13e9849a7 | ||
|
|
004fee4976 | ||
|
|
b08c5ff8ff | ||
|
|
b6e7bda220 | ||
|
|
89e506faae | ||
|
|
c78b51d341 | ||
|
|
0184b837f4 |
No files matched your search
+121
-3
@@ -1,14 +1,28 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.29 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.57 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
add_library(kscore src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp)
|
||||
add_executable(StayHere WIN32 utilities/StayHere/main.cpp)
|
||||
add_executable(StayHereTest WIN32 utilities/StayHere/main.cpp)
|
||||
target_compile_definitions(StayHereTest PRIVATE STAYHERE_TEST_INSTANCE)
|
||||
set_target_properties(StayHere PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/tools")
|
||||
foreach(utilityTarget StayHere StayHereTest)
|
||||
target_compile_definitions(${utilityTarget} PRIVATE UNICODE _UNICODE _WIN32_WINNT=0x0A00)
|
||||
target_link_libraries(${utilityTarget} PRIVATE user32 shell32 gdi32 wtsapi32)
|
||||
if(MSVC)
|
||||
target_compile_options(${utilityTarget} PRIVATE /utf-8)
|
||||
set_property(TARGET ${utilityTarget} PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(${utilityTarget} PRIVATE -municode -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
endforeach()
|
||||
add_library(kscore src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp)
|
||||
target_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 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)
|
||||
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
|
||||
target_link_libraries(KSwitcher PRIVATE kscore)
|
||||
@@ -30,6 +44,15 @@ target_link_libraries(KSwitcherScrollTests PRIVATE kscore)
|
||||
target_link_libraries(KSwitcherTests PRIVATE kscore)
|
||||
add_executable(KSwitcherIntegration tests/integration.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherIntegration PRIVATE kscore)
|
||||
# Opt-in interactive fixture: requires an installed Far Manager.
|
||||
add_executable(KSwitcherFarSnippetTests WIN32 tests/far_snippets.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherFarSnippetTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherFarSnippetTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherFarSnippetTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherFarSnippetTests PRIVATE -municode -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_executable(KSwitcherInputTests tests/input.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherInputTests PRIVATE kscore)
|
||||
target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES)
|
||||
@@ -48,6 +71,7 @@ else()
|
||||
endif()
|
||||
add_executable(KSwitcherOcrTests tests/ocr.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherOcrTests PRIVATE kscore)
|
||||
add_dependencies(KSwitcherOcrTests KSwitcherScreenshot)
|
||||
if(MSVC)
|
||||
set_property(TARGET kscore KSwitcher KSwitcherConfig KSwitcherScreenshot KSwitcherTests KSwitcherScrollTests KSwitcherIntegration KSwitcherInputTests KSwitcherOcrTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
target_compile_options(kscore PRIVATE /W4 /utf-8)
|
||||
@@ -65,8 +89,84 @@ else()
|
||||
target_link_options(KSwitcherOcrTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
enable_testing()
|
||||
add_executable(KSwitcherLanTests tests/lan.cpp)
|
||||
target_link_libraries(KSwitcherLanTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherLanTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherLanTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME lan-pairing-regressions COMMAND KSwitcherLanTests)
|
||||
add_executable(KSwitcherLanInputTests tests/lan_input.cpp)
|
||||
target_link_libraries(KSwitcherLanInputTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherLanInputTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherLanInputTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME lan-input-regressions COMMAND KSwitcherLanInputTests)
|
||||
add_executable(KSwitcherChatProfileTests tests/chat_profiles.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherChatProfileTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherChatProfileTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherChatProfileTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherChatProfileTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests)
|
||||
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
|
||||
target_link_libraries(KSwitcherHistoryHostTests PRIVATE kscore psapi)
|
||||
set_target_properties(KSwitcherHistoryHostTests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/history-host-fixture-$<CONFIG>")
|
||||
add_dependencies(KSwitcherHistoryHostTests KSwitcher KSwitcherScreenshot)
|
||||
add_custom_command(TARGET KSwitcherHistoryHostTests POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy "$<TARGET_FILE:KSwitcher>" "$<TARGET_FILE_DIR:KSwitcherHistoryHostTests>/KSwitcher.exe"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy "$<TARGET_FILE:KSwitcherScreenshot>" "$<TARGET_FILE_DIR:KSwitcherHistoryHostTests>/KSwitcher.Screenshot.exe"
|
||||
COMMAND ${CMAKE_COMMAND} -E touch "$<TARGET_FILE_DIR:KSwitcherHistoryHostTests>/.local-dev")
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherHistoryHostTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherHistoryHostTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherHistoryHostTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_executable(KSwitcherClipboardSnapshotTests tests/clipboard_snapshot.cpp)
|
||||
target_link_libraries(KSwitcherClipboardSnapshotTests PRIVATE kscore psapi)
|
||||
add_dependencies(KSwitcherClipboardSnapshotTests KSwitcherScreenshot)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherClipboardSnapshotTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherClipboardSnapshotTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherClipboardSnapshotTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_executable(KSwitcherImageCaptureTests tests/image_capture.cpp)
|
||||
target_link_libraries(KSwitcherImageCaptureTests PRIVATE kscore)
|
||||
add_dependencies(KSwitcherImageCaptureTests KSwitcherScreenshot)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherImageCaptureTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherImageCaptureTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherImageCaptureTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
# Explicit interactive test: stop the resident first so its clipboard listener
|
||||
# does not capture the test fixtures. Like KSwitcherIntegration, not part of ctest.
|
||||
add_executable(KSwitcherDictionaryTests tests/dictionary.cpp)
|
||||
target_link_libraries(KSwitcherDictionaryTests PRIVATE kscore psapi)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherDictionaryTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherDictionaryTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME dictionary-regressions COMMAND KSwitcherDictionaryTests)
|
||||
set_tests_properties(dictionary-regressions PROPERTIES WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME sync-regressions COMMAND KSwitcherSyncTests)
|
||||
add_test(NAME native-regressions COMMAND KSwitcherTests)
|
||||
add_executable(KSwitcherUtilitiesTests tests/utilities.cpp)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherUtilitiesTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherUtilitiesTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME utilities-regressions COMMAND KSwitcherUtilitiesTests)
|
||||
add_test(NAME stayhere-lifecycle COMMAND powershell -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/stayhere.ps1" -Executable "$<TARGET_FILE:StayHereTest>")
|
||||
add_test(NAME scroll-regressions COMMAND KSwitcherScrollTests)
|
||||
add_test(NAME input-regressions COMMAND KSwitcherInputTests)
|
||||
add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests)
|
||||
@@ -78,3 +178,21 @@ install(FILES LICENSE vendor/json-LICENSE.txt DESTINATION .)
|
||||
|
||||
add_custom_command(TARGET KSwitcher POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/dictionaries" "$<TARGET_FILE_DIR:KSwitcher>/dictionaries")
|
||||
install(DIRECTORY dictionaries DESTINATION .)
|
||||
|
||||
add_executable(KSwitcherLanClipboardTests tests/lan_clipboard.cpp)
|
||||
target_link_libraries(KSwitcherLanClipboardTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherLanClipboardTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherLanClipboardTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME lan-clipboard-regressions COMMAND KSwitcherLanClipboardTests)
|
||||
|
||||
add_executable(KSwitcherSettingsMergeTests tests/settings_merge.cpp)
|
||||
target_link_libraries(KSwitcherSettingsMergeTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherSettingsMergeTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherSettingsMergeTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME settings-save-merge COMMAND KSwitcherSettingsMergeTests)
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
# LAN mouse, keyboard and clipboard — v0.6.57 (experimental)
|
||||
|
||||
KSwitcher discovers other enabled KSwitcher instances, pairs them with the same
|
||||
code on both computers, and shares mouse and keyboard through a screen edge.
|
||||
The module runs inside the resident process. Multiple paired computers can be
|
||||
arranged on a monitor grid. Mouse and keyboard follow neighboring cells, including
|
||||
A → B → C, without relaying input through B. New text and images are also shared
|
||||
with all online paired computers: history and the active clipboard. File transfer
|
||||
is not implemented by clipboard synchronization.
|
||||
|
||||
## Set up multiple computers
|
||||
|
||||
1. Install the v0.6.57 or newer on every participating PC. Input protocol v2 requires all participants to update; earlier one-pair builds cannot connect. Preserve local data; do not copy pairing identities between PCs.
|
||||
2. Open Settings → Tools → KSwitcher computers and enable discovery on both PCs.
|
||||
Only running LAN-enabled KSwitcher instances appear, not generic network devices.
|
||||
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.
|
||||
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.
|
||||
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
|
||||
configured outer screen edge with no keys or buttons held. After the other
|
||||
computer acknowledges the handoff, both mouse and keyboard control that PC.
|
||||
Crossing another shared edge switches directly to that neighbor. Crossing back
|
||||
into the source computer restores its cursor at the corresponding edge. Empty
|
||||
cells, diagonal-only neighbors and offline PCs do not transfer control.
|
||||
|
||||
The source cursor is parked and hidden beneath a tiny no-activation window. A
|
||||
small banner identifies remote control; no full-screen layered bitmap is retained.
|
||||
The destination uses its own keyboard layout and runs its own hotkeys/snippets.
|
||||
The source suppresses forwarded events before its local hotkeys, snippets and
|
||||
other low-level hook consumers. Received input is marked so it is not forwarded
|
||||
again. Source recent-input tracking and shortcut latches reset when ownership changes.
|
||||
|
||||
**Ctrl+Alt+Esc** is emergency return, not the normal switching mechanism. Local
|
||||
physical input on a remotely controlled PC takes control back as well. Stop input
|
||||
sharing, disabling discovery, forgetting the currently controlled pair, suspension, secure
|
||||
desktop changes and connection loss cancel remote ownership. TCP heartbeat loss
|
||||
is detected after two seconds; a handoff request expires after one second.
|
||||
Held remote keys/buttons are released. Releases blocked by a secure desktop are
|
||||
retried when the ordinary desktop is available. Source key-ups for keys already
|
||||
sent remotely are consumed after return, avoiding stray local modifier events.
|
||||
|
||||
## Layout and limitations
|
||||
|
||||
- Positions are relative to this PC. All peers have independent authenticated
|
||||
connections; a failed peer does not disconnect the others. The physical source
|
||||
uses its own grid to choose every destination. Moving a monitor cancels current
|
||||
control safely and applies the updated layout without dropping all connections.
|
||||
Layouts are not synchronized automatically. One source controls a destination
|
||||
at a time. Each grid tile represents an entire PC, not an individual monitor.
|
||||
- Geometry uses the virtual desktop's outer bounding rectangle, including negative
|
||||
monitor coordinates. Internal monitor boundaries do not transfer control.
|
||||
Different resolutions map the entry position proportionally. Irregular layouts
|
||||
can have gaps on an outer edge; this is not a per-monitor arrangement editor.
|
||||
- Transferring while a key or mouse button is held is intentionally blocked.
|
||||
Dragging works within the controlled computer; dragging objects across PCs is
|
||||
not implemented. There is a short return cooldown to avoid bouncing.
|
||||
- Windows can block SendInput to elevated apps and secure desktops. Run both
|
||||
applications at suitable privilege levels for the target programs. The preview
|
||||
does not install a service, bypass UAC or implement remote Ctrl+Alt+Delete.
|
||||
- This is Windows input injection, not a virtual USB HID device. Raw-input games,
|
||||
exclusive full-screen applications and special device keys need separate testing.
|
||||
|
||||
## Network, authentication and storage
|
||||
|
||||
Discovery broadcasts on private IPv4 and link-local interfaces using UDP 45883.
|
||||
Input uses TCP 45884. Allow KSwitcher on your private network when Windows asks;
|
||||
the preview does not change firewall rules. Broadcast-blocked networks, separate
|
||||
VLANs, public IPv4 and IPv6-only networks are not supported by discovery yet.
|
||||
A second LAN-enabled KSwitcher cannot use the same ports on one computer.
|
||||
|
||||
The instance ID belongs to a data directory, not a hostname/IP address. Discovered
|
||||
names and addresses are untrusted. Pairing uses a generated 128-bit code and
|
||||
mutual HMAC-SHA256 challenge proofs bound to both instance IDs. The code is never
|
||||
transmitted or logged. The pair key is separate from the setup code.
|
||||
|
||||
The input channel authenticates both peers with the saved pair key and fresh
|
||||
session challenges. Directional AES-256-GCM session keys bind the identities,
|
||||
nonces and the input protocol domain. Screen positions determine routing after
|
||||
authentication; they are no longer part of the pair channel key. Fixed-size authenticated frames use strict sequence
|
||||
numbers, so tampering, reflection and replay are rejected. Input is not dispatched
|
||||
until authentication succeeds. This PSK channel does not provide forward secrecy.
|
||||
Queues and frame sizes are bounded; overflow disconnects rather than dropping a
|
||||
key-up and leaving a key pressed. The input worker never injects Windows input;
|
||||
the resident's main thread owns the input state and hooks.
|
||||
|
||||
Identity, trust, enablement and screen position stay in DPAPI-protected
|
||||
`data/lan-pairing.bin`, outside settings export and OpenBao sync. Do not clone this
|
||||
file between installations. Forget a pair on both PCs for bilateral removal.
|
||||
Closing the settings window does not cancel pairing or disable sharing.
|
||||
|
||||
Disabled discovery has no socket or worker. Input sharing reuses the single LAN
|
||||
worker; there is no extra resident executable or service. The main input timer
|
||||
runs only while sharing is enabled. The existing configurator talks to the
|
||||
resident through local IPC.
|
||||
|
||||
## Validation
|
||||
|
||||
Tests cover pairing, encrypted frames, replay/tamper rejection, actual loopback
|
||||
TCP authentication and bidirectional delivery, all four edges, ownership races,
|
||||
source suppression, scan codes, clicks/wheel, emergency return, held-key release,
|
||||
blocked injection, secure desktop recovery, exact one-pixel movement and timeout.
|
||||
Tests additionally exercise three actual TCP hubs, independent reconnect,
|
||||
A → B → C and back, vertical turns, unavailable neighbors, stale ownership,
|
||||
modifier delivery to only the active destination, and local shortcut recovery.
|
||||
UI tests drag three monitors and check persistence.
|
||||
|
||||
Three physical computers still need an end-to-end trial for their adapters,
|
||||
firewalls, displays and application privilege levels. The automated TCP tests
|
||||
use local sockets, and input-state tests use simulated desktop environments;
|
||||
they do not claim a completed three-machine hardware test.
|
||||
@@ -10,16 +10,49 @@ The original [Typlo](https://github.com/bitcodepro/Typlo) project and its data r
|
||||
|
||||
[Donate via Monobank](https://send.monobank.ua/jar/88h2TddKfS) · Thank you for supporting KSwitcher.
|
||||
|
||||
## KSwitcher computers — v0.6.57 (experimental)
|
||||
|
||||
Arrange multiple paired PCs on a monitor grid. Mouse and keyboard follow shared
|
||||
edges, including A → B → C and back. New text and images go to every online paired
|
||||
PC's history and active clipboard. The history Computers menu filters by multiple
|
||||
sources using checkboxes. See [LAN-PREVIEW.md](LAN-PREVIEW.md).
|
||||
|
||||
**Update every participating PC to v0.6.57:** input protocol v2 is incompatible
|
||||
with older one-pair builds. Keep each PC's own data directory. Pair every input
|
||||
source with all destinations, arrange the same physical layout on each PC and
|
||||
enable input sharing. Empty cells and offline neighbors block passage.
|
||||
|
||||
**Українською.** Розставте кілька спарованих ПК по сітці: миша й клавіатура
|
||||
переходять через спільний край, зокрема A → B → C і назад. Нові текст та зображення
|
||||
передаються всім доступним спарованим ПК в історію й активний буфер. Фільтр
|
||||
Computers в історії має чекбокси. Оновіть усі ПК до v0.6.57, залишивши кожному
|
||||
власну папку data. Спаруйте джерело вводу з усіма потрібними ПК й задайте
|
||||
однакове фізичне розташування на кожному. Передача файлів не реалізована.
|
||||
|
||||
Saving Settings now merges independent resident/editor changes. If the same field
|
||||
changed on both sides, choose whether to retain your draft without closing the
|
||||
window. Declining preserves all draft edits. No export/import workaround is needed.
|
||||
|
||||
## Run
|
||||
|
||||
Run `build/KSwitcher.exe`, or extract `dist/KSwitcher-win-x64.zip` and run the executable.
|
||||
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.
|
||||
If saving fails, the window stays open with your edits intact.
|
||||
Settings displays **No unsaved changes** with **Save** disabled until an edit is made.
|
||||
**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 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,
|
||||
S for Settings or X for Exit in the tray menu). In forms, press Alt+the underlined letter
|
||||
to activate a button, toggle a checkbox or focus a labeled field. Press Alt to reveal
|
||||
the underlines when Windows hides them. Shortcut-capture fields still record Alt combinations;
|
||||
to activate a button, toggle a checkbox or focus a labeled field. Dialog underline visibility
|
||||
still follows Windows preferences; press Alt in a dialog to reveal them.
|
||||
From v0.6.33, tray and history menus show access letters in the right-hand column.
|
||||
Press the menu letter without Alt: Alt dismisses an open menu. Shortcut-capture fields still record Alt combinations;
|
||||
press Tab to leave a shortcut field before using form access keys.
|
||||
Settings, the snippet editor and log viewer run on demand in **KSwitcher.Config.exe**, beside the main executable.
|
||||
Repeated launches activate the existing configurator; closing its last window exits that process.
|
||||
@@ -70,6 +103,9 @@ Ctrl+Alt+Delete and Win+L; these cannot be assigned.
|
||||
|
||||
Keyboard and mouse input forwarded by Microsoft Mouse Without Borders follows the same input
|
||||
path as a local keyboard/mouse, including shortcuts, recent-word conversion and snippets.
|
||||
On the sending computer, KSwitcher ignores keyboard events consumed by another keyboard hook
|
||||
(including Mouse Without Borders forwarding). The receiving computer still processes delivered
|
||||
input normally, so both computers can run KSwitcher without starting duplicate snippet operations.
|
||||
KSwitcher marks its own generated input so copy/paste, selection, modifier releases and shell-mask
|
||||
keys cannot trigger recursive commands or overwrite the recorded typing run. Other injected input
|
||||
is accepted, including key-up events and VK-only keyboard events. Unicode packets do not provide
|
||||
@@ -170,7 +206,8 @@ for shapes.
|
||||
**Canvas zoom:** use **Ctrl++ / Ctrl+-** (including numpad keys) or **Ctrl+mouse wheel**.
|
||||
Each step changes the view by 25%; the wheel zooms around the cursor, keyboard shortcuts around
|
||||
the viewport center. **Ctrl+0** restores the initial fit. Drag with the **middle mouse button**
|
||||
to pan an enlarged image. Zoom ranges from 0.1× to 16× the initial fit; the status bar shows the
|
||||
to pan an enlarged image. Panning is limited to axes where the image exceeds the viewport;
|
||||
an image that fits stays centered. Zoom ranges from 0.1× to 16× the initial fit; the status bar shows the
|
||||
actual image scale. Zoom and pan do not change annotations, export resolution or undo history.
|
||||
The wheel without Ctrl still adjusts the object under the cursor.
|
||||
|
||||
@@ -186,10 +223,29 @@ Every shape has a round rotation handle above its outline. Drag it to rotate aro
|
||||
hold **Shift** for 15-degree steps. The handle works for toolbar shapes and recognized shapes,
|
||||
including triangles. Resize handles and attached connectors follow the rotation; Ctrl+Z/Ctrl+Y
|
||||
undo and redo it. The square handle still controls outline thickness.
|
||||
From v0.6.34, endpoint, shape-corner and number-radius handles show the four-direction move cursor.
|
||||
Thickness handles retain directional resize cursors; rotation retains the hand cursor. Dragging,
|
||||
snapping and shape constraints are unchanged.
|
||||
**Triangle (G)** is also available directly on the toolbar: drag to create a triangle.
|
||||
Both drawn and recognized triangles have three independent vertex handles instead of bounding-box
|
||||
resize handles. Drag any vertex to reshape the triangle while keeping the other two fixed, even
|
||||
after rotation. Vertex edits support undo/redo, and the rotation and thickness handles remain available.
|
||||
**Arc (U)** draws an open half ellipse inside the dragged rectangle. Use the corner handles
|
||||
to resize it and the round handle to rotate it (Shift snaps to 15 degrees). Arcs support
|
||||
color, thickness, line style, moving, cloning, undo/redo and PNG export.
|
||||
|
||||
**Smoothing (0–100%)** on the screenshot toolbar adjusts pencil paths. With a pencil
|
||||
stroke selected it affects that stroke; otherwise it sets the default for new strokes
|
||||
(initially 25%). **Apply to all strokes** applies the displayed amount to all pencil
|
||||
strokes in the current image and sets the default for new ones. Shapes, text and
|
||||
highlights are unchanged. Zero restores the original path; higher values reduce more
|
||||
jitter. The original samples are retained through moving, endpoint editing and cloning,
|
||||
so lowering the amount does not accumulate distortion. Each slider drag or bulk change
|
||||
is one undo step, and PNG export uses the displayed geometry. Very short strokes remain
|
||||
unchanged. Shift-constrained and linked strokes start without automatic smoothing;
|
||||
you can explicitly adjust them afterwards. Shape/straight-line recognition is separate
|
||||
and does not turn recognized shapes back into pencil strokes.
|
||||
|
||||
**Trapezoid (B)** on the toolbar creates a trapezoid with parallel bases. Pencil recognition also
|
||||
fits nearly parallel, unequal bases into a clean trapezoid. Trapezoids support bounding-box resizing,
|
||||
rotation, styling and undo/redo; Ctrl+Z after recognition restores the original pencil stroke.
|
||||
@@ -258,6 +314,80 @@ thumbnails and source labels aligned with the scaled fonts and spacing.
|
||||
|
||||
## Implemented
|
||||
|
||||
### Chat language profiles — v0.6.48
|
||||
|
||||
> From v0.6.50: Viber chat OCR is temporarily disabled. Saved Viber profiles are retained but inactive. Telegram and Teams profiles are unchanged; clipboard/image OCR remains available.
|
||||
>
|
||||
> З v0.6.50: OCR чатів Viber тимчасово вимкнений. Збережені профілі Viber залишаються, але не діють. Профілі Telegram і Teams та OCR зображень/буфера працюють як раніше.
|
||||
|
||||
|
||||
Settings separates General, Languages, Shortcuts, Clipboard and Tools into native tabs.
|
||||
Switching tabs preserves edits; Save, Cancel, Import and Export stay available below every page.
|
||||
|
||||
Open the desired chat in Telegram Desktop or Microsoft Teams, then open Settings → Languages →
|
||||
**Languages for a chat…**. Select the chat and click the languages to include. Choose
|
||||
**Use languages**, then **Save** in Settings. The subset order is saved from the main
|
||||
layout list when editing the profile; one-language profiles are supported. **Remove profile** restores default behavior.
|
||||
|
||||
For a matching chat, **Alt+Shift**, **Win+Space** (and reverse **Win+Shift+Space**) cycle
|
||||
through that subset. KSwitcher's **Next layout** conversion uses the same subset.
|
||||
Explicit KSwitcher hotkey bindings take precedence. Without a matching profile,
|
||||
Windows shortcuts keep their normal behavior and Next layout uses the global cycle.
|
||||
Unavailable layouts are skipped; if none remain installed, the global cycle is used.
|
||||
Direct layout shortcuts are unchanged. Profiles do not change Windows' installed languages.
|
||||
|
||||
Matching uses the application and visible chat name, not a unique account/contact ID.
|
||||
Identically named chats in one application share a profile; renamed chats need a new
|
||||
profile. Telegram unread counters are ignored. Teams currently recognizes the desktop
|
||||
`Chat | name | Microsoft Teams` title format; other Teams title formats are not supported.
|
||||
Experimental Viber profiles introduced in v0.6.49 are disabled in v0.6.50 because repeated OCR caused delays. There is no background Viber OCR, recognition during language switching, or recognition when opening profiles. Saved Viber profiles are retained and marked inactive; Windows switching and Next layout use their normal/global behavior in Viber. Clipboard and image OCR are unchanged.
|
||||
From v0.6.53, chat profiles (application, visible chat name and ordered language IDs) are included in settings synchronization and manual export/import. Update every synchronizing PC to v0.6.53 or newer first: older clients reject this shared field. Profiles for different chats merge independently; conflicting edits or deletion versus editing of one chat require a choice. Missing Windows layouts stay saved and are skipped during switching, with global-cycle fallback if none are installed. Keep this PC's layouts preserves the global cycle and shortcuts while chat profiles still synchronize. Downloading a pre-v0.6.53 profile preserves existing chat profiles. Chat matching is unchanged; Viber profiles remain inactive.
|
||||
|
||||
**Українською.** Налаштування розділено на вкладки General, Languages, Shortcuts, Clipboard
|
||||
і Tools. Перехід між ними зберігає незбережені зміни; Save, Cancel, Import і Export доступні
|
||||
на кожній вкладці. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages
|
||||
for a chat…**. Вибери чат і потрібні мови, натисни **Use languages**, а потім **Save**.
|
||||
Набір діє для **Alt+Shift**, **Win+Space**, **Win+Shift+Space** та **Next layout** KSwitcher.
|
||||
Можна вибрати й одну мову; порядок зберігається із загального списку під час редагування профілю. **Remove profile**
|
||||
повертає звичайну поведінку. Без профілю системні комбінації працюють як раніше,
|
||||
а Next layout використовує загальний набір. Видалені з Windows розкладки пропускаються;
|
||||
якщо доступних мов профілю не залишилося, використовується загальний набір.
|
||||
Прямі комбінації мов не змінюються; явно задані комбінації KSwitcher мають пріоритет.
|
||||
Зіставлення виконується за програмою та назвою чату: однакові назви в одній програмі
|
||||
мають спільний профіль, після перейменування потрібен новий. Лічильник непрочитаних
|
||||
Telegram ігнорується. Teams підтримує зазначений вище формат заголовка.
|
||||
Експериментальні профілі Viber із v0.6.49 вимкнено у v0.6.50 через затримки від повторного OCR. Фонове розпізнавання, OCR при перемиканні мов та відкритті профілів більше не запускаються. Профілі Viber збережені й позначені як неактивні; системне перемикання та Next layout у Viber використовують звичайну поведінку й загальний набір. OCR буфера та зображень не змінено.
|
||||
Профілі локальні, входять до ручного експорту/імпорту, але не до
|
||||
хмарної синхронізації. Доступно з v0.6.48.
|
||||
|
||||
|
||||
### Telegram Web in Chrome — v0.6.51
|
||||
|
||||
Open a chat in Telegram Web K (`https://web.telegram.org/k/`) in Chrome, then use **Settings → Languages → Languages for a chat...** and select **Telegram Web: name**. Choose languages, then **Use languages → Save**. The same subset applies to Alt+Shift, Win+Space, Win+Shift+Space and Next layout. Web profiles are separate from desktop Telegram profiles. Same-name chats across browser profiles/accounts share a web profile.
|
||||
|
||||
Recognition uses Chrome accessibility: the address bar and active document must both identify a Telegram chat, then the visible header supplies the name. The app watches foreground/focus and address/header-change events; it does not use OCR, a polling timer, an extension, or message-history extraction. The address bar, home page and unsupported URLs do not match. Web A and other browsers have not been validated and are not advertised as supported. Page or accessibility changes can make a chat unavailable instead of guessing.
|
||||
|
||||
**Українською.** З v0.6.51 підтримано Telegram Web K у Chrome. Відкрий чат, потім **Settings → Languages → Languages for a chat...**, вибери **Telegram Web: ім’я**, мови та **Use languages → Save**. Набір діє для Alt+Shift, Win+Space, Win+Shift+Space і Next layout. Вебпрофілі окремі від Telegram Desktop; однакові назви в різних акаунтах/профілях браузера мають спільний вебпрофіль. Адреса й назва беруться через accessibility, без OCR, таймера, розширення та читання історії повідомлень. В адресному рядку, на головній сторінці й для непідтримуваних адрес профіль не діє. Web A та інші браузери не перевірені й не заявлені як підтримувані.
|
||||
|
||||
### Desktop chat snippet selection — v0.6.55
|
||||
|
||||
ChatGPT and Codex desktop editors use paced selection for snippet triggers. If only a verified suffix is selected, KSwitcher extends the selection and verifies the full trigger before replacement. Unrelated text or changed focus cancels the operation. Triggers remain recognized across keyboard layouts. One snippet can target multiple applications: add each with **Add app**, or enter comma-separated process names. These existing application scopes also synchronize.
|
||||
|
||||
**Українською.** У настільних ChatGPT і Codex тригер виділяється з паузами між натисканнями. Якщо виділилася лише перевірена кінцева частина, KSwitcher доповнює виділення й перевіряє весь тригер перед заміною. Інший текст або зміна фокусу скасовують операцію. Тригери розпізнаються в різних розкладках. Один сніпет можна прив’язати до кількох програм через **Add app** або назви процесів через кому; ці прив’язки вже підтримують синхронізацію.
|
||||
|
||||
### Application-specific snippets — v0.6.51
|
||||
|
||||
In **Tools → Snippets**, select a snippet and enable **Only in these applications**. Enter executable names separated by commas, or select a currently open application's process and choose **Add app**. For example: `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Save applies the changes; Cancel discards them.
|
||||
|
||||
A matching application-specific snippet takes precedence over a global snippet with the same trigger. The same trigger can be used for different applications; overlapping scopes for the same trigger are rejected. Existing snippets without a scope remain global. Matching is case-insensitive by process name, with or without `.exe`, and is checked before insertion. No OCR or timer is involved. Chrome scope means the entire browser, not one website.
|
||||
|
||||
Scopes are saved with snippets and included in manual import/export and synchronization; merge conflicts consider the application scopes. Use v0.6.51 or newer on every synchronizing PC before sharing scoped snippets: older versions do not understand the restriction and may treat the snippet as global.
|
||||
|
||||
**Українською.** У **Tools → Snippets** вибери сніпет, увімкни **Only in these applications** та задай назви процесів через кому або вибери відкриту програму зі списку й натисни **Add app**. Наприклад: `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. **Save** зберігає, **Cancel** відкидає зміни.
|
||||
|
||||
Сніпет конкретної програми має пріоритет над глобальним із тим самим тригером. Для різних програм однакові тригери дозволені, для перетинних областей — ні. Старі сніпети залишаються глобальними. Зіставлення за назвою процесу не залежить від регістру та суфікса `.exe`; OCR і таймерів немає. Для Chrome це весь браузер, а не окремий сайт. Обмеження входять до експорту/імпорту та синхронізації. Перед синхронізацією онови всі ПК до v0.6.51 або новішої: старі версії не розуміють обмеження та можуть застосувати сніпет глобально.
|
||||
### Existing features
|
||||
|
||||
- Installed Windows keyboard layouts, configurable cycle/order and direct shortcuts; IMEs are switch-only.
|
||||
Text conversion cycles skip layouts that leave the text unchanged and use the next enabled layout
|
||||
that changes it. If none changes the text, the operation keeps the text and advances one layout.
|
||||
@@ -265,13 +395,31 @@ thumbnails and source labels aligned with the scaled fonts and spacing.
|
||||
of the complete expected text. Browser/editor compatibility depends on its handling of simulated input.
|
||||
- Selection conversion and verified recent input (physical scan codes, 2-second typing-run boundary).
|
||||
- Same-process clipboard ownership plus verified WebView2 descendants, including the Teams fix.
|
||||
Clipboard synchronizers such as Mouse Without Borders may republish a copy only when
|
||||
KSwitcher first observed it owned by the target application and the selection text and
|
||||
editor selection metadata remain identical. Unobserved or altered foreign copies are rejected.
|
||||
Snippets normally require accessibility verification of their selected trigger and pasted text,
|
||||
even with logging disabled. If verification is unavailable or the paste differs, expansion
|
||||
stops without running cursor or Enter actions. Clipboard changes during paste also cancel actions.
|
||||
Far Manager uses its native Alt+Shift+Arrow selection, Ctrl+Insert copy and Shift+Insert
|
||||
paste commands instead: both the trigger and inserted text must match verified clipboard
|
||||
copies from Far. Cancellation restores the full temporary selection, not one cursor step.
|
||||
Far supports nonempty single-line replacements up to 4096 caret steps, including
|
||||
`{cursor}` and verified `{enter}` actions. Empty or multiline replacements are rejected
|
||||
before selection; pasting a newline could execute a command before it can be verified.
|
||||
- Teams recent-word conversion uses a single word-selection command and validates the copied range.
|
||||
If the editor's word boundary differs from the recorded typing, it falls back to paced character
|
||||
selection: Teams can coalesce a burst of Shift+Left events into just one character.
|
||||
- Clipboard snapshot/restoration with concurrent-copy, foreground and input-version checks.
|
||||
A snapshot interrupted by a concurrent clipboard publication is retried up to three total
|
||||
attempts before selection starts, provided the foreground and input context remain unchanged.
|
||||
A silently dropped copy is retried up to three total attempts while the clipboard and input
|
||||
context remain unchanged. Temporary transaction contents are excluded from Windows clipboard
|
||||
history and cloud synchronization. Paste is not blindly retried.
|
||||
history and cloud synchronization. Paste is not blindly retried: with manual paste readback
|
||||
enabled by Write log, a native Windows EDIT gets at most one retry when readback reports the
|
||||
original and fresh native queries confirm that exactly the original range is still selected.
|
||||
Other controls and unknown/changed selections are not retried. A verified failed paste clears
|
||||
repeat-conversion state and does not switch the Windows layout.
|
||||
- Case cycling, Russian/Ukrainian transliteration, verified undo and repeated conversion.
|
||||
- Text snippets across layouts, multiline insertion and a verified `{cursor}` position;
|
||||
`{enter}` presses Enter after insertion and cursor placement (once per marker), before buffered typing resumes.
|
||||
@@ -512,6 +660,30 @@ OpenBao administrator setup:
|
||||
and UI integration, so another service can be added without replacing the synchronization logic.
|
||||
Protocol and conflict regressions run with `build.ps1 -Test` or CMake's `sync-regressions` test.
|
||||
|
||||
## Portable utilities
|
||||
|
||||
The tray menu's **Tools** submenu lists `.exe` files in a `tools` folder beside
|
||||
`KSwitcher.exe`, sorted by filename. For example, place `StayHere.exe` at
|
||||
`tools/StayHere.exe` and choose **Tools → StayHere** to launch it manually.
|
||||
The folder is rescanned whenever the menu opens; no configuration or restart is needed.
|
||||
Only files directly in `tools` are listed (not subfolders, shortcuts, or KSwitcher's
|
||||
own executables beside the main program). Utilities start with `tools` as their working
|
||||
directory and are never started automatically. Their lifetime is independent of KSwitcher.
|
||||
An absent or empty folder displays a disabled placeholder; launch errors are reported.
|
||||
From v0.6.45, the release includes `tools/README.txt`, so extracting the ZIP or
|
||||
installing an update creates the folder. Add your own trusted portable executables;
|
||||
StayHere is bundled from v0.6.46, and settings synchronization does not transfer
|
||||
utility files. Updates preserve personal utilities and refresh bundled StayHere and
|
||||
documentation. Repository development scripts
|
||||
are not included in the portable tools folder.
|
||||
|
||||
Choose **Tools → StayHere** to start the bundled activity utility. It starts
|
||||
enabled; left-click its tray icon to pause/resume or right-click for Exit. While
|
||||
enabled it prevents automatic sleep and, after three minutes without input, sends
|
||||
F15 on its 15-second check. It does not move the mouse, bypass locking, start with
|
||||
KSwitcher automatically, or directly control Teams status. Locked/disconnected
|
||||
sessions do not receive simulated activity. See `tools/StayHere-README.md`.
|
||||
|
||||
## Build
|
||||
|
||||
The easiest reproducible local route uses the pinned portable w64devkit toolchain:
|
||||
@@ -545,8 +717,10 @@ default and require the main **Automatic correction (experimental)** checkbox to
|
||||
|
||||
- **Use custom replacements**: enter one `typo=correction` pair per line, for example
|
||||
`првиіт=привіт` or `helo=hello`. Entries are normalized to lowercase; duplicate source words
|
||||
are rejected. Each side must contain 1–32 letters of the same supported language, without
|
||||
spaces or punctuation. Explicit pairs take priority over dictionary recognition, including
|
||||
are rejected. The typo must contain 1–32 letters. The correction may contain several words
|
||||
separated by single spaces, for example `мамамила=мама мила`, up to 32 characters including
|
||||
spaces. Both sides must use the same supported language, without punctuation; leading,
|
||||
trailing and repeated spaces are not allowed. Explicit pairs take priority over dictionary recognition, including
|
||||
already valid words, and do not require dictionary membership or satisfy the frequency limit.
|
||||
- **Correct spelling typos using dictionaries**: checks unknown words in the current language
|
||||
after no layout correction is found. It accepts exactly one dictionary candidate reachable
|
||||
@@ -562,6 +736,8 @@ ALL CAPS, mixed-case identifiers, numbers, URLs and email addresses are skipped.
|
||||
is applied once, without chaining. Click **OK**, then **Save** in Settings; pairs and switches
|
||||
are included in settings export/import and synchronization. Undo restores the original word
|
||||
and suppresses its correction until restart.
|
||||
When synchronizing phrase replacements, update all participating PCs to v0.6.47 or newer;
|
||||
older clients reject spaces in replacement pairs.
|
||||
|
||||
### Layout correction and shared options
|
||||
|
||||
@@ -614,7 +790,12 @@ support automatic correction. Dictionary recognition is heuristic, not an unders
|
||||
subtitle vocabulary is incomplete, and uncommon names or jargon can need personal exceptions.
|
||||
|
||||
No network service or language model is used. The three dictionary files occupy about 2.6 MB on disk;
|
||||
the English/Ukrainian lookup data uses less than 3 MiB of RAM and is loaded on first automatic check.
|
||||
the bundled EN/UK/RU lookup payload uses about 0.90 MiB of RAM. When automatic correction is enabled,
|
||||
selected dictionaries are loaded before typing and shared by the input predictor and worker.
|
||||
Words are stored in compact indexed blocks; all words and frequency ranks are retained, and editable
|
||||
UTF-8 dictionary files keep the same format. Custom dictionaries can use more memory.
|
||||
`build.ps1 -Test` checks every bundled word/rank and measures lookup speed; CMake exposes the same
|
||||
check as `dictionary-regressions`. The payload figure excludes the rest of the process and allocator overhead.
|
||||
Keep `dictionaries/` beside the executable when copying the app. These word lists derive from
|
||||
[FrequencyWords](https://github.com/hermitdave/FrequencyWords) and are separately licensed under
|
||||
CC BY-SA 4.0; attribution, pinned source revision and license are in `dictionaries/`.
|
||||
@@ -630,6 +811,7 @@ Run `./package.ps1 -PublishRelease` after building and testing to refresh the tr
|
||||
.\build.ps1 -Test # Pure/native regression checks; does not touch the user's clipboard
|
||||
.\build.ps1 -Ocr # Render a synthetic image, decode it with WIC and recognize it with Windows OCR
|
||||
.\build.ps1 -Integration # Interactive, isolated test editor; avoid input for about 10 seconds
|
||||
.\build.ps1 -Far # Explicit integration test using an isolated Far Manager profile
|
||||
.\tests\configuration.ps1 # Separate-process settings tests; close KSwitcher first
|
||||
```
|
||||
|
||||
@@ -685,3 +867,31 @@ Keep `v0.4.2` as the last legacy `vX.Y.Z` release. Publish full packages as
|
||||
legacy version tag: clients that have not installed the bridge would select it.
|
||||
Keep the compatibility bridge in the first 100 releases returned by Gitea while
|
||||
supporting old clients; their immutable update code only reads that page.
|
||||
|
||||
### Editors that omit copied trailing spaces
|
||||
|
||||
From v0.6.31, KSwitcher recovers trailing ordinary spaces omitted by Ctrl+C only when Windows accessibility proves the complete selection. The same focused control and range are rechecked before paste, and the result is read back even without Write log. Recent-text conversion, automatic correction, repeat conversion and Undo retain exact verification. Missing letters, tabs, line breaks and unavailable or ambiguous selections are not reconstructed. No setting or shortcut has changed.
|
||||
|
||||
### Notification registration and Viber — v0.6.36
|
||||
|
||||
Notification registration runs in KSwitcher.Screenshot.exe; keep all three executables together. Startup registration is asynchronous. Viber pastes allow 75 ms for clipboard notifications before Ctrl+V, retaining focus, ownership and selection checks. This mitigates an intermittent clipboard timing issue; it does not guarantee all Viber failures are resolved. UI Automation is unchanged.
|
||||
|
||||
### Image history, OCR and duplicate fingerprints — v0.6.37
|
||||
|
||||
Image clipboard capture and automatic/uncached manual history OCR run in short-lived KSwitcher.Screenshot.exe processes. Keep all three executables together. Original clipboard formats, image limits, privacy exclusions, Windows OCR, optional Tesseract and searchable encrypted OCR results are preserved. Background OCR is cancelled on shutdown or an OCR-profile change; late results do not recreate deleted entries.
|
||||
|
||||
Consecutive duplicates use SHA-256 fingerprints inside the encrypted history index, including pixel fingerprints for equivalent image encodings. Older entries acquire fingerprints on first comparison without a bulk migration. Pins and OCR caches survive duplicate detection; non-consecutive copies still create separate entries. New text no longer loads the preceding image to rule out a duplicate. No shortcut, setting or default changed.
|
||||
|
||||
Moving OCR isolates its temporary memory rather than reducing the combined processing peak. A controlled three-run comparison retained about 0.8 MiB less private RAM in the caller after recognition; combined peak RAM was about 55.6 MiB before and 56.6 MiB with the helper. Results depend on the image, OCR engine and system.
|
||||
|
||||
### Pinned history checkbox — v0.6.42
|
||||
|
||||
Check **★ Pinned only** beside the history search box to show only pinned entries; uncheck it to show all entries. The checkbox sits on the left, immediately followed by the search box; its right edge stays aligned with the history list when resizing. The text search applies within that filter. Unpinning an item removes it from the pinned view immediately. The checkbox state and search are remembered after closing and reopening history. **Clear history…** still deletes the entire history after confirmation, including entries hidden by the filter.
|
||||
|
||||
### History process and clipboard memory — v0.6.40
|
||||
|
||||
History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc** closes it even when focus is on the window or an action button, releasing Windows UI allocations with the process. The resident keeps keyboard hooks, clipboard capture and history storage. Search and the pinned-only filter are preserved in encrypted view state. Each fresh opening selects and reveals the newest matching entry; background refreshes preserve the selected record while browsing. If a full-text item viewer is still open, the helper stays alive until the last viewer closes. Pin/delete, formatted/plain paste and OCR remain available; settings and default shortcuts are unchanged.
|
||||
|
||||
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
|
||||
|
||||
A live development-build test measured **4.37 MiB before history and 4.35 MiB after two open/Esc cycles**, compared with an earlier roughly 8–9 MiB plateau. A same-image clipboard-backup benchmark retained **12.78 MiB before versus 0.05 MiB after**. These measure private working set, not a guaranteed total footprint. Include all helpers when measuring active use: combined memory can be higher while history is open. No forced working-set trimming is used. Existing screenshots and shortcuts remain applicable. The v0.6.38 approach of retaining a hidden history window/RichEdit control is superseded by process termination.
|
||||
Binary file not shown.
+15
-18
@@ -1,29 +1,26 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.6.29 — 2026-11-02
|
||||
## v0.6.57 — 2026-11-06
|
||||
|
||||
## Changes
|
||||
- Added **Clear history… / Alt+H** directly to the Clipboard history window beside Edit image / Open item.
|
||||
- Clearing requires confirmation, with **No** selected by default. It removes all saved entries, including pinned entries and entries hidden by the current search. Cancelling leaves history unchanged.
|
||||
- The button follows the existing bottom action row when resizing. Settings retains its existing Clear history action.
|
||||
- Clearing saved history does not clear the current Windows clipboard or disable future recording. This release does not change memory management.
|
||||
- Settings Save merges independent edits with newer resident settings. Same-field conflicts offer a choice; declining keeps the window and draft open.
|
||||
- Multiple paired PCs on a draggable monitor grid; mouse and keyboard follow neighboring edges, including A → B → C and back. Connections reconnect independently.
|
||||
- New text, formatted text and screenshots synchronize to all online paired PCs: history and active clipboard. Newer local copies are preserved during incoming transfers.
|
||||
- Clipboard history has a persistent Computers checkbox filter and source labels. Lossless PNG transport avoids duplicate image payloads.
|
||||
- LAN modifier chords, DPI-scaled motion, cursor parking/return, automatic conversion ownership and queued wheel reversal fixes. Local shortcut latches reset on ownership changes.
|
||||
- Stable paired status, pairing/input button states, persistent selection and a fixed-size LAN window with scrolling where needed.
|
||||
|
||||
## Validation
|
||||
The final build passed isolated checks for the new button, cancellation, confirmed deletion of pinned/search-hidden entries and persistence after reloading the history store. 48 updater regression checks passed; all executable versions and release-manifest hashes were verified. The full desktop-interaction suite was not rerun for this focused patch.
|
||||
Passed: 5 settings-save merge checks, 203 LAN input/three-peer TCP, 289 clipboard transfer, 43 pairing, 828 settings/chat UI, 570 input, 341 native and 126 sync checks; dictionary equivalence for 140,939 words; wheel, StayHere, Utilities, screenshot UI/save/registration, 54 updater checks and updater progress. Three physical PCs have not been verified together. LAN remains experimental; follow LAN-PREVIEW.md.
|
||||
|
||||
## Known limitations
|
||||
Existing asynchronous-editor selection/clipboard limitations remain; this release does not fix the reported ChatGPT selection mismatch. Dictionary typo correction and OpenBao synchronization remain experimental as documented in v0.6.28.
|
||||
**Update ALL LAN participants to v0.6.57. Input protocol v2 cannot connect to older one-pair builds.** Pair every physical input source with each destination. Configure the same physical arrangement on each PC; layouts are not automatically synchronized. File transfer, offline clipboard backfill, cross-PC dragging and secure desktops remain unsupported.
|
||||
|
||||
**Upgrade:** choose Update in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
|
||||
For manual installation, exit KSwitcher, close screenshot editors and extract the entire ZIP into its installation folder. Keep personal `data/` and customized dictionaries.
|
||||
## Upgrade and compatibility
|
||||
Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
|
||||
For manual installation, exit KSwitcher, close its configurator and screenshot editors, and extract the entire ZIP into its installation folder. Keep personal `data/`, customized dictionaries and your own tools. Keep the three KSwitcher executables together; StayHere runs independently.
|
||||
|
||||
Download **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**. The package includes all three executables, a release manifest, offline dictionaries, documentation and license notices. No personal settings, passwords, server address or clipboard history are included.
|
||||
**Update every synchronizing PC to v0.6.51 or newer before sharing application-specific snippets. Older versions do not understand application restrictions and may treat scoped snippets as global.** Keep a backup before downgrading. Settings with Telegram Web profiles require v0.6.51 or newer. Chat profiles now synchronize from v0.6.53. Update every synchronizing PC to v0.6.53 or newer before syncing: older clients reject the chat-profile field. Synchronization stores application names, visible chat names and language IDs on your configured OpenBao server. No message contents are included.
|
||||
|
||||
Build and package:
|
||||
Download **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**. The package contains no personal settings, credentials or clipboard history.
|
||||
|
||||
```powershell
|
||||
.\build.ps1 -Stage -Test
|
||||
.\package.ps1 -PublishRelease
|
||||
```
|
||||
|
||||
Publish stable `release-vX.Y.Z` tags matching the executable version. Keep `v0.4.2` as the last legacy tag.
|
||||
Publish stable `release-vX.Y.Z` tags matching the executable version. Keep `v0.4.2` as the last legacy tag.
|
||||
@@ -1 +1 @@
|
||||
c9c3e3579575a41d434201d4f37bf3829e53c1ef23c42cb1c077930dfe8fdfa6 KSwitcher-win-x64.zip
|
||||
f3ec4f7a62b4479929d94d6d6f7f68edb8b4a47b84edac7258afb64dbe07aef2 KSwitcher-win-x64.zip
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"version": "0.6.57",
|
||||
"schema": 1,
|
||||
"files": [
|
||||
{
|
||||
"size": 2106368,
|
||||
"path": "KSwitcher.exe",
|
||||
"sha256": "3b7315e1545f70739fd1a7c099ddeab28362b323521d93879fa43fdd76133f8e"
|
||||
},
|
||||
{
|
||||
"size": 2003456,
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"sha256": "a819ec42030990725326730396680388cbcb870dd00c0a97856cb1615f9db27b"
|
||||
},
|
||||
{
|
||||
"size": 3151360,
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"sha256": "8473697245c2c961496135eaaff6de9e9a19e917f2fd7299a16068210223d396"
|
||||
},
|
||||
{
|
||||
"size": 4401,
|
||||
"path": "LICENSE",
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
|
||||
},
|
||||
{
|
||||
"size": 1096,
|
||||
"path": "json-LICENSE.txt",
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
|
||||
},
|
||||
{
|
||||
"size": 79896,
|
||||
"path": "README.md",
|
||||
"sha256": "8b4b1e905a2f0a39d532e61136ec7eca473492a39a538eb073ed829307adefae"
|
||||
},
|
||||
{
|
||||
"size": 7921,
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"sha256": "2467b86bbad7d7dce1e0c65c8c0faf2320e4804e90a85784a058afa357127b6b"
|
||||
},
|
||||
{
|
||||
"size": 732485,
|
||||
"path": "dictionaries/en.txt",
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
|
||||
},
|
||||
{
|
||||
"size": 20566,
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
|
||||
},
|
||||
{
|
||||
"size": 2265,
|
||||
"path": "dictionaries/README.md",
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
|
||||
},
|
||||
{
|
||||
"size": 1109134,
|
||||
"path": "dictionaries/ru.txt",
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
|
||||
},
|
||||
{
|
||||
"size": 1280,
|
||||
"path": "dictionaries/sources.json",
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
|
||||
},
|
||||
{
|
||||
"size": 940799,
|
||||
"path": "dictionaries/uk.txt",
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
|
||||
},
|
||||
{
|
||||
"size": 993,
|
||||
"path": "tools/README.txt",
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
|
||||
},
|
||||
{
|
||||
"size": 134656,
|
||||
"path": "tools/StayHere.exe",
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
|
||||
},
|
||||
{
|
||||
"size": 2796,
|
||||
"path": "tools/StayHere-README.md",
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
param([switch]$Test, [switch]$Integration, [switch]$Ocr, [switch]$Stage)
|
||||
param([switch]$Test, [switch]$Integration, [switch]$Ocr, [switch]$Stage, [switch]$Far)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = $PSScriptRoot
|
||||
$compiler = Join-Path $root '.tools\w64devkit\bin\g++.exe'
|
||||
@@ -15,8 +15,14 @@ Set-Content -LiteralPath (Join-Path (Split-Path $executablePath) '.local-dev') -
|
||||
Push-Location $root
|
||||
try {
|
||||
$common = @('-std=c++20','-Os','-DNDEBUG','-DUNICODE','-D_UNICODE','-DWIN32_LEAN_AND_MEAN','-DNOMINMAX','-D_WIN32_WINNT=0x0A00','-Wall','-Wextra','-Wno-missing-field-initializers','-Isrc','-Ivendor','-ffunction-sections','-fdata-sections')
|
||||
$libs = @('-lwinhttp','-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore')
|
||||
foreach ($name in @('core','platform','autostart','autocorrect','storage','sync','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) {
|
||||
$libs = @('-lws2_32','-lbcrypt','-liphlpapi','-lwinhttp','-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore')
|
||||
$utilityDirectory = Join-Path (Split-Path $executablePath) 'tools'
|
||||
New-Item -ItemType Directory -Force $utilityDirectory,build/release/tools | Out-Null
|
||||
$stayHere = Join-Path $utilityDirectory 'StayHere.exe'
|
||||
& $compiler @common -Werror -mwindows -municode -static -s utilities/StayHere/main.cpp -luser32 -lshell32 -lgdi32 -lwtsapi32 -o $stayHere
|
||||
if ($LASTEXITCODE) { throw 'StayHere build failed' }
|
||||
Copy-Item -LiteralPath $stayHere -Destination build/release/tools/StayHere.exe -Force
|
||||
foreach ($name in @('lan_channel','lan_input','lan','lan_pairing','core','platform','autostart','autocorrect','storage','sync','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) {
|
||||
& $compiler @common -c "src/$name.cpp" -o "build/$name.o"
|
||||
if ($LASTEXITCODE) { throw "Compilation failed: $name" }
|
||||
}
|
||||
@@ -29,19 +35,47 @@ try {
|
||||
& windres --codepage=65001 -DKS_SCREENSHOT_RESOURCES resources/app.rc -O coff -o build/screenshot-res.o
|
||||
if ($LASTEXITCODE) { throw 'Screenshot resource compilation failed' }
|
||||
New-Item -ItemType Directory -Force build/release | Out-Null
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o @libs -o $executablePath
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o @libs -o $executablePath
|
||||
if ($LASTEXITCODE) { throw 'Link failed' }
|
||||
Copy-Item -LiteralPath $executablePath -Destination build/release/KSwitcher.exe -Force
|
||||
$configPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Config.exe'
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o build/configuration.o build/config_main.o build/ui-config.o build/app-res.o @libs -o $configPath
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o build/configuration.o build/config_main.o build/ui-config.o build/app-res.o @libs -o $configPath
|
||||
if ($LASTEXITCODE) { throw 'Configurator link failed' }
|
||||
Copy-Item -LiteralPath $configPath -Destination build/release/KSwitcher.Config.exe -Force
|
||||
$screenshotPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Screenshot.exe'
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/core.o build/platform.o build/ocr.o build/screenshot.o build/screenshot_notifications.o build/screenshot_activation.o build/screenshot_main.o build/screenshot-res.o @libs -o $screenshotPath
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/ocr.o build/screenshot.o build/screenshot_notifications.o build/screenshot_activation.o build/screenshot_main.o build/screenshot-res.o @libs -o $screenshotPath
|
||||
if ($LASTEXITCODE) { throw 'Screenshot link failed' }
|
||||
Copy-Item -LiteralPath $screenshotPath -Destination build/release/KSwitcher.Screenshot.exe -Force
|
||||
if ($Test) {
|
||||
& $compiler @common tests/sync.cpp build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o @libs -static -s -o build/KSwitcherSyncTests.exe
|
||||
& $compiler @common -Werror tests/settings_merge.cpp build/sync.o build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Settings merge test build failed' }
|
||||
& .\build\KSwitcherSettingsMergeTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Settings merge tests failed' }
|
||||
& $compiler @common -Werror tests/lan_clipboard.cpp build/lan_channel.o build/lan_pairing.o build/core.o build/platform.o @libs -static -s -o build/KSwitcherLanClipboardTests.exe
|
||||
if ($LASTEXITCODE) { throw 'LAN clipboard test build failed' }
|
||||
& .\build\KSwitcherLanClipboardTests.exe
|
||||
if ($LASTEXITCODE) { throw 'LAN clipboard tests failed' }
|
||||
& $compiler @common -Werror tests/lan_input.cpp build/lan_channel.o build/lan_input.o build/lan_pairing.o build/core.o build/platform.o @libs -static -s -o build/KSwitcherLanInputTests.exe
|
||||
if ($LASTEXITCODE) { throw 'LAN input test build failed' }
|
||||
& .\build\KSwitcherLanInputTests.exe
|
||||
if ($LASTEXITCODE) { throw 'LAN input tests failed' }
|
||||
& $compiler @common -Werror tests/lan.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o @libs -static -s -o build/KSwitcherLanTests.exe
|
||||
if ($LASTEXITCODE) { throw 'LAN test build failed' }
|
||||
& .\build\KSwitcherLanTests.exe
|
||||
if ($LASTEXITCODE) { throw 'LAN pairing tests failed' }
|
||||
& $compiler @common -Werror -DSTAYHERE_TEST_INSTANCE -mwindows -municode -static -s utilities/StayHere/main.cpp -luser32 -lshell32 -lgdi32 -lwtsapi32 -o build/StayHereTest.exe
|
||||
if ($LASTEXITCODE) { throw 'StayHere fixture build failed' }
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File tests/stayhere.ps1 -Executable (Join-Path $outDir 'StayHereTest.exe')
|
||||
if ($LASTEXITCODE) { throw 'StayHere lifecycle tests failed' }
|
||||
& $compiler @common tests/utilities.cpp -static -s -o build/KSwitcherUtilitiesTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Utilities test build failed' }
|
||||
& .\build\KSwitcherUtilitiesTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Utilities tests failed' }
|
||||
& $compiler @common tests/dictionary.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/autocorrect.o @libs -lpsapi -static -s -o build/KSwitcherDictionaryTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Dictionary test build failed' }
|
||||
& .\build\KSwitcherDictionaryTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Dictionary tests failed' }
|
||||
& $compiler @common tests/sync.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o @libs -static -s -o build/KSwitcherSyncTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Sync test build failed' }
|
||||
& .\build\KSwitcherSyncTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Sync tests failed' }
|
||||
@@ -49,15 +83,19 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Scroll test build failed' }
|
||||
& .\build\KSwitcherScrollTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Scroll tests failed' }
|
||||
& $compiler @common tests/tests.cpp build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o @libs -static -s -o build/KSwitcherTests.exe
|
||||
& $compiler @common tests/tests.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o @libs -static -s -o build/KSwitcherTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Test build failed' }
|
||||
& .\build\KSwitcherTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Tests failed' }
|
||||
& $compiler @common tests/input.cpp build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe
|
||||
& $compiler @common tests/input.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Input test build failed' }
|
||||
& .\build\KSwitcherInputTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Input tests failed' }
|
||||
& $compiler @common tests/screenshot_ui.cpp build/core.o build/platform.o build/ocr.o build/screenshot-res.o @libs -static -s -o build/KSwitcherScreenshotUITests.exe
|
||||
& $compiler @common tests/chat_profiles.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Chat profile test build failed' }
|
||||
& .\build\KSwitcherChatProfileTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Chat profile tests failed' }
|
||||
& $compiler @common tests/screenshot_ui.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/ocr.o build/screenshot-res.o @libs -static -s -o build/KSwitcherScreenshotUITests.exe
|
||||
if ($LASTEXITCODE) { throw 'Screenshot UI test build failed' }
|
||||
& .\build\KSwitcherScreenshotUITests.exe
|
||||
if ($LASTEXITCODE) { throw 'Screenshot UI tests failed' }
|
||||
@@ -65,7 +103,7 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Screenshot save tests failed' }
|
||||
$registrationTest = Join-Path (Split-Path $executablePath) 'KSwitcherRegistrationTests.exe'
|
||||
try {
|
||||
& $compiler @common tests/screenshot_registration.cpp build/core.o build/platform.o @libs -static '-Wl,--gc-sections' -s -o $registrationTest
|
||||
& $compiler @common tests/screenshot_registration.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o @libs -static '-Wl,--gc-sections' -s -o $registrationTest
|
||||
if ($LASTEXITCODE) { throw 'Screenshot registration test build failed' }
|
||||
& $registrationTest
|
||||
if ($LASTEXITCODE) { throw 'Screenshot registration tests failed' }
|
||||
@@ -76,16 +114,43 @@ try {
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File tests/update_progress.ps1
|
||||
if ($LASTEXITCODE) { throw 'Updater progress UI tests failed' }
|
||||
}
|
||||
if ($Far) {
|
||||
& $compiler @common tests/far_snippets.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -mwindows -municode -static -s -o build/KSwitcherFarSnippetTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Far snippet test build failed' }
|
||||
$fixture = Start-Process -FilePath (Join-Path $outDir 'KSwitcherFarSnippetTests.exe') -WindowStyle Hidden -Wait -PassThru
|
||||
Get-Content -LiteralPath (Join-Path $outDir 'far-snippets.log')
|
||||
if ($fixture.ExitCode) { throw 'Far snippet tests failed' }
|
||||
}
|
||||
if ($Integration) {
|
||||
& $compiler @common tests/integration.cpp build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherIntegration.exe
|
||||
$historyFixture = Join-Path (Resolve-Path build) ('history-host-fixture-' + [guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory $historyFixture | Out-Null
|
||||
Copy-Item $executablePath,(Join-Path (Split-Path $executablePath) 'KSwitcher.Screenshot.exe') -Destination $historyFixture
|
||||
Set-Content (Join-Path $historyFixture '.local-dev') 'Isolated history integration test'
|
||||
$historyTest = Join-Path $historyFixture 'KSwitcherHistoryHostTests.exe'
|
||||
& $compiler @common tests/history_host.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/ocr.o @libs -lpsapi -static -s -o $historyTest
|
||||
if ($LASTEXITCODE) { throw 'History host test build failed' }
|
||||
& $historyTest
|
||||
if ($LASTEXITCODE) { throw 'History host tests failed' }
|
||||
$snapshotTest = Join-Path (Split-Path $executablePath) 'KSwitcherClipboardSnapshotTests.exe'
|
||||
& $compiler @common tests/clipboard_snapshot.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/ocr.o @libs -lpsapi -static -s -o $snapshotTest
|
||||
if ($LASTEXITCODE) { throw 'Clipboard snapshot test build failed' }
|
||||
& $snapshotTest
|
||||
if ($LASTEXITCODE) { throw 'Clipboard snapshot tests failed' }
|
||||
$captureTest = Join-Path (Split-Path $executablePath) 'KSwitcherImageCaptureTests.exe'
|
||||
& $compiler @common tests/image_capture.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/ocr.o @libs -static -s -o $captureTest
|
||||
if ($LASTEXITCODE) { throw 'Image capture test build failed' }
|
||||
& $captureTest
|
||||
if ($LASTEXITCODE) { throw 'Image capture tests failed' }
|
||||
& $compiler @common tests/integration.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherIntegration.exe
|
||||
if ($LASTEXITCODE) { throw 'Integration test build failed' }
|
||||
& .\build\KSwitcherIntegration.exe
|
||||
if ($LASTEXITCODE) { throw 'Integration tests failed' }
|
||||
}
|
||||
if ($Ocr) {
|
||||
& $compiler @common tests/ocr.cpp build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherOcrTests.exe
|
||||
$ocrTest = Join-Path (Split-Path $executablePath) 'KSwitcherOcrTests.exe'
|
||||
& $compiler @common tests/ocr.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o $ocrTest
|
||||
if ($LASTEXITCODE) { throw 'OCR test build failed' }
|
||||
& .\build\KSwitcherOcrTests.exe
|
||||
& $ocrTest
|
||||
if ($LASTEXITCODE) { throw 'OCR tests failed' }
|
||||
}
|
||||
foreach ($folder in @('build/dictionaries','build/release/dictionaries','build/staged/dictionaries')) {
|
||||
|
||||
+16
-2
@@ -9,9 +9,14 @@ Copy-Item -LiteralPath (Join-Path $root 'build\release\KSwitcher.Screenshot.exe'
|
||||
Copy-Item -LiteralPath (Join-Path $root 'LICENSE') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'LAN-PREVIEW.md') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'dictionaries') -Destination $destination -Recurse -Force
|
||||
New-Item -ItemType Directory -Force (Join-Path $destination 'tools') | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') -Destination (Join-Path $destination 'tools\README.txt') -Force
|
||||
Copy-Item -LiteralPath (Join-Path $root 'build\release\tools\StayHere.exe') -Destination (Join-Path $destination 'tools\StayHere.exe') -Force
|
||||
Copy-Item -LiteralPath (Join-Path $root 'utilities\StayHere\README.md') -Destination (Join-Path $destination 'tools\StayHere-README.md') -Force
|
||||
# Enumerate the distributable files explicitly; do not include a user's data directory.
|
||||
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','LICENSE','json-LICENSE.txt','README.md','dictionaries') | ForEach-Object { Join-Path $destination $_ }
|
||||
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','LICENSE','json-LICENSE.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ }
|
||||
$entries = foreach ($path in $files) {
|
||||
foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) {
|
||||
@{path=$file.FullName.Substring($destination.Length+1).Replace('\','/'); size=$file.Length; sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||
@@ -22,7 +27,16 @@ $manifest=Join-Path $destination 'release-files.json'
|
||||
@{schema=1; version=$version; files=@($entries)} | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $manifest -Encoding utf8
|
||||
$files += $manifest
|
||||
$archive = Join-Path $root 'dist\KSwitcher-win-x64.zip'
|
||||
Compress-Archive -LiteralPath $files -DestinationPath $archive -Force
|
||||
# Archive only manifest-listed files, preserving relative paths. Never sweep up
|
||||
# personal utilities or leftover developer files from the staging directory.
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
$stream = [IO.File]::Open($archive,[IO.FileMode]::Create)
|
||||
$zip = [IO.Compression.ZipArchive]::new($stream,[IO.Compression.ZipArchiveMode]::Create)
|
||||
try {
|
||||
foreach ($name in @($entries | ForEach-Object { $_.path }) + @('release-files.json')) {
|
||||
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,(Join-Path $destination $name),$name,[IO.Compression.CompressionLevel]::Optimal) | Out-Null
|
||||
}
|
||||
} finally { $zip.Dispose(); $stream.Dispose() }
|
||||
Get-FileHash -LiteralPath $archive -Algorithm SHA256
|
||||
if ($PublishRelease) {
|
||||
$release = Join-Path $root 'Release'
|
||||
|
||||
+3
-3
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
201 RCDATA "update.ps1"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 0,6,29,0
|
||||
PRODUCTVERSION 0,6,29,0
|
||||
FILEVERSION 0,6,57,0
|
||||
PRODUCTVERSION 0,6,57,0
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
BEGIN
|
||||
@@ -20,7 +20,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
||||
VALUE "ProductName", "KSwitcher"
|
||||
VALUE "FileVersion", "0.6.29"
|
||||
VALUE "FileVersion", "0.6.57"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
KSwitcher portable utilities
|
||||
|
||||
Put your trusted portable .exe utilities directly in this tools folder,
|
||||
beside this README.txt. Right-click the KSwitcher tray icon and open Tools.
|
||||
For example: tools/StayHere.exe appears as Tools > StayHere.
|
||||
|
||||
The list refreshes each time the tray menu opens. Subfolders and shortcuts
|
||||
are not listed. Utilities start only when you choose them, with this folder
|
||||
as their working directory. Closing KSwitcher does not close a utility.
|
||||
|
||||
StayHere.exe is bundled. Choose Tools > StayHere to start it; it starts
|
||||
enabled, prevents automatic sleep, and sends F15 after 3 minutes of inactivity.
|
||||
Left-click its tray icon to pause/resume; right-click for Exit. See StayHere-README.md.
|
||||
It does not start automatically with KSwitcher or bypass Windows locking.
|
||||
|
||||
Add other utilities separately. Updates preserve your own files in this folder;
|
||||
bundled StayHere.exe and documentation may be refreshed. Utilities are not
|
||||
transferred by settings synchronization.
|
||||
+626
-55
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,8 @@
|
||||
#include "storage.h"
|
||||
#include "update.h"
|
||||
#include "sync.h"
|
||||
#include "chat_context.h"
|
||||
#include "lan.h"
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
@@ -33,6 +35,12 @@ class App
|
||||
{
|
||||
public:
|
||||
HWND window{}, historyWindow{}, settingsWindow{}, snippetsWindow{};
|
||||
HWND historyService{}; // Non-null only in the short-lived history UI process.
|
||||
bool isolateHistory{};
|
||||
unsigned historyEntryWindows{};
|
||||
std::wstring historySelection, historyTop, historyQuery;
|
||||
bool historyPinnedOnly{};
|
||||
std::vector<std::string> historyComputers;
|
||||
HINSTANCE instance{};
|
||||
std::filesystem::path data;
|
||||
std::vector<Layout> layouts;
|
||||
@@ -41,7 +49,7 @@ class App
|
||||
AutoCorrector autoCorrector;
|
||||
AutoCorrector autoPredictor; // Preloaded, hook-thread-only lookup; no file access while typing.
|
||||
std::atomic<bool> busy{false}, suspended{false};
|
||||
std::atomic<DWORD> ownSequence{0};
|
||||
std::atomic<DWORD> ownSequence{0}, lanSequence{0};
|
||||
std::atomic<uint64_t> inputVersion{0};
|
||||
std::atomic<ULONGLONG> pauseUntil{0};
|
||||
HWND pasteTarget{};
|
||||
@@ -55,7 +63,7 @@ class App
|
||||
bool smoke{};
|
||||
int startCommand{};
|
||||
std::wstring updateStartupEvent;
|
||||
App(HINSTANCE, bool = false, const std::filesystem::path &dataRoot = {});
|
||||
App(HINSTANCE, bool = false, const std::filesystem::path &dataRoot = {}, HWND historyService = nullptr);
|
||||
~App();
|
||||
int execute();
|
||||
void dispatch(int);
|
||||
@@ -63,6 +71,8 @@ class App
|
||||
void pasteEntry(std::wstring, bool plain);
|
||||
void recognizeEntry(std::wstring);
|
||||
void captureHistory();
|
||||
void publishClipboard(Clip, const std::wstring &);
|
||||
void receiveClipboard();
|
||||
void enqueue(std::function<void()>);
|
||||
void enqueueHistorySearch(std::function<void()>);
|
||||
void report(const std::wstring &);
|
||||
@@ -72,25 +82,36 @@ class App
|
||||
void applySettings(const Settings &);
|
||||
void reloadLayouts();
|
||||
void clearHistory();
|
||||
void openHistoryProcess();
|
||||
void refreshHistoryProcess();
|
||||
void remoteHistory(const char *action, const std::wstring &id = {}, bool plain = false);
|
||||
LRESULT historyRequest(HWND, const COPYDATASTRUCT &);
|
||||
void saveHistoryView(const std::wstring &, const std::wstring &, const std::wstring &, bool);
|
||||
void clearLog(bool previous);
|
||||
void setHotkeyCapture(HWND);
|
||||
bool isHotkey(DWORD, UINT);
|
||||
void keyboard(const KBDLLHOOKSTRUCT &, UINT modifiers);
|
||||
bool handleKeyboard(const KBDLLHOOKSTRUCT &, bool down, UINT modifiers);
|
||||
void resetInput();
|
||||
void resetLanInput();
|
||||
void checkUpdate(bool interactive, bool install = false, const std::wstring &version = {});
|
||||
std::wstring syncCommand(int action = 0, const std::vector<SyncChoice> &choices = {});
|
||||
Bytes syncConflictData();
|
||||
Bytes lanCommand(const Bytes &);
|
||||
void pollSync();
|
||||
static App *current;
|
||||
|
||||
private:
|
||||
friend struct InputRegressionAccess;
|
||||
void releaseIdleMemory(ULONGLONG now);
|
||||
HHOOK keyboardHook{}, mouseHook{};
|
||||
std::unique_ptr<LanService> lanService;
|
||||
HANDLE historyProcess{};
|
||||
std::mutex jobsMutex;
|
||||
std::condition_variable jobsReady;
|
||||
std::deque<std::function<void()>> jobs;
|
||||
std::thread worker;
|
||||
HANDLE notificationRegistration{};
|
||||
std::thread historySearchWorker;
|
||||
std::condition_variable historySearchReady;
|
||||
std::function<void()> pendingHistorySearch;
|
||||
@@ -121,6 +142,11 @@ class App
|
||||
int previousAttemptCommand{}, repeatAttempts{};
|
||||
std::vector<std::pair<int, Hotkey>> hookBindings;
|
||||
HotkeyHook hotkeyHook;
|
||||
ChatSwitchHook chatSwitchHook;
|
||||
HWND chatWindow{};
|
||||
std::wstring activeChat, activeChatTitle;
|
||||
void refreshChatContext();
|
||||
void switchChatLayout(bool reverse);
|
||||
HWND typingTarget{};
|
||||
bool autoPending{};
|
||||
int snippetPending = -1;
|
||||
@@ -130,6 +156,7 @@ class App
|
||||
void replayTyping();
|
||||
static LRESULT CALLBACK windowProc(HWND, UINT, WPARAM, LPARAM);
|
||||
static LRESULT CALLBACK keyProc(int, WPARAM, LPARAM);
|
||||
static LRESULT keyboardAfterHooks(int, WPARAM, LPARAM, LRESULT);
|
||||
static LRESULT CALLBACK mouseProc(int, WPARAM, LPARAM);
|
||||
};
|
||||
void showHistory(App &, bool visible = true);
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
// History UI has no clipboard listener or hooks. The resident remains the only writer.
|
||||
namespace {
|
||||
constexpr ULONG_PTR HistoryRequest = 0x4b530200;
|
||||
constexpr UINT HistoryHostShow = WM_APP + 71, HistoryHostRefresh = WM_APP + 72;
|
||||
constexpr wchar_t HistoryHostClass[] = L"KSwitcher.HistoryHost";
|
||||
using HistoryJson = nlohmann::json;
|
||||
HWND historyController(HANDLE process)
|
||||
{
|
||||
if (!process || WaitForSingleObject(process, 0) == WAIT_OBJECT_0) return nullptr;
|
||||
auto window = FindWindowW(HistoryHostClass, nullptr);
|
||||
DWORD pid{}; GetWindowThreadProcessId(window, &pid);
|
||||
return pid == GetProcessId(process) ? window : nullptr;
|
||||
}
|
||||
}
|
||||
void App::openHistoryProcess()
|
||||
{
|
||||
auto foreground = GetForegroundWindow();
|
||||
if (foreground != window && foreground != historyWindow) pasteTarget = foreground;
|
||||
if (historyProcess && WaitForSingleObject(historyProcess, 0) == WAIT_OBJECT_0) {
|
||||
CloseHandle(historyProcess); historyProcess = nullptr; historyWindow = nullptr;
|
||||
}
|
||||
if (historyProcess) {
|
||||
if (auto host = historyController(historyProcess)) {
|
||||
AllowSetForegroundWindow(GetProcessId(historyProcess));
|
||||
PostMessageW(host, HistoryHostShow, 0, 0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
auto path = executable();
|
||||
auto command = L"\"" + path + L"\" --history-host=" + std::to_wstring(reinterpret_cast<uintptr_t>(window));
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
|
||||
PROCESS_INFORMATION child{};
|
||||
if (!CreateProcessW(path.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
|
||||
nullptr, std::filesystem::path(path).parent_path().c_str(), &startup, &child))
|
||||
throw std::runtime_error("Cannot start clipboard history window");
|
||||
CloseHandle(child.hThread);
|
||||
historyProcess = child.hProcess;
|
||||
AllowSetForegroundWindow(child.dwProcessId);
|
||||
}
|
||||
void App::refreshHistoryProcess()
|
||||
{
|
||||
if (auto host = historyController(historyProcess)) PostMessageW(host, HistoryHostRefresh, 0, 0);
|
||||
}
|
||||
void App::remoteHistory(const char *action, const std::wstring &id, bool plain)
|
||||
{
|
||||
if (!historyService || !configurationPeer(historyService, L"KSwitcher.exe"))
|
||||
throw std::runtime_error("KSwitcher has stopped. Reopen clipboard history.");
|
||||
auto text = HistoryJson{{"action", action}, {"id", utf8(id)}, {"plain", plain}}.dump();
|
||||
if (std::string_view(action) == "paste") {
|
||||
DWORD residentPid{}; GetWindowThreadProcessId(historyService, &residentPid);
|
||||
AllowSetForegroundWindow(residentPid);
|
||||
}
|
||||
COPYDATASTRUCT message{HistoryRequest, DWORD(text.size()), text.data()};
|
||||
DWORD_PTR result{};
|
||||
if (!SendMessageTimeoutW(historyService, WM_COPYDATA, reinterpret_cast<WPARAM>(window),
|
||||
reinterpret_cast<LPARAM>(&message), SMTO_ABORTIFHUNG | SMTO_ERRORONEXIT,
|
||||
15000, &result) || result != 1)
|
||||
throw std::runtime_error("KSwitcher could not complete the history request. Reopen history and retry.");
|
||||
}
|
||||
LRESULT App::historyRequest(HWND sender, const COPYDATASTRUCT &message)
|
||||
{
|
||||
DWORD pid{}; GetWindowThreadProcessId(sender, &pid);
|
||||
if (!historyProcess || pid != GetProcessId(historyProcess) ||
|
||||
!configurationPeer(sender, L"KSwitcher.exe") || message.cbData > 4096 ||
|
||||
!message.cbData || !message.lpData || installingUpdate) return FALSE;
|
||||
try {
|
||||
const auto *first = static_cast<const char *>(message.lpData);
|
||||
auto job = HistoryJson::parse(first, first + message.cbData);
|
||||
auto action = job.at("action").get<std::string>();
|
||||
auto id = wide(job.at("id").get<std::string>());
|
||||
if (id.size() > 128) return FALSE;
|
||||
if (action == "ready") {
|
||||
auto ui = reinterpret_cast<HWND>(uintptr_t(std::stoull(id)));
|
||||
DWORD uiPid{}; GetWindowThreadProcessId(ui, &uiPid);
|
||||
wchar_t name[64]{}; GetClassNameW(ui, name, 64);
|
||||
if (uiPid != pid || std::wstring(name) != L"KSwitcher.History") return FALSE;
|
||||
historyWindow = ui;
|
||||
} else if (action == "paste") {
|
||||
if (busy || !history) return FALSE;
|
||||
pasteEntry(id, job.at("plain").get<bool>());
|
||||
} else if (action == "ocr") {
|
||||
if (busy || !history) return FALSE;
|
||||
recognizeEntry(id);
|
||||
} else if (action == "clear") clearHistory();
|
||||
else if (action == "pin" || action == "remove") {
|
||||
if (busy || !history) return FALSE;
|
||||
if (action == "pin") history->pin(id); else history->remove(id);
|
||||
} else return FALSE;
|
||||
return TRUE;
|
||||
} catch (...) { return FALSE; }
|
||||
}
|
||||
void App::saveHistoryView(const std::wstring &selection, const std::wstring &top, const std::wstring &query, bool pinnedOnly)
|
||||
{
|
||||
if (!historyService) return;
|
||||
try {
|
||||
auto text = HistoryJson{{"selection", utf8(selection)}, {"top", utf8(top)}, {"query", utf8(query)}, {"pinnedOnly", pinnedOnly}, {"computers", historyComputers}}.dump();
|
||||
atomicWrite(data / L"history-view.bin", protect(Bytes(text.begin(), text.end())));
|
||||
} catch (...) {} // Closing the UI must still release its process if state cannot be saved.
|
||||
}
|
||||
+14
-11
@@ -46,7 +46,7 @@ std::wstring App::syncCommand(int action, const std::vector<SyncChoice> &choices
|
||||
syncDone.store(true);
|
||||
});
|
||||
}
|
||||
catch (...) { syncRunning = false; throw; }
|
||||
catch (...) { syncRunning = false; Bytes().swap(syncSnapshot); syncResult = {}; throw; }
|
||||
return syncStatus;
|
||||
}
|
||||
void App::pollSync()
|
||||
@@ -57,25 +57,28 @@ void App::pollSync()
|
||||
{
|
||||
if (busy) return;
|
||||
syncWorker.join();
|
||||
// Own completed payloads locally so every return/exception releases them.
|
||||
auto result = std::exchange(syncResult, SyncResult{});
|
||||
auto snapshot = std::exchange(syncSnapshot, Bytes{});
|
||||
syncRunning = false;
|
||||
syncDone = false;
|
||||
syncStatus = syncResult.status;
|
||||
if (syncResult.success)
|
||||
syncStatus = result.status;
|
||||
if (result.success)
|
||||
{
|
||||
if (loadSyncConfig(data) != syncConnection || encodeSettings(settings) != syncSnapshot)
|
||||
if (loadSyncConfig(data) != syncConnection || encodeSettings(settings) != snapshot)
|
||||
{
|
||||
syncStatus = L"Local settings or connection changed during sync. Checking again shortly.";
|
||||
nextSync = GetTickCount64() + 2000;
|
||||
return;
|
||||
}
|
||||
auto next = restoreSyncSettings(syncResult.settings, settings, layouts, syncConnection.keepLocalLayouts);
|
||||
if (encodeSettings(next) != syncSnapshot)
|
||||
auto next = restoreSyncSettings(result.settings, settings, layouts, syncConnection.keepLocalLayouts);
|
||||
if (encodeSettings(next) != snapshot)
|
||||
{
|
||||
atomicWrite(data / L"settings-before-sync.bin", protect(syncSnapshot));
|
||||
atomicWrite(data / L"settings-before-sync.bin", protect(snapshot));
|
||||
applySettings(next);
|
||||
}
|
||||
saveSyncBase(data, syncConnection, syncResult.base.empty() ? syncResult.settings : syncResult.base);
|
||||
pendingSyncConflicts = syncResult.conflicts;
|
||||
saveSyncBase(data, syncConnection, result.base.empty() ? result.settings : result.base);
|
||||
pendingSyncConflicts = std::move(result.conflicts);
|
||||
conflictConnection = syncConnection;
|
||||
SYSTEMTIME time{}; GetLocalTime(&time);
|
||||
wchar_t stamp[32]{};
|
||||
@@ -84,8 +87,8 @@ void App::pollSync()
|
||||
}
|
||||
// Back off after errors (including bad credentials) instead of repeatedly
|
||||
// hitting userpass lockout. The explicit Sync button remains available.
|
||||
syncRetryAfter = syncResult.success ? 0 : GetTickCount64() + 15 * 60000;
|
||||
nextSync = syncResult.success ? GetTickCount64() + SyncIntervalMs : syncRetryAfter;
|
||||
syncRetryAfter = result.success ? 0 : GetTickCount64() + 15 * 60000;
|
||||
nextSync = result.success ? GetTickCount64() + SyncIntervalMs : syncRetryAfter;
|
||||
}
|
||||
if (!syncRunning && GetTickCount64() >= nextSync)
|
||||
{
|
||||
|
||||
+123
-45
@@ -42,82 +42,160 @@ bool safeAutoWord(const std::wstring &word, int minimumLength)
|
||||
auto small = lower(word);
|
||||
return word == small || (word.substr(1) == small.substr(1) && word != upper(word));
|
||||
}
|
||||
std::string_view AutoCorrector::Dictionary::word(size_t index) const
|
||||
namespace {
|
||||
constexpr size_t DictionaryBlockWords = 32;
|
||||
}
|
||||
std::string_view AutoCorrector::Dictionary::word(size_t block) const
|
||||
{
|
||||
auto start = offsets[index];
|
||||
auto end = bytes.find('\t', start);
|
||||
return std::string_view(bytes).substr(start, end - start);
|
||||
size_t start = offsets[block];
|
||||
// Every block starts with a complete word (zero shared prefix).
|
||||
size_t length = static_cast<unsigned char>(bytes[start++]) & 15;
|
||||
if (length == 15) length = static_cast<unsigned char>(bytes[start++]);
|
||||
return std::string_view(bytes).substr(start, length);
|
||||
}
|
||||
AutoCorrector::Dictionary::Dictionary(const std::filesystem::path &path)
|
||||
{
|
||||
auto raw = readFile(path, 2 * 1024 * 1024);
|
||||
bytes.assign(raw.begin(), raw.end());
|
||||
for (size_t start = 0; start < bytes.size();)
|
||||
const auto raw = readFile(path, 2 * 1024 * 1024);
|
||||
const std::string_view source(reinterpret_cast<const char *>(raw.data()), raw.size());
|
||||
std::vector<uint32_t> lines;
|
||||
lines.reserve(std::count(source.begin(), source.end(), '\n') + 1);
|
||||
for (size_t start = 0; start < source.size();)
|
||||
{
|
||||
auto end = bytes.find('\n', start);
|
||||
if (end == bytes.npos)
|
||||
end = bytes.size();
|
||||
auto tab = bytes.find('\t', start);
|
||||
if (tab == bytes.npos || tab >= end || tab == start || tab - start > 160)
|
||||
auto end = source.find('\n', start);
|
||||
if (end == source.npos) end = source.size();
|
||||
auto tab = source.find('\t', start);
|
||||
if (tab == source.npos || tab >= end || tab == start || tab - start > 160)
|
||||
throw std::runtime_error("Invalid auto-correction dictionary");
|
||||
int rank{};
|
||||
auto rankEnd = end > tab + 1 && bytes[end - 1] == '\r' ? end - 1 : end;
|
||||
auto parse = std::from_chars(bytes.data() + tab + 1, bytes.data() + rankEnd, rank);
|
||||
if (parse.ec != std::errc() || parse.ptr != bytes.data() + rankEnd || rank <= 0)
|
||||
auto rankEnd = end > tab + 1 && source[end - 1] == '\r' ? end - 1 : end;
|
||||
auto parse = std::from_chars(source.data() + tab + 1, source.data() + rankEnd, rank);
|
||||
if (parse.ec != std::errc() || parse.ptr != source.data() + rankEnd || rank <= 0)
|
||||
throw std::runtime_error("Invalid dictionary rank");
|
||||
offsets.push_back((uint32_t)start);
|
||||
lines.push_back(static_cast<uint32_t>(start));
|
||||
start = end + 1;
|
||||
}
|
||||
if (offsets.empty())
|
||||
throw std::runtime_error("Empty auto-correction dictionary");
|
||||
auto entry = [&](uint32_t offset) { return std::string_view(bytes).substr(offset, bytes.find('\t', offset) - offset); };
|
||||
auto frequency = [&](uint32_t offset)
|
||||
{
|
||||
if (lines.empty()) throw std::runtime_error("Empty auto-correction dictionary");
|
||||
auto entry = [&](uint32_t offset) { return source.substr(offset, source.find('\t', offset) - offset); };
|
||||
auto frequency = [&](uint32_t offset) {
|
||||
int rank{};
|
||||
auto start = offset + entry(offset).size() + 1;
|
||||
std::from_chars(bytes.data() + start, bytes.data() + bytes.size(), rank);
|
||||
std::from_chars(source.data() + start, source.data() + source.size(), rank);
|
||||
return rank;
|
||||
};
|
||||
std::sort(offsets.begin(), offsets.end(), [&](uint32_t a, uint32_t b)
|
||||
{ return entry(a) == entry(b) ? frequency(a) < frequency(b) : entry(a) < entry(b); });
|
||||
offsets.erase(std::unique(offsets.begin(), offsets.end(), [&](uint32_t a, uint32_t b)
|
||||
{ return entry(a) == entry(b); }), offsets.end());
|
||||
offsets.shrink_to_fit();
|
||||
bytes.shrink_to_fit();
|
||||
std::sort(lines.begin(), lines.end(), [&](uint32_t a, uint32_t b) {
|
||||
return entry(a) == entry(b) ? frequency(a) < frequency(b) : entry(a) < entry(b);
|
||||
});
|
||||
lines.erase(std::unique(lines.begin(), lines.end(), [&](uint32_t a, uint32_t b) {
|
||||
return entry(a) == entry(b);
|
||||
}), lines.end());
|
||||
offsets.reserve((lines.size() + DictionaryBlockWords - 1) / DictionaryBlockWords);
|
||||
std::string_view previous;
|
||||
// Allocate the packed payload exactly once. Geometric growth and a final
|
||||
// shrink otherwise leave discarded buffers in the resident process heap.
|
||||
size_t packedSize = 0;
|
||||
for (size_t i = 0; i < lines.size(); ++i)
|
||||
{
|
||||
auto current = entry(lines[i]);
|
||||
size_t prefix = 0;
|
||||
if (i % DictionaryBlockWords != 0)
|
||||
while (prefix < std::min(previous.size(), current.size()) && previous[prefix] == current[prefix]) ++prefix;
|
||||
auto suffix = current.size() - prefix;
|
||||
packedSize += 1 + (prefix >= 15) + (suffix >= 15) + suffix + 2;
|
||||
auto rank = static_cast<uint32_t>(frequency(lines[i]));
|
||||
if (rank >= 65535)
|
||||
do { ++packedSize; rank >>= 7; } while (rank);
|
||||
previous = current;
|
||||
}
|
||||
bytes.reserve(packedSize);
|
||||
previous = {};
|
||||
for (size_t i = 0; i < lines.size(); ++i)
|
||||
{
|
||||
auto current = entry(lines[i]);
|
||||
size_t prefix = 0;
|
||||
if (i % DictionaryBlockWords == 0)
|
||||
offsets.push_back(static_cast<uint32_t>(bytes.size()));
|
||||
else
|
||||
while (prefix < std::min(previous.size(), current.size()) && previous[prefix] == current[prefix]) ++prefix;
|
||||
size_t suffix = current.size() - prefix;
|
||||
bytes.push_back(static_cast<char>((std::min(prefix, size_t(15)) << 4) | std::min(suffix, size_t(15))));
|
||||
if (prefix >= 15) bytes.push_back(static_cast<char>(prefix));
|
||||
if (suffix >= 15) bytes.push_back(static_cast<char>(suffix));
|
||||
bytes.append(current.substr(prefix));
|
||||
auto rank = static_cast<uint32_t>(frequency(lines[i]));
|
||||
auto shortRank = std::min(rank, uint32_t(65535));
|
||||
bytes.push_back(static_cast<char>(shortRank & 255));
|
||||
bytes.push_back(static_cast<char>(shortRank >> 8));
|
||||
if (rank >= 65535)
|
||||
do {
|
||||
auto next = rank & 127;
|
||||
rank >>= 7;
|
||||
bytes.push_back(static_cast<char>(next | (rank ? 128 : 0)));
|
||||
} while (rank);
|
||||
previous = current;
|
||||
}
|
||||
}
|
||||
int AutoCorrector::Dictionary::rank(const std::wstring &text) const
|
||||
{
|
||||
auto key = utf8(lower(text));
|
||||
size_t begin = 0, end = offsets.size();
|
||||
// Find the last block whose first word is <= the search key.
|
||||
while (begin < end)
|
||||
{
|
||||
auto mid = begin + (end - begin) / 2;
|
||||
if (word(mid) < key)
|
||||
begin = mid + 1;
|
||||
else
|
||||
end = mid;
|
||||
if (word(mid) <= key) begin = mid + 1;
|
||||
else end = mid;
|
||||
}
|
||||
if (begin == offsets.size() || word(begin) != key)
|
||||
return 0;
|
||||
auto start = offsets[begin] + word(begin).size() + 1;
|
||||
int rank{};
|
||||
std::from_chars(bytes.data() + start, bytes.data() + bytes.size(), rank);
|
||||
return rank;
|
||||
if (!begin) return 0;
|
||||
size_t block = begin - 1;
|
||||
size_t at = offsets[block];
|
||||
const size_t limit = begin < offsets.size() ? offsets[begin] : bytes.size();
|
||||
char decoded[160]; // The loader validates lengths; lookup never allocates a decoded word.
|
||||
while (at < limit)
|
||||
{
|
||||
auto lengths = static_cast<unsigned char>(bytes[at++]);
|
||||
size_t prefix = lengths >> 4, suffix = lengths & 15;
|
||||
if (prefix == 15) prefix = static_cast<unsigned char>(bytes[at++]);
|
||||
if (suffix == 15) suffix = static_cast<unsigned char>(bytes[at++]);
|
||||
memcpy(decoded + prefix, bytes.data() + at, suffix);
|
||||
at += suffix;
|
||||
uint32_t rank = static_cast<unsigned char>(bytes[at]) |
|
||||
(uint32_t(static_cast<unsigned char>(bytes[at + 1])) << 8);
|
||||
at += 2;
|
||||
if (rank == 65535) {
|
||||
rank = 0;
|
||||
uint32_t shift = 0;
|
||||
unsigned char part;
|
||||
do {
|
||||
part = static_cast<unsigned char>(bytes[at++]);
|
||||
rank |= uint32_t(part & 127) << shift;
|
||||
shift += 7;
|
||||
} while (part & 128);
|
||||
}
|
||||
auto compared = std::string_view(decoded, size_t(prefix) + suffix).compare(key);
|
||||
if (compared == 0) return static_cast<int>(rank);
|
||||
if (compared > 0) return 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
void AutoCorrector::configure(const std::filesystem::path &folder, const std::vector<std::wstring> &wanted)
|
||||
{
|
||||
if (languages == wanted)
|
||||
return;
|
||||
std::map<std::wstring, Dictionary> next;
|
||||
std::map<std::wstring, std::shared_ptr<const Dictionary>> next;
|
||||
for (auto &lang : wanted)
|
||||
{
|
||||
if (lang != L"en" && lang != L"uk" && lang != L"ru")
|
||||
throw std::runtime_error("Unsupported dictionary language");
|
||||
next.emplace(lang, Dictionary(folder / (lang + L".txt")));
|
||||
next.emplace(lang, std::make_shared<const Dictionary>(folder / (lang + L".txt")));
|
||||
}
|
||||
dictionaries = std::move(next);
|
||||
languages = wanted;
|
||||
}
|
||||
void AutoCorrector::shareDictionaries(const AutoCorrector &source)
|
||||
{
|
||||
dictionaries = source.dictionaries;
|
||||
languages = source.languages;
|
||||
}
|
||||
void AutoCorrector::reject(std::wstring word, const Settings &settings)
|
||||
{
|
||||
while (!word.empty() && openingDelimiter(word.front(), settings))
|
||||
@@ -132,7 +210,7 @@ size_t AutoCorrector::memoryBytes() const
|
||||
{
|
||||
size_t bytes = 0;
|
||||
for (auto &[language, d] : dictionaries)
|
||||
bytes += d.bytes.capacity() + d.offsets.capacity() * sizeof(uint32_t);
|
||||
bytes += d->bytes.capacity() + d->offsets.capacity() * sizeof(uint32_t);
|
||||
return bytes;
|
||||
}
|
||||
std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed, int source,
|
||||
@@ -179,7 +257,7 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
||||
{
|
||||
auto replacement = settings.autoReplacements.find(small);
|
||||
if (replacement != settings.autoReplacements.end() &&
|
||||
replacement->second.find_first_not_of(alphabet) == small.npos)
|
||||
replacement->second.find_first_not_of(alphabet + L" ") == small.npos)
|
||||
return sameLayout(replacement->second);
|
||||
}
|
||||
auto personal = [&](const std::wstring &language, const std::wstring &candidate)
|
||||
@@ -191,7 +269,7 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
||||
};
|
||||
// Valid words from either selected language are never changed.
|
||||
for (auto &[language, d] : dictionaries)
|
||||
if (d.rank(word) || personal(language, word))
|
||||
if (d->rank(word) || personal(language, word))
|
||||
return {};
|
||||
std::optional<AutoSuggestion> candidate;
|
||||
std::optional<std::wstring> matchedText;
|
||||
@@ -211,7 +289,7 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
||||
auto converted = convert(word, layouts[source], layouts[i], true);
|
||||
if (converted == word || !safeAutoWord(converted, settings.autoMinLength))
|
||||
continue;
|
||||
int rank = personal(dictionary->first, converted) ? 1 : dictionary->second.rank(converted);
|
||||
int rank = personal(dictionary->first, converted) ? 1 : dictionary->second->rank(converted);
|
||||
if (!rank)
|
||||
continue;
|
||||
if (matchedText && *matchedText != converted)
|
||||
@@ -233,7 +311,7 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
||||
auto consider = [&](const std::wstring &text)
|
||||
{
|
||||
if (text == small || text == found || text.size() < 4 || text.size() > 32) return true;
|
||||
int rank = personalTargets.contains(text) ? 1 : dictionaries.at(sourceLanguage).rank(text);
|
||||
int rank = personalTargets.contains(text) ? 1 : dictionaries.at(sourceLanguage)->rank(text);
|
||||
if (!rank) return true;
|
||||
if (!found.empty()) return false;
|
||||
found = text;
|
||||
|
||||
+9
-1
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
#include "platform.h"
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <string_view>
|
||||
namespace ks
|
||||
@@ -18,23 +19,30 @@ int matchAutoInput(const Run &, const std::wstring &, const std::vector<Layout>
|
||||
bool autoCorrectionAllowed(HWND, const Settings &);
|
||||
class AutoCorrector
|
||||
{
|
||||
friend struct AutoCorrectorRegressionAccess;
|
||||
struct Dictionary
|
||||
{
|
||||
// Front-coded UTF-8 words in independently searchable blocks of 32.
|
||||
// Prefix/suffix lengths share a byte (15 escapes to a full byte length).
|
||||
// Ranks use two bytes; 65535 escapes to a varint for larger custom ranks.
|
||||
std::string bytes;
|
||||
std::vector<uint32_t> offsets;
|
||||
std::string_view word(size_t) const;
|
||||
explicit Dictionary(const std::filesystem::path &);
|
||||
int rank(const std::wstring &) const;
|
||||
};
|
||||
std::map<std::wstring, Dictionary> dictionaries;
|
||||
std::map<std::wstring, std::shared_ptr<const Dictionary>> dictionaries;
|
||||
std::vector<std::wstring> languages;
|
||||
std::set<std::wstring> rejected;
|
||||
|
||||
public:
|
||||
void configure(const std::filesystem::path &, const std::vector<std::wstring> &);
|
||||
// Share immutable dictionary storage, keeping each consumer's undo rejections private.
|
||||
void shareDictionaries(const AutoCorrector &);
|
||||
std::optional<AutoSuggestion> suggest(const std::wstring &, int source, const std::vector<Layout> &,
|
||||
const Settings &) const;
|
||||
void reject(std::wstring word, const Settings & = {});
|
||||
// Referenced dictionary payload, including shared storage (do not sum across consumers).
|
||||
size_t memoryBytes() const;
|
||||
};
|
||||
} // namespace ks
|
||||
@@ -0,0 +1,143 @@
|
||||
// Chrome Telegram Web integration: native accessibility, no OCR or polling timer.
|
||||
#include "chat_context.h"
|
||||
#include <uiautomation.h>
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
namespace ks {
|
||||
namespace {
|
||||
template<class T> struct BrowserCom {
|
||||
T *p{}; ~BrowserCom(){if(p)p->Release();}
|
||||
T** out(){return &p;} T* operator->(){return p;}
|
||||
};
|
||||
std::wstring browserString(IUIAutomationElement* e, PROPERTYID id) {
|
||||
VARIANT v;VariantInit(&v);std::wstring s;
|
||||
if(SUCCEEDED(e->GetCurrentPropertyValue(id,&v)) && v.vt==VT_BSTR && v.bstrVal) s.assign(v.bstrVal,SysStringLen(v.bstrVal));
|
||||
VariantClear(&v);return s;
|
||||
}
|
||||
struct ChromeElements { BrowserCom<IUIAutomationElement> address,document,header; int addresses{},documents{}; };
|
||||
void findChromeElements(IUIAutomationTreeWalker* walker,IUIAutomationElement* e,ChromeElements& found,int depth,int& budget) {
|
||||
if(depth>12 || --budget<0)return;
|
||||
CONTROLTYPEID type{};BOOL offscreen=TRUE;e->get_CurrentControlType(&type);e->get_CurrentIsOffscreen(&offscreen);
|
||||
if(type==UIA_DocumentControlTypeId){
|
||||
if(!offscreen && browserString(e,UIA_AutomationIdPropertyId)==L"RootWebArea"){
|
||||
if(++found.documents==1){e->AddRef();found.document.p=e;}}
|
||||
return; // Never traverse message content.
|
||||
}
|
||||
if(type==UIA_EditControlTypeId && !offscreen && browserString(e,UIA_ClassNamePropertyId)==L"OmniboxViewViews"){
|
||||
if(++found.addresses==1){e->AddRef();found.address.p=e;}}
|
||||
BrowserCom<IUIAutomationElement> child;walker->GetFirstChildElement(e,child.out());
|
||||
while(child.p && budget>0){findChromeElements(walker,child.p,found,depth+1,budget);BrowserCom<IUIAutomationElement> next;walker->GetNextSiblingElement(child.p,next.out());child.p->Release();child.p=next.p;next.p=nullptr;}
|
||||
}
|
||||
IUIAutomationElement* chromeHeader(IUIAutomationTreeWalker* walker,IUIAutomationElement* document) {
|
||||
// Web K's center pane is separate from its chat list and message history.
|
||||
std::function<IUIAutomationElement*(IUIAutomationElement*,int)> center;
|
||||
center=[&](IUIAutomationElement* e,int depth)->IUIAutomationElement* {
|
||||
if(depth>3)return nullptr;
|
||||
if(browserString(e,UIA_AutomationIdPropertyId)==L"column-center"){e->AddRef();return e;}
|
||||
auto id=browserString(e,UIA_AutomationIdPropertyId);if(id==L"column-left"||id==L"column-right")return nullptr;
|
||||
BrowserCom<IUIAutomationElement> c;walker->GetFirstChildElement(e,c.out());int limit=12;
|
||||
while(c.p && --limit>0){if(auto result=center(c.p,depth+1))return result;BrowserCom<IUIAutomationElement> next;walker->GetNextSiblingElement(c.p,next.out());c.p->Release();c.p=next.p;next.p=nullptr;}return nullptr;
|
||||
};
|
||||
BrowserCom<IUIAutomationElement> pane;pane.p=center(document,0);if(!pane.p)return nullptr;
|
||||
BrowserCom<IUIAutomationElement> header;walker->GetFirstChildElement(pane.p,header.out());if(!header.p)return nullptr;
|
||||
BrowserCom<IUIAutomationElement> c;walker->GetFirstChildElement(header.p,c.out());int limit=16,buttons=0;IUIAutomationElement* title{};
|
||||
while(c.p && --limit>0){CONTROLTYPEID type{};c->get_CurrentControlType(&type);if(type==UIA_ButtonControlTypeId)++buttons;
|
||||
if(type==UIA_TextControlTypeId && !title){title=c.p;title->AddRef();}
|
||||
BrowserCom<IUIAutomationElement> next;walker->GetNextSiblingElement(c.p,next.out());c.p->Release();c.p=next.p;next.p=nullptr;}
|
||||
if(buttons<2 && title){title->Release();title=nullptr;}return title;
|
||||
}
|
||||
std::wstring chromeTitleKey(IUIAutomationElement* header){
|
||||
if(!header)return {};
|
||||
auto name=browserString(header,UIA_NamePropertyId);
|
||||
if(name.empty()||name.size()>512||name.find_first_of(L"\r\n")!=name.npos)return {};
|
||||
return L"telegram-web\n"+name;
|
||||
}
|
||||
std::wstring chromeSnapshot(IUIAutomation* uia,HWND window,ChromeElements& found) {
|
||||
if(!IsWindow(window)||IsIconic(window)||lower(processName(window))!=L"chrome")return {};
|
||||
BrowserCom<IUIAutomationElement> root;BrowserCom<IUIAutomationTreeWalker> walker;
|
||||
if(FAILED(uia->ElementFromHandle(window,root.out()))||!root.p||FAILED(uia->get_ControlViewWalker(walker.out())))return {};
|
||||
int budget=250;findChromeElements(walker.p,root.p,found,0,budget);
|
||||
if(found.addresses!=1||found.documents!=1)return {};
|
||||
auto address=telegramWebKey(browserString(found.address.p,UIA_ValueValuePropertyId));
|
||||
auto document=telegramWebKey(browserString(found.document.p,UIA_ValueValuePropertyId));
|
||||
BOOL editing=FALSE;found.address->get_CurrentHasKeyboardFocus(&editing);
|
||||
if(editing || address.empty() || address!=document)return {};
|
||||
found.header.p=chromeHeader(walker.p,found.document.p);
|
||||
return chromeTitleKey(found.header.p);
|
||||
}
|
||||
std::mutex browserMutex;
|
||||
HWND browserWindow{};std::wstring browserKey;
|
||||
std::atomic<DWORD> browserThreadId{};
|
||||
std::atomic<bool> browserPending{}, browserStopping{};
|
||||
std::thread browserThread;
|
||||
void invalidateBrowser(){std::lock_guard lock(browserMutex);browserKey.clear();}
|
||||
void requestBrowser(){invalidateBrowser();auto id=browserThreadId.load();if(id && !browserPending.exchange(true))PostThreadMessageW(id,WM_APP+61,0,0);}
|
||||
void CALLBACK browserForeground(HWINEVENTHOOK,DWORD,HWND,LONG,LONG,DWORD,DWORD){requestBrowser();}
|
||||
class BrowserChanged final: public IUIAutomationPropertyChangedEventHandler {
|
||||
std::atomic<ULONG> refs{1};
|
||||
public:
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void** out) override {if(!out)return E_POINTER;*out=nullptr;if(iid==IID_IUnknown||iid==IID_IUIAutomationPropertyChangedEventHandler){*out=static_cast<IUIAutomationPropertyChangedEventHandler*>(this);AddRef();return S_OK;}return E_NOINTERFACE;}
|
||||
ULONG STDMETHODCALLTYPE AddRef() override{return ++refs;}
|
||||
ULONG STDMETHODCALLTYPE Release() override{auto n=--refs;if(!n)delete this;return n;}
|
||||
HRESULT STDMETHODCALLTYPE HandlePropertyChangedEvent(IUIAutomationElement*,PROPERTYID,VARIANT) override {requestBrowser();return S_OK;}
|
||||
};
|
||||
}
|
||||
std::wstring readChromeChat(HWND window) {
|
||||
auto hr=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
struct Apartment{bool own;~Apartment(){if(own)CoUninitialize();}} apartment{SUCCEEDED(hr)};
|
||||
BrowserCom<IUIAutomation2> uia;
|
||||
if(FAILED(CoCreateInstance(CLSID_CUIAutomation8,nullptr,CLSCTX_INPROC_SERVER,IID_IUIAutomation2,(void**)uia.out())))return {};
|
||||
uia->put_ConnectionTimeout(150);uia->put_TransactionTimeout(150);
|
||||
ChromeElements elements;return chromeSnapshot(uia.p,window,elements);
|
||||
}
|
||||
std::wstring cachedChromeChat(HWND window){std::lock_guard lock(browserMutex);return window==browserWindow?browserKey:L"";}
|
||||
void startBrowserChatMonitor(){
|
||||
if(browserThread.joinable())return;
|
||||
browserStopping=false;
|
||||
browserThread=std::thread([] {
|
||||
CoInitializeEx(nullptr,COINIT_MULTITHREADED);MSG message{};PeekMessageW(&message,nullptr,0,0,PM_NOREMOVE);
|
||||
browserThreadId=GetCurrentThreadId();
|
||||
auto foreground=SetWinEventHook(EVENT_SYSTEM_FOREGROUND,EVENT_SYSTEM_FOREGROUND,nullptr,browserForeground,0,0,WINEVENT_OUTOFCONTEXT);
|
||||
// Focus changes cover tab selection and entering/leaving the address bar.
|
||||
auto focus=SetWinEventHook(EVENT_OBJECT_FOCUS,EVENT_OBJECT_FOCUS,nullptr,browserForeground,0,0,WINEVENT_OUTOFCONTEXT);
|
||||
BrowserCom<IUIAutomation2> uia;CoCreateInstance(CLSID_CUIAutomation8,nullptr,CLSCTX_INPROC_SERVER,IID_IUIAutomation2,(void**)uia.out());
|
||||
BrowserCom<IUIAutomationElement> address,document,header;BrowserCom<BrowserChanged> handler;handler.p=new BrowserChanged;
|
||||
if(uia.p){uia->put_ConnectionTimeout(150);uia->put_TransactionTimeout(150);}
|
||||
requestBrowser();
|
||||
if(browserStopping)PostThreadMessageW(GetCurrentThreadId(),WM_QUIT,0,0);
|
||||
while(GetMessageW(&message,nullptr,0,0)>0){
|
||||
if(message.message!=WM_APP+61){TranslateMessage(&message);DispatchMessageW(&message);continue;}
|
||||
browserPending=false;
|
||||
if(!uia.p)continue;
|
||||
if(address.p){uia->RemovePropertyChangedEventHandler(address.p,handler.p);address.p->Release();address.p=nullptr;}
|
||||
if(document.p){uia->RemovePropertyChangedEventHandler(document.p,handler.p);document.p->Release();document.p=nullptr;}
|
||||
if(header.p){uia->RemovePropertyChangedEventHandler(header.p,handler.p);header.p->Release();header.p=nullptr;}
|
||||
auto window=GetForegroundWindow();ChromeElements elements;auto key=chromeSnapshot(uia.p,window,elements);
|
||||
PROPERTYID properties[]={UIA_ValueValuePropertyId};
|
||||
bool subscribed=elements.address.p && elements.document.p;
|
||||
if(subscribed){address.p=elements.address.p;elements.address.p=nullptr;document.p=elements.document.p;elements.document.p=nullptr;
|
||||
subscribed=SUCCEEDED(uia->AddPropertyChangedEventHandlerNativeArray(address.p,TreeScope_Element,nullptr,handler.p,properties,1));
|
||||
subscribed=SUCCEEDED(uia->AddPropertyChangedEventHandlerNativeArray(document.p,TreeScope_Element,nullptr,handler.p,properties,1)) && subscribed;
|
||||
if(elements.header.p){header.p=elements.header.p;elements.header.p=nullptr;PROPERTYID nameProperty=UIA_NamePropertyId;
|
||||
subscribed=SUCCEEDED(uia->AddPropertyChangedEventHandlerNativeArray(header.p,TreeScope_Element,nullptr,handler.p,&nameProperty,1)) && subscribed;}
|
||||
// Close the read/subscribe race without scanning the content tree.
|
||||
key=telegramWebKey(browserString(address.p,UIA_ValueValuePropertyId));
|
||||
if(key.empty() || key!=telegramWebKey(browserString(document.p,UIA_ValueValuePropertyId)))key.clear();
|
||||
else key=chromeTitleKey(header.p);
|
||||
BOOL editing=FALSE;address->get_CurrentHasKeyboardFocus(&editing);if(editing)key.clear();
|
||||
}
|
||||
std::lock_guard lock(browserMutex);browserWindow=window;browserKey=subscribed && !browserPending && window==GetForegroundWindow()?key:L"";
|
||||
}
|
||||
browserThreadId=0;
|
||||
if(foreground)UnhookWinEvent(foreground);
|
||||
if(focus)UnhookWinEvent(focus);
|
||||
if(uia.p){if(header.p)uia->RemovePropertyChangedEventHandler(header.p,handler.p);if(address.p)uia->RemovePropertyChangedEventHandler(address.p,handler.p);if(document.p)uia->RemovePropertyChangedEventHandler(document.p,handler.p);}
|
||||
invalidateBrowser();
|
||||
// COM objects release before uninitializing the apartment below.
|
||||
if(header.p){header.p->Release();header.p=nullptr;}
|
||||
if(address.p){address.p->Release();address.p=nullptr;}if(document.p){document.p->Release();document.p=nullptr;}
|
||||
if(uia.p){uia.p->Release();uia.p=nullptr;}CoUninitialize();
|
||||
});
|
||||
}
|
||||
void stopBrowserChatMonitor(){browserStopping=true;auto id=browserThreadId.load();if(id)PostThreadMessageW(id,WM_QUIT,0,0);if(browserThread.joinable())browserThread.join();browserPending=false;}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
#pragma once
|
||||
#include "platform.h"
|
||||
#include <algorithm>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline std::wstring telegramWebKey(std::wstring url)
|
||||
{
|
||||
if (url.starts_with(L"https://")) url.erase(0, 8);
|
||||
const std::wstring host = L"web.telegram.org/";
|
||||
if (!url.starts_with(host)) return {};
|
||||
url.erase(0, host.size());
|
||||
if (!(url.starts_with(L"k/#") || url.starts_with(L"a/#"))) return {};
|
||||
auto peer = url.substr(3);
|
||||
if (peer.empty() || peer.size() > 128) return {};
|
||||
if (peer.front() == L'@')
|
||||
{
|
||||
peer = lower(peer);
|
||||
if (peer.size() < 2 || peer.find_first_not_of(L"abcdefghijklmnopqrstuvwxyz0123456789_", 1) != peer.npos) return {};
|
||||
}
|
||||
else
|
||||
{
|
||||
auto first = peer.front() == L'-' ? 1u : 0u;
|
||||
if (first == peer.size() || peer.find_first_not_of(L"0123456789", first) != peer.npos) return {};
|
||||
}
|
||||
return L"telegram-web\n" + peer;
|
||||
}
|
||||
std::wstring readChromeChat(HWND);
|
||||
std::wstring cachedChromeChat(HWND);
|
||||
void startBrowserChatMonitor();
|
||||
void stopBrowserChatMonitor();
|
||||
struct ChatSwitchHook
|
||||
{
|
||||
bool pressed[256]{};
|
||||
static bool candidate(UINT key, UINT mods)
|
||||
{
|
||||
bool shift = key == VK_SHIFT || key == VK_LSHIFT || key == VK_RSHIFT;
|
||||
bool alt = key == VK_MENU || key == VK_LMENU || key == VK_RMENU;
|
||||
return (key == VK_SPACE && (mods == MOD_WIN || mods == (MOD_WIN | MOD_SHIFT))) ||
|
||||
(shift && mods == MOD_ALT) || (alt && mods == MOD_SHIFT);
|
||||
}
|
||||
// 1 forward, 2 backward, -1 consumed repeat/release, 0 ordinary input.
|
||||
int update(UINT key, bool down, UINT mods, bool enabled)
|
||||
{
|
||||
if (key >= 256) return 0;
|
||||
if (pressed[key]) { if (!down) pressed[key] = false; return -1; }
|
||||
if (!down || !enabled) return 0;
|
||||
if (!candidate(key, mods)) return 0;
|
||||
pressed[key] = true;
|
||||
return key == VK_SPACE && (mods & MOD_SHIFT) ? 2 : 1;
|
||||
}
|
||||
};
|
||||
inline std::wstring chatTitle(HWND window)
|
||||
{
|
||||
wchar_t title[1024]{};
|
||||
if (!window) return {};
|
||||
int length = GetWindowTextW(window, title, std::size(title));
|
||||
if (!length || length >= (int)std::size(title) - 1) return {};
|
||||
return title;
|
||||
}
|
||||
inline std::wstring chatKey(std::wstring process, std::wstring title)
|
||||
{
|
||||
process = lower(process);
|
||||
if (process.ends_with(L".exe")) process.resize(process.size() - 4);
|
||||
while (!title.empty() && (title.front() == 0x200e || title.front() == 0x200f)) title.erase(0, 1);
|
||||
if (process == L"telegram")
|
||||
{
|
||||
// Telegram's unread badge is not part of the contact name.
|
||||
auto badge = title.rfind(L" \u2013 (");
|
||||
if (badge != title.npos && title.back() == L')')
|
||||
{
|
||||
auto digits = title.substr(badge + 4, title.size() - badge - 5);
|
||||
if (!digits.empty() && digits.find_first_not_of(L"0123456789") == digits.npos)
|
||||
title.resize(badge);
|
||||
}
|
||||
if (title.empty() || title == L"Telegram" || title.starts_with(L"Telegram (")) return {};
|
||||
}
|
||||
else if (process == L"ms-teams")
|
||||
{
|
||||
// Only the observed chat title format; meetings/search are not chats.
|
||||
const std::wstring prefix = L"Chat | ", suffix = L" | Microsoft Teams";
|
||||
if (!title.starts_with(prefix) || !title.ends_with(suffix) ||
|
||||
title.size() <= prefix.size() + suffix.size()) return {};
|
||||
title = title.substr(prefix.size(), title.size() - prefix.size() - suffix.size());
|
||||
if (title.empty()) return {};
|
||||
}
|
||||
else return {};
|
||||
return process + L"\n" + title;
|
||||
}
|
||||
inline std::wstring windowChatKey(HWND window)
|
||||
{
|
||||
if (window && lower(processName(window)) == L"chrome") return cachedChromeChat(window);
|
||||
return window ? chatKey(processName(window), chatTitle(window)) : L"";
|
||||
}
|
||||
inline std::vector<std::wstring> chatCycle(const Settings &settings, const std::wstring &key,
|
||||
const std::vector<Layout> &layouts)
|
||||
{
|
||||
auto found = settings.chatCycles.find(key);
|
||||
if (key.empty() || found == settings.chatCycles.end()) return settings.cycle;
|
||||
std::vector<std::wstring> result;
|
||||
for (const auto &id : found->second)
|
||||
if (std::any_of(layouts.begin(), layouts.end(), [&](const Layout &l) { return l.id == id; }))
|
||||
result.push_back(id);
|
||||
return result.empty() ? settings.cycle : result;
|
||||
}
|
||||
inline HKL nextChatLayout(const std::vector<std::wstring> &cycle, const std::vector<Layout> &layouts,
|
||||
HKL current, bool reverse)
|
||||
{
|
||||
std::vector<HKL> handles;
|
||||
for (const auto &id : cycle)
|
||||
for (const auto &layout : layouts)
|
||||
if (layout.id == id) handles.push_back(layout.handle);
|
||||
if (handles.empty()) return nullptr;
|
||||
auto found = std::find(handles.begin(), handles.end(), current);
|
||||
if (found == handles.end()) return handles.front();
|
||||
auto next = (size_t(found - handles.begin()) + (reverse ? handles.size() - 1 : 1)) % handles.size();
|
||||
return handles[next];
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -79,7 +79,7 @@ LRESULT CALLBACK controller(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
// The configurator owns no history store, dictionaries, worker or input hooks.
|
||||
// All mutations are validated and committed by the resident process.
|
||||
App::App(HINSTANCE h, bool, const std::filesystem::path &) : instance(h)
|
||||
App::App(HINSTANCE h, bool, const std::filesystem::path &, HWND) : instance(h)
|
||||
{
|
||||
current = this;
|
||||
data = dataDirectory();
|
||||
@@ -102,7 +102,16 @@ void App::applySettings(const Settings &next)
|
||||
memcpy(payload.data(), &length, sizeof(length));
|
||||
payload.insert(payload.end(), before.begin(), before.end());
|
||||
payload.insert(payload.end(), after.begin(), after.end());
|
||||
settings = decodeSettings(request(*this, ConfigSave, payload), layouts);
|
||||
Bytes saved;
|
||||
try {saved=request(*this,ConfigSave,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);
|
||||
}
|
||||
settings=decodeSettings(saved,layouts);
|
||||
}
|
||||
void App::reloadLayouts()
|
||||
{
|
||||
@@ -112,6 +121,7 @@ void App::reloadLayouts()
|
||||
}
|
||||
void App::clearHistory() { request(*this, ConfigClearHistory); }
|
||||
Bytes App::syncConflictData() { return request(*this, ConfigSyncConflicts); }
|
||||
Bytes App::lanCommand(const Bytes &bytes) { return request(*this, ConfigLan, bytes); }
|
||||
std::wstring App::syncCommand(int action, const std::vector<SyncChoice> &choices)
|
||||
{
|
||||
auto result = action == 4 ? request(*this, ConfigSyncResolve, encodeSyncChoices(choices)) :
|
||||
|
||||
+11
-3
@@ -1,4 +1,5 @@
|
||||
#include "configuration.h"
|
||||
#include "settings_merge.h"
|
||||
#include <cstring>
|
||||
namespace ks
|
||||
{
|
||||
@@ -40,6 +41,13 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
||||
{
|
||||
switch (message.dwData)
|
||||
{
|
||||
case ConfigLan:
|
||||
{
|
||||
if (!message.cbData || message.cbData > 4096) throw std::runtime_error("Invalid LAN request.");
|
||||
auto first = static_cast<const unsigned char *>(message.lpData);
|
||||
reply = app.lanCommand(Bytes(first, first + message.cbData));
|
||||
break;
|
||||
}
|
||||
case ConfigSyncConflicts:
|
||||
reply = app.syncConflictData();
|
||||
break;
|
||||
@@ -60,6 +68,7 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
||||
break;
|
||||
}
|
||||
case ConfigSave:
|
||||
case ConfigSaveEdited:
|
||||
{
|
||||
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.");
|
||||
@@ -67,11 +76,10 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
||||
memcpy(&length, message.lpData, sizeof(length));
|
||||
if (length > message.cbData - sizeof(length)) throw std::runtime_error("Invalid settings snapshot.");
|
||||
auto begin = static_cast<const unsigned char *>(message.lpData) + sizeof(length);
|
||||
if (Bytes(begin, begin + length) != encodeSettings(app.settings))
|
||||
throw std::runtime_error("Settings changed in KSwitcher. Close and reopen the configurator before saving.");
|
||||
Bytes next(begin + length, static_cast<const unsigned char *>(message.lpData) + message.cbData);
|
||||
if (next.empty()) throw std::runtime_error("Empty settings request.");
|
||||
app.applySettings(decodeSettings(next, app.layouts));
|
||||
auto merged=mergeConfigurationSettings(Bytes(begin,begin+length),next,encodeSettings(app.settings),message.dwData==ConfigSaveEdited);
|
||||
app.applySettings(decodeSettings(merged, app.layouts));
|
||||
reply = encodeSettings(app.settings);
|
||||
break;
|
||||
}
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ 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, ConfigEnd = ConfigRead + 11;
|
||||
ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigEnd = ConfigRead + 13;
|
||||
inline constexpr size_t ConfigLimit = 8 * 1024 * 1024;
|
||||
bool configurationPeer(HWND, const wchar_t *filename);
|
||||
void launchConfiguration(App &, bool snippets = false, bool logs = false);
|
||||
|
||||
@@ -6,6 +6,21 @@
|
||||
|
||||
namespace ks
|
||||
{
|
||||
std::wstring snippetAppName(std::wstring name)
|
||||
{
|
||||
auto first = name.find_first_not_of(L" \t"), last = name.find_last_not_of(L" \t");
|
||||
if (first == name.npos) return {};
|
||||
name = lower(name.substr(first, last - first + 1));
|
||||
if (name.ends_with(L".exe")) name.resize(name.size() - 4);
|
||||
return name;
|
||||
}
|
||||
int snippetAppPriority(const Snippet &snippet, const std::wstring &process)
|
||||
{
|
||||
if (snippet.apps.empty()) return 1;
|
||||
auto name = snippetAppName(process);
|
||||
for (const auto &app : snippet.apps) if (snippetAppName(app) == name && !name.empty()) return 2;
|
||||
return 0;
|
||||
}
|
||||
int HotkeyHook::update(UINT key, bool down, UINT modifiers,
|
||||
const std::vector<std::pair<int, Hotkey>> &bindings)
|
||||
{
|
||||
|
||||
@@ -32,7 +32,10 @@ struct Snippet
|
||||
{
|
||||
std::wstring trigger, text;
|
||||
std::wstring id;
|
||||
std::vector<std::wstring> apps; // Empty means everywhere; executable names without .exe.
|
||||
};
|
||||
std::wstring snippetAppName(std::wstring);
|
||||
int snippetAppPriority(const Snippet &, const std::wstring &process);
|
||||
std::wstring snippetId(const Snippet &);
|
||||
std::wstring newSnippetId();
|
||||
struct Template
|
||||
@@ -76,6 +79,8 @@ struct Settings
|
||||
translit = L"Ctrl+Alt+Shift+T", undo = L"Ctrl+Alt+Shift+Z", clipboard = L"Win+V",
|
||||
screenshot = L"Win+Shift+S";
|
||||
std::vector<std::wstring> cycle, direct, directIds;
|
||||
// Exact application + visible chat name; an absent entry uses the global cycle.
|
||||
std::map<std::wstring, std::vector<std::wstring>> chatCycles;
|
||||
std::vector<std::wstring> excluded{L"KeePass", L"KeePassXC", L"1Password", L"Bitwarden"};
|
||||
std::vector<Snippet> snippets;
|
||||
std::vector<std::wstring> snippetTombstones;
|
||||
|
||||
+17
-3
@@ -4,14 +4,28 @@
|
||||
#include <string>
|
||||
|
||||
namespace ks {
|
||||
inline constexpr size_t HistoryThumbnailBudget = 1024 * 1024;
|
||||
inline constexpr size_t HistoryRichTextBudget = 256 * 1024;
|
||||
// Keep the visible working set even in unusually tall windows. Never evict a
|
||||
// visible preview to admit another visible preview: that creates a paint loop.
|
||||
template<class T, class Weight>
|
||||
void trimHistoryPreviews(std::map<std::wstring,T> &cache,
|
||||
const std::set<std::wstring> &visible, size_t limit,
|
||||
size_t byteLimit, Weight weight)
|
||||
{
|
||||
size_t bytes = 0;
|
||||
for (const auto &[id, value] : cache) bytes += weight(value);
|
||||
for(auto it=cache.begin(); (cache.size()>limit || bytes>byteLimit) && it!=cache.end();)
|
||||
if(!visible.contains(it->first)) {
|
||||
bytes -= weight(it->second);
|
||||
it=cache.erase(it);
|
||||
}
|
||||
else ++it;
|
||||
}
|
||||
template<class T>
|
||||
void trimHistoryPreviews(std::map<std::wstring,T> &cache,
|
||||
const std::set<std::wstring> &visible, size_t limit=32)
|
||||
{
|
||||
for(auto it=cache.begin(); cache.size()>limit && it!=cache.end();)
|
||||
if(!visible.contains(it->first)) it=cache.erase(it);
|
||||
else ++it;
|
||||
trimHistoryPreviews(cache, visible, limit, 0, [](const T &) { return size_t{}; });
|
||||
}
|
||||
}
|
||||
+401
@@ -0,0 +1,401 @@
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <iphlpapi.h>
|
||||
#include "lan.h"
|
||||
#include "lan_pairing.h"
|
||||
#include "lan_mesh.h"
|
||||
#include "lan_clipboard.h"
|
||||
#include "lan_layout.h"
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <map>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
using lan::Json;
|
||||
namespace
|
||||
{
|
||||
Bytes encoded(const Json &j) { auto s=j.dump(); return Bytes(s.begin(),s.end()); }
|
||||
bool localAddress(ULONG network)
|
||||
{
|
||||
auto ip=ntohl(network);
|
||||
return (ip>>24)==10 || (ip>>20)==0xac1 || (ip>>16)==0xc0a8 || (ip>>16)==0xa9fe;
|
||||
}
|
||||
std::string hostName()
|
||||
{
|
||||
wchar_t name[256]{}; DWORD size=256;
|
||||
return GetComputerNameW(name,&size) ? utf8(std::wstring(name,size)) : "KSwitcher";
|
||||
}
|
||||
std::vector<ULONG> broadcasts()
|
||||
{
|
||||
ULONG size=16384; Bytes data(size);
|
||||
auto flags=GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER;
|
||||
auto result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size);
|
||||
if(result==ERROR_BUFFER_OVERFLOW) { data.resize(size); result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size); }
|
||||
std::vector<ULONG> out;
|
||||
if(result!=NO_ERROR) return out;
|
||||
for(auto a=(IP_ADAPTER_ADDRESSES*)data.data();a;a=a->Next)
|
||||
if(a->OperStatus==IfOperStatusUp)
|
||||
for(auto u=a->FirstUnicastAddress;u;u=u->Next)
|
||||
if(u->Address.lpSockaddr->sa_family==AF_INET && u->OnLinkPrefixLength>0 && u->OnLinkPrefixLength<31)
|
||||
{
|
||||
auto ip=((sockaddr_in*)u->Address.lpSockaddr)->sin_addr.s_addr;
|
||||
if(localAddress(ip)) out.push_back(htonl(ntohl(ip) | (0xffffffffu >> u->OnLinkPrefixLength)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
struct LanService::Impl
|
||||
{
|
||||
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; };
|
||||
std::filesystem::path path;
|
||||
std::string id,epoch=lan::randomHex(16),name=hostName(),status="Disabled.";
|
||||
std::map<std::string,Peer> peers;
|
||||
Json trusted=Json::object(),positions=Json::object();
|
||||
std::unique_ptr<lan::Pairing> pending;
|
||||
std::unique_ptr<lan::ClipboardExchange> clipboard;
|
||||
bool enabled{};
|
||||
std::atomic<bool> stopping{false};
|
||||
std::mutex mutex;
|
||||
std::thread worker;
|
||||
bool shareInput{};
|
||||
std::string inputPeer;
|
||||
int inputEdge=1;
|
||||
std::atomic<bool> inputConnected{false},abortInput{false};
|
||||
std::atomic<uint64_t> inputEpoch{0};
|
||||
std::atomic<uint64_t> inputConfiguration{0};
|
||||
std::atomic<bool> layoutChanged{false};
|
||||
uint64_t observedEpoch{},observedRevision{},observedConfiguration{};
|
||||
std::mutex inputMutex;
|
||||
std::vector<lan::RoutedInput> inputOut,inputIn;
|
||||
std::map<std::string,uint64_t> inputReady;
|
||||
std::unique_ptr<lan::InputMesh> router;
|
||||
std::string inputStatus="Input sharing disabled.";
|
||||
HWND inputWindow{};std::atomic<bool> inputNotification{false};
|
||||
explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window)
|
||||
{
|
||||
if(std::filesystem::exists(path))
|
||||
{
|
||||
auto j=Json::parse(unprotect(readFile(path,256*1024)));
|
||||
if(j.value("version",0)!=1 || !lan::identifier(j.value("id",""))) throw std::runtime_error("Invalid local LAN configuration.");
|
||||
id=j.at("id"); enabled=j.value("enabled",false); trusted=j.at("trusted");
|
||||
positions=j.value("positions",Json::object());
|
||||
shareInput=j.value("shareInput",false);inputPeer=j.value("inputPeer","");inputEdge=j.value("inputEdge",1);
|
||||
if(inputEdge<0||inputEdge>3||(shareInput&&trusted.empty()))throw std::runtime_error("Invalid input sharing configuration.");
|
||||
if(!trusted.is_object()||trusted.size()>64) throw std::runtime_error("Invalid paired computer list.");
|
||||
for(auto &[key,entry]:trusted.items())
|
||||
if(!lan::identifier(key)||key==id||entry.at("key").get<std::string>().size()!=64||
|
||||
!entry.at("name").is_string()||entry.at("name").get<std::string>().size()>128)
|
||||
throw std::runtime_error("Invalid paired computer key.");
|
||||
}
|
||||
else id=lan::randomHex(16);
|
||||
lan::fillPositions(positions,trusted,inputPeer,inputEdge);
|
||||
clipboard=std::make_unique<lan::ClipboardExchange>(id);
|
||||
configureRouter();
|
||||
if(enabled) start();
|
||||
}
|
||||
~Impl() { stop(); }
|
||||
void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted},
|
||||
{"shareInput",shareInput},{"inputPeer",inputPeer},{"inputEdge",inputEdge},{"positions",positions}}))); }
|
||||
bool queue(const std::string &peer,lan::InputFrame frame)
|
||||
{
|
||||
std::lock_guard lock(inputMutex);
|
||||
if(!inputReady.contains(peer))return false;
|
||||
if(inputOut.size()>=512){abortInput=true;return false;}
|
||||
if(!inputOut.empty()&&inputOut.back().peer==peer&&inputOut.back().epoch==inputReady.at(peer)){
|
||||
std::vector<lan::InputFrame> tail{inputOut.back().frame};lan::enqueueInput(tail,frame);
|
||||
if(tail.size()==1){inputOut.back().frame=tail.front();return true;}
|
||||
}
|
||||
inputOut.push_back({peer,frame,inputReady.at(peer)});return true;
|
||||
}
|
||||
void configureRouter()
|
||||
{
|
||||
if(router)router->cancel(GetTickCount64());
|
||||
router.reset();++inputConfiguration;
|
||||
if(enabled&&shareInput){
|
||||
std::map<std::string,POINT> layout;for(auto &[peer,cell]:positions.items())if(trusted.contains(peer))layout[peer]={cell[0].get<LONG>(),cell[1].get<LONG>()};
|
||||
router=std::make_unique<lan::InputMesh>(id,lan::windowsInputEnvironment(),std::move(layout),[this](const auto &peer,auto f){return queue(peer,f);});
|
||||
}
|
||||
inputStatus=enabled&&shareInput?"Connecting input channels...":"Input sharing disabled.";
|
||||
observedRevision=0;
|
||||
}
|
||||
bool takeChange()
|
||||
{
|
||||
auto revision=router?router->revision():0;auto configuration=inputConfiguration.load();
|
||||
bool changed=revision!=observedRevision||configuration!=observedConfiguration;
|
||||
observedRevision=revision;observedConfiguration=configuration;return changed;
|
||||
}
|
||||
bool tickInput(bool allowEnter)
|
||||
{
|
||||
inputNotification=false;
|
||||
if(layoutChanged.exchange(false)){std::lock_guard lock(mutex);configureRouter();}
|
||||
if(!router)return false;
|
||||
auto epoch=inputEpoch.load();if(epoch!=observedEpoch){router->cancel(GetTickCount64());observedEpoch=epoch;}
|
||||
std::vector<lan::RoutedInput> incoming;std::map<std::string,uint64_t> ready;
|
||||
{std::lock_guard lock(inputMutex);incoming.swap(inputIn);ready=inputReady;}
|
||||
router->tick(ready,GetTickCount64());
|
||||
for(auto &frame:incoming)if(ready.contains(frame.peer)&&ready.at(frame.peer)==frame.epoch)
|
||||
router->receive(frame.peer,frame.frame,GetTickCount64(),allowEnter);
|
||||
return takeChange();
|
||||
}
|
||||
void start()
|
||||
{
|
||||
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
|
||||
worker=std::thread([this]{ run(); });
|
||||
}
|
||||
void stop()
|
||||
{
|
||||
if(router)router->cancel(GetTickCount64());
|
||||
stopping=true;
|
||||
if(worker.joinable()) worker.join();
|
||||
inputConnected=false;++inputEpoch;
|
||||
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
|
||||
std::lock_guard lock(mutex); pending.reset(); peers.clear();clipboard=std::make_unique<lan::ClipboardExchange>(id);
|
||||
}
|
||||
void send(SOCKET socket,const sockaddr_in &address,const Json &j)
|
||||
{
|
||||
auto bytes=j.dump(); if(bytes.size()>2048) return;
|
||||
sendto(socket,bytes.data(),int(bytes.size()),0,(const sockaddr*)&address,sizeof(address));
|
||||
}
|
||||
std::string heartbeat(const std::string &from,const std::string &to,const std::string &a,const std::string &b)
|
||||
{ return "KSwitcher LAN v1|presence|"+from+"|"+to+"|"+a+"|"+b; }
|
||||
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now)
|
||||
{
|
||||
if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return;
|
||||
auto other=j.value("id",""); if(!lan::identifier(other)||other==id) return;
|
||||
auto type=j.value("type","");
|
||||
if(type=="hello")
|
||||
{
|
||||
auto display=j.value("name",""); auto session=j.value("epoch","");
|
||||
if(display.empty()||display.size()>128||!lan::identifier(session)||
|
||||
std::any_of(display.begin(),display.end(),[](unsigned char c){return c<32||c==127;})) return;
|
||||
// Discovery is untrusted and never grants input access.
|
||||
if(!peers.contains(other) && peers.size()>=64) return;
|
||||
auto &peer=peers[other];
|
||||
// A fresh announcement rotates the challenge every three seconds; it
|
||||
// does not revoke a recent successful proof for the same address.
|
||||
// Only a valid presence response renews verified, so untrusted/replayed
|
||||
// announcements cannot extend its PeerLifetime expiry.
|
||||
if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0;
|
||||
clipboard->peerSession(other,j.value("clipboardSession",""));
|
||||
peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now;
|
||||
if(trusted.contains(other))
|
||||
{
|
||||
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
|
||||
response["proof"]=lan::mac(trusted[other].at("key"),heartbeat(id,other,epoch,session));
|
||||
send(socket,address,response);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(!peers.contains(other)||j.value("to","")!=id) return;
|
||||
auto &peer=peers.at(other);
|
||||
if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) return;
|
||||
if(type=="clipboard" && trusted.contains(other))
|
||||
{
|
||||
try {clipboard->receive(other,trusted.at(other).at("key"),j,now,GetClipboardSequenceNumber(),
|
||||
[&](const auto &target,const auto &packet){send(socket,peers.at(target).address,packet);});}
|
||||
catch(const std::exception &) {return;}
|
||||
if(!clipboard->deliveries.empty()&&inputWindow)PostMessageW(inputWindow,LanClipboardReadyMessage,0,0);
|
||||
return;
|
||||
}
|
||||
if(type=="presence" && trusted.contains(other) && j.value("epoch","")==peer.epoch &&
|
||||
lan::equal(j.value("proof",""),lan::mac(trusted[other].at("key"),heartbeat(other,id,peer.epoch,epoch))))
|
||||
{ peer.verified=now; return; }
|
||||
if(pending && pending->peer==other)
|
||||
{
|
||||
for(const auto &response:pending->receive(j,now)) send(socket,address,response);
|
||||
if(pending->confirmed && (!trusted.contains(other)||trusted[other].at("key")!=pending->derived))
|
||||
{
|
||||
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="Paired. Select a screen position and enable mouse and keyboard on both PCs.";
|
||||
}
|
||||
}
|
||||
}
|
||||
void run() noexcept
|
||||
{
|
||||
WSADATA startup{}; SOCKET socket=INVALID_SOCKET; bool winsock=false;
|
||||
try
|
||||
{
|
||||
if(WSAStartup(MAKEWORD(2,2),&startup)) throw std::runtime_error("Cannot start Windows networking.");
|
||||
winsock=true; socket=::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
|
||||
BOOL yes=TRUE; u_long nonblock=1;
|
||||
if(socket==INVALID_SOCKET || setsockopt(socket,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,(char*)&yes,sizeof(yes)) ||
|
||||
setsockopt(socket,SOL_SOCKET,SO_BROADCAST,(char*)&yes,sizeof(yes)) || ioctlsocket(socket,FIONBIO,&nonblock))
|
||||
throw std::runtime_error("Cannot open LAN discovery socket.");
|
||||
int clipboardBuffer=1024*1024;
|
||||
setsockopt(socket,SOL_SOCKET,SO_RCVBUF,reinterpret_cast<const char*>(&clipboardBuffer),sizeof(clipboardBuffer));
|
||||
setsockopt(socket,SOL_SOCKET,SO_SNDBUF,reinterpret_cast<const char*>(&clipboardBuffer),sizeof(clipboardBuffer));
|
||||
sockaddr_in bound{}; bound.sin_family=AF_INET; bound.sin_port=htons(lan::Port);
|
||||
if(bind(socket,(sockaddr*)&bound,sizeof(bound))) throw std::runtime_error("UDP port 45883 is in use. Only one LAN-enabled KSwitcher may run per computer.");
|
||||
uint64_t nextHello=0,nextOffer=0;
|
||||
lan::InputHub hub(id);
|
||||
while(!stopping)
|
||||
{
|
||||
auto now=GetTickCount64();bool clipboardActive=false;
|
||||
std::vector<lan::InputEndpoint> endpoints;
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
clipboard->poll(trusted,now,[&](const auto &target,const auto &packet){
|
||||
if(peers.contains(target))send(socket,peers.at(target).address,packet);
|
||||
});
|
||||
clipboardActive=clipboard->active();
|
||||
if(shareInput)for(auto &[peer,entry]:trusted.items())if(peers.contains(peer))
|
||||
endpoints.push_back({peer,entry.at("key"),peers.at(peer).address.sin_addr.s_addr});
|
||||
if(now>=nextHello)
|
||||
{
|
||||
epoch=lan::randomHex(16); // Fresh challenge prevents replayed presence from staying online.
|
||||
auto hello=lan::envelope("hello",id); hello["name"]=name; hello["epoch"]=epoch;hello["clipboardSession"]=clipboard->session();
|
||||
for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); }
|
||||
nextHello=now+3000;
|
||||
}
|
||||
for(auto it=peers.begin();it!=peers.end();) {
|
||||
if(now-it->second.seen>lan::PeerLifetime) it=peers.erase(it); else ++it;
|
||||
}
|
||||
if(pending && pending->expired(now)) {
|
||||
status=pending->confirmed ? "Pair saved. Select a computer to manage it." : "Pairing expired. Enter the same code and click Pair on both computers.";
|
||||
pending.reset();
|
||||
}
|
||||
if(pending && now>=nextOffer && peers.contains(pending->peer)) {
|
||||
send(socket,peers.at(pending->peer).address,pending->offer()); nextOffer=now+1000;
|
||||
}
|
||||
}
|
||||
std::vector<lan::RoutedInput> out,in;
|
||||
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
|
||||
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
|
||||
hub.poll(endpoints,out,in,now);
|
||||
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
|
||||
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
|
||||
for(auto &frame:in){
|
||||
if(!inputIn.empty()&&inputIn.back().peer==frame.peer&&inputIn.back().epoch==frame.epoch){
|
||||
std::vector<lan::InputFrame> tail{inputIn.back().frame};lan::enqueueInput(tail,frame.frame);
|
||||
if(tail.size()==1){inputIn.back().frame=tail.front();continue;}
|
||||
}
|
||||
inputIn.push_back(frame);
|
||||
}
|
||||
if(inputIn.size()>512){inputIn.clear();abortInput=true;}
|
||||
}
|
||||
if(!in.empty()&&inputWindow&&!inputNotification.exchange(true))
|
||||
if(!PostMessageW(inputWindow,LanInputReadyMessage,0,0))inputNotification=false;
|
||||
{std::lock_guard lock(mutex);inputStatus=hub.status();}
|
||||
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,!endpoints.empty()||clipboardActive?5000:100000};
|
||||
int ready=select(0,&read,nullptr,nullptr,&delay);
|
||||
if(ready==SOCKET_ERROR) throw std::runtime_error("LAN discovery socket failed.");
|
||||
if(ready>0) for(int count=0;count<64;++count)
|
||||
{
|
||||
char buffer[2049]; sockaddr_in sender{}; int size=sizeof(sender);
|
||||
int received=recvfrom(socket,buffer,sizeof(buffer),0,(sockaddr*)&sender,&size);
|
||||
if(received<=0) break;
|
||||
if(received>2048||sender.sin_port!=htons(lan::Port)||!localAddress(sender.sin_addr.s_addr)) continue;
|
||||
try { auto j=Json::parse(buffer,buffer+received); std::lock_guard lock(mutex); receive(socket,sender,j,GetTickCount64()); }
|
||||
catch(const Json::exception &) {} // Malformed network data cannot interrupt discovery.
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(const std::exception &e) { std::lock_guard lock(mutex); status=std::string("LAN stopped: ")+e.what(); }
|
||||
inputConnected=false;++inputEpoch;
|
||||
{std::lock_guard lock(mutex);if(shareInput)inputStatus="Input connection closed.";}
|
||||
if(socket!=INVALID_SOCKET) closesocket(socket);
|
||||
if(winsock) WSACleanup();
|
||||
}
|
||||
Bytes command(const Bytes &input)
|
||||
{
|
||||
auto j=Json::parse(input); auto action=j.value("action","status");
|
||||
if(action=="enable")
|
||||
{
|
||||
stop();
|
||||
bool previous=enabled; enabled=j.at("enabled").get<bool>();
|
||||
try {save();} catch(...) {enabled=previous;if(enabled) start();throw;}
|
||||
configureRouter();
|
||||
if(enabled) start(); else status="Disabled. No discovery sockets or worker thread.";
|
||||
}
|
||||
std::lock_guard lock(mutex);
|
||||
if(action=="position")
|
||||
{
|
||||
auto peer=j.at("peer").get<std::string>();int x=j.at("x"),y=j.at("y");
|
||||
if(!trusted.contains(peer))throw std::runtime_error("Pair this computer before arranging it.");
|
||||
lan::validateCell(positions,peer,x,y);
|
||||
auto before=positions;int beforeEdge=inputEdge;bool beforeActive=shareInput;
|
||||
positions[peer]=Json::array({x,y});
|
||||
if(peer==inputPeer){int edge=lan::cellEdge(positions[peer]);if(edge>=0)inputEdge=edge;}
|
||||
try{save();}catch(...){positions=std::move(before);inputEdge=beforeEdge;shareInput=beforeActive;throw;}
|
||||
configureRouter();
|
||||
}
|
||||
if(action=="input")
|
||||
{
|
||||
bool active=j.at("enabled");auto peer=j.value("peer",inputPeer);int edge=j.value("edge",inputEdge);
|
||||
if(edge<0||edge>3||(active&&(!enabled||trusted.empty()||(j.contains("peer")&&!trusted.contains(peer)))))throw std::runtime_error("Enable discovery and select a paired KSwitcher first.");
|
||||
auto beforePeer=inputPeer;auto beforePositions=positions;int beforeEdge=inputEdge;bool beforeActive=shareInput;
|
||||
if(j.contains("edge")&&trusted.contains(peer)){auto cell=lan::edgeCell(edge);lan::validateCell(positions,peer,cell[0],cell[1]);positions[peer]=cell;}
|
||||
shareInput=active;inputPeer=peer;inputEdge=edge;
|
||||
try{save();}catch(...){shareInput=beforeActive;inputPeer=beforePeer;inputEdge=beforeEdge;positions=std::move(beforePositions);throw;}
|
||||
configureRouter();inputStatus=active?"Connecting input channel...":"Input sharing disabled.";
|
||||
}
|
||||
if(action=="code") return encoded({{"code",lan::randomHex(16)}});
|
||||
if(action=="cancel") { pending.reset(); status="Pairing cancelled."; }
|
||||
if(action=="pair")
|
||||
{
|
||||
auto peer=j.at("peer").get<std::string>();
|
||||
if(!enabled||!peers.contains(peer)) throw std::runtime_error("Select an available KSwitcher computer first.");
|
||||
if(!trusted.contains(peer)&&trusted.size()>=64) throw std::runtime_error("Remove an old pair before adding another computer.");
|
||||
pending=std::make_unique<lan::Pairing>(id,peer,j.at("code").get<std::string>(),GetTickCount64());
|
||||
status="Waiting for the same code and Pair on the other KSwitcher (2 minutes)...";
|
||||
}
|
||||
if(action=="forget")
|
||||
{
|
||||
auto peer=j.at("peer").get<std::string>();auto oldTrusted=trusted;auto oldPositions=positions;bool oldSharing=shareInput;
|
||||
trusted.erase(peer);positions.erase(peer);if(trusted.empty())shareInput=false;
|
||||
try{save();}catch(...){trusted=std::move(oldTrusted);positions=std::move(oldPositions);shareInput=oldSharing;throw;}
|
||||
if(pending&&pending->peer==peer)pending.reset();
|
||||
configureRouter();
|
||||
status="Pair removed on this computer.";
|
||||
}
|
||||
Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()},
|
||||
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnected.load()},
|
||||
{"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"controlMode",router?int(router->mode()):0}};
|
||||
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
|
||||
auto now=GetTickCount64();
|
||||
for(const auto &[peer,p]:peers)
|
||||
{
|
||||
char ip[INET_ADDRSTRLEN]{}; InetNtopA(AF_INET,(void*)&p.address.sin_addr,ip,sizeof(ip));
|
||||
result["peers"].push_back({{"id",peer},{"name",p.name},{"address",ip},{"paired",trusted.contains(peer)},
|
||||
{"verified",p.verified && now-p.verified<lan::PeerLifetime},{"online",true}});
|
||||
}
|
||||
for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer))
|
||||
result["peers"].push_back({{"id",peer},{"name",p.at("name")},{"address",""},{"paired",true},{"verified",false},{"online",false}});
|
||||
return encoded(result);
|
||||
}
|
||||
};
|
||||
LanService::LanService(const std::filesystem::path &path,HWND window) : impl(std::make_unique<Impl>(path,window)) {}
|
||||
LanService::~LanService()=default;
|
||||
Bytes LanService::command(const Bytes &command) { return impl->command(command); }
|
||||
bool LanService::clipboardEnabled()const
|
||||
{
|
||||
std::lock_guard lock(impl->mutex);
|
||||
if(!impl->enabled)return false;
|
||||
for(auto &[id,entry]:impl->trusted.items())if(impl->peers.contains(id))return true;
|
||||
return false;
|
||||
}
|
||||
void LanService::publishClipboard(Bytes bytes,const std::string &app)
|
||||
{
|
||||
std::lock_guard lock(impl->mutex);if(!impl->enabled)return;
|
||||
std::vector<std::string> targets;
|
||||
for(auto &[id,entry]:impl->trusted.items())if(impl->peers.contains(id))targets.push_back(id);
|
||||
if(!targets.empty())impl->clipboard->queue(targets,std::move(bytes),app,GetTickCount64());
|
||||
}
|
||||
std::vector<LanClipboard> LanService::takeClipboard()
|
||||
{
|
||||
std::lock_guard lock(impl->mutex);std::vector<LanClipboard> result;
|
||||
for(auto &d:impl->clipboard->deliveries)if(impl->trusted.contains(d.peer))
|
||||
result.push_back({d.peer,impl->trusted.at(d.peer).at("name"),d.app,std::move(d.bytes),d.sequence});
|
||||
impl->clipboard->deliveries.clear();return result;
|
||||
}
|
||||
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput;}
|
||||
bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);}
|
||||
bool LanService::keyboard(const KBDLLHOOKSTRUCT &k,bool down){return impl->router&&impl->router->keyboard(k,down,GetTickCount64());}
|
||||
bool LanService::mouse(UINT message,const MSLLHOOKSTRUCT &m,bool allowEnter){return impl->router&&impl->router->mouse(message,m,GetTickCount64(),allowEnter);}
|
||||
bool LanService::takeInputChange(){return impl->takeChange();}
|
||||
void LanService::cancelInput(){if(impl->router)impl->router->cancel(GetTickCount64());impl->abortInput=true;}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
#include "platform.h"
|
||||
#include <memory>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69;
|
||||
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
|
||||
// Discovery, pairing and optional encrypted input within the resident process.
|
||||
class LanService
|
||||
{
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl;
|
||||
public:
|
||||
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr);
|
||||
~LanService();
|
||||
Bytes command(const Bytes &);
|
||||
bool clipboardEnabled() const;
|
||||
void publishClipboard(Bytes, const std::string &);
|
||||
std::vector<LanClipboard> takeClipboard();
|
||||
bool inputEnabled() const;
|
||||
bool tickInput(bool allowEnter = true);
|
||||
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
|
||||
bool mouse(UINT, const MSLLHOOKSTRUCT &, bool allowEnter);
|
||||
bool takeInputChange();
|
||||
void cancelInput();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include "lan_channel.h"
|
||||
#include <bcrypt.h>
|
||||
#include <limits>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
namespace
|
||||
{
|
||||
void checked(NTSTATUS s){if(s<0) throw std::runtime_error("Input channel authentication failed.");}
|
||||
void put32(Bytes &b,uint32_t v){for(int n=24;n>=0;n-=8)b.push_back(static_cast<unsigned char>(v>>n));}
|
||||
uint32_t get32(const unsigned char *p){return (uint32_t(p[0])<<24)|(uint32_t(p[1])<<16)|(uint32_t(p[2])<<8)|p[3];}
|
||||
Bytes keyBytes(const std::string &key)
|
||||
{
|
||||
if(key.size()!=64||key.find_first_not_of("0123456789abcdef")!=key.npos) throw std::runtime_error("Invalid input key.");
|
||||
Bytes bytes;for(size_t i=0;i<key.size();i+=2)bytes.push_back(static_cast<unsigned char>(std::stoul(key.substr(i,2),nullptr,16)));return bytes;
|
||||
}
|
||||
bool nonblocking(SOCKET s){u_long value=1;BOOL yes=TRUE;return !ioctlsocket(s,FIONBIO,&value)&&!setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char*)&yes,sizeof(yes));}
|
||||
void closeSocket(SOCKET &s){if(s!=INVALID_SOCKET){closesocket(s);s=INVALID_SOCKET;}}
|
||||
}
|
||||
struct InputCipher::Impl
|
||||
{
|
||||
BCRYPT_ALG_HANDLE alg{};BCRYPT_KEY_HANDLE key{};uint64_t sequence{};
|
||||
explicit Impl(const std::string &secret)
|
||||
{
|
||||
auto bytes=keyBytes(secret);
|
||||
try {
|
||||
checked(BCryptOpenAlgorithmProvider(&alg,BCRYPT_AES_ALGORITHM,nullptr,0));
|
||||
checked(BCryptSetProperty(alg,BCRYPT_CHAINING_MODE,(PUCHAR)BCRYPT_CHAIN_MODE_GCM,sizeof(BCRYPT_CHAIN_MODE_GCM),0));
|
||||
checked(BCryptGenerateSymmetricKey(alg,&key,nullptr,0,bytes.data(),ULONG(bytes.size()),0));
|
||||
} catch(...) {if(key)BCryptDestroyKey(key);if(alg)BCryptCloseAlgorithmProvider(alg,0);throw;}
|
||||
SecureZeroMemory(bytes.data(),bytes.size());
|
||||
}
|
||||
~Impl(){if(key)BCryptDestroyKey(key);if(alg)BCryptCloseAlgorithmProvider(alg,0);}
|
||||
Bytes crypt(Bytes payload,Bytes &tag,bool encrypt)
|
||||
{
|
||||
if(sequence==std::numeric_limits<uint64_t>::max())throw std::runtime_error("Input session exhausted.");
|
||||
unsigned char nonce[12]{};for(int i=0;i<8;++i)nonce[11-i]=static_cast<unsigned char>(sequence>>(i*8));
|
||||
BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;BCRYPT_INIT_AUTH_MODE_INFO(info);
|
||||
info.pbNonce=nonce;info.cbNonce=sizeof(nonce);info.pbTag=tag.data();info.cbTag=ULONG(tag.size());
|
||||
// Protocol/direction are bound by key derivation; sequence and payload length by GCM.
|
||||
Bytes result(payload.size());ULONG written{};
|
||||
auto fn=encrypt?BCryptEncrypt:BCryptDecrypt;
|
||||
checked(fn(key,payload.data(),ULONG(payload.size()),&info,nullptr,0,result.data(),ULONG(result.size()),&written,0));
|
||||
if(written!=payload.size())throw std::runtime_error("Invalid input frame size.");
|
||||
++sequence;return result;
|
||||
}
|
||||
};
|
||||
InputCipher::InputCipher(const std::string &key):impl(std::make_unique<Impl>(key)){}
|
||||
InputCipher::~InputCipher()=default;
|
||||
Bytes InputCipher::encryptPayload(const Bytes &plain)
|
||||
{
|
||||
if(plain.empty()||plain.size()>1024)throw std::runtime_error("Invalid file packet size.");
|
||||
Bytes tag(16);auto result=impl->crypt(plain,tag,true);result.insert(result.end(),tag.begin(),tag.end());return result;
|
||||
}
|
||||
Bytes InputCipher::decryptPayload(const Bytes &packet)
|
||||
{
|
||||
if(packet.size()<17||packet.size()>1040)throw std::runtime_error("Invalid file packet size.");
|
||||
Bytes tag(packet.end()-16,packet.end());return impl->crypt(Bytes(packet.begin(),packet.end()-16),tag,false);
|
||||
}
|
||||
Bytes InputCipher::encrypt(const InputFrame &f)
|
||||
{
|
||||
Bytes plain;put32(plain,uint32_t(f.type));put32(plain,f.token);put32(plain,uint32_t(f.a));put32(plain,uint32_t(f.b));put32(plain,uint32_t(f.c));
|
||||
Bytes tag(16);auto result=impl->crypt(std::move(plain),tag,true);result.insert(result.end(),tag.begin(),tag.end());return result;
|
||||
}
|
||||
InputFrame InputCipher::decrypt(const Bytes &packet)
|
||||
{
|
||||
if(packet.size()!=36)throw std::runtime_error("Invalid encrypted input frame.");
|
||||
Bytes tag(packet.begin()+20,packet.end());auto plain=impl->crypt(Bytes(packet.begin(),packet.begin()+20),tag,false);
|
||||
auto type=get32(plain.data());if(type>uint32_t(InputType::Cross))throw std::runtime_error("Unsupported input frame.");
|
||||
return {InputType(type),get32(plain.data()+4),int32_t(get32(plain.data()+8)),int32_t(get32(plain.data()+12)),int32_t(get32(plain.data()+16))};
|
||||
}
|
||||
std::string inputSessionKey(const std::string &secret,const std::string &from,const std::string &to,const std::string &a,const std::string &b,int edge)
|
||||
{
|
||||
if(!identifier(from)||!identifier(to)||from==to||!identifier(a)||!identifier(b))throw std::runtime_error("Invalid session identity.");
|
||||
return mac(secret,"KSwitcher input v1|"+from+"|"+to+"|"+a+"|"+b+"|"+std::to_string(edge));
|
||||
}
|
||||
struct InputChannel::Impl
|
||||
{
|
||||
std::string local,peer,secret,nonce,state="Waiting for the paired computer...";
|
||||
int edge;uint16_t port;SOCKET listener=INVALID_SOCKET,socket=INVALID_SOCKET;
|
||||
bool connecting{},authenticated{},helloRead{},managed{};
|
||||
uint64_t changed{},lastRead{},lastPing{},retry{};
|
||||
Bytes incoming,outgoing;
|
||||
std::unique_ptr<InputCipher> tx,rx;
|
||||
Impl(std::string a,std::string b,std::string key,int side,uint16_t p,bool multiple):local(std::move(a)),peer(std::move(b)),secret(std::move(key)),edge(side),port(p),managed(multiple){}
|
||||
~Impl(){closeSocket(socket);closeSocket(listener);}
|
||||
void reset(uint64_t now,const std::string &reason)
|
||||
{
|
||||
closeSocket(socket);connecting=authenticated=helloRead=false;incoming.clear();outgoing.clear();tx.reset();rx.reset();++changed;retry=now+1500;state=reason;
|
||||
}
|
||||
void begin(uint64_t now)
|
||||
{
|
||||
nonce=randomHex(16);lastRead=lastPing=now;
|
||||
auto hello=Json{{"app","KSwitcher-input"},{"version",managed?2:1},{"id",local},{"to",peer},{"nonce",nonce},{"edge",edge}}.dump();
|
||||
put32(outgoing,uint32_t(hello.size()));outgoing.insert(outgoing.end(),hello.begin(),hello.end());
|
||||
state="Authenticating paired KSwitcher...";
|
||||
}
|
||||
void poll(uint32_t address,const std::vector<InputFrame> &frames,std::vector<InputFrame> &received,uint64_t now)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(socket==INVALID_SOCKET&&now<retry)return;
|
||||
if(!managed && listener==INVALID_SOCKET && local>peer)
|
||||
{
|
||||
listener=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);BOOL yes=TRUE;
|
||||
if(listener==INVALID_SOCKET||setsockopt(listener,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,(char*)&yes,sizeof(yes))||!nonblocking(listener)){closeSocket(listener);throw std::runtime_error("Cannot open input listener.");}
|
||||
sockaddr_in a{};a.sin_family=AF_INET;a.sin_port=htons(port);
|
||||
if(bind(listener,(sockaddr*)&a,sizeof(a))||listen(listener,1)) {closeSocket(listener);throw std::runtime_error("TCP input port is unavailable.");}
|
||||
}
|
||||
if(socket==INVALID_SOCKET && address && now>=retry)
|
||||
{
|
||||
if(local<peer)
|
||||
{
|
||||
socket=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(socket==INVALID_SOCKET||!nonblocking(socket))throw std::runtime_error("Cannot open input connection.");
|
||||
sockaddr_in a{};a.sin_family=AF_INET;a.sin_port=htons(port);a.sin_addr.s_addr=address;
|
||||
int result=connect(socket,(sockaddr*)&a,sizeof(a));
|
||||
if(result && WSAGetLastError()!=WSAEWOULDBLOCK)throw std::runtime_error("Paired computer is not accepting input connections.");
|
||||
connecting=result!=0;begin(now);
|
||||
if(connecting)state="Connecting to paired PC on TCP 45884...";
|
||||
}
|
||||
else if(!managed)
|
||||
{
|
||||
sockaddr_in a{};int length=sizeof(a);socket=accept(listener,(sockaddr*)&a,&length);
|
||||
if(socket!=INVALID_SOCKET)
|
||||
{
|
||||
if(a.sin_addr.s_addr!=address){closeSocket(socket);return;}
|
||||
if(!nonblocking(socket))throw std::runtime_error("Cannot configure input connection.");
|
||||
begin(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(socket==INVALID_SOCKET)return;
|
||||
// Give TCP establishment time for SYN retransmission / firewall approval.
|
||||
// Keep the short fail-safe only for an already authenticated input session.
|
||||
if(now-lastRead>(authenticated?2000:10000))
|
||||
throw std::runtime_error(authenticated ? "Input connection lost (no heartbeat for 2 seconds); control returned locally." :
|
||||
connecting ? "Cannot reach TCP 45884. Enable input on both PCs and check the receiving PC firewall." :
|
||||
"TCP connected, but input authentication timed out. Check pairing and input setup on both PCs.");
|
||||
if(connecting)
|
||||
{
|
||||
fd_set writes,errors;FD_ZERO(&writes);FD_ZERO(&errors);FD_SET(socket,&writes);FD_SET(socket,&errors);timeval wait{};
|
||||
if(select(0,nullptr,&writes,&errors,&wait)<=0)return;
|
||||
int error=0;int size=sizeof(error);
|
||||
if(getsockopt(socket,SOL_SOCKET,SO_ERROR,(char*)&error,&size))error=WSAGetLastError();
|
||||
if(error)throw std::runtime_error("Cannot connect to TCP 45884 (Windows error "+std::to_string(error)+"). Enable input on both PCs and check the receiving PC firewall.");
|
||||
connecting=false;state="TCP connected; authenticating paired KSwitcher...";
|
||||
}
|
||||
if(authenticated)
|
||||
{
|
||||
for(auto &f:frames){auto bytes=tx->encrypt(f);outgoing.insert(outgoing.end(),bytes.begin(),bytes.end());}
|
||||
if(now-lastPing>=400){auto bytes=tx->encrypt({InputType::Ping});outgoing.insert(outgoing.end(),bytes.begin(),bytes.end());lastPing=now;}
|
||||
}
|
||||
if(outgoing.size()>32768)throw std::runtime_error("Input queue overflow; control returned locally.");
|
||||
if(!outgoing.empty())
|
||||
{
|
||||
int count=::send(socket,(char*)outgoing.data(),int(outgoing.size()),0);
|
||||
if(count>0)outgoing.erase(outgoing.begin(),outgoing.begin()+count);
|
||||
else if(count==0||WSAGetLastError()!=WSAEWOULDBLOCK)throw std::runtime_error("Input send failed.");
|
||||
}
|
||||
unsigned char data[4096];
|
||||
for(int batch=0;batch<8;++batch)
|
||||
{
|
||||
int count=recv(socket,(char*)data,sizeof(data),0);
|
||||
if(count==0)throw std::runtime_error("Other KSwitcher disconnected.");
|
||||
if(count<0){if(WSAGetLastError()!=WSAEWOULDBLOCK)throw std::runtime_error("Input receive failed.");break;}
|
||||
incoming.insert(incoming.end(),data,data+count);
|
||||
}
|
||||
if(incoming.size()>32768)throw std::runtime_error("Input receive queue overflow.");
|
||||
if(!helloRead && incoming.size()>=4)
|
||||
{
|
||||
size_t length=get32(incoming.data());if(length>512||length<32)throw std::runtime_error("Invalid input handshake.");
|
||||
if(incoming.size()<length+4)return;
|
||||
auto hello=Json::parse(incoming.begin()+4,incoming.begin()+4+length);
|
||||
if(hello.value("app","")!="KSwitcher-input"||hello.value("version",0)!=(managed?2:1)||hello.value("id","")!=peer||hello.value("to","")!=local)
|
||||
throw std::runtime_error("Unexpected input peer.");
|
||||
if(!managed&&hello.value("edge",-1)!=(edge^1))throw std::runtime_error("Screen positions must be opposite on the two computers.");
|
||||
auto remoteNonce=hello.value("nonce","");
|
||||
tx=std::make_unique<InputCipher>(inputSessionKey(secret,local,peer,nonce,remoteNonce,managed?-1:edge));
|
||||
rx=std::make_unique<InputCipher>(inputSessionKey(secret,peer,local,remoteNonce,nonce,managed?-1:(edge^1)));
|
||||
incoming.erase(incoming.begin(),incoming.begin()+4+length);helloRead=true;
|
||||
auto bytes=tx->encrypt({InputType::Ready});outgoing.insert(outgoing.end(),bytes.begin(),bytes.end());
|
||||
}
|
||||
while(helloRead && incoming.size()>=36)
|
||||
{
|
||||
auto f=rx->decrypt(Bytes(incoming.begin(),incoming.begin()+36));incoming.erase(incoming.begin(),incoming.begin()+36);lastRead=now;
|
||||
if(!authenticated){if(f.type!=InputType::Ready)throw std::runtime_error("Input received before authentication.");authenticated=true;state="Input connected. Move through the configured screen edge.";}
|
||||
else if(f.type==InputType::Ready)throw std::runtime_error("Repeated input handshake.");
|
||||
else if(f.type!=InputType::Ping)received.push_back(f);
|
||||
}
|
||||
}
|
||||
catch(const std::exception &e){received.clear();reset(now,e.what());}
|
||||
}
|
||||
};
|
||||
InputChannel::InputChannel(std::string a,std::string b,std::string key,int edge,uint16_t port,bool managed):impl(std::make_unique<Impl>(std::move(a),std::move(b),std::move(key),edge,port,managed)){}
|
||||
InputChannel::~InputChannel()=default;
|
||||
void InputChannel::poll(uint32_t ip,const std::vector<InputFrame>&out,std::vector<InputFrame>&in,uint64_t now){impl->poll(ip,out,in,now);}
|
||||
bool InputChannel::adopt(uintptr_t accepted,uint64_t now)
|
||||
{
|
||||
if(!impl->managed||impl->socket!=INVALID_SOCKET||!nonblocking(SOCKET(accepted)))return false;
|
||||
impl->connecting=false;impl->begin(now);impl->socket=SOCKET(accepted);return true;
|
||||
}
|
||||
bool InputChannel::ready()const{return impl->authenticated;}
|
||||
uint64_t InputChannel::generation()const{return impl->changed;}
|
||||
std::string InputChannel::status()const{return impl->state;}
|
||||
void InputChannel::disconnect(){impl->reset(GetTickCount64(),"Input disconnected; local control restored.");}
|
||||
struct InputHub::Impl
|
||||
{
|
||||
struct Link { InputEndpoint endpoint;std::unique_ptr<InputChannel> channel;uint64_t generation{},epoch{}; };
|
||||
struct Pending {SOCKET socket;uint32_t address;uint64_t since;};
|
||||
std::string local;uint16_t port;SOCKET listener=INVALID_SOCKET;
|
||||
std::map<std::string,Link> links;std::vector<Pending> pending;uint64_t epoch{},retry{};
|
||||
std::string error;
|
||||
Impl(std::string id,uint16_t p):local(std::move(id)),port(p){}
|
||||
~Impl(){closeSocket(listener);for(auto &p:pending)closeSocket(p.socket);}
|
||||
void poll(const std::vector<InputEndpoint> &endpoints,const std::vector<RoutedInput> &out,std::vector<RoutedInput> &in,uint64_t now)
|
||||
{
|
||||
for(auto it=links.begin();it!=links.end();){
|
||||
auto match=std::find_if(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id==it->first&&e.key==it->second.endpoint.key&&e.port==it->second.endpoint.port&&e.address==it->second.endpoint.address;});
|
||||
if(match==endpoints.end())it=links.erase(it);else ++it;
|
||||
}
|
||||
for(auto &e:endpoints)if(e.id!=local&&!links.contains(e.id)){
|
||||
Link link;link.endpoint=e;link.channel=std::make_unique<InputChannel>(local,e.id,e.key,0,e.port,true);link.epoch=++epoch;links.emplace(e.id,std::move(link));
|
||||
}
|
||||
bool listenNeeded=std::any_of(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id<local;});
|
||||
if(!listenNeeded){closeSocket(listener);for(auto &p:pending)closeSocket(p.socket);pending.clear();}
|
||||
if(listenNeeded&&listener==INVALID_SOCKET&&now>=retry){
|
||||
listener=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);BOOL yes=TRUE;sockaddr_in a{};a.sin_family=AF_INET;a.sin_port=htons(port);
|
||||
if(listener==INVALID_SOCKET||setsockopt(listener,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,(char*)&yes,sizeof(yes))||!nonblocking(listener)||bind(listener,(sockaddr*)&a,sizeof(a))||listen(listener,SOMAXCONN)){
|
||||
closeSocket(listener);retry=now+1500;error="TCP input port is unavailable.";
|
||||
}else error.clear();
|
||||
}
|
||||
if(listener!=INVALID_SOCKET)for(int n=0;n<16&&pending.size()<64;++n){
|
||||
sockaddr_in a{};int size=sizeof(a);SOCKET sock=accept(listener,(sockaddr*)&a,&size);if(sock==INVALID_SOCKET)break;
|
||||
if(!nonblocking(sock)){closeSocket(sock);continue;}pending.push_back({sock,a.sin_addr.s_addr,now});
|
||||
}
|
||||
for(auto it=pending.begin();it!=pending.end();){
|
||||
bool done=now-it->since>2000;unsigned char bytes[516];int count=recv(it->socket,(char*)bytes,sizeof(bytes),MSG_PEEK);
|
||||
if(count==0||(count<0&&WSAGetLastError()!=WSAEWOULDBLOCK))done=true;
|
||||
if(!done&&count>=4){
|
||||
auto length=get32(bytes);if(length<32||length>512)done=true;
|
||||
else if(count>=int(length+4)){
|
||||
done=true;
|
||||
try{auto hello=Json::parse(bytes+4,bytes+4+length);auto id=hello.value("id","");auto link=links.find(id);
|
||||
if(id<local&&hello.value("to","")==local&&hello.value("version",0)==2&&link!=links.end()&&link->second.endpoint.address==it->address&&link->second.channel->adopt(uintptr_t(it->socket),now))it->socket=INVALID_SOCKET;
|
||||
}catch(const std::exception &){}
|
||||
}
|
||||
}
|
||||
if(done){closeSocket(it->socket);it=pending.erase(it);}else ++it;
|
||||
}
|
||||
for(auto &[id,link]:links){
|
||||
std::vector<InputFrame> frames,received;for(auto &f:out)if(f.peer==id&&(!f.epoch||f.epoch==link.epoch))enqueueInput(frames,f.frame);
|
||||
link.channel->poll(link.endpoint.address,frames,received,now);
|
||||
if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;}
|
||||
for(auto &f:received)in.push_back({id,f,link.epoch});
|
||||
}
|
||||
}
|
||||
};
|
||||
InputHub::InputHub(std::string id,uint16_t port):impl(std::make_unique<Impl>(std::move(id),port)){}
|
||||
InputHub::~InputHub()=default;
|
||||
void InputHub::poll(const std::vector<InputEndpoint> &peers,const std::vector<RoutedInput> &out,std::vector<RoutedInput> &in,uint64_t now){impl->poll(peers,out,in,now);}
|
||||
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.channel->ready())result[id]=l.epoch;return result;}
|
||||
std::string InputHub::status()const{
|
||||
auto count=ready().size();if(count)return "Input connected to "+std::to_string(count)+" computer(s). Move through a neighboring screen edge.";
|
||||
if(!impl->error.empty())return impl->error;
|
||||
for(auto &[id,l]:impl->links)if(!l.channel->status().empty())return l.channel->status();
|
||||
return "Waiting for paired computers...";
|
||||
}
|
||||
void InputHub::disconnect(){for(auto &[id,l]:impl->links)l.channel->disconnect();}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
#include "lan_pairing.h"
|
||||
#include <memory>
|
||||
#include <map>
|
||||
namespace ks::lan
|
||||
{
|
||||
enum class InputType : uint32_t { Ready, Ping, Enter, Accept, Return, Move, Key, Button, Wheel, Cross };
|
||||
struct InputFrame
|
||||
{
|
||||
InputType type{};
|
||||
uint32_t token{};
|
||||
int32_t a{},b{},c{};
|
||||
bool operator==(const InputFrame &) const = default;
|
||||
};
|
||||
// Collapse only contiguous, not-yet-delivered wheel events. A reversal replaces
|
||||
// stale queued motion; key/button boundaries must never be crossed.
|
||||
inline void enqueueInput(std::vector<InputFrame> &queue,const InputFrame &frame)
|
||||
{
|
||||
if(frame.type==InputType::Wheel&&!queue.empty())
|
||||
{
|
||||
auto &last=queue.back();
|
||||
if(last.type==InputType::Wheel&&last.token==frame.token&&last.b==frame.b)
|
||||
{
|
||||
if((last.a<0&&frame.a>0)||(last.a>0&&frame.a<0)){last=frame;return;}
|
||||
auto total=int64_t(last.a)+frame.a;
|
||||
if(total>=-32768&&total<=32767){last.a=int32_t(total);return;}
|
||||
}
|
||||
}
|
||||
queue.push_back(frame);
|
||||
|
||||
}
|
||||
// One directional AES-256-GCM key per session. Strict sequence numbers prevent replay.
|
||||
class InputCipher
|
||||
{
|
||||
struct Impl; std::unique_ptr<Impl> impl;
|
||||
public:
|
||||
explicit InputCipher(const std::string &hexKey);
|
||||
~InputCipher();
|
||||
Bytes encrypt(const InputFrame &);
|
||||
InputFrame decrypt(const Bytes &);
|
||||
Bytes encryptPayload(const Bytes &);
|
||||
Bytes decryptPayload(const Bytes &);
|
||||
};
|
||||
std::string inputSessionKey(const std::string &secret,const std::string &from,const std::string &to,
|
||||
const std::string &fromNonce,const std::string &toNonce,int fromEdge=-1);
|
||||
// Network-thread-only nonblocking TCP channel. No Windows input is injected here.
|
||||
class InputChannel
|
||||
{
|
||||
struct Impl; std::unique_ptr<Impl> impl;
|
||||
public:
|
||||
InputChannel(std::string local,std::string peer,std::string secret,int edge,
|
||||
uint16_t port=45884,bool managed=false);
|
||||
~InputChannel();
|
||||
void poll(uint32_t peerAddress,const std::vector<InputFrame> &out,std::vector<InputFrame> &in,uint64_t now);
|
||||
bool adopt(uintptr_t socket,uint64_t now);
|
||||
bool ready() const;
|
||||
uint64_t generation() const;
|
||||
std::string status() const;
|
||||
void disconnect();
|
||||
};
|
||||
struct InputEndpoint {std::string id,key;uint32_t address{};uint16_t port=45884;};
|
||||
struct RoutedInput {std::string peer;InputFrame frame;uint64_t epoch{};};
|
||||
class InputHub
|
||||
{
|
||||
struct Impl;std::unique_ptr<Impl> impl;
|
||||
public:
|
||||
explicit InputHub(std::string local,uint16_t port=45884);
|
||||
~InputHub();
|
||||
void poll(const std::vector<InputEndpoint> &,const std::vector<RoutedInput> &,std::vector<RoutedInput> &,uint64_t now);
|
||||
std::map<std::string,uint64_t> ready()const;
|
||||
std::string status()const;
|
||||
void disconnect();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
#pragma once
|
||||
#include "lan_channel.h"
|
||||
#include <map>
|
||||
#include <deque>
|
||||
#include <set>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
// Reliable bounded clipboard messages over the existing discovery socket.
|
||||
// Every datagram has a fresh directional AES-GCM key; no plaintext clipboard
|
||||
// metadata or contents appear outside the encrypted CBOR body.
|
||||
class ClipboardExchange
|
||||
{
|
||||
static constexpr size_t Limit=32*1024*1024, Chunk=480, Window=32;
|
||||
struct Item {std::string id,app;Bytes bytes;};
|
||||
struct Sending {std::deque<std::shared_ptr<Item>> queue;size_t ack{};bool begun{};uint64_t last{},progress{};};
|
||||
struct Receiving {std::string id,app;Bytes bytes;size_t size{};uint64_t last{};DWORD sequence{};};
|
||||
std::string local, boot=randomHex(16);
|
||||
std::map<std::string,std::string> sessions;
|
||||
std::map<std::string,Sending> sending;
|
||||
std::map<std::string,Receiving> receiving;
|
||||
std::map<std::string,std::deque<std::pair<std::string,size_t>>> completed;
|
||||
size_t incomingBytes{};uint64_t nextPacket{};
|
||||
std::map<std::string,std::map<std::string,uint64_t>> receivedPackets;
|
||||
static std::string hex(const Bytes &bytes){std::string s;for(auto b:bytes){s+="0123456789abcdef"[b>>4];s+="0123456789abcdef"[b&15];}return s;}
|
||||
static Bytes unhex(const std::string &s)
|
||||
{
|
||||
if(s.size()>2080||s.size()%2||s.find_first_not_of("0123456789abcdef")!=s.npos)throw std::runtime_error("Invalid clipboard packet");
|
||||
Bytes b;for(size_t i=0;i<s.size();i+=2)b.push_back(static_cast<unsigned char>(std::stoul(s.substr(i,2),nullptr,16)));return b;
|
||||
}
|
||||
Json seal(const std::string &peer,const std::string &key,const Json &body)
|
||||
{
|
||||
auto nonce=randomHex(16);auto number=++nextPacket;
|
||||
InputCipher cipher(mac(key,"KSwitcher clipboard v1|"+local+"|"+peer+"|"+boot+"|"+sessions.at(peer)+"|"+std::to_string(number)+"|"+nonce));
|
||||
auto packet=envelope("clipboard",local);packet["to"]=peer;packet["nonce"]=nonce;packet["session"]=sessions.at(peer);packet["fromSession"]=boot;packet["number"]=number;
|
||||
packet["data"]=hex(cipher.encryptPayload(Json::to_cbor(body)));return packet;
|
||||
}
|
||||
public:
|
||||
struct Delivery {std::string peer,id,app;Bytes bytes;DWORD sequence{};};
|
||||
std::vector<Delivery> deliveries;
|
||||
std::string status="Clipboard sharing ready.";
|
||||
explicit ClipboardExchange(std::string id):local(std::move(id)){}
|
||||
const std::string &session()const{return boot;}
|
||||
bool active()const{return !sending.empty();}
|
||||
void peerSession(const std::string &peer,const std::string &value){
|
||||
if(!identifier(value))return;
|
||||
if(sessions.contains(peer)&&sessions.at(peer)!=value){
|
||||
auto found=sending.find(peer);if(found!=sending.end()){found->second.ack=0;found->second.begun=false;found->second.last=0;}
|
||||
}
|
||||
sessions[peer]=value;
|
||||
}
|
||||
void queue(const std::vector<std::string> &peers,Bytes bytes,std::string app,uint64_t now)
|
||||
{
|
||||
if(bytes.empty()||bytes.size()>Limit)throw std::runtime_error("LAN clipboard limit is 32 MiB.");
|
||||
size_t total=bytes.size();std::set<const Item*> counted;
|
||||
for(auto &[peer,s]:sending)for(auto &item:s.queue)if(counted.insert(item.get()).second)total+=item->bytes.size();
|
||||
if(total>2*Limit)throw std::runtime_error("LAN clipboard queue is full.");
|
||||
auto item=std::make_shared<Item>(Item{randomHex(16),app.size()>128?std::string("Application"):app,std::move(bytes)});
|
||||
for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8)continue;if(s.queue.empty()){s.ack=0;s.begun=false;s.last=0;s.progress=now;}s.queue.push_back(item);}
|
||||
if(!peers.empty())status="Sending clipboard to "+std::to_string(peers.size())+" paired computers...";
|
||||
}
|
||||
template<class Send>void poll(const Json &trusted,uint64_t now,Send send)
|
||||
{
|
||||
for(auto it=receiving.begin();it!=receiving.end();)
|
||||
if(!trusted.contains(it->first)||now-it->second.last>30000){incomingBytes-=it->second.size;it=receiving.erase(it);}else ++it;
|
||||
for(auto it=sending.begin();it!=sending.end();)
|
||||
{
|
||||
auto &peer=it->first;auto &s=it->second;
|
||||
if(!trusted.contains(peer)||s.queue.empty()){it=sending.erase(it);continue;}
|
||||
if(now-s.progress>30000){status="Clipboard transfer timed out.";it=sending.erase(it);continue;}
|
||||
if(sessions.contains(peer)&&(!s.last||now-s.last>=100))
|
||||
{
|
||||
auto &item=*s.queue.front();auto key=trusted.at(peer).at("key").template get<std::string>();
|
||||
if(!s.begun)send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}}));
|
||||
else for(size_t offset=s.ack,n=0;offset<item.bytes.size()&&n<Window;offset+=Chunk,++n)
|
||||
send(peer,seal(peer,key,{{"op","chunk"},{"item",item.id},{"offset",offset},
|
||||
{"bytes",Json::binary(Bytes(item.bytes.begin()+offset,item.bytes.begin()+std::min(offset+Chunk,item.bytes.size())))}}));
|
||||
s.last=now;
|
||||
}
|
||||
++it;
|
||||
}
|
||||
}
|
||||
template<class Send>void receive(const std::string &peer,const std::string &key,const Json &packet,uint64_t now,DWORD sequence,Send send)
|
||||
{
|
||||
if(packet.value("session","")!=boot||!sessions.contains(peer)||packet.value("to","")!=local||!identifier(packet.value("nonce","")))return;
|
||||
auto senderBoot=packet.value("fromSession","");auto number=packet.value("number",uint64_t{});
|
||||
if(!identifier(senderBoot)||!number)return;
|
||||
auto &seen=receivedPackets[peer];
|
||||
if((seen.contains(senderBoot)&&number<=seen.at(senderBoot))||(!seen.contains(senderBoot)&&seen.size()>=1024))return;
|
||||
InputCipher cipher(mac(key,"KSwitcher clipboard v1|"+peer+"|"+local+"|"+senderBoot+"|"+boot+"|"+std::to_string(number)+"|"+packet.at("nonce").get<std::string>()));
|
||||
auto body=Json::from_cbor(cipher.decryptPayload(unhex(packet.at("data").get<std::string>())));
|
||||
seen[senderBoot]=number; // Retransmissions use new numbers; reordered old packets are retried.
|
||||
auto id=body.value("item","");if(!identifier(id))return;
|
||||
auto ack=[&](size_t offset){send(peer,seal(peer,key,{{"op","ack"},{"item",id},{"offset",offset}}));};
|
||||
auto op=body.value("op","");
|
||||
if(op=="ack")
|
||||
{
|
||||
auto found=sending.find(peer);if(found==sending.end()||found->second.queue.empty())return;
|
||||
auto &s=found->second;auto &item=*s.queue.front();auto offset=body.at("offset").get<size_t>();
|
||||
if(item.id!=id||offset>item.bytes.size()||offset<s.ack||offset>s.ack+Window*Chunk||(offset!=item.bytes.size()&&offset%Chunk))return;
|
||||
if(offset==s.ack&&s.begun)return;
|
||||
s.begun=true;s.ack=offset;s.progress=now;s.last=0;
|
||||
if(offset==item.bytes.size()){s.queue.pop_front();s.ack=0;s.begun=false;status="Clipboard delivered.";}
|
||||
return;
|
||||
}
|
||||
for(auto &done:completed[peer])if(done.first==id){ack(done.second);return;}
|
||||
if(op=="begin")
|
||||
{
|
||||
auto size=body.at("size").get<size_t>();auto app=body.value("app","");
|
||||
if(!size||size>Limit||app.size()>128)return;
|
||||
auto found=receiving.find(peer);
|
||||
if(found!=receiving.end()){if(found->second.id==id)ack(found->second.bytes.size());return;}
|
||||
size_t waiting=0;for(auto &d:deliveries)waiting+=d.bytes.size();
|
||||
if(incomingBytes+waiting+size>2*Limit||deliveries.size()>=8)return;
|
||||
receiving.emplace(peer,Receiving{id,app,{},size,now,sequence});incomingBytes+=size;ack(0);return;
|
||||
}
|
||||
if(op!="chunk")return;
|
||||
auto found=receiving.find(peer);if(found==receiving.end()||found->second.id!=id)return;
|
||||
auto &r=found->second;auto offset=body.at("offset").get<size_t>();
|
||||
if(!body.at("bytes").is_binary())return;
|
||||
const auto &bytes=body.at("bytes").get_binary();
|
||||
if(bytes.empty()||bytes.size()>Chunk||offset>r.size||bytes.size()>r.size-offset)return;
|
||||
if(offset==r.bytes.size()){r.bytes.insert(r.bytes.end(),bytes.begin(),bytes.end());r.last=now;}
|
||||
ack(r.bytes.size());
|
||||
if(r.bytes.size()==r.size)
|
||||
{
|
||||
deliveries.push_back({peer,r.id,r.app,std::move(r.bytes),r.sequence});
|
||||
auto &done=completed[peer];done.push_back({id,r.size});if(done.size()>64)done.pop_front();
|
||||
incomingBytes-=r.size;receiving.erase(found);status="Clipboard received.";
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
#include "ocr.h"
|
||||
#include <algorithm>
|
||||
namespace ks::lan
|
||||
{
|
||||
// Send one lossless image, not PNG plus multiple uncompressed DIB copies.
|
||||
inline Clip compactClipboardImage(Clip clip)
|
||||
{
|
||||
auto png=std::find_if(clip.formats.begin(),clip.formats.end(),[](const Format &f){return f.name==L"PNG";});
|
||||
bool image=png!=clip.formats.end()||std::any_of(clip.formats.begin(),clip.formats.end(),[](const Format &f){return f.id==CF_DIB||f.id==CF_DIBV5;});
|
||||
if(!image)return clip;
|
||||
Bytes bytes=png!=clip.formats.end()?png->data:encodePng(decodeImage(clip));
|
||||
std::erase_if(clip.formats,[](const Format &f){return f.id==CF_DIB||f.id==CF_DIBV5||f.name==L"PNG";});
|
||||
clip.formats.push_back({RegisterClipboardFormatW(L"PNG"),L"PNG",std::move(bytes)});
|
||||
return clip;
|
||||
}
|
||||
// Older applications paste DIB rather than PNG; expand only at the destination.
|
||||
inline Clip clipboardImageForPaste(Clip clip)
|
||||
{
|
||||
bool dib=false,png=false;
|
||||
for(const auto &f:clip.formats){dib|=f.id==CF_DIB||f.id==CF_DIBV5;png|=f.name==L"PNG";}
|
||||
if(png&&!dib)clip.formats.push_back(imageDib(decodeImage(clip)));
|
||||
return clip;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
#include "lan_input.h"
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <atomic>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
ULONG_PTR remoteInputMarker(){return inputMarker() ^ ULONG_PTR(0x4c414e49);}
|
||||
ULONG_PTR cursorWarpMarker(){return inputMarker() ^ ULONG_PTR(0x4c414e57);}
|
||||
namespace
|
||||
{
|
||||
uint32_t ownershipToken()
|
||||
{
|
||||
static std::atomic<uint32_t> next{1};
|
||||
auto token=next.fetch_add(1);return token?token:next.fetch_add(1);
|
||||
}
|
||||
HCURSOR parkedCursor()
|
||||
{
|
||||
static HCURSOR cursor=[] {unsigned char mask[128],pixels[128]{};
|
||||
std::fill(std::begin(mask),std::end(mask),0xff);
|
||||
return CreateCursor(GetModuleHandleW(nullptr),0,0,32,32,mask,pixels);}();
|
||||
return cursor;
|
||||
}
|
||||
int monitorDpi(POINT point)
|
||||
{
|
||||
static HMODULE module=LoadLibraryW(L"shcore.dll");
|
||||
using Query=HRESULT(WINAPI *)(HMONITOR,int,UINT*,UINT*);
|
||||
static Query query=module?std::bit_cast<Query>(GetProcAddress(module,"GetDpiForMonitor")):nullptr;
|
||||
UINT x=96,y=96;if(query)query(MonitorFromPoint(point,MONITOR_DEFAULTTONEAREST),0,&x,&y);
|
||||
return int(std::clamp<UINT>(x,48,768));
|
||||
}
|
||||
LRESULT CALLBACK controlOverlay(HWND w,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_NCCREATE)SetWindowLongPtrW(w,GWLP_USERDATA,(LONG_PTR)((CREATESTRUCTW*)lp)->lpCreateParams);
|
||||
if(message==WM_SETCURSOR){SetCursor(GetWindowLongPtrW(w,GWLP_USERDATA)?parkedCursor():LoadCursorW(nullptr,IDC_ARROW));return TRUE;}
|
||||
if(message==WM_MOUSEACTIVATE)return MA_NOACTIVATE;
|
||||
if(message==WM_PAINT)
|
||||
{
|
||||
PAINTSTRUCT paint{};HDC dc=BeginPaint(w,&paint);RECT r{};GetClientRect(w,&r);
|
||||
FillRect(dc,&r,(HBRUSH)(COLOR_INFOBK+1));SetBkMode(dc,TRANSPARENT);SetTextColor(dc,GetSysColor(COLOR_INFOTEXT));
|
||||
auto previous=SelectObject(dc,GetStockObject(DEFAULT_GUI_FONT));
|
||||
DrawTextW(dc,L"KSwitcher: mouse + keyboard on the other PC\nCtrl+Alt+Esc returns control here",-1,&r,DT_CENTER|DT_WORDBREAK);
|
||||
SelectObject(dc,previous);EndPaint(w,&paint);return 0;
|
||||
}
|
||||
return DefWindowProcW(w,message,wp,lp);
|
||||
}
|
||||
struct ControlOverlay
|
||||
{
|
||||
HWND notice{},cover{};HCURSOR previous{};
|
||||
~ControlOverlay(){hide();}
|
||||
void hide(){bool shown=notice||cover;if(cover)DestroyWindow(cover);if(notice)DestroyWindow(notice);notice=cover=nullptr;
|
||||
if(shown)SetCursor(previous?previous:LoadCursorW(nullptr,IDC_ARROW));
|
||||
previous=nullptr;}
|
||||
void show()
|
||||
{
|
||||
if(notice)return;
|
||||
WNDCLASSW cls{};cls.hInstance=GetModuleHandleW(nullptr);cls.lpfnWndProc=controlOverlay;cls.lpszClassName=L"KSwitcher.RemoteControlOverlay";cls.hCursor=LoadCursorW(nullptr,IDC_ARROW);
|
||||
RegisterClassW(&cls);
|
||||
auto style=WS_EX_TOPMOST|WS_EX_TOOLWINDOW|WS_EX_NOACTIVATE;
|
||||
POINT cursor{};GetCursorPos(&cursor);MONITORINFO monitor{sizeof(monitor)};GetMonitorInfoW(MonitorFromPoint(cursor,MONITOR_DEFAULTTONEAREST),&monitor);
|
||||
CURSORINFO ci{sizeof(ci)};if(GetCursorInfo(&ci))previous=ci.hCursor;
|
||||
int size=MulDiv(64,monitorDpi(cursor),96);
|
||||
cover=CreateWindowExW(style|WS_EX_LAYERED,cls.lpszClassName,L"",WS_POPUP,
|
||||
(monitor.rcMonitor.left+monitor.rcMonitor.right-size)/2,(monitor.rcMonitor.top+monitor.rcMonitor.bottom-size)/2,
|
||||
size,size,nullptr,nullptr,cls.hInstance,(void*)1);
|
||||
if(cover){SetLayeredWindowAttributes(cover,0,1,LWA_ALPHA);ShowWindow(cover,SW_SHOWNOACTIVATE);}
|
||||
notice=CreateWindowExW(style,cls.lpszClassName,L"KSwitcher remote control",WS_POPUP,monitor.rcMonitor.left+20,monitor.rcMonitor.top+20,400,48,nullptr,nullptr,cls.hInstance,nullptr);
|
||||
if(notice)ShowWindow(notice,SW_SHOWNOACTIVATE);
|
||||
if(cover)SetCursor(parkedCursor());
|
||||
}
|
||||
};
|
||||
bool ordinaryDesktop()
|
||||
{
|
||||
HDESK d=OpenInputDesktop(0,FALSE,DESKTOP_READOBJECTS);if(!d)return false;
|
||||
wchar_t name[256]{};DWORD count{};bool ok=GetUserObjectInformationW(d,UOI_NAME,name,sizeof(name),&count)!=0;
|
||||
CloseDesktop(d);return ok&&_wcsicmp(name,L"Default")==0;
|
||||
}
|
||||
INPUT button(unsigned index,bool down)
|
||||
{
|
||||
INPUT input{};input.type=INPUT_MOUSE;
|
||||
static constexpr DWORD flags[5][2]={{MOUSEEVENTF_LEFTUP,MOUSEEVENTF_LEFTDOWN},{MOUSEEVENTF_RIGHTUP,MOUSEEVENTF_RIGHTDOWN},
|
||||
{MOUSEEVENTF_MIDDLEUP,MOUSEEVENTF_MIDDLEDOWN},{MOUSEEVENTF_XUP,MOUSEEVENTF_XDOWN},{MOUSEEVENTF_XUP,MOUSEEVENTF_XDOWN}};
|
||||
input.mi.dwFlags=flags[index][down];if(index>=3)input.mi.mouseData=index==3?XBUTTON1:XBUTTON2;return input;
|
||||
}
|
||||
}
|
||||
InputEnvironment windowsInputEnvironment()
|
||||
{
|
||||
auto overlay=std::make_shared<ControlOverlay>();
|
||||
return {
|
||||
[]{LONG x=GetSystemMetrics(SM_XVIRTUALSCREEN),y=GetSystemMetrics(SM_YVIRTUALSCREEN);return RECT{x,y,x+GetSystemMetrics(SM_CXVIRTUALSCREEN),y+GetSystemMetrics(SM_CYVIRTUALSCREEN)};},
|
||||
[]{POINT p{};GetCursorPos(&p);return p;},
|
||||
[](const INPUT &i){INPUT input=i;return SendInput(1,&input,sizeof(input))==1;},
|
||||
ordinaryDesktop,
|
||||
[]{for(int key=1;key<256;++key)if(GetAsyncKeyState(key)&0x8000)return true;return false;},
|
||||
[]{POINT p{};GetCursorPos(&p);MONITORINFO info{sizeof(info)};
|
||||
if(GetMonitorInfoW(MonitorFromPoint(p,MONITOR_DEFAULTTONEAREST),&info))p={(info.rcMonitor.left+info.rcMonitor.right)/2,(info.rcMonitor.top+info.rcMonitor.bottom)/2};
|
||||
return p;},
|
||||
[overlay](ControlMode mode){if(mode==ControlMode::Sending)overlay->show();else overlay->hide();},
|
||||
monitorDpi
|
||||
};
|
||||
}
|
||||
bool atEdge(POINT p,RECT r,int side)
|
||||
{return side==0?p.x<=r.left:side==1?p.x>=r.right-1:side==2?p.y<=r.top:p.y>=r.bottom-1;}
|
||||
int edgePosition(POINT p,RECT r,int side)
|
||||
{
|
||||
auto length=side<2?r.bottom-r.top:r.right-r.left;
|
||||
auto offset=side<2?p.y-r.top:p.x-r.left;
|
||||
return int(std::clamp<int64_t>(int64_t(offset)*65535/std::max<LONG>(1,length-1),0,65535));
|
||||
}
|
||||
POINT edgePoint(RECT r,int side,int position,int inset)
|
||||
{
|
||||
position=std::clamp(position,0,65535);
|
||||
LONG x=r.left+LONG(int64_t(position)*std::max<LONG>(0,r.right-r.left-1)/65535);
|
||||
LONG y=r.top+LONG(int64_t(position)*std::max<LONG>(0,r.bottom-r.top-1)/65535);
|
||||
POINT p=side==0?POINT{r.left+inset,y}:side==1?POINT{r.right-1-inset,y}:side==2?POINT{x,r.top+inset}:POINT{x,r.bottom-1-inset};
|
||||
p.x=std::clamp(p.x,r.left,r.right-1);p.y=std::clamp(p.y,r.top,r.bottom-1);return p;
|
||||
}
|
||||
InputRouter::InputRouter(InputEnvironment e,std::function<bool(InputFrame)> s,int side,bool prefer,bool multiple)
|
||||
:env(std::move(e)),send(std::move(s)),edge(side),preferLocal(prefer),multi(multiple)
|
||||
{if(side<0||side>3)throw std::runtime_error("Invalid screen position.");}
|
||||
InputRouter::~InputRouter(){cancel(GetTickCount64());release();}
|
||||
void InputRouter::mode(ControlMode value){if(mode_!=value){mode_=value;++revision_;if(env.modeChanged&&!(value==ControlMode::Local&&returning)&&!(value==ControlMode::Requesting&&transit))env.modeChanged(value);}}
|
||||
bool InputRouter::emit(INPUT i)
|
||||
{
|
||||
if(i.type==INPUT_KEYBOARD)i.ki.dwExtraInfo=remoteInputMarker();
|
||||
else i.mi.dwExtraInfo=remoteInputMarker();
|
||||
return env.desktop()&&env.inject(i);
|
||||
}
|
||||
bool InputRouter::move(POINT p,bool warp)
|
||||
{
|
||||
auto r=env.bounds();if(r.right<=r.left||r.bottom<=r.top)return false;
|
||||
INPUT input{};input.type=INPUT_MOUSE;input.mi.dwFlags=MOUSEEVENTF_MOVE|MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_VIRTUALDESK;
|
||||
// Target pixel centres, avoiding a one-pixel bias on every relative mouse event.
|
||||
input.mi.dx=LONG((2*int64_t(std::clamp(p.x,r.left,r.right-1)-r.left)+1)*32768/(r.right-r.left));
|
||||
input.mi.dy=LONG((2*int64_t(std::clamp(p.y,r.top,r.bottom-1)-r.top)+1)*32768/(r.bottom-r.top));
|
||||
input.mi.dwExtraInfo=warp?cursorWarpMarker():remoteInputMarker();
|
||||
if(warp&&mode_==ControlMode::Sending)awaitingWarp=true;
|
||||
bool ok=env.desktop()&&env.inject(input);
|
||||
if(!ok)awaitingWarp=false;
|
||||
return ok;
|
||||
}
|
||||
bool InputRouter::post(InputFrame f){return connected&&send(f);}
|
||||
bool InputRouter::held()const
|
||||
{
|
||||
return std::any_of(physical.begin(),physical.end(),[](bool b){return b;})||env.held();
|
||||
}
|
||||
void InputRouter::release()
|
||||
{
|
||||
for(size_t i=0;i<remoteKeys.size();++i)if(remoteKeys[i]&&emit(releases[i]))remoteKeys[i]=false;
|
||||
for(unsigned i=0;i<5;++i)if(remoteButtons[i]&&emit(button(i,false)))remoteButtons[i]=false;
|
||||
}
|
||||
void InputRouter::local(uint64_t now,int position)
|
||||
{
|
||||
bool sending=mode_==ControlMode::Sending||transit;
|
||||
if(position<0)position=edgePosition(returnPoint,env.bounds(),edge);
|
||||
if(sending){returning=true;returnTarget=edgePoint(env.bounds(),edge,position);returnStarted=now;}
|
||||
release();mode(ControlMode::Local);cooldown=now+600;token=0;transit=false;crossEdge=-1;remainderX=remainderY=0;awaitingWarp=awaitingEntry=false;
|
||||
if(sending&&!move(returnTarget,true)){returning=false;if(env.modeChanged)env.modeChanged(ControlMode::Local);}
|
||||
}
|
||||
bool InputRouter::handoff(int side,int position,uint64_t now)
|
||||
{
|
||||
if(!multi||mode_!=ControlMode::Sending||held()||side<0||side>3)return false;
|
||||
edge=side;transit=true;token=ownershipToken();
|
||||
requested=now;mode(ControlMode::Requesting);
|
||||
if(!post({InputType::Enter,token,edge,std::clamp(position,0,65535)})){cancel(now,"next computer unavailable");return false;}
|
||||
return true;
|
||||
}
|
||||
void InputRouter::returnAt(int side,int position,uint64_t now)
|
||||
{
|
||||
if(side>=0&&side<4)edge=side;
|
||||
local(now,std::clamp(position,0,65535));
|
||||
}
|
||||
void InputRouter::cancel(uint64_t now,const char *reason)
|
||||
{
|
||||
if(mode_!=ControlMode::Local)log(L"LAN input: "+wide(reason)+L"; mode="+std::to_wstring(int(mode_)));
|
||||
if(mode_!=ControlMode::Local)post({InputType::Return,token,edgePosition(env.cursor(),env.bounds(),edge)});
|
||||
local(now);
|
||||
}
|
||||
void InputRouter::tick(bool ready,uint64_t now)
|
||||
{
|
||||
if(returning)
|
||||
{
|
||||
auto p=env.cursor();
|
||||
if((p.x==returnTarget.x&&p.y==returnTarget.y)||now-returnStarted>250)
|
||||
{returning=false;if(env.modeChanged)env.modeChanged(ControlMode::Local);}
|
||||
}
|
||||
connected=ready;
|
||||
if(!ready)cancel(now,"channel unavailable");
|
||||
else if(!env.desktop())cancel(now,"input desktop unavailable");
|
||||
else if(mode_==ControlMode::Requesting&&now-requested>1000)cancel(now,"handoff acknowledgement timed out");
|
||||
if(mode_==ControlMode::Sending&&awaitingWarp)
|
||||
{
|
||||
auto p=env.cursor();
|
||||
if(p.x==anchor.x&&p.y==anchor.y)awaitingWarp=false;
|
||||
else if(now-warpStarted>250)cancel(now,"source cursor parking did not complete");
|
||||
}
|
||||
if(mode_==ControlMode::Receiving&&awaitingEntry)
|
||||
{
|
||||
auto p=env.cursor();
|
||||
if(p.x==receivedPoint.x&&p.y==receivedPoint.y)
|
||||
{
|
||||
awaitingEntry=false;
|
||||
if(!post({InputType::Accept,token}))cancel(now,"cannot acknowledge cursor entry");
|
||||
}
|
||||
else if(now-entryStarted>250)cancel(now,"destination cursor entry did not complete");
|
||||
}
|
||||
if(mode_==ControlMode::Local)release(); // Retry releases blocked by a temporarily secure desktop.
|
||||
}
|
||||
void InputRouter::receive(const InputFrame &f,uint64_t now)
|
||||
{
|
||||
if(!connected||!env.desktop()){cancel(now);return;}
|
||||
if(f.type==InputType::Enter)
|
||||
{
|
||||
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535||held()||returning||
|
||||
mode_==ControlMode::Sending||mode_==ControlMode::Receiving||(mode_==ControlMode::Requesting&&preferLocal))
|
||||
{post({InputType::Return,f.token,32768});return;}
|
||||
if(mode_==ControlMode::Requesting)cancel(now);
|
||||
if(multi)edge=f.a^1;
|
||||
crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
|
||||
receivedPoint=edgePoint(env.bounds(),edge,f.b);
|
||||
awaitingEntry=true;entryStarted=now;
|
||||
if(!move(receivedPoint))cancel(now,"destination cursor injection failed");
|
||||
return;
|
||||
}
|
||||
if(f.type==InputType::Accept)
|
||||
{
|
||||
if(mode_!=ControlMode::Requesting||f.token!=token||held()||(!transit&&!atEdge(env.cursor(),env.bounds(),edge))){post({InputType::Return,f.token,32768});if(f.token==token)cancel(now);return;}
|
||||
transit=false;auto r=env.bounds();anchor=env.anchor?env.anchor():POINT{(r.left+r.right)/2,(r.top+r.bottom)/2};mode(ControlMode::Sending);
|
||||
warpStarted=now;
|
||||
if(!move(anchor,true))cancel(now,"source cursor parking failed");
|
||||
return;
|
||||
}
|
||||
if(f.token!=token||!token)return;
|
||||
if(f.type==InputType::Return){log(L"LAN input: peer returned control");local(now,std::clamp(f.a,0,65535));return;}
|
||||
if(mode_!=ControlMode::Receiving)return;
|
||||
bool ok=true;
|
||||
if(f.type==InputType::Move)
|
||||
{
|
||||
if(std::abs(int64_t(f.a))>32768||std::abs(int64_t(f.b))>32768){cancel(now);return;}
|
||||
if(f.c!=0&&(f.c<48||f.c>768)){cancel(now);return;}
|
||||
// SendInput queues movement; GetCursorPos may still describe the old
|
||||
// centre while several network frames are drained in one timer tick.
|
||||
auto p=receivedPoint;auto r=env.bounds();
|
||||
double scale=f.c&&env.dpi?double(std::clamp(env.dpi(p),48,768))/f.c:1.0;
|
||||
double x=f.a*scale+remainderX,y=f.b*scale+remainderY;
|
||||
auto dx=int64_t(x),dy=int64_t(y);remainderX=x-dx;remainderY=y-dy;
|
||||
p.x=LONG(std::clamp<int64_t>(int64_t(p.x)+dx,r.left,r.right-1));p.y=LONG(std::clamp<int64_t>(int64_t(p.y)+dy,r.top,r.bottom-1));
|
||||
if(!multi&&atEdge(p,r,edge)&&!std::any_of(remoteKeys.begin(),remoteKeys.end(),[](bool b){return b;})&&
|
||||
!std::any_of(remoteButtons.begin(),remoteButtons.end(),[](bool b){return b;}))
|
||||
{log(L"LAN input: cursor crossed return edge");post({InputType::Return,token,edgePosition(p,r,edge)});local(now);return;}
|
||||
ok=move(p);if(ok)receivedPoint=p;
|
||||
if(multi&&ok&&!std::any_of(remoteKeys.begin(),remoteKeys.end(),[](bool b){return b;})&&
|
||||
!std::any_of(remoteButtons.begin(),remoteButtons.end(),[](bool b){return b;})){
|
||||
int horizontal=dx<0?0:1,vertical=dy<0?2:3,side=-1;
|
||||
if(std::abs(dy)>std::abs(dx)&&dy&&atEdge(p,r,vertical))side=vertical;
|
||||
else if(dx&&atEdge(p,r,horizontal))side=horizontal;
|
||||
else if(dy&&atEdge(p,r,vertical))side=vertical;
|
||||
if(side>=0&&(side!=crossEdge||now-crossAt>=150)){
|
||||
crossEdge=side;crossAt=now;ok=post({InputType::Cross,token,side,edgePosition(p,r,side)});
|
||||
}else if(side<0)crossEdge=-1;
|
||||
}
|
||||
}
|
||||
else if(f.type==InputType::Key)
|
||||
{
|
||||
if(f.a<1||f.a>255||f.b<0||f.b>255||f.c<0||f.c>3){cancel(now);return;}
|
||||
INPUT input{};input.type=INPUT_KEYBOARD;input.ki.wVk=WORD(f.a);input.ki.wScan=WORD(f.b);
|
||||
input.ki.dwFlags=(f.c&1?0:KEYEVENTF_KEYUP)|(f.c&2?KEYEVENTF_EXTENDEDKEY:0);
|
||||
bool modifier=f.a==VK_SHIFT||f.a==VK_CONTROL||f.a==VK_MENU||
|
||||
(f.a>=VK_LSHIFT&&f.a<=VK_RMENU)||f.a==VK_LWIN||f.a==VK_RWIN;
|
||||
// Explicit modifier VKs preserve their Windows state independently of
|
||||
// the sending keyboard's scan-code mapping. Text keys remain physical.
|
||||
if(f.b&&f.a!=VK_PAUSE&&!modifier)input.ki.dwFlags|=KEYEVENTF_SCANCODE;
|
||||
ok=emit(input);if(ok){remoteKeys[size_t(f.a)]=(f.c&1)!=0;input.ki.dwFlags|=KEYEVENTF_KEYUP;releases[size_t(f.a)]=input;}
|
||||
}
|
||||
else if(f.type==InputType::Button)
|
||||
{
|
||||
if(f.a<0||f.a>4||f.b<0||f.b>1){cancel(now);return;}
|
||||
ok=emit(button(unsigned(f.a),f.b!=0));if(ok)remoteButtons[size_t(f.a)]=f.b!=0;
|
||||
}
|
||||
else if(f.type==InputType::Wheel)
|
||||
{
|
||||
if(f.a<-32768||f.a>32767||f.b<0||f.b>1){cancel(now);return;}
|
||||
INPUT input{};input.type=INPUT_MOUSE;input.mi.dwFlags=f.b?MOUSEEVENTF_HWHEEL:MOUSEEVENTF_WHEEL;input.mi.mouseData=DWORD(f.a);ok=emit(input);
|
||||
}
|
||||
if(!ok)cancel(now,"Windows input injection failed");
|
||||
}
|
||||
bool InputRouter::keyboard(const KBDLLHOOKSTRUCT &k,bool down,uint64_t now)
|
||||
{
|
||||
// Conversion/layout changes can produce synthetic modifier releases.
|
||||
// Never reinterpret our own tagged input as a physical takeover, even if
|
||||
// another hook has changed the injection flag.
|
||||
if(k.flags&LLKHF_INJECTED||k.dwExtraInfo==inputMarker()||
|
||||
k.dwExtraInfo==remoteInputMarker()||k.vkCode>255||!k.vkCode)return false;
|
||||
auto key=size_t(k.vkCode);physical[key]=down;
|
||||
if(mode_!=ControlMode::Local&&down&&key==VK_ESCAPE&&(physical[VK_LCONTROL]||physical[VK_RCONTROL]||physical[VK_CONTROL])&&
|
||||
(physical[VK_LMENU]||physical[VK_RMENU]||physical[VK_MENU]))
|
||||
{outKeys[key]=true;cancel(now);return true;}
|
||||
// A real local press takes over. A key-up alone is not evidence of intent:
|
||||
// Windows may generate it while changing the target keyboard layout.
|
||||
if(down&&(mode_==ControlMode::Receiving||mode_==ControlMode::Requesting))cancel(now,"local physical keyboard takeover");
|
||||
if(mode_==ControlMode::Sending)
|
||||
{
|
||||
outKeys[key]=down;
|
||||
if(!post({InputType::Key,token,int32_t(k.vkCode),int32_t(k.scanCode),int32_t((down?1:0)|((k.flags&LLKHF_EXTENDED)?2:0))}))cancel(now);
|
||||
return true;
|
||||
}
|
||||
if(outKeys[key]){if(!down)outKeys[key]=false;return true;}
|
||||
return false;
|
||||
}
|
||||
bool InputRouter::mouse(UINT message,const MSLLHOOKSTRUCT &m,uint64_t now,bool allowEnter)
|
||||
{
|
||||
if((m.flags&LLMHF_INJECTED)&&m.dwExtraInfo==cursorWarpMarker())
|
||||
{awaitingWarp=false;return false;}
|
||||
if(m.flags&LLMHF_INJECTED)return false;
|
||||
if(returning&&message==WM_MOUSEMOVE)return true;
|
||||
int index=-1;bool down=false;
|
||||
switch(message){case WM_LBUTTONDOWN:down=true;[[fallthrough]];case WM_LBUTTONUP:index=0;break;
|
||||
case WM_RBUTTONDOWN:down=true;[[fallthrough]];case WM_RBUTTONUP:index=1;break;
|
||||
case WM_MBUTTONDOWN:down=true;[[fallthrough]];case WM_MBUTTONUP:index=2;break;
|
||||
case WM_XBUTTONDOWN:down=true;[[fallthrough]];case WM_XBUTTONUP:index=HIWORD(m.mouseData)==XBUTTON1?3:4;break;}
|
||||
if(mode_==ControlMode::Receiving&&message==WM_MOUSEMOVE)
|
||||
{
|
||||
if(m.pt.x==receivedPoint.x&&m.pt.y==receivedPoint.y)return false;
|
||||
}
|
||||
if(mode_==ControlMode::Receiving||(mode_==ControlMode::Requesting&&message!=WM_MOUSEMOVE))cancel(now,"local physical mouse takeover");
|
||||
if(mode_==ControlMode::Requesting&&!transit&&message==WM_MOUSEMOVE&&!atEdge(m.pt,env.bounds(),edge))cancel(now);
|
||||
if(mode_==ControlMode::Requesting&&transit&&message==WM_MOUSEMOVE)return true;
|
||||
if(mode_==ControlMode::Sending)
|
||||
{
|
||||
bool ok=true;
|
||||
if(message==WM_MOUSEMOVE)
|
||||
{
|
||||
// Do not interpret pre-warp edge coordinates as a huge delta from
|
||||
// the centre before Windows has actually parked the cursor.
|
||||
if(awaitingWarp)return true;
|
||||
auto dx=m.pt.x-anchor.x,dy=m.pt.y-anchor.y;
|
||||
if(dx||dy)ok=post({InputType::Move,token,dx,dy,env.dpi?std::clamp(env.dpi(anchor),48,768):0});
|
||||
// The hook consumes this physical motion, so Windows keeps the
|
||||
// cursor parked. Re-injecting an identical warp here can yield no
|
||||
// notification and must never become a gate for the next movement.
|
||||
}
|
||||
else if(index>=0){outButtons[size_t(index)]=down;ok=post({InputType::Button,token,index,down?1:0});}
|
||||
else if(message==WM_MOUSEWHEEL||message==WM_MOUSEHWHEEL)ok=post({InputType::Wheel,token,int16_t(HIWORD(m.mouseData)),message==WM_MOUSEHWHEEL?1:0});
|
||||
if(!ok)cancel(now);
|
||||
return true;
|
||||
}
|
||||
if(index>=0&&outButtons[size_t(index)]){if(!down)outButtons[size_t(index)]=false;return true;}
|
||||
if(mode_==ControlMode::Local&&connected&&allowEnter&&message==WM_MOUSEMOVE&&now>=cooldown&&
|
||||
env.desktop()&&!held()&&atEdge(m.pt,env.bounds(),edge))
|
||||
{
|
||||
token=ownershipToken();
|
||||
returnPoint=m.pt;requested=now;mode(ControlMode::Requesting);
|
||||
if(!post({InputType::Enter,token,edge,edgePosition(m.pt,env.bounds(),edge)}))cancel(now);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
#include "lan_channel.h"
|
||||
#include <array>
|
||||
namespace ks::lan
|
||||
{
|
||||
enum class ControlMode { Local, Requesting, Sending, Receiving };
|
||||
struct InputEnvironment
|
||||
{
|
||||
std::function<RECT()> bounds;
|
||||
std::function<POINT()> cursor;
|
||||
std::function<bool(const INPUT &)> inject;
|
||||
std::function<bool()> desktop;
|
||||
std::function<bool()> held;
|
||||
std::function<POINT()> anchor;
|
||||
std::function<void(ControlMode)> modeChanged;
|
||||
std::function<int(POINT)> dpi;
|
||||
};
|
||||
InputEnvironment windowsInputEnvironment();
|
||||
ULONG_PTR remoteInputMarker();
|
||||
ULONG_PTR cursorWarpMarker();
|
||||
bool atEdge(POINT,RECT,int edge);
|
||||
int edgePosition(POINT,RECT,int edge);
|
||||
POINT edgePoint(RECT,int edge,int position,int inset=8);
|
||||
class InputRouter
|
||||
{
|
||||
InputEnvironment env;
|
||||
std::function<bool(InputFrame)> send;
|
||||
ControlMode mode_=ControlMode::Local;
|
||||
int edge{};bool preferLocal{},connected{},multi{},transit{};
|
||||
int crossEdge=-1;uint64_t crossAt{};
|
||||
uint32_t token{};
|
||||
uint64_t cooldown{},requested{},revision_{};
|
||||
POINT anchor{},returnPoint{},receivedPoint{};
|
||||
bool awaitingWarp{},awaitingEntry{};
|
||||
uint64_t warpStarted{},entryStarted{};
|
||||
bool returning{};POINT returnTarget{};uint64_t returnStarted{};
|
||||
double remainderX{},remainderY{};
|
||||
std::array<bool,256> physical{},outKeys{},remoteKeys{};
|
||||
std::array<INPUT,256> releases{};
|
||||
std::array<bool,5> outButtons{},remoteButtons{};
|
||||
void mode(ControlMode);
|
||||
bool emit(INPUT);
|
||||
bool move(POINT,bool warp=false);
|
||||
bool post(InputFrame);
|
||||
bool held() const;
|
||||
void release();
|
||||
void local(uint64_t now,int position=-1);
|
||||
public:
|
||||
InputRouter(InputEnvironment,std::function<bool(InputFrame)>,int edge,bool preferLocal,bool multi=false);
|
||||
~InputRouter();
|
||||
void selectEdge(int side,bool prefer){edge=side;preferLocal=prefer;}
|
||||
uint32_t sessionToken()const{return token;}
|
||||
bool canHandoff()const{return mode_==ControlMode::Sending&&!held();}
|
||||
bool handoff(int side,int position,uint64_t now);
|
||||
void returnAt(int side,int position,uint64_t now);
|
||||
ControlMode mode()const{return mode_;}
|
||||
uint64_t revision()const{return revision_;}
|
||||
void tick(bool ready,uint64_t now);
|
||||
void receive(const InputFrame &,uint64_t now);
|
||||
bool keyboard(const KBDLLHOOKSTRUCT &,bool down,uint64_t now);
|
||||
bool mouse(UINT,const MSLLHOOKSTRUCT &,uint64_t now,bool allowEnter=true);
|
||||
void cancel(uint64_t now,const char *reason="control cancelled");
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
#include "lan_pairing.h"
|
||||
#include <set>
|
||||
namespace ks::lan
|
||||
{
|
||||
inline Json edgeCell(int edge)
|
||||
{
|
||||
switch(edge){case 0:return Json::array({-1,0});case 1:return Json::array({1,0});case 2:return Json::array({0,-1});default:return Json::array({0,1});}
|
||||
}
|
||||
inline int cellEdge(const Json &cell)
|
||||
{
|
||||
for(int edge=0;edge<4;++edge)if(cell==edgeCell(edge))return edge;
|
||||
return -1;
|
||||
}
|
||||
inline void validateCell(const Json &positions,const std::string &peer,int x,int y)
|
||||
{
|
||||
if(x < -8||x > 8||y < -8||y > 8)throw std::runtime_error("Keep computers within the layout grid.");
|
||||
if(!x&&!y)throw std::runtime_error("This cell belongs to this computer.");
|
||||
for(auto &[id,cell]:positions.items())if(id!=peer&&cell==Json::array({x,y}))throw std::runtime_error("Another computer already occupies this cell.");
|
||||
}
|
||||
inline void fillPositions(Json &positions,const Json &trusted,const std::string &active,int edge)
|
||||
{
|
||||
if(!positions.is_object())throw std::runtime_error("Invalid computer layout.");
|
||||
for(auto it=positions.begin();it!=positions.end();)if(!trusted.contains(it.key()))it=positions.erase(it);else ++it;
|
||||
for(auto &[peer,cell]:positions.items()){
|
||||
if(!cell.is_array()||cell.size()!=2||!cell[0].is_number_integer()||!cell[1].is_number_integer())throw std::runtime_error("Invalid computer position.");
|
||||
validateCell(positions,peer,cell[0].get<int>(),cell[1].get<int>());
|
||||
}
|
||||
if(trusted.contains(active)&&!positions.contains(active)){
|
||||
auto cell=edgeCell(edge);bool free=true;for(auto &[peer,other]:positions.items())if(other==cell)free=false;
|
||||
if(free)positions[active]=cell;
|
||||
}
|
||||
for(auto &[peer,value]:trusted.items())if(!positions.contains(peer)){
|
||||
bool placed=false;
|
||||
for(int radius=1;radius<=8&&!placed;++radius)for(int y=-radius;y<=radius&&!placed;++y)for(int x=-radius;x<=radius&&!placed;++x){
|
||||
if(std::abs(x)+std::abs(y)!=radius)continue;
|
||||
bool free=true;for(auto &[id,cell]:positions.items())if(cell==Json::array({x,y}))free=false;
|
||||
if(free){positions[peer]=Json::array({x,y});placed=true;}
|
||||
}
|
||||
if(!placed)throw std::runtime_error("Computer layout is full.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
#include "lan_input.h"
|
||||
#include <map>
|
||||
namespace ks::lan
|
||||
{
|
||||
// The physical input source routes directly to the current destination. A
|
||||
// destination only reports edge crossings; it never relays injected key events.
|
||||
class InputMesh
|
||||
{
|
||||
std::string local,active;
|
||||
InputEnvironment env;
|
||||
std::map<std::string,POINT> positions;
|
||||
std::map<std::string,uint64_t> ready;
|
||||
std::function<bool(const std::string &,InputFrame)> send;
|
||||
uint64_t activeGeneration{},routeRevision{};
|
||||
InputRouter router;
|
||||
std::string neighbor(const std::string &from,int side)const
|
||||
{
|
||||
POINT p{};if(from!=local){auto found=positions.find(from);if(found==positions.end())return {};p=found->second;}
|
||||
if(side==0)--p.x;else if(side==1)++p.x;else if(side==2)--p.y;else if(side==3)++p.y;else return {};
|
||||
if(!p.x&&!p.y)return local;
|
||||
for(auto &[id,cell]:positions)if(cell.x==p.x&&cell.y==p.y)return id;
|
||||
return {};
|
||||
}
|
||||
void select(const std::string &peer,int side,uint64_t now)
|
||||
{
|
||||
if(active!=peer){active=peer;++routeRevision;}
|
||||
activeGeneration=ready.at(peer);router.selectEdge(side,local<peer);router.tick(true,now);
|
||||
}
|
||||
public:
|
||||
InputMesh(std::string id,InputEnvironment environment,std::map<std::string,POINT> layout,
|
||||
std::function<bool(const std::string &,InputFrame)> sender)
|
||||
:local(std::move(id)),env(std::move(environment)),positions(std::move(layout)),send(std::move(sender)),
|
||||
router(env,[this](InputFrame f){return !active.empty()&&ready.contains(active)&&send(active,f);},1,true,true){}
|
||||
ControlMode mode()const{return router.mode();}
|
||||
uint64_t revision()const{return router.revision()+routeRevision;}
|
||||
const std::string &peer()const{return active;}
|
||||
void cancel(uint64_t now){router.cancel(now);}
|
||||
void tick(std::map<std::string,uint64_t> connections,uint64_t now)
|
||||
{
|
||||
ready=std::move(connections);
|
||||
if(!active.empty()){
|
||||
bool connected=ready.contains(active);
|
||||
if(connected&&activeGeneration!=ready.at(active)){router.cancel(now,"peer reconnected");activeGeneration=ready.at(active);}
|
||||
router.tick(connected,now);
|
||||
}
|
||||
}
|
||||
void receive(const std::string &peer,const InputFrame &f,uint64_t now,bool allowEnter=true)
|
||||
{
|
||||
if(!ready.contains(peer)||!positions.contains(peer))return;
|
||||
if(f.type==InputType::Enter){
|
||||
if(!allowEnter||f.a<0||f.a>3||(router.mode()!=ControlMode::Local&&active!=peer)){
|
||||
send(peer,{InputType::Return,f.token,32768});return;
|
||||
}
|
||||
if(router.mode()==ControlMode::Local)select(peer,f.a^1,now);
|
||||
}
|
||||
if(active!=peer)return;
|
||||
if(f.type==InputType::Cross){
|
||||
if(f.token!=router.sessionToken()||!router.canHandoff()||f.a<0||f.a>3||f.b<0||f.b>65535)return;
|
||||
auto target=neighbor(peer,f.a);
|
||||
if(target.empty()||(target!=local&&!ready.contains(target)))return;
|
||||
if(!send(peer,{InputType::Return,f.token,f.b})){router.cancel(now,"cannot release previous computer");return;}
|
||||
if(target==local){router.returnAt(f.a^1,f.b,now);++routeRevision;return;}
|
||||
active=target;activeGeneration=ready.at(target);++routeRevision;
|
||||
router.handoff(f.a,f.b,now);return;
|
||||
}
|
||||
router.receive(f,now);
|
||||
}
|
||||
bool keyboard(const KBDLLHOOKSTRUCT &key,bool down,uint64_t now){return router.keyboard(key,down,now);}
|
||||
bool mouse(UINT message,const MSLLHOOKSTRUCT &mouse,uint64_t now,bool allowEnter=true)
|
||||
{
|
||||
bool enter=false;
|
||||
if(router.mode()==ControlMode::Local&&allowEnter&&message==WM_MOUSEMOVE&&!(mouse.flags&LLMHF_INJECTED)){
|
||||
for(int side=0;side<4;++side)if(atEdge(mouse.pt,env.bounds(),side)){
|
||||
auto target=neighbor(local,side);
|
||||
if(!target.empty()&&ready.contains(target)){select(target,side,now);enter=true;break;}
|
||||
}
|
||||
}
|
||||
return router.mouse(message,mouse,now,enter);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
#include "lan_pairing.h"
|
||||
#include <bcrypt.h>
|
||||
#include <algorithm>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
namespace
|
||||
{
|
||||
void checked(NTSTATUS s) { if (s < 0) throw std::runtime_error("Windows cryptography failed."); }
|
||||
std::string hex(const Bytes &data)
|
||||
{
|
||||
std::string out; out.reserve(data.size()*2);
|
||||
for (auto b : data) { out += "0123456789abcdef"[b>>4]; out += "0123456789abcdef"[b&15]; }
|
||||
return out;
|
||||
}
|
||||
std::string proof(const char *kind, const std::string &from, const std::string &to,
|
||||
const std::string &a, const std::string &b = {})
|
||||
{ return std::string("KSwitcher LAN v1|") + kind + "|" + from + "|" + to + "|" + a + "|" + b; }
|
||||
}
|
||||
std::string randomHex(size_t size)
|
||||
{
|
||||
if (size > 64) throw std::runtime_error("Invalid random size.");
|
||||
Bytes bytes(size); checked(BCryptGenRandom(nullptr, bytes.data(), ULONG(size), BCRYPT_USE_SYSTEM_PREFERRED_RNG));
|
||||
return hex(bytes);
|
||||
}
|
||||
bool identifier(const std::string &s)
|
||||
{ return s.size()==32 && s.find_first_not_of("0123456789abcdef")==s.npos; }
|
||||
std::string normalizeCode(const std::string &input)
|
||||
{
|
||||
std::string result;
|
||||
for (auto c : input)
|
||||
{
|
||||
if (c=='-' || c==' ') continue;
|
||||
if (c>='A' && c<='F') c+= 'a'-'A';
|
||||
result+=c;
|
||||
}
|
||||
if (!identifier(result)) throw std::runtime_error("Use the same generated 32-character pairing code on both computers.");
|
||||
return result;
|
||||
}
|
||||
std::string mac(const std::string &key, const std::string &text)
|
||||
{
|
||||
BCRYPT_ALG_HANDLE alg{}; BCRYPT_HASH_HANDLE hash{};
|
||||
checked(BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, nullptr, BCRYPT_ALG_HANDLE_HMAC_FLAG));
|
||||
struct Close { BCRYPT_ALG_HANDLE a; BCRYPT_HASH_HANDLE &h; ~Close(){if(h) BCryptDestroyHash(h); BCryptCloseAlgorithmProvider(a,0);} } close{alg,hash};
|
||||
checked(BCryptCreateHash(alg,&hash,nullptr,0,(PUCHAR)key.data(),ULONG(key.size()),0));
|
||||
checked(BCryptHashData(hash,(PUCHAR)text.data(),ULONG(text.size()),0));
|
||||
Bytes out(32); checked(BCryptFinishHash(hash,out.data(),ULONG(out.size()),0)); return hex(out);
|
||||
}
|
||||
bool equal(const std::string &a, const std::string &b)
|
||||
{
|
||||
if (a.size()!=b.size()) return false;
|
||||
unsigned diff=0; for(size_t i=0;i<a.size();++i) diff |= unsigned(a[i]^b[i]); return diff==0;
|
||||
}
|
||||
Json envelope(const std::string &type, const std::string &id)
|
||||
{ return {{"app","KSwitcher-LAN"},{"version",1},{"type",type},{"id",id}}; }
|
||||
Pairing::Pairing(std::string a,std::string b,const std::string &key,uint64_t now)
|
||||
: local(std::move(a)),peer(std::move(b)),code(normalizeCode(key)),nonce(randomHex(16)),started(now)
|
||||
{
|
||||
if(!identifier(local)||!identifier(peer)||local==peer) throw std::runtime_error("Invalid KSwitcher peer.");
|
||||
}
|
||||
bool Pairing::expired(uint64_t now) const { return now-started >= PairLifetime; }
|
||||
Json Pairing::offer() const
|
||||
{
|
||||
auto j=envelope("offer",local); j["to"]=peer; j["nonce"]=nonce;
|
||||
j["proof"]=mac(code,proof("offer",local,peer,nonce)); return j;
|
||||
}
|
||||
std::vector<Json> Pairing::receive(const Json &j,uint64_t now)
|
||||
{
|
||||
if(expired(now)||j.value("app","")!="KSwitcher-LAN"||j.value("version",0)!=1||
|
||||
j.value("id","")!=peer||j.value("to","")!=local) return {};
|
||||
auto type=j.value("type",""); auto other=j.value("nonce","");
|
||||
if(!identifier(other)) return {};
|
||||
if(type=="offer")
|
||||
{
|
||||
if(!equal(j.value("proof",""),mac(code,proof("offer",peer,local,other)))) return {};
|
||||
// A new attempt cannot replace a nonce already authenticated in this attempt.
|
||||
if(!remoteNonce.empty() && remoteNonce!=other) return {};
|
||||
remoteNonce=other;
|
||||
derived=local<peer ? mac(code,proof("key",local,peer,nonce,other)) : mac(code,proof("key",peer,local,other,nonce));
|
||||
auto ack=envelope("ack",local); ack["to"]=peer; ack["nonce"]=nonce; ack["echo"]=other;
|
||||
ack["proof"]=mac(code,proof("ack",local,peer,other,nonce)); return {ack};
|
||||
}
|
||||
if(type=="ack" && j.value("echo","")==nonce)
|
||||
{
|
||||
if(!equal(j.value("proof",""),mac(code,proof("ack",peer,local,nonce,other)))) return {};
|
||||
if(!remoteNonce.empty()&&remoteNonce!=other) return {};
|
||||
remoteNonce=other;
|
||||
derived=local<peer ? mac(code,proof("key",local,peer,nonce,other)) : mac(code,proof("key",peer,local,other,nonce));
|
||||
acknowledged=true;
|
||||
auto done=envelope("confirm",local); done["to"]=peer; done["nonce"]=nonce;
|
||||
done["proof"]=mac(derived,proof("confirm",local,peer,nonce,other)); return {done};
|
||||
}
|
||||
if(type=="confirm" && acknowledged && other==remoteNonce &&
|
||||
equal(j.value("proof",""),mac(derived,proof("confirm",peer,local,other,nonce)))) confirmed=true;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
#include "platform.h"
|
||||
#include "../vendor/json.hpp"
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
using Json = nlohmann::json;
|
||||
inline constexpr unsigned Port = 45883;
|
||||
inline constexpr uint64_t PairLifetime = 120000, PeerLifetime = 12000;
|
||||
std::string randomHex(size_t bytes);
|
||||
std::string normalizeCode(const std::string &);
|
||||
std::string mac(const std::string &key, const std::string &text);
|
||||
bool equal(const std::string &, const std::string &);
|
||||
bool identifier(const std::string &);
|
||||
Json envelope(const std::string &type, const std::string &id);
|
||||
struct Pairing
|
||||
{
|
||||
std::string local, peer, code, nonce, remoteNonce, derived;
|
||||
uint64_t started{};
|
||||
bool acknowledged{}, confirmed{};
|
||||
Pairing(std::string local, std::string peer, const std::string &code, uint64_t now);
|
||||
bool expired(uint64_t now) const;
|
||||
Json offer() const;
|
||||
std::vector<Json> receive(const Json &, uint64_t now);
|
||||
};
|
||||
}
|
||||
@@ -1,12 +1,27 @@
|
||||
#include "app.h"
|
||||
#include <shellapi.h>
|
||||
#include <shlobj.h>
|
||||
#include "configuration.h"
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||
{
|
||||
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
int argc{};
|
||||
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
|
||||
std::wstring arg = argc > 1 ? argv[1] : L"";
|
||||
if (argc == 2 && arg.starts_with(L"--history-host=")) {
|
||||
LocalFree(argv);
|
||||
int result = 1;
|
||||
try {
|
||||
auto service = reinterpret_cast<HWND>(uintptr_t(std::stoull(arg.substr(15))));
|
||||
wchar_t name[64]{}; GetClassNameW(service, name, 64);
|
||||
if (std::wstring(name) != L"KSwitcher.Main" || !ks::configurationPeer(service, L"KSwitcher.exe"))
|
||||
throw std::runtime_error("Invalid history service");
|
||||
ks::App app(instance, true, {}, service);
|
||||
result = app.execute();
|
||||
} catch (...) {}
|
||||
CoUninitialize();
|
||||
return result;
|
||||
}
|
||||
if (arg.starts_with(L"--configure-autostart="))
|
||||
{
|
||||
int result = 1;
|
||||
@@ -72,6 +87,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||
try
|
||||
{
|
||||
ks::App app(instance, arg == L"--smoke-test");
|
||||
app.isolateHistory = !app.smoke;
|
||||
if (arg.starts_with(L"--update-ready-event="))
|
||||
app.updateStartupEvent = arg.substr(std::wstring(L"--update-ready-event=").size());
|
||||
else if (!arg.empty() && arg != L"--smoke-test")
|
||||
|
||||
+11
-6
@@ -123,13 +123,16 @@ struct OcrStatics : IInspectable
|
||||
Pixels decodeImage(const Clip &clip, UINT maxWidth, UINT maxHeight)
|
||||
{
|
||||
Bytes encoded;
|
||||
const Bytes *input = &encoded;
|
||||
for (const auto &f : clip.formats)
|
||||
if (f.name == L"PNG")
|
||||
{
|
||||
encoded = f.data;
|
||||
input = &f.data;
|
||||
break;
|
||||
}
|
||||
if (encoded.empty())
|
||||
if (input->empty())
|
||||
{
|
||||
input = &encoded;
|
||||
for (const auto &f : clip.formats)
|
||||
if ((f.id == CF_DIB || f.id == CF_DIBV5) && f.data.size() >= 40)
|
||||
{
|
||||
@@ -146,19 +149,21 @@ Pixels decodeImage(const Clip &clip, UINT maxWidth, UINT maxHeight)
|
||||
file.bfType = 0x4d42;
|
||||
file.bfSize = (DWORD)(sizeof(file) + f.data.size());
|
||||
file.bfOffBits = (DWORD)offset;
|
||||
encoded.resize(sizeof(file));
|
||||
encoded.resize(sizeof(file) + f.data.size());
|
||||
memcpy(encoded.data(), &file, sizeof(file));
|
||||
encoded.insert(encoded.end(), f.data.begin(), f.data.end());
|
||||
memcpy(encoded.data() + sizeof(file), f.data.data(), f.data.size());
|
||||
break;
|
||||
}
|
||||
if (encoded.empty())
|
||||
}
|
||||
if (input->empty())
|
||||
throw std::runtime_error("This clipboard item has no supported image");
|
||||
Com<IWICImagingFactory> wic;
|
||||
check(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory,
|
||||
(void **)wic.out()));
|
||||
Com<IWICStream> stream;
|
||||
check(wic->CreateStream(stream.out()));
|
||||
check(stream->InitializeFromMemory(encoded.data(), (DWORD)encoded.size()));
|
||||
// WIC decoding only reads the stream. The clip outlives every WIC object here.
|
||||
check(stream->InitializeFromMemory(const_cast<BYTE *>(input->data()), (DWORD)input->size()));
|
||||
Com<IWICBitmapDecoder> decoder;
|
||||
check(wic->CreateDecoderFromStream(stream.p, nullptr, WICDecodeMetadataCacheOnLoad, decoder.out()));
|
||||
Com<IWICBitmapFrameDecode> frame;
|
||||
|
||||
+18
-1
@@ -13,7 +13,7 @@ class PasteProbe
|
||||
|
||||
public:
|
||||
std::wstring status = L"not-requested";
|
||||
PasteProbe(bool enabled, const std::wstring &original)
|
||||
PasteProbe(bool enabled, HWND target)
|
||||
{
|
||||
if (!enabled)
|
||||
return;
|
||||
@@ -25,6 +25,18 @@ class PasteProbe
|
||||
automation->put_TransactionTimeout(200);
|
||||
if (FAILED(automation->GetFocusedElement(&element)) || !element)
|
||||
return;
|
||||
if (target)
|
||||
{
|
||||
DWORD process{};
|
||||
GetWindowThreadProcessId(target, &process);
|
||||
int focusedProcess{};
|
||||
if (!process || FAILED(element->get_CurrentProcessId(&focusedProcess)) ||
|
||||
process != static_cast<DWORD>(focusedProcess) || GetForegroundWindow() != target)
|
||||
{
|
||||
status = L"focused-control-changed";
|
||||
return;
|
||||
}
|
||||
}
|
||||
BOOL password = TRUE;
|
||||
if (FAILED(element->get_CurrentIsPassword(&password)) || password)
|
||||
{
|
||||
@@ -35,6 +47,11 @@ class PasteProbe
|
||||
(void **)&pattern)) ||
|
||||
!pattern)
|
||||
return;
|
||||
}
|
||||
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr)
|
||||
: PasteProbe(enabled, target)
|
||||
{
|
||||
if (!pattern) return;
|
||||
auto selected = read(1, false);
|
||||
auto normalize = [](std::wstring value)
|
||||
{
|
||||
|
||||
+62
-7
@@ -159,6 +159,31 @@ void showRequestedWindow(HWND window)
|
||||
if (!IsWindowVisible(window))
|
||||
ShowWindow(window, SW_SHOW);
|
||||
}
|
||||
void showMenuAccessKeys(HMENU menu)
|
||||
{
|
||||
// Mouse-opened popups ignore the owner's keyboard-cue state.
|
||||
// Preserve the mnemonic and expose it in the right-hand hint column.
|
||||
for (int i = 0; i < GetMenuItemCount(menu); ++i)
|
||||
{
|
||||
if (auto child = GetSubMenu(menu, i)) showMenuAccessKeys(child);
|
||||
int length = GetMenuStringW(menu, i, nullptr, 0, MF_BYPOSITION);
|
||||
std::wstring text(length + 1, L'\0');
|
||||
GetMenuStringW(menu, i, text.data(), (int)text.size(), MF_BYPOSITION);
|
||||
text.resize(length);
|
||||
if (text.find(L'\t') != text.npos) continue;
|
||||
for (size_t p = 0; p + 1 < text.size(); ++p)
|
||||
{
|
||||
if (text[p] != L'&') continue;
|
||||
if (text[p + 1] == L'&') { ++p; continue; }
|
||||
text += L"\t" + upper(text.substr(p + 1, 1));
|
||||
MENUITEMINFOW item{sizeof(item)};
|
||||
item.fMask = MIIM_STRING;
|
||||
item.dwTypeData = text.data();
|
||||
SetMenuItemInfoW(menu, i, TRUE, &item);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool activateWindow(HWND window)
|
||||
{
|
||||
if (!IsWindow(window))
|
||||
@@ -240,15 +265,27 @@ std::wstring processName(HWND window)
|
||||
CloseHandle(h);
|
||||
return ok ? std::filesystem::path(std::wstring(path, n)).stem().wstring() : L"";
|
||||
}
|
||||
Clip readClipboard(HWND window, size_t limit)
|
||||
Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<DWORD> expected)
|
||||
{
|
||||
ClipboardLock lock(window);
|
||||
if (expected && *expected != GetClipboardSequenceNumber())
|
||||
throw std::runtime_error("Clipboard changed while taking snapshot");
|
||||
if (mode == ClipboardRead::WithoutImages &&
|
||||
(IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
|
||||
IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))))
|
||||
throw std::runtime_error("Clipboard changed to an image");
|
||||
Clip c;
|
||||
size_t total = 0;
|
||||
for (UINT f = EnumClipboardFormats(0); f; f = EnumClipboardFormats(f))
|
||||
{
|
||||
if (!globalFormat(f))
|
||||
continue;
|
||||
wchar_t name[256]{};
|
||||
if (f >= 0xc000) GetClipboardFormatNameW(f, name, 256);
|
||||
if (mode == ClipboardRead::Selection && f != CF_UNICODETEXT &&
|
||||
std::wstring_view(name) != L"VisualStudioEditorOperationsLineCutCopyClipboardTag" &&
|
||||
std::wstring_view(name) != L"MSDEVLineSelect" && std::wstring_view(name) != L"vscode-editor-data")
|
||||
continue;
|
||||
HANDLE handle = GetClipboardData(f);
|
||||
if (!handle)
|
||||
continue;
|
||||
@@ -266,8 +303,6 @@ Clip readClipboard(HWND window, size_t limit)
|
||||
GlobalUnlock(handle);
|
||||
if (f >= 0xc000)
|
||||
{
|
||||
wchar_t name[256]{};
|
||||
GetClipboardFormatNameW(f, name, 256);
|
||||
format.name = name;
|
||||
}
|
||||
total += size;
|
||||
@@ -275,7 +310,8 @@ Clip readClipboard(HWND window, size_t limit)
|
||||
}
|
||||
return c;
|
||||
}
|
||||
DWORD writeClipboard(HWND window, const Clip &c)
|
||||
DWORD writeClipboard(HWND window, const Clip &c) { return writeClipboardGuarded(window, c, {}); }
|
||||
DWORD writeClipboardGuarded(HWND window, const Clip &c, std::optional<DWORD> expected)
|
||||
{
|
||||
// Allocate all blocks before replacing any existing data.
|
||||
std::vector<std::pair<UINT, HGLOBAL>> blocks;
|
||||
@@ -302,6 +338,8 @@ DWORD writeClipboard(HWND window, const Clip &c)
|
||||
blocks.emplace_back(id, h);
|
||||
}
|
||||
ClipboardLock lock(window);
|
||||
if (expected && *expected != GetClipboardSequenceNumber())
|
||||
throw std::runtime_error("Clipboard changed before restoring snapshot");
|
||||
if (!EmptyClipboard())
|
||||
throw std::runtime_error("Cannot replace clipboard");
|
||||
for (auto &[id, h] : blocks)
|
||||
@@ -397,7 +435,7 @@ bool needsSelectionDelay(HWND target)
|
||||
{
|
||||
const auto name = lower(processName(target));
|
||||
return name == L"ms-teams" || name == L"msedgewebview2" ||
|
||||
name == L"chrome" || name == L"msedge";
|
||||
name == L"chrome" || name == L"msedge" || name == L"chatgpt" || name == L"codex";
|
||||
}
|
||||
bool selectPrevious(size_t count, const std::function<bool()> &valid)
|
||||
{
|
||||
@@ -579,10 +617,25 @@ std::recursive_mutex logGate;
|
||||
bool loggingEnabled = false;
|
||||
DiagnosticBuffer diagnosticBuffer;
|
||||
}
|
||||
size_t DiagnosticBuffer::expire(ULONGLONG now)
|
||||
{
|
||||
size_t removed = 0;
|
||||
while (!entries.empty() && now - entries.front().first > 30000)
|
||||
{
|
||||
entries.pop_front();
|
||||
++removed;
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
void expireDiagnostics(ULONGLONG now)
|
||||
{
|
||||
std::lock_guard lock(logGate);
|
||||
diagnosticBuffer.expire(now);
|
||||
}
|
||||
std::wstring DiagnosticBuffer::record(const std::wstring &message, bool problem, ULONGLONG now)
|
||||
{
|
||||
while (!entries.empty() && (entries.size() >= 128 || now - entries.front().first > 30000))
|
||||
entries.pop_front();
|
||||
expire(now);
|
||||
while (entries.size() >= 128) entries.pop_front();
|
||||
entries.emplace_back(now, message);
|
||||
if (!problem)
|
||||
return {};
|
||||
@@ -680,3 +733,5 @@ void log(const std::wstring &message)
|
||||
}
|
||||
}
|
||||
} // namespace ks
|
||||
|
||||
#include "browser_chat.inc"
|
||||
+7
-1
@@ -38,12 +38,16 @@ HKL windowLayout(HWND);
|
||||
bool switchWindowLayout(HWND, HKL, const std::function<bool()> &valid);
|
||||
bool activateWindow(HWND);
|
||||
void showRequestedWindow(HWND);
|
||||
void showMenuAccessKeys(HMENU);
|
||||
bool ownsClipboard(HWND);
|
||||
bool webViewDescendant(DWORD owner, DWORD host,
|
||||
const std::function<std::optional<std::pair<DWORD, std::wstring>>(DWORD)> &read);
|
||||
std::wstring processName(HWND);
|
||||
Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024);
|
||||
enum class ClipboardRead { All, Selection, WithoutImages };
|
||||
Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024,
|
||||
ClipboardRead = ClipboardRead::All, std::optional<DWORD> expected = {});
|
||||
DWORD writeClipboard(HWND, const Clip &);
|
||||
DWORD writeClipboardGuarded(HWND, const Clip &, std::optional<DWORD> expected);
|
||||
Clip textClip(const std::wstring &);
|
||||
bool chord(WORD key, UINT modifiers = 0);
|
||||
// Process-local marker, shared by every KSwitcher input producer (not an authentication token).
|
||||
@@ -71,10 +75,12 @@ class DiagnosticBuffer
|
||||
{
|
||||
std::deque<std::pair<ULONGLONG, std::wstring>> entries;
|
||||
public:
|
||||
size_t expire(ULONGLONG now);
|
||||
std::wstring record(const std::wstring &message, bool problem, ULONGLONG now);
|
||||
void clear() { entries.clear(); }
|
||||
};
|
||||
void setLoggingEnabled(bool enabled);
|
||||
void expireDiagnostics(ULONGLONG now);
|
||||
void diagnosticEvent(const std::wstring &message, bool problem = false);
|
||||
void diagnosticOperation(const std::string &json);
|
||||
std::wstring readDiagnosticLog(bool previous);
|
||||
|
||||
+2
-1
@@ -252,7 +252,7 @@ DWORD CALLBACK readStream(DWORD_PTR cookie, LPBYTE buffer, LONG size, LONG *read
|
||||
return 0;
|
||||
}
|
||||
} // namespace
|
||||
std::string richPreview(const Clip &clip)
|
||||
std::string richPreview(const Clip &clip, bool plainFallback)
|
||||
{
|
||||
for (const auto &f : clip.formats)
|
||||
if (f.name == L"Rich Text Format" && f.data.size() <= 65536)
|
||||
@@ -276,6 +276,7 @@ std::string richPreview(const Clip &clip)
|
||||
{
|
||||
}
|
||||
}
|
||||
if (!plainFallback) return {};
|
||||
auto text = clip.text();
|
||||
if (text.size() > 4096)
|
||||
text.resize(4096);
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
std::string richPreview(const Clip &);
|
||||
std::string richPreview(const Clip &, bool plainFallback = true);
|
||||
HWND createRichText(HWND parent, int id, bool visible);
|
||||
bool setRichText(HWND, const std::string &);
|
||||
} // namespace ks
|
||||
+111
-25
@@ -54,7 +54,7 @@ bool confirmScreenshotClose(HWND owner)
|
||||
// If Windows cannot display the confirmation, keep the screenshot open.
|
||||
return SUCCEEDED(result) && button==IDYES;
|
||||
}
|
||||
constexpr int ToolIds[]{27,10,11,22,23,24,25,36,37,21,19,26,20,12,18,13};
|
||||
constexpr int ToolIds[]{27,10,11,22,23,24,25,36,37,38,21,19,26,20,12,18,13};
|
||||
struct Surface
|
||||
{
|
||||
HDC dc = CreateCompatibleDC(nullptr);
|
||||
@@ -124,7 +124,7 @@ bool chooseTextFont(HWND owner,Mark &m)
|
||||
m.fontWeight=font.lfWeight; m.fontItalic=font.lfItalic!=0;
|
||||
return true;
|
||||
}
|
||||
constexpr int CursorTools[]{10,11,22,23,24,25,36,37,19};
|
||||
constexpr int CursorTools[]{10,11,22,23,24,25,36,37,38,19};
|
||||
HCURSOR makeToolCursor(int tool,int size)
|
||||
{
|
||||
// Monochrome AND/XOR cursor: white outline keeps the glyph visible on dark images.
|
||||
@@ -148,6 +148,7 @@ HCURSOR makeToolCursor(int tool,int size)
|
||||
case 22: line(18,29,29,18); break;
|
||||
case 23: Rectangle(dc,x(17),y(18),x(30),y(29)); break;
|
||||
case 24: Ellipse(dc,x(17),y(17),x(30),y(30)); break;
|
||||
case 38: Arc(dc,x(16),y(18),x(31),y(38),x(31),y(28),x(16),y(28)); break;
|
||||
case 25: Ellipse(dc,x(16),y(20),x(31),y(28)); break;
|
||||
case 36: { POINT p[]{{x(23),y(17)},{x(31),y(30)},{x(16),y(30)},{x(23),y(17)}}; Polyline(dc,p,4); break; }
|
||||
case 37: { POINT p[]{{x(20),y(18)},{x(27),y(18)},{x(31),y(30)},{x(16),y(30)},{x(20),y(18)}}; Polyline(dc,p,5); break; }
|
||||
@@ -177,6 +178,8 @@ struct Capture
|
||||
Mark textDefaults{};
|
||||
ScreenshotShape shape=ScreenshotShape::None;
|
||||
LineStyle lineStyle=LineStyle::Solid;
|
||||
int smoothing=25;
|
||||
bool smoothingDrag=false;
|
||||
LineEnds arrowEnds=LineEnds::End, freehandEnds=LineEnds::None;
|
||||
COLORREF currentColor=RGB(225,42,50);
|
||||
COLORREF customColors[16]{};
|
||||
@@ -268,6 +271,7 @@ void updateStatus(Capture &c)
|
||||
else if(c.textTool) text=L"Text (T): click the image to type | Double-click existing text to edit";
|
||||
else if(c.highlight) text=L"Highlight (H): drag to paint | Ctrl+drag = paint over an object | V = pointer";
|
||||
else if(c.freehand) text=L"Freehand (F): auto-smooth / shapes; Ctrl+Z restores original | Shift = 45-degree steps | Ctrl = draw over objects";
|
||||
else if(c.shape==ScreenshotShape::Arc) text=L"Arc (U): drag to draw a half ellipse | Handles = resize / rotate | V = pointer";
|
||||
else if(c.arrow) text=L"Drag to draw | Ctrl+drag over objects = linked connector | V = pointer";
|
||||
else text=L"Number (N): click to add | V = select and edit | Ctrl+C = copy screenshot";
|
||||
text=L"Zoom: "+std::to_wstring(int(std::lround(100.0*(c.view.right-c.view.left)/c.image->width)))+
|
||||
@@ -409,6 +413,14 @@ std::vector<POINT> shapeOutline(const Mark &m)
|
||||
auto r=region(m.from,m.to);
|
||||
if(m.shape==ScreenshotShape::Rectangle)
|
||||
points={{r.left,r.top},{r.right,r.top},{r.right,r.bottom},{r.left,r.bottom},{r.left,r.top}};
|
||||
else if(m.shape==ScreenshotShape::Arc) {
|
||||
// An open half ellipse spanning the drag rectangle, with no closing chord.
|
||||
for(int i=0;i<=90;++i) {
|
||||
double a=i*3.141592653589793/90;
|
||||
points.push_back({LONG(std::lround((r.left+r.right)/2.0-(r.right-r.left)/2.0*std::cos(a))),
|
||||
LONG(std::lround(r.bottom-(r.bottom-r.top)*std::sin(a)))});
|
||||
}
|
||||
}
|
||||
else if(m.shape==ScreenshotShape::Triangle)
|
||||
points={{(r.left+r.right)/2,r.top},{r.right,r.bottom},{r.left,r.bottom},{(r.left+r.right)/2,r.top}};
|
||||
else if(m.shape==ScreenshotShape::Trapezoid)
|
||||
@@ -550,7 +562,7 @@ void drawMarks(HDC dc, const std::vector<Mark> &marks, const Mark *preview = nul
|
||||
if(m.shape!=ScreenshotShape::None) {
|
||||
auto hollow=SelectObject(dc,GetStockObject(HOLLOW_BRUSH));
|
||||
auto r=region(m.from,m.to);
|
||||
if(!m.points.empty() || m.rotation!=0 || m.shape==ScreenshotShape::Triangle || m.shape==ScreenshotShape::Trapezoid) {
|
||||
if(!m.points.empty() || m.rotation!=0 || m.shape==ScreenshotShape::Triangle || m.shape==ScreenshotShape::Trapezoid || m.shape==ScreenshotShape::Arc) {
|
||||
auto points=shapeOutline(m); Polyline(dc,points.data(),int(points.size()));
|
||||
}
|
||||
else if(m.shape==ScreenshotShape::Rectangle) Rectangle(dc,r.left,r.top,r.right+1,r.bottom+1);
|
||||
@@ -620,6 +632,13 @@ bool selectedLine(const Capture &c)
|
||||
}
|
||||
void syncLineOptions(HWND w,const Capture &c)
|
||||
{
|
||||
bool pencil=c.selected>=0 && c.marks[c.selected].freehand;
|
||||
int amount=pencil?c.marks[c.selected].smoothing:c.smoothing;
|
||||
SendDlgItemMessageW(w,41,TBM_SETPOS,TRUE,amount);
|
||||
auto smoothingText=L"Smoothing: "+std::to_wstring(amount)+L"%";
|
||||
SetDlgItemTextW(w,42,smoothingText.c_str());
|
||||
SetDlgItemTextW(w,43,pencil?L"Selected stroke":L"New pencil strokes");
|
||||
EnableWindow(GetDlgItem(w,44),std::any_of(c.marks.begin(),c.marks.end(),[](const Mark &m){return m.freehand;}));
|
||||
EnableWindow(GetDlgItem(w,34),c.textTool || (c.selected>=0 && (c.marks[c.selected].isText() || !c.marks[c.selected].label.empty())));
|
||||
EnableWindow(GetDlgItem(w,35),c.selected>=0 && c.marks[c.selected].isLine());
|
||||
bool selected=selectedLine(c),enabled=selected || c.arrow || c.freehand;
|
||||
@@ -668,7 +687,7 @@ void layout(HWND w, Capture &c)
|
||||
RECT statusRect{}; GetWindowRect(status,&statusRect);
|
||||
c.statusHeight=statusRect.bottom-statusRect.top;
|
||||
r.bottom-=c.statusHeight;
|
||||
const int positions[]{8,44,80,116,152,188,224,260,296,332,368,404,440,488,524,572};
|
||||
const int positions[]{8,44,80,116,152,188,224,260,296,332,368,404,440,476,524,560,608};
|
||||
static_assert(std::size(positions)==std::size(ToolIds));
|
||||
for (size_t i = 0; i < std::size(ToolIds); ++i)
|
||||
{
|
||||
@@ -677,10 +696,14 @@ void layout(HWND w, Capture &c)
|
||||
MulDiv(32,dpi,96),MulDiv(32,dpi,96),TRUE);
|
||||
}
|
||||
SendDlgItemMessageW(w,28,WM_SETFONT,(WPARAM)c.font,TRUE);
|
||||
MoveWindow(GetDlgItem(w,28),MulDiv(612,dpi,96),MulDiv(6,dpi,96),
|
||||
MoveWindow(GetDlgItem(w,28),MulDiv(648,dpi,96),MulDiv(6,dpi,96),
|
||||
MulDiv(78,dpi,96),MulDiv(32,dpi,96),TRUE);
|
||||
c.panelHeight=c.unit+MulDiv(40,dpi,96);
|
||||
for(int id:{30,31,32,33,34,35}) SendDlgItemMessageW(w,id,WM_SETFONT,(WPARAM)c.font,TRUE);
|
||||
c.panelHeight=c.unit+MulDiv(80,dpi,96);
|
||||
for(int id:{30,31,32,33,34,35,41,42,43,44}) SendDlgItemMessageW(w,id,WM_SETFONT,(WPARAM)c.font,TRUE);
|
||||
MoveWindow(GetDlgItem(w,42),MulDiv(12,dpi,96),c.unit+MulDiv(44,dpi,96),MulDiv(128,dpi,96),MulDiv(24,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,41),MulDiv(142,dpi,96),c.unit+MulDiv(40,dpi,96),MulDiv(200,dpi,96),MulDiv(30,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,43),MulDiv(350,dpi,96),c.unit+MulDiv(44,dpi,96),MulDiv(150,dpi,96),MulDiv(24,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,44),MulDiv(516,dpi,96),c.unit+MulDiv(40,dpi,96),MulDiv(210,dpi,96),MulDiv(30,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,32),MulDiv(12,dpi,96),c.unit+MulDiv(6,dpi,96),MulDiv(64,dpi,96),MulDiv(24,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,30),MulDiv(80,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(150,dpi,96),MulDiv(180,dpi,96),TRUE);
|
||||
MoveWindow(GetDlgItem(w,33),MulDiv(248,dpi,96),c.unit+MulDiv(6,dpi,96),MulDiv(40,dpi,96),MulDiv(24,dpi,96),TRUE);
|
||||
@@ -771,7 +794,7 @@ HCURSOR toolCursor(const Capture &c)
|
||||
if(c.pointer) return LoadCursorW(nullptr,IDC_ARROW);
|
||||
if(c.textTool) return LoadCursorW(nullptr,IDC_IBEAM);
|
||||
if(c.freehand && c.pencilCursor) return c.pencilCursor;
|
||||
int tool=c.highlight?19:c.straight?22:c.shape==ScreenshotShape::Trapezoid?37:c.shape==ScreenshotShape::Triangle?36:c.shape!=ScreenshotShape::None?22+int(c.shape):c.arrow?11:10;
|
||||
int tool=c.highlight?19:c.straight?22:c.shape==ScreenshotShape::Arc?38:c.shape==ScreenshotShape::Trapezoid?37:c.shape==ScreenshotShape::Triangle?36:c.shape!=ScreenshotShape::None?22+int(c.shape):c.arrow?11:10;
|
||||
for(size_t i=0;i<std::size(CursorTools);++i)
|
||||
if(CursorTools[i]==tool && c.drawingCursors[i]) return c.drawingCursors[i];
|
||||
return LoadCursorW(nullptr,IDC_CROSS);
|
||||
@@ -783,12 +806,13 @@ HCURSOR actionCursor(const Capture &c,std::pair<int,MarkPart> hit,bool inside)
|
||||
if(hit.second==MarkPart::Body || hit.second==MarkPart::Label) cursor=IDC_SIZEALL;
|
||||
else if(hit.second==MarkPart::Rotation) cursor=IDC_HAND;
|
||||
else if(hit.second>=MarkPart::Vertex0 && hit.second<=MarkPart::Vertex2) cursor=IDC_SIZEALL;
|
||||
else if(hit.second==MarkPart::Radius) cursor=IDC_SIZEWE;
|
||||
else if(hit.second==MarkPart::Start || hit.second==MarkPart::End || hit.second==MarkPart::Thickness) {
|
||||
else if(hit.second==MarkPart::Start || hit.second==MarkPart::End || hit.second==MarkPart::Radius)
|
||||
cursor=IDC_SIZEALL;
|
||||
else if(hit.second==MarkPart::Thickness) {
|
||||
const auto &mark=c.marks[hit.first];
|
||||
auto [from,to]=hit.second==MarkPart::Thickness?thicknessSegment(mark):std::pair{mark.from,mark.to};
|
||||
auto [from,to]=thicknessSegment(mark);
|
||||
double angle=std::atan2(double(to.y-from.y),double(to.x-from.x));
|
||||
if(hit.second==MarkPart::Thickness) angle+=3.141592653589793/2;
|
||||
angle+=3.141592653589793/2;
|
||||
int axis=(int(std::lround(angle/(3.141592653589793/4)))+8)%4;
|
||||
const LPCWSTR cursors[]{IDC_SIZEWE,IDC_SIZENWSE,IDC_SIZENS,IDC_SIZENESW};
|
||||
cursor=cursors[axis];
|
||||
@@ -882,7 +906,7 @@ void drawTool(const DRAWITEMSTRUCT &item, const Capture &c)
|
||||
bool active=(item.CtlID==27 && c.pointer)||(item.CtlID==10 && !c.pointer && !c.arrow && !c.highlight && !c.freehand && !c.textTool)||(item.CtlID==11 && c.arrow && !c.straight && c.shape==ScreenshotShape::None)||
|
||||
(item.CtlID==19 && c.highlight)||(item.CtlID==21 && c.freehand)||
|
||||
(item.CtlID==22 && c.straight)||(item.CtlID>=23 && item.CtlID<=25 && int(c.shape)==int(item.CtlID)-22)||(item.CtlID==26 && c.textTool)||
|
||||
(item.CtlID==36 && c.shape==ScreenshotShape::Triangle)||(item.CtlID==37 && c.shape==ScreenshotShape::Trapezoid);
|
||||
(item.CtlID==36 && c.shape==ScreenshotShape::Triangle)||(item.CtlID==37 && c.shape==ScreenshotShape::Trapezoid)||(item.CtlID==38 && c.shape==ScreenshotShape::Arc);
|
||||
bool disabled=item.itemState&ODS_DISABLED;
|
||||
POINT mouse; GetCursorPos(&mouse); ScreenToClient(item.hwndItem,&mouse);
|
||||
bool hover=PtInRect(&r,mouse) && !disabled;
|
||||
@@ -896,13 +920,14 @@ void drawTool(const DRAWITEMSTRUCT &item, const Capture &c)
|
||||
RoundRect(dc,r.left,r.top,r.right,r.bottom,corner,corner);
|
||||
SelectObject(dc,oldPen); SelectObject(dc,oldBrush); DeleteObject(pen); DeleteObject(brush);
|
||||
int iconIndex=item.CtlID==35?13:item.CtlID==34?14:item.CtlID>=22?int(item.CtlID)-13:item.CtlID==18?5:item.CtlID==19?6:item.CtlID==20?7:item.CtlID==21?8:item.CtlID-10;
|
||||
auto icon=(item.CtlID==36 || item.CtlID==37)?nullptr:item.CtlID==27?(HICON)LoadCursorW(nullptr,IDC_ARROW):c.toolIcons[disabled?2:active?1:0][iconIndex];
|
||||
if(item.CtlID==36 || item.CtlID==37) {
|
||||
auto icon=(item.CtlID==36 || item.CtlID==37 || item.CtlID==38)?nullptr:item.CtlID==27?(HICON)LoadCursorW(nullptr,IDC_ARROW):c.toolIcons[disabled?2:active?1:0][iconIndex];
|
||||
if(item.CtlID==36 || item.CtlID==37 || item.CtlID==38) {
|
||||
int cx=(r.left+r.right)/2,cy=(r.top+r.bottom)/2,s=c.iconSize/2;
|
||||
auto trianglePen=CreatePen(PS_SOLID,std::max(1,MulDiv(2,GetDpiForWindow(item.hwndItem),96)),
|
||||
disabled?RGB(148,163,184):active?RGB(37,99,235):RGB(51,65,85));
|
||||
auto previous=SelectObject(dc,trianglePen);
|
||||
if(item.CtlID==36) { POINT vertices[]{{cx,cy-s},{cx+s,cy+s},{cx-s,cy+s},{cx,cy-s}}; Polyline(dc,vertices,4); }
|
||||
if(item.CtlID==38) Arc(dc,cx-s,cy-s,cx+s,cy+3*s,cx+s,cy+s,cx-s,cy+s);
|
||||
else if(item.CtlID==36) { POINT vertices[]{{cx,cy-s},{cx+s,cy+s},{cx-s,cy+s},{cx,cy-s}}; Polyline(dc,vertices,4); }
|
||||
else { POINT vertices[]{{cx-s/2,cy-s},{cx+s/2,cy-s},{cx+s,cy+s},{cx-s,cy+s},{cx-s/2,cy-s}}; Polyline(dc,vertices,5); }
|
||||
SelectObject(dc,previous); DeleteObject(trianglePen);
|
||||
}
|
||||
@@ -1024,7 +1049,7 @@ void edit(HWND w, Capture &c)
|
||||
InitCommonControlsEx(&statusControls);
|
||||
CreateWindowExW(0,STATUSCLASSNAMEW,L"",WS_CHILD|WS_VISIBLE|SBARS_TOOLTIPS,
|
||||
0,0,0,0,w,(HMENU)50,c.app.instance,nullptr);
|
||||
const wchar_t *labels[]{L"Pointer (V): select and edit objects", L"Number (N)", L"Arrow (A); Ctrl+drag between objects to link", L"Straight line (L); Ctrl+drag between objects to link", L"Rectangle (R)", L"Circle (O)", L"Ellipse (E)", L"Triangle (G): drag to draw; drag each vertex to reshape", L"Trapezoid (B): drag to draw", L"Freehand line (F); Shift for 45-degree steps; move >50 px off line to turn; Ctrl to draw over objects", L"Highlight (H); Ctrl+drag to paint over an object",
|
||||
const wchar_t *labels[]{L"Pointer (V): select and edit objects", L"Number (N)", L"Arrow (A); Ctrl+drag between objects to link", L"Straight line (L); Ctrl+drag between objects to link", L"Rectangle (R)", L"Circle (O)", L"Ellipse (E)", L"Triangle (G): drag to draw; drag each vertex to reshape", L"Trapezoid (B): drag to draw", L"Arc (U): drag to draw a half ellipse; use handles to resize or rotate", L"Freehand line (F); Shift for 45-degree steps; move >50 px off line to turn; Ctrl to draw over objects", L"Highlight (H); Ctrl+drag to paint over an object",
|
||||
L"Text (T); double-click or F2 to edit", L"Color — selected object and new objects", L"Undo (Ctrl+Z)", L"Redo (Ctrl+Y / Ctrl+Shift+Z)", L"Copy (Ctrl+C)"};
|
||||
static_assert(std::size(labels)==std::size(ToolIds));
|
||||
auto saveButton=CreateWindowW(L"BUTTON",L"Save...",WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_PUSHBUTTON,
|
||||
@@ -1060,6 +1085,14 @@ void edit(HWND w, Capture &c)
|
||||
SetWindowSubclass(labelButton,toolHover,1,0);
|
||||
fontTip.uId=(UINT_PTR)labelButton; fontTip.lpszText=const_cast<wchar_t *>(L"Arrow label (F2 / double-click); drag label to reposition");
|
||||
SendMessageW(tips,TTM_ADDTOOLW,0,(LPARAM)&fontTip);
|
||||
INITCOMMONCONTROLSEX sliders{sizeof(sliders),ICC_BAR_CLASSES}; InitCommonControlsEx(&sliders);
|
||||
CreateWindowW(TRACKBAR_CLASSW,L"Pencil smoothing",WS_CHILD|WS_VISIBLE|WS_TABSTOP|TBS_NOTICKS,
|
||||
0,0,0,0,w,(HMENU)41,c.app.instance,nullptr);
|
||||
SendDlgItemMessageW(w,41,TBM_SETRANGE,TRUE,MAKELPARAM(0,100));
|
||||
SendDlgItemMessageW(w,41,TBM_SETPAGESIZE,0,10);
|
||||
for(int id:{42,43}) CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE,0,0,0,0,w,(HMENU)(INT_PTR)id,c.app.instance,nullptr);
|
||||
CreateWindowW(L"BUTTON",L"Apply to all strokes",WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_PUSHBUTTON,
|
||||
0,0,0,0,w,(HMENU)44,c.app.instance,nullptr);
|
||||
c.syncHistory();
|
||||
auto work = monitor.rcWork;
|
||||
SetWindowPos(w,HWND_NOTOPMOST,work.left+20,work.top+20,
|
||||
@@ -1119,7 +1152,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
break;
|
||||
case WM_DRAWITEM:
|
||||
if((wp>=10 && wp<=13) || (wp>=18 && wp<=27) || wp==34 || wp==35 || wp==36 || wp==37) { drawTool(*reinterpret_cast<DRAWITEMSTRUCT *>(lp),*c); return TRUE; }
|
||||
if((wp>=10 && wp<=13) || (wp>=18 && wp<=27) || wp==34 || wp==35 || wp==36 || wp==37 || wp==38) { drawTool(*reinterpret_cast<DRAWITEMSTRUCT *>(lp),*c); return TRUE; }
|
||||
break;
|
||||
case WM_CTLCOLORSTATIC:
|
||||
SetBkColor((HDC)wp,RGB(255,255,255)); SetTextColor((HDC)wp,RGB(51,65,85));
|
||||
@@ -1128,6 +1161,21 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case WM_SETCURSOR:
|
||||
if ((HWND)wp==w && LOWORD(lp)==HTCLIENT) { captureCursor(w,*c); return TRUE; }
|
||||
break;
|
||||
case WM_HSCROLL:
|
||||
if((HWND)lp==GetDlgItem(w,41) && !c->dragging) {
|
||||
int amount=int(SendDlgItemMessageW(w,41,TBM_GETPOS,0,0));
|
||||
bool pencil=c->selected>=0 && c->marks[c->selected].freehand;
|
||||
if(pencil && c->marks[c->selected].smoothing!=amount) {
|
||||
if(!c->smoothingDrag) c->remember(c->marks);
|
||||
setScreenshotSmoothing(c->marks[c->selected],amount);
|
||||
resolveScreenshotLinks(c->marks);
|
||||
c->smoothingDrag=LOWORD(wp)==TB_THUMBTRACK;
|
||||
} else if(!pencil) c->smoothing=amount;
|
||||
if(LOWORD(wp)!=TB_THUMBTRACK) c->smoothingDrag=false;
|
||||
syncLineOptions(w,*c); InvalidateRect(w,nullptr,FALSE);
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case WM_COMMAND:
|
||||
if(LOWORD(wp)==40) {
|
||||
if(c->inlineText && HIWORD(wp)==EN_CHANGE) { readInlineText(*c); positionInlineText(*c); }
|
||||
@@ -1135,6 +1183,17 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
return 0;
|
||||
}
|
||||
if (c->dragging) return 0;
|
||||
if(LOWORD(wp)==44) {
|
||||
int amount=int(SendDlgItemMessageW(w,41,TBM_GETPOS,0,0));
|
||||
c->smoothing=amount;
|
||||
if(std::any_of(c->marks.begin(),c->marks.end(),[&](const Mark &m){return m.freehand && m.smoothing!=amount;})) {
|
||||
c->remember(c->marks);
|
||||
for(auto &mark:c->marks) if(mark.freehand) setScreenshotSmoothing(mark,amount);
|
||||
resolveScreenshotLinks(c->marks);
|
||||
}
|
||||
c->smoothingDrag=false; syncLineOptions(w,*c); InvalidateRect(w,nullptr,FALSE);
|
||||
return 0;
|
||||
}
|
||||
if(LOWORD(wp)==35) {
|
||||
finishInlineText(w,*c,true);
|
||||
if(c->selected>=0 && c->marks[c->selected].isLine()) beginMarkText(w,*c,c->selected);
|
||||
@@ -1213,13 +1272,13 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if(changed) { c->copied=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; }
|
||||
c->syncHistory();
|
||||
}
|
||||
if (LOWORD(wp)==10 || LOWORD(wp)==11 || LOWORD(wp)==19 || LOWORD(wp)==36 || LOWORD(wp)==37 || (LOWORD(wp)>=21 && LOWORD(wp)<=27))
|
||||
if (LOWORD(wp)==10 || LOWORD(wp)==11 || LOWORD(wp)==19 || LOWORD(wp)==36 || LOWORD(wp)==37 || LOWORD(wp)==38 || (LOWORD(wp)>=21 && LOWORD(wp)<=27))
|
||||
{
|
||||
c->pointer=LOWORD(wp)==27;
|
||||
c->arrow = LOWORD(wp)==11 || LOWORD(wp)==36 || LOWORD(wp)==37 || (LOWORD(wp)>=22 && LOWORD(wp)<=25);
|
||||
c->arrow = LOWORD(wp)==11 || LOWORD(wp)==36 || LOWORD(wp)==37 || LOWORD(wp)==38 || (LOWORD(wp)>=22 && LOWORD(wp)<=25);
|
||||
c->straight=LOWORD(wp)==22;
|
||||
c->textTool=LOWORD(wp)==26;
|
||||
c->shape=LOWORD(wp)==37?ScreenshotShape::Trapezoid:LOWORD(wp)==36?ScreenshotShape::Triangle:LOWORD(wp)>=23 && LOWORD(wp)<=25?ScreenshotShape(LOWORD(wp)-22):ScreenshotShape::None;
|
||||
c->shape=LOWORD(wp)==38?ScreenshotShape::Arc:LOWORD(wp)==37?ScreenshotShape::Trapezoid:LOWORD(wp)==36?ScreenshotShape::Triangle:LOWORD(wp)>=23 && LOWORD(wp)<=25?ScreenshotShape(LOWORD(wp)-22):ScreenshotShape::None;
|
||||
c->selected=-1; c->selectedLabel=false;
|
||||
c->highlight=LOWORD(wp)==19;
|
||||
c->freehand=LOWORD(wp)==21;
|
||||
@@ -1232,6 +1291,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
for(int id=22;id<=27;++id) InvalidateRect(GetDlgItem(w,id),nullptr,FALSE);
|
||||
InvalidateRect(GetDlgItem(w,36),nullptr,FALSE);
|
||||
InvalidateRect(GetDlgItem(w,37),nullptr,FALSE);
|
||||
InvalidateRect(GetDlgItem(w,38),nullptr,FALSE);
|
||||
}
|
||||
|
||||
SetFocus(w); captureCursor(w,*c); InvalidateRect(w,nullptr,FALSE); return 0;
|
||||
@@ -1292,6 +1352,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if(wp=='E') SendMessageW(w,WM_COMMAND,25,0);
|
||||
if(wp=='G') SendMessageW(w,WM_COMMAND,36,0);
|
||||
if(wp=='B') SendMessageW(w,WM_COMMAND,37,0);
|
||||
if(wp=='U') SendMessageW(w,WM_COMMAND,38,0);
|
||||
}
|
||||
if (wp=='N' || wp=='A') SendMessageW(w,WM_COMMAND,wp=='N'?10:11,0);
|
||||
if(wp=='H') SendMessageW(w,WM_COMMAND,19,0);
|
||||
@@ -1529,6 +1590,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
c->remember(c->marks); c->marks.push_back(std::move(c->stroke));
|
||||
if(c->freehand) {
|
||||
auto &mark=c->marks.back();
|
||||
mark.rawPoints=mark.points;
|
||||
linkScreenshotEndpoint(mark,true,c->start,c->marks,6);
|
||||
linkScreenshotEndpoint(mark,false,c->end,c->marks,6);
|
||||
resolveScreenshotLinks(c->marks);
|
||||
@@ -1539,10 +1601,18 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
ScreenshotShape recognized{};
|
||||
bool straightLine=false;
|
||||
auto improved=improveScreenshotStroke(c->marks.back().points,&recognized,&straightLine);
|
||||
if(recognized==ScreenshotShape::None && !straightLine) {
|
||||
improved=smoothScreenshotStroke(c->marks.back().rawPoints,c->smoothing);
|
||||
const auto &raw=c->marks.back().rawPoints;
|
||||
if(improved.size()==raw.size() && std::equal(improved.begin(),improved.end(),raw.begin(),
|
||||
[](POINT a,POINT b){return a.x==b.x && a.y==b.y;})) improved.clear();
|
||||
}
|
||||
if(!improved.empty()) {
|
||||
c->remember(c->marks);
|
||||
auto &mark=c->marks.back();
|
||||
mark.points=std::move(improved);
|
||||
if(recognized==ScreenshotShape::None && !straightLine) {
|
||||
setScreenshotSmoothing(mark,c->smoothing);
|
||||
} else { mark.points=std::move(improved); mark.rawPoints.clear(); }
|
||||
mark.from=mark.points.front(); mark.to=mark.points.back();
|
||||
if(straightLine) { mark.points.clear(); mark.freehand=false; }
|
||||
if(recognized!=ScreenshotShape::None) {
|
||||
@@ -1562,7 +1632,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
c->marks.back().style=c->lineStyle; c->marks.back().ends=c->straight || c->shape!=ScreenshotShape::None?LineEnds::None:c->arrowEnds;
|
||||
c->marks.back().shape=c->shape;
|
||||
auto &mark=c->marks.back();
|
||||
if(mark.shape==ScreenshotShape::Triangle || mark.shape==ScreenshotShape::Trapezoid) mark.points=shapeOutline(mark);
|
||||
if(mark.shape==ScreenshotShape::Triangle || mark.shape==ScreenshotShape::Trapezoid || mark.shape==ScreenshotShape::Arc) mark.points=shapeOutline(mark);
|
||||
linkScreenshotEndpoint(mark,true,c->start,c->marks,6);
|
||||
linkScreenshotEndpoint(mark,false,c->end,c->marks,6);
|
||||
resolveScreenshotLinks(c->marks);
|
||||
@@ -1585,7 +1655,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (c->editing)
|
||||
{
|
||||
auto limits = reinterpret_cast<MINMAXINFO *>(lp);
|
||||
limits->ptMinTrackSize = {MulDiv(730,GetDpiForWindow(w),96),MulDiv(240,GetDpiForWindow(w),96)};
|
||||
limits->ptMinTrackSize = {MulDiv(766,GetDpiForWindow(w),96),MulDiv(240,GetDpiForWindow(w),96)};
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
@@ -1900,7 +1970,14 @@ void resolveScreenshotLinks(std::vector<ScreenshotMark> &marks)
|
||||
POINT start=from?from->from:m.from, end=to?to->from:m.to;
|
||||
if(from) m.from=rim(*from,end,true);
|
||||
if(to) m.to=rim(*to,start,false);
|
||||
if(m.freehand && !m.points.empty()) { m.points.front()=m.from; m.points.back()=m.to; }
|
||||
if(m.freehand && !m.points.empty()) {
|
||||
m.points.front()=m.from; m.points.back()=m.to;
|
||||
if(!m.rawPoints.empty() && (m.rawPoints.front().x!=m.from.x || m.rawPoints.front().y!=m.from.y ||
|
||||
m.rawPoints.back().x!=m.to.x || m.rawPoints.back().y!=m.to.y)) {
|
||||
m.rawPoints.front()=m.from; m.rawPoints.back()=m.to;
|
||||
setScreenshotSmoothing(m,m.smoothing);
|
||||
}
|
||||
}
|
||||
}
|
||||
state[index]=2;
|
||||
};
|
||||
@@ -2054,10 +2131,15 @@ ScreenshotMark dragScreenshotMark(const ScreenshotMark &original, MarkPart part,
|
||||
return low<=high?std::clamp(delta,low,high):0L;
|
||||
};
|
||||
auto bounds=markBounds(m);
|
||||
for(auto p:m.rawPoints) {
|
||||
bounds.left=std::min(bounds.left,p.x); bounds.right=std::max(bounds.right,p.x);
|
||||
bounds.top=std::min(bounds.top,p.y); bounds.bottom=std::max(bounds.bottom,p.y);
|
||||
}
|
||||
LONG dx=shift(position.x-origin.x,bounds.left,bounds.right,width);
|
||||
LONG dy=shift(position.y-origin.y,bounds.top,bounds.bottom,height);
|
||||
m.from.x+=dx; m.to.x+=dx; m.from.y+=dy; m.to.y+=dy;
|
||||
for(auto &point:m.points) { point.x+=dx; point.y+=dy; }
|
||||
for(auto &point:m.rawPoints) { point.x+=dx; point.y+=dy; }
|
||||
}
|
||||
else if(part==MarkPart::Start || part==MarkPart::End)
|
||||
{
|
||||
@@ -2082,6 +2164,10 @@ ScreenshotMark dragScreenshotMark(const ScreenshotMark &original, MarkPart part,
|
||||
}
|
||||
}
|
||||
if(m.freehand && !m.points.empty()) (part==MarkPart::Start?m.points.front():m.points.back())=endpoint;
|
||||
if(m.freehand && !m.rawPoints.empty()) {
|
||||
(part==MarkPart::Start?m.rawPoints.front():m.rawPoints.back())=endpoint;
|
||||
setScreenshotSmoothing(m,m.smoothing);
|
||||
}
|
||||
if(m.shape!=ScreenshotShape::None && m.rotation!=0) {
|
||||
auto fixedBefore=rotateShapePoint(original,part==MarkPart::Start?original.to:original.from);
|
||||
auto fixedAfter=rotateShapePoint(m,part==MarkPart::Start?m.to:m.from);
|
||||
|
||||
+3
-1
@@ -15,7 +15,7 @@ void showScreenshot(ScreenshotHost &);
|
||||
void showScreenshotEditor(ScreenshotHost &,const Clip &);
|
||||
enum class LineStyle { Solid, Dotted, Dashed, DashDot };
|
||||
enum class LineEnds { End, Start, Both, None };
|
||||
enum class ScreenshotShape { None, Rectangle, Circle, Ellipse, Triangle, Trapezoid };
|
||||
enum class ScreenshotShape { None, Rectangle, Circle, Ellipse, Triangle, Trapezoid, Arc };
|
||||
struct ScreenshotOffset { double x, y; };
|
||||
struct ScreenshotLink {
|
||||
unsigned long long target{};
|
||||
@@ -39,6 +39,8 @@ struct ScreenshotMark {
|
||||
bool labelRotationManual=false;
|
||||
unsigned long long id{};
|
||||
ScreenshotLink fromLink, toLink;
|
||||
std::vector<POINT> rawPoints; // Original pencil path for reversible smoothing.
|
||||
int smoothing=0; // 0..100; applies only to freehand strokes.
|
||||
bool isText() const { return !text.empty(); }
|
||||
bool isHighlight() const { return !points.empty() && !freehand && shape==ScreenshotShape::None; }
|
||||
bool isLine() const { return !number && !isText() && !isHighlight() && shape==ScreenshotShape::None; }
|
||||
|
||||
@@ -50,6 +50,30 @@ void registerScreenshotNotifications()
|
||||
// Notify the shell that notification identity/activation registration changed.
|
||||
SHChangeNotify(SHCNE_ASSOCCHANGED,SHCNF_IDLIST,nullptr,nullptr);
|
||||
}
|
||||
HANDLE startScreenshotNotificationRegistration()
|
||||
{
|
||||
auto path=std::filesystem::path(executable()).parent_path()/L"KSwitcher.Screenshot.exe";
|
||||
auto command=L"\""+path.wstring()+L"\" --register-notifications";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
startup.dwFlags=STARTF_USESHOWWINDOW; startup.wShowWindow=SW_HIDE;
|
||||
PROCESS_INFORMATION process{};
|
||||
if(!CreateProcessW(path.c_str(),command.data(),nullptr,nullptr,FALSE,CREATE_NO_WINDOW,
|
||||
nullptr,path.parent_path().c_str(),&startup,&process))
|
||||
throw std::runtime_error(utf8(lastError(L"Cannot start notification registration helper")));
|
||||
CloseHandle(process.hThread);
|
||||
return process.hProcess;
|
||||
}
|
||||
void registerScreenshotNotificationsInHelper()
|
||||
{
|
||||
auto process=startScreenshotNotificationRegistration();
|
||||
auto wait=WaitForSingleObject(process,10000);
|
||||
DWORD code=ERROR_GEN_FAILURE;
|
||||
bool completed=wait==WAIT_OBJECT_0 && GetExitCodeProcess(process,&code);
|
||||
CloseHandle(process);
|
||||
if(!completed || code)
|
||||
throw std::runtime_error(completed ? "Notification registration helper failed: "+std::to_string(code)
|
||||
: "Notification registration helper did not complete within 10 seconds");
|
||||
}
|
||||
bool validScreenshotToken(const std::wstring &id)
|
||||
{
|
||||
if(id.size()!=36) return false;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "screenshot.h"
|
||||
#include "screenshot_notifications.h"
|
||||
#include "storage.h"
|
||||
#include <commctrl.h>
|
||||
#include <shellapi.h>
|
||||
#include <roapi.h>
|
||||
@@ -49,6 +50,18 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
||||
std::wstring token;
|
||||
bool autoOpenEditor=false, writeLog=false;
|
||||
int argc{}; auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
|
||||
if(argc==3 && std::wstring(argv[1])==L"--clipboard-snapshot") {
|
||||
std::filesystem::path request=argv[2]; LocalFree(argv);
|
||||
return ks::runClipboardSnapshot(request);
|
||||
}
|
||||
if(argc==3 && (std::wstring(argv[1])==L"--capture-history" || std::wstring(argv[1])==L"--history-ocr")) {
|
||||
bool ocr=std::wstring(argv[1])==L"--history-ocr";
|
||||
std::filesystem::path request=argv[2]; LocalFree(argv);
|
||||
auto initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
if(FAILED(initialized)) return 1;
|
||||
int result=ocr ? ks::runHistoryOcr(request) : ks::runImageHistoryCapture(request);
|
||||
CoUninitialize(); return result;
|
||||
}
|
||||
if(argc>1 && std::wstring(argv[argc-1])==L"--write-log") {
|
||||
writeLog=true; --argc;
|
||||
ks::setLoggingEnabled(true);
|
||||
|
||||
@@ -206,7 +206,7 @@ bool notifyUpdateAvailable(const std::wstring &version)
|
||||
{
|
||||
try {
|
||||
// Reuse the screenshot notification identity, Windows settings and COM activator.
|
||||
registerScreenshotNotifications();
|
||||
registerScreenshotNotificationsInHelper();
|
||||
ComPtr<Notifications::IToastNotificationManagerStatics> manager;
|
||||
String managerClass(L"Windows.UI.Notifications.ToastNotificationManager");
|
||||
check(RoGetActivationFactory(managerClass.value,IID_PPV_ARGS(&manager)));
|
||||
|
||||
@@ -4,6 +4,10 @@ namespace ks {
|
||||
bool notifyScreenshot(const Clip &);
|
||||
std::string screenshotNotificationError();
|
||||
void registerScreenshotNotifications();
|
||||
// Caller owns the returned process handle; the helper exits after registration.
|
||||
HANDLE startScreenshotNotificationRegistration();
|
||||
// For background notification workers only; bounded wait, never on the UI thread.
|
||||
void registerScreenshotNotificationsInHelper();
|
||||
int runScreenshotToastActivator();
|
||||
DWORD startScreenshotActivationListener();
|
||||
bool validScreenshotToken(const std::wstring &);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include "sync.h"
|
||||
namespace ks
|
||||
{
|
||||
// The open editor is a draft based on a snapshot, not a replacement for all
|
||||
// settings that may have changed in the resident since the editor opened.
|
||||
inline Bytes mergeConfigurationSettings(const Bytes &base,const Bytes &draft,const Bytes ¤t,bool preferDraft=false)
|
||||
{
|
||||
auto merged=mergeSyncProfile(base,draft,current);
|
||||
if(!merged.conflicts.empty()){
|
||||
if(!preferDraft){
|
||||
std::string fields;
|
||||
for(auto &c:merged.conflicts){if(!fields.empty())fields+=", ";fields+=utf8(c.label);}
|
||||
throw std::runtime_error("Settings conflict: "+fields);
|
||||
}
|
||||
std::vector<SyncChoice> choices;
|
||||
for(auto &c:merged.conflicts)choices.push_back({c,true});
|
||||
merged=mergeSyncProfile(base,draft,current,choices);
|
||||
if(!merged.conflicts.empty())throw std::runtime_error("Resolve conflicting settings in this window before saving.");
|
||||
}
|
||||
return merged.local;
|
||||
}
|
||||
}
|
||||
+422
-26
@@ -4,6 +4,7 @@
|
||||
#include <algorithm>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <wincrypt.h>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
@@ -60,6 +61,25 @@ bool validId(const std::wstring &id)
|
||||
} // namespace
|
||||
void validateSettings(const Settings &s)
|
||||
{
|
||||
if (s.chatCycles.size() > 1000) throw std::runtime_error("Too many chat language profiles");
|
||||
for (const auto &[key, cycle] : s.chatCycles)
|
||||
{
|
||||
auto separator = key.find(L'\n');
|
||||
if (separator == key.npos || separator + 1 == key.size() || key.size() > 1024 ||
|
||||
key.find(L'\n', separator + 1) != key.npos || key.find(L'\r') != key.npos ||
|
||||
(key.substr(0, separator) != L"telegram" && key.substr(0, separator) != L"ms-teams" && key.substr(0, separator) != L"viber" && key.substr(0, separator) != L"telegram-web"))
|
||||
throw std::runtime_error("Invalid chat language profile");
|
||||
if (cycle.empty() || cycle.size() > 64) throw std::runtime_error("Select at least one chat language");
|
||||
std::vector<std::wstring> seen;
|
||||
for (const auto &id : cycle)
|
||||
{
|
||||
if (id.size() != 12 || !id.starts_with(L"win:") ||
|
||||
id.find_first_not_of(L"0123456789abcdefABCDEF", 4) != id.npos ||
|
||||
std::find(seen.begin(), seen.end(), id) != seen.end())
|
||||
throw std::runtime_error("Invalid or duplicate chat layout");
|
||||
seen.push_back(id);
|
||||
}
|
||||
}
|
||||
if (s.tesseractPath.size() > 32700 || s.tesseractPath.find_first_of(L"\r\n\"") != s.tesseractPath.npos)
|
||||
throw std::runtime_error("Invalid Tesseract executable path");
|
||||
if (s.tesseractLanguages.empty() || s.tesseractLanguages.size() > 128 ||
|
||||
@@ -117,9 +137,11 @@ void validateSettings(const Settings &s)
|
||||
L"абвгдеёжзийклмнопрстуфхцчшщъыьэюя"})
|
||||
valid |= !from.empty() && !to.empty() && from.size() <= 32 && to.size() <= 32 &&
|
||||
from == lower(from) && to == lower(to) && from != to &&
|
||||
from.find_first_not_of(alphabet) == from.npos && to.find_first_not_of(alphabet) == to.npos;
|
||||
from.find_first_not_of(alphabet) == from.npos &&
|
||||
to.find_first_not_of(std::wstring(alphabet) + L" ") == to.npos &&
|
||||
to.front() != L' ' && to.back() != L' ' && to.find(L" ") == to.npos;
|
||||
if (!valid)
|
||||
throw std::runtime_error("Replacement pairs must be different lowercase words of 1-32 letters in the same language");
|
||||
throw std::runtime_error("Use a lowercase typo of 1-32 letters and a different correction of 1-32 characters in the same language. Single spaces between correction words are allowed.");
|
||||
}
|
||||
for (const auto &[language, words] : s.autoWords)
|
||||
{
|
||||
@@ -147,8 +169,19 @@ void validateSettings(const Settings &s)
|
||||
if (snippet.trigger.size() < 2 || snippet.trigger.size() > 64 ||
|
||||
snippet.trigger.find_first_of(L"\r\n\t ") != snippet.trigger.npos)
|
||||
throw std::runtime_error("Snippet triggers must contain 2–64 characters without whitespace");
|
||||
if (!seen.insert(lower(snippet.trigger)).second)
|
||||
throw std::runtime_error("Duplicate snippet trigger");
|
||||
if (snippet.apps.size() > 64) throw std::runtime_error("Too many snippet applications");
|
||||
std::vector<std::wstring> scopes;
|
||||
for (const auto &app : snippet.apps)
|
||||
{
|
||||
auto normalized = snippetAppName(app);
|
||||
if (normalized.empty() || normalized.size() > 250 || normalized.find_first_of(L"\\/:*?\"<>|,\r\n\t") != normalized.npos)
|
||||
throw std::runtime_error("Use application names such as chrome.exe, not paths or wildcards");
|
||||
scopes.push_back(normalized);
|
||||
}
|
||||
if (scopes.empty()) scopes.push_back(L"");
|
||||
for (const auto &scope : scopes)
|
||||
if (!seen.insert(lower(snippet.trigger) + L"\n" + scope).second)
|
||||
throw std::runtime_error("Duplicate snippet trigger for the same application or global scope");
|
||||
auto t = parseTemplate(snippet.text);
|
||||
if (t.text.empty() || t.cursors > 1)
|
||||
throw std::runtime_error("Each snippet needs text and at most one {cursor} marker");
|
||||
@@ -231,6 +264,16 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
|
||||
s.cycle.push_back(w);
|
||||
}
|
||||
}
|
||||
if (j.contains("chatCycles"))
|
||||
{
|
||||
if (!j.at("chatCycles").is_object()) throw std::runtime_error("Invalid chat profiles object");
|
||||
for (const auto &[key, cycle] : j.at("chatCycles").items())
|
||||
{
|
||||
if (!cycle.is_array() || cycle.empty()) throw std::runtime_error("Empty chat language profile");
|
||||
for (const auto &id : cycle)
|
||||
s.chatCycles[wide(key)].push_back(wide(id.get<std::string>()));
|
||||
}
|
||||
}
|
||||
if (j.contains("layoutHotkeys"))
|
||||
{
|
||||
std::fill(s.direct.begin(), s.direct.end(), L"");
|
||||
@@ -249,6 +292,12 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
|
||||
for (auto &sn : j.at("snippets"))
|
||||
{
|
||||
Snippet item{str(sn, "trigger"), str(sn, "text"), str(sn, "id")};
|
||||
if (sn.contains("apps"))
|
||||
{
|
||||
if (!sn.at("apps").is_array()) throw std::runtime_error("Snippet apps must be a list");
|
||||
for (const auto &app : sn.at("apps")) item.apps.push_back(snippetAppName(wide(app.get<std::string>())));
|
||||
}
|
||||
if (item.id.empty() && !item.apps.empty()) item.id = newSnippetId();
|
||||
item.id = snippetId(item);
|
||||
s.snippets.push_back(std::move(item));
|
||||
}
|
||||
@@ -287,6 +336,9 @@ Bytes encodeSettings(const Settings &s)
|
||||
{"screenshotHotkey", utf8(s.screenshot)},
|
||||
{"screenshotAutoOpenEditor", s.screenshotAutoOpenEditor}};
|
||||
j["layouts"] = Json::array();
|
||||
j["chatCycles"] = Json::object();
|
||||
for (const auto &[key, cycle] : s.chatCycles)
|
||||
for (const auto &id : cycle) j["chatCycles"][utf8(key)].push_back(utf8(id));
|
||||
for (auto &id : s.cycle)
|
||||
j["layouts"].push_back(utf8(id));
|
||||
j["autoCorrectLayout"] = s.autoCorrect;
|
||||
@@ -319,7 +371,15 @@ Bytes encodeSettings(const Settings &s)
|
||||
j["layoutHotkeys"].push_back({{"layoutId", utf8(s.directIds[i])}, {"hotkey", utf8(s.direct[i])}});
|
||||
j["snippets"] = Json::array();
|
||||
for (auto &sn : s.snippets)
|
||||
j["snippets"].push_back({{"trigger", utf8(sn.trigger)}, {"text", utf8(sn.text)}, {"id", utf8(snippetId(sn))}});
|
||||
{
|
||||
Json item{{"trigger", utf8(sn.trigger)}, {"text", utf8(sn.text)}, {"id", utf8(snippetId(sn))}};
|
||||
if (!sn.apps.empty())
|
||||
{
|
||||
item["apps"] = Json::array();
|
||||
for (const auto &app : sn.apps) item["apps"].push_back(utf8(snippetAppName(app)));
|
||||
}
|
||||
j["snippets"].push_back(std::move(item));
|
||||
}
|
||||
j["snippetTombstones"] = Json::array();
|
||||
for (const auto &id : s.snippetTombstones) j["snippetTombstones"].push_back(utf8(id));
|
||||
j["excludedApps"] = Json::array();
|
||||
@@ -343,6 +403,20 @@ Bytes encodeClip(const Clip &clip)
|
||||
}
|
||||
return b;
|
||||
}
|
||||
Bytes selectionClipboardIdentity(const Clip &clip)
|
||||
{
|
||||
auto normalized = clip;
|
||||
// GlobalSize includes allocation slack. A clipboard relay may allocate a
|
||||
// different-sized block for the same NUL-terminated Unicode string.
|
||||
for (auto &format : normalized.formats)
|
||||
if (format.id == CF_UNICODETEXT)
|
||||
format = textClip(clip.text()).formats.front();
|
||||
std::sort(normalized.formats.begin(), normalized.formats.end(), [](const Format &a, const Format &b)
|
||||
{
|
||||
return std::tie(a.name, a.id) < std::tie(b.name, b.id);
|
||||
});
|
||||
return encodeClip(normalized);
|
||||
}
|
||||
Clip decodeClip(const Bytes &b)
|
||||
{
|
||||
size_t p = 0;
|
||||
@@ -374,9 +448,17 @@ Clip decodeClip(const Bytes &b)
|
||||
History::History(const std::filesystem::path &folder) : folder_(folder)
|
||||
{
|
||||
std::filesystem::create_directories(folder_);
|
||||
loadIndex();
|
||||
}
|
||||
void History::loadIndex()
|
||||
{
|
||||
std::vector<Entry> loaded;
|
||||
auto index = folder_ / L"index.dat";
|
||||
if (!std::filesystem::exists(index))
|
||||
{
|
||||
entries_.clear();
|
||||
return;
|
||||
}
|
||||
auto j = parse(unprotect(readFile(index, 16 * 1024 * 1024)));
|
||||
if (!j.is_array() || j.size() > 10000)
|
||||
throw std::runtime_error("Invalid history index");
|
||||
@@ -391,8 +473,170 @@ History::History(const std::filesystem::path &folder) : folder_(folder)
|
||||
e.value("image", false),
|
||||
e.value("files", false), e.value("ocrState", e.value("image", false) ? 1 : 0),
|
||||
str(e, "ocrProfile", L"windows")};
|
||||
item.computer=e.value("computer",std::string{});item.computerName=str(e,"computerName");
|
||||
if (e.value("fingerprintVersion", 0) == 1) {
|
||||
item.contentHash = e.value("contentHash", std::string{});
|
||||
item.imageHash = e.value("imageHash", std::string{});
|
||||
item.pixelHash = e.value("pixelHash", std::string{});
|
||||
}
|
||||
if (validId(item.id) && std::filesystem::exists(folder_ / (item.id + L".dat")))
|
||||
entries_.push_back(std::move(item));
|
||||
loaded.push_back(std::move(item));
|
||||
}
|
||||
entries_ = std::move(loaded);
|
||||
}
|
||||
void History::reload() { std::lock_guard lock(mutex_); loadIndex(); }
|
||||
void ClipboardSnapshot::cleanup() noexcept
|
||||
{
|
||||
if (request_.empty()) return;
|
||||
std::error_code ignored;
|
||||
for (const auto *suffix : {L"", L".snapshot", L".result"})
|
||||
std::filesystem::remove(std::filesystem::path(request_.wstring() + suffix), ignored);
|
||||
request_.clear();
|
||||
}
|
||||
ClipboardSnapshot::~ClipboardSnapshot() { cleanup(); }
|
||||
DWORD ClipboardSnapshot::run(bool restore, DWORD sequence)
|
||||
{
|
||||
atomicWrite(request_, protect(jsonBytes(Json{{"schema", 1}, {"restore", restore}, {"sequence", sequence}})));
|
||||
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
|
||||
auto command = L"\"" + helper.wstring() + L"\" --clipboard-snapshot \"" + request_.wstring() + L"\"";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
|
||||
PROCESS_INFORMATION process{};
|
||||
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
|
||||
nullptr, helper.parent_path().c_str(), &startup, &process))
|
||||
throw std::runtime_error("Cannot start clipboard snapshot helper");
|
||||
CloseHandle(process.hThread);
|
||||
auto wait = WaitForSingleObject(process.hProcess, 10000);
|
||||
DWORD result = ERROR_GEN_FAILURE;
|
||||
if (wait != WAIT_OBJECT_0)
|
||||
{
|
||||
TerminateProcess(process.hProcess, ERROR_TIMEOUT);
|
||||
WaitForSingleObject(process.hProcess, INFINITE);
|
||||
}
|
||||
GetExitCodeProcess(process.hProcess, &result);
|
||||
CloseHandle(process.hProcess);
|
||||
if (wait != WAIT_OBJECT_0 || result) throw std::runtime_error("Clipboard snapshot helper failed");
|
||||
return parse(unprotect(readFile(request_.wstring() + L".result", 4096))).at("sequence").get<DWORD>();
|
||||
}
|
||||
void ClipboardSnapshot::capture(HWND window, DWORD sequence)
|
||||
{
|
||||
cleanup();
|
||||
clip_ = {};
|
||||
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
|
||||
!IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")))
|
||||
{
|
||||
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence);
|
||||
return;
|
||||
}
|
||||
request_ = std::filesystem::temp_directory_path() / (L"ks-clipboard-" + newSnippetId() + L".request");
|
||||
try { run(false, sequence); }
|
||||
catch (...) { cleanup(); throw; }
|
||||
}
|
||||
DWORD ClipboardSnapshot::restore(HWND window, DWORD sequence)
|
||||
{
|
||||
return request_.empty() ? writeClipboardGuarded(window, clip_, sequence) : run(true, sequence);
|
||||
}
|
||||
int runClipboardSnapshot(const std::filesystem::path &request)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!request.is_absolute() || !request.filename().wstring().starts_with(L"ks-clipboard-") ||
|
||||
request.extension() != L".request") return 1;
|
||||
auto job = parse(unprotect(readFile(request, 4096)));
|
||||
if (job.at("schema") != 1) return 1;
|
||||
auto sequence = job.at("sequence").get<DWORD>();
|
||||
const auto snapshot = request.wstring() + L".snapshot";
|
||||
if (job.at("restore").get<bool>())
|
||||
{
|
||||
auto clip = decodeClip(unprotect(readFile(snapshot, 70 * 1024 * 1024)));
|
||||
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
|
||||
if (!window) return 1;
|
||||
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
|
||||
sequence = writeClipboardGuarded(window, clip, sequence);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
|
||||
if (sequence != GetClipboardSequenceNumber()) return 2;
|
||||
atomicWrite(snapshot, protect(encodeClip(clip)));
|
||||
}
|
||||
atomicWrite(request.wstring() + L".result", protect(jsonBytes(Json{{"sequence", sequence}})));
|
||||
return 0;
|
||||
}
|
||||
catch (...) { return 1; }
|
||||
}
|
||||
bool History::captureImage(DWORD sequence, const std::wstring &app, const Settings &settings)
|
||||
{
|
||||
// Serialize helper index changes with all resident history mutations. Only
|
||||
// metadata is reloaded: GetClipboardData's image allocations die with the child.
|
||||
std::lock_guard lock(mutex_);
|
||||
if (sequence != GetClipboardSequenceNumber()) return false;
|
||||
auto request = std::filesystem::absolute(folder_) / (L"capture-" + newSnippetId() + L".request");
|
||||
struct Cleanup {
|
||||
std::filesystem::path path;
|
||||
~Cleanup() { std::error_code ignored; std::filesystem::remove(path, ignored); }
|
||||
} cleanup{request};
|
||||
Json job{{"schema", 1}, {"sequence", sequence}, {"app", utf8(app)},
|
||||
{"settings", Json::parse(encodeSettings(settings))}};
|
||||
atomicWrite(request, protect(jsonBytes(job)));
|
||||
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
|
||||
auto command = L"\"" + helper.wstring() + L"\" --capture-history \"" + request.wstring() + L"\"";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
|
||||
PROCESS_INFORMATION process{};
|
||||
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
|
||||
nullptr, helper.parent_path().c_str(), &startup, &process))
|
||||
throw std::runtime_error(utf8(lastError(L"Cannot start image history helper")));
|
||||
CloseHandle(process.hThread);
|
||||
auto wait = WaitForSingleObject(process.hProcess, 30000);
|
||||
DWORD result = ERROR_GEN_FAILURE;
|
||||
if (wait != WAIT_OBJECT_0)
|
||||
{
|
||||
// Never release the index lock while a timed-out child can still write it.
|
||||
TerminateProcess(process.hProcess, ERROR_TIMEOUT);
|
||||
WaitForSingleObject(process.hProcess, INFINITE);
|
||||
}
|
||||
GetExitCodeProcess(process.hProcess, &result);
|
||||
CloseHandle(process.hProcess);
|
||||
loadIndex(); // Also reconcile any completed atomic save before a child failure.
|
||||
if (wait != WAIT_OBJECT_0) throw std::runtime_error("Image history helper timed out");
|
||||
if (result == 2) return false;
|
||||
if (result == 3) throw std::runtime_error("Clipboard exceeds the configured size limit");
|
||||
if (result) throw std::runtime_error("Image history helper failed: " + std::to_string(result));
|
||||
return true;
|
||||
}
|
||||
int runImageHistoryCapture(const std::filesystem::path &request)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!request.is_absolute() || !request.filename().wstring().starts_with(L"capture-") ||
|
||||
request.extension() != L".request") return 1;
|
||||
auto job = parse(unprotect(readFile(request, 4 * 1024 * 1024)));
|
||||
if (job.at("schema") != 1) return 1;
|
||||
auto sequence = job.at("sequence").get<DWORD>();
|
||||
auto settings = decodeSettings(jsonBytes(job.at("settings")), readLayouts());
|
||||
auto valid = [&] {
|
||||
return settings.history && sequence == GetClipboardSequenceNumber() &&
|
||||
!IsClipboardFormatAvailable(RegisterClipboardFormatW(L"ExcludeClipboardContentFromMonitorProcessing")) &&
|
||||
!IsClipboardFormatAvailable(RegisterClipboardFormatW(L"Clipboard Viewer Ignore"));
|
||||
};
|
||||
if (!valid()) return 2;
|
||||
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
|
||||
!IsClipboardFormatAvailable(CF_BITMAP) &&
|
||||
!IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))) return 2;
|
||||
auto clip = readClipboard(nullptr, size_t(settings.maxImageMiB) * 1024 * 1024);
|
||||
if (!valid()) return 2;
|
||||
for (const auto &format : clip.formats)
|
||||
if (format.name == L"CanIncludeInClipboardHistory" && format.data.size() >= 4 &&
|
||||
!format.data[0] && !format.data[1] && !format.data[2] && !format.data[3]) return 2;
|
||||
History history(request.parent_path());
|
||||
if (!valid()) return 2;
|
||||
history.add(clip, str(job, "app"), settings);
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
return std::string(e.what()) == "Clipboard exceeds the configured size limit" ? 3 : 1;
|
||||
}
|
||||
}
|
||||
void History::saveIndex()
|
||||
@@ -401,12 +645,14 @@ void History::saveIndex()
|
||||
for (const auto &e : entries_)
|
||||
j.push_back({{"id", utf8(e.id)},
|
||||
{"preview", utf8(e.preview)},
|
||||
{"app", utf8(e.app)},
|
||||
{"app", utf8(e.app)}, {"computer", e.computer}, {"computerName", utf8(e.computerName)},
|
||||
{"bytes", e.bytes},
|
||||
{"at", e.at},
|
||||
{"pinned", e.pinned},
|
||||
{"image", e.image},
|
||||
{"files", e.files}, {"ocrState", e.ocrState}, {"ocrProfile", utf8(e.ocrProfile)}});
|
||||
{"files", e.files}, {"ocrState", e.ocrState}, {"ocrProfile", utf8(e.ocrProfile)},
|
||||
{"fingerprintVersion", 1}, {"contentHash", e.contentHash},
|
||||
{"imageHash", e.imageHash}, {"pixelHash", e.pixelHash}});
|
||||
atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j)));
|
||||
}
|
||||
std::vector<Entry> History::entries() const
|
||||
@@ -439,12 +685,10 @@ void History::prune(const Settings &s)
|
||||
entries_.erase(entries_.begin() + i);
|
||||
}
|
||||
}
|
||||
bool sameClipboardImage(const Clip &a, const Clip &b)
|
||||
static const Format *clipboardImageFormat(const Clip &c)
|
||||
{
|
||||
// OLE DataObject / Ole Private Data change when Snipping Tool republishes
|
||||
// the same capture. They are transport metadata, not image identity.
|
||||
auto image = [](const Clip &c) -> const Format *
|
||||
{
|
||||
if (!c.text().empty())
|
||||
return nullptr;
|
||||
for (const auto &f : c.formats)
|
||||
@@ -458,8 +702,42 @@ bool sameClipboardImage(const Clip &a, const Clip &b)
|
||||
if (f.id == id && !f.data.empty())
|
||||
return &f;
|
||||
return nullptr;
|
||||
};
|
||||
const auto *left = image(a), *right = image(b);
|
||||
}
|
||||
static std::string clipboardHash(const Bytes &bytes)
|
||||
{
|
||||
struct Hash {
|
||||
HCRYPTPROV provider{}; HCRYPTHASH hash{};
|
||||
~Hash() { if (hash) CryptDestroyHash(hash); if (provider) CryptReleaseContext(provider, 0); }
|
||||
} state;
|
||||
if (!CryptAcquireContextW(&state.provider, nullptr, nullptr, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) ||
|
||||
!CryptCreateHash(state.provider, CALG_SHA_256, 0, 0, &state.hash) ||
|
||||
!CryptHashData(state.hash, bytes.data(), static_cast<DWORD>(bytes.size()), 0))
|
||||
throw std::runtime_error("Cannot hash clipboard data");
|
||||
BYTE digest[32]{}; DWORD size = sizeof(digest);
|
||||
if (!CryptGetHashParam(state.hash, HP_HASHVAL, digest, &size, 0) || size != sizeof(digest))
|
||||
throw std::runtime_error("Cannot read clipboard hash");
|
||||
static constexpr char hex[] = "0123456789abcdef";
|
||||
std::string result; result.reserve(64);
|
||||
for (auto b : digest) { result += hex[b >> 4]; result += hex[b & 15]; }
|
||||
return result;
|
||||
}
|
||||
static void imageFingerprints(Entry &entry, const Clip &clip, bool decodePixels = true)
|
||||
{
|
||||
const auto *image = clipboardImageFormat(clip);
|
||||
if (!image) return;
|
||||
if (entry.imageHash.empty())
|
||||
entry.imageHash = std::to_string(image->id) + ":" + utf8(image->name) + ":" + clipboardHash(image->data);
|
||||
if (!decodePixels) return;
|
||||
try {
|
||||
auto pixels = decodeImage(clip);
|
||||
entry.pixelHash = std::to_string(pixels.width) + "x" + std::to_string(pixels.height) + ":" + clipboardHash(pixels.bgra);
|
||||
} catch (const std::exception &) {
|
||||
// Undecodable images can still be compared by their original bytes.
|
||||
}
|
||||
}
|
||||
bool sameClipboardImage(const Clip &a, const Clip &b)
|
||||
{
|
||||
const auto *left = clipboardImageFormat(a), *right = clipboardImageFormat(b);
|
||||
if (!left || !right)
|
||||
return false;
|
||||
if (left->id == right->id && left->name == right->name && left->data == right->data)
|
||||
@@ -476,22 +754,47 @@ bool sameClipboardImage(const Clip &a, const Clip &b)
|
||||
return false; // Undecodable data is not evidence of a duplicate.
|
||||
}
|
||||
}
|
||||
void History::add(const Clip &clip, const std::wstring &app, const Settings &s)
|
||||
void History::add(const Clip &clip, const std::wstring &app, const Settings &s, const std::string &computer, const std::wstring &computerName)
|
||||
{
|
||||
if (clip.formats.empty() || !clip.size())
|
||||
return;
|
||||
auto data = encodeClip(clip);
|
||||
if (data.size() > uint64_t(s.maxImageMiB) * 1024 * 1024)
|
||||
return;
|
||||
bool image = false, files = false;
|
||||
for (const auto &f : clip.formats)
|
||||
{
|
||||
image |= f.id == CF_DIB || f.id == CF_DIBV5 || f.name == L"PNG";
|
||||
files |= f.id == CF_HDROP;
|
||||
}
|
||||
std::lock_guard lock(mutex_);
|
||||
// Compare only the newest record; never keep image payloads in the resident index.
|
||||
if (!entries_.empty())
|
||||
Entry fingerprints;
|
||||
fingerprints.contentHash = clipboardHash(data);
|
||||
if (!entries_.empty() && entries_.front().computer == computer && entries_.front().contentHash == fingerprints.contentHash)
|
||||
return;
|
||||
imageFingerprints(fingerprints, clip, false);
|
||||
if (!entries_.empty() && entries_.front().computer == computer && !fingerprints.imageHash.empty() && entries_.front().imageHash == fingerprints.imageHash)
|
||||
return;
|
||||
imageFingerprints(fingerprints, clip);
|
||||
// Different payload kinds cannot be duplicates. Consult the index first so
|
||||
// copying text after a screenshot never loads/decrypts the previous image.
|
||||
if (!entries_.empty() && entries_.front().computer == computer && entries_.front().image == image && entries_.front().files == files)
|
||||
{
|
||||
try
|
||||
{
|
||||
auto previous = load(entries_.front().id);
|
||||
if (encodeClip(previous) == data || sameClipboardImage(previous, clip))
|
||||
auto &previous = entries_.front();
|
||||
bool migrated = previous.contentHash.empty();
|
||||
if (migrated) {
|
||||
auto oldClip = load(previous.id);
|
||||
previous.contentHash = clipboardHash(encodeClip(oldClip));
|
||||
imageFingerprints(previous, oldClip);
|
||||
}
|
||||
if (previous.contentHash == fingerprints.contentHash ||
|
||||
(!fingerprints.imageHash.empty() && previous.imageHash == fingerprints.imageHash) ||
|
||||
(!fingerprints.pixelHash.empty() && previous.pixelHash == fingerprints.pixelHash)) {
|
||||
if (migrated) saveIndex();
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
@@ -506,12 +809,6 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s)
|
||||
auto encrypted = protect(data);
|
||||
atomicWrite(folder_ / (id + L".dat"), encrypted);
|
||||
auto text = clip.text();
|
||||
bool image = false, files = false;
|
||||
for (auto &f : clip.formats)
|
||||
{
|
||||
image |= f.id == CF_DIB || f.id == CF_DIBV5 || f.name == L"PNG";
|
||||
files |= f.id == CF_HDROP;
|
||||
}
|
||||
if (text.empty())
|
||||
text = files ? L"[Files]" : image ? L"[Image]" : L"[Clipboard data]";
|
||||
for (auto &c : text)
|
||||
@@ -524,7 +821,8 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s)
|
||||
entries_.insert(entries_.begin(),
|
||||
Entry{id, text, app, encrypted.size(),
|
||||
(uint64_t(now.dwHighDateTime) << 32) | now.dwLowDateTime, false, image, files,
|
||||
image ? 1 : 0, ocrProfile(s)});
|
||||
image ? 1 : 0, ocrProfile(s), std::move(fingerprints.contentHash),
|
||||
std::move(fingerprints.imageHash), std::move(fingerprints.pixelHash), computer, computerName});
|
||||
prune(s);
|
||||
saveIndex();
|
||||
}
|
||||
@@ -563,6 +861,103 @@ void History::clear()
|
||||
std::filesystem::remove(folder_ / (e.id + L".ocr"), ec);
|
||||
}
|
||||
}
|
||||
static Bytes historyImageJob(const std::filesystem::path &folder, const std::wstring &id,
|
||||
const Json &job, const std::function<bool()> &cancelled)
|
||||
{
|
||||
if (!validId(id)) throw std::runtime_error("Invalid history ID");
|
||||
if (cancelled && cancelled()) throw std::runtime_error("History OCR cancelled");
|
||||
auto request = std::filesystem::absolute(folder) / (L"ocr-" + newSnippetId() + L".request");
|
||||
auto response = request; response += L".result";
|
||||
struct Cleanup {
|
||||
std::filesystem::path request, response;
|
||||
~Cleanup() {
|
||||
std::error_code ignored;
|
||||
std::filesystem::remove(request, ignored);
|
||||
std::filesystem::remove(response, ignored);
|
||||
}
|
||||
} cleanup{request, response};
|
||||
atomicWrite(request, protect(jsonBytes(job)));
|
||||
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
|
||||
auto command = L"\"" + helper.wstring() + L"\" --history-ocr \"" + request.wstring() + L"\"";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
|
||||
PROCESS_INFORMATION process{};
|
||||
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
|
||||
nullptr, helper.parent_path().c_str(), &startup, &process))
|
||||
throw std::runtime_error(utf8(lastError(L"Cannot start history OCR helper")));
|
||||
CloseHandle(process.hThread);
|
||||
struct Child {
|
||||
HANDLE handle;
|
||||
~Child() {
|
||||
if (WaitForSingleObject(handle, 0) != WAIT_OBJECT_0) {
|
||||
TerminateProcess(handle, ERROR_CANCELLED);
|
||||
WaitForSingleObject(handle, INFINITE);
|
||||
}
|
||||
CloseHandle(handle);
|
||||
}
|
||||
} child{process.hProcess};
|
||||
auto deadline = GetTickCount64() + 60000;
|
||||
for (;;) {
|
||||
auto wait = WaitForSingleObject(child.handle, 100);
|
||||
if (wait == WAIT_OBJECT_0) break;
|
||||
if (wait != WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper");
|
||||
if (cancelled && cancelled()) throw std::runtime_error("History OCR cancelled");
|
||||
if (GetTickCount64() >= deadline) throw std::runtime_error("History OCR helper timed out");
|
||||
}
|
||||
DWORD result{};
|
||||
if (!GetExitCodeProcess(child.handle, &result) || result)
|
||||
throw std::runtime_error("History OCR helper failed: " + std::to_string(result));
|
||||
return unprotect(readFile(response, 8 * 1024 * 1024));
|
||||
}
|
||||
std::wstring History::recognizeImage(const std::wstring &id, const Settings &settings,
|
||||
const std::function<bool()> &cancelled) const
|
||||
{
|
||||
Json job{{"schema", 1}, {"id", utf8(id)}, {"tesseract", settings.useTesseract},
|
||||
{"path", utf8(settings.tesseractPath)}, {"languages", utf8(settings.tesseractLanguages)}};
|
||||
auto reply = parse(historyImageJob(folder_, id, job, cancelled));
|
||||
if (reply.at("schema") != 1 || str(reply, "id") != id)
|
||||
throw std::runtime_error("Invalid history OCR response");
|
||||
return str(reply, "text");
|
||||
}
|
||||
Pixels History::thumbnail(const std::wstring &id, const std::function<bool()> &cancelled) const
|
||||
{
|
||||
auto bytes = historyImageJob(folder_, id, Json{{"schema", 1}, {"id", utf8(id)}, {"thumbnail", true}}, cancelled);
|
||||
size_t at = 0;
|
||||
auto width = get32(bytes, at), height = get32(bytes, at);
|
||||
if (!width || !height || width > 208 || height > 128 || bytes.size() - at != width * height * 4)
|
||||
throw std::runtime_error("Invalid history thumbnail response");
|
||||
bytes.erase(bytes.begin(), bytes.begin() + at);
|
||||
return Pixels{width, height, std::move(bytes)};
|
||||
}
|
||||
int runHistoryOcr(const std::filesystem::path &request)
|
||||
{
|
||||
try {
|
||||
if (!request.is_absolute() || !request.filename().wstring().starts_with(L"ocr-") ||
|
||||
request.extension() != L".request") return 1;
|
||||
auto job = parse(unprotect(readFile(request, 1024 * 1024)));
|
||||
auto id = str(job, "id");
|
||||
if (job.at("schema") != 1 || !validId(id)) return 1;
|
||||
auto clip = decodeClip(unprotect(readFile(request.parent_path() / (id + L".dat"), 80 * 1024 * 1024)));
|
||||
if (job.value("thumbnail", false)) {
|
||||
auto pixels = decodeImage(clip, 208, 128);
|
||||
if (!pixels.width || !pixels.height) return 1;
|
||||
Bytes reply;
|
||||
put32(reply, pixels.width); put32(reply, pixels.height);
|
||||
reply.insert(reply.end(), pixels.bgra.begin(), pixels.bgra.end());
|
||||
atomicWrite(request.wstring() + L".result", protect(reply));
|
||||
return 0;
|
||||
}
|
||||
Settings settings;
|
||||
settings.useTesseract = job.at("tesseract").get<bool>();
|
||||
settings.tesseractPath = str(job, "path");
|
||||
settings.tesseractLanguages = str(job, "languages");
|
||||
auto text = utf8(recognizeText(clip, settings));
|
||||
if (text.size() > 1024 * 1024) return 1;
|
||||
auto response = request; response += L".result";
|
||||
atomicWrite(response, protect(jsonBytes(Json{{"schema", 1}, {"id", utf8(id)}, {"text", text}})));
|
||||
return 0;
|
||||
} catch (...) { return 1; }
|
||||
}
|
||||
bool History::saveOcr(const std::wstring &id, const std::optional<std::wstring> &text, const Settings &settings)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
@@ -603,9 +998,10 @@ std::optional<std::wstring> History::ocrText(const std::wstring &id, const std::
|
||||
if (bytes.empty() || bytes.front() != 1) throw std::runtime_error("Invalid OCR text format");
|
||||
return wide(std::string(bytes.begin() + 1, bytes.end()));
|
||||
}
|
||||
std::vector<Entry> History::search(const std::wstring &query) const
|
||||
std::vector<Entry> History::search(const std::wstring &query, bool pinnedOnly) const
|
||||
{
|
||||
auto items = entries();
|
||||
if (pinnedOnly) std::erase_if(items, [](const Entry &entry) { return !entry.pinned; });
|
||||
if (query.empty())
|
||||
return items;
|
||||
auto q = lower(query);
|
||||
|
||||
+32
-2
@@ -1,8 +1,10 @@
|
||||
#pragma once
|
||||
#include "platform.h"
|
||||
#include <mutex>
|
||||
#include <functional>
|
||||
namespace ks
|
||||
{
|
||||
struct Pixels;
|
||||
Settings loadSettings(const std::filesystem::path &, const std::vector<Layout> &);
|
||||
Settings decodeSettings(const Bytes &, const std::vector<Layout> &);
|
||||
Bytes encodeSettings(const Settings &);
|
||||
@@ -15,6 +17,9 @@ struct Entry
|
||||
bool pinned{}, image{}, files{};
|
||||
int ocrState{}; // 0: legacy/not applicable, 1: pending, 2: saved, 3: failed
|
||||
std::wstring ocrProfile = L"windows";
|
||||
std::string contentHash, imageHash, pixelHash;
|
||||
std::string computer;
|
||||
std::wstring computerName;
|
||||
};
|
||||
class History
|
||||
{
|
||||
@@ -22,21 +27,46 @@ class History
|
||||
std::vector<Entry> entries_;
|
||||
mutable std::mutex mutex_;
|
||||
void saveIndex();
|
||||
void loadIndex();
|
||||
void prune(const Settings &);
|
||||
|
||||
public:
|
||||
explicit History(const std::filesystem::path &);
|
||||
void reload();
|
||||
std::vector<Entry> entries() const;
|
||||
Clip load(const std::wstring &id) const;
|
||||
void add(const Clip &, const std::wstring &app, const Settings &);
|
||||
void add(const Clip &, const std::wstring &app, const Settings &, const std::string &computer = {}, const std::wstring &computerName = {});
|
||||
bool captureImage(DWORD sequence, const std::wstring &app, const Settings &);
|
||||
std::wstring recognizeImage(const std::wstring &id, const Settings &,
|
||||
const std::function<bool()> &cancelled = {}) const;
|
||||
Pixels thumbnail(const std::wstring &id, const std::function<bool()> &cancelled = {}) const;
|
||||
bool saveOcr(const std::wstring &id, const std::optional<std::wstring> &, const Settings &);
|
||||
std::optional<std::wstring> ocrText(const std::wstring &id, const std::wstring &profile = L"") const;
|
||||
void remove(const std::wstring &);
|
||||
void pin(const std::wstring &);
|
||||
void clear();
|
||||
std::vector<Entry> search(const std::wstring &) const;
|
||||
std::vector<Entry> search(const std::wstring &, bool pinnedOnly = false) const;
|
||||
};
|
||||
Bytes encodeClip(const Clip &);
|
||||
Bytes selectionClipboardIdentity(const Clip &);
|
||||
Clip decodeClip(const Bytes &);
|
||||
bool sameClipboardImage(const Clip &, const Clip &);
|
||||
int runImageHistoryCapture(const std::filesystem::path &request);
|
||||
int runHistoryOcr(const std::filesystem::path &request);
|
||||
// Image backups stay encrypted on disk and are read/written only by a short-lived helper.
|
||||
class ClipboardSnapshot
|
||||
{
|
||||
Clip clip_;
|
||||
std::filesystem::path request_;
|
||||
void cleanup() noexcept;
|
||||
DWORD run(bool restore, DWORD sequence);
|
||||
public:
|
||||
ClipboardSnapshot() = default;
|
||||
ClipboardSnapshot(const ClipboardSnapshot &) = delete;
|
||||
ClipboardSnapshot &operator=(const ClipboardSnapshot &) = delete;
|
||||
~ClipboardSnapshot();
|
||||
void capture(HWND, DWORD sequence);
|
||||
DWORD restore(HWND, DWORD sequence);
|
||||
};
|
||||
int runClipboardSnapshot(const std::filesystem::path &request);
|
||||
} // namespace ks
|
||||
@@ -38,6 +38,42 @@ inline double cross(Point a, Point b, Point c) { return (b.x-a.x)*(c.y-a.y)-(b.y
|
||||
}
|
||||
|
||||
namespace ks {
|
||||
// Filter by distance along the path, not mouse-event count. Always start from
|
||||
// the original path so lowering the amount restores detail without drift.
|
||||
inline std::vector<POINT> smoothScreenshotStroke(const std::vector<POINT> &input, int amount) {
|
||||
amount=std::clamp(amount,0,100);
|
||||
if(!amount || input.size()<5) return input;
|
||||
using namespace stroke_detail;
|
||||
std::vector<Point> raw;
|
||||
for(auto p:input) if(raw.empty() || distance(raw.back(),{double(p.x),double(p.y)})>0)
|
||||
raw.push_back({double(p.x),double(p.y)});
|
||||
double total=length(raw);
|
||||
if(raw.size()<5 || total<16) return input;
|
||||
auto points=sample(raw,size_t(std::clamp(std::ceil(total/2)+1,3.0,4096.0)));
|
||||
double step=total/(points.size()-1),radius=0.5+32*std::pow(amount/100.0,2);
|
||||
int reach=std::max(1,int(std::ceil(radius/step)));
|
||||
std::vector<POINT> result;
|
||||
for(size_t i=0;i<points.size();++i) {
|
||||
Point sum{}; double weights=0;
|
||||
for(int j=std::max(0,int(i)-reach);j<=std::min(int(points.size())-1,int(i)+reach);++j) {
|
||||
double d=(j-double(i))*step,weight=std::exp(-2*d*d/(radius*radius));
|
||||
sum.x+=points[j].x*weight; sum.y+=points[j].y*weight; weights+=weight;
|
||||
}
|
||||
double blend=std::min(1.0,std::min(i,points.size()-1-i)*step/radius);
|
||||
POINT p{LONG(std::lround(points[i].x+blend*(sum.x/weights-points[i].x))),
|
||||
LONG(std::lround(points[i].y+blend*(sum.y/weights-points[i].y)))};
|
||||
if(result.empty() || p.x!=result.back().x || p.y!=result.back().y) result.push_back(p);
|
||||
}
|
||||
result.front()=input.front(); result.back()=input.back();
|
||||
return result;
|
||||
}
|
||||
inline void setScreenshotSmoothing(ScreenshotMark &mark,int amount) {
|
||||
if(!mark.freehand || mark.shape!=ScreenshotShape::None || mark.points.empty()) return;
|
||||
if(mark.rawPoints.empty()) mark.rawPoints=mark.points;
|
||||
mark.smoothing=std::clamp(amount,0,100);
|
||||
mark.points=smoothScreenshotStroke(mark.rawPoints,mark.smoothing);
|
||||
mark.from=mark.points.front(); mark.to=mark.points.back();
|
||||
}
|
||||
// Returns a replacement path; an empty result means no visible improvement.
|
||||
// Report recognized geometry separately from a smoothed freehand path.
|
||||
inline std::vector<POINT> improveScreenshotStroke(const std::vector<POINT> &input, ScreenshotShape *shape=nullptr,
|
||||
|
||||
+6
-1
@@ -229,6 +229,9 @@ Settings restoreSyncSettings(const Bytes &shared, const Settings &local, const s
|
||||
if (!j.contains("autoCorrectReplace")) j["autoCorrectReplace"] = false;
|
||||
if (!j.contains("autoCorrectTypos")) j["autoCorrectTypos"] = false;
|
||||
if (!j.contains("autoCorrectReplacements")) j["autoCorrectReplacements"] = Json::object();
|
||||
// Profiles uploaded before v0.6.53 do not participate in chat synchronization.
|
||||
// An explicit empty object from a newer client does mean remove all profiles.
|
||||
if (!j.contains("chatCycles")) j["chatCycles"] = original.at("chatCycles");
|
||||
auto allowed = parse(sharedSyncSettings(local));
|
||||
if (!j.is_object() || j.value("format", "") != "kswitcher-settings" || j.value("schemaVersion", 0) != 1)
|
||||
throw std::runtime_error("Unsupported synchronized settings format.");
|
||||
@@ -294,7 +297,9 @@ SyncResult synchronize(SyncProvider &provider, const Bytes &base, const Bytes &l
|
||||
if (action == SyncAction::Automatic) merged = mergeSyncProfile(mergeBase, mergeLocal, remote.settings, choices);
|
||||
else
|
||||
{
|
||||
auto selected = bytes(normalizeProfile(parse(action == SyncAction::Download ? remote.settings : mergeLocal)));
|
||||
auto profile = parse(action == SyncAction::Download ? remote.settings : mergeLocal);
|
||||
if (!profile.contains("chatCycles")) profile["chatCycles"] = parse(local).value("chatCycles", Json::object());
|
||||
auto selected = bytes(normalizeProfile(profile));
|
||||
merged = {selected, selected, selected, {}};
|
||||
}
|
||||
if (validate) { validate(merged.local); validate(merged.remote); }
|
||||
|
||||
+25
-3
@@ -8,6 +8,7 @@ Json normalizeProfile(Json j)
|
||||
if (!j.contains("autoCorrectTypos")) j["autoCorrectTypos"] = false;
|
||||
if (!j.contains("autoCorrectReplacements")) j["autoCorrectReplacements"] = Json::object();
|
||||
if (!j.contains("snippetTombstones")) j["snippetTombstones"] = Json::array();
|
||||
if (!j.contains("chatCycles")) j["chatCycles"] = Json::object();
|
||||
for (auto &sn : j.at("snippets"))
|
||||
if (!sn.contains("id")) sn["id"] = utf8(snippetId({wide(sn.at("trigger").get<std::string>()), L""}));
|
||||
return j;
|
||||
@@ -53,6 +54,10 @@ Json flatProfile(Json j)
|
||||
for (auto it = replacements.begin(); it != replacements.end();)
|
||||
if (it.value().is_null()) it = replacements.erase(it);
|
||||
else ++it;
|
||||
auto &chats = j["chatCycles"];
|
||||
for (auto it = chats.begin(); it != chats.end();)
|
||||
if (it.value().is_null()) it = chats.erase(it);
|
||||
else ++it;
|
||||
Json snippets = Json::array(), deleted = Json::array();
|
||||
for (const auto &[id, item] : j.at("snippets").items())
|
||||
{
|
||||
@@ -94,6 +99,7 @@ std::wstring fieldLabel(const std::string &key)
|
||||
{"translitHotkey", L"Transliteration shortcut"}, {"undoHotkey", L"Undo shortcut"},
|
||||
{"clipboardHotkey", L"Clipboard shortcut"}, {"screenshotHotkey", L"Screenshot shortcut"},
|
||||
{"layouts", L"Layout cycle order"}, {"layoutHotkeys", L"Layout shortcuts"},
|
||||
{"chatCycles", L"Chat languages"},
|
||||
{"convertLastWord", L"Convert recent word"}, {"switchSystemLayout", L"Switch system layout"},
|
||||
{"autoCorrectMinLength", L"Minimum word length"}, {"autoCorrectMaxRank", L"Maximum word rank"},
|
||||
{"autoCorrectLayout", L"Automatic layout correction"}, {"autoCorrectLanguages", L"Dictionary languages"},
|
||||
@@ -141,6 +147,11 @@ MergeNode mergeNode(const Json &b, const Json &l, const Json &r, const std::stri
|
||||
auto item = get(l); if (item.is_null() || tombstone(item)) item = get(r);
|
||||
childLabel = L"Snippet: " + wide(item.is_object() ? item.value("trigger", key) : key);
|
||||
}
|
||||
if (path == "/chatCycles") {
|
||||
auto name = key;
|
||||
if (auto separator = name.find('\n'); separator != name.npos) name.replace(separator, 1, " / ");
|
||||
childLabel = L"Chat languages: " + wide(name);
|
||||
}
|
||||
auto child = mergeNode(get(b), get(l), get(r), path + "/" + pointerKey(key), childLabel, choices, conflicts, forced);
|
||||
// Keep nulls in the ancestor so deletion conflicts survive restarts.
|
||||
out.local[key] = child.local; out.remote[key] = child.remote; out.base[key] = child.base;
|
||||
@@ -158,8 +169,14 @@ void collisionPaths(const Json &j, std::set<std::string> &paths)
|
||||
if (sn.is_null() || tombstone(sn)) continue;
|
||||
auto path = "/snippets/" + pointerKey(id);
|
||||
auto key = lower(wide(sn.at("trigger").get<std::string>()));
|
||||
auto [it, inserted] = triggers.emplace(key, path);
|
||||
if (!inserted) { paths.insert(path); paths.insert(it->second); }
|
||||
std::vector<std::wstring> scopes;
|
||||
if (sn.contains("apps")) for (const auto &app : sn.at("apps")) scopes.push_back(snippetAppName(wide(app.get<std::string>())));
|
||||
if (scopes.empty()) scopes.push_back(L"");
|
||||
for (const auto &scope : scopes)
|
||||
{
|
||||
auto [it, inserted] = triggers.emplace(key + L"\n" + scope, path);
|
||||
if (!inserted) { paths.insert(path); paths.insert(it->second); }
|
||||
}
|
||||
}
|
||||
std::map<std::pair<UINT, UINT>, std::string> shortcuts;
|
||||
auto add = [&](const Json &text, const std::string &path) {
|
||||
@@ -175,7 +192,12 @@ void collisionPaths(const Json &j, std::set<std::string> &paths)
|
||||
}
|
||||
SyncMerge mergeSyncProfile(const Bytes &base, const Bytes &local, const Bytes &remote, const std::vector<SyncChoice> &choices)
|
||||
{
|
||||
auto l = treeProfile(parse(local)), r = treeProfile(parse(remote));
|
||||
auto localProfile = parse(local), remoteProfile = parse(remote);
|
||||
// Absence in an older client is not a deletion. Preserve the participating
|
||||
// client's chat profiles until both copies understand this field.
|
||||
if (!remoteProfile.contains("chatCycles")) remoteProfile["chatCycles"] = localProfile.value("chatCycles", Json::object());
|
||||
if (!localProfile.contains("chatCycles")) localProfile["chatCycles"] = remoteProfile.at("chatCycles");
|
||||
auto l = treeProfile(localProfile), r = treeProfile(remoteProfile);
|
||||
// With no common history, union independent entries; differing scalar values
|
||||
// remain on their respective devices until the user resolves the conflict.
|
||||
auto b = base.empty() ? Json::object() : treeProfile(parse(base));
|
||||
|
||||
+557
-88
@@ -1,3 +1,4 @@
|
||||
#include "lan_layout.h"
|
||||
#include "../resources/resource.h"
|
||||
#include "app.h"
|
||||
#include "history_preview.h"
|
||||
@@ -468,23 +469,32 @@ struct SearchResult
|
||||
uint64_t generation;
|
||||
std::vector<Entry> items;
|
||||
};
|
||||
struct TextPreview
|
||||
{
|
||||
std::string rtf;
|
||||
std::wstring plain;
|
||||
};
|
||||
struct PreviewResult
|
||||
{
|
||||
uint64_t generation;
|
||||
std::wstring id;
|
||||
Pixels pixels;
|
||||
std::string rtf;
|
||||
TextPreview text;
|
||||
};
|
||||
struct HistoryView
|
||||
{
|
||||
App *app{};
|
||||
std::vector<Entry> items;
|
||||
std::wstring rememberedSelection, rememberedTop;
|
||||
uint64_t generation{};
|
||||
std::shared_ptr<std::atomic<bool>> previewActive = std::make_shared<std::atomic<bool>>(true);
|
||||
std::map<std::wstring, Pixels> thumbnails;
|
||||
std::map<std::wstring, std::string> richTexts;
|
||||
std::map<std::wstring, TextPreview> richTexts;
|
||||
HWND rich{};
|
||||
std::set<std::wstring> pending;
|
||||
bool scrolling{};
|
||||
bool closed{};
|
||||
bool selectFirstOnResults{};
|
||||
};
|
||||
bool selectedImage(HWND w, HistoryView *v)
|
||||
{
|
||||
@@ -502,16 +512,22 @@ std::wstring selected(HWND w, HistoryView *v)
|
||||
}
|
||||
void search(HWND w, HistoryView *v)
|
||||
{
|
||||
v->previewActive->store(false);
|
||||
v->previewActive = std::make_shared<std::atomic<bool>>(true);
|
||||
v->closed = false;
|
||||
auto q = value(w, 101);
|
||||
const bool pinnedOnly = SendDlgItemMessageW(w, 117, BM_GETCHECK, 0, 0) == BST_CHECKED;
|
||||
auto generation = ++v->generation;
|
||||
v->pending.clear();
|
||||
auto *app = v->app;
|
||||
app->enqueueHistorySearch(
|
||||
[w, app, q, generation]
|
||||
[w, app, q, generation, pinnedOnly, computers=app->historyComputers]
|
||||
{
|
||||
try
|
||||
{
|
||||
auto result = new SearchResult{generation, app->history->search(q)};
|
||||
auto result = new SearchResult{generation, app->history->search(q, pinnedOnly)};
|
||||
if(!computers.empty())std::erase_if(result->items,[&](const Entry &e){return
|
||||
std::find(computers.begin(),computers.end(),e.computer)==computers.end();});
|
||||
if (!PostMessageW(w, ResultsMessage, 0, (LPARAM)result))
|
||||
delete result;
|
||||
}
|
||||
@@ -521,6 +537,79 @@ void search(HWND w, HistoryView *v)
|
||||
}
|
||||
});
|
||||
}
|
||||
struct ComputerFilter
|
||||
{
|
||||
HWND owner{},list{};HistoryView *view{};bool filling{};
|
||||
std::vector<std::pair<std::string,std::wstring>> computers;
|
||||
};
|
||||
LRESULT CALLBACK filterKeys(HWND w,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(msg==WM_KEYDOWN&&wp==VK_ESCAPE){DestroyWindow(GetParent(w));return 0;}
|
||||
if(msg==WM_NCDESTROY)RemoveWindowSubclass(w,filterKeys,1);
|
||||
return DefSubclassProc(w,msg,wp,lp);
|
||||
}
|
||||
LRESULT CALLBACK computerFilterProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
auto *f=reinterpret_cast<ComputerFilter*>(GetWindowLongPtrW(w,GWLP_USERDATA));
|
||||
if(msg==WM_NCCREATE){f=static_cast<ComputerFilter*>(reinterpret_cast<CREATESTRUCTW*>(lp)->lpCreateParams);SetWindowLongPtrW(w,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(f));}
|
||||
if(f&&msg==WM_NOTIFY&&!f->filling&&reinterpret_cast<NMHDR*>(lp)->code==LVN_ITEMCHANGED){
|
||||
auto *change=reinterpret_cast<NMLISTVIEW*>(lp);
|
||||
if(change->iItem>=0&&(change->uChanged&LVIF_STATE)&&((change->uOldState^change->uNewState)&LVIS_STATEIMAGEMASK)){
|
||||
f->filling=true;
|
||||
bool checked=ListView_GetCheckState(f->list,change->iItem)!=0;
|
||||
if(change->iItem==0)for(int i=1;i<=int(f->computers.size());++i)ListView_SetCheckState(f->list,i,checked);
|
||||
bool all=true;auto &chosen=f->view->app->historyComputers;chosen.clear();
|
||||
for(int i=0;i<int(f->computers.size());++i){if(ListView_GetCheckState(f->list,i+1))chosen.push_back(f->computers[i].first);else all=false;}
|
||||
ListView_SetCheckState(f->list,0,all);
|
||||
if(all)chosen.clear();else if(chosen.empty())chosen.push_back("__none");
|
||||
f->filling=false;
|
||||
SetDlgItemTextW(f->owner,118,all?L" Computers: All ▾":L" Computers: Selected ▾");
|
||||
search(f->owner,f->view);
|
||||
f->view->app->saveHistoryView(f->view->rememberedSelection,f->view->rememberedTop,value(f->owner,101),SendDlgItemMessageW(f->owner,117,BM_GETCHECK,0,0)==BST_CHECKED);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(msg==WM_ACTIVATE&&LOWORD(wp)==WA_INACTIVE){DestroyWindow(w);return 0;}
|
||||
if(msg==WM_CLOSE){DestroyWindow(w);return 0;}
|
||||
if(msg==WM_NCDESTROY){SetWindowLongPtrW(w,GWLP_USERDATA,0);delete f;}
|
||||
return DefWindowProcW(w,msg,wp,lp);
|
||||
}
|
||||
void showComputerFilter(HWND owner,HistoryView *v)
|
||||
{
|
||||
std::map<std::string,std::wstring> names{{"",L"This computer"}};
|
||||
for(auto &entry:v->app->history->entries())if(!entry.computer.empty())names[entry.computer]=entry.computerName;
|
||||
try{
|
||||
auto path=v->app->data/L"lan-pairing.bin";
|
||||
if(std::filesystem::exists(path)){
|
||||
auto config=nlohmann::json::parse(unprotect(readFile(path,256*1024)));
|
||||
for(auto &[id,peer]:config.at("trusted").items())names[id]=wide(peer.at("name").get<std::string>());
|
||||
}
|
||||
}catch(...){}
|
||||
auto *f=new ComputerFilter{owner,nullptr,v,true,{}};
|
||||
for(auto &[id,name]:names)f->computers.push_back({id,name});
|
||||
WNDCLASSW cls{};cls.lpfnWndProc=computerFilterProc;cls.hInstance=v->app->instance;cls.hCursor=LoadCursorW(nullptr,IDC_ARROW);cls.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);cls.lpszClassName=L"KSwitcher.ComputerFilter";RegisterClassW(&cls);
|
||||
RECT r{};GetWindowRect(GetDlgItem(owner,118),&r);
|
||||
int width=scale(owner,300),height=scale(owner,std::min(280,32+int(names.size()+1)*26));
|
||||
MONITORINFO monitor{sizeof(monitor)};GetMonitorInfoW(MonitorFromWindow(owner,MONITOR_DEFAULTTONEAREST),&monitor);
|
||||
int x=std::clamp(int(r.left),int(monitor.rcWork.left),std::max(int(monitor.rcWork.left),int(monitor.rcWork.right)-width));
|
||||
int y=r.bottom+height>monitor.rcWork.bottom?std::max(int(monitor.rcWork.top),int(r.top)-height):int(r.bottom);
|
||||
auto popup=CreateWindowExW(WS_EX_TOOLWINDOW,cls.lpszClassName,L"Computers",WS_POPUP|WS_BORDER,x,y,width,height,owner,nullptr,v->app->instance,f);
|
||||
if(!popup){delete f;return;}
|
||||
RECT client{};GetClientRect(popup,&client);
|
||||
f->list=CreateWindowExW(0,WC_LISTVIEWW,L"Computers",WS_CHILD|WS_VISIBLE|WS_TABSTOP|LVS_REPORT|LVS_NOCOLUMNHEADER|LVS_SINGLESEL,0,0,client.right,client.bottom,popup,nullptr,v->app->instance,nullptr);
|
||||
SendMessageW(f->list,WM_SETFONT,SendDlgItemMessageW(owner,118,WM_GETFONT,0,0),TRUE);
|
||||
ListView_SetExtendedListViewStyle(f->list,LVS_EX_CHECKBOXES|LVS_EX_FULLROWSELECT|LVS_EX_DOUBLEBUFFER);
|
||||
LVCOLUMNW column{LVCF_WIDTH};column.cx=client.right-scale(owner,24);ListView_InsertColumn(f->list,0,&column);
|
||||
auto &chosen=v->app->historyComputers;
|
||||
for(int i=0;i<=int(f->computers.size());++i){
|
||||
std::wstring label=i?f->computers[i-1].second:L"All computers";
|
||||
LVITEMW item{LVIF_TEXT};item.iItem=i;item.pszText=label.data();ListView_InsertItem(f->list,&item);
|
||||
bool checked=chosen.empty()||(i&&std::find(chosen.begin(),chosen.end(),f->computers[i-1].first)!=chosen.end());
|
||||
ListView_SetCheckState(f->list,i,checked);
|
||||
}
|
||||
f->filling=false;SetWindowSubclass(f->list,filterKeys,1,0);
|
||||
ShowWindow(popup,SW_SHOW);SetFocus(f->list);
|
||||
}
|
||||
void requestPreview(HWND w, HistoryView *v, const Entry &entry)
|
||||
{
|
||||
if(v->scrolling) return;
|
||||
@@ -529,23 +618,31 @@ void requestPreview(HWND w, HistoryView *v, const Entry &entry)
|
||||
if (v->thumbnails.contains(id) || v->richTexts.contains(id) || !v->pending.insert(id).second)
|
||||
return;
|
||||
auto generation = v->generation;
|
||||
auto active = v->previewActive;
|
||||
auto *app = v->app;
|
||||
app->enqueue(
|
||||
[w, app, id, generation, image]
|
||||
[w, app, id, generation, image, active]
|
||||
{
|
||||
if (!active->load()) return;
|
||||
auto result = new PreviewResult{generation, id, {}, {}};
|
||||
try
|
||||
{
|
||||
auto clip = app->history->load(id);
|
||||
if (image)
|
||||
result->pixels = decodeImage(clip, 208, 128);
|
||||
else
|
||||
result->rtf = richPreview(clip);
|
||||
result->pixels = app->history->thumbnail(id, [active] { return !active->load(); });
|
||||
else {
|
||||
auto clip = app->history->load(id);
|
||||
if (!active->load()) { delete result; return; }
|
||||
result->text.rtf = richPreview(clip, false);
|
||||
if (result->text.rtf.empty()) {
|
||||
result->text.plain = clip.text();
|
||||
if (result->text.plain.size() > 4096) result->text.plain.resize(4096);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
}
|
||||
if (!PostMessageW(w, PreviewMessage, 0, (LPARAM)result))
|
||||
if (!active->load() || !PostMessageW(w, PreviewMessage, 0, (LPARAM)result))
|
||||
delete result;
|
||||
});
|
||||
}
|
||||
@@ -599,9 +696,13 @@ void drawHistoryRow(HWND w, HistoryView *v, const DRAWITEMSTRUCT &draw)
|
||||
if (!entry.image && !entry.files)
|
||||
{
|
||||
auto rich = v->richTexts.find(entry.id);
|
||||
if (rich != v->richTexts.end() && v->rich && !rich->second.empty())
|
||||
if (rich != v->richTexts.end() && rich->second.rtf.empty())
|
||||
text = (entry.pinned ? L"★ " : L"") + rich->second.plain;
|
||||
if (rich != v->richTexts.end() && !rich->second.rtf.empty() && !v->rich)
|
||||
v->rich = createRichText(w, 105, false);
|
||||
if (rich != v->richTexts.end() && v->rich && !rich->second.rtf.empty())
|
||||
{
|
||||
setRichText(v->rich, rich->second);
|
||||
setRichText(v->rich, rich->second.rtf);
|
||||
CHARFORMAT2W format{};
|
||||
format.cbSize = sizeof(format);
|
||||
format.dwMask = CFM_COLOR;
|
||||
@@ -634,7 +735,7 @@ void drawHistoryRow(HWND w, HistoryView *v, const DRAWITEMSTRUCT &draw)
|
||||
DrawTextW(dc, text.c_str(), -1, &title, DT_WORDBREAK | DT_END_ELLIPSIS | DT_NOPREFIX);
|
||||
RECT detail{title.left, box.bottom - scale(w, 26), title.right, box.bottom - scale(w, 8)};
|
||||
SetTextColor(dc, GetSysColor(selected ? COLOR_HIGHLIGHTTEXT : COLOR_GRAYTEXT));
|
||||
auto subtitle = (entry.pinned ? L"★ " : L"") + std::to_wstring(draw.itemID + 1) + L" · " + entry.app;
|
||||
auto subtitle = (entry.pinned ? L"★ " : L"") + std::to_wstring(draw.itemID + 1) + L" · " + entry.app + L" · " + (entry.computer.empty()?L"This computer":entry.computerName);
|
||||
DrawTextW(dc, subtitle.c_str(), -1, &detail, DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX);
|
||||
if (draw.itemState & ODS_FOCUS)
|
||||
{
|
||||
@@ -716,6 +817,13 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case WM_COMMAND:
|
||||
{
|
||||
int id = LOWORD(wp);
|
||||
if(id==118&&HIWORD(wp)==BN_CLICKED){showComputerFilter(w,v);return 0;}
|
||||
if (id == 117 && HIWORD(wp) == BN_CLICKED)
|
||||
{
|
||||
KillTimer(w, 1);
|
||||
search(w, v);
|
||||
return 0;
|
||||
}
|
||||
if (id == 101 && HIWORD(wp) == EN_CHANGE)
|
||||
{
|
||||
// Reject an older result even during the debounce interval.
|
||||
@@ -748,7 +856,10 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if (!entry.empty())
|
||||
{
|
||||
if (id == 112)
|
||||
if (v->app->historyService) {
|
||||
v->app->remoteHistory(id == 112 ? "pin" : "remove", entry);
|
||||
v->app->history->reload();
|
||||
} else if (id == 112)
|
||||
v->app->history->pin(entry);
|
||||
else
|
||||
v->app->history->remove(entry);
|
||||
@@ -770,6 +881,7 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
case WM_TIMER:
|
||||
KillTimer(w, 1);
|
||||
if (v->closed) return 0;
|
||||
search(w, v);
|
||||
return 0;
|
||||
case ResultsMessage:
|
||||
@@ -778,8 +890,18 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
if (result->generation != v->generation)
|
||||
return 0;
|
||||
auto old = selected(w, v);
|
||||
if (old.empty()) old = v->rememberedSelection;
|
||||
int top=(int)SendDlgItemMessageW(w,102,LB_GETTOPINDEX,0,0);
|
||||
auto topId=top>=0 && top<(int)v->items.size()?v->items[top].id:L"";
|
||||
if (topId.empty()) topId = v->rememberedTop;
|
||||
if (v->selectFirstOnResults)
|
||||
{
|
||||
old.clear();
|
||||
topId.clear();
|
||||
v->rememberedSelection.clear();
|
||||
v->rememberedTop.clear();
|
||||
v->selectFirstOnResults = false;
|
||||
}
|
||||
v->items = std::move(result->items);
|
||||
SendDlgItemMessageW(w, 102, WM_SETREDRAW, FALSE, 0);
|
||||
SendDlgItemMessageW(w, 102, LB_RESETCONTENT, 0, 0);
|
||||
@@ -819,12 +941,14 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
visible.insert(v->items[i].id);
|
||||
if(v->items[i].id==result->id) { changed=intersection; repaint=true; }
|
||||
}
|
||||
if (!result->rtf.empty())
|
||||
v->richTexts[result->id] = std::move(result->rtf);
|
||||
if (!result->text.rtf.empty() || !result->text.plain.empty())
|
||||
v->richTexts[result->id] = std::move(result->text);
|
||||
else
|
||||
v->thumbnails[result->id] = std::move(result->pixels);
|
||||
trimHistoryPreviews(v->thumbnails,visible);
|
||||
trimHistoryPreviews(v->richTexts,visible);
|
||||
trimHistoryPreviews(v->thumbnails,visible,32,HistoryThumbnailBudget,
|
||||
[](const Pixels &p) { return p.bgra.capacity(); });
|
||||
trimHistoryPreviews(v->richTexts,visible,32,HistoryRichTextBudget,
|
||||
[](const TextPreview &s) { return s.rtf.capacity() + s.plain.capacity() * sizeof(wchar_t); });
|
||||
if(repaint) InvalidateRect(list,&changed,FALSE);
|
||||
return 0;
|
||||
}
|
||||
@@ -867,6 +991,7 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
AppendMenuW(menu, MF_STRING, 113, L"&Delete");
|
||||
AppendMenuW(menu, MF_STRING, 114, selectedImage(w,v)?L"&Edit image in screenshot editor":L"&Open full item");
|
||||
AppendMenuW(menu, MF_STRING, 115, L"&Copy text from image (OCR)");
|
||||
showMenuAccessKeys(menu);
|
||||
int cmd = TrackPopupMenu(menu, TPM_RETURNCMD, p.x, p.y, 0, w, nullptr);
|
||||
DestroyMenu(menu);
|
||||
if (cmd)
|
||||
@@ -874,15 +999,29 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
return 0;
|
||||
}
|
||||
case WM_CLOSE:
|
||||
{
|
||||
v->rememberedSelection = selected(w, v);
|
||||
int top = (int)SendDlgItemMessageW(w,102,LB_GETTOPINDEX,0,0);
|
||||
v->rememberedTop = top >= 0 && top < (int)v->items.size() ? v->items[top].id : L"";
|
||||
v->app->saveHistoryView(v->rememberedSelection, v->rememberedTop, value(w, 101),
|
||||
SendDlgItemMessageW(w, 117, BM_GETCHECK, 0, 0) == BST_CHECKED);
|
||||
KillTimer(w, 1);
|
||||
v->closed = true;
|
||||
v->previewActive->store(false);
|
||||
++v->generation; // Discard search/preview results queued before closing.
|
||||
ShowWindow(w, SW_HIDE);
|
||||
SendDlgItemMessageW(w,102,LB_RESETCONTENT,0,0);
|
||||
std::vector<Entry>().swap(v->items);
|
||||
v->thumbnails.clear();
|
||||
v->richTexts.clear();
|
||||
if (v->rich)
|
||||
SetWindowTextW(v->rich, L"");
|
||||
if (v->rich) SetWindowTextW(v->rich, L"");
|
||||
v->pending.clear();
|
||||
++v->generation;
|
||||
if (v->app->historyService && !v->app->historyEntryWindows)
|
||||
PostMessageW(v->app->window, WM_CLOSE, 0, 0);
|
||||
return 0;
|
||||
}
|
||||
case WM_NCDESTROY:
|
||||
v->previewActive->store(false);
|
||||
disposeFont(w);
|
||||
v->app->historyWindow = nullptr;
|
||||
delete v;
|
||||
@@ -905,7 +1044,131 @@ struct SettingsView
|
||||
std::vector<int> order;
|
||||
int selection = -1;
|
||||
bool filling{};
|
||||
std::vector<std::vector<HWND>> pages;
|
||||
bool ready{}, refreshing{};
|
||||
};
|
||||
void updateSettingsState(HWND w, SettingsView *v);
|
||||
void selectSettingsPage(HWND w, SettingsView *v)
|
||||
{
|
||||
int selected = TabCtrl_GetCurSel(GetDlgItem(w, 260));
|
||||
for (size_t page = 0; page < v->pages.size(); ++page)
|
||||
for (HWND child : v->pages[page]) ShowWindow(child, (int)page == selected ? SW_SHOWNA : SW_HIDE);
|
||||
InvalidateRect(w, nullptr, TRUE);
|
||||
}
|
||||
struct ChatLanguagesView
|
||||
{
|
||||
HWND parent{};
|
||||
SettingsView *settings{};
|
||||
std::vector<std::wstring> keys;
|
||||
};
|
||||
void fillChatLanguages(HWND w, ChatLanguagesView *v)
|
||||
{
|
||||
int index = (int)SendDlgItemMessageW(w, 710, LB_GETCURSEL, 0, 0);
|
||||
if (index < 0 || index >= (int)v->keys.size()) return;
|
||||
const auto &draft = v->settings->draft;
|
||||
auto saved = draft.chatCycles.find(v->keys[index]);
|
||||
const auto &cycle = saved == draft.chatCycles.end() ? draft.cycle : saved->second;
|
||||
for (size_t i = 0; i < v->settings->order.size(); ++i)
|
||||
{
|
||||
auto &layout = v->settings->app->layouts[v->settings->order[i]];
|
||||
SendDlgItemMessageW(w, 711, LB_SETSEL,
|
||||
std::find(cycle.begin(), cycle.end(), layout.id) != cycle.end(), i);
|
||||
}
|
||||
value(w, 712, saved == draft.chatCycles.end() ? L"No profile yet. Select the languages for this chat." :
|
||||
L"Saved profile. Select languages, or remove it to use the defaults.");
|
||||
EnableWindow(GetDlgItem(w, 713), saved != draft.chatCycles.end());
|
||||
}
|
||||
LRESULT CALLBACK chatLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
auto *v = (ChatLanguagesView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||||
if (!v) return DefWindowProcW(w, msg, wp, lp);
|
||||
try
|
||||
{
|
||||
if (msg == WM_COMMAND)
|
||||
{
|
||||
int id = LOWORD(wp);
|
||||
if (id == 710 && HIWORD(wp) == LBN_SELCHANGE) { fillChatLanguages(w, v); return 0; }
|
||||
if (id == IDOK || id == 713)
|
||||
{
|
||||
int selected = (int)SendDlgItemMessageW(w, 710, LB_GETCURSEL, 0, 0);
|
||||
if (selected < 0 || selected >= (int)v->keys.size())
|
||||
throw std::runtime_error("Open Telegram, Telegram Web K in Chrome, or Teams, then reopen this dialog. Viber OCR is disabled.");
|
||||
auto next = v->settings->draft;
|
||||
if (id == 713) next.chatCycles.erase(v->keys[selected]);
|
||||
else
|
||||
{
|
||||
std::vector<std::wstring> cycle;
|
||||
for (size_t i = 0; i < v->settings->order.size(); ++i)
|
||||
if (SendDlgItemMessageW(w, 711, LB_GETSEL, i, 0) > 0)
|
||||
cycle.push_back(v->settings->app->layouts[v->settings->order[i]].id);
|
||||
if (cycle.empty()) throw std::runtime_error("Select at least one language.");
|
||||
next.chatCycles[v->keys[selected]] = std::move(cycle);
|
||||
}
|
||||
validateSettings(next);
|
||||
v->settings->draft.chatCycles = std::move(next.chatCycles);
|
||||
DestroyWindow(w);
|
||||
return 0;
|
||||
}
|
||||
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
|
||||
}
|
||||
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
|
||||
if (msg == WM_DPICHANGED) { resizeForDpi(w, wp, lp); return 0; }
|
||||
if (msg == WM_NCDESTROY)
|
||||
{
|
||||
EnableWindow(v->parent, TRUE);
|
||||
SetForegroundWindow(v->parent);
|
||||
disposeFont(w);
|
||||
delete v;
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e) { error(w, e); }
|
||||
return DefWindowProcW(w, msg, wp, lp);
|
||||
}
|
||||
void showChatLanguages(HWND parent, SettingsView *settings)
|
||||
{
|
||||
std::set<std::wstring> keys;
|
||||
for (const auto &[key, cycle] : settings->draft.chatCycles) keys.insert(key);
|
||||
struct Context { std::set<std::wstring> &keys; const Settings &settings; } context{keys, settings->draft};
|
||||
EnumWindows([](HWND candidate, LPARAM context) -> BOOL
|
||||
{
|
||||
if (!IsWindowVisible(candidate)) return TRUE;
|
||||
auto &data = *(Context *)context;
|
||||
auto key = lower(processName(candidate)) == L"chrome" ? readChromeChat(candidate) : windowChatKey(candidate);
|
||||
if (!key.empty()) data.keys.insert(std::move(key));
|
||||
return TRUE;
|
||||
}, (LPARAM)&context);
|
||||
HWND w = makeWindow(*settings->app, L"KSwitcher.ChatLanguages", L"Languages for a chat", chatLanguagesProc, 640, 524);
|
||||
auto *v = new ChatLanguagesView{parent, settings, {keys.begin(), keys.end()}};
|
||||
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
|
||||
label(w, L"Telegram / Telegram Web (Chrome) / Teams; Viber inactive", 18, 16, 604);
|
||||
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER,
|
||||
710, 18, 44, 604, 140);
|
||||
for (const auto &key : v->keys)
|
||||
{
|
||||
auto split = key.find(L'\n');
|
||||
auto name = std::wstring(key.starts_with(L"telegram\n") ? L"Telegram: " : key.starts_with(L"telegram-web\n") ? L"Telegram Web: " : key.starts_with(L"viber\n") ? L"Viber (inactive): " : L"Teams: ") + key.substr(split + 1);
|
||||
SendDlgItemMessageW(w, 710, LB_ADDSTRING, 0, (LPARAM)name.c_str());
|
||||
}
|
||||
control(w, L"STATIC", L"Open a chat, then reopen this dialog to add it.", 0, 712, 18, 194, 604, 26);
|
||||
label(w, L"Click languages to include (saved in the order shown)", 18, 228, 604);
|
||||
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT | WS_BORDER,
|
||||
711, 18, 256, 604, 132);
|
||||
for (int i : settings->order)
|
||||
SendDlgItemMessageW(w, 711, LB_ADDSTRING, 0, (LPARAM)settings->app->layouts[i].name.c_str());
|
||||
label(w, L"Applies to Alt+Shift, Win+Space and KSwitcher Next layout.", 18, 402, 604);
|
||||
label(w, L"Matched by chat name. Identical names share a profile. Then Save settings.", 18, 430, 604);
|
||||
button(w, L"&Remove profile", 713, 18, 476, 170);
|
||||
button(w, L"&Use languages", IDOK, 300, 476, 170);
|
||||
button(w, L"&Cancel", IDCANCEL, 486, 476, 136);
|
||||
EnableWindow(GetDlgItem(w, IDOK), !keys.empty());
|
||||
EnableWindow(GetDlgItem(w, 713), FALSE);
|
||||
if (!keys.empty()) { SendDlgItemMessageW(w, 710, LB_SETCURSEL, 0, 0); fillChatLanguages(w, v); }
|
||||
EnableWindow(parent, FALSE);
|
||||
showRequestedWindow(w);
|
||||
SetFocus(GetDlgItem(w, 710));
|
||||
}
|
||||
void collectLayout(HWND w, SettingsView *v)
|
||||
{
|
||||
if (v->selection < 0 || v->selection >= (int)v->order.size())
|
||||
@@ -985,6 +1248,7 @@ void fillSettings(HWND w, SettingsView *v)
|
||||
v->selection = 0;
|
||||
fillLayouts(w, v);
|
||||
v->filling = false;
|
||||
updateSettingsState(w, v);
|
||||
}
|
||||
int integer(HWND w, int id)
|
||||
{
|
||||
@@ -1114,7 +1378,10 @@ LRESULT CALLBACK autoOptionsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
auto words = parseCommaList(text);
|
||||
std::sort(words.begin(), words.end());
|
||||
words.erase(std::unique(words.begin(), words.end()), words.end());
|
||||
draft.autoWords[language] = std::move(words);
|
||||
// Opening and accepting an untouched empty dictionary must not
|
||||
// introduce a new entry and mark Settings as changed.
|
||||
if (!words.empty() || draft.autoWords.contains(language))
|
||||
draft.autoWords[language] = std::move(words);
|
||||
}
|
||||
draft.autoExcluded = parseCommaList(value(w, 404));
|
||||
draft.autoPrefixChars = value(w, 408);
|
||||
@@ -1223,7 +1490,7 @@ void showAutoOptions(HWND parent, SettingsView *v)
|
||||
label(w, L"Enter punctuation without spaces or separators. These characters are kept.", 18, 530, 525);
|
||||
checkbox(w, L"Use custom &replacements (take priority over dictionaries)", 414, 18, 562, 524);
|
||||
check(w, 414, v->draft.autoReplace);
|
||||
label(w, L"One pair per line: typo=correction (same language, letters only)", 18, 592, 525);
|
||||
label(w, L"One pair per line: typo=correction (same language; correction may contain spaces)", 18, 592, 525);
|
||||
edit(w, 416, 18, 618, 524, 70, ES_MULTILINE | WS_VSCROLL | ES_AUTOVSCROLL | ES_WANTRETURN);
|
||||
std::wstring pairs;
|
||||
for (const auto &[from, to] : v->draft.autoReplacements) pairs += from + L"=" + to + L"\r\n";
|
||||
@@ -1338,6 +1605,68 @@ void showOcrOptions(HWND parent, SettingsView *v)
|
||||
showRequestedWindow(w); SetForegroundWindow(w);
|
||||
}
|
||||
#include "ui_sync.inl"
|
||||
#include "ui_lan.inl"
|
||||
bool settingsChanged(HWND w, SettingsView *v)
|
||||
{
|
||||
try
|
||||
{
|
||||
return encodeSettings(collectSettings(w, v)) != encodeSettings(v->app->settings);
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
// Invalid edits are unsaved changes too. Allow discarding them without
|
||||
// requiring the user to repair the fields first.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
void updateSettingsState(HWND w, SettingsView *v)
|
||||
{
|
||||
if (!v || !v->ready || v->filling || v->refreshing) return;
|
||||
v->refreshing = true;
|
||||
bool changed = settingsChanged(w, v);
|
||||
EnableWindow(GetDlgItem(w, IDOK), changed);
|
||||
const wchar_t *text = changed ? L"Unsaved changes — click Save to apply." : L"No unsaved changes.";
|
||||
if (value(w, 261) != text) value(w, 261, text);
|
||||
v->refreshing = false;
|
||||
}
|
||||
// Refresh after commands have updated controls/drafts, including early returns.
|
||||
// Saving can destroy Settings, so retrieve its state only if it still exists.
|
||||
struct SettingsStateRefresh
|
||||
{
|
||||
HWND window;
|
||||
~SettingsStateRefresh()
|
||||
{
|
||||
if (IsWindow(window))
|
||||
updateSettingsState(window, reinterpret_cast<SettingsView *>(GetWindowLongPtrW(window, GWLP_USERDATA)));
|
||||
}
|
||||
};
|
||||
void closeSettings(HWND w, SettingsView *v)
|
||||
{
|
||||
if (settingsChanged(w, v))
|
||||
{
|
||||
int choice = MessageBoxW(w,
|
||||
L"You have unsaved settings 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
|
||||
{
|
||||
if (v->app->busy)
|
||||
throw std::runtime_error("Wait for the current text operation to finish");
|
||||
v->app->applySettings(collectSettings(w, v));
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
error(w, e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
DestroyWindow(w);
|
||||
}
|
||||
LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if (msg == WM_DPICHANGED)
|
||||
@@ -1359,8 +1688,22 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
switch (msg)
|
||||
{
|
||||
case WM_ENABLE:
|
||||
if (wp) updateSettingsState(w, v);
|
||||
break;
|
||||
case WM_ACTIVATE:
|
||||
if (LOWORD(wp) != WA_INACTIVE) updateSettingsState(w, v);
|
||||
break;
|
||||
case WM_NOTIFY:
|
||||
if (((NMHDR *)lp)->idFrom == 260 && ((NMHDR *)lp)->code == TCN_SELCHANGE)
|
||||
{
|
||||
selectSettingsPage(w, v);
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case WM_COMMAND:
|
||||
{
|
||||
SettingsStateRefresh refresh{w};
|
||||
int id = LOWORD(wp);
|
||||
if (id == 220 && HIWORD(wp) == LBN_SELCHANGE && !v->filling)
|
||||
{
|
||||
@@ -1375,6 +1718,8 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
if (id == 257) { showOcrOptions(w, v); return 0; }
|
||||
if (id == 258) { showSyncOptions(w, *v->app); return 0; }
|
||||
if (id == 262) { showLan(w, *v->app); return 0; }
|
||||
if (id == 259) { collectLayout(w, v); showChatLanguages(w, v); return 0; }
|
||||
if (id == 230)
|
||||
{
|
||||
collectLayout(w, v);
|
||||
@@ -1395,6 +1740,7 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
if (id == IDOK)
|
||||
{
|
||||
if (!settingsChanged(w, v)) return 0;
|
||||
if (v->app->busy)
|
||||
throw std::runtime_error("Wait for the current text operation to finish");
|
||||
v->app->applySettings(collectSettings(w, v));
|
||||
@@ -1403,7 +1749,7 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
if (id == IDCANCEL)
|
||||
{
|
||||
DestroyWindow(w);
|
||||
closeSettings(w, v);
|
||||
return 0;
|
||||
}
|
||||
if (id == 250)
|
||||
@@ -1454,7 +1800,7 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
break;
|
||||
}
|
||||
case WM_CLOSE:
|
||||
DestroyWindow(w);
|
||||
closeSettings(w, v);
|
||||
return 0;
|
||||
case WM_NCDESTROY:
|
||||
disposeFont(w);
|
||||
@@ -1480,14 +1826,27 @@ void updateSnippetEditor(HWND w, SnippetView *v)
|
||||
bool selected = v->selection >= 0 && v->selection < (int)v->snippets.size();
|
||||
value(w, 302, selected ? v->snippets[v->selection].trigger : L"");
|
||||
value(w, 303, selected ? v->snippets[v->selection].text : L"");
|
||||
for (int id : {302, 303, 311, 312, 313})
|
||||
std::wstring apps;
|
||||
if (selected) for (const auto &app : v->snippets[v->selection].apps)
|
||||
{
|
||||
if (!apps.empty()) apps += L", ";
|
||||
if (!app.empty()) apps += app + L".exe";
|
||||
}
|
||||
value(w, 315, apps);
|
||||
bool restricted = selected && !v->snippets[v->selection].apps.empty();
|
||||
CheckDlgButton(w, 314, restricted ? BST_CHECKED : BST_UNCHECKED);
|
||||
for (int id : {302, 303, 311, 312, 313, 314})
|
||||
EnableWindow(GetDlgItem(w, id), selected);
|
||||
for (int id : {315, 316, 317}) EnableWindow(GetDlgItem(w, id), selected && restricted);
|
||||
}
|
||||
void fillSnippets(HWND w, SnippetView *v)
|
||||
{
|
||||
SendDlgItemMessageW(w, 301, LB_RESETCONTENT, 0, 0);
|
||||
for (auto &sn : v->snippets)
|
||||
SendDlgItemMessageW(w, 301, LB_ADDSTRING, 0, (LPARAM)sn.trigger.c_str());
|
||||
{
|
||||
auto label = sn.trigger + (sn.apps.empty() ? L" [All apps]" : L" [" + sn.apps.front() + (sn.apps.size() > 1 ? L", ...]" : L"]"));
|
||||
SendDlgItemMessageW(w, 301, LB_ADDSTRING, 0, (LPARAM)label.c_str());
|
||||
}
|
||||
if (v->selection >= 0)
|
||||
SendDlgItemMessageW(w, 301, LB_SETCURSEL, v->selection, 0);
|
||||
updateSnippetEditor(w, v);
|
||||
@@ -1500,6 +1859,18 @@ void collectSnippet(HWND w, SnippetView *v)
|
||||
if (snippet.id.empty()) snippet.id = snippetId(snippet);
|
||||
snippet.trigger = value(w, 302);
|
||||
snippet.text = value(w, 303);
|
||||
snippet.apps.clear();
|
||||
if (IsDlgButtonChecked(w, 314) == BST_CHECKED)
|
||||
{
|
||||
std::wistringstream input(value(w, 315)); std::wstring item;
|
||||
while (std::getline(input, item, L','))
|
||||
{
|
||||
auto app = snippetAppName(item);
|
||||
if (!app.empty()) snippet.apps.push_back(app);
|
||||
}
|
||||
// An explicitly restricted but empty list must not become global.
|
||||
if (snippet.apps.empty()) snippet.apps.push_back(L"");
|
||||
}
|
||||
}
|
||||
}
|
||||
LRESULT CALLBACK snippetProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
@@ -1526,6 +1897,24 @@ LRESULT CALLBACK snippetProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case WM_COMMAND:
|
||||
{
|
||||
int id = LOWORD(wp);
|
||||
if (id == 314)
|
||||
{
|
||||
bool restricted = IsDlgButtonChecked(w, 314) == BST_CHECKED;
|
||||
for (int field : {315, 316, 317}) EnableWindow(GetDlgItem(w, field), restricted);
|
||||
return 0;
|
||||
}
|
||||
if (id == 317)
|
||||
{
|
||||
auto app = value(w, 316);
|
||||
if (!app.empty())
|
||||
{
|
||||
auto current = value(w, 315);
|
||||
std::wistringstream input(current); std::wstring entry;
|
||||
while (std::getline(input, entry, L',')) if (snippetAppName(entry) == snippetAppName(app)) return 0;
|
||||
value(w, 315, current.empty() ? app : current + L", " + app);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (id == 301 && HIWORD(wp) == LBN_SELCHANGE)
|
||||
{
|
||||
collectSnippet(w, v);
|
||||
@@ -1571,6 +1960,7 @@ LRESULT CALLBACK snippetProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
auto *parent = (SettingsView *)GetWindowLongPtrW(v->app->settingsWindow, GWLP_USERDATA);
|
||||
parent->draft.snippets = s.snippets;
|
||||
updateSettingsState(v->app->settingsWindow, parent);
|
||||
}
|
||||
DestroyWindow(w);
|
||||
return 0;
|
||||
@@ -1602,13 +1992,19 @@ LRESULT CALLBACK snippetProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
#ifndef KS_CONFIG_APP
|
||||
LRESULT CALLBACK entryProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if (msg == WM_NCCREATE)
|
||||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)((CREATESTRUCTW *)lp)->lpCreateParams);
|
||||
if (msg == WM_SIZE)
|
||||
{
|
||||
MoveWindow(GetDlgItem(w, 1), 10, 10, LOWORD(lp) - 20, HIWORD(lp) - 20, TRUE);
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_NCDESTROY)
|
||||
if (msg == WM_NCDESTROY) {
|
||||
disposeFont(w);
|
||||
auto *app = (App *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||||
if (app && app->historyService && app->historyEntryWindows && !--app->historyEntryWindows &&
|
||||
!IsWindowVisible(app->historyWindow)) PostMessageW(app->window, WM_CLOSE, 0, 0);
|
||||
}
|
||||
return DefWindowProcW(w, msg, wp, lp);
|
||||
}
|
||||
#endif
|
||||
@@ -1616,6 +2012,7 @@ LRESULT CALLBACK entryProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
#ifndef KS_CONFIG_APP
|
||||
void refreshHistory(App &app)
|
||||
{
|
||||
if (app.isolateHistory) { app.refreshHistoryProcess(); return; }
|
||||
if (app.historyWindow)
|
||||
{
|
||||
auto *v = (HistoryView *)GetWindowLongPtrW(app.historyWindow, GWLP_USERDATA);
|
||||
@@ -1624,6 +2021,7 @@ void refreshHistory(App &app)
|
||||
}
|
||||
void showHistory(App &app, bool visible)
|
||||
{
|
||||
if (app.isolateHistory) { if (visible) app.openHistoryProcess(); return; }
|
||||
if (!app.history)
|
||||
{
|
||||
app.report(L"Clipboard history is unavailable. See the log in the data folder.");
|
||||
@@ -1644,9 +2042,14 @@ void showHistory(App &app, bool visible)
|
||||
HWND w = makeWindow(app, L"KSwitcher.History", L"Clipboard history", historyProc, 760, 500);
|
||||
app.historyWindow = w;
|
||||
windowLayoutState(w)->history = true;
|
||||
((HistoryView *)GetWindowLongPtrW(w, GWLP_USERDATA))->rich = createRichText(w, 105, false);
|
||||
label(w, L"&Search clipboard history", 16, 12, 500);
|
||||
edit(w, 101, 16, 38, 728);
|
||||
auto filter = control(w, L"BUTTON", L"★ Pinned only", WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
117, 16, 38, 112, 25);
|
||||
SendMessageW(filter, BM_SETCHECK, app.historyPinnedOnly ? BST_CHECKED : BST_UNCHECKED, 0);
|
||||
auto computers = control(w,L"BUTTON",app.historyComputers.empty()?L" Computers: All ▾":L" Computers: Selected ▾",
|
||||
WS_TABSTOP | BS_PUSHBUTTON | BS_LEFT,118,136,36,180,28);
|
||||
(void)computers;
|
||||
label(w, L"&Search clipboard history", 328, 12, 400);
|
||||
edit(w, 101, 328, 38, 416);
|
||||
auto list = control(w, L"LISTBOX", L"",
|
||||
WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER |
|
||||
LBS_OWNERDRAWFIXED | LBS_HASSTRINGS,
|
||||
@@ -1660,8 +2063,18 @@ void showHistory(App &app, bool visible)
|
||||
button(w, L"Clear &history…", 116, 546, 452, 150);
|
||||
SetWindowSubclass(list, historyKey, 1, (DWORD_PTR)w);
|
||||
SetWindowSubclass(GetDlgItem(w, 101), historyKey, 1, (DWORD_PTR)w);
|
||||
if (app.historyService) {
|
||||
auto *v = (HistoryView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||||
v->rememberedSelection = app.historySelection;
|
||||
v->rememberedTop = app.historyTop;
|
||||
SetDlgItemTextW(w, 101, app.historyQuery.c_str());
|
||||
}
|
||||
}
|
||||
if (!visible) return;
|
||||
// A fresh invocation starts at the newest matching item. Background search
|
||||
// and OCR refreshes still preserve the user's selection while browsing.
|
||||
auto *view = (HistoryView *)GetWindowLongPtrW(app.historyWindow, GWLP_USERDATA);
|
||||
view->selectFirstOnResults = true;
|
||||
POINT cursor;
|
||||
GetCursorPos(&cursor);
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
@@ -1693,56 +2106,99 @@ void showSettings(App &app, bool visible)
|
||||
activateWindow(target);
|
||||
return;
|
||||
}
|
||||
HWND w = makeWindow(app, L"KSwitcher.Settings", L"KSwitcher settings", settingsProc, 780, 660, 0, false);
|
||||
HWND w = makeWindow(app, L"KSwitcher.Settings", L"KSwitcher settings", settingsProc, 720, 510, 0, false);
|
||||
app.settingsWindow = w;
|
||||
label(w, L"Text conversion", 18, 16);
|
||||
checkbox(w, L"Con&vert recently typed text when nothing is selected", 201, 18, 43, 390);
|
||||
checkbox(w, L"Switch Windows input &layout after conversion", 202, 18, 70, 390);
|
||||
checkbox(w, L"Record clip&board history", 203, 18, 106);
|
||||
checkbox(w, L"Start with &Windows", 204, 18, 133);
|
||||
checkbox(w, L"Start with Windows as ad&ministrator", 206, 18, 160, 395);
|
||||
checkbox(w, L"&Keep screen awake", 205, 18, 184, 210);
|
||||
checkbox(w, L"Write lo&g", 208, 240, 184, 160);
|
||||
label(w, L"Click a shortcut and press the desired keys", 420, 16, 350);
|
||||
const wchar_t *names[] = {L"Next layout", L"Change case", L"Transliterate", L"Undo",
|
||||
L"Clipboard history", L"Screen capture"};
|
||||
auto *v = (SettingsView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||||
INITCOMMONCONTROLSEX tabsInit{sizeof(tabsInit), ICC_TAB_CLASSES};
|
||||
InitCommonControlsEx(&tabsInit);
|
||||
HWND tabs = control(w, WC_TABCONTROLW, L"", WS_TABSTOP, 260, 18, 16, 684, 32);
|
||||
const wchar_t *tabNames[] = {L"General", L"Languages", L"Shortcuts", L"Clipboard", L"Tools"};
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
TCITEMW item{}; item.mask = TCIF_TEXT; item.pszText = const_cast<wchar_t *>(tabNames[i]);
|
||||
TabCtrl_InsertItem(tabs, i, &item);
|
||||
}
|
||||
size_t start = windowLayoutState(w)->controls.size();
|
||||
auto page = [&]
|
||||
{
|
||||
std::vector<HWND> children;
|
||||
const auto &controls = windowLayoutState(w)->controls;
|
||||
for (size_t i = start; i < controls.size(); ++i) children.push_back(controls[i].first);
|
||||
v->pages.push_back(std::move(children));
|
||||
start = controls.size();
|
||||
};
|
||||
label(w, L"Text conversion", 24, 76, 650);
|
||||
checkbox(w, L"Con&vert recently typed text when nothing is selected", 201, 24, 110, 660);
|
||||
checkbox(w, L"Switch Windows input &layout after conversion", 202, 24, 146, 660);
|
||||
checkbox(w, L"Automatic correction (e&xperimental)", 207, 24, 182, 390);
|
||||
button(w, L"&Correction options...", 255, 454, 180, 230);
|
||||
label(w, L"Windows integration", 24, 254, 650);
|
||||
checkbox(w, L"Start with &Windows", 204, 24, 288, 660);
|
||||
checkbox(w, L"Start with Windows as ad&ministrator", 206, 24, 324, 660);
|
||||
checkbox(w, L"&Keep screen awake", 205, 24, 360, 660);
|
||||
page();
|
||||
|
||||
label(w, L"Default language cycle — top to bottom", 24, 76, 650);
|
||||
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER,
|
||||
220, 24, 108, 410, 240);
|
||||
button(w, L"Move u&p", 232, 454, 108, 110);
|
||||
button(w, L"Move &down", 233, 574, 108, 110);
|
||||
checkbox(w, L"&Include in cycle", 230, 454, 154, 230);
|
||||
label(w, L"Direct layout shortcut", 454, 206, 230);
|
||||
hotkeyEdit(app, w, 231, 454, 234, 230);
|
||||
label(w, L"Backspace / Delete clears it", 454, 270, 230);
|
||||
button(w, L"Re&fresh layouts", 253, 454, 322, 230);
|
||||
button(w, L"Languages for a &chat...", 259, 24, 378, 230);
|
||||
label(w, L"Telegram / Telegram Web (Chrome) / Teams", 272, 382, 412);
|
||||
page();
|
||||
|
||||
label(w, L"Click a shortcut field and press the desired keys", 24, 76, 660);
|
||||
const wchar_t *names[] = {L"Next layout", L"Change case", L"Transliterate", L"Undo", L"Clipboard history", L"Screen capture"};
|
||||
for (int i = 0; i < 6; ++i)
|
||||
{
|
||||
label(w, names[i], 420, 48 + i * 30, 115);
|
||||
hotkeyEdit(app, w, 210 + i, 540, 44 + i * 30, 220);
|
||||
label(w, names[i], 24, 116 + i * 40, 180);
|
||||
hotkeyEdit(app, w, 210 + i, 230, 112 + i * 40, 454);
|
||||
}
|
||||
checkbox(w, L"Open editor after screen capt&ure", 209, 420, 224, 340);
|
||||
checkbox(w, L"Automatic correction (e&xperimental)", 207, 18, 210, 395);
|
||||
label(w, L"Layout cycle — top to bottom", 18, 240, 400);
|
||||
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER, 220,
|
||||
18, 262, 470, 172);
|
||||
button(w, L"Move u&p", 232, 504, 262, 120);
|
||||
button(w, L"Move &down", 233, 632, 262, 128);
|
||||
checkbox(w, L"&Include in cycle", 230, 504, 300, 240);
|
||||
label(w, L"Direct layout shortcut", 504, 332, 240);
|
||||
hotkeyEdit(app, w, 231, 504, 356, 256);
|
||||
label(w, L"Backspace / Delete clears a shortcut", 504, 382, 256);
|
||||
button(w, L"Re&fresh layouts", 253, 504, 408, 150);
|
||||
label(w, L"History limits", 18, 444);
|
||||
label(w, L"Items", 18, 478, 50);
|
||||
edit(w, 240, 70, 474, 90);
|
||||
label(w, L"Total MiB", 180, 478, 75);
|
||||
edit(w, 241, 260, 474, 90);
|
||||
label(w, L"Per item MiB", 370, 478, 100);
|
||||
edit(w, 242, 475, 474, 80);
|
||||
button(w, L"Clear &history…", 254, 580, 474, 180);
|
||||
label(w, L"Exclude applications (process names, comma-separated)", 18, 516, 700);
|
||||
edit(w, 243, 18, 544, 742);
|
||||
button(w, L"&Auto-correction options…", 255, 18, 575, 240);
|
||||
button(w, L"View l&og…", 256, 278, 575, 220);
|
||||
button(w, L"OCR op&tions…", 257, 518, 575, 242);
|
||||
button(w, L"Impo&rt settings…", 250, 18, 606, 145);
|
||||
button(w, L"&Export settings…", 251, 173, 606, 145);
|
||||
button(w, L"S&nippets…", 252, 328, 606, 110);
|
||||
button(w, L"S&ync...", 258, 448, 606, 90);
|
||||
button(w, L"&Save", IDOK, 548, 606, 100);
|
||||
button(w, L"&Cancel", IDCANCEL, 660, 606, 100);
|
||||
fillSettings(w, (SettingsView *)GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
checkbox(w, L"Open editor after screen capt&ure", 209, 24, 378, 660);
|
||||
page();
|
||||
|
||||
checkbox(w, L"Record clip&board history", 203, 24, 80, 660);
|
||||
label(w, L"History limits", 24, 140, 660);
|
||||
label(w, L"Items", 24, 176, 180);
|
||||
label(w, L"Total MiB", 254, 176, 180);
|
||||
label(w, L"Per item MiB", 484, 176, 180);
|
||||
edit(w, 240, 24, 204, 200);
|
||||
edit(w, 241, 254, 204, 200);
|
||||
edit(w, 242, 484, 204, 200);
|
||||
button(w, L"Clear &history...", 254, 24, 258, 200);
|
||||
label(w, L"Exclude applications (process names, comma-separated)", 24, 330, 660);
|
||||
edit(w, 243, 24, 362, 660);
|
||||
page();
|
||||
|
||||
label(w, L"Additional tools and preferences", 24, 76, 660);
|
||||
button(w, L"S&nippets...", 252, 24, 116, 210);
|
||||
label(w, L"Manage reusable text and expansion triggers.", 254, 120, 430);
|
||||
button(w, L"OCR op&tions...", 257, 24, 170, 210);
|
||||
label(w, L"Configure text recognition from images.", 254, 174, 430);
|
||||
button(w, L"S&ync...", 258, 24, 224, 210);
|
||||
label(w, L"Synchronize preferences between computers.", 254, 228, 430);
|
||||
button(w, L"KSwitcher &computers...", 262, 24, 278, 210);
|
||||
label(w, L"Share mouse and keyboard with paired computers.", 254, 282, 430);
|
||||
button(w, L"View l&og...", 256, 24, 332, 210);
|
||||
label(w, L"Inspect recent operations and diagnostics.", 254, 336, 430);
|
||||
checkbox(w, L"Write lo&g", 208, 24, 378, 210);
|
||||
page();
|
||||
|
||||
control(w, L"STATIC", L"No unsaved changes.", 0, 261, 18, 430, 684, 24);
|
||||
button(w, L"Impo&rt...", 250, 18, 466, 125);
|
||||
button(w, L"&Export...", 251, 155, 466, 125);
|
||||
button(w, L"&Save", IDOK, 490, 466, 100);
|
||||
button(w, L"&Cancel", IDCANCEL, 602, 466, 100);
|
||||
fillSettings(w, v);
|
||||
v->ready = true;
|
||||
updateSettingsState(w, v);
|
||||
TabCtrl_SetCurSel(tabs, 0);
|
||||
selectSettingsPage(w, v);
|
||||
if (visible)
|
||||
{
|
||||
showRequestedWindow(w);
|
||||
@@ -1756,22 +2212,34 @@ void showSnippets(App &app)
|
||||
SetForegroundWindow(app.snippetsWindow);
|
||||
return;
|
||||
}
|
||||
HWND w = makeWindow(app, L"KSwitcher.Snippets", L"Text snippets", snippetProc, 740, 520);
|
||||
HWND w = makeWindow(app, L"KSwitcher.Snippets", L"Text snippets", snippetProc, 740, 620);
|
||||
app.snippetsWindow = w;
|
||||
label(w, L"Triggers", 16, 16);
|
||||
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER, 301,
|
||||
16, 44, 200, 380);
|
||||
button(w, L"&Add", 310, 16, 438, 90);
|
||||
button(w, L"&Delete", 311, 116, 438, 100);
|
||||
16, 44, 200, 480);
|
||||
button(w, L"&Add", 310, 16, 538, 90);
|
||||
button(w, L"&Delete", 311, 116, 538, 100);
|
||||
label(w, L"&Trigger (for example ;addr)", 236, 16, 470);
|
||||
edit(w, 302, 236, 44, 488);
|
||||
label(w, L"&Replacement text", 236, 82, 480);
|
||||
edit(w, 303, 236, 110, 488, 270, ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL | WS_VSCROLL);
|
||||
control(w, L"STATIC", L"{cursor}: caret; {enter}: press Enter after insertion.\nUse {{cursor}} / {{enter}} for literal markers.", 0, 0, 236, 392, 488, 36);
|
||||
button(w, L"Insert cursor &marker", 312, 236, 430, 190);
|
||||
button(w, L"Insert &Enter marker", 313, 436, 430, 190);
|
||||
button(w, L"&Save", IDOK, 510, 478, 100);
|
||||
button(w, L"&Cancel", IDCANCEL, 624, 478, 100);
|
||||
control(w, L"BUTTON", L"Only in these &applications (unchecked: everywhere)", WS_TABSTOP | BS_AUTOCHECKBOX, 314, 236, 82, 488, 24);
|
||||
edit(w, 315, 236, 112, 488);
|
||||
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, 316, 236, 148, 364, 200);
|
||||
button(w, L"Add a&pp", 317, 612, 145, 112);
|
||||
std::set<std::wstring> apps;
|
||||
EnumWindows([](HWND candidate, LPARAM context)->BOOL {
|
||||
if (IsWindowVisible(candidate)) { auto name = processName(candidate); if (!name.empty()) ((std::set<std::wstring>*)context)->insert(lower(name) + L".exe"); }
|
||||
return TRUE;
|
||||
}, (LPARAM)&apps);
|
||||
for (const auto &name : apps) SendDlgItemMessageW(w, 316, CB_ADDSTRING, 0, (LPARAM)name.c_str());
|
||||
SendDlgItemMessageW(w, 316, CB_SETCURSEL, 0, 0);
|
||||
label(w, L"Process names, comma-separated; e.g. chrome.exe, ms-teams.exe", 236, 182, 488);
|
||||
label(w, L"&Replacement text", 236, 212, 480);
|
||||
edit(w, 303, 236, 240, 488, 240, ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL | WS_VSCROLL);
|
||||
control(w, L"STATIC", L"{cursor}: caret; {enter}: press Enter after insertion.\nUse {{cursor}} / {{enter}} for literal markers.", 0, 0, 236, 492, 488, 36);
|
||||
button(w, L"Insert cursor &marker", 312, 236, 530, 190);
|
||||
button(w, L"Insert &Enter marker", 313, 436, 530, 190);
|
||||
button(w, L"&Save", IDOK, 510, 578, 100);
|
||||
button(w, L"&Cancel", IDCANCEL, 624, 578, 100);
|
||||
fillSnippets(w, (SnippetView *)GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||
showRequestedWindow(w);
|
||||
SetForegroundWindow(w);
|
||||
@@ -1816,6 +2284,7 @@ void showEntry(App &app, const std::wstring &id)
|
||||
}
|
||||
HWND w = makeWindow(app, L"KSwitcher.Entry", L"Clipboard item", entryProc, 720, 500,
|
||||
WS_THICKFRAME | WS_MAXIMIZEBOX);
|
||||
if (app.historyService) ++app.historyEntryWindows;
|
||||
auto field = edit(w, 1, 10, 10, 700, 480, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL);
|
||||
SetWindowTextW(field, text.c_str());
|
||||
showRequestedWindow(w);
|
||||
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
// Uses the resident service; the configurator never opens a discovery socket.
|
||||
struct LanView
|
||||
{
|
||||
HWND parent{};
|
||||
App *app{};
|
||||
nlohmann::json snapshot=nlohmann::json::object();
|
||||
std::vector<std::string> ids;
|
||||
std::wstring error;
|
||||
std::string dragPeer;POINT dragStart{},dragPoint{};bool dragMoved{};
|
||||
std::string gridState;
|
||||
std::vector<std::wstring> rows;
|
||||
};
|
||||
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);
|
||||
}
|
||||
std::string selectedLan(HWND w,LanView &v)
|
||||
{
|
||||
auto index=SendDlgItemMessageW(w,702,LB_GETCURSEL,0,0);
|
||||
return index>=0 && size_t(index)<v.ids.size() ? v.ids[size_t(index)] : "";
|
||||
}
|
||||
void refreshLan(HWND w,LanView &v)
|
||||
{
|
||||
auto selected=selectedLan(w,v);
|
||||
auto next=lanRequest(*v.app,{{"action","status"}});
|
||||
if(selected.empty())
|
||||
{
|
||||
std::string onlyPaired;size_t pairedCount=0;
|
||||
for(const auto &peer:next["peers"])if(peer.value("paired",false))
|
||||
{onlyPaired=peer.at("id").get<std::string>();++pairedCount;}
|
||||
if(pairedCount==1)selected=onlyPaired;
|
||||
}
|
||||
std::vector<std::string> ids;
|
||||
std::vector<std::wstring> rows;
|
||||
for(const auto &peer:next["peers"])
|
||||
{
|
||||
auto id=peer.at("id").get<std::string>();ids.push_back(id);
|
||||
auto state=peer.at("paired").get<bool>() ? L"Paired" : L"Not paired";
|
||||
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"] — "+state);
|
||||
}
|
||||
// Presence/challenge refreshes must not repaint or reset the pairing list.
|
||||
if(v.ids!=ids||v.rows!=rows)
|
||||
{
|
||||
SendDlgItemMessageW(w,702,WM_SETREDRAW,FALSE,0);
|
||||
SendDlgItemMessageW(w,702,LB_RESETCONTENT,0,0); v.ids=std::move(ids);v.rows=std::move(rows);
|
||||
for(size_t i=0;i<v.ids.size();++i)
|
||||
{
|
||||
auto row=SendDlgItemMessageW(w,702,LB_ADDSTRING,0,(LPARAM)v.rows[i].c_str());
|
||||
if(v.ids[i]==selected) SendDlgItemMessageW(w,702,LB_SETCURSEL,row,0);
|
||||
}
|
||||
SendDlgItemMessageW(w,702,WM_SETREDRAW,TRUE,0); InvalidateRect(GetDlgItem(w,702),nullptr,TRUE);
|
||||
}
|
||||
for(size_t i=0;i<v.ids.size();++i)if(v.ids[i]==selected)
|
||||
SendDlgItemMessageW(w,702,LB_SETCURSEL,i,0);
|
||||
selected=selectedLan(w,v);
|
||||
v.snapshot=std::move(next);
|
||||
bool enabled=v.snapshot.at("enabled"), pending=v.snapshot.at("pending"), online=false, paired=false;
|
||||
for(const auto &peer:v.snapshot["peers"]) if(peer.at("id")==selected) {online=peer.at("online");paired=peer.at("paired");}
|
||||
value(w,701,enabled ? L"&Disable discovery" : L"&Enable discovery");
|
||||
value(w,709,L"This KSwitcher: "+wide(v.snapshot.at("name").get<std::string>())+L" ["+wide(v.snapshot.at("id").get<std::string>().substr(0,8))+L"]");
|
||||
value(w,708,v.error.empty() ? wide(v.snapshot.at("status").get<std::string>()) : v.error);
|
||||
value(w,710,v.ids.empty() ? (enabled ? L"No KSwitcher found. Enable discovery on the other PC too. UDP 45883 must be allowed on your private network." : L"Discovery is disabled on this computer.") : L"Select the matching KSwitcher name and ID shown on the other computer.");
|
||||
EnableWindow(GetDlgItem(w,705),enabled&&online&&!pending&&!paired);
|
||||
EnableWindow(GetDlgItem(w,706),pending);
|
||||
EnableWindow(GetDlgItem(w,707),paired);
|
||||
for(int id:{703,704}) EnableWindow(GetDlgItem(w,id),enabled&&!pending&&!paired);
|
||||
auto positions=v.snapshot.value("positions",nlohmann::json::object());
|
||||
EnableWindow(GetDlgItem(w,715),enabled&&!positions.empty()&&!v.snapshot.value("shareInput",false));
|
||||
EnableWindow(GetDlgItem(w,716),v.snapshot.value("shareInput",false));
|
||||
auto gridState=positions.dump()+v.snapshot["peers"].dump()+selected+v.snapshot.value("controlPeer",std::string{})+v.snapshot.value("inputReady",nlohmann::json::object()).dump()+(v.snapshot.value("shareInput",false)?"1":"0");
|
||||
if(gridState!=v.gridState){v.gridState=std::move(gridState);InvalidateRect(GetDlgItem(w,721),nullptr,FALSE);}
|
||||
std::wstring detail=L"Drag paired monitors to empty cells. This PC stays fixed. Arrow keys also work.";
|
||||
detail=L"Drag monitors to neighboring cells. Mouse crosses shared edges; empty cells block passage.";
|
||||
value(w,719,v.error.empty()?detail:v.error);
|
||||
auto inputStatus=wide(v.snapshot.value("inputStatus",std::string("Input sharing disabled.")));
|
||||
if(!v.snapshot.value("shareInput",false))
|
||||
inputStatus=!enabled ? L"Enable discovery to set up mouse and keyboard sharing." :
|
||||
selected.empty() ? L"Select a computer in the list above to enable input." :
|
||||
!paired ? L"Pair the selected computer first." :
|
||||
L"Arrange the monitors, then enable input sharing on all PCs.";
|
||||
auto mode=v.snapshot.value("controlMode",0);
|
||||
if(mode==2)inputStatus=L"Mouse and keyboard control the OTHER PC. Ctrl+Alt+Esc returns here.";
|
||||
else if(mode==3)inputStatus=L"This PC is controlled remotely. Local physical input takes control back.";
|
||||
value(w,718,inputStatus);
|
||||
}
|
||||
#include "ui_lan_layout.inl"
|
||||
LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(msg==WM_DPICHANGED) {resizeForDpi(w,wp,lp);return 0;}
|
||||
auto v=(LanView*)GetWindowLongPtrW(w,GWLP_USERDATA);
|
||||
if(!v) return DefWindowProcW(w,msg,wp,lp);
|
||||
if(msg==WM_DESTROY) {DestroyWindow(GetDlgItem(w,721));KillTimer(w,1);EnableWindow(v->parent,TRUE);SetForegroundWindow(v->parent);delete v;SetWindowLongPtrW(w,GWLP_USERDATA,0);return 0;}
|
||||
if(msg==WM_CLOSE||(msg==WM_COMMAND&&LOWORD(wp)==IDCANCEL)) {DestroyWindow(w);return 0;}
|
||||
try
|
||||
{
|
||||
if(msg==WM_TIMER) {refreshLan(w,*v);return 0;}
|
||||
if(msg==WM_COMMAND)
|
||||
{
|
||||
int id=LOWORD(wp); auto peer=selectedLan(w,*v);
|
||||
if(id==702&&HIWORD(wp)==LBN_SELCHANGE) {refreshLan(w,*v);return 0;}
|
||||
if(HIWORD(wp)!=BN_CLICKED) return DefWindowProcW(w,msg,wp,lp);
|
||||
if(!IsWindowEnabled(GetDlgItem(w,id)))return 0;
|
||||
v->error.clear();
|
||||
if(id==701) lanRequest(*v->app,{{"action","enable"},{"enabled",!v->snapshot.value("enabled",false)}});
|
||||
if(id==704)
|
||||
{
|
||||
auto code=lanRequest(*v->app,{{"action","code"}}).at("code").get<std::string>();
|
||||
std::string grouped; for(size_t i=0;i<code.size();++i) {if(i&&i%4==0) grouped+='-';grouped+=code[i];}
|
||||
value(w,703,wide(grouped)); SetFocus(GetDlgItem(w,703)); SendDlgItemMessageW(w,703,EM_SETSEL,0,-1);
|
||||
}
|
||||
if(id==705) {lanRequest(*v->app,{{"action","pair"},{"peer",peer},{"code",utf8(value(w,703))}});value(w,703,L"");}
|
||||
if(id==706) lanRequest(*v->app,{{"action","cancel"}});
|
||||
if(id==707) lanRequest(*v->app,{{"action","forget"},{"peer",peer}});
|
||||
if(id==715)
|
||||
{
|
||||
lanRequest(*v->app,{{"action","input"},{"enabled",true}});
|
||||
}
|
||||
if(id==716)lanRequest(*v->app,{{"action","input"},{"enabled",false}});
|
||||
refreshLan(w,*v); return 0;
|
||||
}
|
||||
}
|
||||
catch(const std::exception &e) {v->error=wide(e.what());value(w,708,v->error);}
|
||||
return DefWindowProcW(w,msg,wp,lp);
|
||||
}
|
||||
void showLan(HWND parent,App &app)
|
||||
{
|
||||
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers — mouse and keyboard",lanProc,740,836,0,false);
|
||||
SetWindowLongPtrW(w,GWLP_HWNDPARENT,(LONG_PTR)parent);
|
||||
auto v=new LanView{parent,&app};SetWindowLongPtrW(w,GWLP_USERDATA,(LONG_PTR)v);
|
||||
label(w,L"Find running KSwitcher instances on your local network and pair them.",18,16,700);
|
||||
control(w,L"STATIC",L"",0,709,18,45,700,24);
|
||||
button(w,L"&Enable discovery",701,18,78,210);
|
||||
label(w,L"Only enabled KSwitcher instances announce themselves.",244,82,470);
|
||||
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,18,120,700,96);
|
||||
control(w,L"STATIC",L"",0,710,18,224,700,40);
|
||||
label(w,L"Same pairing c&ode on both computers",18,273,700);
|
||||
edit(w,703,18,301,470);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
|
||||
button(w,L"&Generate code",704,504,300,214);
|
||||
label(w,L"Generate once, enter that code on both PCs, select each other, then click Pair on both.",18,338,700);
|
||||
button(w,L"&Pair",705,18,370,140);button(w,L"Cancel &pairing",706,174,370,160);button(w,L"&Forget pair",707,350,370,160);
|
||||
control(w,L"STATIC",L"",0,708,18,412,700,40);
|
||||
label(w,L"Arrange your computers",18,458,700);
|
||||
WNDCLASSW gridClass{};gridClass.lpfnWndProc=lanGridProc;gridClass.hInstance=app.instance;gridClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);gridClass.lpszClassName=L"KSwitcher.LAN.Layout";RegisterClassW(&gridClass);
|
||||
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer above, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
|
||||
scale(w,18),scale(w,486),scale(w,700),scale(w,180),w,reinterpret_cast<HMENU>(721),app.instance,v);
|
||||
windowLayoutState(w)->controls.push_back({grid,{18,486,718,666}});
|
||||
control(w,L"STATIC",L"",0,719,18,674,700,24);
|
||||
button(w,L"Enable &input sharing",715,18,706,330);
|
||||
button(w,L"&Stop input sharing",716,370,706,240);
|
||||
control(w,L"STATIC",L"",0,718,18,744,700,28);
|
||||
control(w,L"STATIC",L"Arrange the same physical layout on every PC. Pair each input source with every destination and enable input on all PCs. Clipboard goes to all paired PCs.",0,720,18,776,580,40);
|
||||
button(w,L"&Close",IDCANCEL,618,792,100);
|
||||
EnableWindow(parent,FALSE);showRequestedWindow(w);SetForegroundWindow(w);
|
||||
SetTimer(w,1,1000,nullptr);
|
||||
try {refreshLan(w,*v);} catch(const std::exception &e){v->error=wide(e.what());value(w,708,v->error);}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
struct LanGridMetrics
|
||||
{
|
||||
int left=-1,right=1,top=-1,bottom=1,width{},height{};
|
||||
RECT cell(int x,int y)const{return {(x-left)*width/(right-left+1),(y-top)*height/(bottom-top+1),(x-left+1)*width/(right-left+1),(y-top+1)*height/(bottom-top+1)};}
|
||||
POINT point(POINT p)const{return {std::clamp(left+int(p.x)*(right-left+1)/std::max(1,width),left,right),std::clamp(top+int(p.y)*(bottom-top+1)/std::max(1,height),top,bottom)};}
|
||||
};
|
||||
LanGridMetrics lanGridMetrics(HWND w,const LanView &v)
|
||||
{
|
||||
RECT r{};GetClientRect(w,&r);LanGridMetrics g;g.width=r.right;g.height=r.bottom;
|
||||
const auto positions=v.snapshot.value("positions",nlohmann::json::object());
|
||||
for(auto &[id,cell]:positions.items()){
|
||||
int x=cell[0],y=cell[1];g.left=std::min(g.left,x-1);g.right=std::max(g.right,x+1);g.top=std::min(g.top,y-1);g.bottom=std::max(g.bottom,y+1);
|
||||
}
|
||||
g.left=std::max(-8,g.left);g.right=std::min(8,g.right);g.top=std::max(-8,g.top);g.bottom=std::min(8,g.bottom);return g;
|
||||
}
|
||||
void moveLanMonitor(HWND parent,LanView &v,const std::string &peer,int x,int y)
|
||||
{
|
||||
try{lanRequest(*v.app,{{"action","position"},{"peer",peer},{"x",x},{"y",y}});v.error.clear();}
|
||||
catch(const std::exception &e){v.error=wide(e.what());}
|
||||
refreshLan(parent,v);
|
||||
}
|
||||
LRESULT CALLBACK lanGridProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
auto *v=reinterpret_cast<LanView*>(GetWindowLongPtrW(w,GWLP_USERDATA));
|
||||
if(msg==WM_NCCREATE){v=static_cast<LanView*>(reinterpret_cast<CREATESTRUCTW*>(lp)->lpCreateParams);SetWindowLongPtrW(w,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(v));}
|
||||
if(!v)return DefWindowProcW(w,msg,wp,lp);
|
||||
auto parent=GetParent(w);
|
||||
if(msg==WM_ERASEBKGND)return 1;
|
||||
if(msg==WM_GETDLGCODE)return DLGC_WANTARROWS;
|
||||
if(msg==WM_SETFOCUS||msg==WM_KILLFOCUS){InvalidateRect(w,nullptr,FALSE);return 0;}
|
||||
if(msg==WM_LBUTTONDOWN){
|
||||
SetFocus(w);POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};auto g=lanGridMetrics(w,*v);
|
||||
const auto positions=v->snapshot.value("positions",nlohmann::json::object());
|
||||
for(auto &[id,cell]:positions.items()){
|
||||
auto r=g.cell(cell[0],cell[1]);if(!PtInRect(&r,p))continue;
|
||||
auto found=std::find(v->ids.begin(),v->ids.end(),id);if(found==v->ids.end())break;
|
||||
SendDlgItemMessageW(parent,702,LB_SETCURSEL,std::distance(v->ids.begin(),found),0);
|
||||
v->dragPeer=id;v->dragStart=p;v->dragPoint=p;v->dragMoved=false;SetCapture(w);refreshLan(parent,*v);break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(msg==WM_MOUSEMOVE&&!v->dragPeer.empty()){
|
||||
v->dragPoint={GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
if(std::abs(v->dragPoint.x-v->dragStart.x)>scale(w,4)||std::abs(v->dragPoint.y-v->dragStart.y)>scale(w,4))v->dragMoved=true;
|
||||
InvalidateRect(w,nullptr,FALSE);return 0;
|
||||
}
|
||||
if(msg==WM_LBUTTONUP&&!v->dragPeer.empty()){
|
||||
auto peer=v->dragPeer;auto p=lanGridMetrics(w,*v).point({GET_X_LPARAM(lp),GET_Y_LPARAM(lp)});bool moved=v->dragMoved;
|
||||
RECT client{};GetClientRect(w,&client);POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
v->dragPeer.clear();v->dragMoved=false;ReleaseCapture();
|
||||
if(moved&&PtInRect(&client,mouse))moveLanMonitor(parent,*v,peer,p.x,p.y);
|
||||
InvalidateRect(w,nullptr,FALSE);return 0;
|
||||
}
|
||||
if(msg==WM_CAPTURECHANGED){v->dragPeer.clear();v->dragMoved=false;InvalidateRect(w,nullptr,FALSE);return 0;}
|
||||
if(msg==WM_KEYDOWN){
|
||||
if(wp==VK_ESCAPE&&!v->dragPeer.empty()){v->dragPeer.clear();ReleaseCapture();InvalidateRect(w,nullptr,FALSE);return 0;}
|
||||
auto peer=selectedLan(parent,*v);auto positions=v->snapshot.value("positions",nlohmann::json::object());
|
||||
if(positions.contains(peer)&&(wp==VK_LEFT||wp==VK_RIGHT||wp==VK_UP||wp==VK_DOWN)){
|
||||
int x=positions[peer][0],y=positions[peer][1];x+=(wp==VK_RIGHT)-(wp==VK_LEFT);y+=(wp==VK_DOWN)-(wp==VK_UP);
|
||||
moveLanMonitor(parent,*v,peer,x,y);return 0;
|
||||
}
|
||||
}
|
||||
if(msg==WM_PAINT){
|
||||
PAINTSTRUCT ps{};auto target=BeginPaint(w,&ps);RECT bounds{};GetClientRect(w,&bounds);
|
||||
auto dc=CreateCompatibleDC(target);auto bitmap=CreateCompatibleBitmap(target,std::max(1L,bounds.right),std::max(1L,bounds.bottom));auto oldBitmap=SelectObject(dc,bitmap);
|
||||
auto fill=CreateSolidBrush(RGB(247,249,251));FillRect(dc,&bounds,fill);DeleteObject(fill);
|
||||
auto oldFont=SelectObject(dc,GetPropW(parent,L"Font"));SetBkMode(dc,TRANSPARENT);
|
||||
auto gridPen=CreatePen(PS_DOT,1,RGB(214,222,230));auto oldPen=SelectObject(dc,gridPen);auto oldBrush=SelectObject(dc,GetStockObject(NULL_BRUSH));
|
||||
auto g=lanGridMetrics(w,*v);
|
||||
for(int x=g.left;x<=g.right+1;++x){int at=(x-g.left)*g.width/(g.right-g.left+1);MoveToEx(dc,at,0,nullptr);LineTo(dc,at,g.height);}
|
||||
for(int y=g.top;y<=g.bottom+1;++y){int at=(y-g.top)*g.height/(g.bottom-g.top+1);MoveToEx(dc,0,at,nullptr);LineTo(dc,g.width,at);}
|
||||
auto selected=selectedLan(parent,*v);
|
||||
auto draw=[&](const std::string &id,const std::wstring &name,int x,int y,bool local){
|
||||
auto cell=g.cell(x,y);int margin=scale(w,8),cellWidth=cell.right-cell.left;
|
||||
TEXTMETRICW metrics{};GetTextMetricsW(dc,&metrics);
|
||||
RECT title{cell.left+scale(w,3),cell.bottom-scale(w,3)-metrics.tmHeight,cell.right-scale(w,3),cell.bottom-scale(w,3)};
|
||||
int top=cell.top+scale(w,4),height=std::min(scale(w,36),int(title.top)-top-scale(w,8));
|
||||
int width=std::min({scale(w,110),cellWidth-2*margin,height*2});
|
||||
if(width<8||height<8)return;
|
||||
int left=(cell.left+cell.right-width)/2;
|
||||
bool active=!local&&v->snapshot.value("shareInput",false)&&v->snapshot.value("controlMode",0)!=0&&v->snapshot.value("controlPeer",std::string{})==id;
|
||||
COLORREF color=id==selected?RGB(0,105,190):active?RGB(30,130,90):RGB(105,120,133);
|
||||
auto pen=CreatePen(PS_SOLID,scale(w,2),color);SelectObject(dc,pen);
|
||||
auto brush=CreateSolidBrush(local?RGB(220,237,252):RGB(255,255,255));SelectObject(dc,brush);
|
||||
RoundRect(dc,left,top,left+width,top+height,scale(w,4),scale(w,4));SelectObject(dc,GetStockObject(NULL_BRUSH));DeleteObject(brush);
|
||||
int center=left+width/2;MoveToEx(dc,center,top+height,nullptr);LineTo(dc,center,top+height+scale(w,5));
|
||||
MoveToEx(dc,center-scale(w,12),top+height+scale(w,5),nullptr);LineTo(dc,center+scale(w,12),top+height+scale(w,5));
|
||||
RECT screen{left+scale(w,3),top+scale(w,2),left+width-scale(w,3),top+height-scale(w,2)};SetTextColor(dc,color);
|
||||
const wchar_t *caption=local?L"Local":active?L"Active":L"Paired";
|
||||
if(height>=metrics.tmHeight+scale(w,4))DrawTextW(dc,caption,-1,&screen,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS);
|
||||
SetTextColor(dc,RGB(30,40,50));
|
||||
DrawTextW(dc,name.c_str(),-1,&title,DT_CENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
if(id==selected){RECT outline{cell.left+scale(w,2),cell.top+scale(w,2),cell.right-scale(w,2),cell.bottom-scale(w,2)};if(GetFocus()==w)DrawFocusRect(dc,&outline);}
|
||||
SelectObject(dc,gridPen);DeleteObject(pen);
|
||||
};
|
||||
draw("",wide(v->snapshot.value("name",std::string("This PC"))),0,0,true);
|
||||
for(const auto &peer:v->snapshot.value("peers",nlohmann::json::array())){
|
||||
auto id=peer.at("id").get<std::string>();auto positions=v->snapshot.value("positions",nlohmann::json::object());
|
||||
if(positions.contains(id))draw(id,wide(peer.at("name").get<std::string>()),positions[id][0],positions[id][1],false);
|
||||
}
|
||||
if(v->dragMoved&&!v->dragPeer.empty()){
|
||||
auto point=g.point(v->dragPoint);auto r=g.cell(point.x,point.y);bool valid=true;
|
||||
try{lan::validateCell(v->snapshot.at("positions"),v->dragPeer,point.x,point.y);}catch(...){valid=false;}
|
||||
auto pen=CreatePen(PS_SOLID,scale(w,2),valid?RGB(0,105,190):RGB(190,50,40));SelectObject(dc,pen);
|
||||
Rectangle(dc,r.left+2,r.top+2,r.right-2,r.bottom-2);SelectObject(dc,gridPen);DeleteObject(pen);
|
||||
}
|
||||
SelectObject(dc,oldPen);SelectObject(dc,oldBrush);SelectObject(dc,oldFont);DeleteObject(gridPen);
|
||||
BitBlt(target,0,0,bounds.right,bounds.bottom,dc,0,0,SRCCOPY);SelectObject(dc,oldBitmap);DeleteObject(bitmap);DeleteDC(dc);EndPaint(w,&ps);return 0;
|
||||
}
|
||||
return DefWindowProcW(w,msg,wp,lp);
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.29";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.57";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <cwchar>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
// Scan each time the menu opens, relative to the resident executable, not its working directory.
|
||||
inline std::vector<std::filesystem::path> discoverUtilities(const std::filesystem::path &folder,
|
||||
std::error_code &error)
|
||||
{
|
||||
error.clear();
|
||||
std::vector<std::filesystem::path> result;
|
||||
std::filesystem::directory_iterator it(folder, error), end;
|
||||
if (error == std::errc::no_such_file_or_directory) error.clear();
|
||||
while (!error && it != end)
|
||||
{
|
||||
std::error_code entryError;
|
||||
if (_wcsicmp(it->path().extension().c_str(), L".exe") == 0 && it->is_regular_file(entryError))
|
||||
result.push_back(it->path());
|
||||
it.increment(error);
|
||||
}
|
||||
if (error) result.clear();
|
||||
std::sort(result.begin(), result.end(), [](const auto &a, const auto &b) {
|
||||
return _wcsicmp(a.filename().c_str(), b.filename().c_str()) < 0;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
inline std::wstring utilityMenuLabel(const std::filesystem::path &path)
|
||||
{
|
||||
std::wstring label;
|
||||
for (wchar_t ch : path.stem().wstring())
|
||||
{
|
||||
label += ch;
|
||||
if (ch == L'&') label += ch; // Win32 uses ampersands for access keys.
|
||||
}
|
||||
return label;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Experimental Viber header OCR; never called on the keyboard hook thread.
|
||||
#include <uiautomation.h>
|
||||
#include <mutex>
|
||||
namespace ks {
|
||||
namespace {
|
||||
std::mutex viberMutex;
|
||||
HWND viberWindow{};
|
||||
std::wstring viberKey;
|
||||
ULONGLONG viberTime{};
|
||||
std::wstring elementClass(IUIAutomationElement *e) {
|
||||
BSTR s{}; e->get_CurrentClassName(&s); std::wstring out=s?s:L""; SysFreeString(s); return out;
|
||||
}
|
||||
bool findViberHeader(IUIAutomationTreeWalker *walker,IUIAutomationElement *e,RECT &pane,RECT &search,int depth,int &budget) {
|
||||
if(depth>5 || --budget<0) return false;
|
||||
bool stack=elementClass(e).starts_with(L"StackView_");
|
||||
Com<IUIAutomationElement> child;walker->GetFirstChildElement(e,child.out());
|
||||
bool found=false,info=false;
|
||||
while(child.p && --budget>0) {
|
||||
if(stack) {
|
||||
auto name=elementClass(child.p);
|
||||
if(name.starts_with(L"SearchButton_")){child->get_CurrentBoundingRectangle(&search);found=true;}
|
||||
if(name.starts_with(L"InfoButton_")) info=true;
|
||||
} else if(findViberHeader(walker,child.p,pane,search,depth+1,budget)) return true;
|
||||
Com<IUIAutomationElement> next;walker->GetNextSiblingElement(child.p,next.out());
|
||||
child.p->Release();child.p=next.p;next.p=nullptr;
|
||||
}
|
||||
if(found && info){e->get_CurrentBoundingRectangle(&pane);return true;}
|
||||
return false;
|
||||
}
|
||||
Pixels viberHeader(HWND window) {
|
||||
if(!IsWindow(window)||IsIconic(window)) return {};
|
||||
Com<IUIAutomation2> automation;
|
||||
check(CoCreateInstance(CLSID_CUIAutomation8,nullptr,CLSCTX_INPROC_SERVER,IID_IUIAutomation2,(void**)automation.out()));
|
||||
automation->put_ConnectionTimeout(200);automation->put_TransactionTimeout(200);
|
||||
Com<IUIAutomationElement> root;check(automation->ElementFromHandle(window,root.out()));
|
||||
Com<IUIAutomationTreeWalker> walker;check(automation->get_RawViewWalker(walker.out()));
|
||||
RECT pane{},search{},rect{};int budget=160;
|
||||
if(!findViberHeader(walker.p,root.p,pane,search,0,budget)||!GetWindowRect(window,&rect)) return {};
|
||||
double scale=GetDpiForWindow(window)/96.0;
|
||||
int x=pane.left+int(76*scale)-rect.left,y=search.top-int(12*scale)-rect.top;
|
||||
int width=search.left-int(12*scale)-rect.left-x,height=int(28*scale);
|
||||
int ww=rect.right-rect.left,wh=rect.bottom-rect.top;
|
||||
if(width<30||height<10||x<0||y<0||x+width>ww||y+height>wh||uint64_t(ww)*wh>16000000) return {};
|
||||
HDC dc=CreateCompatibleDC(nullptr);BITMAPINFO bi{};bi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
|
||||
bi.bmiHeader.biWidth=ww;bi.bmiHeader.biHeight=-wh;bi.bmiHeader.biPlanes=1;bi.bmiHeader.biBitCount=32;
|
||||
void *bits{};HBITMAP bitmap=CreateDIBSection(dc,&bi,DIB_RGB_COLORS,&bits,nullptr,0);
|
||||
if(!bitmap){DeleteDC(dc);return {};}
|
||||
auto old=SelectObject(dc,bitmap);Pixels p;
|
||||
if(PrintWindow(window,dc,2)) {
|
||||
p.width=width;p.height=height;p.bgra.resize(size_t(width)*height*4);
|
||||
for(int row=0;row<height;++row) memcpy(p.bgra.data()+size_t(row)*width*4,(BYTE*)bits+(size_t(y+row)*ww+x)*4,size_t(width)*4);
|
||||
}
|
||||
SelectObject(dc,old);DeleteObject(bitmap);DeleteDC(dc);return p;
|
||||
}
|
||||
}
|
||||
std::wstring cachedViberChat(HWND window) {
|
||||
std::lock_guard lock(viberMutex);
|
||||
return window==viberWindow && GetTickCount64()-viberTime<2000 ? viberKey : L"";
|
||||
}
|
||||
std::wstring recognizeViberChat(HWND window,const Settings &settings) {
|
||||
std::wstring key;
|
||||
try {
|
||||
auto hr=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
struct Apartment {bool owned;~Apartment(){if(owned)CoUninitialize();}} apartment{SUCCEEDED(hr)};
|
||||
auto context=SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
|
||||
struct Dpi {DPI_AWARENESS_CONTEXT old;~Dpi(){if(old)SetThreadDpiAwarenessContext(old);}} dpi{context};
|
||||
auto before=viberHeader(window);
|
||||
if(!before.bgra.empty()) {
|
||||
Settings options=settings;options.useTesseract=true;
|
||||
Clip clip;clip.formats.push_back(imageDib(before));
|
||||
auto title=recognizeText(clip,options);
|
||||
while(!title.empty() && iswspace(title.back())) title.pop_back();
|
||||
while(!title.empty() && iswspace(title.front())) title.erase(0,1);
|
||||
auto after=viberHeader(window);
|
||||
if(!title.empty() && title.size()<512 && title.find_first_of(L"\r\n")==title.npos && before.width==after.width && before.height==after.height && before.bgra==after.bgra)
|
||||
key=L"viber\n"+title;
|
||||
}
|
||||
} catch(...) {}
|
||||
{std::lock_guard lock(viberMutex);viberWindow=window;viberKey=key;viberTime=GetTickCount64();}
|
||||
return key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
#include "app.h"
|
||||
#include "ocr.h"
|
||||
#include "screenshot.h"
|
||||
#include "lan_pairing.h"
|
||||
#include <iostream>
|
||||
#include <commctrl.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
int passed{};
|
||||
void require(bool ok, const char *message)
|
||||
{
|
||||
if (!ok) throw std::runtime_error(message);
|
||||
++passed;
|
||||
}
|
||||
void contextChecks()
|
||||
{
|
||||
ks::Settings scoped;
|
||||
scoped.snippets = {{L";sig", L"Global", L"global"},
|
||||
{L";sig", L"Work", L"teams", {L"MS-Teams.EXE", L"OUTLOOK.exe"}},
|
||||
{L";sig", L"Personal", L"telegram", {L"telegram"}}};
|
||||
ks::validateSettings(scoped);
|
||||
require(ks::snippetAppPriority(scoped.snippets[1], L"ms-teams") > ks::snippetAppPriority(scoped.snippets[0], L"ms-teams"), "app snippet precedes global regardless of list order");
|
||||
require(ks::snippetAppPriority(scoped.snippets[1], L"Telegram.exe") == 0, "restricted snippet cannot run in another app");
|
||||
require(ks::snippetAppPriority(scoped.snippets[1], L"Outlook.EXE") == 2, "restricted snippet also runs in its second application");
|
||||
require(ks::snippetAppPriority(scoped.snippets[0], L"") == 1, "legacy/global snippets remain available");
|
||||
auto scopedRoundtrip = ks::decodeSettings(ks::encodeSettings(scoped), {});
|
||||
require(scopedRoundtrip.snippets[1].apps == std::vector<std::wstring>{L"ms-teams", L"outlook"}, "scopes normalize and persist");
|
||||
require(scopedRoundtrip.snippets[0].apps.empty(), "absent scope remains global");
|
||||
auto collision = scoped; collision.snippets.push_back({L";SIG", L"Ambiguous", L"other", {L"outlook.exe"}});
|
||||
bool collisionRejected=false;try { ks::validateSettings(collision); } catch(...) { collisionRejected=true; }
|
||||
require(collisionRejected, "overlapping app lists with same trigger rejected");
|
||||
auto emptyScope = scoped; emptyScope.snippets[1].apps={L""};
|
||||
bool emptyRejected=false;try { ks::validateSettings(emptyScope); } catch(...) { emptyRejected=true; }
|
||||
require(emptyRejected, "empty explicit restriction cannot become global");
|
||||
require(ks::telegramWebKey(L"https://web.telegram.org/k/#@Example") == L"telegram-web\n@example", "Telegram Web username normalized");
|
||||
require(ks::telegramWebKey(L"web.telegram.org/a/#-123456") == L"telegram-web\n-123456", "Telegram Web numeric peer");
|
||||
for (const auto *url : {L"https://web.telegram.org/k/", L"https://web.telegram.org.evil/k/#@example",
|
||||
L"http://web.telegram.org/k/#@example", L"https://evil/web.telegram.org/k/#@example",
|
||||
L"https://web.telegram.org/k/#@example?foo", L"https://web.telegram.org/k/#@",
|
||||
L"https://web.telegram.org/k/#-", L"https://web.telegram.org/k/#settings"})
|
||||
require(ks::telegramWebKey(url).empty(), "Reject non-chat or untrusted Telegram Web URL");
|
||||
const auto key = ks::chatKey(L"Telegram.exe", L"\u200eТестовий чат \u2013 (12)");
|
||||
require(key == L"telegram\nТестовий чат", "Telegram unread suffix");
|
||||
require(ks::chatKey(L"Telegram", L"Тестовий чат") == key, "stable unread profile");
|
||||
require(ks::chatKey(L"Telegram", L"Team (2026)") == L"telegram\nTeam (2026)", "preserve parentheses");
|
||||
require(ks::chatKey(L"Telegram", L"Telegram").empty(), "no profile on home");
|
||||
require(ks::chatKey(L"Viber", L"Rakuten Viber").empty(), "Viber generic window title is not a chat");
|
||||
require(ks::chatKey(L"ms-teams", L"Chat | Alice | Microsoft Teams") == L"ms-teams\nAlice", "Teams chat");
|
||||
require(ks::chatKey(L"ms-teams", L"Calendar | Alice | Microsoft Teams").empty(), "Teams calendar excluded");
|
||||
require(ks::chatKey(L"ms-teams", L"Chat | Microsoft Teams").empty(), "Teams chat home excluded");
|
||||
require(ks::chatKey(L"other", L"Chat | Alice | Microsoft Teams").empty(), "app identity required");
|
||||
ks::Settings settings;
|
||||
settings.cycle = {L"win:04090409", L"win:04220422", L"win:04190419"};
|
||||
settings.chatCycles[key] = {settings.cycle[1], settings.cycle[0]};
|
||||
settings.chatCycles[L"viber\nТестовий контакт"] = {settings.cycle[1], settings.cycle[0]};
|
||||
settings.chatCycles[L"telegram-web\n@example"] = {settings.cycle[0], settings.cycle[1]};
|
||||
std::vector<ks::Layout> installed(3);
|
||||
for (size_t i = 0; i < installed.size(); ++i)
|
||||
{
|
||||
installed[i].id = settings.cycle[i];
|
||||
installed[i].handle = (HKL)(uintptr_t)(i + 1);
|
||||
}
|
||||
auto subset = settings.chatCycles[key];
|
||||
require(ks::nextChatLayout(subset, installed, installed[1].handle, false) == installed[0].handle, "cycle within subset");
|
||||
require(ks::nextChatLayout(subset, installed, installed[0].handle, false) == installed[1].handle, "wrap skips excluded language");
|
||||
require(ks::nextChatLayout(subset, installed, installed[2].handle, false) == installed[1].handle, "outside subset enters first language");
|
||||
require(ks::nextChatLayout(settings.cycle, installed, installed[0].handle, true) == installed[2].handle, "reverse wraps");
|
||||
require(ks::nextChatLayout({settings.cycle[1]}, installed, installed[0].handle, false) == installed[1].handle, "single language selects allowed layout");
|
||||
require(!ks::nextChatLayout({L"win:04070407"}, installed, installed[0].handle, false), "missing layout is not activated");
|
||||
require(ks::nextConversionLayout(L"", installed, {1}, 0) == 1, "conversion uses single allowed language");
|
||||
require(ks::chatCycle(settings, key, installed) == settings.chatCycles[key], "profile order");
|
||||
require(ks::chatCycle(settings, L"telegram\nOther", installed) == settings.cycle, "unknown fallback");
|
||||
require(ks::decodeSettings(ks::encodeSettings(settings), installed).chatCycles == settings.chatCycles, "Unicode roundtrip");
|
||||
require(ks::decodeSettings({}, installed).chatCycles.empty(), "old defaults without profiles");
|
||||
auto withoutProfiles = settings;
|
||||
withoutProfiles.chatCycles.clear();
|
||||
require(ks::sharedSyncSettings(settings) != ks::sharedSyncSettings(withoutProfiles), "profiles included in sync");
|
||||
auto restored = ks::restoreSyncSettings(ks::sharedSyncSettings(settings), withoutProfiles, installed, false);
|
||||
require(restored.chatCycles == settings.chatCycles, "sync transfers chat profiles to another PC");
|
||||
settings.chatCycles[key] = {settings.cycle[1]};
|
||||
require(ks::chatCycle(settings, key, installed).size() == 1, "one-language profile");
|
||||
settings.chatCycles[key] = {L"win:04070407"};
|
||||
require(ks::chatCycle(settings, key, installed) == settings.cycle, "missing layouts fallback");
|
||||
settings.chatCycles[key] = {};
|
||||
bool rejected = false;
|
||||
try { ks::encodeSettings(settings); } catch (...) { rejected = true; }
|
||||
require(rejected, "empty profile rejected");
|
||||
settings.chatCycles[key] = {settings.cycle[0], settings.cycle[0]};
|
||||
rejected = false;
|
||||
try { ks::encodeSettings(settings); } catch (...) { rejected = true; }
|
||||
require(rejected, "duplicate profile layout rejected");
|
||||
ks::ChatSwitchHook hook;
|
||||
require(hook.update(VK_SPACE, true, MOD_WIN, false) == 0, "unprofiled Win+Space passes");
|
||||
require(hook.update(VK_SPACE, true, MOD_WIN, true) == 1, "Win+Space forward");
|
||||
require(hook.update(VK_SPACE, true, MOD_WIN, true) == -1, "consume repeat");
|
||||
require(hook.update(VK_SPACE, false, 0, false) == -1, "release after profile change");
|
||||
require(hook.update(VK_SPACE, true, MOD_WIN | MOD_SHIFT, true) == 2, "reverse cycle");
|
||||
hook.update(VK_SPACE, false, 0, true);
|
||||
require(hook.update(VK_LSHIFT, true, MOD_ALT, true) == 1, "Alt then Shift");
|
||||
hook.update(VK_LSHIFT, false, 0, true);
|
||||
require(hook.update(VK_LMENU, true, MOD_SHIFT, true) == 1, "Shift then Alt");
|
||||
hook.update(VK_LMENU, false, 0, true);
|
||||
require(hook.update(VK_LSHIFT, true, MOD_ALT | MOD_CONTROL, true) == 0, "do not consume Ctrl+Alt+Shift");
|
||||
require(hook.update('A', true, MOD_ALT, true) == 0, "ordinary keys pass");
|
||||
}
|
||||
}
|
||||
int main()
|
||||
{
|
||||
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-chat-tests-" + std::to_wstring(GetCurrentProcessId()));
|
||||
try
|
||||
{
|
||||
contextChecks();
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, root);
|
||||
require(!app.layouts.empty(), "installed layouts available");
|
||||
app.settings.toggle = app.settings.casing = app.settings.translit = app.settings.undo = L"";
|
||||
app.settings.clipboard = app.settings.screenshot = L"";
|
||||
app.settings.direct.assign(app.layouts.size(), L"");
|
||||
app.settings.history = app.settings.autoCorrect = false;
|
||||
const std::wstring key = L"telegram\n! Fixture chat";
|
||||
app.settings.chatCycles[key] = {app.layouts[0].id};
|
||||
ks::showSettings(app);
|
||||
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 changes.","new Settings shows clean state with Save disabled");
|
||||
SendMessageW(parent,WM_COMMAND,IDOK,0);
|
||||
require(IsWindow(parent),"Save command with no changes does not apply or close Settings");
|
||||
bool originalLog=IsDlgButtonChecked(parent,208)==BST_CHECKED;
|
||||
CheckDlgButton(parent,208,originalLog?BST_UNCHECKED:BST_CHECKED);
|
||||
SendMessageW(parent,WM_COMMAND,MAKEWPARAM(208,BN_CLICKED),0);
|
||||
require(saveEnabled() && status().find(L"Unsaved changes") == 0,"checkbox edit immediately marks Settings dirty");
|
||||
CheckDlgButton(parent,208,originalLog?BST_CHECKED:BST_UNCHECKED);
|
||||
SendMessageW(parent,WM_COMMAND,MAKEWPARAM(208,BN_CLICKED),0);
|
||||
require(!saveEnabled(),"reverting checkbox disables Save again");
|
||||
wchar_t originalLimit[32]{}; GetDlgItemTextW(parent,240,originalLimit,32);
|
||||
SetDlgItemTextW(parent,240,L"invalid");
|
||||
require(saveEnabled(),"invalid text remains an unsaved edit");
|
||||
SetDlgItemTextW(parent,240,originalLimit);
|
||||
require(!saveEnabled(),"restoring valid original text clears dirty state");
|
||||
SendMessageW(parent,WM_COMMAND,257,0);
|
||||
HWND ocr=FindWindowW(L"KSwitcher.OcrOptions",nullptr);
|
||||
require(ocr!=nullptr,"OCR preferences open");
|
||||
wchar_t languages[128]{}; GetDlgItemTextW(ocr,503,languages,128);
|
||||
SetDlgItemTextW(ocr,503,L"eng");
|
||||
SendMessageW(ocr,WM_COMMAND,IDCANCEL,0);
|
||||
require(!saveEnabled(),"cancelled child changes leave Settings clean");
|
||||
SendMessageW(parent,WM_COMMAND,257,0);
|
||||
ocr=FindWindowW(L"KSwitcher.OcrOptions",nullptr);
|
||||
SetDlgItemTextW(ocr,503,std::wstring(languages)==L"eng"?L"ukr":L"eng");
|
||||
SendMessageW(ocr,WM_COMMAND,IDOK,0);
|
||||
require(!IsWindow(ocr) && saveEnabled(),"accepted OCR edits enable parent Save");
|
||||
SendMessageW(parent,WM_COMMAND,257,0);
|
||||
ocr=FindWindowW(L"KSwitcher.OcrOptions",nullptr);
|
||||
SetDlgItemTextW(ocr,503,languages);
|
||||
SendMessageW(ocr,WM_COMMAND,IDOK,0);
|
||||
require(!saveEnabled(),"reverting OCR draft in child clears parent dirty state");
|
||||
SendMessageW(parent,WM_COMMAND,255,0);
|
||||
HWND automatic=FindWindowW(L"KSwitcher.AutoOptions",nullptr);
|
||||
require(automatic!=nullptr,"automatic correction preferences open");
|
||||
bool replace=IsDlgButtonChecked(automatic,414)==BST_CHECKED;
|
||||
CheckDlgButton(automatic,414,replace?BST_UNCHECKED:BST_CHECKED);
|
||||
SendMessageW(automatic,WM_COMMAND,IDOK,0);
|
||||
require(!IsWindow(automatic) && saveEnabled(),"accepted auto-correction edits enable Save");
|
||||
SendMessageW(parent,WM_COMMAND,255,0);
|
||||
automatic=FindWindowW(L"KSwitcher.AutoOptions",nullptr);
|
||||
CheckDlgButton(automatic,414,replace?BST_CHECKED:BST_UNCHECKED);
|
||||
SendMessageW(automatic,WM_COMMAND,IDOK,0);
|
||||
require(!saveEnabled(),"reverting auto-correction draft disables Save");
|
||||
HWND tabs = GetDlgItem(parent, 260);
|
||||
require(tabs && TabCtrl_GetItemCount(tabs) == 5, "five settings categories");
|
||||
for (int page = 0; page < 5; ++page)
|
||||
{
|
||||
TabCtrl_SetCurSel(tabs, page);
|
||||
NMHDR notification{tabs, 260, TCN_SELCHANGE};
|
||||
SendMessageW(parent, WM_NOTIFY, 260, (LPARAM)¬ification);
|
||||
std::vector<RECT> boxes;
|
||||
for (HWND child = GetWindow(parent, GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
|
||||
{
|
||||
if (!(GetWindowLongPtrW(child, GWL_STYLE) & WS_VISIBLE)) continue;
|
||||
RECT rect{}; GetWindowRect(child, &rect);
|
||||
for (const auto &other : boxes)
|
||||
{
|
||||
RECT overlap{};
|
||||
require(!IntersectRect(&overlap, &rect, &other), "visible settings controls never overlap");
|
||||
}
|
||||
boxes.push_back(rect);
|
||||
}
|
||||
RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
RECT rect{}; GetClientRect(parent, &rect);
|
||||
HDC dc = GetDC(parent);
|
||||
auto clip = ks::screenshotClip(dc, rect.right, rect.bottom, {});
|
||||
ReleaseDC(parent, dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / (L"settings-tab-" + std::to_wstring(page) + L".png"),
|
||||
ks::encodePng(ks::decodeImage(clip)));
|
||||
}
|
||||
TabCtrl_SetCurSel(tabs, 1);
|
||||
NMHDR notification{tabs, 260, TCN_SELCHANGE};
|
||||
SendMessageW(parent, WM_NOTIFY, 260, (LPARAM)¬ification);
|
||||
require(!saveEnabled(),"changing tabs leaves Settings clean");
|
||||
SendMessageW(parent, WM_COMMAND, 259, 0);
|
||||
HWND dialog = FindWindowW(L"KSwitcher.ChatLanguages", nullptr);
|
||||
require(dialog && !IsWindowEnabled(parent), "chat dialog opens with disabled parent");
|
||||
int index = (int)SendDlgItemMessageW(dialog, 710, LB_FINDSTRINGEXACT, -1, (LPARAM)L"Telegram: ! Fixture chat");
|
||||
require(index >= 0, "saved chat listed");
|
||||
SendDlgItemMessageW(dialog, 710, LB_SETCURSEL, index, 0);
|
||||
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(710, LBN_SELCHANGE), 0);
|
||||
require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "saved single language selected");
|
||||
RedrawWindow(dialog, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
|
||||
RECT rect{}; GetClientRect(dialog, &rect);
|
||||
HDC dc = GetDC(dialog);
|
||||
auto clip = ks::screenshotClip(dc, rect.right, rect.bottom, {});
|
||||
ReleaseDC(dialog, dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"chat-languages.png",
|
||||
ks::encodePng(ks::decodeImage(clip)));
|
||||
SendDlgItemMessageW(dialog, 711, LB_SETSEL, TRUE, -1);
|
||||
SendMessageW(dialog, WM_COMMAND, IDCANCEL, 0);
|
||||
require(!IsWindow(dialog) && IsWindowEnabled(parent), "cancel closes dialog");
|
||||
require(!saveEnabled(),"cancelled chat edits do not enable Save");
|
||||
SendMessageW(parent, WM_COMMAND, 259, 0);
|
||||
dialog = FindWindowW(L"KSwitcher.ChatLanguages", nullptr);
|
||||
index = (int)SendDlgItemMessageW(dialog, 710, LB_FINDSTRINGEXACT, -1, (LPARAM)L"Telegram: ! Fixture chat");
|
||||
SendDlgItemMessageW(dialog, 710, LB_SETCURSEL, index, 0);
|
||||
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(710, LBN_SELCHANGE), 0);
|
||||
require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "cancel discards language edits");
|
||||
SendDlgItemMessageW(dialog, 711, LB_SETSEL, TRUE, -1);
|
||||
SendMessageW(dialog, WM_COMMAND, IDOK, 0);
|
||||
require(!IsWindow(dialog) && IsWindowEnabled(parent), "profile applies to settings draft");
|
||||
require(saveEnabled() == (app.layouts.size()>1),"accepted chat edits refresh Save immediately");
|
||||
SendMessageW(parent, WM_COMMAND, IDOK, 0);
|
||||
require(!app.settingsWindow && app.settings.chatCycles.at(key).size() == app.layouts.size(), "settings saves selected languages");
|
||||
require(ks::loadSettings(root / L"settings.json", app.layouts).chatCycles == app.settings.chatCycles, "profile saved to disk");
|
||||
ks::showSettings(app);
|
||||
parent = app.settingsWindow;
|
||||
require(!saveEnabled(),"reopened saved Settings is clean");
|
||||
SendMessageW(parent, WM_COMMAND, 259, 0);
|
||||
dialog = FindWindowW(L"KSwitcher.ChatLanguages", nullptr);
|
||||
index = (int)SendDlgItemMessageW(dialog, 710, LB_FINDSTRINGEXACT, -1, (LPARAM)L"Telegram: ! Fixture chat");
|
||||
SendDlgItemMessageW(dialog, 710, LB_SETCURSEL, index, 0);
|
||||
SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(710, LBN_SELCHANGE), 0);
|
||||
SendMessageW(dialog, WM_COMMAND, 713, 0);
|
||||
require(saveEnabled() && status().find(L"Unsaved changes")==0,"removing child profile immediately marks parent dirty");
|
||||
RedrawWindow(parent,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
GetClientRect(parent,&rect); dc=GetDC(parent);
|
||||
clip=ks::screenshotClip(dc,rect.right,rect.bottom,{}); ReleaseDC(parent,dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"settings-unsaved.png",
|
||||
ks::encodePng(ks::decodeImage(clip)));
|
||||
SendMessageW(parent, WM_COMMAND, IDOK, 0);
|
||||
require(!app.settings.chatCycles.contains(key), "remove profile restores default");
|
||||
app.settings.snippets = {{L";scope", L"Example", L"scope-fixture"}};
|
||||
ks::showSettings(app); parent=app.settingsWindow;
|
||||
require(!saveEnabled(),"Settings starts clean before separately saved snippet edit");
|
||||
ks::showSnippets(app);
|
||||
HWND snippets = app.snippetsWindow;
|
||||
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
|
||||
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
|
||||
require(IsDlgButtonChecked(snippets,314)==BST_UNCHECKED, "old snippet shows everywhere");
|
||||
CheckDlgButton(snippets,314,BST_CHECKED);
|
||||
SendMessageW(snippets,WM_COMMAND,314,0);
|
||||
SetDlgItemTextW(snippets,315,L"Notepad.exe");
|
||||
auto secondApp = SendDlgItemMessageW(snippets,316,CB_ADDSTRING,0,(LPARAM)L"MS-Teams.EXE");
|
||||
SendDlgItemMessageW(snippets,316,CB_SETCURSEL,secondApp,0);
|
||||
SendMessageW(snippets,WM_COMMAND,317,0);
|
||||
SendMessageW(snippets,WM_COMMAND,317,0);
|
||||
wchar_t appList[128]{};
|
||||
GetDlgItemTextW(snippets,315,appList,128);
|
||||
require(std::wstring(appList)==L"Notepad.exe, MS-Teams.EXE", "Add app appends a second application without duplicates");
|
||||
SendMessageW(snippets,WM_COMMAND,IDOK,0);
|
||||
require(!app.snippetsWindow && app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "snippet editor saves selected applications");
|
||||
require(!saveEnabled() && status()==L"No unsaved changes.","separately saved snippet edit leaves Settings clean");
|
||||
SendMessageW(parent,WM_COMMAND,IDCANCEL,0);
|
||||
ks::showSnippets(app);snippets=app.snippetsWindow;
|
||||
SendDlgItemMessageW(snippets,301,LB_SETCURSEL,0,0);
|
||||
SendMessageW(snippets,WM_COMMAND,MAKEWPARAM(301,LBN_SELCHANGE),0);
|
||||
require(IsDlgButtonChecked(snippets,314)==BST_CHECKED, "scope restored when reopening editor");
|
||||
RedrawWindow(snippets,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
RECT snippetRect{};GetClientRect(snippets,&snippetRect);
|
||||
HDC snippetDc=GetDC(snippets);
|
||||
auto snippetImage=ks::screenshotClip(snippetDc,snippetRect.right,snippetRect.bottom,{});
|
||||
ReleaseDC(snippets,snippetDc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"snippet-scopes.png",ks::encodePng(ks::decodeImage(snippetImage)));
|
||||
SetDlgItemTextW(snippets,315,L"chrome.exe");
|
||||
SendMessageW(snippets,WM_COMMAND,IDCANCEL,0);
|
||||
require(app.settings.snippets[0].apps==std::vector<std::wstring>{L"notepad",L"ms-teams"}, "cancel preserves existing scope");
|
||||
ks::showSettings(app);parent=app.settingsWindow;
|
||||
SendMessageW(parent,WM_COMMAND,262,0);
|
||||
HWND lan=FindWindowW(L"KSwitcher.LAN",nullptr);
|
||||
require(lan && !IsWindowEnabled(parent),"LAN pairing opens a native child window");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,705)),"pairing disabled without discovered peer");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,706)),"no cancellation without pending pairing");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,707)),"cannot forget nonexistent pair");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,715)),"input sharing requires a paired computer");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,716)),"stop input disabled when sharing is off");
|
||||
require(GetDlgItem(lan,721)!=nullptr,"monitor arrangement grid is present");
|
||||
require(!(GetWindowLongPtrW(lan,GWL_STYLE)&(WS_THICKFRAME|WS_MAXIMIZEBOX)),"LAN window has a fixed size");
|
||||
require(GetDlgItem(lan,711)==nullptr,"obsolete side radios are removed");
|
||||
require(SendDlgItemMessageW(lan,702,LB_GETCOUNT,0,0)==0,"disabled discovery lists no generic network devices");
|
||||
require(!std::filesystem::exists(root/L"lan-pairing.bin"),"opening LAN settings does not enable or save discovery");
|
||||
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
RECT lanRect{};GetClientRect(lan,&lanRect);HDC lanDc=GetDC(lan);
|
||||
auto lanImage=ks::screenshotClip(lanDc,lanRect.right,lanRect.bottom,{});ReleaseDC(lan,lanDc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-pairing.png",ks::encodePng(ks::decodeImage(lanImage)));
|
||||
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);
|
||||
require(IsWindowEnabled(parent)&&!saveEnabled(),"closing discovery restores Settings without false unsaved state");
|
||||
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);
|
||||
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,262,0);
|
||||
HWND lan=FindWindowW(L"KSwitcher.LAN",nullptr);
|
||||
require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"single saved pair selected automatically when opening LAN settings");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,705))&&!IsWindowEnabled(GetDlgItem(lan,703))&&!IsWindowEnabled(GetDlgItem(lan,704)),"saved pair disables pairing and code controls");
|
||||
SendDlgItemMessageW(lan,702,LB_SETCURSEL,-1,0);
|
||||
SendMessageW(lan,WM_TIMER,1,0);
|
||||
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");
|
||||
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;
|
||||
while(GetTickCount64()<repaintUntil)
|
||||
{
|
||||
MSG message{};
|
||||
while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE)){TranslateMessage(&message);DispatchMessageW(&message);}
|
||||
Sleep(10);
|
||||
}
|
||||
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
RECT r{};GetClientRect(lan,&r);HDC dc=GetDC(lan);auto screenshot=ks::screenshotClip(dc,r.right,r.bottom,{});ReleaseDC(lan,dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-screen-layout.png",ks::encodePng(ks::decodeImage(screenshot)));
|
||||
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);
|
||||
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
}
|
||||
{
|
||||
using J=ks::lan::Json;const std::string b(32,'b'),c(32,'c');
|
||||
J fixture={{"version",1},{"id",std::string(32,'a')},{"enabled",false},{"inputPeer",b},{"inputEdge",0},
|
||||
{"trusted",{{b,{{"name","Left desktop"},{"key",std::string(64,'f')}}},{c,{{"name","Right laptop"},{"key",std::string(64,'e')}}}}},
|
||||
{"positions",{{b,J::array({-1,0})},{c,J::array({1,0})}}}};
|
||||
auto text=fixture.dump();ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(text.begin(),text.end())));
|
||||
ks::App layoutApp(GetModuleHandleW(nullptr),true,root);ks::showSettings(layoutApp);
|
||||
SendMessageW(layoutApp.settingsWindow,WM_COMMAND,262,0);auto lan=FindWindowW(L"KSwitcher.LAN",nullptr);auto grid=GetDlgItem(lan,721);
|
||||
RECT r{};GetClientRect(grid,&r);
|
||||
auto point=[&](int column,int row){return MAKELPARAM((2*column+1)*r.right/10,(2*row+1)*r.bottom/6);};
|
||||
SendMessageW(grid,WM_LBUTTONDOWN,MK_LBUTTON,point(1,1));SendMessageW(grid,WM_MOUSEMOVE,MK_LBUTTON,point(1,0));SendMessageW(grid,WM_LBUTTONUP,0,point(1,0));
|
||||
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");
|
||||
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
GetClientRect(lan,&r);auto dc=GetDC(lan);auto screenshot=ks::screenshotClip(dc,r.right,r.bottom,{});ReleaseDC(lan,dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-three-computers.png",ks::encodePng(ks::decodeImage(screenshot)));
|
||||
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);SendMessageW(layoutApp.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
}
|
||||
std::filesystem::remove_all(root);
|
||||
std::cout << "Passed " << passed << " chat profile checks\n";
|
||||
CoUninitialize();
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception &e) { std::cerr << "FAIL: " << e.what() << '\n'; CoUninitialize(); return 1; }
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Run with the resident stopped. The suite restores the original clipboard.
|
||||
#include "storage.h"
|
||||
#include "ocr.h"
|
||||
#include <psapi.h>
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
static void require(bool ok, const char *name) {
|
||||
if (!ok) throw std::runtime_error(name);
|
||||
std::cout << "PASS " << name << '\n';
|
||||
}
|
||||
static HWND owner() {
|
||||
return CreateWindowExW(0,L"STATIC",L"Snapshot test",0,0,0,0,0,HWND_MESSAGE,nullptr,nullptr,nullptr);
|
||||
}
|
||||
static void child(const std::wstring &argument) {
|
||||
auto exe=ks::executable(), command=L"\""+exe+L"\" "+argument;
|
||||
STARTUPINFOW startup{sizeof(startup)}; startup.dwFlags=STARTF_USESHOWWINDOW; startup.wShowWindow=SW_HIDE;
|
||||
PROCESS_INFORMATION p{};
|
||||
if(!CreateProcessW(exe.c_str(),command.data(),nullptr,nullptr,FALSE,CREATE_NO_WINDOW,nullptr,nullptr,&startup,&p))
|
||||
throw std::runtime_error("start fixture process");
|
||||
CloseHandle(p.hThread);
|
||||
auto wait=WaitForSingleObject(p.hProcess,30000); DWORD code=1;
|
||||
if(wait!=WAIT_OBJECT_0) {TerminateProcess(p.hProcess,1);WaitForSingleObject(p.hProcess,INFINITE);}
|
||||
GetExitCodeProcess(p.hProcess,&code); CloseHandle(p.hProcess);
|
||||
if(code) throw std::runtime_error("fixture process failed");
|
||||
}
|
||||
static size_t resident() {
|
||||
ks::Bytes b(1024*1024); auto ws=reinterpret_cast<PSAPI_WORKING_SET_INFORMATION*>(b.data());
|
||||
if(!QueryWorkingSet(GetCurrentProcess(),ws,DWORD(b.size()))) throw std::runtime_error("working set query");
|
||||
size_t pages=0; for(size_t i=0;i<ws->NumberOfEntries;++i) if(!ws->WorkingSetInfo[i].Shared) ++pages;
|
||||
return pages*4096;
|
||||
}
|
||||
static void verifyImage(HWND w) {
|
||||
auto c=ks::readClipboard(w,64*1024*1024);
|
||||
for(auto id:{CF_DIB,CF_DIBV5}) {
|
||||
auto it=std::find_if(c.formats.begin(),c.formats.end(),[&](const auto &f){return f.id==UINT(id);});
|
||||
require(it!=c.formats.end(),"restores image representation");
|
||||
auto pixels=ks::decodeImage(ks::Clip{{*it}});
|
||||
require(pixels.width==1566 && pixels.height==1068 && pixels.bgra.front()==77,"preserves image pixels");
|
||||
}
|
||||
require(c.text()==L"Snapshot mixed text","preserves accompanying text");
|
||||
}
|
||||
int main(int argc,char**argv) {
|
||||
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
HWND w=owner(); int result=0; ks::Clip original; bool saved=false;
|
||||
try {
|
||||
std::string mode=argc>1?argv[1]:"suite";
|
||||
if(mode=="publish") {
|
||||
ks::Pixels p{1566,1068,ks::Bytes(1566*1068*4,255)}; p.bgra[0]=77;
|
||||
auto dib=ks::imageDib(p); auto v5=dib;
|
||||
BITMAPV5HEADER h{}; h.bV5Size=sizeof(h); h.bV5Width=p.width; h.bV5Height=-p.height;
|
||||
h.bV5Planes=1; h.bV5BitCount=32; h.bV5Compression=BI_BITFIELDS;
|
||||
h.bV5RedMask=0xff0000; h.bV5GreenMask=0xff00; h.bV5BlueMask=0xff; h.bV5AlphaMask=0xff000000;
|
||||
v5.id=CF_DIBV5; v5.data.resize(sizeof(h)+p.bgra.size());
|
||||
memcpy(v5.data.data(),&h,sizeof(h)); memcpy(v5.data.data()+sizeof(h),p.bgra.data(),p.bgra.size());
|
||||
auto clip=ks::textClip(L"Snapshot mixed text"); clip.formats.push_back(dib); clip.formats.push_back(v5);
|
||||
ks::writeClipboard(w,clip);
|
||||
} else if(mode=="old" || mode=="new") {
|
||||
child(L"publish"); auto baseline=resident();
|
||||
if(mode=="old") {
|
||||
auto clip=ks::readClipboard(w,64*1024*1024);
|
||||
ks::writeClipboard(w,ks::textClip(L"temporary")); ks::writeClipboard(w,clip);
|
||||
} else {
|
||||
ks::ClipboardSnapshot snapshot; snapshot.capture(w,GetClipboardSequenceNumber());
|
||||
auto seq=ks::writeClipboard(w,ks::textClip(L"temporary"));
|
||||
require(snapshot.restore(w,seq)==GetClipboardSequenceNumber(),"helper returns current sequence");
|
||||
}
|
||||
auto after=resident();
|
||||
auto report="baseline="+std::to_string(baseline)+" after="+std::to_string(after)+" delta="+std::to_string(int64_t(after)-int64_t(baseline))+"\n";
|
||||
auto path=std::filesystem::path(ks::executable()).parent_path()/(L"snapshot-memory-"+ks::wide(mode)+L".txt");
|
||||
ks::atomicWrite(path,ks::Bytes(report.begin(),report.end()));
|
||||
verifyImage(w); // Only after measuring: verification intentionally reads images.
|
||||
} else {
|
||||
original=ks::readClipboard(w,128*1024*1024); saved=true;
|
||||
child(L"old"); child(L"new"); child(L"publish");
|
||||
auto seq=GetClipboardSequenceNumber();
|
||||
auto selected=ks::readClipboard(w,32*1024*1024,ks::ClipboardRead::Selection);
|
||||
require(selected.formats.size()==1 && selected.text()==L"Snapshot mixed text","selection read excludes image data");
|
||||
bool rejected=false;
|
||||
try {ks::readClipboard(w,32*1024*1024,ks::ClipboardRead::WithoutImages,seq);} catch(...) {rejected=true;}
|
||||
require(rejected,"resident rejects images before reading their data");
|
||||
{
|
||||
ks::ClipboardSnapshot snapshot; snapshot.capture(w,seq);
|
||||
auto stale=ks::writeClipboard(w,ks::textClip(L"temporary"));
|
||||
ks::writeClipboard(w,ks::textClip(L"external copy")); rejected=false;
|
||||
try {snapshot.restore(w,stale);} catch(...) {rejected=true;}
|
||||
require(rejected && ks::readClipboard(w).text()==L"external copy","stale image restore preserves external copy");
|
||||
}
|
||||
{
|
||||
ks::ClipboardSnapshot snapshot; snapshot.capture(w,GetClipboardSequenceNumber());
|
||||
auto temporary=ks::writeClipboard(w,ks::textClip(L"temporary"));
|
||||
snapshot.restore(w,temporary);
|
||||
require(ks::readClipboard(w).text()==L"external copy","text snapshot fast path restores clipboard");
|
||||
}
|
||||
{
|
||||
ks::Clip empty; auto seqEmpty=ks::writeClipboard(w,empty);
|
||||
ks::ClipboardSnapshot snapshot; snapshot.capture(w,seqEmpty);
|
||||
snapshot.restore(w,ks::writeClipboard(w,ks::textClip(L"temporary")));
|
||||
require(ks::readClipboard(w).formats.empty(),"empty clipboard restored");
|
||||
}
|
||||
auto marked=ks::textClip(L"line"); marked.formats.push_back({0,L"MSDEVLineSelect",ks::Bytes{1}});
|
||||
ks::writeClipboard(w,marked);
|
||||
require(ks::readClipboard(w,1024,ks::ClipboardRead::Selection).formats.size()==2,"selection reader preserves editor guard metadata");
|
||||
std::cout<<"PASS clipboard snapshot suite\n";
|
||||
}
|
||||
} catch(const std::exception &e) {std::cerr<<"FAIL "<<e.what()<<'\n';result=1;}
|
||||
if(saved) try {ks::writeClipboard(w,original);} catch(...) {result=1;}
|
||||
DestroyWindow(w); CoUninitialize(); return result;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
#include "autocorrect.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <psapi.h>
|
||||
#include <random>
|
||||
namespace ks {
|
||||
struct AutoCorrectorRegressionAccess {
|
||||
static int rank(const AutoCorrector &c,const std::wstring &lang,const std::wstring &word) {
|
||||
return c.dictionaries.at(lang)->rank(word);
|
||||
}
|
||||
static std::vector<int> ranks(const std::filesystem::path &path,const std::vector<std::wstring> &words) {
|
||||
AutoCorrector::Dictionary d(path);
|
||||
std::vector<int> values;for(const auto &word:words)values.push_back(d.rank(word));return values;
|
||||
}
|
||||
};
|
||||
}
|
||||
int main(int argc,char **argv) {
|
||||
try {
|
||||
auto start=std::chrono::steady_clock::now();
|
||||
ks::AutoCorrector c;c.configure(L"dictionaries",{L"en",L"uk",L"ru"});
|
||||
PROCESS_MEMORY_COUNTERS_EX m{};
|
||||
GetProcessMemoryInfo(GetCurrentProcess(),reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&m),sizeof(m));
|
||||
std::cout<<"dictionary_bytes="<<c.memoryBytes()<<" private_bytes="<<m.PrivateUsage
|
||||
<<" load_ms="<<std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()<<'\n';
|
||||
struct Query {std::wstring language,word; int rank;};
|
||||
std::vector<Query> queries;
|
||||
for(const auto *lang:{L"en",L"uk",L"ru"}) {
|
||||
std::ifstream input(std::filesystem::path(L"dictionaries")/(std::wstring(lang)+L".txt"));
|
||||
std::map<std::wstring,int> expected;
|
||||
for(std::string line;std::getline(input,line);) {
|
||||
auto tab=line.find('\t');auto word=ks::wide(line.substr(0,tab));auto rank=std::stoi(line.substr(tab+1));
|
||||
auto [it,added]=expected.emplace(word,rank);if(!added)it->second=std::min(it->second,rank);
|
||||
}
|
||||
if(expected.empty())throw std::runtime_error("Missing benchmark dictionary");
|
||||
for(auto &[word,rank]:expected) {
|
||||
if(ks::AutoCorrectorRegressionAccess::rank(c,lang,word)!=rank)throw std::runtime_error("Dictionary rank differs from source");
|
||||
if(ks::AutoCorrectorRegressionAccess::rank(c,lang,word+L"~")!=0)throw std::runtime_error("False dictionary hit");
|
||||
queries.push_back({lang,word,rank});queries.push_back({lang,word+L"~",0});
|
||||
}
|
||||
}
|
||||
std::mt19937 random(42);std::shuffle(queries.begin(),queries.end(),random);
|
||||
uint64_t checksum=0,expected=0;
|
||||
for(auto &q:queries)expected+=q.rank;
|
||||
start=std::chrono::steady_clock::now();
|
||||
for(int pass=0;pass<5;++pass)for(auto &q:queries)checksum+=ks::AutoCorrectorRegressionAccess::rank(c,q.language,q.word);
|
||||
auto ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count();
|
||||
if(checksum!=expected*5)throw std::runtime_error("Lookup checksum mismatch");
|
||||
std::cout<<"verified_words="<<queries.size()/2<<" queries="<<queries.size()*5<<" lookup_ms="<<ms
|
||||
<<" ns_per_lookup="<<ms*1000000/(queries.size()*5)<<" checksum="<<checksum<<'\n';
|
||||
auto fixture=std::filesystem::temp_directory_path()/(L"KSwitcher-dictionary-"+
|
||||
std::to_wstring(GetCurrentProcessId())+L"-"+std::to_wstring(GetTickCount64())+L".txt");
|
||||
struct RemoveFixture { std::filesystem::path path; ~RemoveFixture(){std::error_code ec;std::filesystem::remove(path,ec);} } cleanup{fixture};
|
||||
auto put=[&](const std::string &text){ks::atomicWrite(fixture,ks::Bytes(text.begin(),text.end()));};
|
||||
std::string text="duplicate\t9\r\nduplicate\t2\n";
|
||||
std::vector<std::wstring> words;
|
||||
std::vector<int> expectedRanks;
|
||||
for(int i=129;i>=0;--i) {
|
||||
auto word=L"prefix_"+std::to_wstring(i);
|
||||
text+=ks::utf8(word)+"\t"+std::to_string(i+1)+"\n";
|
||||
words.push_back(word);expectedRanks.push_back(i+1);
|
||||
}
|
||||
text+=std::string(160,'x')+"\t2147483647"; // Maximum length/rank, no final newline.
|
||||
words.insert(words.end(),{std::wstring(160,L'x'),L"DUPLICATE",L"",L"prefix_",L"zzzz"});
|
||||
expectedRanks.insert(expectedRanks.end(),{2147483647,2,0,0,0});
|
||||
for(auto rank:{65534,65535,65536}) {
|
||||
auto word=std::wstring(159,L'x')+wchar_t(L'y'+rank-65534);
|
||||
text+="\n"+ks::utf8(word)+"\t"+std::to_string(rank);
|
||||
words.push_back(word);expectedRanks.push_back(rank);
|
||||
}
|
||||
put(text);
|
||||
if(ks::AutoCorrectorRegressionAccess::ranks(fixture,words)!=expectedRanks)
|
||||
throw std::runtime_error("Block boundaries, duplicate ranks or maximum values failed");
|
||||
for(const auto &invalid:std::vector<std::string>{"","missing-tab","x\t0","x\t-1","x\t2147483648",std::string(161,'x')+"\t1","\t1","x\t1bad"}) {
|
||||
put(invalid);bool rejected=false;
|
||||
try {ks::AutoCorrectorRegressionAccess::ranks(fixture,{L"x"});}catch(const std::runtime_error &){rejected=true;}
|
||||
if(!rejected)throw std::runtime_error("Invalid dictionary was accepted");
|
||||
}
|
||||
const bool baseline=argc==2 && std::string(argv[1])=="--baseline";
|
||||
if(!baseline && c.memoryBytes()>=1536*1024)throw std::runtime_error("Bundled dictionaries exceed compact memory budget");
|
||||
std::cout<<"Passed complete dictionary equivalence and format regressions\n";
|
||||
return 0;
|
||||
}catch(const std::exception&e){std::cerr<<e.what()<<'\n';return 1;}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// Explicit Windows integration test. Opens an isolated Far profile and never
|
||||
// types into an existing Far window. Requires Far Manager at its default path.
|
||||
#include "app.h"
|
||||
#include <cstdlib>
|
||||
#include <cwctype>
|
||||
#include <fstream>
|
||||
#include <future>
|
||||
|
||||
namespace ks {
|
||||
struct InputRegressionAccess {
|
||||
static void runQueued(App &app) {
|
||||
std::function<void()> job;
|
||||
{ std::lock_guard lock(app.jobsMutex);
|
||||
if (app.jobs.empty()) throw std::runtime_error("snippet did not queue");
|
||||
job=std::move(app.jobs.front());app.jobs.pop_front(); }
|
||||
auto future=std::async(std::launch::async,[job=std::move(job)] {
|
||||
CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);job();CoUninitialize();
|
||||
});
|
||||
while(future.wait_for(std::chrono::milliseconds(5))!=std::future_status::ready) {
|
||||
MSG message{};while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) {
|
||||
TranslateMessage(&message);DispatchMessageW(&message);
|
||||
}
|
||||
}
|
||||
future.get();app.replayTyping();
|
||||
}
|
||||
};
|
||||
}
|
||||
int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) {
|
||||
auto base=std::filesystem::path(ks::executable()).parent_path();
|
||||
std::ofstream log(base/L"far-snippets.log");
|
||||
int checks=0;
|
||||
auto require=[&](bool ok,const char *message) {
|
||||
if(!ok)throw std::runtime_error(message);
|
||||
++checks;log<<"PASS "<<message<<'\n';log.flush();
|
||||
};
|
||||
auto folder=std::filesystem::temp_directory_path()/(L"ks-far-snippets-"+ks::newSnippetId());
|
||||
std::filesystem::create_directories(folder);
|
||||
CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
|
||||
ks::Clip saved;bool captured=false;PROCESS_INFORMATION child{};
|
||||
HANDLE input=INVALID_HANDLE_VALUE,output=INVALID_HANDLE_VALUE;
|
||||
HWND farWindow{};
|
||||
HWND owner=CreateWindowExW(0,L"STATIC",L"Far snippet fixture clipboard",0,0,0,0,0,HWND_MESSAGE,nullptr,instance,nullptr);
|
||||
auto originalForeground=GetForegroundWindow();
|
||||
int result=1;
|
||||
try {
|
||||
saved=ks::readClipboard(owner,128*1024*1024);captured=true;
|
||||
auto sentinel=ks::textClip(L"KSwitcher Far fixture clipboard");
|
||||
sentinel.formats.push_back({0,L"ExcludeClipboardContentFromMonitorProcessing",ks::Bytes{0}});
|
||||
ks::writeClipboard(owner,sentinel);
|
||||
const auto programFiles=_wgetenv(L"ProgramFiles");
|
||||
if(!programFiles)throw std::runtime_error("ProgramFiles is unavailable");
|
||||
auto farExecutable=std::filesystem::path(programFiles)/L"Far Manager/Far.exe";
|
||||
std::wstring command=L"\""+farExecutable.wstring()+L"\" -m -p -s \""+folder.wstring()+L"\\profile\"";
|
||||
// A GUID-length working directory can horizontally scroll Far's command
|
||||
// line, making absolute cursor-cell assertions invalid. Keep the prompt
|
||||
// short; profile and application data still live in the unique fixture.
|
||||
auto workingDirectory=folder.root_path();
|
||||
STARTUPINFOW startup{sizeof(startup)};startup.dwFlags=STARTF_USESHOWWINDOW;startup.wShowWindow=SW_HIDE;
|
||||
require(CreateProcessW(nullptr,command.data(),nullptr,nullptr,FALSE,CREATE_NEW_CONSOLE,nullptr,workingDirectory.c_str(),&startup,&child),"start isolated Far without plugins/macros");
|
||||
CloseHandle(child.hThread);Sleep(1800);
|
||||
require(AttachConsole(child.dwProcessId),"attach isolated console for test-only input and observation");
|
||||
input=CreateFileW(L"CONIN$",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,nullptr,OPEN_EXISTING,0,nullptr);
|
||||
output=CreateFileW(L"CONOUT$",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,nullptr,OPEN_EXISTING,0,nullptr);
|
||||
require(input!=INVALID_HANDLE_VALUE && output!=INVALID_HANDLE_VALUE,"open isolated console buffers");
|
||||
auto target=GetConsoleWindow();farWindow=target;ShowWindow(target,SW_SHOW);
|
||||
require(ks::activateWindow(target),"activate only the isolated Far window");
|
||||
auto key=[&](WORD vk,wchar_t c=0,DWORD mods=0) {
|
||||
INPUT_RECORD records[2]{};
|
||||
for(int i=0;i<2;++i) {
|
||||
auto &r=records[i];r.EventType=KEY_EVENT;
|
||||
r.Event.KeyEvent={BOOL(i==0),1,vk,WORD(MapVirtualKeyW(vk,MAPVK_VK_TO_VSC)),{c},mods};
|
||||
}
|
||||
DWORD written{};
|
||||
if(!WriteConsoleInputW(input,records,2,&written)||written!=2)throw std::runtime_error("test input failed");
|
||||
Sleep(60);
|
||||
};
|
||||
auto position=[&] {CONSOLE_SCREEN_BUFFER_INFO info{};if(!GetConsoleScreenBufferInfo(output,&info))throw std::runtime_error("console position unavailable");return info.dwCursorPosition;};
|
||||
auto row=[&] {
|
||||
CONSOLE_SCREEN_BUFFER_INFO info{};GetConsoleScreenBufferInfo(output,&info);
|
||||
std::wstring text(info.dwSize.X,L' ');DWORD count{};
|
||||
if(!ReadConsoleOutputCharacterW(output,text.data(),DWORD(text.size()),{0,info.dwCursorPosition.Y},&count))throw std::runtime_error("console row unavailable");
|
||||
return text;
|
||||
};
|
||||
{
|
||||
ks::App app(instance,false,folder/L"data");app.window=owner;
|
||||
app.settings.history=false;app.settings.autoCorrect=false;app.settings.writeLog=true;
|
||||
auto prepare=[&](wchar_t last=L'r') {
|
||||
if(!ks::activateWindow(target))throw std::runtime_error("isolated Far lost foreground");
|
||||
key(VK_ESCAPE);key('Y',0,LEFT_CTRL_PRESSED);key(VK_OEM_1,L':',SHIFT_PRESSED);key(WORD(towupper(last)),last);
|
||||
app.run.reset();app.run.window=target;app.run.layout=ks::windowLayout(target);
|
||||
app.run.at=GetTickCount64();app.run.keys=L":r";
|
||||
};
|
||||
auto expand=[&](const std::wstring &replacement) {
|
||||
app.settings.snippets={{L":r",replacement}};
|
||||
app.transform(0,0);ks::InputRegressionAccess::runQueued(app);Sleep(120);
|
||||
};
|
||||
for(int panels=0;panels<2;++panels) {
|
||||
prepare();auto before=position();auto original=row();expand(L"rider .");
|
||||
auto expected=original;expected.replace(before.X-2,2,L"rider .");expected.resize(original.size());
|
||||
// Far's rightmost scroll indicator is redrawn rather than shifted.
|
||||
require(row().substr(0,before.X+5)==expected.substr(0,before.X+5),"actual snippet replaces :r with rider .");
|
||||
require(position().X==before.X+5,"successful expansion leaves cursor after replacement");
|
||||
require(ks::readClipboard(owner).text()==sentinel.text(),"snippet restores original clipboard");
|
||||
prepare(L'x');before=position();original=row();expand(L"rider .{enter}");
|
||||
require(row()==original && position().X==before.X,"mismatched trigger restores original caret and never executes Enter");
|
||||
prepare();before=position();original=row();expand(L"left{cursor}right");
|
||||
require(row().substr(before.X-2,9)==L"leftright" && position().X==before.X+2,"cursor marker uses Far selection semantics");
|
||||
prepare();before=position();original=row();expand(L"first\nsecond{enter}");
|
||||
require(row()==original && position().X==before.X,"multiline console template rejected before changing text or caret");
|
||||
prepare();before=position();original=row();expand(L"echo KSWITCHER_FAR_FIXTURE{enter}");
|
||||
for(int wait=0;wait<30 && position().X!=before.X-2;++wait)Sleep(100);
|
||||
require(position().X==before.X-2 && row().substr(before.X-2,2)==L" ",
|
||||
"verified Enter runs only the harmless fixture echo and returns to an empty command line");
|
||||
key('O',0,LEFT_CTRL_PRESSED);
|
||||
}
|
||||
app.window=nullptr;
|
||||
}
|
||||
log<<"Passed "<<checks<<" Far snippet integration checks\n";result=0;
|
||||
}catch(const std::exception &e){log<<"FAIL "<<e.what()<<" win32="<<GetLastError()<<'\n';}
|
||||
// A real user or clipboard synchronizer can copy during this explicit test.
|
||||
// Never replace that newer content with the fixture's original snapshot.
|
||||
const auto restoreSequence=GetClipboardSequenceNumber();
|
||||
const bool restoreClipboard=GetClipboardOwner()==owner || (farWindow && ks::ownsClipboard(farWindow));
|
||||
if(input!=INVALID_HANDLE_VALUE)CloseHandle(input);
|
||||
if(output!=INVALID_HANDLE_VALUE)CloseHandle(output);
|
||||
FreeConsole();
|
||||
if(child.hProcess){TerminateProcess(child.hProcess,0);WaitForSingleObject(child.hProcess,5000);CloseHandle(child.hProcess);}
|
||||
if(captured && restoreClipboard && GetClipboardSequenceNumber()==restoreSequence)
|
||||
try{ks::writeClipboard(owner,saved);}catch(...){result=1;}
|
||||
DestroyWindow(owner);
|
||||
if(IsWindow(originalForeground))ks::activateWindow(originalForeground);
|
||||
CoUninitialize();return result;
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// Run from an isolated fixture folder containing KSwitcher.exe and Screenshot.exe,
|
||||
// with the normal resident stopped. Never points at the installed user's data.
|
||||
#include "storage.h"
|
||||
#include "ocr.h"
|
||||
#include "json.hpp"
|
||||
#include <commctrl.h>
|
||||
#include <psapi.h>
|
||||
#include <iostream>
|
||||
static HWND editor{};
|
||||
static bool pastedImage{};
|
||||
static LRESULT CALLBACK targetProc(HWND w,UINT message,WPARAM wp,LPARAM lp) {
|
||||
if(message==WM_SETFOCUS && editor) {SetFocus(editor);return 0;}
|
||||
return DefWindowProcW(w,message,wp,lp);
|
||||
}
|
||||
static void require(bool ok,const char *what) {if(!ok)throw std::runtime_error(what);std::cout<<"PASS "<<what<<'\n';}
|
||||
static void pump() {MSG m;while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}}
|
||||
template<class F> static void until(F condition,const char *what,DWORD timeout=10000) {
|
||||
auto end=GetTickCount64()+timeout;
|
||||
while(!condition()){if(GetTickCount64()>=end)throw std::runtime_error(what);pump();Sleep(10);}
|
||||
}
|
||||
static LRESULT send(HWND w,UINT message,WPARAM wp=0,LPARAM lp=0) {
|
||||
DWORD_PTR result{};
|
||||
if(!SendMessageTimeoutW(w,message,wp,lp,SMTO_ABORTIFHUNG,5000,&result))throw std::runtime_error("window request timed out");
|
||||
return LRESULT(result);
|
||||
}
|
||||
static void command(HWND resident,int cmd) {
|
||||
COPYDATASTRUCT data{1,sizeof(cmd),&cmd};send(resident,WM_COPYDATA,0,LPARAM(&data));
|
||||
}
|
||||
static size_t memory(HANDLE process) {
|
||||
ks::Bytes bytes(1024*1024);auto ws=reinterpret_cast<PSAPI_WORKING_SET_INFORMATION*>(bytes.data());
|
||||
if(!QueryWorkingSet(process,ws,DWORD(bytes.size())))throw std::runtime_error("memory query failed");
|
||||
size_t pages=0;for(size_t i=0;i<ws->NumberOfEntries;++i)if(!ws->WorkingSetInfo[i].Shared)++pages;
|
||||
return pages*4096;
|
||||
}
|
||||
static std::wstring editorText() {wchar_t text[256]{};GetWindowTextW(editor,text,256);return text;}
|
||||
static LRESULT CALLBACK editProc(HWND w,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) {
|
||||
if(message==WM_PASTE && IsClipboardFormatAvailable(CF_DIB)) {pastedImage=true;return 0;}
|
||||
return DefSubclassProc(w,message,wp,lp);
|
||||
}
|
||||
static ks::Clip excluded(ks::Clip clip) {
|
||||
clip.formats.push_back({0,L"ExcludeClipboardContentFromMonitorProcessing",ks::Bytes{0}});return clip;
|
||||
}
|
||||
int main() {
|
||||
CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
|
||||
PROCESS_INFORMATION process{};HWND resident{},target{};ks::Clip saved;bool captured=false;int result=0;
|
||||
try {
|
||||
auto folder=std::filesystem::path(ks::executable()).parent_path();
|
||||
require(folder.filename().wstring().starts_with(L"history-host-fixture-"),"isolated fixture directory");
|
||||
require(!FindWindowW(L"KSwitcher.Main",nullptr),"normal resident is stopped");
|
||||
WNDCLASSW targetClass{};targetClass.lpfnWndProc=targetProc;targetClass.hInstance=GetModuleHandleW(nullptr);
|
||||
targetClass.lpszClassName=L"KSwitcher.HistoryTestDestination";RegisterClassW(&targetClass);
|
||||
target=CreateWindowExW(0,targetClass.lpszClassName,L"KSwitcher history test destination",WS_OVERLAPPEDWINDOW|WS_VISIBLE,
|
||||
50,50,500,250,nullptr,nullptr,nullptr,nullptr);
|
||||
editor=CreateWindowExW(0,L"EDIT",L"",WS_CHILD|WS_VISIBLE|ES_MULTILINE,10,10,450,180,target,nullptr,nullptr,nullptr);
|
||||
SetWindowSubclass(editor,editProc,1,0);
|
||||
saved=ks::readClipboard(target,128*1024*1024);captured=true;
|
||||
ks::writeClipboard(target,excluded(ks::textClip(L"fixture clipboard")));
|
||||
auto settings=ks::loadSettings(folder/L"missing.json",ks::readLayouts());
|
||||
settings.autoCorrect=false;settings.writeLog=true;settings.history=true;settings.maxItems=500;settings.maxMiB=100;
|
||||
std::filesystem::create_directories(folder/L"data");
|
||||
ks::saveSettings(folder/L"data/settings.json",settings);
|
||||
ks::History history(folder/L"data/history");
|
||||
history.clear(); // This executable only runs in its dedicated fixture directory.
|
||||
ks::Pixels pixels{1566,1068,ks::Bytes(1566*1068*4,255)};
|
||||
auto image=ks::Clip{{ks::imageDib(pixels)}};
|
||||
history.add(image,L"test",settings);
|
||||
auto imageId=history.entries().front().id;
|
||||
// Seed once rather than rewriting the encrypted index 500 times. This
|
||||
// also avoids measuring fixture creation in the resident under test.
|
||||
auto indexPath=folder/L"data/history/index.dat";
|
||||
auto rows=nlohmann::json::parse(ks::unprotect(ks::readFile(indexPath,1024*1024)));
|
||||
for(int i=0;i<499;++i) {
|
||||
auto id=ks::lower(ks::newSnippetId().substr(1,36)),text=L"History fixture "+std::to_wstring(i);
|
||||
auto bytes=ks::protect(ks::encodeClip(ks::textClip(text)));
|
||||
ks::atomicWrite(folder/L"data/history"/(id+L".dat"),bytes);
|
||||
rows.insert(rows.begin(),nlohmann::json{{"id",ks::utf8(id)},{"preview",ks::utf8(text)},
|
||||
{"app","test"},{"bytes",bytes.size()},{"at",i+1},{"pinned",false},{"image",false},{"files",false}});
|
||||
}
|
||||
auto encoded=rows.dump();ks::atomicWrite(indexPath,ks::protect(ks::Bytes(encoded.begin(),encoded.end())));
|
||||
history.reload();
|
||||
auto textId=history.entries().front().id;
|
||||
auto exe=folder/L"KSwitcher.exe";auto line=L"\""+exe.wstring()+L"\"";
|
||||
STARTUPINFOW startup{sizeof(startup)};startup.dwFlags=STARTF_USESHOWWINDOW;startup.wShowWindow=SW_HIDE;
|
||||
require(CreateProcessW(exe.c_str(),line.data(),nullptr,nullptr,FALSE,CREATE_NO_WINDOW,nullptr,folder.c_str(),&startup,&process),"start isolated resident");
|
||||
CloseHandle(process.hThread);process.hThread=nullptr;
|
||||
until([&]{resident=FindWindowW(L"KSwitcher.Main",nullptr);return resident!=nullptr;},"resident startup");
|
||||
auto base=memory(process.hProcess);
|
||||
std::string forged="{\"action\":\"clear\",\"id\":\"\",\"plain\":false}";
|
||||
COPYDATASTRUCT forgedRequest{0x4b530200,DWORD(forged.size()),forged.data()};
|
||||
require(send(resident,WM_COPYDATA,WPARAM(target),LPARAM(&forgedRequest))==0,
|
||||
"history rejects requests from an untrusted process");
|
||||
auto open=[&] {
|
||||
require(ks::activateWindow(target),"destination foreground");SetFocus(editor);command(resident,5);
|
||||
HWND window{};
|
||||
until([&]{window=FindWindowW(L"KSwitcher.History",nullptr);return window&&IsWindowVisible(window);},"history startup");
|
||||
until([&]{return send(GetDlgItem(window,102),LB_GETCOUNT)>0;},"history rows");
|
||||
DWORD pid{};GetWindowThreadProcessId(window,&pid);
|
||||
require(pid!=process.dwProcessId,"history belongs to a separate process");
|
||||
return window;
|
||||
};
|
||||
auto close=[&](HWND window) {
|
||||
DWORD pid{};GetWindowThreadProcessId(window,&pid);HANDLE child=OpenProcess(SYNCHRONIZE,FALSE,pid);
|
||||
PostMessageW(window,WM_KEYDOWN,VK_ESCAPE,0); // Escape also works with focus on the window itself.
|
||||
until([&]{return WaitForSingleObject(child,0)==WAIT_OBJECT_0;},"history helper exits after Escape");
|
||||
CloseHandle(child);
|
||||
require(!FindWindowW(L"KSwitcher.History",nullptr),"Escape destroys history window");
|
||||
};
|
||||
for(int i=0;i<3;++i){auto w=open();until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==500;},"all history rows loaded");require(true,"all history entries visible");close(w);}
|
||||
auto idle=memory(process.hProcess);
|
||||
std::cout<<"MEMORY resident_before="<<base<<" after_three_closes="<<idle<<'\n';
|
||||
require(idle<base+2*1024*1024,"repeated history does not retain UI heap in resident");
|
||||
auto w=open();send(w,WM_COMMAND,112);
|
||||
until([&]{history.reload();return history.entries().front().pinned;},"resident pin mutation");
|
||||
require(history.entries().front().id==textId,"pin preserves history identity");
|
||||
auto filter=[&](HWND window,int index) {
|
||||
auto checkbox=GetDlgItem(window,117);
|
||||
if(send(checkbox,BM_GETCHECK)!=(index ? BST_CHECKED : BST_UNCHECKED)) send(checkbox,BM_CLICK);
|
||||
};
|
||||
filter(w,1);
|
||||
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==1;},"pinned filter hides unpinned entries");
|
||||
send(GetDlgItem(w,101),WM_SETTEXT,0,LPARAM(L"History fixture 497"));
|
||||
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==0;},"search cannot match an unpinned item in pinned view");
|
||||
send(GetDlgItem(w,101),WM_SETTEXT,0,LPARAM(L"History fixture 498"));
|
||||
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==1;},"history search");
|
||||
send(w,WM_COMMAND,112);
|
||||
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==0;},"unpin removes the last pinned result");
|
||||
filter(w,0);
|
||||
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==1;},"all items restores the matching unpinned entry");
|
||||
send(w,WM_COMMAND,112);
|
||||
filter(w,1);
|
||||
close(w);w=open();
|
||||
require(send(GetDlgItem(w,117),BM_GETCHECK)==BST_CHECKED,"pinned checkbox survives helper restart");
|
||||
wchar_t query[100]{};send(GetDlgItem(w,101),WM_GETTEXT,100,LPARAM(query));
|
||||
require(std::wstring(query)==L"History fixture 498","search survives helper restart");
|
||||
send(w,WM_COMMAND,114);
|
||||
HWND entry{};until([&]{entry=FindWindowW(L"KSwitcher.Entry",nullptr);return entry!=nullptr;},"full item opens");
|
||||
DWORD childPid{};GetWindowThreadProcessId(w,&childPid);HANDLE child=OpenProcess(SYNCHRONIZE,FALSE,childPid);
|
||||
send(GetDlgItem(w,101),WM_KEYDOWN,VK_ESCAPE);
|
||||
require(WaitForSingleObject(child,0)==WAIT_TIMEOUT && IsWindow(entry),"full item remains usable after closing history");
|
||||
send(entry,WM_CLOSE);
|
||||
until([&]{return WaitForSingleObject(child,0)==WAIT_OBJECT_0;},"helper exits after last full item closes");CloseHandle(child);
|
||||
w=open();filter(w,0);send(GetDlgItem(w,101),WM_SETTEXT,0,LPARAM(L""));
|
||||
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==500;},"clear search");close(w);
|
||||
ks::writeClipboard(target,excluded(image));
|
||||
w=open();send(w,WM_COMMAND,111);
|
||||
until([&]{return editorText()==L"History fixture 498";},"paste plain text into native editor");
|
||||
until([&]{return IsClipboardFormatAvailable(CF_DIB)&&!FindWindowW(L"KSwitcher.HistoryHost",nullptr);},"image clipboard restored after paste");
|
||||
require(ks::decodeImage(ks::readClipboard(target,64*1024*1024)).width==pixels.width,"image clipboard survives history paste");
|
||||
auto afterPaste=memory(process.hProcess);
|
||||
std::cout<<"MEMORY after_paste_with_image_backup="<<afterPaste<<'\n';
|
||||
require(afterPaste<base+2*1024*1024,"image clipboard backup stays outside resident");
|
||||
ks::writeClipboard(target,excluded(ks::textClip(L"keep clipboard")));
|
||||
w=open();send(GetDlgItem(w,101),WM_SETTEXT,0,LPARAM(L"Image"));
|
||||
until([&]{return send(GetDlgItem(w,102),LB_GETCOUNT)==1;},"image search");
|
||||
pastedImage=false;send(w,WM_COMMAND,110);
|
||||
until([&]{return pastedImage;},"image paste reaches destination");
|
||||
until([&]{return ks::readClipboard(target).text()==L"keep clipboard";},"clipboard restored after image paste");
|
||||
std::cout<<"MEMORY after_image_paste="<<memory(process.hProcess)<<'\n';
|
||||
require(memory(process.hProcess)<base+2*1024*1024,"image paste does not retain full bitmap in resident");
|
||||
until([&]{return !FindWindowW(L"KSwitcher.HistoryHost",nullptr);},"image paste helper exits");
|
||||
w=open();send(w,WM_COMMAND,113);
|
||||
until([&]{history.reload();return history.entries().size()==499;},"resident removes selected image");
|
||||
GetWindowThreadProcessId(w,&childPid);child=OpenProcess(SYNCHRONIZE,FALSE,childPid);
|
||||
// Startup update checks temporarily reject exit; retry after that
|
||||
// operation finishes instead of treating its guard as a host leak.
|
||||
ULONGLONG nextExit{};
|
||||
until([&]{
|
||||
if(WaitForSingleObject(process.hProcess,0)==WAIT_OBJECT_0) return true;
|
||||
if(GetTickCount64()>=nextExit) {
|
||||
command(resident,99);nextExit=GetTickCount64()+500;
|
||||
}
|
||||
return false;
|
||||
},"resident accepts exit after startup update check",30000);
|
||||
until([&]{return WaitForSingleObject(child,0)==WAIT_OBJECT_0;},"resident shutdown closes history helper");
|
||||
CloseHandle(child);resident=nullptr;
|
||||
std::cout<<"PASS isolated history host suite\n";
|
||||
} catch(const std::exception &e){std::cerr<<"FAIL "<<e.what()<<" editor="<<ks::utf8(editorText())<<" foreground="<<(GetForegroundWindow()==target)<<'\n';result=1;}
|
||||
if(resident)try{command(resident,99);}catch(...){}
|
||||
if(process.hProcess){if(WaitForSingleObject(process.hProcess,10000)!=WAIT_OBJECT_0){TerminateProcess(process.hProcess,1);WaitForSingleObject(process.hProcess,INFINITE);}CloseHandle(process.hProcess);}
|
||||
if(captured)try{ks::writeClipboard(target,saved);}catch(...){result=1;}
|
||||
if(target) DestroyWindow(target);
|
||||
CoUninitialize();
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// Interactive clipboard test. Run with the resident stopped; the original
|
||||
// clipboard is restored. The helper must be beside this test executable.
|
||||
#include "storage.h"
|
||||
#include "ocr.h"
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
static void require(bool ok,const char *name) {
|
||||
if(!ok) throw std::runtime_error(name);
|
||||
std::cout << "PASS " << name << '\n';
|
||||
}
|
||||
int main() {
|
||||
CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
HWND owner=CreateWindowExW(0,L"STATIC",L"Capture test",0,0,0,0,0,HWND_MESSAGE,nullptr,nullptr,nullptr);
|
||||
ks::Clip saved; bool captured=false; int result=0;
|
||||
auto folder=std::filesystem::temp_directory_path()/(L"KSwitcher-image-capture-"+std::to_wstring(GetCurrentProcessId()));
|
||||
try {
|
||||
saved=ks::readClipboard(owner,128*1024*1024); captured=true;
|
||||
ks::Settings settings; settings.history=true;
|
||||
ks::History history(folder);
|
||||
history.add(ks::textClip(L"keep pinned"),L"test",settings);
|
||||
auto pinned=history.entries().front().id; history.pin(pinned);
|
||||
ks::Pixels pixels{32,16,ks::Bytes(32*16*4,255)};
|
||||
ks::Clip image{{ks::imageDib(pixels),{0,L"PNG",ks::encodePng(pixels)}}};
|
||||
auto sequence=ks::writeClipboard(owner,image);
|
||||
require(history.captureImage(sequence,L"capture test",settings),"helper captures image");
|
||||
auto entries=history.entries();
|
||||
require(entries.size()==2 && entries.front().image && entries.front().ocrState==1,"resident reloads metadata with pending OCR");
|
||||
require(entries.front().contentHash.size()==64 && !entries.front().pixelHash.empty(),
|
||||
"helper persists fingerprints and resident reloads them");
|
||||
require(entries.back().id==pinned && entries.back().pinned,"helper preserves existing pinned entry");
|
||||
auto restored=history.load(entries.front().id);
|
||||
auto thumbnail=history.thumbnail(entries.front().id);
|
||||
require(thumbnail.width==pixels.width && thumbnail.height==pixels.height && thumbnail.bgra==pixels.bgra,
|
||||
"helper thumbnail preserves small image pixels");
|
||||
bool thumbnailCancelled=false;
|
||||
try {history.thumbnail(entries.front().id,[]{return true;});} catch(...) {thumbnailCancelled=true;}
|
||||
require(thumbnailCancelled,"closed history cancels thumbnail work");
|
||||
auto has=[&](const ks::Format &expected) {
|
||||
return std::any_of(restored.formats.begin(),restored.formats.end(),[&](const ks::Format &actual) {
|
||||
return (expected.name.empty()?actual.id==expected.id:actual.name==expected.name) && actual.data==expected.data;
|
||||
});
|
||||
};
|
||||
require(has(image.formats[0]) && has(image.formats[1]),
|
||||
"encrypted history preserves both image representations");
|
||||
require(ks::readFile(folder/(entries.front().id+L".dat"),1024*1024)!=ks::encodeClip(restored),"saved image is encrypted");
|
||||
require(GetClipboardSequenceNumber()==sequence,"capture leaves clipboard unchanged");
|
||||
require(history.captureImage(sequence,L"capture test",settings) && history.entries().size()==2,"duplicate capture is not added");
|
||||
ks::writeClipboard(owner,ks::textClip(L"new clipboard"));
|
||||
require(!history.captureImage(sequence,L"stale",settings) && history.entries().size()==2,"stale request does not save another clipboard");
|
||||
for(auto name : {L"ExcludeClipboardContentFromMonitorProcessing",L"Clipboard Viewer Ignore",L"CanIncludeInClipboardHistory"}) {
|
||||
auto blocked=image; blocked.formats.push_back({0,name,ks::Bytes(4,0)});
|
||||
sequence=ks::writeClipboard(owner,blocked);
|
||||
require(!history.captureImage(sequence,L"excluded",settings) && history.entries().size()==2,"clipboard privacy flag prevents capture");
|
||||
}
|
||||
pixels={1024,512,ks::Bytes(1024*512*4,255)};
|
||||
sequence=ks::writeClipboard(owner,ks::Clip{{ks::imageDib(pixels)}});
|
||||
settings.maxImageMiB=1;
|
||||
bool rejected=false;
|
||||
try {history.captureImage(sequence,L"oversized",settings);} catch(const std::exception &e) {
|
||||
rejected=std::string(e.what())=="Clipboard exceeds the configured size limit";
|
||||
}
|
||||
require(rejected && history.entries().size()==2,"oversized image is rejected without changing index");
|
||||
require(GetClipboardSequenceNumber()==sequence,"rejection leaves clipboard unchanged");
|
||||
settings.maxImageMiB=20;
|
||||
history.add(ks::Clip{{ks::imageDib(pixels)}},L"thumbnail fixture",settings);
|
||||
auto largeId=history.entries().front().id;
|
||||
thumbnail=history.thumbnail(largeId);
|
||||
require(thumbnail.width==208 && thumbnail.height==104 && thumbnail.bgra.size()==208*104*4,
|
||||
"large image returns only bounded thumbnail pixels");
|
||||
history.remove(largeId);
|
||||
bool missingRejected=false;
|
||||
try {history.thumbnail(largeId);} catch(...) {missingRejected=true;}
|
||||
require(missingRejected,"deleted image cannot be previewed or recreated");
|
||||
for(const auto &file:std::filesystem::directory_iterator(folder))
|
||||
require(file.path().extension()!=L".request","encrypted capture request is cleaned up");
|
||||
} catch(const std::exception &e) {std::cerr << "FAIL " << e.what() << '\n';result=1;}
|
||||
if(captured) try {ks::writeClipboard(owner,saved);} catch(...) {result=1;}
|
||||
DestroyWindow(owner); CoUninitialize();
|
||||
// Remove only the exact PID-specific fixture under the system temp directory.
|
||||
std::error_code ignored;
|
||||
if(std::filesystem::weakly_canonical(folder).parent_path()==std::filesystem::weakly_canonical(std::filesystem::temp_directory_path()))
|
||||
std::filesystem::remove_all(folder,ignored);
|
||||
return result;
|
||||
}
|
||||
+221
-3
@@ -2,9 +2,23 @@
|
||||
#include "ui_scroll.h"
|
||||
#include "ui_geometry.h"
|
||||
#include "screenshot.h"
|
||||
#include "ocr.h"
|
||||
#include <commctrl.h>
|
||||
#include <iostream>
|
||||
#include <cmath>
|
||||
static int settingsCloseChoice = IDCANCEL;
|
||||
static int settingsClosePrompts = 0;
|
||||
static void CALLBACK answerSettingsClose(HWND, UINT, UINT_PTR, DWORD)
|
||||
{
|
||||
HWND dialog = FindWindowW(L"#32770", L"KSwitcher — Unsaved settings");
|
||||
DWORD process{};
|
||||
if (dialog && GetWindowThreadProcessId(dialog, &process) == GetCurrentThreadId() &&
|
||||
process == GetCurrentProcessId())
|
||||
{
|
||||
++settingsClosePrompts;
|
||||
SendMessageW(dialog, WM_COMMAND, settingsCloseChoice, 0);
|
||||
}
|
||||
}
|
||||
LRESULT CALLBACK countControlMoves(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR data)
|
||||
{
|
||||
if (message == WM_WINDOWPOSCHANGING) ++*reinterpret_cast<int *>(data);
|
||||
@@ -12,6 +26,49 @@ LRESULT CALLBACK countControlMoves(HWND w, UINT message, WPARAM wp, LPARAM lp, U
|
||||
}
|
||||
namespace ks {
|
||||
struct InputRegressionAccess {
|
||||
static int snippetChoice(App &a, const std::vector<Snippet> &snippets) {
|
||||
a.settings.snippets=snippets; a.settings.autoCorrect=false; a.busy=false;
|
||||
a.snippetPending=-1; a.typingTarget=nullptr; a.snippetTyping=false;
|
||||
auto target=GetForegroundWindow();
|
||||
a.run.keys=L";si"; a.run.window=target; a.run.layout=windowLayout(target); a.run.at=GetTickCount64();
|
||||
KBDLLHOOKSTRUCT key{};key.vkCode='G';key.scanCode=0x22;
|
||||
a.keyboard(key,0);
|
||||
int chosen=a.snippetPending;
|
||||
a.busy=false;a.snippetPending=-1;a.typingTarget=nullptr;a.snippetTyping=false;
|
||||
return chosen;
|
||||
}
|
||||
static bool idleUndo(App &a) {
|
||||
a.last=LastTransform{}; a.last->at=100;
|
||||
a.releaseIdleMemory(120100);
|
||||
if (!a.last) return false;
|
||||
a.busy=true;
|
||||
a.releaseIdleMemory(120101);
|
||||
if (!a.last) { a.busy=false; return false; }
|
||||
a.busy=false;
|
||||
a.releaseIdleMemory(120101);
|
||||
return !a.last;
|
||||
}
|
||||
static bool releasedSync(const App &a) {
|
||||
return a.syncSnapshot.capacity()==0 && a.syncResult.settings.capacity()==0 &&
|
||||
a.syncResult.base.capacity()==0 && a.syncResult.conflicts.capacity()==0;
|
||||
}
|
||||
static bool completedSync(App &a, int mode) {
|
||||
sampleConflicts(a);
|
||||
auto conflicts=encodeSyncConflicts(a.pendingSyncConflicts);
|
||||
a.syncConnection=loadSyncConfig(a.data);
|
||||
a.syncSnapshot=encodeSettings(a.settings);
|
||||
a.syncResult={mode!=1,sharedSyncSettings(a.settings),2,L"test"};
|
||||
a.syncResult.base=a.syncResult.settings;
|
||||
a.syncResult.conflicts=a.pendingSyncConflicts;
|
||||
if(mode==2) a.syncResult.settings={1,2,3}; // Decode exception after joining.
|
||||
a.syncWorker=std::thread([]{});
|
||||
a.syncRunning=true; a.syncDone=true; a.busy=true;
|
||||
a.pollSync();
|
||||
bool retained=!a.syncSnapshot.empty() && a.syncRunning;
|
||||
a.busy=false; a.pollSync();
|
||||
return retained && releasedSync(a) && !a.syncRunning &&
|
||||
encodeSyncConflicts(a.pendingSyncConflicts)==conflicts;
|
||||
}
|
||||
static inline bool delivery = true;
|
||||
static inline int notifications = 0;
|
||||
static bool notify(const std::wstring &) { ++notifications; return delivery; }
|
||||
@@ -31,6 +88,7 @@ struct InputRegressionAccess {
|
||||
a.syncRunning=true; a.syncDone=true;
|
||||
a.pollSync();
|
||||
return encodeSettings(a.settings)==before && !a.syncRunning &&
|
||||
releasedSync(a) &&
|
||||
!std::filesystem::exists(a.data/L"sync-base.bin");
|
||||
}
|
||||
static bool syncBackoff(App &a) {
|
||||
@@ -48,6 +106,9 @@ struct InputRegressionAccess {
|
||||
}
|
||||
static void notificationSetup(App &a) { a.updateNotifier = notify; }
|
||||
static void setup(App &a) { a.hookBindings = {{Toggle,{MOD_CONTROL,VK_F12}}, {Case,{MOD_CONTROL|MOD_SHIFT,'U'}}}; }
|
||||
static LRESULT routedKey(int code, UINT message, const KBDLLHOOKSTRUCT &key, LRESULT routed) {
|
||||
return App::keyboardAfterHooks(code,message,(LPARAM)&key,routed);
|
||||
}
|
||||
static bool updateTimer(App &a) {
|
||||
a.updateRunning=true; // Exercise timer scheduling without launching a network request.
|
||||
App::windowProc(a.window,WM_TIMER,5,0);
|
||||
@@ -74,12 +135,44 @@ int main(int argc, char **argv) {
|
||||
return result.state == L"current" || result.state == L"available" ? 0 : 1;
|
||||
} catch (const std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
|
||||
}
|
||||
auto temp=std::filesystem::temp_directory_path()/(L"KSwitcher-input-tests-"+std::to_wstring(GetCurrentProcessId()));
|
||||
auto temp=std::filesystem::temp_directory_path()/(L"KSwitcher-input-tests-"+ks::newSnippetId());
|
||||
int checks=0;
|
||||
auto require=[&](bool ok,const char* text) { if(!ok) throw std::runtime_error(text); ++checks; };
|
||||
try {
|
||||
INITCOMMONCONTROLSEX controls{sizeof(controls),ICC_STANDARD_CLASSES|ICC_LISTVIEW_CLASSES};
|
||||
InitCommonControlsEx(&controls);
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr),true,temp/L"snippet-scopes");
|
||||
app.window=CreateWindowExW(0,L"STATIC",L"Snippet scope test",0,0,0,0,0,HWND_MESSAGE,nullptr,GetModuleHandleW(nullptr),nullptr);
|
||||
auto process=ks::processName(GetForegroundWindow());
|
||||
require(!process.empty(),"scope test has foreground process");
|
||||
std::vector<ks::Snippet> snippets{{L";sig",L"global",L"global"},{L";sig",L"scoped",L"scoped",{process}}};
|
||||
require(ks::InputRegressionAccess::snippetChoice(app,snippets)==1,"app-specific trigger wins even when global is first");
|
||||
snippets[1].apps={L"kswitcher-no-such-process"};
|
||||
require(ks::InputRegressionAccess::snippetChoice(app,snippets)==0,"unmatched app falls back to global snippet");
|
||||
snippets.erase(snippets.begin());
|
||||
require(ks::InputRegressionAccess::snippetChoice(app,snippets)==-1,"scoped snippet is not queued in another application");
|
||||
DestroyWindow(app.window);app.window=nullptr;
|
||||
}
|
||||
{
|
||||
HMENU menu = CreatePopupMenu(), child = CreatePopupMenu();
|
||||
AppendMenuW(menu,MF_STRING | MF_CHECKED,1,L"&Settings…");
|
||||
AppendMenuW(menu,MF_STRING,2,L"Copy\tCtrl+C");
|
||||
AppendMenuW(child,MF_STRING,3,L"Rock && &Roll");
|
||||
AppendMenuW(menu,MF_POPUP,(UINT_PTR)child,L"&Pause");
|
||||
ks::showMenuAccessKeys(menu);
|
||||
ks::showMenuAccessKeys(menu);
|
||||
wchar_t label[128]{};
|
||||
GetMenuStringW(menu,1,label,128,MF_BYCOMMAND);
|
||||
require(std::wstring(label)==L"&Settings…\tS" &&
|
||||
(GetMenuState(menu,1,MF_BYCOMMAND)&MF_CHECKED),
|
||||
"visible menu mnemonic is idempotent and preserves item state");
|
||||
GetMenuStringW(menu,2,label,128,MF_BYCOMMAND);
|
||||
require(std::wstring(label)==L"Copy\tCtrl+C","existing menu shortcut hints are retained");
|
||||
GetMenuStringW(child,3,label,128,MF_BYCOMMAND);
|
||||
require(std::wstring(label)==L"Rock && &Roll\tR","submenu hints skip escaped ampersands");
|
||||
DestroyMenu(menu);
|
||||
}
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr),true,temp);
|
||||
ks::InputRegressionAccess::setup(app);
|
||||
@@ -583,6 +676,35 @@ int main(int argc, char **argv) {
|
||||
};
|
||||
auto commands=[&] { MSG m{}; int n=0; while(PeekMessageW(&m,app.window,WM_HOTKEY,WM_HOTKEY,PM_REMOVE)) ++n; return n; };
|
||||
auto f12=event(VK_F12);
|
||||
{
|
||||
auto localF12=f12;localF12.flags=0;localF12.dwExtraInfo=0;
|
||||
app.handleKeyboard(localF12,true,MOD_CONTROL);commands();
|
||||
app.resetLanInput();
|
||||
require(app.handleKeyboard(localF12,true,MOD_CONTROL)&&commands()==1,
|
||||
"local shortcut works after LAN handoff even when release happened on another PC");
|
||||
app.handleKeyboard(localF12,false,0);
|
||||
auto letter=event('A',30);letter.flags=0;letter.dwExtraInfo=0;
|
||||
app.resetLanInput();app.handleKeyboard(letter,true,0);
|
||||
require(!app.run.keys.empty(),"local typing tracking resumes after LAN ownership reset");
|
||||
app.run.reset();
|
||||
}
|
||||
|
||||
{
|
||||
const auto before = app.inputVersion.load();
|
||||
const auto recorded = app.run.keys;
|
||||
for (UINT message : {WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, WM_SYSKEYUP})
|
||||
require(ks::InputRegressionAccess::routedKey(HC_ACTION,message,event('A',30),7)==7,
|
||||
"forwarded keyboard events preserve downstream suppression");
|
||||
require(app.inputVersion==before && app.run.keys==recorded && commands()==0,
|
||||
"forwarded events never track text, invalidate transactions or dispatch shortcuts");
|
||||
require(ks::InputRegressionAccess::routedKey(-1,WM_KEYDOWN,event('A',30),0)==0 &&
|
||||
app.inputVersion==before,"negative hook codes do not process keyboard input");
|
||||
require(ks::InputRegressionAccess::routedKey(HC_ACTION,WM_KEYDOWN,event('A',30,true),0)==0 &&
|
||||
app.inputVersion==before,"own input remains excluded after downstream routing");
|
||||
require(ks::InputRegressionAccess::routedKey(HC_ACTION,WM_KEYDOWN,event('A',30),0)==0 &&
|
||||
app.inputVersion>before,"delivered remote input is still processed on the receiver");
|
||||
app.run.reset();
|
||||
}
|
||||
require(!app.handleKeyboard(event(VK_LCONTROL),true,0),"remote modifier passes through");
|
||||
require(app.handleKeyboard(f12,true,MOD_CONTROL),"remote Ctrl+F12 handled");
|
||||
require(app.handleKeyboard(f12,true,MOD_CONTROL),"remote repeat suppressed");
|
||||
@@ -629,6 +751,49 @@ int main(int argc, char **argv) {
|
||||
fitted=ks::fitWindowRect({2000,2000,2600,2400},{-1920,0,0,1080});
|
||||
require(fitted.left==-600&&fitted.top==680&&fitted.right==0,"negative-coordinate monitor supported");
|
||||
ks::showSettings(app,false);
|
||||
{
|
||||
auto timer = SetTimer(nullptr, 0, 10, answerSettingsClose);
|
||||
require(timer != 0, "settings close prompt responder");
|
||||
SendMessageW(app.settingsWindow, WM_CLOSE, 0, 0);
|
||||
require(!app.settingsWindow && settingsClosePrompts == 0,
|
||||
"unchanged settings close without prompting");
|
||||
ks::showSettings(app,false);
|
||||
auto settingsWindow = app.settingsWindow;
|
||||
auto initial = SendDlgItemMessageW(settingsWindow,205,BM_GETCHECK,0,0);
|
||||
SendDlgItemMessageW(settingsWindow,205,BM_SETCHECK,!initial,0);
|
||||
SendMessageW(settingsWindow, WM_CLOSE, 0, 0);
|
||||
require(IsWindow(settingsWindow) && settingsClosePrompts == 1,
|
||||
"cancel close preserves changed settings");
|
||||
SendDlgItemMessageW(settingsWindow,205,BM_SETCHECK,initial,0);
|
||||
SendMessageW(settingsWindow, WM_CLOSE, 0, 0);
|
||||
require(!app.settingsWindow && settingsClosePrompts == 1,
|
||||
"reverted settings close without prompting");
|
||||
ks::showSettings(app,false);
|
||||
SetDlgItemTextW(app.settingsWindow,240,L"invalid");
|
||||
settingsCloseChoice = IDNO;
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
require(!app.settingsWindow && settingsClosePrompts == 2,
|
||||
"Cancel button allows discarding invalid edits");
|
||||
auto originalSettings = app.settings;
|
||||
// The isolated harness has no keyboard hook; save without shortcuts.
|
||||
app.settings.toggle = app.settings.casing = app.settings.translit =
|
||||
app.settings.undo = app.settings.clipboard = app.settings.screenshot = L"";
|
||||
app.settings.direct.assign(app.layouts.size(), L"");
|
||||
ks::showSettings(app,false);
|
||||
SendDlgItemMessageW(app.settingsWindow,208,BM_SETCHECK,
|
||||
originalSettings.writeLog ? BST_UNCHECKED : BST_CHECKED,0);
|
||||
settingsCloseChoice = IDYES;
|
||||
SendMessageW(app.settingsWindow,WM_CLOSE,0,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");
|
||||
app.settings = originalSettings;
|
||||
ks::setLoggingEnabled(originalSettings.writeLog);
|
||||
KillTimer(nullptr,timer);
|
||||
settingsCloseChoice = IDCANCEL;
|
||||
ks::showSettings(app,false);
|
||||
}
|
||||
require(GetDlgItem(app.settingsWindow,258)!=nullptr,"sync available without local opt-in");
|
||||
// Mnemonics only target visible controls; show without taking foreground focus.
|
||||
ShowWindow(app.settingsWindow,SW_SHOWNOACTIVATE);
|
||||
@@ -716,6 +881,10 @@ int main(int argc, char **argv) {
|
||||
require(IsWindowEnabled(app.settingsWindow),"closing sync restores parent");
|
||||
require(ks::InputRegressionAccess::staleSync(app,false),"in-flight sync cannot overwrite newer local edits");
|
||||
require(ks::InputRegressionAccess::staleSync(app,true),"disconnect discards in-flight downloaded profile");
|
||||
require(ks::InputRegressionAccess::idleUndo(app),"idle cleanup retains available/busy Undo and frees expired Undo");
|
||||
for(int mode=0;mode<3;++mode)
|
||||
require(ks::InputRegressionAccess::completedSync(app,mode),
|
||||
"completed, failed and invalid sync release buffers but preserve conflict choices");
|
||||
require(ks::InputRegressionAccess::syncBackoff(app),"saving settings preserves authentication error backoff");
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,255,0);
|
||||
auto autoOptions=FindWindowW(L"KSwitcher.AutoOptions",nullptr);
|
||||
@@ -769,11 +938,19 @@ int main(int argc, char **argv) {
|
||||
"personal dictionary field fits options window");
|
||||
}
|
||||
SetDlgItemTextW(autoOptions,412,L"Релізик\r\nрелізик, словечко");
|
||||
SetDlgItemTextW(autoOptions,416,L" Првиіт = Привіт\r\nhelo=hello");
|
||||
SetDlgItemTextW(autoOptions,416,L" Првиіт = Привіт\r\nhelo=hello\r\n Мамамила = Мама мила ");
|
||||
SendDlgItemMessageW(autoOptions,414,BM_SETCHECK,BST_CHECKED,0);
|
||||
SendDlgItemMessageW(autoOptions,415,BM_SETCHECK,BST_CHECKED,0);
|
||||
SendMessageW(autoOptions,WM_COMMAND,IDOK,0);
|
||||
require(!IsWindow(autoOptions),"personal words accepted without file editing");
|
||||
{
|
||||
auto timer = SetTimer(nullptr,0,10,answerSettingsClose);
|
||||
auto before = settingsClosePrompts;
|
||||
SendMessageW(app.settingsWindow,WM_CLOSE,0,0);
|
||||
KillTimer(nullptr,timer);
|
||||
require(app.settingsWindow && settingsClosePrompts == before + 1,
|
||||
"accepted personal dictionary edits trigger unsaved settings warning");
|
||||
}
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,255,0);
|
||||
autoOptions=FindWindowW(L"KSwitcher.AutoOptions",nullptr);
|
||||
ShowWindow(autoOptions,SW_HIDE);
|
||||
@@ -783,7 +960,7 @@ int main(int argc, char **argv) {
|
||||
"personal dictionary normalizes case, newlines and duplicate words");
|
||||
wchar_t pairs[128]{};
|
||||
GetDlgItemTextW(autoOptions,416,pairs,128);
|
||||
require(std::wstring(pairs)==L"helo=hello\r\nпрвиіт=привіт\r\n" &&
|
||||
require(std::wstring(pairs)==L"helo=hello\r\nмамамила=мама мила\r\nпрвиіт=привіт\r\n" &&
|
||||
SendDlgItemMessageW(autoOptions,414,BM_GETCHECK,0,0)==BST_CHECKED &&
|
||||
SendDlgItemMessageW(autoOptions,415,BM_GETCHECK,0,0)==BST_CHECKED,
|
||||
"typo options and normalized replacement pairs survive reopening");
|
||||
@@ -792,6 +969,7 @@ int main(int argc, char **argv) {
|
||||
ks::showHistory(app,false);
|
||||
auto history=app.historyWindow;
|
||||
require(history&&!IsWindowVisible(history),"history layout tested without changing focus");
|
||||
require(!GetDlgItem(history,105),"history creates no RichEdit control before formatted content is displayed");
|
||||
{
|
||||
app.history=std::make_unique<ks::History>(temp/L"history-search");
|
||||
app.history->add(ks::textClip(L"згенеруй приклад"),L"test",app.settings);
|
||||
@@ -819,6 +997,43 @@ int main(int argc, char **argv) {
|
||||
SetDlgItemTextW(history,101,L"");
|
||||
require(pumpUntil(2),"clearing search restores history");
|
||||
require(GetFocus()==originalFocus,"history search preserves focus");
|
||||
SendDlgItemMessageW(history,102,LB_SETCURSEL,1,0);
|
||||
ks::refreshHistory(app); // A result may still be in flight when closing.
|
||||
SendDlgItemMessageW(history,101,WM_KEYDOWN,VK_ESCAPE,0);
|
||||
require(!IsWindowVisible(history) && !GetDlgItem(history,105),
|
||||
"Escape closes history and leaves no RichEdit control");
|
||||
SendMessageW(history,WM_TIMER,1,0); // KillTimer cannot retract a posted timer message.
|
||||
require(pumpUntil(0),"closing history releases list strings");
|
||||
auto until=GetTickCount64()+250;
|
||||
while(GetTickCount64()<until) {
|
||||
MSG message{};
|
||||
while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE)) {
|
||||
TranslateMessage(&message); DispatchMessageW(&message);
|
||||
}
|
||||
Sleep(5);
|
||||
}
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCOUNT,0,0)==0,
|
||||
"late search results do not refill closed history");
|
||||
ks::refreshHistory(app);
|
||||
require(pumpUntil(2),"history reloads after releasing hidden rows");
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==1,
|
||||
"history retains selected record across close and reload");
|
||||
SendMessageW(history,WM_CLOSE,0,0);
|
||||
ks::Pixels screenshot{2,2,ks::Bytes(16,255)};
|
||||
app.history->add(ks::Clip{{ks::imageDib(screenshot)}},L"screenshot",app.settings);
|
||||
require(app.history->entries().front().image,"new screenshot is the newest history entry");
|
||||
ks::showHistory(app);
|
||||
require(pumpUntil(3),"reopening history loads the new screenshot");
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==0 &&
|
||||
SendDlgItemMessageW(history,102,LB_GETTOPINDEX,0,0)==0,
|
||||
"fresh history invocation selects and reveals newest screenshot instead of saved selection");
|
||||
SendDlgItemMessageW(history,102,LB_SETCURSEL,2,0);
|
||||
app.history->add(ks::textClip(L"background clipboard update"),L"test",app.settings);
|
||||
ks::refreshHistory(app);
|
||||
require(pumpUntil(4),"background refresh loads a new item");
|
||||
require(SendDlgItemMessageW(history,102,LB_GETCURSEL,0,0)==3,
|
||||
"background refresh preserves the selected record while browsing");
|
||||
ShowWindow(history,SW_HIDE);
|
||||
}
|
||||
auto childRect=[&](int id) { RECT r{}; GetWindowRect(GetDlgItem(history,id),&r); MapWindowPoints(nullptr,history,(POINT*)&r,2); return r; };
|
||||
RECT historyFrame{}; GetWindowRect(history,&historyFrame);
|
||||
@@ -843,6 +1058,9 @@ int main(int argc, char **argv) {
|
||||
require(SendDlgItemMessageW(settings,209,BM_GETCHECK,0,0)==BST_UNCHECKED,"automatic screenshot editor checkbox defaults off");
|
||||
require(settings&&!IsWindowVisible(settings),"settings layout tested without changing user focus");
|
||||
for(auto pair:{std::pair{209,215},std::pair{209,207},std::pair{209,220},std::pair{209,232},std::pair{207,215},std::pair{207,232},std::pair{207,220},std::pair{232,230},std::pair{230,231},std::pair{231,253}}) {
|
||||
// Controls on different settings tabs intentionally share the page area.
|
||||
if (!(GetWindowLongPtrW(GetDlgItem(settings,pair.first),GWL_STYLE)&WS_VISIBLE) ||
|
||||
!(GetWindowLongPtrW(GetDlgItem(settings,pair.second),GWL_STYLE)&WS_VISIBLE)) continue;
|
||||
RECT first{},second{},overlap{};
|
||||
GetWindowRect(GetDlgItem(settings,pair.first),&first); GetWindowRect(GetDlgItem(settings,pair.second),&second);
|
||||
require(!IntersectRect(&overlap,&first,&second),"capture hotkey and layout controls do not overlap");
|
||||
|
||||
+213
-8
@@ -9,6 +9,7 @@ namespace ks
|
||||
{
|
||||
struct InputRegressionAccess
|
||||
{
|
||||
static bool hasLast(App &app) { return app.last.has_value(); }
|
||||
static bool deferring(App &app)
|
||||
{
|
||||
std::lock_guard lock(app.stateMutex);
|
||||
@@ -21,6 +22,7 @@ namespace
|
||||
ks::App *app{};
|
||||
HWND host{}, field{};
|
||||
ks::Clip saved;
|
||||
bool snippetRecoveryOnly = false;
|
||||
bool captured = false, failed = false;
|
||||
bool conversionOnly = false;
|
||||
bool typosOnly = false;
|
||||
@@ -28,8 +30,21 @@ int pasteBehavior = 0;
|
||||
int enterPresses = 0;
|
||||
int copyFailuresRemaining = 0, copyRequests = 0;
|
||||
int droppedSelectionKeys = 0;
|
||||
bool trimCopiedSpaces = false;
|
||||
int trimmedCopies = 0;
|
||||
bool temporaryClipboardExcluded = true;
|
||||
bool clipboardAccessTimedOut = false;
|
||||
uint64_t forwardedVersion{};
|
||||
int forwardedEvents{};
|
||||
LRESULT CALLBACK forwardingHook(int code, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if (code == HC_ACTION && reinterpret_cast<KBDLLHOOKSTRUCT *>(lp)->dwExtraInfo == 456)
|
||||
{
|
||||
++forwardedEvents;
|
||||
return 1; // Model MWB consuming source input routed to another machine.
|
||||
}
|
||||
return CallNextHookEx(nullptr, code, wp, lp);
|
||||
}
|
||||
LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||||
{
|
||||
if (message == WM_KEYDOWN && wp == VK_LEFT && droppedSelectionKeys > 0 &&
|
||||
@@ -76,10 +91,42 @@ LRESULT CALLBACK observeEnter(HWND w, UINT message, WPARAM wp, LPARAM lp, UINT_P
|
||||
--copyFailuresRemaining;
|
||||
return 0;
|
||||
}
|
||||
if (trimCopiedSpaces)
|
||||
{
|
||||
auto result = DefSubclassProc(w, message, wp, lp);
|
||||
// Native EDIT closes the clipboard in its copy handler, including
|
||||
// our outer opening. Reopen it before changing its published data.
|
||||
if (!OpenClipboard(w))
|
||||
{
|
||||
clipboardAccessTimedOut = true;
|
||||
return result;
|
||||
}
|
||||
auto handle = GetClipboardData(CF_UNICODETEXT);
|
||||
auto data = handle ? static_cast<const wchar_t *>(GlobalLock(handle)) : nullptr;
|
||||
if (data)
|
||||
{
|
||||
std::wstring copied(data);
|
||||
GlobalUnlock(handle);
|
||||
const auto originalSize = copied.size();
|
||||
while (!copied.empty() && copied.back() == L' ') copied.pop_back();
|
||||
auto replacement = GlobalAlloc(GMEM_MOVEABLE, (copied.size() + 1) * sizeof(wchar_t));
|
||||
auto output = GlobalLock(replacement);
|
||||
memcpy(output, copied.c_str(), (copied.size() + 1) * sizeof(wchar_t));
|
||||
GlobalUnlock(replacement);
|
||||
if (!EmptyClipboard() || !SetClipboardData(CF_UNICODETEXT, replacement))
|
||||
{
|
||||
GlobalFree(replacement);
|
||||
clipboardAccessTimedOut = true;
|
||||
}
|
||||
else if (copied.size() != originalSize) ++trimmedCopies;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (message == WM_PASTE && pasteBehavior)
|
||||
{
|
||||
if (pasteBehavior == 3) { pasteBehavior = 0; return 0; }
|
||||
if (pasteBehavior == 2) SendMessageW(w, EM_REPLACESEL, TRUE, (LPARAM)L"other!");
|
||||
return 0;
|
||||
}
|
||||
@@ -274,6 +321,8 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
app->settings.autoCorrect = true;
|
||||
app->settings.switchLayout = true;
|
||||
app->settings.autoLanguages = {L"en", L"ru"};
|
||||
// Direct fixture mutations bypass applySettings' dictionary preload.
|
||||
app->autoPredictor.configure(L"dictionaries", app->settings.autoLanguages);
|
||||
app->settings.cycle = {app->layouts[en].id, app->layouts[ru].id};
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
prepare(L"ghbdtn ", false);
|
||||
@@ -371,6 +420,7 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
require(text() == L"ghbdtn" && rows.back().outcome == L"Original text remained",
|
||||
"blocked paste records original text remaining in the actual editor");
|
||||
require(ks::readClipboard(app->window).text() == sentinel, "readback preserves clipboard after blocked paste");
|
||||
require(!ks::InputRegressionAccess::hasLast(*app), "failed paste does not retain a fictional previous result");
|
||||
pasteBehavior = 2;
|
||||
prepare(L"ghbdtn", true);
|
||||
app->transform(ks::Direct + ru);
|
||||
@@ -381,6 +431,7 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
auto rows = ks::parseOperationLog(ks::wide(diagnosticLog()));
|
||||
require(text() == L"other!" && rows.back().outcome == L"Readback differs",
|
||||
"unexpected editor content records readback mismatch");
|
||||
require(!ks::InputRegressionAccess::hasLast(*app), "changed readback cannot seed repeat conversion");
|
||||
pasteBehavior = 0;
|
||||
prepare(L"привет", true);
|
||||
app->transform(ks::Direct + ru);
|
||||
@@ -449,13 +500,149 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
details.find(L"Selection initial match=0") != details.npos &&
|
||||
details.find(L"SelectPrevious") != details.npos,
|
||||
"incident includes clipboard and selection stages");
|
||||
finish();
|
||||
pasteBehavior = 3;
|
||||
prepare(L"=nhtdjuf", true);
|
||||
app->transform(ks::Direct + ru);
|
||||
stage = 49;
|
||||
break;
|
||||
}
|
||||
case 49:
|
||||
{
|
||||
require(text() == L"=тревога" && pasteBehavior == 0,
|
||||
"native Edit retries one ignored paste only while original remains selected");
|
||||
require(ks::readClipboard(app->window).text() == sentinel, "native paste retry restores clipboard");
|
||||
trimCopiedSpaces = true;
|
||||
app->settings.writeLog = false;
|
||||
prepare(L"OLDghbdtn NEXT", false);
|
||||
SendMessageW(field, EM_SETSEL, 11, 11);
|
||||
record(L"ghbdtn ");
|
||||
app->transform(ks::Direct + ru);
|
||||
break;
|
||||
}
|
||||
case 50:
|
||||
require(text() == L"OLDпривет NEXT", "trimmed clipboard recovery preserves two spaces and surrounding text without logging");
|
||||
app->transform(ks::Direct + en);
|
||||
break;
|
||||
case 51:
|
||||
require(text() == L"OLDghbdtn NEXT", "repeat conversion preserves accessibility-proven spaces");
|
||||
app->transform(ks::Undo);
|
||||
break;
|
||||
case 52:
|
||||
require(text() == L"OLDпривет NEXT", "undo preserves accessibility-proven spaces");
|
||||
prepare(L"ghbdtn", false);
|
||||
record(L"ghbdtn ");
|
||||
app->transform(ks::Direct + ru);
|
||||
break;
|
||||
case 53:
|
||||
require(text() == L"ghbdtn", "missing real space cannot be inferred from tracked keys");
|
||||
prepare(L"wrong ", false);
|
||||
record(L"ghbdtn ");
|
||||
app->transform(ks::Direct + ru);
|
||||
break;
|
||||
case 54:
|
||||
require(text() == L"wrong ", "unrelated selection remains rejected with trimmed clipboard");
|
||||
app->settings.autoCorrect = true;
|
||||
app->settings.autoLanguages = {L"en", L"ru"};
|
||||
// The worker now shares the predictor's immutable dictionaries.
|
||||
// This fixture changes settings directly instead of applySettings.
|
||||
app->autoPredictor.configure(L"dictionaries", app->settings.autoLanguages);
|
||||
app->autoCorrector = ks::AutoCorrector{};
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
prepare(L"ghbdtn ", false);
|
||||
record(L"ghbdtn ");
|
||||
app->transform(ks::AutoCorrect);
|
||||
break;
|
||||
case 55:
|
||||
require(text() == L"привет ", "automatic correction recovers copied trailing space without logging");
|
||||
app->transform(ks::Undo);
|
||||
break;
|
||||
case 56:
|
||||
{
|
||||
require(text() == L"ghbdtn ", "automatic correction undo retains recovered space");
|
||||
require(ks::readClipboard(app->window).text() == sentinel, "space recovery restores clipboard");
|
||||
pasteBehavior = 1;
|
||||
prepare(L"ghbdtn ", false);
|
||||
record(L"ghbdtn ");
|
||||
app->transform(ks::Direct + ru);
|
||||
break;
|
||||
}
|
||||
case 57:
|
||||
{
|
||||
require(text() == L"ghbdtn " && !ks::InputRegressionAccess::hasLast(*app),
|
||||
"recovered selection with blocked paste clears repeat state even without logging");
|
||||
require(trimmedCopies >= 7, "fixture actually stripped spaces during recovery scenarios");
|
||||
pasteBehavior = 0;
|
||||
trimCopiedSpaces = false;
|
||||
// User-selected middle range, followed by the same command with
|
||||
// no selection: retain both surrounding text and trailing spaces.
|
||||
prepare(L"OLDghbdtn NEXT", false);
|
||||
SendMessageW(field, EM_SETSEL, 3, 11);
|
||||
app->transform(ks::Direct + ru);
|
||||
break;
|
||||
}
|
||||
case 58:
|
||||
require(text() == L"OLDпривет NEXT", "explicit middle selection preserves surrounding text");
|
||||
app->transform(ks::Direct + en);
|
||||
break;
|
||||
case 59:
|
||||
require(text() == L"OLDghbdtn NEXT", "hotkey without selection reconverts only the previous middle range");
|
||||
require(ks::readClipboard(app->window).text() == sentinel, "selected and repeated conversions restore clipboard");
|
||||
finish();
|
||||
break;
|
||||
case 64:
|
||||
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
|
||||
captured = true;
|
||||
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
|
||||
app->settings.snippets = {{L";repo-changes-jira", L"expanded{cursor}"}};
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
prepare(L"prefix ;repo-changes-jira", false);
|
||||
record(L";repo-changes-jira");
|
||||
droppedSelectionKeys = 10;
|
||||
enterPresses = 0;
|
||||
app->transform(0, 0);
|
||||
break;
|
||||
case 65:
|
||||
require(text() == L"prefix expanded", "long snippet recovers partial selection and preserves prefix");
|
||||
require(droppedSelectionKeys == 0 && enterPresses == 0, "snippet recovery consumes missing arrows without Enter");
|
||||
require(ks::readClipboard(app->window).text() == sentinel, "snippet recovery restores clipboard");
|
||||
if (snippetRecoveryOnly) { finish(); break; }
|
||||
stage = 62;
|
||||
break;
|
||||
case 62:
|
||||
if (!captured) saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
|
||||
captured = true;
|
||||
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
|
||||
app->settings.snippets = {{L";r", L"unexpected{enter}"}};
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
prepare(L"prefix ", false);
|
||||
forwardedVersion = app->inputVersion.load();
|
||||
copyRequests = forwardedEvents = 0;
|
||||
{
|
||||
std::vector<INPUT> inputs;
|
||||
for (WORD key : {WORD(VK_OEM_1), WORD('R')})
|
||||
for (DWORD flags : {DWORD(0), DWORD(KEYEVENTF_KEYUP)})
|
||||
{
|
||||
auto input = ks::keyboardInput(key, flags);
|
||||
input.ki.dwExtraInfo = 456;
|
||||
inputs.push_back(input);
|
||||
}
|
||||
require(SendInput((UINT)inputs.size(),inputs.data(),sizeof(INPUT))==inputs.size(),
|
||||
"forwarded snippet input submitted to real hook chain");
|
||||
}
|
||||
break;
|
||||
case 63:
|
||||
require(forwardedEvents==4,"downstream forwarding hook consumed every key event");
|
||||
require(app->inputVersion==forwardedVersion && copyRequests==0,
|
||||
"forwarded snippet does not start tracking or clipboard work on source computer");
|
||||
require(text()==L"prefix " && ks::readClipboard(app->window).text()==sentinel,
|
||||
"forwarded snippet leaves source editor and clipboard untouched");
|
||||
stage = 30;
|
||||
break;
|
||||
case 30:
|
||||
case 32:
|
||||
case 34:
|
||||
case 37:
|
||||
case 60:
|
||||
// Earlier password/word tests replace the original multiline
|
||||
// editor with a single-line EDIT. Restore the snippet fixture:
|
||||
// a single-line control cannot insert the tested Enter action.
|
||||
@@ -484,6 +671,11 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
enterPresses = 0;
|
||||
copyRequests = 0;
|
||||
copyFailuresRemaining = stage == 38 ? 10 : stage == 33 ? 1 : 0;
|
||||
if (stage == 61)
|
||||
{
|
||||
pasteBehavior = 2; // Editor inserts unrelated clipboard text.
|
||||
app->settings.writeLog = false;
|
||||
}
|
||||
temporaryClipboardExcluded = true;
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
prepare(L"prefix ", false);
|
||||
@@ -547,6 +739,13 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
require(ks::readClipboard(app->window).text() == sentinel,
|
||||
"exhausted copy retries restore the clipboard");
|
||||
copyFailuresRemaining = 0;
|
||||
stage = 60;
|
||||
break;
|
||||
case 61:
|
||||
require(text() == L"prefix other! x", "incorrect snippet paste preserves following typing");
|
||||
require(enterPresses == 0, "unverified snippet never submits Enter even without logging");
|
||||
require(ks::readClipboard(app->window).text() == sentinel, "rejected snippet restores clipboard");
|
||||
pasteBehavior = 0;
|
||||
finish();
|
||||
break;
|
||||
case 20:
|
||||
@@ -559,6 +758,7 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
app->settings.autoCorrect = true;
|
||||
app->settings.switchLayout = true;
|
||||
app->settings.autoLanguages = {L"en", L"ru"};
|
||||
app->autoPredictor.configure(L"dictionaries", app->settings.autoLanguages);
|
||||
app->settings.cycle = {app->layouts[en].id, app->layouts[ru].id};
|
||||
app->autoCorrector = ks::AutoCorrector{};
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
@@ -608,6 +808,7 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
});
|
||||
require(uk != app->layouts.end(), "Ukrainian layout available for punctuation-key regression");
|
||||
app->settings.autoLanguages = {L"en", L"uk"};
|
||||
app->autoPredictor.configure(L"dictionaries", app->settings.autoLanguages);
|
||||
app->settings.cycle = {app->layouts[en].id, uk->id};
|
||||
app->settings.autoWords[L"uk"] = {L"робить"};
|
||||
app->autoCorrector = ks::AutoCorrector{};
|
||||
@@ -621,14 +822,14 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case 22:
|
||||
require(text() == L"робить ", "automatic correction selects and converts the whole word across an internal comma");
|
||||
app->settings.autoReplace = true;
|
||||
app->settings.autoReplacements = {{L"helo", L"hello"}};
|
||||
app->settings.autoReplacements = {{L"helo", L"hello world"}};
|
||||
ActivateKeyboardLayout(app->layouts[en].handle, 0);
|
||||
prepare(L"(Helo)! ", false);
|
||||
record(L"(Helo)! ");
|
||||
app->transform(ks::AutoCorrect);
|
||||
break;
|
||||
case 23:
|
||||
require(text() == L"(Hello)! ", "explicit typo pair replaces verified text with punctuation and capital");
|
||||
require(text() == L"(Hello world)! ", "explicit phrase pair replaces verified text with punctuation and capital");
|
||||
app->transform(ks::Undo);
|
||||
break;
|
||||
case 24:
|
||||
@@ -654,7 +855,7 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case 27:
|
||||
require(text() == L"kswithcer ", "Undo suppresses the rejected spelling correction");
|
||||
app->settings.autoReplace = true;
|
||||
app->settings.autoReplacements = {{L"tehh", L"the"}};
|
||||
app->settings.autoReplacements = {{L"tehh", L"the word"}};
|
||||
app->autoPredictor.configure(L"dictionaries", app->settings.autoLanguages);
|
||||
prepare(L"", false);
|
||||
{
|
||||
@@ -671,7 +872,7 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
break;
|
||||
case 28:
|
||||
require(text() == L"the x", "custom replacement through keyboard hook preserves subsequent typing");
|
||||
require(text() == L"the word x", "custom phrase replacement through keyboard hook preserves subsequent typing");
|
||||
app->settings.autoReplace = false;
|
||||
app->settings.autoTypos = false;
|
||||
if (typosOnly) { finish(); break; }
|
||||
@@ -853,14 +1054,18 @@ int main(int argc, char **argv)
|
||||
field =
|
||||
CreateWindowW(L"EDIT", L"", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_MULTILINE | ES_WANTRETURN,
|
||||
20, 20, 590, 230, host, nullptr, cls.hInstance, nullptr);
|
||||
deadline = GetTickCount64() + 30000;
|
||||
deadline = GetTickCount64() + 60000;
|
||||
SetWindowSubclass(field, observeEnter, 1, 0);
|
||||
if (typosOnly || (argc > 1 && std::string(argv[1]) == "--typing-only"))
|
||||
stage = 20;
|
||||
if (argc > 1 && std::string(argv[1]) == "--snippets-only")
|
||||
stage = 30;
|
||||
snippetRecoveryOnly = argc > 1 && std::string(argv[1]) == "--snippet-recovery-only";
|
||||
if (snippetRecoveryOnly || (argc > 1 && std::string(argv[1]) == "--snippets-only"))
|
||||
stage = 64;
|
||||
SetTimer(host, 1, 100, nullptr);
|
||||
auto forwarding = SetWindowsHookExW(WH_KEYBOARD_LL,forwardingHook,GetModuleHandleW(nullptr),0);
|
||||
require(forwarding!=nullptr,"downstream forwarding fixture installed before application hook");
|
||||
app->execute();
|
||||
UnhookWindowsHookEx(forwarding);
|
||||
}
|
||||
std::filesystem::remove_all(root);
|
||||
}
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#include "lan.h"
|
||||
#include "lan_pairing.h"
|
||||
#include <iostream>
|
||||
#include <tlhelp32.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
int passed{};
|
||||
void check(bool ok,const char *name) {if(!ok) throw std::runtime_error(name);++passed;}
|
||||
template<class F> void rejects(F f,const char *name) {bool failed=false;try{f();}catch(...){failed=true;}check(failed,name);}
|
||||
unsigned threads()
|
||||
{
|
||||
HANDLE snapshot=CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,0);
|
||||
if(snapshot==INVALID_HANDLE_VALUE) throw std::runtime_error("Cannot inspect test threads");
|
||||
THREADENTRY32 entry{sizeof(entry)};unsigned count=0;
|
||||
if(Thread32First(snapshot,&entry)) do {if(entry.th32OwnerProcessID==GetCurrentProcessId()) ++count;} while(Thread32Next(snapshot,&entry));
|
||||
CloseHandle(snapshot);return count;
|
||||
}
|
||||
}
|
||||
int main(int argc,char **argv)
|
||||
{
|
||||
using namespace ks;using namespace ks::lan;
|
||||
try
|
||||
{
|
||||
const std::string a(32,'a'),b(32,'b'),c(32,'c'),code="0123456789abcdef0123456789abcdef";
|
||||
check(normalizeCode("0123-4567-89AB-CDEF-0123-4567-89ab-cdef")==code,"code accepts groups and case");
|
||||
rejects([]{normalizeCode("123456");},"short guessable codes rejected");
|
||||
rejects([]{normalizeCode(std::string(32,'x'));},"invalid code rejected");
|
||||
check(identifier(randomHex(16)),"cryptographic instance ID");
|
||||
check(mac("key","The quick brown fox jumps over the lazy dog")=="f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", "HMAC SHA256 known vector");
|
||||
check(equal("abc","abc")&&!equal("abc","abd")&&!equal("abc","ab"),"proof comparison");
|
||||
Pairing left(a,b,code,100),right(b,a,code,100),wrong(b,a,std::string(32,'f'),100);
|
||||
check(wrong.receive(left.offer(),101).empty(),"different code cannot acknowledge");
|
||||
auto forged=left.offer();forged["id"]=c;
|
||||
check(right.receive(forged,101).empty(),"identity substitution rejected");
|
||||
forged=left.offer();forged["version"]=2;
|
||||
check(right.receive(forged,101).empty(),"unsupported protocol rejected");
|
||||
forged=left.offer();forged["to"]=c;
|
||||
check(right.receive(forged,101).empty(),"wrong destination rejected");
|
||||
auto ackR=right.receive(left.offer(),101),ackL=left.receive(right.offer(),101);
|
||||
check(ackR.size()==1&&ackL.size()==1,"mutual offers acknowledged");
|
||||
check(!left.confirmed&&!right.confirmed,"discovery and offers are not trust");
|
||||
auto confirmL=left.receive(ackR[0],102),confirmR=right.receive(ackL[0],102);
|
||||
check(confirmL.size()==1&&confirmR.size()==1,"authenticated challenges confirmed");
|
||||
left.receive(confirmR[0],103);right.receive(confirmL[0],103);
|
||||
check(left.confirmed&&right.confirmed&&left.derived==right.derived,"both endpoints derive same pair key");
|
||||
check(left.derived!=code&&left.derived.size()==64,"pair key separate from setup code");
|
||||
Pairing retry(a,b,code,200);
|
||||
check(retry.receive(ackR[0],201).empty()&&!retry.confirmed,"old ACK cannot pair new attempt");
|
||||
check(retry.receive(confirmR[0],201).empty()&&!retry.confirmed,"old confirmation cannot pair new attempt");
|
||||
Pairing expired(b,a,code,100);
|
||||
check(expired.receive(left.offer(),100+PairLifetime).empty(),"pairing window expires");
|
||||
check(left.receive(right.offer(),104).size()==1,"duplicate UDP offer is safely acknowledged");
|
||||
rejects([&]{Pairing self(a,a,code,0);},"self-pair rejected");
|
||||
auto root=std::filesystem::temp_directory_path()/wide("ks-lan-test-"+randomHex(16));
|
||||
std::filesystem::create_directory(root);
|
||||
struct Cleanup{std::filesystem::path p;~Cleanup(){std::error_code ec;std::filesystem::remove_all(p,ec);}} cleanup{root};
|
||||
auto request=[](LanService &service,Json j){auto s=j.dump();return Json::parse(service.command(Bytes(s.begin(),s.end())));};
|
||||
std::string identity;
|
||||
{
|
||||
auto idleThreads=threads();
|
||||
LanService service(root);
|
||||
check(threads()==idleThreads,"disabled LAN creates no worker thread");
|
||||
auto state=request(service,{{"action","status"}});
|
||||
check(!state.at("enabled").get<bool>()&&state.at("peers").empty(),"disabled by default");
|
||||
identity=state.at("id");
|
||||
check(!std::filesystem::exists(root/L"lan-pairing.bin"),"viewing disabled status does not create config");
|
||||
auto generated=request(service,{{"action","code"}}).at("code").get<std::string>();
|
||||
check(identifier(generated),"generated pairing code has 128 bits");
|
||||
rejects([&]{request(service,{{"action","pair"},{"peer",b},{"code",code}});},"cannot pair undiscovered peer while disabled");
|
||||
request(service,{{"action","enable"},{"enabled",false}});
|
||||
auto sealed=readFile(root/L"lan-pairing.bin",256*1024);
|
||||
check(std::string(sealed.begin(),sealed.end()).find(identity)==std::string::npos,"local configuration protected by DPAPI");
|
||||
if(argc>1&&std::string(argv[1])=="--network")
|
||||
{
|
||||
request(service,{{"action","enable"},{"enabled",true}});
|
||||
Sleep(400);
|
||||
auto active=request(service,{{"action","status"}});
|
||||
check(active.at("enabled").get<bool>() && active.at("status").get<std::string>().find("LAN stopped:")==std::string::npos,"opt-in discovery starts successfully");
|
||||
check(threads()>idleThreads,"enabled discovery has a worker");
|
||||
request(service,{{"action","enable"},{"enabled",false}});
|
||||
check(threads()==idleThreads,"disabling discovery joins its worker");
|
||||
// Reopening immediately exercises socket cleanup and exclusive bind.
|
||||
request(service,{{"action","enable"},{"enabled",true}});Sleep(200);
|
||||
check(request(service,{{"action","status"}}).at("status").get<std::string>().find("LAN stopped:")==std::string::npos,"discovery port released and reusable");
|
||||
request(service,{{"action","enable"},{"enabled",false}});
|
||||
}
|
||||
}
|
||||
{
|
||||
LanService restored(root);auto state=request(restored,{{"action","status"}});
|
||||
check(state.at("id")==identity&&!state.at("enabled").get<bool>(),"stable local instance ID and disabled state restored");
|
||||
}
|
||||
{
|
||||
auto saved=Json::parse(unprotect(readFile(root/L"lan-pairing.bin",256*1024)));
|
||||
saved["trusted"][b]={{"name","Other KSwitcher"},{"key",left.derived}};
|
||||
auto json=saved.dump();atomicWrite(root/L"lan-pairing.bin",protect(Bytes(json.begin(),json.end())));
|
||||
LanService restored(root);auto state=request(restored,{{"action","status"}});
|
||||
check(state["peers"].size()==1 && state["peers"][0].at("paired").get<bool>() && !state["peers"][0].at("online").get<bool>(),"saved pair remains visible offline");
|
||||
check(state.dump().find(left.derived)==std::string::npos,"status never exposes stored pair keys");
|
||||
rejects([&]{request(restored,{{"action","input"},{"enabled",true},{"peer",b},{"edge",1}});},"input cannot be enabled without discovery");
|
||||
rejects([&]{request(restored,{{"action","input"},{"enabled",false},{"edge",4}});},"invalid screen edge rejected");
|
||||
auto position=request(restored,{{"action","input"},{"enabled",false},{"peer",b},{"edge",2}});
|
||||
check(position.at("inputEdge")==2&&!restored.inputEnabled(),"screen position saved without enabling input");
|
||||
if(argc>1&&std::string(argv[1])=="--network")
|
||||
{
|
||||
request(restored,{{"action","enable"},{"enabled",true}});
|
||||
rejects([&]{request(restored,{{"action","input"},{"enabled",true},{"peer",c},{"edge",1}});},"discovered but unpaired peer cannot receive input");
|
||||
request(restored,{{"action","input"},{"enabled",true},{"peer",b},{"edge",2}});
|
||||
check(restored.inputEnabled(),"paired input enabled with explicit screen position");
|
||||
request(restored,{{"action","enable"},{"enabled",false}});
|
||||
check(!restored.inputEnabled(),"disabling discovery also stops input runtime");
|
||||
}
|
||||
request(restored,{{"action","forget"},{"peer",b}});
|
||||
check(request(restored,{{"action","status"}})["peers"].empty(),"forget removes offline pair");
|
||||
check(!request(restored,{{"action","status"}}).at("shareInput").get<bool>(),"forgetting the input peer revokes persisted input permission");
|
||||
}
|
||||
if(argc>1&&std::string(argv[1])=="--network")
|
||||
{
|
||||
auto saved=Json::parse(unprotect(readFile(root/L"lan-pairing.bin",256*1024)));
|
||||
saved["trusted"][b]={{"name","Restart peer"},{"key",left.derived}};
|
||||
saved["enabled"]=true;saved["shareInput"]=true;saved["inputPeer"]=b;saved["inputEdge"]=3;
|
||||
auto text=saved.dump();atomicWrite(root/L"lan-pairing.bin",protect(Bytes(text.begin(),text.end())));
|
||||
for(int restart=0;restart<2;++restart)
|
||||
{
|
||||
LanService restored(root);Sleep(100);
|
||||
auto state=request(restored,{{"action","status"}});
|
||||
check(restored.inputEnabled()&&state.at("enabled")==true&&state.at("inputPeer")==b&&state.at("inputEdge")==3,
|
||||
"restart restores discovery, pairing, input permission and screen edge without opening settings");
|
||||
}
|
||||
}
|
||||
{
|
||||
auto folder=root/L"layout";std::filesystem::create_directories(folder);
|
||||
auto saved=Json::parse(unprotect(readFile(root/L"lan-pairing.bin",256*1024)));
|
||||
saved["enabled"]=false;saved["shareInput"]=false;saved["inputPeer"]=b;saved["inputEdge"]=1;saved.erase("positions");
|
||||
saved["trusted"]={{b,{{"name","Right PC"},{"key",left.derived}}},{c,{{"name","Third PC"},{"key",left.derived}}}};
|
||||
auto text=saved.dump();atomicWrite(folder/L"lan-pairing.bin",protect(Bytes(text.begin(),text.end())));
|
||||
{
|
||||
LanService layout(folder);auto state=request(layout,{{"action","status"}});
|
||||
check(state["positions"][b]==Json::array({1,0}),"legacy side migrates to monitor grid");
|
||||
check(state["positions"].size()==2&&state["positions"][c]!=state["positions"][b],"three-PC layout has unique cells");
|
||||
request(layout,{{"action","position"},{"peer",c},{"x",-1},{"y",0}});
|
||||
request(layout,{{"action","position"},{"peer",b},{"x",0},{"y",-1}});
|
||||
rejects([&]{request(layout,{{"action","position"},{"peer",c},{"x",0},{"y",-1}});},"occupied cell rejected");
|
||||
rejects([&]{request(layout,{{"action","position"},{"peer",c},{"x",0},{"y",0}});},"local monitor cell protected");
|
||||
rejects([&]{request(layout,{{"action","position"},{"peer",c},{"x",9},{"y",0}});},"out-of-grid position rejected");
|
||||
check(request(layout,{{"action","status"}})["positions"][c]==Json::array({-1,0}),"failed drops preserve previous position");
|
||||
}
|
||||
{
|
||||
LanService layout(folder);auto state=request(layout,{{"action","status"}});
|
||||
check(state["positions"][b]==Json::array({0,-1})&&state["positions"][c]==Json::array({-1,0}),"all monitor positions survive restart");
|
||||
check(state["inputEdge"]==2,"active peer direction follows monitor position");
|
||||
if(argc>1&&std::string(argv[1])=="--network"){
|
||||
request(layout,{{"action","enable"},{"enabled",true}});
|
||||
request(layout,{{"action","input"},{"enabled",true}});
|
||||
request(layout,{{"action","position"},{"peer",c},{"x",0},{"y",-2}});
|
||||
auto multi=request(layout,{{"action","status"}});
|
||||
check(multi["shareInput"]==true&&multi["positions"][c]==Json::array({0,-2}),"multi-PC sharing remains enabled for a chained nonadjacent destination");
|
||||
request(layout,{{"action","forget"},{"peer",b}});
|
||||
check(request(layout,{{"action","status"}})["shareInput"]==true,"forgetting legacy selected pair keeps remaining pairs enabled");
|
||||
}
|
||||
request(layout,{{"action","forget"},{"peer",c}});
|
||||
check(!request(layout,{{"action","status"}})["positions"].contains(c),"forgetting pair removes its monitor");
|
||||
}
|
||||
}
|
||||
std::cout<<"Passed "<<passed<<" LAN discovery/pairing checks\n";
|
||||
}
|
||||
catch(const std::exception &e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
#include <winsock2.h>
|
||||
#include "lan_clipboard.h"
|
||||
#include <iostream>
|
||||
using namespace ks;using namespace ks::lan;
|
||||
int checks{};
|
||||
void check(bool b,const char *s){if(!b)throw std::runtime_error(s);++checks;}
|
||||
int main(){try{
|
||||
const std::string aid(32,'a'),bid(32,'b'),cid(32,'c'),key(64,'d');
|
||||
ClipboardExchange a(aid),b(bid),c(cid);
|
||||
a.peerSession(bid,b.session());a.peerSession(cid,c.session());b.peerSession(aid,a.session());c.peerSession(aid,a.session());
|
||||
Json trusted{{bid,{{"key",key}}},{cid,{{"key",key}}}},back{{aid,{{"key",key}}}};
|
||||
Bytes payload(13000);for(size_t i=0;i<payload.size();++i)payload[i]=static_cast<unsigned char>(i);
|
||||
a.queue({bid,cid},payload,"editor.exe",1);
|
||||
std::deque<std::pair<std::string,Json>> packets,acks;Json firstPacket;int sent=0;
|
||||
auto output=[&](const std::string &to,const Json &p){check(p.dump().size()<=2048,"datagram fits discovery bound");if(firstPacket.is_null())firstPacket=p;packets.push_back({to,p});};
|
||||
auto ack=[&](const std::string &,const Json &p){acks.push_back({p.at("id"),p});};
|
||||
for(uint64_t now=10;now<10000;now+=20){
|
||||
a.poll(trusted,now,output);
|
||||
while(!packets.empty()){
|
||||
auto [to,p]=std::move(packets.front());packets.pop_front();if(++sent%7==0)continue;
|
||||
auto &receiver=to==bid?b:c;
|
||||
receiver.receive(aid,key,p,now,123,ack);
|
||||
receiver.receive(aid,key,p,now,123,ack); // duplicate datagrams do not duplicate history
|
||||
}
|
||||
while(!acks.empty()){
|
||||
auto [from,p]=std::move(acks.front());acks.pop_front();if(++sent%11==0)continue;
|
||||
a.receive(from,key,p,now,123,output);
|
||||
}
|
||||
}
|
||||
check(b.deliveries.size()==1&&c.deliveries.size()==1,"all paired instances receive exactly once despite loss/duplicates");
|
||||
check(b.deliveries[0].bytes==payload&&c.deliveries[0].bytes==payload,"binary clipboard survives retransmission");
|
||||
check(b.deliveries[0].sequence==123&&b.deliveries[0].app=="editor.exe","capture sequence and origin retained");
|
||||
b.receive(aid,key,firstPacket,10000,123,ack);
|
||||
check(acks.empty(),"authenticated old packet replay is ignored");
|
||||
ClipboardExchange restarted(bid);restarted.peerSession(aid,a.session());
|
||||
restarted.receive(aid,key,firstPacket,10001,123,ack);
|
||||
check(restarted.deliveries.empty()&&acks.empty(),"old datagrams rejected after recipient restart");
|
||||
auto damaged=firstPacket;damaged["number"]=1000000;auto data=damaged["data"].get<std::string>();data[0]=data[0]=='0'?'1':'0';damaged["data"]=data;
|
||||
bool rejected=false;try{b.receive(aid,key,damaged,10002,123,ack);}catch(...){rejected=true;}
|
||||
check(rejected,"modified ciphertext rejected");
|
||||
a.queue({bid},Bytes{1,2,3},"second",10003);
|
||||
a.peerSession(bid,restarted.session());
|
||||
for(uint64_t now=10004;now<11000;now+=20){
|
||||
a.poll(trusted,now,output);
|
||||
while(!packets.empty()){auto p=std::move(packets.front().second);packets.pop_front();restarted.receive(aid,key,p,now,456,ack);}
|
||||
while(!acks.empty()){auto p=std::move(acks.front().second);acks.pop_front();a.receive(bid,key,p,now,456,output);}
|
||||
}
|
||||
check(restarted.deliveries.size()==1&&restarted.deliveries[0].bytes==Bytes({1,2,3}),"clipboard works after peer restart");
|
||||
bool limited=false;try{a.queue({bid},Bytes(32*1024*1024+1),"large",12000);}catch(...){limited=true;}
|
||||
check(limited,"oversized clipboard bounded");
|
||||
{
|
||||
WSADATA startup{};check(WSAStartup(MAKEWORD(2,2),&startup)==0,"UDP benchmark starts");
|
||||
SOCKET sa=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP),sb=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
|
||||
struct Cleanup {SOCKET a,b;~Cleanup(){closesocket(a);closesocket(b);WSACleanup();}} cleanup{sa,sb};
|
||||
sockaddr_in aa{},ab{};aa.sin_family=ab.sin_family=AF_INET;aa.sin_addr.s_addr=ab.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
|
||||
check(bind(sa,reinterpret_cast<sockaddr*>(&aa),sizeof(aa))==0&&bind(sb,reinterpret_cast<sockaddr*>(&ab),sizeof(ab))==0,"UDP benchmark binds");
|
||||
int length=sizeof(aa);getsockname(sa,reinterpret_cast<sockaddr*>(&aa),&length);length=sizeof(ab);getsockname(sb,reinterpret_cast<sockaddr*>(&ab),&length);
|
||||
for(auto socket:{sa,sb}){u_long nonblock=1;ioctlsocket(socket,FIONBIO,&nonblock);int buffer=1024*1024;setsockopt(socket,SOL_SOCKET,SO_RCVBUF,reinterpret_cast<char*>(&buffer),sizeof(buffer));}
|
||||
ClipboardExchange sender(aid),receiver(bid);sender.peerSession(bid,receiver.session());receiver.peerSession(aid,sender.session());
|
||||
Bytes large(2*1024*1024);uint32_t random=123;for(auto &v:large){random=random*1664525+1013904223;v=static_cast<unsigned char>(random>>24);}
|
||||
auto started=GetTickCount64();sender.queue({bid},large,"benchmark",started);
|
||||
auto send=[&](SOCKET socket,const sockaddr_in &address,const Json &p){auto data=p.dump();if(sendto(socket,data.data(),int(data.size()),0,reinterpret_cast<const sockaddr*>(&address),sizeof(address))!=int(data.size()))throw std::runtime_error("UDP benchmark send failed");};
|
||||
while(receiver.deliveries.empty()&&GetTickCount64()-started<15000){
|
||||
auto now=GetTickCount64();sender.poll(trusted,now,[&](const auto &,const Json &p){send(sa,ab,p);});
|
||||
bool progressed=false;
|
||||
for(int n=0;n<64;++n){char buffer[2048];auto size=recv(sb,buffer,sizeof(buffer),0);if(size<=0)break;progressed=true;
|
||||
receiver.receive(aid,key,Json::parse(buffer,buffer+size),now,123,[&](const auto &,const Json &p){send(sb,aa,p);});}
|
||||
for(int n=0;n<64;++n){char buffer[2048];auto size=recv(sa,buffer,sizeof(buffer),0);if(size<=0)break;progressed=true;
|
||||
sender.receive(bid,key,Json::parse(buffer,buffer+size),now,123,[&](const auto &,const Json &p){send(sa,ab,p);});}
|
||||
if(!progressed)Sleep(1);
|
||||
}
|
||||
check(receiver.deliveries.size()==1&&receiver.deliveries[0].bytes==large,"2 MiB crosses actual encrypted UDP sockets intact");
|
||||
std::cout<<"2 MiB encrypted UDP loopback: "<<(GetTickCount64()-started)<<" ms\n";
|
||||
}
|
||||
std::cout<<checks<<" LAN clipboard checks passed\n";return 0;
|
||||
}catch(const std::exception &e){std::cerr<<e.what()<<'\n';return 1;}}
|
||||
@@ -0,0 +1,417 @@
|
||||
#include <winsock2.h>
|
||||
#include "lan_input.h"
|
||||
#include "lan_mesh.h"
|
||||
#include <iostream>
|
||||
#include <deque>
|
||||
|
||||
using namespace ks;using namespace ks::lan;
|
||||
namespace
|
||||
{
|
||||
int passed{};
|
||||
void check(bool value,const char *text){if(!value)throw std::runtime_error(text);++passed;}
|
||||
template<class F>void rejects(F f,const char *text){bool failed=false;try{f();}catch(...){failed=true;}check(failed,text);}
|
||||
struct Desktop
|
||||
{
|
||||
RECT rect{-1920,-200,0,880};POINT point{-1000,300};bool available=true,physicalHeld=false,allow=true;
|
||||
std::vector<INPUT> events;int dpi=96;bool delayed=false;InputRouter *router{};
|
||||
InputEnvironment environment()
|
||||
{
|
||||
return {[this]{return rect;},[this]{return point;},[this](const INPUT &i){
|
||||
if(!allow)return false;
|
||||
events.push_back(i);
|
||||
if(i.type==INPUT_MOUSE&&(i.mi.dwFlags&MOUSEEVENTF_MOVE)&&!delayed)
|
||||
{
|
||||
point={rect.left+LONG(int64_t(i.mi.dx)*(rect.right-rect.left)/65536),rect.top+LONG(int64_t(i.mi.dy)*(rect.bottom-rect.top)/65536)};
|
||||
if(router){MSLLHOOKSTRUCT m{};m.pt=point;m.flags=LLMHF_INJECTED;m.dwExtraInfo=i.mi.dwExtraInfo;router->mouse(WM_MOUSEMOVE,m,1000);}
|
||||
}
|
||||
return true;
|
||||
},[this]{return available;},[this]{return physicalHeld;},{},{},[this](POINT){return dpi;}};
|
||||
}
|
||||
unsigned keyEvents(bool down)const
|
||||
{return unsigned(std::count_if(events.begin(),events.end(),[down](auto &i){return i.type==INPUT_KEYBOARD&&bool(i.ki.dwFlags&KEYEVENTF_KEYUP)!=down;}));}
|
||||
};
|
||||
KBDLLHOOKSTRUCT key(unsigned vk,unsigned scan=0){KBDLLHOOKSTRUCT k{};k.vkCode=vk;k.scanCode=scan;return k;}
|
||||
bool motion(InputRouter &router,Desktop &desktop,POINT p,uint64_t now)
|
||||
{
|
||||
auto before=desktop.point;desktop.point=p;MSLLHOOKSTRUCT m{};m.pt=p;
|
||||
bool consumed=router.mouse(WM_MOUSEMOVE,m,now);
|
||||
if(consumed&&router.mode()==ControlMode::Sending)desktop.point=before;
|
||||
return consumed;
|
||||
}
|
||||
void exchange(InputRouter &source,InputRouter &target,std::deque<InputFrame> &out,uint64_t now)
|
||||
{(void)source;while(!out.empty()){auto f=out.front();out.pop_front();target.receive(f,now);}}
|
||||
struct Pair
|
||||
{
|
||||
Desktop a,b;std::deque<InputFrame> ab,ba;
|
||||
InputRouter left,right;
|
||||
explicit Pair(int side):left(a.environment(),[this](auto f){ab.push_back(f);return true;},side,true),
|
||||
right(b.environment(),[this](auto f){ba.push_back(f);return true;},side^1,false)
|
||||
{a.router=&left;b.router=&right;b.rect={0,0,1600,900};b.point={600,400};left.tick(true,1000);right.tick(true,1000);}
|
||||
~Pair(){a.router=b.router=nullptr;}
|
||||
void deliver(uint64_t now=1100){exchange(left,right,ab,now);right.tick(true,now);exchange(right,left,ba,now);left.tick(true,now);}
|
||||
void enter(int edge)
|
||||
{
|
||||
motion(left,a,edgePoint(a.rect,edge,30000,0),1000);
|
||||
check(left.mode()==ControlMode::Requesting,"crossing edge requests ownership, not immediate suppression");
|
||||
deliver();check(left.mode()==ControlMode::Sending&&right.mode()==ControlMode::Receiving,"mouse and keyboard ownership acknowledged together");
|
||||
}
|
||||
};
|
||||
void routerChecks()
|
||||
{
|
||||
{
|
||||
std::vector<InputFrame> queue;
|
||||
for(int i=0;i<20;++i)enqueueInput(queue,{InputType::Wheel,1,120,0});
|
||||
check(queue.size()==1&&queue[0].a==2400,"pending wheel burst coalesces without losing same-direction distance");
|
||||
enqueueInput(queue,{InputType::Wheel,1,-120,0});
|
||||
check(queue.size()==1&&queue[0].a==-120,"wheel reversal replaces undelivered stale direction");
|
||||
enqueueInput(queue,{InputType::Key,1,VK_CONTROL,0,1});enqueueInput(queue,{InputType::Wheel,1,120,0});
|
||||
check(queue.size()==3&&queue[1].type==InputType::Key,"wheel coalescing preserves modifier barriers");
|
||||
enqueueInput(queue,{InputType::Wheel,1,120,1});enqueueInput(queue,{InputType::Wheel,2,120,1});
|
||||
check(queue.size()==5,"wheel coalescing preserves axis and ownership boundaries");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.enter(1);p.a.delayed=true;
|
||||
p.left.cancel(1200);
|
||||
auto before=p.a.point;
|
||||
check(motion(p.left,p.a,{before.x+10,before.y},1201),"physical movement is gated while return-to-edge is queued");
|
||||
p.a.point=edgePoint(p.a.rect,1,edgePosition(p.a.point,p.a.rect,1));p.left.tick(true,1500);
|
||||
check(!motion(p.left,p.a,{p.a.point.x-10,p.a.point.y},1501),"return movement gate always clears within bounded timeout");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.enter(1);
|
||||
for(auto vk:{VK_SHIFT,VK_LSHIFT,VK_RSHIFT,VK_CONTROL,VK_MENU})
|
||||
p.right.keyboard(key(vk),false,1200);
|
||||
check(p.right.mode()==ControlMode::Receiving&&p.ba.empty(),"layout-generated unpaired modifier releases cannot return remote ownership");
|
||||
auto own=key(VK_SHIFT);own.dwExtraInfo=inputMarker();
|
||||
p.right.keyboard(own,true,1201);p.right.keyboard(own,false,1202);
|
||||
check(p.right.mode()==ControlMode::Receiving&&p.ba.empty(),"own correction marker cannot trigger takeover even with injection flag stripped");
|
||||
p.right.keyboard(key('B'),true,1203);
|
||||
check(p.right.mode()==ControlMode::Local&&!p.ba.empty(),"real local key press still takes over after conversion release noise");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.enter(1);MSLLHOOKSTRUCT mouse{};mouse.pt=p.b.point;
|
||||
p.right.mouse(WM_MOUSEMOVE,mouse,1200);
|
||||
check(p.right.mode()==ControlMode::Receiving,"stationary untagged mouse notification does not cancel remote control");
|
||||
mouse.pt.x+=20;p.right.mouse(WM_MOUSEMOVE,mouse,1201);
|
||||
check(p.right.mode()==ControlMode::Local,"actual local mouse movement still takes control back");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.enter(1);p.b.delayed=true;auto before=p.b.events.back().mi.dx;
|
||||
for(int i=0;i<5;++i){auto point=p.a.point;point.x+=10;motion(p.left,p.a,point,1300+i);p.deliver(1300+i);}
|
||||
auto pixels=LONG(int64_t(p.b.events.back().mi.dx)*(p.b.rect.right-p.b.rect.left)/65536);
|
||||
check(pixels==58&&p.b.point.x==8&&p.b.events.back().mi.dx>before,
|
||||
"queued remote moves accumulate from entry edge even before Windows updates cursor position");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.b.delayed=true;
|
||||
motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1000);p.deliver(1100);
|
||||
check(p.left.mode()==ControlMode::Requesting,"source stays local until destination cursor actually reaches entry edge");
|
||||
p.right.tick(true,1400);p.deliver(1400);
|
||||
check(p.left.mode()==ControlMode::Local&&p.right.mode()==ControlMode::Local,"failed destination positioning returns both peers locally");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.a.delayed=true;p.enter(1);p.left.tick(true,1400);p.deliver(1400);
|
||||
check(p.left.mode()==ControlMode::Local&&p.right.mode()==ControlMode::Local,"missing source warp acknowledgement cannot suppress movement indefinitely");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.a.delayed=true;p.enter(1);auto queued=p.ab.size();
|
||||
motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1200);
|
||||
check(p.ab.size()==queued,"pre-parking physical motion cannot become a giant centre-relative delta");
|
||||
MSLLHOOKSTRUCT warp{};warp.flags=LLMHF_INJECTED;warp.dwExtraInfo=cursorWarpMarker();
|
||||
p.left.mouse(WM_MOUSEMOVE,warp,1201);p.a.point={(p.a.rect.left+p.a.rect.right)/2,(p.a.rect.top+p.a.rect.bottom)/2};
|
||||
auto point=p.a.point;++point.x;motion(p.left,p.a,point,1202);
|
||||
check(p.ab.size()==queued+1,"source movement resumes after actual warp acknowledgement");
|
||||
}
|
||||
for(auto modifier:{VK_LCONTROL,VK_LMENU,VK_LSHIFT,VK_LWIN})
|
||||
{
|
||||
Pair p(1);p.enter(1);p.b.events.clear();
|
||||
auto mod=key(modifier,modifier==VK_LCONTROL?0x1d:modifier==VK_LMENU?0x38:modifier==VK_LSHIFT?0x2a:0x5b);
|
||||
if(modifier==VK_LWIN)mod.flags=LLKHF_EXTENDED;
|
||||
p.left.keyboard(mod,true,1200);p.left.keyboard(key('C',0x2e),true,1201);
|
||||
p.left.keyboard(key('C',0x2e),false,1202);p.left.keyboard(mod,false,1203);p.deliver(1204);
|
||||
check(p.b.events.size()==4&&p.b.events[0].ki.wVk==modifier&&p.b.events[1].ki.wVk=='C'&&
|
||||
!(p.b.events[0].ki.dwFlags&KEYEVENTF_KEYUP)&&(p.b.events[3].ki.dwFlags&KEYEVENTF_KEYUP),
|
||||
"modifier chord delivered in order with matching release");
|
||||
check(!(p.b.events[0].ki.dwFlags&KEYEVENTF_SCANCODE)&&!(p.b.events[3].ki.dwFlags&KEYEVENTF_SCANCODE),
|
||||
"modifier down and up use explicit Windows key identities");
|
||||
auto correction=key(VK_CONTROL,0x1d);correction.flags=LLKHF_INJECTED;correction.dwExtraInfo=ks::inputMarker();
|
||||
p.right.keyboard(correction,true,1210);p.right.keyboard(correction,false,1211);p.right.tick(true,1220);
|
||||
check(p.right.mode()==ControlMode::Receiving&&p.left.mode()==ControlMode::Sending,
|
||||
"generated correction keys do not take back remote ownership");
|
||||
}
|
||||
for(auto dpis:{std::pair{96,192},std::pair{240,96}})
|
||||
{
|
||||
Pair p(1);p.a.dpi=dpis.first;p.b.dpi=dpis.second;p.enter(1);auto before=p.b.point;
|
||||
for(int i=0;i<100;++i){auto point=p.a.point;++point.x;motion(p.left,p.a,point,1300+i);p.deliver(1300+i);}
|
||||
check(std::abs(p.b.point.x-before.x-100*dpis.second/dpis.first)<=1,"mouse movement scales between monitor DPIs without losing small deltas");
|
||||
}
|
||||
for(int side=0;side<4;++side)
|
||||
{
|
||||
Pair p(side);auto middle=edgePoint(p.a.rect,side,32768,0);
|
||||
check(atEdge(middle,p.a.rect,side),"all four virtual-screen edges supported");
|
||||
check(std::abs(edgePosition(middle,p.a.rect,side)-32768)<100,"negative monitor coordinates normalize");
|
||||
p.enter(side);
|
||||
auto old=p.b.point;
|
||||
for(int step=0;step<20;++step)
|
||||
{
|
||||
auto point=p.a.point;if(side==0)--point.x;else if(side==1)++point.x;else if(side==2)--point.y;else ++point.y;
|
||||
motion(p.left,p.a,point,1110+step);p.deliver(1110+step);
|
||||
}
|
||||
check(side<2 ? std::abs(p.b.point.x-old.x)==20 : std::abs(p.b.point.y-old.y)==20,"one-pixel mouse movements have no accumulating warp bias");
|
||||
check(p.left.keyboard(key('A',0x1e),true,1200),"source key down suppressed");p.deliver(1200);
|
||||
check(p.a.keyEvents(true)==0&&p.b.keyEvents(true)==1,"key only injected on computer with cursor");
|
||||
check(p.b.events.back().ki.dwFlags&KEYEVENTF_SCANCODE,"physical scan code preserved across layouts");
|
||||
check(p.left.keyboard(key('A',0x1e),false,1210),"source key up suppressed");p.deliver(1210);
|
||||
check(p.b.keyEvents(false)==1,"remote key released");
|
||||
auto injected=key('A',0x1e);injected.flags=LLKHF_INJECTED;injected.dwExtraInfo=remoteInputMarker();
|
||||
check(!p.right.keyboard(injected,true,1220),"received input continues to destination hotkeys/snippets, no routing loop");
|
||||
MSLLHOOKSTRUCT click{};check(p.left.mouse(WM_LBUTTONDOWN,click,1230),"source click suppressed");p.deliver(1230);
|
||||
check(p.b.events.back().mi.dwFlags==MOUSEEVENTF_LEFTDOWN,"remote left button pressed");
|
||||
p.left.mouse(WM_LBUTTONUP,click,1240);p.deliver(1240);
|
||||
check(p.b.events.back().mi.dwFlags==MOUSEEVENTF_LEFTUP,"remote left button released");
|
||||
click.mouseData=DWORD(120)<<16;p.left.mouse(WM_MOUSEWHEEL,click,1250);p.deliver(1250);
|
||||
check(p.b.events.back().mi.dwFlags==MOUSEEVENTF_WHEEL&&p.b.events.back().mi.mouseData==120,"wheel delta forwarded");
|
||||
auto centre=p.a.point;POINT moved=centre;
|
||||
if(side==0)moved.x-=30;else if(side==1)moved.x+=30;else if(side==2)moved.y-=30;else moved.y+=30;
|
||||
check(motion(p.left,p.a,moved,1300),"remote mouse move suppressed locally");p.deliver(1300);
|
||||
check(p.b.point.x!=old.x||p.b.point.y!=old.y,"cursor moves on target");
|
||||
// Repeated source movement towards the return edge.
|
||||
for(int n=0;n<5&&p.left.mode()==ControlMode::Sending;++n)
|
||||
{
|
||||
moved=p.a.point;if(side==0)moved.x+=400;else if(side==1)moved.x-=400;else if(side==2)moved.y+=400;else moved.y-=400;
|
||||
motion(p.left,p.a,moved,1400+n);p.deliver(1400+n);
|
||||
}
|
||||
check(p.left.mode()==ControlMode::Local&&p.right.mode()==ControlMode::Local,"crossing target return edge restores local ownership");
|
||||
check(!atEdge(p.a.point,p.a.rect,side),"return cursor inset avoids immediate bounce");
|
||||
check(!p.left.keyboard(key('B'),true,1500),"normal local typing resumes");p.left.keyboard(key('B'),false,1501);
|
||||
}
|
||||
{
|
||||
Pair p(1);p.enter(1);p.left.keyboard(key(VK_LCONTROL),true,1200);p.left.keyboard(key(VK_LMENU),true,1201);p.deliver();
|
||||
check(p.left.keyboard(key(VK_ESCAPE),true,1202),"emergency return chord consumed");p.deliver();
|
||||
check(p.left.mode()==ControlMode::Local&&p.right.mode()==ControlMode::Local,"emergency chord returns both sides");
|
||||
check(p.b.keyEvents(false)==2,"emergency return releases remote modifiers");
|
||||
check(p.left.keyboard(key(VK_LCONTROL),false,1203)&&p.left.keyboard(key(VK_LMENU),false,1204),"stray source modifier releases consumed after return");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.enter(1);p.left.keyboard(key('A'),true,1200);p.deliver();
|
||||
p.left.tick(false,1300);p.right.tick(false,1300);
|
||||
check(p.b.keyEvents(false)==1&&p.left.mode()==ControlMode::Local,"disconnect releases held remote key");
|
||||
check(p.left.keyboard(key('A'),false,1400),"source does not leak orphaned key-up after disconnect");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.enter(1);p.left.keyboard(key('A'),true,1200);p.deliver();p.b.available=false;p.right.tick(true,1300);
|
||||
check(p.right.mode()==ControlMode::Local&&p.b.keyEvents(false)==0,"secure desktop stops ownership without injecting there");
|
||||
p.b.available=true;p.right.tick(true,1400);check(p.b.keyEvents(false)==1,"blocked release retried when normal desktop returns");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.a.physicalHeld=true;motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1000);
|
||||
check(p.left.mode()==ControlMode::Local,"no cross-screen handoff with physically held key/button");
|
||||
p.a.physicalHeld=false;motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1100);
|
||||
p.left.keyboard(key('X'),true,1101);p.deliver(1200);
|
||||
check(p.left.mode()==ControlMode::Local&&p.right.mode()==ControlMode::Local,"typing during handoff cancels stale accept");
|
||||
}
|
||||
{
|
||||
Pair p(1);motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1000);motion(p.right,p.b,edgePoint(p.b.rect,0,30000,0),1000);
|
||||
p.deliver();p.deliver();check(p.left.mode()==ControlMode::Sending&&p.right.mode()==ControlMode::Receiving,"simultaneous crossing has deterministic ownership");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.enter(1);p.left.keyboard(key('A'),true,1200);p.deliver();
|
||||
check(!p.right.keyboard(key('B'),true,1300),"local physical keyboard takes over target");p.deliver();
|
||||
check(p.left.mode()==ControlMode::Local&&p.b.keyEvents(false)==1,"local takeover returns source and releases remote keys");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.b.allow=false;motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1000);p.deliver();
|
||||
check(p.left.mode()==ControlMode::Local&&p.right.mode()==ControlMode::Local,"blocked SendInput fails closed without capturing source");
|
||||
}
|
||||
{
|
||||
Pair p(1);p.enter(1);MSLLHOOKSTRUCT m{};m.mouseData=DWORD(XBUTTON2)<<16;
|
||||
p.left.mouse(WM_XBUTTONDOWN,m,1200);p.deliver();p.right.tick(false,1300);
|
||||
check(p.b.events.back().mi.dwFlags==MOUSEEVENTF_XUP&&p.b.events.back().mi.mouseData==XBUTTON2,"disconnect releases held extra mouse button");
|
||||
}
|
||||
{
|
||||
Pair p(1);motion(p.left,p.a,edgePoint(p.a.rect,1,30000,0),1000);p.left.tick(true,2101);
|
||||
check(p.left.mode()==ControlMode::Local,"unanswered ownership request times out locally");p.deliver(2200);p.deliver(2200);
|
||||
check(p.left.mode()==ControlMode::Local&&p.right.mode()==ControlMode::Local,"late handoff acknowledgement cannot steal control");
|
||||
}
|
||||
{
|
||||
Desktop d;bool accept=true;std::deque<InputFrame> frames;
|
||||
InputRouter router(d.environment(),[&](auto f){frames.push_back(f);return accept;},1,true);
|
||||
router.tick(true,1000);motion(router,d,edgePoint(d.rect,1,30000,0),1000);
|
||||
auto token=frames.front().token;router.receive({InputType::Accept,token},1100);
|
||||
accept=false;check(router.keyboard(key('Q'),true,1200),"failed queue still consumes the key rather than typing locally");
|
||||
check(router.mode()==ControlMode::Local&&router.keyboard(key('Q'),false,1300),"queue failure returns control and consumes orphan release");
|
||||
}
|
||||
}
|
||||
|
||||
struct MeshFixture
|
||||
{
|
||||
struct Message{std::string from,to;InputFrame frame;};
|
||||
std::deque<Message> messages;Desktop desktops[3];std::unique_ptr<InputMesh> meshes[3];uint64_t now=1000;
|
||||
std::map<std::string,uint64_t> connections[3];
|
||||
MeshFixture(bool vertical=false){
|
||||
POINT cells[3]={{0,0},{1,0},vertical?POINT{1,-1}:POINT{2,0}};
|
||||
for(int i=0;i<3;++i){
|
||||
desktops[i].rect={0,0,800,600};desktops[i].point={400,300};std::map<std::string,POINT> positions;
|
||||
for(int j=0;j<3;++j)if(i!=j){auto name=std::to_string(j);positions[name]={cells[j].x-cells[i].x,cells[j].y-cells[i].y};connections[i][name]=1;}
|
||||
meshes[i]=std::make_unique<InputMesh>(std::to_string(i),desktops[i].environment(),positions,[this,i](auto &peer,auto f){messages.push_back({std::to_string(i),peer,f});return true;});
|
||||
}pump();
|
||||
}
|
||||
~MeshFixture(){for(auto &m:meshes)m.reset();}
|
||||
void pump(){for(int rounds=0;rounds<10;++rounds){
|
||||
while(!messages.empty()){auto m=messages.front();messages.pop_front();meshes[std::stoi(m.to)]->receive(m.from,m.frame,now);}
|
||||
for(int i=0;i<3;++i)meshes[i]->tick(connections[i],now);
|
||||
}}
|
||||
void move(int x,int y){++now;auto &d=desktops[0];auto old=d.point;MSLLHOOKSTRUCT m{};m.pt={old.x+x,old.y+y};d.point=m.pt;
|
||||
bool consumed=meshes[0]->mouse(WM_MOUSEMOVE,m,now);if(consumed&&meshes[0]->mode()==ControlMode::Sending)d.point=old;pump();}
|
||||
void enter(){desktops[0].point={798,300};move(1,0);check(meshes[0]->mode()==ControlMode::Sending&&meshes[1]->mode()==ControlMode::Receiving,"mesh enters first neighbor");}
|
||||
};
|
||||
void meshChecks()
|
||||
{
|
||||
{
|
||||
MeshFixture f;f.enter();f.move(900,0);
|
||||
check(f.meshes[0]->peer()=="2"&&f.meshes[2]->mode()==ControlMode::Receiving&&f.meshes[1]->mode()==ControlMode::Local,"A routes directly to C through B right edge");
|
||||
f.desktops[1].events.clear();f.desktops[2].events.clear();
|
||||
for(auto k:{VK_LSHIFT,int('A')})f.meshes[0]->keyboard(key(k),true,++f.now);
|
||||
for(auto k:{int('A'),VK_LSHIFT})f.meshes[0]->keyboard(key(k),false,++f.now);
|
||||
f.pump();
|
||||
check(f.desktops[1].keyEvents(true)==0&&f.desktops[2].keyEvents(true)==2&&f.desktops[2].keyEvents(false)==2,"modifier chord goes only to current destination C");
|
||||
f.move(-900,0);check(f.meshes[0]->peer()=="1"&&f.meshes[1]->mode()==ControlMode::Receiving,"C left edge returns through B");
|
||||
f.move(-900,0);check(f.meshes[0]->mode()==ControlMode::Local&&f.desktops[0].point.x>780,"B left edge restores source at its right edge");
|
||||
}
|
||||
{
|
||||
MeshFixture f(true);f.enter();f.move(0,-900);
|
||||
check(f.meshes[0]->peer()=="2"&&f.desktops[2].point.y>580,"vertical turn enters C at bottom edge");
|
||||
f.move(0,900);check(f.meshes[0]->peer()=="1","vertical return routes back to B");
|
||||
}
|
||||
{
|
||||
MeshFixture f;f.connections[0].erase("2");f.pump();f.enter();f.move(900,0);
|
||||
check(f.meshes[0]->peer()=="1"&&f.meshes[1]->mode()==ControlMode::Receiving,"offline neighbor blocks passage without losing current control");
|
||||
f.meshes[0]->keyboard(key(VK_LSHIFT),true,++f.now);f.pump();f.connections[0].erase("1");f.connections[1].erase("0");f.pump();
|
||||
check(f.meshes[0]->mode()==ControlMode::Local&&f.meshes[1]->mode()==ControlMode::Local&&f.desktops[1].keyEvents(false)==1,"disconnect restores local control and releases held modifier");
|
||||
}
|
||||
{
|
||||
MeshFixture f;f.enter();f.meshes[1]->receive("2",{InputType::Enter,99,1,20000},++f.now);
|
||||
check(f.meshes[1]->peer()=="0"&&f.meshes[1]->mode()==ControlMode::Receiving,"another controller cannot steal receiving desktop");f.pump();
|
||||
f.move(900,0);f.meshes[0]->receive("1",{InputType::Return,1,20000},++f.now);
|
||||
check(f.meshes[0]->mode()==ControlMode::Sending&&f.meshes[0]->peer()=="2","late previous peer return cannot cancel current destination");
|
||||
f.connections[0]["2"]=2;f.pump();check(f.meshes[0]->mode()==ControlMode::Local,"new connection generation does not continue stale ownership");
|
||||
}
|
||||
}
|
||||
uint16_t freePort()
|
||||
{
|
||||
SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(s==INVALID_SOCKET)throw std::runtime_error("test socket");
|
||||
sockaddr_in a{};a.sin_family=AF_INET;a.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
|
||||
if(bind(s,(sockaddr*)&a,sizeof(a))){closesocket(s);throw std::runtime_error("test bind");}
|
||||
int size=sizeof(a);getsockname(s,(sockaddr*)&a,&size);auto port=ntohs(a.sin_port);closesocket(s);return port;
|
||||
}
|
||||
|
||||
void hubChecks()
|
||||
{
|
||||
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
|
||||
struct Close{~Close(){WSACleanup();}} close;
|
||||
std::string ids[3]={std::string(32,'a'),std::string(32,'b'),std::string(32,'c')},secret(64,'f');
|
||||
uint16_t ports[3]={freePort(),freePort(),freePort()};
|
||||
std::unique_ptr<InputHub> hubs[3];std::vector<InputEndpoint> endpoints[3];std::vector<RoutedInput> incoming[3];
|
||||
for(int i=0;i<3;++i){hubs[i]=std::make_unique<InputHub>(ids[i],ports[i]);for(int j=0;j<3;++j)if(i!=j)endpoints[i].push_back({ids[j],secret,htonl(INADDR_LOOPBACK),ports[j]});}
|
||||
auto pump=[&](uint64_t offset=0){for(int i=2;i>=0;--i)hubs[i]->poll(endpoints[i],{},incoming[i],GetTickCount64()+offset);Sleep(1);};
|
||||
auto deadline=GetTickCount64()+5000;
|
||||
while((hubs[0]->ready().size()!=2||hubs[1]->ready().size()!=2||hubs[2]->ready().size()!=2)&&GetTickCount64()<deadline)pump();
|
||||
check(hubs[0]->ready().size()==2&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"three TCP hubs authenticate all independent pair channels on one listener per PC");
|
||||
InputFrame keyFrame{InputType::Key,7,'A',0,1},cross{InputType::Cross,8,2,30000};
|
||||
hubs[0]->poll(endpoints[0],{{ids[1],keyFrame},{ids[2],cross}},incoming[0],GetTickCount64());
|
||||
for(int n=0;n<100&&(incoming[1].empty()||incoming[2].empty());++n)pump();
|
||||
check(incoming[1].size()==1&&incoming[1][0].peer==ids[0]&&incoming[1][0].frame==keyFrame&&incoming[2].size()==1&&incoming[2][0].frame==cross,"hub routes encrypted frames only to their named destinations");
|
||||
for(auto &in:incoming)in.clear();
|
||||
auto survivor=hubs[0]->ready().at(ids[2]),old=hubs[0]->ready().at(ids[1]);
|
||||
hubs[1]->disconnect();for(int n=0;n<30;++n)pump();
|
||||
check(hubs[0]->ready().contains(ids[2])&&hubs[0]->ready().at(ids[2])==survivor,"one computer disconnect leaves other authenticated channel intact");
|
||||
for(int n=0;n<300&&(hubs[0]->ready().size()!=2||hubs[1]->ready().size()!=2);++n)pump(1800);
|
||||
check(hubs[0]->ready().size()==2&&hubs[0]->ready().at(ids[1])!=old,"mesh reconnect restores channel with fresh ownership generation");
|
||||
endpoints[0].erase(endpoints[0].begin());hubs[0]->poll(endpoints[0],{},incoming[0],GetTickCount64()+1800);
|
||||
check(!hubs[0]->ready().contains(ids[1])&&hubs[0]->ready().contains(ids[2]),"forgetting one pair revokes only its channel");
|
||||
}
|
||||
void channelChecks()
|
||||
{
|
||||
std::string a(32,'a'),b(32,'b'),secret(64,'f');auto na=randomHex(16),nb=randomHex(16);
|
||||
auto k=inputSessionKey(secret,a,b,na,nb);check(k!=inputSessionKey(secret,b,a,nb,na),"directional session keys differ");
|
||||
check(inputSessionKey(secret,a,b,na,nb,0)!=inputSessionKey(secret,a,b,na,nb,1),"screen geometry bound into authenticated session");
|
||||
InputCipher tx(k),rx(k);InputFrame f{InputType::Key,37,'A',0x1e,1};auto packet=tx.encrypt(f);
|
||||
check(packet.size()==36&&rx.decrypt(packet)==f,"AES-GCM authenticated input roundtrip");
|
||||
rejects([&]{rx.decrypt(packet);},"encrypted frame replay rejected");
|
||||
auto next=tx.encrypt({InputType::Move,37,-12,400});auto tampered=next;tampered[4]^=1;
|
||||
rejects([&]{rx.decrypt(tampered);},"ciphertext modification rejected");
|
||||
check(rx.decrypt(next)==InputFrame{InputType::Move,37,-12,400},"failed authentication does not expose or advance data");
|
||||
InputCipher wrong(inputSessionKey(secret,b,a,nb,na));rejects([&]{wrong.decrypt(packet);},"reflection across directions rejected");
|
||||
InputCipher otherSession(inputSessionKey(secret,a,b,randomHex(16),nb));rejects([&]{otherSession.decrypt(packet);},"old-session input rejected");
|
||||
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
|
||||
struct Close{~Close(){WSACleanup();}} close;
|
||||
{
|
||||
auto port=freePort();InputChannel client(a,b,secret,1,port),server(b,a,secret,0,port);
|
||||
std::vector<InputFrame> received;auto start=GetTickCount64();
|
||||
server.poll(htonl(INADDR_LOOPBACK),{},received,start);
|
||||
client.poll(htonl(INADDR_LOOPBACK),{},received,start);
|
||||
auto generation=client.generation();
|
||||
client.poll(htonl(INADDR_LOOPBACK),{},received,start+3000);
|
||||
check(client.generation()==generation,"initial handshake allows more than the active heartbeat timeout");
|
||||
for(int n=0;n<200&&(!client.ready()||!server.ready());++n)
|
||||
{
|
||||
auto now=GetTickCount64()+3000;
|
||||
server.poll(htonl(INADDR_LOOPBACK),{},received,now);client.poll(htonl(INADDR_LOOPBACK),{},received,now);Sleep(1);
|
||||
}
|
||||
check(client.ready()&&server.ready(),"delayed initial handshake still authenticates");
|
||||
}
|
||||
{
|
||||
auto port=freePort();InputChannel client(a,b,secret,1,port),server(b,a,secret,0,port);
|
||||
std::vector<InputFrame> received;auto start=GetTickCount64();
|
||||
server.poll(htonl(INADDR_LOOPBACK),{},received,start);
|
||||
client.poll(htonl(INADDR_LOOPBACK),{},received,start);
|
||||
client.poll(htonl(INADDR_LOOPBACK),{},received,start+100);
|
||||
client.poll(htonl(INADDR_LOOPBACK),{},received,start+11000);
|
||||
check(!client.ready()&&client.status().find("authentication timed out")!=std::string::npos,
|
||||
"initial authentication timeout distinguished from lost active connection");
|
||||
}
|
||||
{
|
||||
auto port=freePort();InputChannel client(a,b,secret,1,port),server(b,a,secret,0,port);
|
||||
auto deadline=GetTickCount64()+5000;std::vector<InputFrame> received;
|
||||
while((!client.ready()||!server.ready())&&GetTickCount64()<deadline)
|
||||
{
|
||||
server.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());client.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());Sleep(1);
|
||||
}
|
||||
check(client.ready()&&server.ready(),"real TCP peers mutually authenticate with paired key");
|
||||
check(received.empty(),"handshake produces no input events");
|
||||
client.poll(htonl(INADDR_LOOPBACK),{f},received,GetTickCount64());
|
||||
for(int n=0;n<100&&received.empty();++n){server.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());client.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());Sleep(1);}
|
||||
check(received.size()==1&&received[0]==f,"real TCP channel delivers one ordered authenticated key");received.clear();
|
||||
InputFrame reverse{InputType::Wheel,37,-120,1};server.poll(htonl(INADDR_LOOPBACK),{reverse},received,GetTickCount64());
|
||||
for(int n=0;n<100&&received.empty();++n){client.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());Sleep(1);}
|
||||
check(received.size()==1&&received[0]==reverse,"real input channel is bidirectional");
|
||||
received.clear();server.disconnect();
|
||||
client.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());
|
||||
for(int n=0;n<300&&(!client.ready()||!server.ready());++n)
|
||||
{
|
||||
auto now=GetTickCount64()+1800;
|
||||
server.poll(htonl(INADDR_LOOPBACK),{},received,now);client.poll(htonl(INADDR_LOOPBACK),{},received,now);Sleep(1);
|
||||
}
|
||||
check(client.ready()&&server.ready(),"paired channel reconnects automatically after peer disconnect without new pairing");
|
||||
auto generation=client.generation();client.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64()+5000);
|
||||
check(!client.ready()&&client.generation()!=generation,"heartbeat timeout closes channel and changes generation");
|
||||
}
|
||||
{
|
||||
auto port=freePort();InputChannel client(a,b,secret,1,port),server(b,a,std::string(64,'e'),0,port);
|
||||
std::vector<InputFrame> received;auto start=GetTickCount64();
|
||||
while(GetTickCount64()-start<400){server.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());client.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());Sleep(1);}
|
||||
check(!client.ready()&&!server.ready()&&received.empty(),"wrong saved pair key never authorizes input");
|
||||
}
|
||||
{
|
||||
auto port=freePort();InputChannel client(a,b,secret,1,port),server(b,a,secret,1,port);
|
||||
std::vector<InputFrame> received;auto start=GetTickCount64();
|
||||
while(GetTickCount64()-start<400){server.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());client.poll(htonl(INADDR_LOOPBACK),{},received,GetTickCount64());Sleep(1);}
|
||||
check(!client.ready()&&!server.ready()&&received.empty(),"conflicting screen arrangement rejected before input");
|
||||
}
|
||||
}
|
||||
}
|
||||
int main()
|
||||
{
|
||||
try{channelChecks();hubChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
|
||||
catch(const std::exception &e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}
|
||||
}
|
||||
@@ -59,6 +59,24 @@ int main(int argc, char **argv)
|
||||
app.settings.history = true;
|
||||
app.history->add(clip, L"OCR fixture", app.settings);
|
||||
auto id = app.history->entries().front().id;
|
||||
auto isolated = app.history->recognizeImage(id, config);
|
||||
if (isolated != text) throw std::runtime_error("Helper and in-process OCR results differ");
|
||||
bool cancelled = false;
|
||||
try { app.history->recognizeImage(id, config, [] { return true; }); }
|
||||
catch (const std::exception &) { cancelled = true; }
|
||||
if (!cancelled) throw std::runtime_error("Cancelled OCR request was executed");
|
||||
auto invalid = config;
|
||||
invalid.useTesseract = true;
|
||||
invalid.tesseractPath = (temp / L"missing-tesseract.exe").wstring();
|
||||
bool failed = false;
|
||||
try { app.history->recognizeImage(id, invalid); }
|
||||
catch (const std::exception &) { failed = true; }
|
||||
if (!failed || app.history->entries().front().ocrState != 1)
|
||||
throw std::runtime_error("Failed helper modified history metadata");
|
||||
for (const auto &file : std::filesystem::directory_iterator(temp / L"history"))
|
||||
if (file.path().filename().wstring().starts_with(L"ocr-"))
|
||||
throw std::runtime_error("OCR helper left temporary files");
|
||||
std::cout << "PASS isolated OCR equivalence, cancellation, failure and encrypted IPC cleanup\n";
|
||||
if (tesseract)
|
||||
{
|
||||
app.history->saveOcr(id, L"old Windows result", app.settings);
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
static std::wstring programs;
|
||||
static std::wstring activationExecutable, activationCommand;
|
||||
static int activationCalls{};
|
||||
static DWORD launchFlags{}; static bool inheritsHandles{};
|
||||
static BOOL WINAPI testCreateProcess(LPCWSTR path, LPWSTR command, LPSECURITY_ATTRIBUTES,
|
||||
LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCWSTR, LPSTARTUPINFOW, LPPROCESS_INFORMATION)
|
||||
LPSECURITY_ATTRIBUTES, BOOL inherit, DWORD flags, LPVOID, LPCWSTR, LPSTARTUPINFOW, LPPROCESS_INFORMATION)
|
||||
{
|
||||
launchFlags=flags; inheritsHandles=inherit;
|
||||
++activationCalls; activationExecutable=path; activationCommand=command;
|
||||
SetLastError(ERROR_CANCELLED); return FALSE; // Inspect activation without starting any program.
|
||||
}
|
||||
@@ -55,6 +57,14 @@ int main()
|
||||
valid=id.vt==VT_CLSID && *id.puuid==ks::ActivatorId; PropVariantClear(&id);
|
||||
if(!valid) throw std::runtime_error("shortcut activator missing");
|
||||
ks::registerScreenshotNotifications(); // Registration is safe to repeat.
|
||||
bool launchFailed=false;
|
||||
try { ks::startScreenshotNotificationRegistration(); }
|
||||
catch(const std::exception &) { launchFailed=true; }
|
||||
if(!launchFailed || activationExecutable!=helper.wstring() ||
|
||||
activationCommand!=L"\""+helper.wstring()+L"\" --register-notifications" ||
|
||||
!(launchFlags&CREATE_NO_WINDOW) || inheritsHandles)
|
||||
throw std::runtime_error("registration must launch the sibling helper and propagate failure");
|
||||
activationCalls=0;
|
||||
ks::Activator activator(helper.wstring(),false);
|
||||
activator.Activate(L"HrynCo.KSwitcher.Screenshot",L"check-update",nullptr,0);
|
||||
auto main=(helper.parent_path()/L"KSwitcher.exe").wstring();
|
||||
|
||||
+99
-1
@@ -83,6 +83,53 @@ int main(int argc, char **argv)
|
||||
require(c.pencilCursor!=nullptr,"pencil drawing cursor loads");
|
||||
require(c.freehand && !c.pointer && ks::toolCursor(c)==c.pencilCursor,
|
||||
"new screenshot editor starts with the pencil tool");
|
||||
{
|
||||
require(GetDlgItem(window,41) && GetDlgItem(window,44),"smoothing slider and Apply to all exist");
|
||||
auto adjust=[&](int value,int code=TB_THUMBPOSITION) {
|
||||
SendDlgItemMessageW(window,41,TBM_SETPOS,TRUE,value);
|
||||
SendMessageW(window,WM_HSCROLL,MAKEWPARAM(code,0),(LPARAM)GetDlgItem(window,41));
|
||||
};
|
||||
adjust(70); require(c.smoothing==70 && c.marks.empty(),"no selection changes default smoothing");
|
||||
ks::Mark pencil{{40,80},{240,80},0}; pencil.freehand=true;
|
||||
for(int i=0;i<=100;++i) pencil.points.push_back({40+i*2,80+(i%2?5:0)});
|
||||
ks::Mark rectangle{{40,130},{240,210},0}; rectangle.shape=ks::ScreenshotShape::Rectangle;
|
||||
c.marks={pencil,pencil,rectangle}; c.selected=0;
|
||||
auto rawImage=ks::decodeImage(ks::screenshotClip(c.image->dc,320,240,c.marks)).bgra;
|
||||
adjust(40,TB_THUMBTRACK); adjust(90,TB_THUMBTRACK); adjust(90,TB_ENDTRACK);
|
||||
require(c.marks[0].smoothing==90 && c.marks[1].smoothing==0 && c.smoothing==70,
|
||||
"selected stroke smoothing leaves other objects and default alone");
|
||||
SendMessageW(window,WM_COMMAND,12,0);
|
||||
require(c.marks[0].smoothing==0,"one undo reverses an entire slider drag");
|
||||
SendMessageW(window,WM_COMMAND,18,0);
|
||||
require(c.marks[0].smoothing==90,"redo restores smoothing amount and path");
|
||||
c.selected=0; ks::syncLineOptions(window,c);
|
||||
SendMessageW(window,WM_COMMAND,44,0);
|
||||
require(c.marks[0].smoothing==90 && c.marks[1].smoothing==90 && c.smoothing==90 &&
|
||||
c.marks[2].shape==ks::ScreenshotShape::Rectangle && c.marks[2].rawPoints.empty(),
|
||||
"Apply to all updates pencil strokes and default without changing shapes");
|
||||
require(ks::decodeImage(ks::screenshotClip(c.image->dc,320,240,c.marks)).bgra!=rawImage,
|
||||
"PNG export uses the smoothed geometry");
|
||||
SendMessageW(window,WM_COMMAND,12,0);
|
||||
require(c.marks[0].smoothing==90 && c.marks[1].smoothing==0,"bulk smoothing is one undo step");
|
||||
c.selected=0; adjust(0);
|
||||
require(c.marks[0].points.size()==pencil.points.size() && c.marks[0].points[1].y==85,
|
||||
"selected zero smoothing restores exact original path");
|
||||
require(ks::decodeImage(ks::screenshotClip(c.image->dc,320,240,c.marks)).bgra==rawImage,
|
||||
"restoring zero smoothing restores the exact original exported pixels");
|
||||
c.marks.clear(); c.selected=-1; c.history=ks::ScreenshotHistory{};
|
||||
adjust(75);
|
||||
auto mouse=[&](UINT message,POINT p) {
|
||||
int x=c.view.left+MulDiv(p.x,c.view.right-c.view.left,c.image->width);
|
||||
int y=c.view.top+MulDiv(p.y,c.view.bottom-c.view.top,c.image->height);
|
||||
SendMessageW(window,message,message==WM_LBUTTONUP?0:MK_LBUTTON,MAKELPARAM(x,y));
|
||||
};
|
||||
mouse(WM_LBUTTONDOWN,{40,90});
|
||||
for(int i=1;i<=100;++i) mouse(WM_MOUSEMOVE,{40+i*2,90+LONG(std::lround(35*std::sin(i*.04)+3*std::sin(i*1.7)))});
|
||||
mouse(WM_LBUTTONUP,{240,64});
|
||||
require(c.marks.size()==1 && c.marks[0].freehand && c.marks[0].smoothing==75 && !c.marks[0].rawPoints.empty(),
|
||||
"new curved pencil stroke uses toolbar default and retains original samples");
|
||||
c.marks.clear(); c.selected=-1; c.history=ks::ScreenshotHistory{}; c.smoothing=25;
|
||||
}
|
||||
{
|
||||
require(GetDlgItem(window,36)!=nullptr,"triangle has a dedicated toolbar button");
|
||||
SendMessageW(window,WM_KEYDOWN,'G',0);
|
||||
@@ -141,6 +188,38 @@ int main(int argc, char **argv)
|
||||
SendMessageW(window,WM_COMMAND,12,0); require(c.marks.empty(),"undo trapezoid creation");
|
||||
SendMessageW(window,WM_COMMAND,18,0); require(c.marks[0].shape==ks::ScreenshotShape::Trapezoid,"redo trapezoid creation");
|
||||
c.marks.clear(); c.selected=-1; c.history=ks::ScreenshotHistory{};
|
||||
require(GetDlgItem(window,38)!=nullptr,"arc has a dedicated toolbar button");
|
||||
SendMessageW(window,WM_KEYDOWN,'U',0);
|
||||
require(c.shape==ks::ScreenshotShape::Arc && c.arrow && !c.freehand,"U selects arc tool");
|
||||
mouse(WM_LBUTTONDOWN,{60,70}); mouse(WM_LBUTTONUP,{240,180});
|
||||
require(c.marks.size()==1 && c.marks[0].shape==ks::ScreenshotShape::Arc && !c.marks[0].isHighlight(),
|
||||
"arc tool creates an editable shape");
|
||||
auto arc=c.marks[0];
|
||||
require(ks::hitScreenshotMark(arc,{150,70},3)==ks::MarkPart::Body &&
|
||||
ks::hitScreenshotMark(arc,{150,180},3)==ks::MarkPart::None,
|
||||
"arc selects its curve but has no closing chord");
|
||||
ks::Surface rendered(320,240); PatBlt(rendered.dc,0,0,320,240,WHITENESS);
|
||||
ks::drawMarks(rendered.dc,{arc});
|
||||
require(GetPixel(rendered.dc,150,70)==arc.color && GetPixel(rendered.dc,150,180)==RGB(255,255,255),
|
||||
"arc renders an open curve without a closing chord");
|
||||
auto exported=ks::decodeImage(ks::screenshotClip(c.image->dc,320,240,{arc}));
|
||||
auto channel=[&](int x,int y,int component){return exported.bgra[(y*exported.width+x)*4+component];};
|
||||
require(channel(150,70,2)==GetRValue(arc.color) && channel(150,70,1)==GetGValue(arc.color) &&
|
||||
channel(150,180,0)==255 && channel(150,180,1)==255 && channel(150,180,2)==255,
|
||||
"PNG export preserves the arc and its open chord");
|
||||
mouse(WM_LBUTTONDOWN,arc.to); mouse(WM_LBUTTONUP,{260,200});
|
||||
require(c.marks[0].to.x==260 && c.marks[0].points.back().y==200,"arc resizes with its bounds");
|
||||
auto arcGrip=ks::screenshotShapeRotationHandle(arc);
|
||||
auto turned=ks::dragScreenshotMark(arc,ks::MarkPart::Rotation,arcGrip,{280,135},320,240);
|
||||
require(turned.rotation!=0 && ks::hitScreenshotMark(turned,ks::rotateShapePoint(turned,{150,70}),3)==ks::MarkPart::Body,
|
||||
"rotated arc remains selectable");
|
||||
std::vector<ks::Mark> linked{arc}; ks::Mark connector{{10,10},{150,70},0};
|
||||
ks::linkScreenshotEndpoint(connector,false,{150,70},linked,4);
|
||||
require(connector.toLink.target!=0,"connector can attach to the arc curve");
|
||||
SendMessageW(window,WM_COMMAND,12,0); require(c.marks[0].to.x==240,"undo arc resize");
|
||||
SendMessageW(window,WM_COMMAND,12,0); require(c.marks.empty(),"undo arc creation");
|
||||
SendMessageW(window,WM_COMMAND,18,0); require(c.marks[0].shape==ks::ScreenshotShape::Arc,"redo arc creation");
|
||||
c.marks.clear(); c.selected=-1; c.history=ks::ScreenshotHistory{};
|
||||
SendMessageW(window,WM_COMMAND,21,0);
|
||||
}
|
||||
{
|
||||
@@ -225,6 +304,17 @@ int main(int argc, char **argv)
|
||||
require(c.zoom>zoom && std::abs(before.x-after.x)<=1 && std::abs(before.y-after.y)<=1,
|
||||
"Ctrl+wheel zoom keeps image point under cursor");
|
||||
require(!c.history.canUndo(),"zoom does not add image edits to undo history");
|
||||
// A fixed zoom can still fit inside a high-DPI editor. Size the
|
||||
// fixture from the actual viewport, with room for the tested drag
|
||||
// on both axes, then start from a centered view.
|
||||
const double panZoom=std::max({1.0,
|
||||
double(c.canvas.right-c.canvas.left+128)/(c.view.right-c.view.left),
|
||||
double(c.canvas.bottom-c.canvas.top+128)/(c.view.bottom-c.view.top)});
|
||||
ks::zoomCanvas(window,c,panZoom,center);
|
||||
c.panX=c.panY=0; ks::layout(window,c);
|
||||
require(c.view.left+15<c.canvas.left && c.view.top+10<c.canvas.top &&
|
||||
c.view.right>c.canvas.right && c.view.bottom>c.canvas.bottom,
|
||||
"pan fixture has drag clearance on both axes within the supported zoom range");
|
||||
auto view=c.view;
|
||||
SendMessageW(window,WM_MBUTTONDOWN,MK_MBUTTON,MAKELPARAM(center.x,center.y));
|
||||
SendMessageW(window,WM_MOUSEMOVE,MK_MBUTTON,MAKELPARAM(center.x+15,center.y+10));
|
||||
@@ -443,8 +533,16 @@ int main(int argc, char **argv)
|
||||
c.marks={{{20,20},{120,20},0}};
|
||||
require(ks::actionCursor(c,{0,ks::MarkPart::Body},true)==LoadCursorW(nullptr,IDC_SIZEALL),"move cursor overrides drawing tool");
|
||||
require(ks::actionCursor(c,{0,ks::MarkPart::Rotation},true)==LoadCursorW(nullptr,IDC_HAND),"rotation cursor overrides drawing tool");
|
||||
require(ks::actionCursor(c,{0,ks::MarkPart::End},true)==LoadCursorW(nullptr,IDC_SIZEWE),"endpoint resize overrides drawing tool");
|
||||
for(auto part:{ks::MarkPart::Start,ks::MarkPart::End,ks::MarkPart::Radius,
|
||||
ks::MarkPart::Label,ks::MarkPart::Vertex0,ks::MarkPart::Vertex1,ks::MarkPart::Vertex2})
|
||||
require(ks::actionCursor(c,{0,part},true)==LoadCursorW(nullptr,IDC_SIZEALL),
|
||||
"freely movable handles use four-direction cursor for every drawing tool");
|
||||
require(ks::actionCursor(c,{0,ks::MarkPart::Thickness},true)==LoadCursorW(nullptr,IDC_SIZENS),"thickness resize is perpendicular to line");
|
||||
c.marks[0].to={20,120};
|
||||
require(ks::actionCursor(c,{0,ks::MarkPart::End},true)==LoadCursorW(nullptr,IDC_SIZEALL),
|
||||
"vertical line endpoint still moves in both axes");
|
||||
require(ks::actionCursor(c,{0,ks::MarkPart::Thickness},true)==LoadCursorW(nullptr,IDC_SIZEWE),
|
||||
"vertical line thickness retains horizontal resize cursor");
|
||||
}
|
||||
c.marks.clear(); SendMessageW(window,WM_COMMAND,27,0);
|
||||
wchar_t windowTitle[128]{}; GetWindowTextW(window,windowTitle,128);
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#include "settings_merge.h"
|
||||
#include <iostream>
|
||||
using namespace ks;
|
||||
int main(){try{
|
||||
Settings base;base.autoCorrect=false;base.toggle=L"Ctrl+Alt+F11";
|
||||
auto draft=base,current=base;draft.toggle=L"Ctrl+Alt+F12";current.autoCorrect=true;
|
||||
auto merged=decodeSettings(mergeConfigurationSettings(encodeSettings(base),encodeSettings(draft),encodeSettings(current)),{});
|
||||
if(merged.toggle!=draft.toggle||!merged.autoCorrect)throw std::runtime_error("independent changes lost");
|
||||
current.toggle=L"Ctrl+Alt+F10";bool rejected=false;
|
||||
try{mergeConfigurationSettings(encodeSettings(base),encodeSettings(draft),encodeSettings(current));}
|
||||
catch(const std::exception &e){rejected=std::string(e.what()).starts_with("Settings conflict: ");}
|
||||
if(!rejected)throw std::runtime_error("same-field conflict silently overwritten");
|
||||
merged=decodeSettings(mergeConfigurationSettings(encodeSettings(base),encodeSettings(draft),encodeSettings(current),true),{});
|
||||
if(merged.toggle!=draft.toggle||!merged.autoCorrect)throw std::runtime_error("confirmed edits discarded unrelated current changes");
|
||||
merged=decodeSettings(mergeConfigurationSettings(encodeSettings(base),encodeSettings(base),encodeSettings(current)),{});
|
||||
if(merged.toggle!=current.toggle||!merged.autoCorrect)throw std::runtime_error("unchanged draft reverted current settings");
|
||||
draft=base;current=base;draft.chatCycles[L"telegram\nfirst"]={L"win:04090409"};current.chatCycles[L"telegram\nsecond"]={L"win:04220422"};
|
||||
merged=decodeSettings(mergeConfigurationSettings(encodeSettings(base),encodeSettings(draft),encodeSettings(current)),{});
|
||||
if(merged.chatCycles.size()!=2)throw std::runtime_error("independent nested changes lost");
|
||||
std::cout<<"Passed 5 settings-save merge checks\n";
|
||||
}catch(const std::exception &e){std::cerr<<e.what()<<'\n';return 1;}}
|
||||
@@ -0,0 +1,29 @@
|
||||
param([Parameter(Mandatory=$true)][string]$Executable)
|
||||
$ErrorActionPreference='Stop'
|
||||
function Command([string]$Argument) {
|
||||
$commandProcess=Start-Process -FilePath $Executable -ArgumentList $Argument -WindowStyle Hidden -PassThru
|
||||
try {
|
||||
$null=$commandProcess.Handle
|
||||
$commandProcess.WaitForExit()
|
||||
return $commandProcess.ExitCode
|
||||
} finally { $commandProcess.Dispose() }
|
||||
}
|
||||
if ((Command '--status') -ne 3) { throw 'An isolated StayHere test instance is already running' }
|
||||
$process=Start-Process -FilePath $Executable -WindowStyle Hidden -PassThru
|
||||
$null=$process.Handle
|
||||
try {
|
||||
$ready=$false
|
||||
for($i=0;$i -lt 20;$i++) {
|
||||
if((Command '--status') -eq 1){$ready=$true;break}
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
if(!$ready){throw 'StayHere did not start enabled'}
|
||||
if((Command '--pause') -ne 0 -or (Command '--status') -ne 2){throw 'StayHere pause failed'}
|
||||
if((Command '--resume') -ne 0 -or (Command '--status') -ne 1){throw 'StayHere resume failed'}
|
||||
if((Command '--exit') -ne 0 -or !$process.WaitForExit(3000)){throw 'StayHere exit failed'}
|
||||
if((Command '--status') -ne 3){throw 'StayHere instance remained after exit'}
|
||||
Write-Output 'Passed isolated StayHere start/status/pause/resume/exit checks'
|
||||
} finally {
|
||||
if(!$process.HasExited){$null=Command '--exit';if(!$process.WaitForExit(3000)){$process.Kill()}}
|
||||
$process.Dispose()
|
||||
}
|
||||
@@ -122,4 +122,31 @@ inline void testStrokeImprovement() {
|
||||
double deviation=0; for(auto p:smooth) deviation+=std::abs(p.y-100);
|
||||
require(deviation/smooth.size()<1.5 && smooth.front().y==jitter.front().y && smooth.back().y==jitter.back().y,
|
||||
"smoothing reduces jitter and preserves endpoints");
|
||||
auto equal=[](const auto &a,const auto &b){return a.size()==b.size() && std::equal(a.begin(),a.end(),b.begin(),
|
||||
[](POINT x,POINT y){return x.x==y.x && x.y==y.y;});};
|
||||
require(equal(ks::smoothScreenshotStroke(jitter,0),jitter),"zero smoothing preserves exact mouse samples");
|
||||
std::vector<POINT> waves;
|
||||
for(int i=0;i<=200;++i) waves.push_back({30+i,100+LONG(std::lround(6*std::sin(i*.5)))});
|
||||
auto roughness=[](const auto &p){double total=0; for(size_t i=1;i<p.size();++i) total+=std::abs(p[i].y-p[i-1].y); return total;};
|
||||
auto low=ks::smoothScreenshotStroke(waves,25),high=ks::smoothScreenshotStroke(waves,100);
|
||||
require(roughness(high)<roughness(low) && roughness(low)<roughness(waves),"higher smoothing removes more jitter");
|
||||
require(high.front().x==waves.front().x && high.front().y==waves.front().y &&
|
||||
high.back().x==waves.back().x && high.back().y==waves.back().y,"smoothing preserves both endpoints");
|
||||
ks::ScreenshotMark mark{waves.front(),waves.back(),0}; mark.freehand=true; mark.points=waves;
|
||||
ks::setScreenshotSmoothing(mark,100); ks::setScreenshotSmoothing(mark,25);
|
||||
require(equal(mark.points,low),"lowering smoothing recomputes from original instead of accumulating filters");
|
||||
ks::setScreenshotSmoothing(mark,0);
|
||||
require(equal(mark.points,waves),"zero restores original after multiple adjustments");
|
||||
ks::setScreenshotSmoothing(mark,100);
|
||||
auto moved=ks::dragScreenshotMark(mark,ks::MarkPart::Body,{0,0},{10,15},500,500);
|
||||
ks::setScreenshotSmoothing(moved,0);
|
||||
require(moved.points[40].x==waves[40].x+10 && moved.points[40].y==waves[40].y+15,
|
||||
"moving preserves the original path in moved coordinates");
|
||||
auto resized=ks::dragScreenshotMark(mark,ks::MarkPart::End,mark.to,{260,130},500,500);
|
||||
ks::setScreenshotSmoothing(resized,0);
|
||||
require(resized.points.back().x==260 && resized.points.back().y==130,"endpoint editing survives smoothing changes");
|
||||
auto duplicate=ks::cloneScreenshotMark(mark,{mark},500,500);
|
||||
ks::setScreenshotSmoothing(duplicate,0);
|
||||
require(duplicate.points[40].x==waves[40].x+16 && duplicate.points[40].y==waves[40].y+16,
|
||||
"cloning retains independent original geometry");
|
||||
}
|
||||
@@ -70,6 +70,91 @@ int main()
|
||||
reordered.directIds = {L"00000422", L"00000409"}; reordered.direct = {L"Ctrl+2", L"Ctrl+1"};
|
||||
require(sharedSyncSettings(ordered) == sharedSyncSettings(reordered), "layout enumeration does not cause sync churn");
|
||||
auto j = parse(base);
|
||||
{
|
||||
const std::wstring chat=L"telegram\nРобота / ~test";
|
||||
const auto chatKey=utf8(chat);
|
||||
Settings chats=local;
|
||||
chats.chatCycles[chat]={L"win:00000422",L"win:00000409"};
|
||||
chats.chatCycles[L"telegram-web\nРобота / ~test"]={L"win:00000409"};
|
||||
chats.chatCycles[L"ms-teams\nTeam"]={L"win:00000422"};
|
||||
chats.chatCycles[L"viber\nSaved inactive"]={L"win:00000409"};
|
||||
auto shared=sharedSyncSettings(chats);
|
||||
require(restoreSyncSettings(shared,local,{},true).chatCycles==chats.chatCycles,
|
||||
"sync transfers all chat applications, Unicode names and ordered layout IDs even when not installed");
|
||||
auto legacy=j; legacy.erase("chatCycles");
|
||||
require(restoreSyncSettings(bytes(legacy),chats,{},true).chatCycles==chats.chatCycles,
|
||||
"legacy profile without chat field preserves existing profiles");
|
||||
require(restoreSyncSettings(base,chats,{},true).chatCycles.empty(),
|
||||
"explicit empty chat map clears synchronized profiles");
|
||||
auto l=j,r=j;
|
||||
l["chatCycles"][chatKey]=Json::array({"win:00000422","win:00000409"});
|
||||
r["chatCycles"]["ms-teams\nOther"]=Json::array({"win:00000409"});
|
||||
auto first=mergeSyncProfile({},bytes(l),bytes(r));
|
||||
require(first.conflicts.empty() && parse(first.local)["chatCycles"].size()==2 && first.local==first.remote,
|
||||
"first sync unions profiles for different chats");
|
||||
auto ancestor=first.local;
|
||||
l=r=parse(ancestor);
|
||||
l["chatCycles"][chatKey]=Json::array({"win:00000409","win:00000422"});
|
||||
r["chatCycles"]["ms-teams\nOther"]=Json::array({"win:00000422"});
|
||||
auto independent=mergeSyncProfile(ancestor,bytes(l),bytes(r));
|
||||
require(independent.conflicts.empty() && parse(independent.local)["chatCycles"]==
|
||||
Json({{chatKey,l["chatCycles"][chatKey]},{"ms-teams\nOther",r["chatCycles"]["ms-teams\nOther"]}}),
|
||||
"independent chat edits merge without losing language order");
|
||||
r["chatCycles"][chatKey]=Json::array({"win:00000422"});
|
||||
auto conflict=mergeSyncProfile(ancestor,bytes(l),bytes(r));
|
||||
require(conflict.conflicts.size()==1 && conflict.conflicts[0].key.find("~1")!=std::string::npos &&
|
||||
conflict.conflicts[0].label.find(L"Chat languages: telegram / ")==0,
|
||||
"same-chat edit conflict has readable name and escaped pointer");
|
||||
auto again=mergeSyncProfile(conflict.base,conflict.local,conflict.remote);
|
||||
require(again.conflicts.size()==1,"chat conflict survives persisted merge ancestor");
|
||||
auto resolved=mergeSyncProfile(again.base,again.local,again.remote,{{again.conflicts[0],false}});
|
||||
require(resolved.conflicts.empty() && parse(resolved.local)["chatCycles"][chatKey]==r["chatCycles"][chatKey],
|
||||
"choose remote languages for one chat");
|
||||
l=r=parse(ancestor); l["chatCycles"].erase(chatKey);
|
||||
auto removed=mergeSyncProfile(ancestor,bytes(l),bytes(r));
|
||||
require(removed.conflicts.empty() && !restoreSyncSettings(removed.local,local,{},true).chatCycles.contains(chat),
|
||||
"chat deletion propagates and merged profile remains loadable");
|
||||
r["chatCycles"][chatKey]=Json::array({"win:00000409"});
|
||||
auto deletion=mergeSyncProfile(ancestor,bytes(l),bytes(r));
|
||||
require(deletion.conflicts.size()==1,"chat deletion versus edit requires a choice");
|
||||
auto erase=mergeSyncProfile(deletion.base,deletion.local,deletion.remote,{{deletion.conflicts[0],true}});
|
||||
require(erase.conflicts.empty() && !parse(erase.remote)["chatCycles"].contains(chatKey),
|
||||
"choosing deletion removes chat without leaving null entries");
|
||||
auto stale=mergeSyncProfile(ancestor,bytes(l),bytes(legacy));
|
||||
require(stale.conflicts.empty() && parse(stale.local)["chatCycles"]==l["chatCycles"],
|
||||
"older remote missing chat field cannot delete or resurrect local chat profiles");
|
||||
auto validate=[&](const Bytes &value){restoreSyncSettings(value,chats,{},true);};
|
||||
FakeProvider provider; provider.remote={1,bytes(legacy)};
|
||||
auto download=synchronize(provider,{},shared,SyncAction::Download,validate,{},true);
|
||||
require(provider.writes==0 && restoreSyncSettings(download.settings,local,{},true).chatCycles==chats.chatCycles,
|
||||
"download from older server profile preserves chat settings");
|
||||
provider.remote={1,base};
|
||||
download=synchronize(provider,{},shared,SyncAction::Download,validate,{},true);
|
||||
require(restoreSyncSettings(download.settings,local,{},true).chatCycles.empty(),
|
||||
"download explicit empty chat map removes local profiles");
|
||||
provider.remote={1,bytes(legacy)};
|
||||
auto upload=synchronize(provider,{},shared,SyncAction::Upload,validate,{},true);
|
||||
require(provider.writes==1 && restoreSyncSettings(provider.remote.settings,local,{},true).chatCycles==chats.chatCycles,
|
||||
"upload publishes chat profiles while keeping PC layout settings separate");
|
||||
auto invalid=j; invalid["chatCycles"][chatKey]=Json::array();
|
||||
rejects([&]{restoreSyncSettings(bytes(invalid),local,{},true);},"reject empty synchronized chat cycle");
|
||||
invalid["chatCycles"][chatKey]=Json::array({"not-a-layout"});
|
||||
rejects([&]{restoreSyncSettings(bytes(invalid),local,{},true);},"reject invalid synchronized layout ID");
|
||||
invalid["chatCycles"]=Json::object({{"unknown\nChat",Json::array({"win:00000409"})}});
|
||||
rejects([&]{restoreSyncSettings(bytes(invalid),local,{},true);},"reject unknown synchronized chat application");
|
||||
}
|
||||
{
|
||||
Settings scoped = local;
|
||||
scoped.snippets.push_back({L"test", L"Work apps", L"teams-scope", {L"ms-teams", L"outlook"}});
|
||||
auto wire=sharedSyncSettings(scoped);
|
||||
require(restoreSyncSettings(wire, local, {}).snippets[1].apps==std::vector<std::wstring>{L"ms-teams", L"outlook"}, "sync preserves multiple app scopes");
|
||||
auto leftScope=j,rightScope=j;
|
||||
leftScope["snippets"].push_back({{"id","left-scope"},{"trigger","same"},{"text","left"},{"apps",Json::array({"notepad"})}});
|
||||
rightScope["snippets"].push_back({{"id","right-scope"},{"trigger","same"},{"text","right"},{"apps",Json::array({"ms-teams"})}});
|
||||
require(parse(mergeSyncSettings(base,bytes(leftScope),bytes(rightScope)))["snippets"].size()==3, "same trigger in different apps merges");
|
||||
rightScope["snippets"].back()["apps"]=Json::array({"NOTEPAD.exe"});
|
||||
rejects([&]{mergeSyncSettings(base,bytes(leftScope),bytes(rightScope));}, "sync detects overlapping application scopes");
|
||||
}
|
||||
require(!j.contains("startWithSystem") && !j.contains("tesseractPath") && !j.contains("historyEnabled"), "local-only fields excluded");
|
||||
auto restored = restoreSyncSettings(base, local, {});
|
||||
require(restored.autostart && restored.elevatedAutostart && !restored.history && restored.tesseractPath == local.tesseractPath, "preserve device settings");
|
||||
|
||||
+178
-16
@@ -1,9 +1,11 @@
|
||||
#include "autocorrect.h"
|
||||
#include "history_preview.h"
|
||||
#include "ocr.h"
|
||||
#include "lan_clipboard_image.h"
|
||||
#include "richtext.h"
|
||||
#include "storage.h"
|
||||
#include "diagnostics.h"
|
||||
#include "json.hpp"
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
@@ -23,20 +25,6 @@ void rejects(const std::function<void()> &f, const char *name)
|
||||
bool thrown = false;
|
||||
try
|
||||
{
|
||||
{
|
||||
std::map<std::wstring,int> previews;
|
||||
std::set<std::wstring> visible;
|
||||
for(int i=0;i<40;++i) previews[std::to_wstring(i)]=i;
|
||||
for(int i=0;i<8;++i) visible.insert(std::to_wstring(i));
|
||||
ks::trimHistoryPreviews(previews,visible);
|
||||
require(previews.size()==32,"preview cache stays bounded");
|
||||
for(const auto &id:visible) require(previews.contains(id),"visible preview survives eviction");
|
||||
for(int i=0;i<40;++i) { auto id=std::to_wstring(i); previews[id]=i; visible.insert(id); }
|
||||
ks::trimHistoryPreviews(previews,visible);
|
||||
require(previews.size()==40,"tall viewport does not thrash visible previews");
|
||||
visible.clear(); ks::trimHistoryPreviews(previews,visible);
|
||||
require(previews.size()==32,"cache shrinks after leaving tall viewport");
|
||||
}
|
||||
f();
|
||||
}
|
||||
catch (...)
|
||||
@@ -60,6 +48,34 @@ int main(int argc, char **argv)
|
||||
}
|
||||
try
|
||||
{
|
||||
// Byte budgets must retain visible entries even when they alone exceed the budget.
|
||||
{
|
||||
std::map<std::wstring, size_t> cache{{L"a", 800}, {L"b", 800}, {L"c", 100}};
|
||||
std::set<std::wstring> visible{L"b"};
|
||||
auto weight=[](size_t bytes) { return bytes; };
|
||||
ks::trimHistoryPreviews(cache, visible, 32, 1000, weight);
|
||||
require(cache.size()==2 && cache.contains(L"b") && cache.contains(L"c"),
|
||||
"byte budget evicts offscreen previews below count limit");
|
||||
ks::trimHistoryPreviews(cache, visible, 32, 100, weight);
|
||||
require(cache.size()==1 && cache.contains(L"b"), "oversized visible preview never thrashes");
|
||||
visible.clear();
|
||||
ks::trimHistoryPreviews(cache, visible, 32, 100, weight);
|
||||
require(cache.empty(), "oversized preview is freed after leaving viewport");
|
||||
}
|
||||
{
|
||||
std::map<std::wstring,int> previews;
|
||||
std::set<std::wstring> visible;
|
||||
for(int i=0;i<40;++i) previews[std::to_wstring(i)]=i;
|
||||
for(int i=0;i<8;++i) visible.insert(std::to_wstring(i));
|
||||
ks::trimHistoryPreviews(previews,visible);
|
||||
require(previews.size()==32,"preview cache stays bounded");
|
||||
for(const auto &id:visible) require(previews.contains(id),"visible preview survives eviction");
|
||||
for(int i=0;i<40;++i) { auto id=std::to_wstring(i); previews[id]=i; visible.insert(id); }
|
||||
ks::trimHistoryPreviews(previews,visible);
|
||||
require(previews.size()==40,"tall viewport does not thrash visible previews");
|
||||
visible.clear(); ks::trimHistoryPreviews(previews,visible);
|
||||
require(previews.size()==32,"cache shrinks after leaving tall viewport");
|
||||
}
|
||||
{
|
||||
ks::DiagnosticJson record{{"attempt", "42"}, {"process", "editor.exe"}, {"command", "Convert / cycle"},
|
||||
{"source", "English"}, {"target", "Ukrainian"}, {"outcome", "Original text remained"},
|
||||
@@ -99,6 +115,10 @@ int main(int argc, char **argv)
|
||||
"large diagnostic selections are explicitly truncated");
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
ks::DiagnosticBuffer diagnostics;
|
||||
diagnostics.record(L"idle-expiry", false, 0);
|
||||
require(diagnostics.expire(30000)==0,"diagnostics remain available at expiry boundary");
|
||||
require(diagnostics.expire(30001)==1,"idle expiry releases context without another log event");
|
||||
require(diagnostics.expire(60000)==0,"repeated idle expiry is safe");
|
||||
require(diagnostics.record(L"successful-attempt", false, 100).empty(),
|
||||
"successful diagnostics stay in memory");
|
||||
auto incident = diagnostics.record(L"failed-attempt", true, 200);
|
||||
@@ -171,6 +191,8 @@ int main(int argc, char **argv)
|
||||
"HTML entities and Unicode survive without script text");
|
||||
require((effects(0, 6) & CFE_BOLD) != 0, "inline CSS bold is rendered");
|
||||
auto plain = ks::textClip(L"{\\literal} Привіт");
|
||||
require(ks::richPreview(plain, false).empty(), "plain history preview does not require RichEdit");
|
||||
require(!ks::richPreview(styled, false).empty(), "formatted history preview retains HTML rendering");
|
||||
ks::setRichText(rich, ks::richPreview(plain));
|
||||
GetWindowTextW(rich, rendered, 256);
|
||||
require(std::wstring(rendered) == plain.text(), "plain Unicode and RTF metacharacters are escaped");
|
||||
@@ -217,6 +239,26 @@ int main(int argc, char **argv)
|
||||
require(!autoSettings.autoCorrect, "auto-correction defaults off");
|
||||
autoSettings.cycle = {L"en", L"uk"};
|
||||
corrector.configure(L"dictionaries", autoSettings.autoLanguages);
|
||||
{
|
||||
ks::AutoCorrector consumer;
|
||||
consumer.shareDictionaries(corrector);
|
||||
require(consumer.suggest(L"ghbdsn ", 0, layouts, autoSettings).has_value(),
|
||||
"shared dictionaries produce the same correction");
|
||||
consumer.reject(L"ghbdsn");
|
||||
consumer.shareDictionaries(corrector);
|
||||
require(!consumer.suggest(L"ghbdsn ", 0, layouts, autoSettings),
|
||||
"refreshing shared dictionaries preserves consumer undo rejections");
|
||||
require(corrector.suggest(L"ghbdsn ", 0, layouts, autoSettings).has_value(),
|
||||
"consumer rejections do not affect the predictor");
|
||||
ks::AutoCorrector retained;
|
||||
retained.shareDictionaries(corrector);
|
||||
corrector.configure({}, {});
|
||||
require(retained.suggest(L"ghbdsn ", 0, layouts, autoSettings).has_value(),
|
||||
"in-flight dictionary snapshot survives source reset");
|
||||
consumer.shareDictionaries(corrector);
|
||||
require(consumer.memoryBytes() == 0, "disabled correction releases consumer dictionaries");
|
||||
corrector.shareDictionaries(retained);
|
||||
}
|
||||
{
|
||||
auto options = autoSettings;
|
||||
options.autoTypos = true;
|
||||
@@ -476,6 +518,24 @@ int main(int argc, char **argv)
|
||||
auto encoded = ks::encodeClip(clip);
|
||||
require(ks::decodeClip(encoded).text() == clip.text(), "clipboard Unicode roundtrip");
|
||||
require(ks::decodeClip(encoded).formats[1].name == L"HTML Format", "registered format identity");
|
||||
auto selection = ks::textClip(L";pa");
|
||||
selection.formats.push_back({0, L"vscode-editor-data", {1, 2, 3}});
|
||||
auto relayed = selection;
|
||||
relayed.formats.front().data.resize(128, 0xab);
|
||||
std::reverse(relayed.formats.begin(), relayed.formats.end());
|
||||
require(ks::selectionClipboardIdentity(selection) == ks::selectionClipboardIdentity(relayed),
|
||||
"clipboard relay tolerates Unicode allocation slack and format order");
|
||||
relayed.formats.front().data[0] ^= 1;
|
||||
require(ks::selectionClipboardIdentity(selection) != ks::selectionClipboardIdentity(relayed),
|
||||
"clipboard relay rejects changed editor metadata");
|
||||
relayed = selection;
|
||||
relayed.formats.pop_back();
|
||||
require(ks::selectionClipboardIdentity(selection) != ks::selectionClipboardIdentity(relayed),
|
||||
"clipboard relay rejects missing editor metadata");
|
||||
relayed = selection;
|
||||
relayed.formats.front() = ks::textClip(L";pb").formats.front();
|
||||
require(ks::selectionClipboardIdentity(selection) != ks::selectionClipboardIdentity(relayed),
|
||||
"clipboard relay rejects changed Unicode text");
|
||||
auto encrypted = ks::protect(encoded);
|
||||
require(encrypted != encoded, "history ciphertext differs");
|
||||
require(ks::unprotect(encrypted) == encoded, "Windows DPAPI roundtrip");
|
||||
@@ -531,6 +591,12 @@ int main(int argc, char **argv)
|
||||
options.autoNever = {L"hlelo"};
|
||||
require(!edited.suggest(L"hlelo ", 0, layouts, options), "never-correct overrides explicit pairs");
|
||||
options.autoNever.clear();
|
||||
options.autoReplacements[L"мамамила"] = L"мама мила";
|
||||
correction = edited.suggest(L"(Мамамила)! ", 2, layouts, options);
|
||||
require(correction && correction->text == L"(Мама мила)! " && correction->target == 2,
|
||||
"joined words split while preserving capitalization, punctuation and layout");
|
||||
edited.reject(L"мамамила ", options);
|
||||
require(!edited.suggest(L"мамамила ", 2, layouts, options), "undo suppresses phrase replacements");
|
||||
edited.reject(L"(Hlelo)! ", options);
|
||||
require(!edited.suggest(L"hlelo ", 0, layouts, options), "undo rejection suppresses custom replacements");
|
||||
options.autoReplace = false;
|
||||
@@ -545,6 +611,20 @@ int main(int argc, char **argv)
|
||||
require(!ambiguous.suggest(L"hell ", 0, layouts, options), "frequency filter does not conceal ambiguous typo targets");
|
||||
}
|
||||
ks::Pixels pixels{2, 1, {10, 20, 30, 255, 40, 50, 60, 255}};
|
||||
{
|
||||
auto png = ks::encodePng(pixels);
|
||||
ks::Clip encoded{{{0, L"PNG", png}}};
|
||||
for (int i=0; i<3; ++i) {
|
||||
auto decoded=ks::decodeImage(encoded);
|
||||
require(decoded.bgra==pixels.bgra && decoded.width==2 && decoded.height==1,
|
||||
"borrowed PNG stream preserves decoded pixels on repeated reads");
|
||||
require(encoded.formats[0].data==png,"PNG decoder never modifies the borrowed input");
|
||||
}
|
||||
ks::Clip fallback{{{0,L"PNG",{}},ks::imageDib(pixels)}};
|
||||
require(ks::decodeImage(fallback).bgra==pixels.bgra,"empty PNG falls back to DIB");
|
||||
ks::Clip invalid{{{0,L"PNG",{1,2,3}}}};
|
||||
rejects([&] { ks::decodeImage(invalid); },"invalid borrowed PNG fails safely");
|
||||
}
|
||||
ks::Clip firstImage{{ks::imageDib(pixels), {0, L"Ole Private Data", {1, 2, 3}}}};
|
||||
auto thumbnail = ks::decodeImage(firstImage, 1, 1);
|
||||
require(thumbnail.width == 1 && thumbnail.height == 1 && thumbnail.bgra.size() == 4,
|
||||
@@ -583,13 +663,62 @@ int main(int argc, char **argv)
|
||||
"Snipping Tool republish retains one pinned history entry");
|
||||
history.add(changedImage, L"SnippingTool", defaults);
|
||||
require(history.entries().size() == 2, "a new screenshot is retained");
|
||||
auto copiedText = ks::textClip(L"text after screenshot");
|
||||
history.add(copiedText, L"Editor", defaults);
|
||||
history.add(copiedText, L"Editor", defaults);
|
||||
require(history.entries().size() == 3 && !history.entries().front().image,
|
||||
"text after screenshot is retained and consecutive text duplicates are skipped");
|
||||
history.add(changedImage, L"SnippingTool", defaults);
|
||||
history.add(changedImage, L"SnippingTool", defaults);
|
||||
require(history.entries().size() == 4 && history.entries().front().image,
|
||||
"image after text is retained and consecutive image duplicates are skipped");
|
||||
history.add(withText, L"Editor", defaults);
|
||||
require(history.entries().size() == 5,
|
||||
"mixed image and text payload is not discarded by metadata prefilter");
|
||||
}
|
||||
{
|
||||
auto folder = temp / L"fingerprints";
|
||||
ks::Settings defaults;
|
||||
ks::History history(folder);
|
||||
history.add(firstImage, L"test", defaults);
|
||||
auto id = history.entries().front().id;
|
||||
history.pin(id);
|
||||
history.saveOcr(id, L"retained OCR", defaults);
|
||||
ks::History reopened(folder);
|
||||
require(reopened.entries().front().contentHash.size() == 64,
|
||||
"SHA-256 fingerprint survives encrypted index reload");
|
||||
// Deny payload reads: duplicates must still be detected using only the index.
|
||||
auto handle = CreateFileW((folder / (id + L".dat")).c_str(), GENERIC_READ, 0, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
require(handle != INVALID_HANDLE_VALUE, "lock image payload for no-read regression");
|
||||
reopened.add(firstImage, L"test", defaults);
|
||||
reopened.add(secondImage, L"test", defaults);
|
||||
reopened.add(recoded, L"test", defaults);
|
||||
CloseHandle(handle);
|
||||
require(reopened.entries().size() == 1 && reopened.entries().front().pinned &&
|
||||
reopened.ocrText(id) == std::optional<std::wstring>(L"retained OCR"),
|
||||
"exact, OLE and pixel-equivalent duplicates need no payload read and retain pin/OCR");
|
||||
auto index = nlohmann::json::parse(ks::unprotect(ks::readFile(folder / L"index.dat", 1024*1024)));
|
||||
for (auto &entry : index)
|
||||
for (auto key : {"fingerprintVersion", "contentHash", "imageHash", "pixelHash"}) entry.erase(key);
|
||||
auto legacy = index.dump();
|
||||
ks::atomicWrite(folder / L"index.dat", ks::protect(ks::Bytes(legacy.begin(), legacy.end())));
|
||||
ks::History migrated(folder);
|
||||
migrated.add(secondImage, L"test", defaults);
|
||||
ks::History persisted(folder);
|
||||
require(persisted.entries().size() == 1 && persisted.entries().front().contentHash.size() == 64,
|
||||
"legacy duplicate migrates fingerprints without adding or losing an entry");
|
||||
persisted.add(changedImage, L"test", defaults);
|
||||
require(persisted.entries().size() == 2, "pixel fingerprint preserves genuinely changed images");
|
||||
persisted.add(firstImage, L"test", defaults);
|
||||
require(persisted.entries().size() == 3, "hash deduplication remains consecutive rather than global");
|
||||
}
|
||||
ks::Settings settings;
|
||||
settings.writeLog = false;
|
||||
settings.elevatedAutostart = true;
|
||||
settings.autoCorrect = true;
|
||||
settings.autoReplace = settings.autoTypos = true;
|
||||
settings.autoReplacements = {{L"првиіт", L"привіт"}, {L"helo", L"hello"}};
|
||||
settings.autoReplacements = {{L"првиіт", L"привіт"}, {L"helo", L"hello"}, {L"мамамила", L"мама мила"}};
|
||||
settings.autoMaxRank = 10000;
|
||||
settings.autoMinLength = 5;
|
||||
settings.autoPrefixChars = L"(#";
|
||||
@@ -604,7 +733,13 @@ int main(int argc, char **argv)
|
||||
require(restored.autoWords == settings.autoWords, "personal dictionaries survive settings roundtrip");
|
||||
require(restored.autoReplace && restored.autoTypos && restored.autoReplacements == settings.autoReplacements,
|
||||
"typo options and Unicode pairs survive settings roundtrip");
|
||||
for (const auto &pair : {std::pair{L"hello", L"привіт"}, {L"hello", L"hello"}, {L"hi!", L"hello"}})
|
||||
for (const auto &pair : {std::pair{L"hello", L"привіт"}, {L"hello", L"hello"}, {L"hi!", L"hello"},
|
||||
{L"helloworld", L" hello world"}, {L"helloworld", L"hello world "},
|
||||
{L"helloworld", L"hello world"}, {L"helloworld", L"hello\tworld"},
|
||||
{L"helloworld", L"hello\nworld"}, {L"hello world", L"helloworld"},
|
||||
{L"helloworld", L"hello світ"}, {L"helloworld", L"hello world!"},
|
||||
{L"helloworld", L"hello Hello"}, {L"helloworld", L""},
|
||||
{L"helloworld", L"abcdefghijklmnopqrstuvwxyz abcdef"}})
|
||||
{
|
||||
auto invalid = settings;
|
||||
invalid.autoReplacements = {{pair.first, pair.second}};
|
||||
@@ -761,6 +896,33 @@ int main(int argc, char **argv)
|
||||
ks::validateTesseract(options);
|
||||
require(true, "Windows OCR works without optional installation");
|
||||
}
|
||||
{
|
||||
ks::History h(temp/L"computer-origins");auto clip=ks::textClip(L"shared text");
|
||||
h.add(clip,L"editor",settings);
|
||||
h.add(clip,L"editor",settings,"peer-a",L"Office PC");
|
||||
h.add(clip,L"editor",settings,"peer-a",L"Office PC");
|
||||
require(h.entries().size()==2,"duplicate suppression preserves different clipboard sources");
|
||||
ks::History restored(temp/L"computer-origins");
|
||||
require(restored.entries().front().computer=="peer-a"&&restored.entries().front().computerName==L"Office PC","computer metadata survives history reload");
|
||||
require(restored.entries().back().computer.empty(),"legacy and local records remain local");
|
||||
}
|
||||
{
|
||||
ks::Pixels pixels{1920,1080,ks::Bytes(1920*1080*4,255)};
|
||||
for(size_t i=0;i<pixels.bgra.size();i+=4){pixels.bgra[i]=static_cast<unsigned char>((i/4)%1920/16);pixels.bgra[i+1]=static_cast<unsigned char>((i/4)/1920/16);}
|
||||
ks::Clip original;original.formats.push_back(ks::imageDib(pixels));
|
||||
original.formats.push_back({RegisterClipboardFormatW(L"PNG"),L"PNG",ks::encodePng(pixels)});
|
||||
auto packed=ks::lan::compactClipboardImage(original);
|
||||
require(packed.formats.size()==1&&packed.formats[0].name==L"PNG","LAN sends only one image format");
|
||||
require(packed.size()*10<original.size(),"screen-like image LAN payload reduced by more than 90 percent");
|
||||
require(ks::decodeImage(packed).bgra==pixels.bgra,"LAN PNG preserves exact pixels");
|
||||
auto paste=ks::lan::clipboardImageForPaste(packed);
|
||||
require(std::any_of(paste.formats.begin(),paste.formats.end(),[](const auto &f){return f.id==CF_DIB||f.id==CF_DIBV5;}),"LAN receiver restores a DIB for ordinary paste");
|
||||
original.formats.pop_back();
|
||||
require(ks::decodeImage(ks::lan::compactClipboardImage(original)).bgra==pixels.bgra,"DIB-only clipboard is losslessly compressed");
|
||||
auto text=ks::textClip(L"plain text");
|
||||
require(ks::encodeClip(ks::lan::compactClipboardImage(text))==ks::encodeClip(text),"LAN text clipboard remains unchanged");
|
||||
std::cout<<"LAN screenshot bytes: "<<original.size()<<" -> "<<packed.size()<<"\n";
|
||||
}
|
||||
// Test-owned directory only; never touch the user's clipboard or stored history.
|
||||
std::filesystem::remove_all(temp);
|
||||
CoUninitialize();
|
||||
|
||||
@@ -50,6 +50,9 @@ try {
|
||||
foreach ($name in @('LICENSE','json-LICENSE.txt','README.md')) { [IO.File]::WriteAllText((Join-Path $source $name),'fixture') }
|
||||
[IO.Directory]::CreateDirectory((Join-Path $source 'dictionaries')) | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $source 'dictionaries/en.txt'),'new dictionary')
|
||||
[IO.Directory]::CreateDirectory((Join-Path $source 'tools')) | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $source 'tools/README.txt'),'portable utilities instructions')
|
||||
[IO.File]::WriteAllText((Join-Path $source 'tools/StayHere.exe'),'bundled StayHere fixture')
|
||||
function Write-TestManifest($Folder) {
|
||||
$entries=@(Get-ChildItem -LiteralPath $Folder -File -Recurse | Where-Object Name -ne 'release-files.json' | ForEach-Object {
|
||||
@{path=$_.FullName.Substring($Folder.Length+1).Replace('\','/');size=$_.Length;sha256=(Get-FileHash -LiteralPath $_.FullName).Hash}
|
||||
@@ -92,8 +95,18 @@ try {
|
||||
$null=$z.CreateEntry('undeclared.dll'); $z.Dispose()
|
||||
Reject { Expand-Release $extra (Join-Path $root 'extrastage') $binaryVersion } 'undeclared file rejected'
|
||||
$target=Join-Path $root 'install'; $backup=Join-Path $root 'backup'
|
||||
$freshTarget=Join-Path $root 'fresh-install'
|
||||
[IO.Directory]::CreateDirectory($freshTarget) | Out-Null
|
||||
$freshChanges=[Collections.Generic.List[string]]::new()
|
||||
$freshStage=Join-Path $root 'fresh-stage'
|
||||
Copy-Item -LiteralPath $stage -Destination $freshStage -Recurse
|
||||
Install-Files $freshStage $freshTarget (Join-Path $root 'fresh-backup') $freshChanges
|
||||
Assert (Test-Path -LiteralPath (Join-Path $freshTarget 'tools/README.txt')) 'update creates portable tools folder'
|
||||
[IO.Directory]::CreateDirectory((Join-Path $target 'data')) | Out-Null
|
||||
[IO.Directory]::CreateDirectory((Join-Path $target 'dictionaries')) | Out-Null
|
||||
[IO.Directory]::CreateDirectory((Join-Path $target 'tools')) | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $target 'tools/Personal.exe'),'personal utility fixture')
|
||||
[IO.File]::WriteAllText((Join-Path $target 'tools/StayHere.exe'),'older StayHere fixture')
|
||||
[IO.File]::WriteAllText((Join-Path $target 'data/settings.json'),'personal settings')
|
||||
[IO.File]::WriteAllText((Join-Path $target 'dictionaries/en.txt'),'personal dictionary')
|
||||
[IO.File]::WriteAllText((Join-Path $target 'KSwitcher.exe'),'old binary fixture')
|
||||
@@ -105,9 +118,14 @@ try {
|
||||
}
|
||||
Assert ([IO.File]::ReadAllText((Join-Path $target 'future-tool.exe')) -eq 'future companion fixture') 'new companion name installs without changing updater'
|
||||
Assert ([IO.File]::ReadAllText((Join-Path $target 'data/settings.json')) -eq 'personal settings') 'settings preserved'
|
||||
Assert ([IO.File]::ReadAllText((Join-Path $target 'tools/Personal.exe')) -eq 'personal utility fixture') 'personal utilities preserved'
|
||||
Assert ([IO.File]::ReadAllText((Join-Path $target 'tools/README.txt')) -eq 'portable utilities instructions') 'bundled tools documentation installed'
|
||||
Assert ([IO.File]::ReadAllText((Join-Path $target 'tools/StayHere.exe')) -eq 'bundled StayHere fixture') 'bundled StayHere updated'
|
||||
Assert ([IO.File]::ReadAllText((Join-Path $target 'dictionaries/en.txt')) -eq 'personal dictionary') 'dictionary preserved'
|
||||
Undo-Files $target $backup $changed
|
||||
Assert ([IO.File]::ReadAllText((Join-Path $target 'KSwitcher.exe')) -eq 'old binary fixture') 'rollback restores original'
|
||||
Assert ([IO.File]::ReadAllText((Join-Path $target 'tools/Personal.exe')) -eq 'personal utility fixture') 'rollback preserves personal utilities'
|
||||
Assert ([IO.File]::ReadAllText((Join-Path $target 'tools/StayHere.exe')) -eq 'older StayHere fixture') 'rollback restores previous StayHere'
|
||||
Assert (!(Test-Path -LiteralPath (Join-Path $target 'README.md'))) 'rollback removes newly introduced files'
|
||||
Assert (!(Test-Path -LiteralPath (Join-Path $target 'KSwitcher.Config.exe'))) 'rollback removes newly introduced configurator'
|
||||
Assert (!(Test-Path -LiteralPath (Join-Path $target 'KSwitcher.Screenshot.exe'))) 'rollback removes newly introduced screenshot editor'
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
#include <windows.h>
|
||||
#include "../src/utilities.h"
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
int main()
|
||||
{
|
||||
namespace fs = std::filesystem;
|
||||
auto root = fs::temp_directory_path() / (L"KSwitcher-utilities-" + std::to_wstring(GetCurrentProcessId()));
|
||||
try
|
||||
{
|
||||
std::error_code error;
|
||||
if (!ks::discoverUtilities(root / L"missing", error).empty() || error)
|
||||
throw std::runtime_error("Missing folder must be empty, not an error");
|
||||
fs::create_directories(root / L"tools" / L"nested");
|
||||
fs::create_directory(root / L"tools" / L"directory.exe");
|
||||
for (auto name : {L"Zed.exe", L"alpha.EXE", L"A & B.exe", L"readme.txt", L"shortcut.lnk"})
|
||||
std::ofstream(root / L"tools" / name).put('x');
|
||||
std::ofstream(root / L"tools" / L"nested" / L"hidden.exe").put('x');
|
||||
auto found = ks::discoverUtilities(root / L"tools", error);
|
||||
if (error || found.size() != 3 || found[0].filename() != L"A & B.exe" ||
|
||||
found[1].filename() != L"alpha.EXE" || found[2].filename() != L"Zed.exe")
|
||||
throw std::runtime_error("Scan must filter direct executable files and sort names");
|
||||
if (ks::utilityMenuLabel(found[0]) != L"A && B")
|
||||
throw std::runtime_error("Ampersand must be displayed literally");
|
||||
fs::remove(found[1]);
|
||||
if (ks::discoverUtilities(root / L"tools", error).size() != 2)
|
||||
throw std::runtime_error("Scan must refresh after a file is removed");
|
||||
ks::discoverUtilities(root / L"tools" / L"readme.txt", error);
|
||||
if (!error) throw std::runtime_error("Non-directory must report an error");
|
||||
fs::remove_all(root);
|
||||
std::cout << "Utilities regression tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
std::error_code ignored;
|
||||
fs::remove_all(root, ignored);
|
||||
std::cerr << e.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
param([ValidateRange(1,20)][int]$Runs=3,[ValidateRange(100,10000)][int]$SettleMilliseconds=1500)
|
||||
# Private resident pages are counted externally, so the measurement buffer is
|
||||
# allocated in PowerShell, not in the measured process. Never trim working sets.
|
||||
$ErrorActionPreference='Stop'
|
||||
$root=Split-Path $PSScriptRoot -Parent
|
||||
$output=Join-Path $root 'build/memory-components'
|
||||
New-Item -ItemType Directory -Force $output | Out-Null
|
||||
$exe=Join-Path $output 'probe.exe'
|
||||
& "$root/.tools/w64devkit/bin/g++.exe" -std=c++20 -Os -static -s -DUNICODE -D_UNICODE -D_WIN32_WINNT=0x0A00 "$PSScriptRoot/memory-components.cpp" -o $exe -lole32 -loleaut32 -lshell32 -lpropsys -lshlwapi -luuid -luiautomationcore
|
||||
if($LASTEXITCODE) { throw 'Probe compilation failed' }
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class ComponentWorkingSet {
|
||||
[DllImport("psapi.dll", SetLastError=true)] static extern bool QueryWorkingSet(IntPtr process,IntPtr buffer,int size);
|
||||
public static long PrivateBytes(IntPtr process) {
|
||||
int size=4*1024*1024;
|
||||
IntPtr buffer=Marshal.AllocHGlobal(size);
|
||||
try {
|
||||
if(!QueryWorkingSet(process,buffer,size)) throw new System.ComponentModel.Win32Exception();
|
||||
long count=Marshal.ReadIntPtr(buffer).ToInt64(), pages=0;
|
||||
if(count>(size/IntPtr.Size)-1) throw new InvalidOperationException("Working set buffer is too small");
|
||||
for(int i=0;i<count;i++) if((Marshal.ReadIntPtr(buffer,(i+1)*IntPtr.Size).ToInt64() & 256)==0) pages++;
|
||||
return pages*Environment.SystemPageSize;
|
||||
} finally { Marshal.FreeHGlobal(buffer); }
|
||||
}
|
||||
}
|
||||
'@
|
||||
$rows=[Collections.Generic.List[object]]::new()
|
||||
foreach($run in 1..$Runs) {
|
||||
foreach($mode in @('baseline','sta','mta','shell','uia','focused','combined')) {
|
||||
$start=[Diagnostics.ProcessStartInfo]::new($exe,$mode)
|
||||
$start.UseShellExecute=$false; $start.CreateNoWindow=$true
|
||||
$start.RedirectStandardOutput=$true; $start.RedirectStandardInput=$true; $start.RedirectStandardError=$true
|
||||
$process=[Diagnostics.Process]::Start($start)
|
||||
$errors=$process.StandardError.ReadToEndAsync()
|
||||
try {
|
||||
foreach($expected in @('baseline','com','active','released','uninitialized')) {
|
||||
$pending=$process.StandardOutput.ReadLineAsync()
|
||||
if(!$pending.Wait(15000)) { throw "Timeout: $mode/$expected" }
|
||||
$phase=$pending.Result
|
||||
if($phase -ne $expected) { throw "Unexpected phase '$phase', expected $expected" }
|
||||
Start-Sleep -Milliseconds $SettleMilliseconds
|
||||
$process.Refresh()
|
||||
$rows.Add([pscustomobject]@{Run=$run;Mode=$mode;Phase=$phase;PrivateBytes=$process.PrivateMemorySize64;PrivateWorkingSet=[ComponentWorkingSet]::PrivateBytes($process.Handle);WorkingSet=$process.WorkingSet64;Threads=$process.Threads.Count;Modules=@($process.Modules | ForEach-Object ModuleName)})
|
||||
$process.StandardInput.Write("`n"); $process.StandardInput.Flush()
|
||||
}
|
||||
if(!$process.WaitForExit(15000)) { throw 'Exit timeout' }
|
||||
if($process.ExitCode) { throw "Probe failed: $($errors.Result)" }
|
||||
$errors.Result | Set-Content (Join-Path $output "$run-$mode.txt")
|
||||
} finally {
|
||||
if(!$process.HasExited) { $process.Kill(); $process.WaitForExit() }
|
||||
$process.Dispose()
|
||||
$rows | ConvertTo-Json -Depth 5 | Set-Content (Join-Path $output 'results.json')
|
||||
}
|
||||
Write-Host "Completed $run/$Runs $mode"
|
||||
}
|
||||
}
|
||||
$rows | Group-Object Mode,Phase | ForEach-Object {
|
||||
[pscustomobject]@{Case=$_.Name;PrivateMiB=[math]::Round(($_.Group.PrivateBytes | Measure-Object -Average).Average/1MB,3);PrivateWorkingSetMiB=[math]::Round(($_.Group.PrivateWorkingSet | Measure-Object -Average).Average/1MB,3)}
|
||||
} | Format-Table
|
||||
@@ -0,0 +1,65 @@
|
||||
// Standalone attribution probe. No clipboard, registry or user input mutations.
|
||||
#include <windows.h>
|
||||
#include <shlobj.h>
|
||||
#include <propkey.h>
|
||||
#include <propvarutil.h>
|
||||
#include <uiautomation.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
|
||||
static void check(HRESULT hr) {
|
||||
if (FAILED(hr)) { fprintf(stderr,"HRESULT=%08lx\n",(unsigned long)hr); exit(2); }
|
||||
}
|
||||
static void phase(const char *name) {
|
||||
printf("%s\n",name); fflush(stdout);
|
||||
if (getchar()==EOF) exit(3);
|
||||
}
|
||||
int main(int argc,char **argv) {
|
||||
const char *mode=argc>1?argv[1]:"baseline";
|
||||
const bool baseline=!strcmp(mode,"baseline");
|
||||
const bool shell=!strcmp(mode,"shell") || !strcmp(mode,"combined");
|
||||
const bool uia=!strcmp(mode,"uia") || !strcmp(mode,"focused") || !strcmp(mode,"combined");
|
||||
phase("baseline");
|
||||
if(!baseline) check(CoInitializeEx(nullptr,!strcmp(mode,"sta") || shell ? COINIT_APARTMENTTHREADED : COINIT_MULTITHREADED));
|
||||
phase("com");
|
||||
IShellLinkW *link{}; IPropertyStore *store{}; IPersistFile *file{};
|
||||
IUIAutomation2 *automation{}; IUIAutomationElement *element{}; IUIAutomationTextPattern *pattern{};
|
||||
wchar_t temporary[MAX_PATH]{},shortcut[MAX_PATH]{},exe[MAX_PATH]{};
|
||||
if(shell) {
|
||||
check(CoCreateInstance(CLSID_ShellLink,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&link)));
|
||||
GetModuleFileNameW(nullptr,exe,MAX_PATH);
|
||||
check(link->SetPath(exe)); check(link->SetIconLocation(exe,0));
|
||||
check(link->QueryInterface(IID_PPV_ARGS(&store)));
|
||||
PROPVARIANT value{}; check(InitPropVariantFromString(L"KSwitcher.MemoryProbe",&value));
|
||||
check(store->SetValue(PKEY_AppUserModel_ID,value)); PropVariantClear(&value);
|
||||
GUID id{0xe3f78047,0xf0ad,0x49b6,{0x90,0x74,0x41,0x19,0x31,0x70,0x61,0x67}};
|
||||
value.vt=VT_CLSID; value.puuid=&id;
|
||||
check(store->SetValue(PKEY_AppUserModel_ToastActivatorCLSID,value)); check(store->Commit());
|
||||
PWSTR programs{}; check(SHGetKnownFolderPath(FOLDERID_Programs,0,nullptr,&programs)); CoTaskMemFree(programs);
|
||||
GetTempPathW(MAX_PATH,temporary); if(!GetTempFileNameW(temporary,L"ksm",0,shortcut)) return 4;
|
||||
check(link->QueryInterface(IID_PPV_ARGS(&file))); check(file->Save(shortcut,TRUE));
|
||||
}
|
||||
if(uia) {
|
||||
check(CoCreateInstance(CLSID_CUIAutomation8,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&automation)));
|
||||
check(automation->put_ConnectionTimeout(200)); check(automation->put_TransactionTimeout(200));
|
||||
if(strcmp(mode,"uia")) {
|
||||
HRESULT focused=automation->GetFocusedElement(&element);
|
||||
fprintf(stderr,"focus=%08lx\n",(unsigned long)focused);
|
||||
if(SUCCEEDED(focused) && element) {
|
||||
BOOL password=TRUE,enabled=FALSE; CONTROLTYPEID type{};
|
||||
element->get_CurrentIsPassword(&password); element->get_CurrentIsEnabled(&enabled); element->get_CurrentControlType(&type);
|
||||
fprintf(stderr,"type=%d enabled=%d protected=%d\n",type,enabled,password);
|
||||
if(!password) fprintf(stderr,"pattern=%08lx\n",(unsigned long)element->GetCurrentPatternAs(UIA_TextPatternId,IID_PPV_ARGS(&pattern)));
|
||||
}
|
||||
}
|
||||
}
|
||||
phase("active");
|
||||
if(pattern) pattern->Release(); if(element) element->Release(); if(automation) automation->Release();
|
||||
if(file) file->Release(); if(store) store->Release(); if(link) link->Release();
|
||||
if(shortcut[0]) DeleteFileW(shortcut);
|
||||
phase("released");
|
||||
if(!baseline) { CoFreeUnusedLibrariesEx(0,0); CoUninitialize(); }
|
||||
phase("uninitialized");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# StayHere
|
||||
|
||||
Маленька портативна утиліта для Windows, без .NET та інсталяції.
|
||||
|
||||
Виберіть **Tools → StayHere** у меню трея (у v0.6.46 цей пункт називається Utilities)
|
||||
або запустіть `tools/StayHere.exe` поруч із KSwitcher.exe.
|
||||
Зелена крапка в треї означає, що підтримка активності ввімкнена.
|
||||
Клацання лівою кнопкою перемикає режим; правою — відкриває меню з перемикачем і виходом.
|
||||
Після кожного запуску режим увімкнений. Автозапуск не додається.
|
||||
|
||||
Раз на 15 секунд перевіряється час бездіяльності. Після 3 хвилин без вводу
|
||||
надсилається натискання й відпускання F15. Поки ви працюєте, клавіші не надсилаються.
|
||||
Курсор миші не рухається. Увімкнений режим також утримує екран і систему від
|
||||
автоматичного сну. На заблокованому екрані та у відключеному сеансі активність
|
||||
не імітується. Ручне блокування Windows не обходиться.
|
||||
|
||||
Механізм перенесено за поведінкою з Typlo. Він підтримує системну активність,
|
||||
але не керує статусом Teams через API: статус залежить також від Teams,
|
||||
календаря, інших пристроїв та політик організації. F15 може мати власне
|
||||
призначення в окремих програмах. На підвищених вікнах Windows може блокувати ввід;
|
||||
тоді підказка іконки показує помилку. Утиліта не запитує права адміністратора.
|
||||
|
||||
## Збірка
|
||||
|
||||
У репозиторії KSwitcher виконайте `./build.ps1 -Stage` з кореня проєкту.
|
||||
Утиліта збирається з `utilities/StayHere/main.cpp` у `build/staged/tools/StayHere.exe`
|
||||
і включається пакувальником у реліз. CMake також має ціль `StayHere`.
|
||||
Для запуску достатньо одного `StayHere.exe`; .NET не потрібний.
|
||||
|
||||
CLI: `--pause`, `--resume`, `--exit` керують запущеним екземпляром.
|
||||
`--status` повертає код 1 для активного режиму, 2 для паузи, 3 якщо утиліта не запущена.
|
||||
@@ -0,0 +1,238 @@
|
||||
#include <windows.h>
|
||||
#include <shellapi.h>
|
||||
#include <wtsapi32.h>
|
||||
#include <cwchar>
|
||||
#include <initializer_list>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
#ifdef STAYHERE_TEST_INSTANCE
|
||||
constexpr wchar_t ClassName[] = L"StayHere.Test.Tray.1";
|
||||
constexpr wchar_t MutexName[] = L"Local\\StayHere.Test.Tray.1";
|
||||
#else
|
||||
constexpr wchar_t ClassName[] = L"StayHere.Tray.1";
|
||||
constexpr wchar_t MutexName[] = L"Local\\StayHere.Tray.1";
|
||||
#endif
|
||||
constexpr UINT TrayMessage = WM_APP + 1;
|
||||
constexpr UINT ControlMessage = WM_APP + 2;
|
||||
constexpr UINT Toggle = 1, Quit = 2, Pause = 3, Resume = 4, Status = 5;
|
||||
constexpr DWORD IdleThreshold = 180000;
|
||||
bool enabled = true;
|
||||
bool sessionLocked = false;
|
||||
bool powerOk = true;
|
||||
bool inputOk = true;
|
||||
UINT taskbarCreated;
|
||||
HICON activeIcon, pausedIcon;
|
||||
NOTIFYICONDATAW tray{};
|
||||
|
||||
constexpr bool shouldSignal(bool active, bool unlocked, DWORD now, DWORD lastInput) {
|
||||
return active && unlocked && DWORD(now - lastInput) >= IdleThreshold;
|
||||
}
|
||||
static_assert(!shouldSignal(true, true, 179999, 0));
|
||||
static_assert(shouldSignal(true, true, 180000, 0));
|
||||
static_assert(!shouldSignal(false, true, 180000, 0));
|
||||
static_assert(!shouldSignal(true, false, 180000, 0));
|
||||
static_assert(shouldSignal(true, true, 179000, 0xfffffc18)); // tick counter wrap
|
||||
|
||||
bool interactiveDesktop() {
|
||||
if (sessionLocked) return false;
|
||||
HDESK desktop = OpenInputDesktop(0, FALSE, DESKTOP_READOBJECTS);
|
||||
if (!desktop) return false;
|
||||
wchar_t name[128]{};
|
||||
DWORD needed = 0;
|
||||
bool ok = GetUserObjectInformationW(desktop, UOI_NAME, name, sizeof(name), &needed)
|
||||
&& _wcsicmp(name, L"Default") == 0;
|
||||
CloseDesktop(desktop);
|
||||
if (!ok) return false;
|
||||
DWORD session;
|
||||
LPWSTR buffer = nullptr;
|
||||
DWORD bytes = 0;
|
||||
if (!ProcessIdToSessionId(GetCurrentProcessId(), &session)) return false;
|
||||
if (!WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, session, WTSConnectState, &buffer, &bytes)) return false;
|
||||
ok = bytes >= sizeof(WTS_CONNECTSTATE_CLASS)
|
||||
&& *reinterpret_cast<WTS_CONNECTSTATE_CLASS*>(buffer) == WTSActive;
|
||||
WTSFreeMemory(buffer);
|
||||
return ok;
|
||||
}
|
||||
|
||||
HICON makeIcon(COLORREF color) {
|
||||
HDC screen = GetDC(nullptr);
|
||||
HDC dc = CreateCompatibleDC(screen);
|
||||
HBITMAP bitmap = CreateCompatibleBitmap(screen, 32, 32);
|
||||
HGDIOBJ previous = SelectObject(dc, bitmap);
|
||||
RECT rect{0, 0, 32, 32};
|
||||
FillRect(dc, &rect, static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
|
||||
HBRUSH brush = CreateSolidBrush(color);
|
||||
HGDIOBJ oldBrush = SelectObject(dc, brush);
|
||||
HGDIOBJ oldPen = SelectObject(dc, GetStockObject(NULL_PEN));
|
||||
Ellipse(dc, 3, 3, 29, 29);
|
||||
SelectObject(dc, oldBrush);
|
||||
SelectObject(dc, oldPen);
|
||||
DeleteObject(brush);
|
||||
SelectObject(dc, previous);
|
||||
HBITMAP mask = CreateBitmap(32, 32, 1, 1, nullptr);
|
||||
HGDIOBJ maskPrevious = SelectObject(dc, mask);
|
||||
PatBlt(dc, 0, 0, 32, 32, WHITENESS);
|
||||
oldBrush = SelectObject(dc, GetStockObject(BLACK_BRUSH));
|
||||
oldPen = SelectObject(dc, GetStockObject(NULL_PEN));
|
||||
Ellipse(dc, 3, 3, 29, 29);
|
||||
SelectObject(dc, oldPen);
|
||||
SelectObject(dc, oldBrush);
|
||||
SelectObject(dc, maskPrevious);
|
||||
ICONINFO info{TRUE, 0, 0, mask, bitmap};
|
||||
HICON icon = CreateIconIndirect(&info);
|
||||
DeleteObject(bitmap);
|
||||
DeleteObject(mask);
|
||||
DeleteDC(dc);
|
||||
ReleaseDC(nullptr, screen);
|
||||
return icon;
|
||||
}
|
||||
|
||||
void updateTray() {
|
||||
tray.hIcon = enabled ? activeIcon : pausedIcon;
|
||||
const wchar_t* tip = !enabled ? L"StayHere — призупинено"
|
||||
: !powerOk ? L"StayHere — помилка утримання від сну"
|
||||
: !inputOk ? L"StayHere — не вдалося надіслати F15"
|
||||
: L"StayHere — активно (F15 після 3 хв простою)";
|
||||
lstrcpynW(tray.szTip, tip, ARRAYSIZE(tray.szTip));
|
||||
Shell_NotifyIconW(NIM_MODIFY, &tray);
|
||||
}
|
||||
|
||||
void setEnabled(bool value) {
|
||||
enabled = value;
|
||||
inputOk = true;
|
||||
powerOk = SetThreadExecutionState(ES_CONTINUOUS |
|
||||
(enabled && interactiveDesktop() ? ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED : 0)) != 0;
|
||||
updateTray();
|
||||
}
|
||||
|
||||
void tick() {
|
||||
const bool unlocked = interactiveDesktop();
|
||||
powerOk = SetThreadExecutionState(ES_CONTINUOUS |
|
||||
(enabled && unlocked ? ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED : 0)) != 0;
|
||||
LASTINPUTINFO idle{sizeof(idle), 0};
|
||||
if (GetLastInputInfo(&idle) && shouldSignal(enabled, unlocked, GetTickCount(), idle.dwTime)) {
|
||||
// Avoid inserting a key into a chord being held while the user is away.
|
||||
for (int key : {VK_SHIFT, VK_CONTROL, VK_MENU, VK_LWIN, VK_RWIN,
|
||||
VK_LBUTTON, VK_RBUTTON, VK_MBUTTON}) {
|
||||
if (GetAsyncKeyState(key) & 0x8000) return;
|
||||
}
|
||||
INPUT input[2]{};
|
||||
input[0].type = input[1].type = INPUT_KEYBOARD;
|
||||
input[0].ki.wVk = input[1].ki.wVk = VK_F15;
|
||||
input[1].ki.dwFlags = KEYEVENTF_KEYUP;
|
||||
inputOk = SendInput(2, input, sizeof(INPUT)) == 2;
|
||||
if (!inputOk) { // If only key-down succeeded, make a best effort to release it.
|
||||
SendInput(1, &input[1], sizeof(INPUT));
|
||||
}
|
||||
}
|
||||
updateTray();
|
||||
}
|
||||
|
||||
void showMenu(HWND window) {
|
||||
HMENU menu = CreatePopupMenu();
|
||||
AppendMenuW(menu, MF_STRING | (enabled ? MF_CHECKED : 0), Toggle, L"Підтримувати активність");
|
||||
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
|
||||
AppendMenuW(menu, MF_STRING, Quit, L"Вийти");
|
||||
POINT pos;
|
||||
GetCursorPos(&pos);
|
||||
SetForegroundWindow(window);
|
||||
UINT command = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_RIGHTBUTTON, pos.x, pos.y, 0, window, nullptr);
|
||||
DestroyMenu(menu);
|
||||
if (command) SendMessageW(window, ControlMessage, command, 0);
|
||||
PostMessageW(window, WM_NULL, 0, 0);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK windowProc(HWND window, UINT message, WPARAM wp, LPARAM lp) {
|
||||
if (message == taskbarCreated) {
|
||||
Shell_NotifyIconW(NIM_ADD, &tray);
|
||||
return 0;
|
||||
}
|
||||
switch (message) {
|
||||
case TrayMessage:
|
||||
if (lp == WM_RBUTTONUP || lp == WM_CONTEXTMENU) showMenu(window);
|
||||
else if (lp == WM_LBUTTONUP) setEnabled(!enabled);
|
||||
return 0;
|
||||
case ControlMessage:
|
||||
if (wp == Status) return enabled ? 1 : 2;
|
||||
if (wp == Toggle) setEnabled(!enabled);
|
||||
else if (wp == Pause) setEnabled(false);
|
||||
else if (wp == Resume) setEnabled(true);
|
||||
else if (wp == Quit) DestroyWindow(window);
|
||||
return 0;
|
||||
case WM_TIMER: tick(); return 0;
|
||||
case WM_WTSSESSION_CHANGE:
|
||||
if (wp == WTS_SESSION_LOCK || wp == WTS_REMOTE_DISCONNECT || wp == WTS_CONSOLE_DISCONNECT)
|
||||
sessionLocked = true;
|
||||
else if (wp == WTS_SESSION_UNLOCK || wp == WTS_REMOTE_CONNECT || wp == WTS_CONSOLE_CONNECT)
|
||||
sessionLocked = false;
|
||||
setEnabled(enabled);
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
KillTimer(window, 1);
|
||||
WTSUnRegisterSessionNotification(window);
|
||||
SetThreadExecutionState(ES_CONTINUOUS);
|
||||
Shell_NotifyIconW(NIM_DELETE, &tray);
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcW(window, message, wp, lp);
|
||||
}
|
||||
}
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int) {
|
||||
int argc{};
|
||||
auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
|
||||
if(!argv)return 10;
|
||||
const std::wstring argument=argc==2?argv[1]:L"";
|
||||
LocalFree(argv);
|
||||
if(argc>2)return 10;
|
||||
const auto commandLine=argument.c_str();
|
||||
UINT command = 0;
|
||||
if (wcscmp(commandLine, L"--pause") == 0) command = Pause;
|
||||
else if (wcscmp(commandLine, L"--resume") == 0) command = Resume;
|
||||
else if (wcscmp(commandLine, L"--exit") == 0) command = Quit;
|
||||
else if (wcscmp(commandLine, L"--status") == 0) command = Status;
|
||||
else if (*commandLine) return 10;
|
||||
HWND existing = FindWindowW(ClassName, nullptr);
|
||||
if (command) {
|
||||
if (!existing) return 3;
|
||||
DWORD_PTR result = 0;
|
||||
if (!SendMessageTimeoutW(existing, ControlMessage, command, 0, SMTO_ABORTIFHUNG, 2000, &result)) return 4;
|
||||
return command == Status ? static_cast<int>(result) : 0;
|
||||
}
|
||||
HANDLE mutex = CreateMutexW(nullptr, FALSE, MutexName);
|
||||
if (!mutex) return 5;
|
||||
if (GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(mutex); return 0; }
|
||||
taskbarCreated = RegisterWindowMessageW(L"TaskbarCreated");
|
||||
activeIcon = makeIcon(RGB(40, 185, 100));
|
||||
pausedIcon = makeIcon(RGB(135, 140, 150));
|
||||
WNDCLASSW wc{};
|
||||
wc.lpfnWndProc = windowProc;
|
||||
wc.hInstance = instance;
|
||||
wc.lpszClassName = ClassName;
|
||||
if (!RegisterClassW(&wc)) return 6;
|
||||
HWND window = CreateWindowExW(0, ClassName, L"StayHere", WS_OVERLAPPED,
|
||||
0, 0, 0, 0, nullptr, nullptr, instance, nullptr);
|
||||
if (!window) return 7;
|
||||
tray.cbSize = sizeof(tray);
|
||||
tray.hWnd = window;
|
||||
tray.uID = 1;
|
||||
tray.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
|
||||
tray.uCallbackMessage = TrayMessage;
|
||||
tray.hIcon = activeIcon;
|
||||
lstrcpyW(tray.szTip, L"StayHere");
|
||||
if (!Shell_NotifyIconW(NIM_ADD, &tray)) { DestroyWindow(window); return 8; }
|
||||
WTSRegisterSessionNotification(window, NOTIFY_FOR_THIS_SESSION);
|
||||
setEnabled(true);
|
||||
if (!SetTimer(window, 1, 15000, nullptr)) { DestroyWindow(window); return 9; }
|
||||
MSG msg{};
|
||||
while (GetMessageW(&msg, nullptr, 0, 0) > 0) {
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
DestroyIcon(activeIcon);
|
||||
DestroyIcon(pausedIcon);
|
||||
CloseHandle(mutex);
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user