Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0387904a0 | ||
|
|
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 | ||
|
|
ca553a5e7d | ||
|
|
55993c0f90 | ||
|
|
738c81dce2 | ||
|
|
22edece7cf | ||
|
|
908985d775 | ||
|
|
20f3b72287 |
No files matched your search
+130
-3
@@ -1,14 +1,28 @@
|
|||||||
cmake_minimum_required(VERSION 3.24)
|
cmake_minimum_required(VERSION 3.24)
|
||||||
project(KSwitcher VERSION 0.6.23 LANGUAGES CXX RC)
|
project(KSwitcher VERSION 0.6.58 LANGUAGES CXX RC)
|
||||||
if(NOT WIN32)
|
if(NOT WIN32)
|
||||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||||
endif()
|
endif()
|
||||||
set(CMAKE_CXX_STANDARD 20)
|
set(CMAKE_CXX_STANDARD 20)
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
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)
|
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_include_directories(kscore PUBLIC src PRIVATE vendor)
|
||||||
target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
|
target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
|
||||||
target_link_libraries(kscore PUBLIC 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)
|
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_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
|
||||||
target_link_libraries(KSwitcher PRIVATE kscore)
|
target_link_libraries(KSwitcher PRIVATE kscore)
|
||||||
@@ -17,11 +31,28 @@ set_target_properties(KSwitcherConfig PROPERTIES OUTPUT_NAME "KSwitcher.Config")
|
|||||||
target_compile_definitions(KSwitcherConfig PRIVATE KS_CONFIG_APP)
|
target_compile_definitions(KSwitcherConfig PRIVATE KS_CONFIG_APP)
|
||||||
target_link_libraries(KSwitcherConfig PRIVATE kscore)
|
target_link_libraries(KSwitcherConfig PRIVATE kscore)
|
||||||
add_executable(KSwitcherTests tests/tests.cpp)
|
add_executable(KSwitcherTests tests/tests.cpp)
|
||||||
|
add_executable(KSwitcherSyncTests tests/sync.cpp)
|
||||||
|
target_include_directories(KSwitcherSyncTests PRIVATE vendor)
|
||||||
|
target_link_libraries(KSwitcherSyncTests PRIVATE kscore)
|
||||||
|
if(MSVC)
|
||||||
|
set_property(TARGET KSwitcherSyncTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||||
|
else()
|
||||||
|
target_link_options(KSwitcherSyncTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||||
|
endif()
|
||||||
add_executable(KSwitcherScrollTests tests/scroll.cpp)
|
add_executable(KSwitcherScrollTests tests/scroll.cpp)
|
||||||
target_link_libraries(KSwitcherScrollTests PRIVATE kscore)
|
target_link_libraries(KSwitcherScrollTests PRIVATE kscore)
|
||||||
target_link_libraries(KSwitcherTests 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)
|
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)
|
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)
|
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_link_libraries(KSwitcherInputTests PRIVATE kscore)
|
||||||
target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES)
|
target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES)
|
||||||
@@ -40,6 +71,7 @@ else()
|
|||||||
endif()
|
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)
|
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)
|
target_link_libraries(KSwitcherOcrTests PRIVATE kscore)
|
||||||
|
add_dependencies(KSwitcherOcrTests KSwitcherScreenshot)
|
||||||
if(MSVC)
|
if(MSVC)
|
||||||
set_property(TARGET kscore KSwitcher KSwitcherConfig KSwitcherScreenshot KSwitcherTests KSwitcherScrollTests KSwitcherIntegration KSwitcherInputTests KSwitcherOcrTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
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)
|
target_compile_options(kscore PRIVATE /W4 /utf-8)
|
||||||
@@ -57,7 +89,84 @@ else()
|
|||||||
target_link_options(KSwitcherOcrTests PRIVATE -static -static-libgcc -static-libstdc++)
|
target_link_options(KSwitcherOcrTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||||
endif()
|
endif()
|
||||||
enable_testing()
|
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_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 scroll-regressions COMMAND KSwitcherScrollTests)
|
||||||
add_test(NAME input-regressions COMMAND KSwitcherInputTests)
|
add_test(NAME input-regressions COMMAND KSwitcherInputTests)
|
||||||
add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests)
|
add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests)
|
||||||
@@ -69,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")
|
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 .)
|
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)
|
||||||
+122
@@ -0,0 +1,122 @@
|
|||||||
|
# LAN mouse, keyboard and clipboard — v0.6.58 (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.58 or newer on every participating PC. Input protocol v2 requires all participants to update; earlier one-pair builds cannot connect. Preserve local data; do not copy pairing identities between PCs.
|
||||||
|
2. Open Settings → 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.
|
||||||
|
|
||||||
|
## v0.6.58 connection fixes
|
||||||
|
|
||||||
|
Saved trust keeps TCP listeners available even when discovery announcements are missed. Working authenticated input sessions no longer depend on discovery presence. Pair saved is distinct from input connected; the list refreshes every second. A changed instance ID requires a new pairing. Keep each PC's own data folder during upgrades. Connection state changes and listener Windows errors are written to the diagnostic log.
|
||||||
@@ -10,12 +10,54 @@ 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.
|
[Donate via Monobank](https://send.monobank.ua/jar/88h2TddKfS) · Thank you for supporting KSwitcher.
|
||||||
|
|
||||||
|
## KSwitcher computers — v0.6.58 (experimental)
|
||||||
|
|
||||||
|
TCP input listeners and authenticated connections survive missed discovery announcements.
|
||||||
|
The list distinguishes saved pairing from connected input and refreshes every second.
|
||||||
|
Keep each PC’s own data folder during updates; a different instance ID requires new pairing.
|
||||||
|
|
||||||
|
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.58:** 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.58, залишивши кожному
|
||||||
|
власну папку 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
|
||||||
|
|
||||||
Run `build/KSwitcher.exe`, or extract `dist/KSwitcher-win-x64.zip` and run the executable.
|
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 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.
|
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.
|
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. 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.
|
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.
|
Repeated launches activate the existing configurator; closing its last window exits that process.
|
||||||
Saving applies changes immediately through the resident KSwitcher process. The configurator does not
|
Saving applies changes immediately through the resident KSwitcher process. The configurator does not
|
||||||
@@ -65,6 +107,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
|
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.
|
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
|
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
|
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
|
is accepted, including key-up events and VK-only keyboard events. Unicode packets do not provide
|
||||||
@@ -111,10 +156,10 @@ change its diameter. Wheel up increases the size; wheel down decreases it. These
|
|||||||
and update linked arrows. **Ctrl+D** clones the selected object with a small offset. A cloned number
|
and update linked arrows. **Ctrl+D** clones the selected object with a small offset. A cloned number
|
||||||
gets the smallest available positive number, just like a newly placed number: gaps left by deletion
|
gets the smallest available positive number, just like a newly placed number: gaps left by deletion
|
||||||
are filled first, without renumbering existing objects. A cloned arrow keeps its style but starts without endpoint links.
|
are filled first, without renumbering existing objects. A cloned arrow keeps its style but starts without endpoint links.
|
||||||
Arrow and line endpoints can attach to numbered markers, rectangles, circles, ellipses, text blocks,
|
Arrow and line endpoints can attach to numbered markers, rectangles, circles, ellipses, triangles, trapezoids, text blocks,
|
||||||
and other arrows or strokes. In Arrow or Straight line mode, hold **Ctrl** and drag from one object
|
and other arrows or strokes. In Arrow or Straight line mode, hold **Ctrl** and drag from one object
|
||||||
to another to draw over them and automatically attach both endpoints. Without Ctrl, existing objects
|
to another to draw over them and automatically attach both endpoints. Without Ctrl, existing objects
|
||||||
can still be selected and edited as before. With Pointer, drag an existing endpoint onto a target to attach it. Attached endpoints follow movement and resizing; text attachments
|
can still be selected and edited as before. With Pointer, drag an existing endpoint onto a target to attach it. Attached endpoints follow movement and resizing; shape and text attachments
|
||||||
also follow rotation. Arrow-to-arrow attachments retain their relative position along the target line.
|
also follow rotation. Arrow-to-arrow attachments retain their relative position along the target line.
|
||||||
Clicking a connector or adding/editing its caption preserves its links. Moving the whole connector
|
Clicking a connector or adding/editing its caption preserves its links. Moving the whole connector
|
||||||
intentionally detaches its endpoints; moving one endpoint detaches only that end. Deleting a target
|
intentionally detaches its endpoints; moving one endpoint detaches only that end. Deleting a target
|
||||||
@@ -162,7 +207,57 @@ resize; circles keep equal width and height. Move shapes by their outlines, adju
|
|||||||
the mouse wheel or side handle, recolor, clone with Ctrl+D, and undo/redo as with other objects.
|
the mouse wheel or side handle, recolor, clone with Ctrl+D, and undo/redo as with other objects.
|
||||||
Hold Ctrl to start drawing over an existing object. Line style applies to outlines; Ends is disabled
|
Hold Ctrl to start drawing over an existing object. Line style applies to outlines; Ends is disabled
|
||||||
for shapes.
|
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. 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.
|
||||||
|
|
||||||
**Freehand line (F)** draws an opaque curve by following the mouse. The curve is one object:
|
**Freehand line (F)** draws an opaque curve by following the mouse. The curve is one object:
|
||||||
|
after mouse release, nearly straight strokes become editable straight lines at their drawn angle,
|
||||||
|
preserving endpoints, color, thickness, line style and arrowheads. Short strokes, broad curves and
|
||||||
|
retraced strokes are not straightened. Other strokes receive light smoothing to reduce jitter.
|
||||||
|
Confidently recognized closed outlines become
|
||||||
|
rectangles, circles, ellipses, triangles or trapezoids (including tilted outlines), stored as shape objects.
|
||||||
|
Drag either bounding-box corner handle to resize the entire recognized outline; circles keep equal
|
||||||
|
width and height. Shapes can also be moved, recolored and cloned.
|
||||||
|
Every shape has a round rotation handle above its outline. Drag it to rotate around the center;
|
||||||
|
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.
|
||||||
|
Oval fitting tolerates uneven contours and small closing gaps or overlaps; broad open arcs and
|
||||||
|
repeated loops remain freehand strokes.
|
||||||
|
Press **Ctrl+Z** once to restore the original stroke, again to remove it; **Ctrl+Y** reapplies the improvement.
|
||||||
|
Small strokes, strokes linked to other objects, and any stroke drawn partly with Shift are left unchanged.
|
||||||
|
Ambiguous shapes are only smoothed. To edit the resulting curve,
|
||||||
move it, change its color or thickness, clone it, or drag its endpoints. Hold Ctrl to start a new
|
move it, change its color or thickness, clone it, or drag its endpoints. Hold Ctrl to start a new
|
||||||
stroke over an existing object. Hold **Shift** while drawing to constrain the current segment
|
stroke over an existing object. Hold **Shift** while drawing to constrain the current segment
|
||||||
to a horizontal, vertical or 45-degree diagonal line; release Shift to resume freehand drawing in the same stroke.
|
to a horizontal, vertical or 45-degree diagonal line; release Shift to resume freehand drawing in the same stroke.
|
||||||
@@ -223,6 +318,80 @@ thumbnails and source labels aligned with the scaled fonts and spacing.
|
|||||||
|
|
||||||
## Implemented
|
## 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.
|
- 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
|
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.
|
that changes it. If none changes the text, the operation keeps the text and advances one layout.
|
||||||
@@ -230,13 +399,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.
|
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).
|
- 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.
|
- 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.
|
- 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
|
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.
|
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.
|
- 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
|
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
|
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.
|
- Case cycling, Russian/Ukrainian transliteration, verified undo and repeated conversion.
|
||||||
- Text snippets across layouts, multiline insertion and a verified `{cursor}` position;
|
- 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.
|
`{enter}` presses Enter after insertion and cursor placement (once per marker), before buffered typing resumes.
|
||||||
@@ -286,6 +473,10 @@ existing saved shortcuts are preserved. While KSwitcher runs, this binding opens
|
|||||||
|
|
||||||
History controls: Enter to paste, Shift+Enter for plain text, Ctrl+1…9 for quick paste,
|
History controls: Enter to paste, Shift+Enter for plain text, Ctrl+1…9 for quick paste,
|
||||||
Ctrl+P to pin/unpin, Delete to delete, Ctrl+O for the full item, Escape to hide.
|
Ctrl+P to pin/unpin, Delete to delete, Ctrl+O for the full item, Escape to hide.
|
||||||
|
|
||||||
|
**Clear history… / Alt+H** in the history window clears all saved entries after confirmation,
|
||||||
|
including pinned entries and entries hidden by search. No is the default choice. The current
|
||||||
|
Windows clipboard and future recording are unchanged. Settings also retains its Clear history action.
|
||||||
For an image, **Edit image**, **Ctrl+O**, or **Edit image in screenshot editor**
|
For an image, **Edit image**, **Ctrl+O**, or **Edit image in screenshot editor**
|
||||||
in the context menu opens the original image in the built-in screenshot editor.
|
in the context menu opens the original image in the built-in screenshot editor.
|
||||||
Annotate it there, then copy the result. Opening the editor leaves the
|
Annotate it there, then copy the result. Opening the editor leaves the
|
||||||
@@ -301,7 +492,14 @@ the executable's directory is not writable. Each clipboard payload is an encrypt
|
|||||||
only bounded previews/metadata stay in memory. Image data is loaded on demand and released when
|
only bounded previews/metadata stay in memory. Image data is loaded on demand and released when
|
||||||
the history popup is hidden. Settings **Write log** (`writeLog`, enabled by default) controls all
|
the history popup is hidden. Settings **Write log** (`writeLog`, enabled by default) controls all
|
||||||
log writes. Disabling it also clears diagnostic context from memory; existing log files remain.
|
log writes. Disabling it also clears diagnostic context from memory; existing log files remain.
|
||||||
Diagnostic stages stay in a memory buffer of at most 40 events for 30 seconds.
|
Diagnostic stages stay in a memory buffer of at most 128 events for 30 seconds.
|
||||||
|
Selection diagnostics include the expected text, each copied candidate before and after suffix
|
||||||
|
recovery, paced Shift+Left progress or batch delivery counts, and clipboard sequence changes,
|
||||||
|
retry counts and elapsed times. Focus, caret geometry and keyboard layout are recorded when
|
||||||
|
Windows exposes them; selection offsets are available for native EDIT controls and explicitly
|
||||||
|
marked unavailable for other editors. Input interruptions identify keyboard, mouse, settings
|
||||||
|
or layout-refresh events during an operation. Failed selection verification includes the expected
|
||||||
|
selection and actual copied text in the operation details, without implying that a paste occurred.
|
||||||
Only problem operations write a structured summary to `kswitcher.log`, with their preceding
|
Only problem operations write a structured summary to `kswitcher.log`, with their preceding
|
||||||
context. Successful operations stay in that bounded memory buffer and are included only when
|
context. Successful operations stay in that bounded memory buffer and are included only when
|
||||||
a subsequent problem flushes it; they do not create separate rows. Flushed context is discarded. Ordinary application
|
a subsequent problem flushes it; they do not create separate rows. Flushed context is discarded. Ordinary application
|
||||||
@@ -353,6 +551,143 @@ This is a working native implementation, not a claim of complete UI/release pari
|
|||||||
The Windows focus/injection rules still apply: an unelevated process cannot edit an elevated app.
|
The Windows focus/injection rules still apply: an unelevated process cannot edit an elevated app.
|
||||||
Conversion is cancelled rather than pasting into a different window or replacing unverified recent text.
|
Conversion is cancelled rather than pasting into a different window or replacing unverified recent text.
|
||||||
|
|
||||||
|
## OpenBao synchronization (experimental, opt-in)
|
||||||
|
|
||||||
|
The **Sync...** button is available in Settings for everyone. Synchronization remains disabled
|
||||||
|
until you configure your own OpenBao and enable it. Connection configuration is saved separately
|
||||||
|
in `sync.json`. The portable data directory is normally `data/` beside the executable; installations
|
||||||
|
without a writable application directory use the existing local-app-data fallback.
|
||||||
|
No server address or account is included in the application.
|
||||||
|
|
||||||
|
The first provider is **OpenBao KV v2**. The dialog accepts an HTTPS server origin, username,
|
||||||
|
password, KV mount (default `kswitcher`), profile path (default `personal/settings`) and userpass
|
||||||
|
authentication mount (default `userpass`). Use the same profile on each of your PCs. This is
|
||||||
|
administrator-provisioned private access, not public account registration. Non-root namespaces,
|
||||||
|
reverse-proxy URL prefixes, MFA login flows and other providers are not implemented yet.
|
||||||
|
|
||||||
|
Enable synchronization and choose **Save / Sign in / Sync**. The dialog saves connection changes
|
||||||
|
immediately; the main Settings window's Save/Cancel does not control this separate configuration.
|
||||||
|
When synchronization is disabled, connection fields and sync actions are inactive. Check **Enable
|
||||||
|
synchronization** to make them available. To disable an existing connection, uncheck it and click
|
||||||
|
**Save**; this preserves the saved connection and password without starting a sync request.
|
||||||
|
**Disconnect / forget password** remains available while synchronization is disabled.
|
||||||
|
A blank password keeps the existing Windows credential for that server, login mount and username.
|
||||||
|
The password is saved in Windows Credential Manager, not in settings exports, logs or the remote
|
||||||
|
profile. HTTPS certificate validation is mandatory and redirects are refused. Login tokens are
|
||||||
|
kept in memory for one sync attempt, with best-effort self-revocation afterwards. Configure bounded
|
||||||
|
token lifetimes on the server as well (for example a 5-minute default and 10-minute maximum).
|
||||||
|
**Disconnect / forget password** disables synchronization and removes the current connection's
|
||||||
|
saved credential. A request already sent to the server may still complete; its downloaded settings
|
||||||
|
will not be applied after the connection changes. Old credentials for other connection identities
|
||||||
|
can be removed in Windows Credential Manager under `KSwitcher.Sync/`.
|
||||||
|
|
||||||
|
On the first connection, **Save / Sign in / Sync** merges the existing profiles without
|
||||||
|
requiring a whole-profile replacement. Independent entries (such as snippets, exclusions and
|
||||||
|
replacement pairs) are combined. Different values for the same setting remain on their respective
|
||||||
|
sides and appear in **Resolve individual conflicts...**; no value is guessed without a common history.
|
||||||
|
Nonconflicting changes synchronize immediately, and unresolved conflicts survive subsequent syncs.
|
||||||
|
|
||||||
|
- **Upload local** creates the remote profile or replaces it with this PC's saved shared settings.
|
||||||
|
- **Download remote** replaces this PC's shared settings with the server profile.
|
||||||
|
- If the server has no profile yet, choose **Upload local** to create it.
|
||||||
|
- Unsaved edits in Settings are not synchronized. Close and reopen Settings after a download;
|
||||||
|
the existing stale-editor check prevents an old Settings window overwriting downloaded changes.
|
||||||
|
|
||||||
|
Once connected, the resident checks at startup, every **10 minutes**, and about two seconds after saving settings, on a separate
|
||||||
|
network thread. Errors back off for 15 minutes; the Sync button allows a manual retry. Local use
|
||||||
|
continues offline. Independent changes to different settings fields are merged against the last
|
||||||
|
successful baseline. **Resolve individual conflicts...** shows the name and local/server values
|
||||||
|
for each conflict. Choose either value for selected settings and apply your choices; unselected
|
||||||
|
conflicts stay pending. Other, nonconflicting changes continue to synchronize. Choices are checked
|
||||||
|
against freshly read values before writing, so a stale dialog cannot overwrite a newer edit.
|
||||||
|
Conflicting shortcuts are separate settings, including bindings for individual keyboard layouts.
|
||||||
|
Exclusions and personal dictionary words merge by membership. Ordered layout/dictionary lists
|
||||||
|
remain single settings because their ordering affects behavior.
|
||||||
|
|
||||||
|
Snippets have persistent IDs that survive renaming. Different snippets merge independently;
|
||||||
|
trigger and text edits within a snippet can merge too. Deleting a snippet retains a deletion
|
||||||
|
marker, so an unchanged offline copy cannot bring it back. Deletion versus a concurrent edit
|
||||||
|
is an explicit conflict, offering the deleted or edited version. Duplicate triggers and shortcut
|
||||||
|
collisions created by independent edits are also presented for resolution. Deletion markers are
|
||||||
|
retained without automatic expiry; recreating a snippet in the editor gives it a new ID.
|
||||||
|
|
||||||
|
Existing profiles migrate automatically: legacy snippet IDs derive deterministically from the
|
||||||
|
original trigger, then are stored permanently. Sync writes use envelope version 2; older clients
|
||||||
|
refuse this version instead of dropping IDs/deletions. Update all participating PCs before using
|
||||||
|
the new merge behavior. Existing version-1 profiles and local baselines remain readable.
|
||||||
|
|
||||||
|
Download/Upload are still available for deliberate whole-profile recovery/initialization, not
|
||||||
|
required for ordinary conflicts. Every server write uses the version just read as a CAS
|
||||||
|
condition, including explicit Upload. A racing write is rejected rather than silently overwritten.
|
||||||
|
Deleted server versions are not silently recreated.
|
||||||
|
|
||||||
|
Hotkeys, snippets, application exclusions, layout order, conversion, screenshot and autocorrection
|
||||||
|
preferences are shared. Startup/elevation, keep-awake, logging, history enablement/limits,
|
||||||
|
Tesseract executable/engine selection, connection details and credentials stay local. Clipboard
|
||||||
|
history, screenshots and dictionary files are never uploaded. Full synchronization identifies
|
||||||
|
missing keyboard layouts by language (when Windows can identify it) and exact ID.
|
||||||
|
Install the same layout variant, or select **Keep this PC's layouts and layout shortcuts (sync
|
||||||
|
other settings)** and click **Save / Sign in / Sync**. This device-local option keeps the entire
|
||||||
|
local layout cycle and its direct shortcuts unchanged while synchronizing the other shared settings.
|
||||||
|
The server's layout cycle and direct shortcuts are preserved on automatic sync and explicit Upload;
|
||||||
|
Download also keeps the local layout configuration. Later syncs cannot erase missing server layouts
|
||||||
|
just because this PC does not have them installed. Uncheck the option to resume full layout sync.
|
||||||
|
Settings are JSON inside OpenBao; this is not end-to-end encryption from the vault administrator.
|
||||||
|
|
||||||
|
The last common profile (`sync-base.bin`) and the settings preceding the most recent downloaded
|
||||||
|
change (`settings-before-sync.bin`) are protected with Windows DPAPI and belong to this Windows
|
||||||
|
account/machine. Reinstallation recovery uses the remote profile and a fresh login; copying these
|
||||||
|
local DPAPI files to a new machine does not recover them. For an older server snapshot, use OpenBao
|
||||||
|
KV version history to restore that snapshot as the latest version, then choose Download remote.
|
||||||
|
The app does not yet provide a server-history browser. Keep ordinary server backups too.
|
||||||
|
|
||||||
|
OpenBao administrator setup:
|
||||||
|
|
||||||
|
1. Enable a KV **version 2** engine at `kswitcher`; enable **Require Check-and-Set** and set
|
||||||
|
maximum versions to a suitable value, such as 30.
|
||||||
|
2. Create a dedicated userpass account, with a policy restricted to the chosen profile. Do not
|
||||||
|
use the administrator account. For the defaults, the application needs only:
|
||||||
|
|
||||||
|
```hcl
|
||||||
|
path "kswitcher/data/personal/settings" {
|
||||||
|
capabilities = ["create", "read", "update"]
|
||||||
|
}
|
||||||
|
path "auth/token/revoke-self" {
|
||||||
|
capabilities = ["update"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Set bounded token lifetimes on that account/auth mount and enter its credentials in KSwitcher.
|
||||||
|
Keep the server's address and TLS certificate reachable/trusted on each participating PC.
|
||||||
|
|
||||||
|
`SyncProvider` separates versioned read/conditional-write operations from merging, local state
|
||||||
|
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
|
## Build
|
||||||
|
|
||||||
The easiest reproducible local route uses the pinned portable w64devkit toolchain:
|
The easiest reproducible local route uses the pinned portable w64devkit toolchain:
|
||||||
@@ -372,13 +707,44 @@ Alternatively open this directory as a CMake project in Visual Studio with the C
|
|||||||
and Windows SDK installed, or use CMake with a Windows GCC toolchain. CMake/MSVC is provided but the
|
and Windows SDK installed, or use CMake with a Windows GCC toolchain. CMake/MSVC is provided but the
|
||||||
verified local build uses GCC/w64devkit.
|
verified local build uses GCC/w64devkit.
|
||||||
|
|
||||||
## Automatic layout correction (experimental)
|
## Automatic correction (experimental)
|
||||||
|
|
||||||
Enable **Automatically correct layout (experimental)** in Settings, then use **Auto-correction
|
Enable **Automatic correction (experimental)** in Settings, then use **Auto-correction
|
||||||
options…** to select dictionary languages and edit excluded applications or words to never correct.
|
options…** to select dictionary languages and edit excluded applications or words to never correct.
|
||||||
The feature is off by default. English and Ukrainian are selected initially; Russian is optional.
|
The feature is off by default. English and Ukrainian are selected initially; Russian is optional.
|
||||||
Target layouts must also be enabled in the layout cycle.
|
Target layouts must also be enabled in the layout cycle.
|
||||||
|
|
||||||
|
### Custom replacements and spelling typos
|
||||||
|
|
||||||
|
Two optional modes in **Auto-correction options…** extend layout correction. Both are off by
|
||||||
|
default and require the main **Automatic correction (experimental)** checkbox to be enabled.
|
||||||
|
|
||||||
|
- **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. 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
|
||||||
|
by inserting, deleting or replacing one letter, or swapping two adjacent letters. Both input
|
||||||
|
and target must have at least four letters. Multiple candidates leave the input unchanged,
|
||||||
|
even if a frequency limit would exclude one of them. Personal dictionary words participate.
|
||||||
|
This is word-level spelling correction, not grammar or sentence-context correction.
|
||||||
|
|
||||||
|
Both modes run after Space, preserve surrounding punctuation and an initial capital, and keep
|
||||||
|
the current layout. The selected dictionary languages, enabled layout cycle, minimum input
|
||||||
|
length, excluded applications, never-correct list, protected fields and Undo behavior apply.
|
||||||
|
ALL CAPS, mixed-case identifiers, numbers, URLs and email addresses are skipped. A replacement
|
||||||
|
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
|
||||||
|
|
||||||
**Characters before a word** and **Characters after a word** configure punctuation to preserve around
|
**Characters before a word** and **Characters after a word** configure punctuation to preserve around
|
||||||
the corrected word. Enter characters directly, without spaces or separators; a comma or semicolon
|
the corrected word. Enter characters directly, without spaces or separators; a comma or semicolon
|
||||||
is itself a character. Defaults include parentheses, square/curly brackets, quotation marks and common
|
is itself a character. Defaults include parentheses, square/curly brackets, quotation marks and common
|
||||||
@@ -428,7 +794,12 @@ support automatic correction. Dictionary recognition is heuristic, not an unders
|
|||||||
subtitle vocabulary is incomplete, and uncommon names or jargon can need personal exceptions.
|
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;
|
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
|
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
|
[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/`.
|
CC BY-SA 4.0; attribution, pinned source revision and license are in `dictionaries/`.
|
||||||
@@ -444,6 +815,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 -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 -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 -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
|
.\tests\configuration.ps1 # Separate-process settings tests; close KSwitcher first
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -499,3 +871,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.
|
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
|
Keep the compatibility bridge in the first 100 releases returned by Gitea while
|
||||||
supporting old clients; their immutable update code only reads that page.
|
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.
+12
-19
@@ -1,30 +1,23 @@
|
|||||||
# Latest Windows release
|
# Latest Windows release
|
||||||
|
|
||||||
## v0.6.23 — 2026-11-01
|
## v0.6.58 — 2026-11-06
|
||||||
|
|
||||||
## Changes
|
## Changes
|
||||||
- Add Ukrainian `поточні` to the bundled dictionary: `Gjnjxys ` and `Поточны ` can become `Поточні ` with Ukrainian enabled. Supplemental rank 50001 is included by the default unlimited frequency setting.
|
- Keep trusted TCP input listeners and connections alive across missing discovery announcements. Retain the last known address for reconnection; authenticate incoming trusted peers even before discovery sees their address.
|
||||||
- Use paced selection in Chrome and Edge, as already used for Teams/WebView, to reduce incomplete selections during recent-text conversion, repeat conversion and Undo. Full verification remains mandatory.
|
- Show saved pairing separately from actual input connectivity: connected, disabled here, offline or not connected. Background identity verification does not flash the list.
|
||||||
- Save annotated screenshots as full-resolution PNG with **Save… / Ctrl+S**. The first save asks for a destination; later saves update it. **Ctrl+Shift+S** opens Save As. Saving keeps the editor open and does not change the clipboard. Closing warns about changes not saved or copied.
|
- Log TCP listener failures with the Windows error and peer connection state changes for troubleshooting.
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
423 native regressions, 473 input/UI checks, shared wheel handling, screenshot editor UI, PNG save regressions, notification registration, 48 updater checks and updater progress checks passed.
|
Passed: 205 LAN input checks (including missed discovery and authentication before discovery), 289 clipboard transfer, 43 pairing, 829 settings/chat UI, 570 input, 341 native, 126 sync and 5 settings-save merge checks; dictionary equivalence for 140,939 words; wheel, StayHere, Utilities, screenshot UI/save/registration, 54 updater checks and updater progress. LAN remains experimental; three physical PCs have not been verified together.
|
||||||
|
|
||||||
## Limitations
|
Update both PCs to receive these fixes. Preserve each PC's own data directory and pairing identity. Input protocol v2 remains compatible with v0.6.57. A changed instance ID requires pairing again. The computer list refreshes automatically once per second while open.
|
||||||
The reported Chrome editor failure has not yet been verified live after the selection change. Existing clipboard/accessibility restrictions and paste readback limitations remain. Automatic correction runs after Space and requires a dictionary match.
|
|
||||||
|
|
||||||
**Dictionary upgrade:** the updater preserves existing dictionaries, so an older installation may not receive the new word automatically. Add `поточні` under **Settings → Auto-correction options → My dictionary → Ukrainian**, then click **OK → Save**. Personal words work at any frequency rank limit. Back up custom dictionary files before replacing them manually.
|
## 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.
|
||||||
|
|
||||||
**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.
|
**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.
|
||||||
For manual installation, exit KSwitcher, close screenshot editors and extract the entire ZIP into its installation folder. Keep personal `data/` and customized dictionaries.
|
|
||||||
|
|
||||||
Download **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**. The package contains all three executables, a release manifest, offline dictionaries, documentation and license notices. It contains no personal settings, clipboard history, Tesseract installation or language models.
|
Download **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**. The package contains no personal settings, credentials or clipboard history.
|
||||||
|
|
||||||
Build and package:
|
Publish stable `release-vX.Y.Z` tags matching the executable version. Keep `v0.4.2` as the last legacy tag.
|
||||||
|
|
||||||
```powershell
|
|
||||||
.\build.ps1 -Stage -Test
|
|
||||||
.\package.ps1 -PublishRelease
|
|
||||||
```
|
|
||||||
|
|
||||||
Commit the archive, checksum and sources together. Publish both assets on a stable `release-vX.Y.Z` tag matching the executable version. Keep `v0.4.2` as the last legacy tag.
|
|
||||||
@@ -1 +1 @@
|
|||||||
414604b295912ad466c1a6c6b6ff85b032b9e4480bf115c249885cef60817475 KSwitcher-win-x64.zip
|
16d8138c63442931bf947707b28820d9b89943169ac9f25db3cb50d23c0ff319 KSwitcher-win-x64.zip
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
{
|
||||||
|
"files": [
|
||||||
|
{
|
||||||
|
"sha256": "a7be2f749082bb6417b4cf7e8c8ea221ef4f7ba63dabc3cbbe8694ab1a3d942c",
|
||||||
|
"path": "KSwitcher.exe",
|
||||||
|
"size": 2108416
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "c8a88364c9967ce5fd150519d632b14460e225a0cfae51a8de50f39782d8010c",
|
||||||
|
"path": "KSwitcher.Config.exe",
|
||||||
|
"size": 2005504
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "68eed5abefed0208ef7bdd431094c7357c53bd3ca03dfd91aaeb7dbb4f291e06",
|
||||||
|
"path": "KSwitcher.Screenshot.exe",
|
||||||
|
"size": 3153408
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||||
|
"path": "LICENSE",
|
||||||
|
"size": 4401
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||||
|
"path": "json-LICENSE.txt",
|
||||||
|
"size": 1096
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "87f396a6bf988725b14bf5b6eb7c2b60ce33ff51828290ce40e136c66942cc09",
|
||||||
|
"path": "README.md",
|
||||||
|
"size": 80168
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "72e131bdf46d32a8a17fb352292bc8983c0e5a7ed84812218b11cf6b69c9afc4",
|
||||||
|
"path": "LAN-PREVIEW.md",
|
||||||
|
"size": 8376
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||||
|
"path": "dictionaries/en.txt",
|
||||||
|
"size": 732485
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||||
|
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||||
|
"size": 20566
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||||
|
"path": "dictionaries/README.md",
|
||||||
|
"size": 2265
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||||
|
"path": "dictionaries/ru.txt",
|
||||||
|
"size": 1109134
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||||
|
"path": "dictionaries/sources.json",
|
||||||
|
"size": 1280
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||||
|
"path": "dictionaries/uk.txt",
|
||||||
|
"size": 940799
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||||
|
"path": "tools/README.txt",
|
||||||
|
"size": 993
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
|
||||||
|
"path": "tools/StayHere.exe",
|
||||||
|
"size": 134656
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||||
|
"path": "tools/StayHere-README.md",
|
||||||
|
"size": 2796
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"schema": 1,
|
||||||
|
"version": "0.6.58"
|
||||||
|
}
|
||||||
@@ -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'
|
$ErrorActionPreference = 'Stop'
|
||||||
$root = $PSScriptRoot
|
$root = $PSScriptRoot
|
||||||
$compiler = Join-Path $root '.tools\w64devkit\bin\g++.exe'
|
$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
|
Push-Location $root
|
||||||
try {
|
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')
|
$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 = @('-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore')
|
$libs = @('-lws2_32','-lbcrypt','-liphlpapi','-lwinhttp','-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore')
|
||||||
foreach ($name in @('core','platform','autostart','autocorrect','storage','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) {
|
$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"
|
& $compiler @common -c "src/$name.cpp" -o "build/$name.o"
|
||||||
if ($LASTEXITCODE) { throw "Compilation failed: $name" }
|
if ($LASTEXITCODE) { throw "Compilation failed: $name" }
|
||||||
}
|
}
|
||||||
@@ -29,31 +35,67 @@ try {
|
|||||||
& windres --codepage=65001 -DKS_SCREENSHOT_RESOURCES resources/app.rc -O coff -o build/screenshot-res.o
|
& windres --codepage=65001 -DKS_SCREENSHOT_RESOURCES resources/app.rc -O coff -o build/screenshot-res.o
|
||||||
if ($LASTEXITCODE) { throw 'Screenshot resource compilation failed' }
|
if ($LASTEXITCODE) { throw 'Screenshot resource compilation failed' }
|
||||||
New-Item -ItemType Directory -Force build/release | Out-Null
|
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/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' }
|
if ($LASTEXITCODE) { throw 'Link failed' }
|
||||||
Copy-Item -LiteralPath $executablePath -Destination build/release/KSwitcher.exe -Force
|
Copy-Item -LiteralPath $executablePath -Destination build/release/KSwitcher.exe -Force
|
||||||
$configPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Config.exe'
|
$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/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' }
|
if ($LASTEXITCODE) { throw 'Configurator link failed' }
|
||||||
Copy-Item -LiteralPath $configPath -Destination build/release/KSwitcher.Config.exe -Force
|
Copy-Item -LiteralPath $configPath -Destination build/release/KSwitcher.Config.exe -Force
|
||||||
$screenshotPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Screenshot.exe'
|
$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' }
|
if ($LASTEXITCODE) { throw 'Screenshot link failed' }
|
||||||
Copy-Item -LiteralPath $screenshotPath -Destination build/release/KSwitcher.Screenshot.exe -Force
|
Copy-Item -LiteralPath $screenshotPath -Destination build/release/KSwitcher.Screenshot.exe -Force
|
||||||
if ($Test) {
|
if ($Test) {
|
||||||
|
& $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' }
|
||||||
& $compiler @common tests/scroll.cpp @libs -static -s -o build/KSwitcherScrollTests.exe
|
& $compiler @common tests/scroll.cpp @libs -static -s -o build/KSwitcherScrollTests.exe
|
||||||
if ($LASTEXITCODE) { throw 'Scroll test build failed' }
|
if ($LASTEXITCODE) { throw 'Scroll test build failed' }
|
||||||
& .\build\KSwitcherScrollTests.exe
|
& .\build\KSwitcherScrollTests.exe
|
||||||
if ($LASTEXITCODE) { throw 'Scroll tests failed' }
|
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/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' }
|
if ($LASTEXITCODE) { throw 'Test build failed' }
|
||||||
& .\build\KSwitcherTests.exe
|
& .\build\KSwitcherTests.exe
|
||||||
if ($LASTEXITCODE) { throw 'Tests failed' }
|
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/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' }
|
if ($LASTEXITCODE) { throw 'Input test build failed' }
|
||||||
& .\build\KSwitcherInputTests.exe
|
& .\build\KSwitcherInputTests.exe
|
||||||
if ($LASTEXITCODE) { throw 'Input tests failed' }
|
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' }
|
if ($LASTEXITCODE) { throw 'Screenshot UI test build failed' }
|
||||||
& .\build\KSwitcherScreenshotUITests.exe
|
& .\build\KSwitcherScreenshotUITests.exe
|
||||||
if ($LASTEXITCODE) { throw 'Screenshot UI tests failed' }
|
if ($LASTEXITCODE) { throw 'Screenshot UI tests failed' }
|
||||||
@@ -61,7 +103,7 @@ try {
|
|||||||
if ($LASTEXITCODE) { throw 'Screenshot save tests failed' }
|
if ($LASTEXITCODE) { throw 'Screenshot save tests failed' }
|
||||||
$registrationTest = Join-Path (Split-Path $executablePath) 'KSwitcherRegistrationTests.exe'
|
$registrationTest = Join-Path (Split-Path $executablePath) 'KSwitcherRegistrationTests.exe'
|
||||||
try {
|
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' }
|
if ($LASTEXITCODE) { throw 'Screenshot registration test build failed' }
|
||||||
& $registrationTest
|
& $registrationTest
|
||||||
if ($LASTEXITCODE) { throw 'Screenshot registration tests failed' }
|
if ($LASTEXITCODE) { throw 'Screenshot registration tests failed' }
|
||||||
@@ -72,16 +114,43 @@ try {
|
|||||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File tests/update_progress.ps1
|
& "$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 ($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) {
|
if ($Integration) {
|
||||||
& $compiler @common tests/integration.cpp build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.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' }
|
if ($LASTEXITCODE) { throw 'Integration test build failed' }
|
||||||
& .\build\KSwitcherIntegration.exe
|
& .\build\KSwitcherIntegration.exe
|
||||||
if ($LASTEXITCODE) { throw 'Integration tests failed' }
|
if ($LASTEXITCODE) { throw 'Integration tests failed' }
|
||||||
}
|
}
|
||||||
if ($Ocr) {
|
if ($Ocr) {
|
||||||
& $compiler @common tests/ocr.cpp build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.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' }
|
if ($LASTEXITCODE) { throw 'OCR test build failed' }
|
||||||
& .\build\KSwitcherOcrTests.exe
|
& $ocrTest
|
||||||
if ($LASTEXITCODE) { throw 'OCR tests failed' }
|
if ($LASTEXITCODE) { throw 'OCR tests failed' }
|
||||||
}
|
}
|
||||||
foreach ($folder in @('build/dictionaries','build/release/dictionaries','build/staged/dictionaries')) {
|
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 'LICENSE') -Destination $destination
|
||||||
Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -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 '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
|
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.
|
# 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) {
|
$entries = foreach ($path in $files) {
|
||||||
foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) {
|
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()}
|
@{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
|
@{schema=1; version=$version; files=@($entries)} | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $manifest -Encoding utf8
|
||||||
$files += $manifest
|
$files += $manifest
|
||||||
$archive = Join-Path $root 'dist\KSwitcher-win-x64.zip'
|
$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
|
Get-FileHash -LiteralPath $archive -Algorithm SHA256
|
||||||
if ($PublishRelease) {
|
if ($PublishRelease) {
|
||||||
$release = Join-Path $root 'Release'
|
$release = Join-Path $root 'Release'
|
||||||
|
|||||||
+3
-3
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
|||||||
1 RT_MANIFEST "app.manifest"
|
1 RT_MANIFEST "app.manifest"
|
||||||
201 RCDATA "update.ps1"
|
201 RCDATA "update.ps1"
|
||||||
1 VERSIONINFO
|
1 VERSIONINFO
|
||||||
FILEVERSION 0,6,23,0
|
FILEVERSION 0,6,58,0
|
||||||
PRODUCTVERSION 0,6,23,0
|
PRODUCTVERSION 0,6,58,0
|
||||||
FILEOS VOS_NT_WINDOWS32
|
FILEOS VOS_NT_WINDOWS32
|
||||||
FILETYPE VFT_APP
|
FILETYPE VFT_APP
|
||||||
BEGIN
|
BEGIN
|
||||||
@@ -20,7 +20,7 @@ BEGIN
|
|||||||
BEGIN
|
BEGIN
|
||||||
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
||||||
VALUE "ProductName", "KSwitcher"
|
VALUE "ProductName", "KSwitcher"
|
||||||
VALUE "FileVersion", "0.6.23"
|
VALUE "FileVersion", "0.6.58"
|
||||||
END
|
END
|
||||||
END
|
END
|
||||||
BLOCK "VarFileInfo"
|
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.
|
||||||
+738
-78
File diff suppressed because it is too large.
Load diff
@@ -2,6 +2,9 @@
|
|||||||
#include "autocorrect.h"
|
#include "autocorrect.h"
|
||||||
#include "storage.h"
|
#include "storage.h"
|
||||||
#include "update.h"
|
#include "update.h"
|
||||||
|
#include "sync.h"
|
||||||
|
#include "chat_context.h"
|
||||||
|
#include "lan.h"
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <deque>
|
#include <deque>
|
||||||
@@ -32,6 +35,12 @@ class App
|
|||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
HWND window{}, historyWindow{}, settingsWindow{}, snippetsWindow{};
|
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{};
|
HINSTANCE instance{};
|
||||||
std::filesystem::path data;
|
std::filesystem::path data;
|
||||||
std::vector<Layout> layouts;
|
std::vector<Layout> layouts;
|
||||||
@@ -40,7 +49,7 @@ class App
|
|||||||
AutoCorrector autoCorrector;
|
AutoCorrector autoCorrector;
|
||||||
AutoCorrector autoPredictor; // Preloaded, hook-thread-only lookup; no file access while typing.
|
AutoCorrector autoPredictor; // Preloaded, hook-thread-only lookup; no file access while typing.
|
||||||
std::atomic<bool> busy{false}, suspended{false};
|
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<uint64_t> inputVersion{0};
|
||||||
std::atomic<ULONGLONG> pauseUntil{0};
|
std::atomic<ULONGLONG> pauseUntil{0};
|
||||||
HWND pasteTarget{};
|
HWND pasteTarget{};
|
||||||
@@ -54,7 +63,7 @@ class App
|
|||||||
bool smoke{};
|
bool smoke{};
|
||||||
int startCommand{};
|
int startCommand{};
|
||||||
std::wstring updateStartupEvent;
|
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();
|
~App();
|
||||||
int execute();
|
int execute();
|
||||||
void dispatch(int);
|
void dispatch(int);
|
||||||
@@ -62,6 +71,8 @@ class App
|
|||||||
void pasteEntry(std::wstring, bool plain);
|
void pasteEntry(std::wstring, bool plain);
|
||||||
void recognizeEntry(std::wstring);
|
void recognizeEntry(std::wstring);
|
||||||
void captureHistory();
|
void captureHistory();
|
||||||
|
void publishClipboard(Clip, const std::wstring &);
|
||||||
|
void receiveClipboard();
|
||||||
void enqueue(std::function<void()>);
|
void enqueue(std::function<void()>);
|
||||||
void enqueueHistorySearch(std::function<void()>);
|
void enqueueHistorySearch(std::function<void()>);
|
||||||
void report(const std::wstring &);
|
void report(const std::wstring &);
|
||||||
@@ -71,22 +82,36 @@ class App
|
|||||||
void applySettings(const Settings &);
|
void applySettings(const Settings &);
|
||||||
void reloadLayouts();
|
void reloadLayouts();
|
||||||
void clearHistory();
|
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 clearLog(bool previous);
|
||||||
void setHotkeyCapture(HWND);
|
void setHotkeyCapture(HWND);
|
||||||
bool isHotkey(DWORD, UINT);
|
bool isHotkey(DWORD, UINT);
|
||||||
void keyboard(const KBDLLHOOKSTRUCT &, UINT modifiers);
|
void keyboard(const KBDLLHOOKSTRUCT &, UINT modifiers);
|
||||||
bool handleKeyboard(const KBDLLHOOKSTRUCT &, bool down, UINT modifiers);
|
bool handleKeyboard(const KBDLLHOOKSTRUCT &, bool down, UINT modifiers);
|
||||||
void resetInput();
|
void resetInput();
|
||||||
|
void resetLanInput();
|
||||||
void checkUpdate(bool interactive, bool install = false, const std::wstring &version = {});
|
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;
|
static App *current;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
friend struct InputRegressionAccess;
|
friend struct InputRegressionAccess;
|
||||||
|
void releaseIdleMemory(ULONGLONG now);
|
||||||
HHOOK keyboardHook{}, mouseHook{};
|
HHOOK keyboardHook{}, mouseHook{};
|
||||||
|
std::unique_ptr<LanService> lanService;
|
||||||
|
HANDLE historyProcess{};
|
||||||
std::mutex jobsMutex;
|
std::mutex jobsMutex;
|
||||||
std::condition_variable jobsReady;
|
std::condition_variable jobsReady;
|
||||||
std::deque<std::function<void()>> jobs;
|
std::deque<std::function<void()>> jobs;
|
||||||
std::thread worker;
|
std::thread worker;
|
||||||
|
HANDLE notificationRegistration{};
|
||||||
std::thread historySearchWorker;
|
std::thread historySearchWorker;
|
||||||
std::condition_variable historySearchReady;
|
std::condition_variable historySearchReady;
|
||||||
std::function<void()> pendingHistorySearch;
|
std::function<void()> pendingHistorySearch;
|
||||||
@@ -96,6 +121,16 @@ class App
|
|||||||
Settings historyOcrSettings;
|
Settings historyOcrSettings;
|
||||||
void scheduleHistoryOcr(const Settings &);
|
void scheduleHistoryOcr(const Settings &);
|
||||||
std::thread updateWorker;
|
std::thread updateWorker;
|
||||||
|
std::thread syncWorker;
|
||||||
|
std::atomic<bool> syncDone{false};
|
||||||
|
bool syncRunning{};
|
||||||
|
ULONGLONG nextSync{}, syncRetryAfter{};
|
||||||
|
SyncResult syncResult;
|
||||||
|
SyncConfig syncConnection;
|
||||||
|
SyncConfig conflictConnection;
|
||||||
|
std::vector<SyncConflict> pendingSyncConflicts;
|
||||||
|
Bytes syncSnapshot;
|
||||||
|
std::wstring syncStatus = L"Not connected.";
|
||||||
bool updateRunning{}, installingUpdate{};
|
bool updateRunning{}, installingUpdate{};
|
||||||
std::wstring availableUpdate, notifiedUpdate;
|
std::wstring availableUpdate, notifiedUpdate;
|
||||||
bool (*updateNotifier)(const std::wstring &){};
|
bool (*updateNotifier)(const std::wstring &){};
|
||||||
@@ -107,6 +142,11 @@ class App
|
|||||||
int previousAttemptCommand{}, repeatAttempts{};
|
int previousAttemptCommand{}, repeatAttempts{};
|
||||||
std::vector<std::pair<int, Hotkey>> hookBindings;
|
std::vector<std::pair<int, Hotkey>> hookBindings;
|
||||||
HotkeyHook hotkeyHook;
|
HotkeyHook hotkeyHook;
|
||||||
|
ChatSwitchHook chatSwitchHook;
|
||||||
|
HWND chatWindow{};
|
||||||
|
std::wstring activeChat, activeChatTitle;
|
||||||
|
void refreshChatContext();
|
||||||
|
void switchChatLayout(bool reverse);
|
||||||
HWND typingTarget{};
|
HWND typingTarget{};
|
||||||
bool autoPending{};
|
bool autoPending{};
|
||||||
int snippetPending = -1;
|
int snippetPending = -1;
|
||||||
@@ -116,6 +156,7 @@ class App
|
|||||||
void replayTyping();
|
void replayTyping();
|
||||||
static LRESULT CALLBACK windowProc(HWND, UINT, WPARAM, LPARAM);
|
static LRESULT CALLBACK windowProc(HWND, UINT, WPARAM, LPARAM);
|
||||||
static LRESULT CALLBACK keyProc(int, WPARAM, LPARAM);
|
static LRESULT CALLBACK keyProc(int, WPARAM, LPARAM);
|
||||||
|
static LRESULT keyboardAfterHooks(int, WPARAM, LPARAM, LRESULT);
|
||||||
static LRESULT CALLBACK mouseProc(int, WPARAM, LPARAM);
|
static LRESULT CALLBACK mouseProc(int, WPARAM, LPARAM);
|
||||||
};
|
};
|
||||||
void showHistory(App &, bool visible = true);
|
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.
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
// Included by app.cpp; all App mutations happen on its window thread.
|
||||||
|
Bytes App::syncConflictData()
|
||||||
|
{
|
||||||
|
if (loadSyncConfig(data) != conflictConnection) return encodeSyncConflicts({});
|
||||||
|
return encodeSyncConflicts(pendingSyncConflicts);
|
||||||
|
}
|
||||||
|
std::wstring App::syncCommand(int action, const std::vector<SyncChoice> &choices)
|
||||||
|
{
|
||||||
|
if (action == 0) return syncStatus;
|
||||||
|
if (syncRunning) return L"Synchronization is already running.";
|
||||||
|
auto c = loadSyncConfig(data);
|
||||||
|
if (!c.enabled) return syncStatus = L"Synchronization is disabled.";
|
||||||
|
validateSyncConfig(c);
|
||||||
|
if (action == 4 && (c != conflictConnection || choices.empty()))
|
||||||
|
throw std::runtime_error("Connection changed or no choices selected. Sync again.");
|
||||||
|
if (busy) return L"Wait for the current text operation to finish.";
|
||||||
|
syncRetryAfter = 0; // Explicit retries may bypass the automatic error backoff.
|
||||||
|
if (syncWorker.joinable()) syncWorker.join();
|
||||||
|
syncConnection = c;
|
||||||
|
syncSnapshot = encodeSettings(settings);
|
||||||
|
auto snapshot = settings;
|
||||||
|
auto availableLayouts = layouts;
|
||||||
|
syncRunning = true;
|
||||||
|
syncDone = false;
|
||||||
|
syncStatus = L"Connecting to OpenBao...";
|
||||||
|
nextSync = GetTickCount64() + SyncIntervalMs;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
syncWorker = std::thread([this, c, snapshot, availableLayouts, action, choices] {
|
||||||
|
SyncResult result;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
auto provider = makeSyncProvider(c);
|
||||||
|
// An explicit choice also repairs a missing/corrupt local baseline.
|
||||||
|
auto base = action == 1 || action == 4 ? loadSyncBase(data, c) : Bytes{};
|
||||||
|
result = synchronize(*provider, base, sharedSyncSettings(snapshot),
|
||||||
|
action == 2 ? SyncAction::Download : action == 3 ? SyncAction::Upload : SyncAction::Automatic,
|
||||||
|
[&](const Bytes &b) { restoreSyncSettings(b, snapshot, availableLayouts, c.keepLocalLayouts); }, choices,
|
||||||
|
c.keepLocalLayouts);
|
||||||
|
if (result.success && c.keepLocalLayouts)
|
||||||
|
result.status += L" Partial sync: this PC's layouts and their shortcuts were kept; server layouts were preserved.";
|
||||||
|
}
|
||||||
|
catch (const nlohmann::json::exception &) { result.status = L"Invalid sync data or server response."; }
|
||||||
|
catch (const std::exception &e) { result.status = wide(e.what()); }
|
||||||
|
syncResult = std::move(result);
|
||||||
|
syncDone.store(true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (...) { syncRunning = false; Bytes().swap(syncSnapshot); syncResult = {}; throw; }
|
||||||
|
return syncStatus;
|
||||||
|
}
|
||||||
|
void App::pollSync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (syncRunning && syncDone.load())
|
||||||
|
{
|
||||||
|
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 = result.status;
|
||||||
|
if (result.success)
|
||||||
|
{
|
||||||
|
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(result.settings, settings, layouts, syncConnection.keepLocalLayouts);
|
||||||
|
if (encodeSettings(next) != snapshot)
|
||||||
|
{
|
||||||
|
atomicWrite(data / L"settings-before-sync.bin", protect(snapshot));
|
||||||
|
applySettings(next);
|
||||||
|
}
|
||||||
|
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]{};
|
||||||
|
swprintf(stamp, std::size(stamp), L" (%02u:%02u:%02u)", time.wHour, time.wMinute, time.wSecond);
|
||||||
|
syncStatus += stamp;
|
||||||
|
}
|
||||||
|
// Back off after errors (including bad credentials) instead of repeatedly
|
||||||
|
// hitting userpass lockout. The explicit Sync button remains available.
|
||||||
|
syncRetryAfter = result.success ? 0 : GetTickCount64() + 15 * 60000;
|
||||||
|
nextSync = result.success ? GetTickCount64() + SyncIntervalMs : syncRetryAfter;
|
||||||
|
}
|
||||||
|
if (!syncRunning && GetTickCount64() >= nextSync)
|
||||||
|
{
|
||||||
|
nextSync = GetTickCount64() + SyncIntervalMs;
|
||||||
|
if (loadSyncConfig(data).enabled) syncCommand(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (const nlohmann::json::exception &) { syncStatus = L"Invalid local sync configuration or cached profile."; nextSync = GetTickCount64() + SyncIntervalMs; }
|
||||||
|
catch (const std::exception &e) { syncStatus = wide(e.what()); nextSync = GetTickCount64() + SyncIntervalMs; }
|
||||||
|
}
|
||||||
+187
-44
@@ -42,82 +42,160 @@ bool safeAutoWord(const std::wstring &word, int minimumLength)
|
|||||||
auto small = lower(word);
|
auto small = lower(word);
|
||||||
return word == small || (word.substr(1) == small.substr(1) && word != upper(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];
|
size_t start = offsets[block];
|
||||||
auto end = bytes.find('\t', start);
|
// Every block starts with a complete word (zero shared prefix).
|
||||||
return std::string_view(bytes).substr(start, end - start);
|
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)
|
AutoCorrector::Dictionary::Dictionary(const std::filesystem::path &path)
|
||||||
{
|
{
|
||||||
auto raw = readFile(path, 2 * 1024 * 1024);
|
const auto raw = readFile(path, 2 * 1024 * 1024);
|
||||||
bytes.assign(raw.begin(), raw.end());
|
const std::string_view source(reinterpret_cast<const char *>(raw.data()), raw.size());
|
||||||
for (size_t start = 0; start < bytes.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);
|
auto end = source.find('\n', start);
|
||||||
if (end == bytes.npos)
|
if (end == source.npos) end = source.size();
|
||||||
end = bytes.size();
|
auto tab = source.find('\t', start);
|
||||||
auto tab = bytes.find('\t', start);
|
if (tab == source.npos || tab >= end || tab == start || tab - start > 160)
|
||||||
if (tab == bytes.npos || tab >= end || tab == start || tab - start > 160)
|
|
||||||
throw std::runtime_error("Invalid auto-correction dictionary");
|
throw std::runtime_error("Invalid auto-correction dictionary");
|
||||||
int rank{};
|
int rank{};
|
||||||
auto rankEnd = end > tab + 1 && bytes[end - 1] == '\r' ? end - 1 : end;
|
auto rankEnd = end > tab + 1 && source[end - 1] == '\r' ? end - 1 : end;
|
||||||
auto parse = std::from_chars(bytes.data() + tab + 1, bytes.data() + rankEnd, rank);
|
auto parse = std::from_chars(source.data() + tab + 1, source.data() + rankEnd, rank);
|
||||||
if (parse.ec != std::errc() || parse.ptr != bytes.data() + rankEnd || rank <= 0)
|
if (parse.ec != std::errc() || parse.ptr != source.data() + rankEnd || rank <= 0)
|
||||||
throw std::runtime_error("Invalid dictionary rank");
|
throw std::runtime_error("Invalid dictionary rank");
|
||||||
offsets.push_back((uint32_t)start);
|
lines.push_back(static_cast<uint32_t>(start));
|
||||||
start = end + 1;
|
start = end + 1;
|
||||||
}
|
}
|
||||||
if (offsets.empty())
|
if (lines.empty()) throw std::runtime_error("Empty auto-correction dictionary");
|
||||||
throw std::runtime_error("Empty auto-correction dictionary");
|
auto entry = [&](uint32_t offset) { return source.substr(offset, source.find('\t', offset) - offset); };
|
||||||
auto entry = [&](uint32_t offset) { return std::string_view(bytes).substr(offset, bytes.find('\t', offset) - offset); };
|
auto frequency = [&](uint32_t offset) {
|
||||||
auto frequency = [&](uint32_t offset)
|
|
||||||
{
|
|
||||||
int rank{};
|
int rank{};
|
||||||
auto start = offset + entry(offset).size() + 1;
|
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;
|
return rank;
|
||||||
};
|
};
|
||||||
std::sort(offsets.begin(), offsets.end(), [&](uint32_t a, uint32_t b)
|
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); });
|
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());
|
lines.erase(std::unique(lines.begin(), lines.end(), [&](uint32_t a, uint32_t b) {
|
||||||
offsets.shrink_to_fit();
|
return entry(a) == entry(b);
|
||||||
bytes.shrink_to_fit();
|
}), 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
|
int AutoCorrector::Dictionary::rank(const std::wstring &text) const
|
||||||
{
|
{
|
||||||
auto key = utf8(lower(text));
|
auto key = utf8(lower(text));
|
||||||
size_t begin = 0, end = offsets.size();
|
size_t begin = 0, end = offsets.size();
|
||||||
|
// Find the last block whose first word is <= the search key.
|
||||||
while (begin < end)
|
while (begin < end)
|
||||||
{
|
{
|
||||||
auto mid = begin + (end - begin) / 2;
|
auto mid = begin + (end - begin) / 2;
|
||||||
if (word(mid) < key)
|
if (word(mid) <= key) begin = mid + 1;
|
||||||
begin = mid + 1;
|
else end = mid;
|
||||||
else
|
|
||||||
end = mid;
|
|
||||||
}
|
}
|
||||||
if (begin == offsets.size() || word(begin) != key)
|
if (!begin) return 0;
|
||||||
return 0;
|
size_t block = begin - 1;
|
||||||
auto start = offsets[begin] + word(begin).size() + 1;
|
size_t at = offsets[block];
|
||||||
int rank{};
|
const size_t limit = begin < offsets.size() ? offsets[begin] : bytes.size();
|
||||||
std::from_chars(bytes.data() + start, bytes.data() + bytes.size(), rank);
|
char decoded[160]; // The loader validates lengths; lookup never allocates a decoded word.
|
||||||
return rank;
|
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)
|
void AutoCorrector::configure(const std::filesystem::path &folder, const std::vector<std::wstring> &wanted)
|
||||||
{
|
{
|
||||||
if (languages == wanted)
|
if (languages == wanted)
|
||||||
return;
|
return;
|
||||||
std::map<std::wstring, Dictionary> next;
|
std::map<std::wstring, std::shared_ptr<const Dictionary>> next;
|
||||||
for (auto &lang : wanted)
|
for (auto &lang : wanted)
|
||||||
{
|
{
|
||||||
if (lang != L"en" && lang != L"uk" && lang != L"ru")
|
if (lang != L"en" && lang != L"uk" && lang != L"ru")
|
||||||
throw std::runtime_error("Unsupported dictionary language");
|
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);
|
dictionaries = std::move(next);
|
||||||
languages = wanted;
|
languages = wanted;
|
||||||
}
|
}
|
||||||
|
void AutoCorrector::shareDictionaries(const AutoCorrector &source)
|
||||||
|
{
|
||||||
|
dictionaries = source.dictionaries;
|
||||||
|
languages = source.languages;
|
||||||
|
}
|
||||||
void AutoCorrector::reject(std::wstring word, const Settings &settings)
|
void AutoCorrector::reject(std::wstring word, const Settings &settings)
|
||||||
{
|
{
|
||||||
while (!word.empty() && openingDelimiter(word.front(), settings))
|
while (!word.empty() && openingDelimiter(word.front(), settings))
|
||||||
@@ -132,7 +210,7 @@ size_t AutoCorrector::memoryBytes() const
|
|||||||
{
|
{
|
||||||
size_t bytes = 0;
|
size_t bytes = 0;
|
||||||
for (auto &[language, d] : dictionaries)
|
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;
|
return bytes;
|
||||||
}
|
}
|
||||||
std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed, int source,
|
std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed, int source,
|
||||||
@@ -164,6 +242,24 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
|||||||
auto sourceLanguage = layoutLanguage(layouts[source]);
|
auto sourceLanguage = layoutLanguage(layouts[source]);
|
||||||
if (!dictionaries.contains(sourceLanguage))
|
if (!dictionaries.contains(sourceLanguage))
|
||||||
return {};
|
return {};
|
||||||
|
const std::wstring alphabet = sourceLanguage == L"en" ? L"abcdefghijklmnopqrstuvwxyz" :
|
||||||
|
sourceLanguage == L"uk" ? L"абвгґдеєжзиіїйклмнопрстуфхцчшщьюя" : L"абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
|
||||||
|
auto small = lower(word);
|
||||||
|
bool sameLanguage = safeAutoWord(word, settings.autoMinLength) &&
|
||||||
|
small.find_first_not_of(alphabet) == small.npos &&
|
||||||
|
std::find(settings.cycle.begin(), settings.cycle.end(), layouts[source].id) != settings.cycle.end();
|
||||||
|
auto sameLayout = [&](std::wstring text)
|
||||||
|
{
|
||||||
|
if (word != small) text[0] = upper(text.substr(0, 1))[0];
|
||||||
|
return AutoSuggestion{source, source, prefix + text + suffix};
|
||||||
|
};
|
||||||
|
if (settings.autoReplace && sameLanguage)
|
||||||
|
{
|
||||||
|
auto replacement = settings.autoReplacements.find(small);
|
||||||
|
if (replacement != settings.autoReplacements.end() &&
|
||||||
|
replacement->second.find_first_not_of(alphabet + L" ") == small.npos)
|
||||||
|
return sameLayout(replacement->second);
|
||||||
|
}
|
||||||
auto personal = [&](const std::wstring &language, const std::wstring &candidate)
|
auto personal = [&](const std::wstring &language, const std::wstring &candidate)
|
||||||
{
|
{
|
||||||
auto found = settings.autoWords.find(language);
|
auto found = settings.autoWords.find(language);
|
||||||
@@ -173,7 +269,7 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
|||||||
};
|
};
|
||||||
// Valid words from either selected language are never changed.
|
// Valid words from either selected language are never changed.
|
||||||
for (auto &[language, d] : dictionaries)
|
for (auto &[language, d] : dictionaries)
|
||||||
if (d.rank(word) || personal(language, word))
|
if (d->rank(word) || personal(language, word))
|
||||||
return {};
|
return {};
|
||||||
std::optional<AutoSuggestion> candidate;
|
std::optional<AutoSuggestion> candidate;
|
||||||
std::optional<std::wstring> matchedText;
|
std::optional<std::wstring> matchedText;
|
||||||
@@ -193,7 +289,7 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
|||||||
auto converted = convert(word, layouts[source], layouts[i], true);
|
auto converted = convert(word, layouts[source], layouts[i], true);
|
||||||
if (converted == word || !safeAutoWord(converted, settings.autoMinLength))
|
if (converted == word || !safeAutoWord(converted, settings.autoMinLength))
|
||||||
continue;
|
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)
|
if (!rank)
|
||||||
continue;
|
continue;
|
||||||
if (matchedText && *matchedText != converted)
|
if (matchedText && *matchedText != converted)
|
||||||
@@ -203,7 +299,54 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
|||||||
(!candidate || priority(i) < priority(candidate->target)))
|
(!candidate || priority(i) < priority(candidate->target)))
|
||||||
candidate = AutoSuggestion{source, i, prefix + converted + suffix};
|
candidate = AutoSuggestion{source, i, prefix + converted + suffix};
|
||||||
}
|
}
|
||||||
return candidate;
|
if (candidate || matchedText || !settings.autoTypos || !sameLanguage || word.size() < 4)
|
||||||
|
return candidate;
|
||||||
|
// Generate only single edits. Stop at a second distinct dictionary hit,
|
||||||
|
// including rare hits: frequency limits must never hide ambiguity.
|
||||||
|
std::wstring found;
|
||||||
|
int foundRank = 0;
|
||||||
|
std::set<std::wstring> personalTargets;
|
||||||
|
if (auto it = settings.autoWords.find(sourceLanguage); it != settings.autoWords.end())
|
||||||
|
for (const auto &text : it->second) personalTargets.insert(lower(text));
|
||||||
|
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);
|
||||||
|
if (!rank) return true;
|
||||||
|
if (!found.empty()) return false;
|
||||||
|
found = text;
|
||||||
|
foundRank = rank;
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
for (size_t i = 0; i < small.size(); ++i)
|
||||||
|
{
|
||||||
|
auto text = small;
|
||||||
|
text.erase(i, 1);
|
||||||
|
if (!consider(text)) return {};
|
||||||
|
if (i + 1 < small.size())
|
||||||
|
{
|
||||||
|
text = small;
|
||||||
|
std::swap(text[i], text[i + 1]);
|
||||||
|
if (!consider(text)) return {};
|
||||||
|
}
|
||||||
|
for (wchar_t c : alphabet)
|
||||||
|
{
|
||||||
|
text = small;
|
||||||
|
text[i] = c;
|
||||||
|
if (!consider(text)) return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (small.size() < 32)
|
||||||
|
for (size_t i = 0; i <= small.size(); ++i)
|
||||||
|
for (wchar_t c : alphabet)
|
||||||
|
{
|
||||||
|
auto text = small;
|
||||||
|
text.insert(i, 1, c);
|
||||||
|
if (!consider(text)) return {};
|
||||||
|
}
|
||||||
|
if (!found.empty() && (settings.autoMaxRank == 0 || foundRank <= settings.autoMaxRank))
|
||||||
|
return sameLayout(found);
|
||||||
|
return {};
|
||||||
}
|
}
|
||||||
int matchAutoInput(const Run &run, const std::wstring &text, const std::vector<Layout> &layouts,
|
int matchAutoInput(const Run &run, const std::wstring &text, const std::vector<Layout> &layouts,
|
||||||
const Layout &physical, const Settings &settings)
|
const Layout &physical, const Settings &settings)
|
||||||
|
|||||||
+9
-1
@@ -1,6 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "platform.h"
|
#include "platform.h"
|
||||||
#include <map>
|
#include <map>
|
||||||
|
#include <memory>
|
||||||
#include <set>
|
#include <set>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
namespace ks
|
namespace ks
|
||||||
@@ -18,23 +19,30 @@ int matchAutoInput(const Run &, const std::wstring &, const std::vector<Layout>
|
|||||||
bool autoCorrectionAllowed(HWND, const Settings &);
|
bool autoCorrectionAllowed(HWND, const Settings &);
|
||||||
class AutoCorrector
|
class AutoCorrector
|
||||||
{
|
{
|
||||||
|
friend struct AutoCorrectorRegressionAccess;
|
||||||
struct Dictionary
|
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::string bytes;
|
||||||
std::vector<uint32_t> offsets;
|
std::vector<uint32_t> offsets;
|
||||||
std::string_view word(size_t) const;
|
std::string_view word(size_t) const;
|
||||||
explicit Dictionary(const std::filesystem::path &);
|
explicit Dictionary(const std::filesystem::path &);
|
||||||
int rank(const std::wstring &) const;
|
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::vector<std::wstring> languages;
|
||||||
std::set<std::wstring> rejected;
|
std::set<std::wstring> rejected;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
void configure(const std::filesystem::path &, const std::vector<std::wstring> &);
|
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> &,
|
std::optional<AutoSuggestion> suggest(const std::wstring &, int source, const std::vector<Layout> &,
|
||||||
const Settings &) const;
|
const Settings &) const;
|
||||||
void reject(std::wstring word, const Settings & = {});
|
void reject(std::wstring word, const Settings & = {});
|
||||||
|
// Referenced dictionary payload, including shared storage (do not sum across consumers).
|
||||||
size_t memoryBytes() const;
|
size_t memoryBytes() const;
|
||||||
};
|
};
|
||||||
} // namespace ks
|
} // 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];
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
-2
@@ -79,9 +79,10 @@ LRESULT CALLBACK controller(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
|||||||
}
|
}
|
||||||
// The configurator owns no history store, dictionaries, worker or input hooks.
|
// The configurator owns no history store, dictionaries, worker or input hooks.
|
||||||
// All mutations are validated and committed by the resident process.
|
// 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;
|
current = this;
|
||||||
|
data = dataDirectory();
|
||||||
layouts = readLayouts();
|
layouts = readLayouts();
|
||||||
}
|
}
|
||||||
App::~App()
|
App::~App()
|
||||||
@@ -101,7 +102,16 @@ void App::applySettings(const Settings &next)
|
|||||||
memcpy(payload.data(), &length, sizeof(length));
|
memcpy(payload.data(), &length, sizeof(length));
|
||||||
payload.insert(payload.end(), before.begin(), before.end());
|
payload.insert(payload.end(), before.begin(), before.end());
|
||||||
payload.insert(payload.end(), after.begin(), after.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()
|
void App::reloadLayouts()
|
||||||
{
|
{
|
||||||
@@ -110,6 +120,14 @@ void App::reloadLayouts()
|
|||||||
settings = decodeSettings(bytes, layouts);
|
settings = decodeSettings(bytes, layouts);
|
||||||
}
|
}
|
||||||
void App::clearHistory() { request(*this, ConfigClearHistory); }
|
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)) :
|
||||||
|
request(*this, ConfigSync, Bytes{static_cast<unsigned char>(action)});
|
||||||
|
return wide(std::string(result.begin(), result.end()));
|
||||||
|
}
|
||||||
void App::setHotkeyCapture(HWND field)
|
void App::setHotkeyCapture(HWND field)
|
||||||
{
|
{
|
||||||
hotkeyCapture = field;
|
hotkeyCapture = field;
|
||||||
@@ -180,6 +198,12 @@ int runConfigurator(HINSTANCE instance, bool snippets, bool logs)
|
|||||||
if (app.settingsWindow && !IsWindowEnabled(app.settingsWindow))
|
if (app.settingsWindow && !IsWindowEnabled(app.settingsWindow))
|
||||||
{
|
{
|
||||||
HWND popup = GetLastActivePopup(app.settingsWindow);
|
HWND popup = GetLastActivePopup(app.settingsWindow);
|
||||||
|
while (!IsWindowEnabled(popup))
|
||||||
|
{
|
||||||
|
HWND next = GetLastActivePopup(popup);
|
||||||
|
if (next == popup) break;
|
||||||
|
popup = next;
|
||||||
|
}
|
||||||
if (popup != app.settingsWindow && IsDialogMessageW(popup, &message)) continue;
|
if (popup != app.settingsWindow && IsDialogMessageW(popup, &message)) continue;
|
||||||
}
|
}
|
||||||
if (app.settingsWindow && IsDialogMessageW(app.settingsWindow, &message)) continue;
|
if (app.settingsWindow && IsDialogMessageW(app.settingsWindow, &message)) continue;
|
||||||
|
|||||||
+30
-3
@@ -1,4 +1,5 @@
|
|||||||
#include "configuration.h"
|
#include "configuration.h"
|
||||||
|
#include "settings_merge.h"
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
namespace ks
|
namespace ks
|
||||||
{
|
{
|
||||||
@@ -40,7 +41,34 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
|||||||
{
|
{
|
||||||
switch (message.dwData)
|
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;
|
||||||
|
case ConfigSyncResolve:
|
||||||
|
{
|
||||||
|
if (!message.cbData) throw std::runtime_error("Empty conflict choices.");
|
||||||
|
auto first = static_cast<const unsigned char *>(message.lpData);
|
||||||
|
auto status = utf8(app.syncCommand(4, decodeSyncChoices(Bytes(first, first + message.cbData))));
|
||||||
|
reply.assign(status.begin(), status.end());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case ConfigSync:
|
||||||
|
{
|
||||||
|
if (message.cbData != 1 || *static_cast<const unsigned char *>(message.lpData) > 3)
|
||||||
|
throw std::runtime_error("Invalid sync command.");
|
||||||
|
auto status = utf8(app.syncCommand(*static_cast<const unsigned char *>(message.lpData)));
|
||||||
|
reply.assign(status.begin(), status.end());
|
||||||
|
break;
|
||||||
|
}
|
||||||
case ConfigSave:
|
case ConfigSave:
|
||||||
|
case ConfigSaveEdited:
|
||||||
{
|
{
|
||||||
if (app.busy) throw std::runtime_error("Wait for the current text operation to finish.");
|
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.");
|
if (message.cbData < sizeof(DWORD)) throw std::runtime_error("Invalid settings request.");
|
||||||
@@ -48,11 +76,10 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
|||||||
memcpy(&length, message.lpData, sizeof(length));
|
memcpy(&length, message.lpData, sizeof(length));
|
||||||
if (length > message.cbData - sizeof(length)) throw std::runtime_error("Invalid settings snapshot.");
|
if (length > message.cbData - sizeof(length)) throw std::runtime_error("Invalid settings snapshot.");
|
||||||
auto begin = static_cast<const unsigned char *>(message.lpData) + sizeof(length);
|
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);
|
Bytes next(begin + length, static_cast<const unsigned char *>(message.lpData) + message.cbData);
|
||||||
if (next.empty()) throw std::runtime_error("Empty settings request.");
|
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);
|
reply = encodeSettings(app.settings);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-1
@@ -5,7 +5,9 @@ namespace ks
|
|||||||
inline constexpr ULONG_PTR ConfigRead = 0x4b530100, ConfigSave = ConfigRead + 1,
|
inline constexpr ULONG_PTR ConfigRead = 0x4b530100, ConfigSave = ConfigRead + 1,
|
||||||
ConfigLayouts = ConfigRead + 2, ConfigClearHistory = ConfigRead + 3,
|
ConfigLayouts = ConfigRead + 2, ConfigClearHistory = ConfigRead + 3,
|
||||||
ConfigCapture = ConfigRead + 4, ConfigLogs = ConfigRead + 5,
|
ConfigCapture = ConfigRead + 4, ConfigLogs = ConfigRead + 5,
|
||||||
ConfigReply = ConfigRead + 6, ConfigClearLog = ConfigRead + 7, ConfigEnd = ConfigRead + 8;
|
ConfigReply = ConfigRead + 6, ConfigClearLog = ConfigRead + 7,
|
||||||
|
ConfigSync = ConfigRead + 8, ConfigSyncConflicts = ConfigRead + 9,
|
||||||
|
ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigEnd = ConfigRead + 13;
|
||||||
inline constexpr size_t ConfigLimit = 8 * 1024 * 1024;
|
inline constexpr size_t ConfigLimit = 8 * 1024 * 1024;
|
||||||
bool configurationPeer(HWND, const wchar_t *filename);
|
bool configurationPeer(HWND, const wchar_t *filename);
|
||||||
void launchConfiguration(App &, bool snippets = false, bool logs = false);
|
void launchConfiguration(App &, bool snippets = false, bool logs = false);
|
||||||
|
|||||||
@@ -6,6 +6,21 @@
|
|||||||
|
|
||||||
namespace ks
|
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,
|
int HotkeyHook::update(UINT key, bool down, UINT modifiers,
|
||||||
const std::vector<std::pair<int, Hotkey>> &bindings)
|
const std::vector<std::pair<int, Hotkey>> &bindings)
|
||||||
{
|
{
|
||||||
|
|||||||
+11
@@ -31,7 +31,13 @@ std::wstring transliterate(const std::wstring &);
|
|||||||
struct Snippet
|
struct Snippet
|
||||||
{
|
{
|
||||||
std::wstring trigger, text;
|
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
|
struct Template
|
||||||
{
|
{
|
||||||
std::wstring text, suffix;
|
std::wstring text, suffix;
|
||||||
@@ -51,6 +57,8 @@ struct Settings
|
|||||||
bool recent = true, switchLayout = true, history = true, autostart = false, awake = false;
|
bool recent = true, switchLayout = true, history = true, autostart = false, awake = false;
|
||||||
bool elevatedAutostart = false;
|
bool elevatedAutostart = false;
|
||||||
bool autoCorrect = false;
|
bool autoCorrect = false;
|
||||||
|
bool autoReplace = false, autoTypos = false;
|
||||||
|
std::map<std::wstring, std::wstring> autoReplacements;
|
||||||
bool writeLog = true;
|
bool writeLog = true;
|
||||||
bool screenshotAutoOpenEditor = false;
|
bool screenshotAutoOpenEditor = false;
|
||||||
bool useTesseract = false;
|
bool useTesseract = false;
|
||||||
@@ -71,8 +79,11 @@ struct Settings
|
|||||||
translit = L"Ctrl+Alt+Shift+T", undo = L"Ctrl+Alt+Shift+Z", clipboard = L"Win+V",
|
translit = L"Ctrl+Alt+Shift+T", undo = L"Ctrl+Alt+Shift+Z", clipboard = L"Win+V",
|
||||||
screenshot = L"Win+Shift+S";
|
screenshot = L"Win+Shift+S";
|
||||||
std::vector<std::wstring> cycle, direct, directIds;
|
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<std::wstring> excluded{L"KeePass", L"KeePassXC", L"1Password", L"Bitwarden"};
|
||||||
std::vector<Snippet> snippets;
|
std::vector<Snippet> snippets;
|
||||||
|
std::vector<std::wstring> snippetTombstones;
|
||||||
};
|
};
|
||||||
// Consume repeats and key-up for intercepted chords, even if settings change.
|
// Consume repeats and key-up for intercepted chords, even if settings change.
|
||||||
struct HotkeyHook
|
struct HotkeyHook
|
||||||
|
|||||||
+2
-1
@@ -37,7 +37,8 @@ inline std::vector<OperationLogRow> parseOperationLog(const std::wstring &conten
|
|||||||
L"Operation: " + field("attempt") + L"\r\nResult: " + row.outcome +
|
L"Operation: " + field("attempt") + L"\r\nResult: " + row.outcome +
|
||||||
L"\r\nVerification: " + field("verification") + L"\r\nElapsed: " +
|
L"\r\nVerification: " + field("verification") + L"\r\nElapsed: " +
|
||||||
std::to_wstring(j.value("elapsedMs", 0ULL)) + L" ms\r\n\r\nOriginal:\r\n" +
|
std::to_wstring(j.value("elapsedMs", 0ULL)) + L" ms\r\n\r\nOriginal:\r\n" +
|
||||||
field("original") + L"\r\n\r\nExpected result:\r\n" + field("expected") +
|
field("original") + L"\r\n\r\nExpected selection:\r\n" + field("selectionExpected") +
|
||||||
|
L"\r\n\r\nExpected result / verification target:\r\n" + field("expected") +
|
||||||
L"\r\n\r\nRead back:\r\n" + field("actual") + L"\r\n\r\nForeground unchanged: " +
|
L"\r\n\r\nRead back:\r\n" + field("actual") + L"\r\n\r\nForeground unchanged: " +
|
||||||
(j.value("foregroundSame", false) ? L"yes" : L"no") + L"\r\nInput context unchanged: " +
|
(j.value("foregroundSame", false) ? L"yes" : L"no") + L"\r\nInput context unchanged: " +
|
||||||
(j.value("inputSame", false) ? L"yes" : L"no") + L"\r\nText truncated: " +
|
(j.value("inputSame", false) ? L"yes" : L"no") + L"\r\nText truncated: " +
|
||||||
|
|||||||
+17
-3
@@ -4,14 +4,28 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
namespace ks {
|
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
|
// 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.
|
// 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>
|
template<class T>
|
||||||
void trimHistoryPreviews(std::map<std::wstring,T> &cache,
|
void trimHistoryPreviews(std::map<std::wstring,T> &cache,
|
||||||
const std::set<std::wstring> &visible, size_t limit=32)
|
const std::set<std::wstring> &visible, size_t limit=32)
|
||||||
{
|
{
|
||||||
for(auto it=cache.begin(); cache.size()>limit && it!=cache.end();)
|
trimHistoryPreviews(cache, visible, limit, 0, [](const T &) { return size_t{}; });
|
||||||
if(!visible.contains(it->first)) it=cache.erase(it);
|
|
||||||
else ++it;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+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())
|
||||||
|
endpoints.push_back({peer,entry.at("key"),peers.contains(peer)?peers.at(peer).address.sin_addr.s_addr:0});
|
||||||
|
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,282 @@
|
|||||||
|
#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{};std::string lastState; };
|
||||||
|
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;});
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
// Discovery is a hint, not the lifetime of authenticated input sessions.
|
||||||
|
// Keep the last usable address across missed announcements. A new address
|
||||||
|
// is used only once a channel is down, never to tear down working input.
|
||||||
|
for(auto &e:endpoints){if(e.id==local)continue;auto &link=links.at(e.id);
|
||||||
|
if(e.address&&!link.channel->ready()&&e.address!=link.endpoint.address){
|
||||||
|
link.channel->disconnect();link.endpoint.address=e.address;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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)){
|
||||||
|
auto detail="TCP input port "+std::to_string(port)+" is unavailable (Windows error "+std::to_string(WSAGetLastError())+").";
|
||||||
|
if(error!=detail)log(L"LAN input: "+wide(detail));
|
||||||
|
closeSocket(listener);retry=now+1500;error=std::move(detail);
|
||||||
|
}else {error.clear();log(L"LAN input listener ready on TCP "+std::to_wstring(port));}
|
||||||
|
}
|
||||||
|
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.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);
|
||||||
|
auto state=link.channel->status();if(state!=link.lastState){link.lastState=state;log(L"LAN input peer "+wide(id.substr(0,8))+L": "+wide(state));}
|
||||||
|
if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;}
|
||||||
|
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 "app.h"
|
||||||
#include <shellapi.h>
|
#include <shellapi.h>
|
||||||
#include <shlobj.h>
|
#include <shlobj.h>
|
||||||
|
#include "configuration.h"
|
||||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||||
{
|
{
|
||||||
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||||
int argc{};
|
int argc{};
|
||||||
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
|
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
|
||||||
std::wstring arg = argc > 1 ? argv[1] : L"";
|
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="))
|
if (arg.starts_with(L"--configure-autostart="))
|
||||||
{
|
{
|
||||||
int result = 1;
|
int result = 1;
|
||||||
@@ -72,6 +87,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
ks::App app(instance, arg == L"--smoke-test");
|
ks::App app(instance, arg == L"--smoke-test");
|
||||||
|
app.isolateHistory = !app.smoke;
|
||||||
if (arg.starts_with(L"--update-ready-event="))
|
if (arg.starts_with(L"--update-ready-event="))
|
||||||
app.updateStartupEvent = arg.substr(std::wstring(L"--update-ready-event=").size());
|
app.updateStartupEvent = arg.substr(std::wstring(L"--update-ready-event=").size());
|
||||||
else if (!arg.empty() && arg != L"--smoke-test")
|
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)
|
Pixels decodeImage(const Clip &clip, UINT maxWidth, UINT maxHeight)
|
||||||
{
|
{
|
||||||
Bytes encoded;
|
Bytes encoded;
|
||||||
|
const Bytes *input = &encoded;
|
||||||
for (const auto &f : clip.formats)
|
for (const auto &f : clip.formats)
|
||||||
if (f.name == L"PNG")
|
if (f.name == L"PNG")
|
||||||
{
|
{
|
||||||
encoded = f.data;
|
input = &f.data;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (encoded.empty())
|
if (input->empty())
|
||||||
|
{
|
||||||
|
input = &encoded;
|
||||||
for (const auto &f : clip.formats)
|
for (const auto &f : clip.formats)
|
||||||
if ((f.id == CF_DIB || f.id == CF_DIBV5) && f.data.size() >= 40)
|
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.bfType = 0x4d42;
|
||||||
file.bfSize = (DWORD)(sizeof(file) + f.data.size());
|
file.bfSize = (DWORD)(sizeof(file) + f.data.size());
|
||||||
file.bfOffBits = (DWORD)offset;
|
file.bfOffBits = (DWORD)offset;
|
||||||
encoded.resize(sizeof(file));
|
encoded.resize(sizeof(file) + f.data.size());
|
||||||
memcpy(encoded.data(), &file, sizeof(file));
|
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;
|
break;
|
||||||
}
|
}
|
||||||
if (encoded.empty())
|
}
|
||||||
|
if (input->empty())
|
||||||
throw std::runtime_error("This clipboard item has no supported image");
|
throw std::runtime_error("This clipboard item has no supported image");
|
||||||
Com<IWICImagingFactory> wic;
|
Com<IWICImagingFactory> wic;
|
||||||
check(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory,
|
check(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory,
|
||||||
(void **)wic.out()));
|
(void **)wic.out()));
|
||||||
Com<IWICStream> stream;
|
Com<IWICStream> stream;
|
||||||
check(wic->CreateStream(stream.out()));
|
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;
|
Com<IWICBitmapDecoder> decoder;
|
||||||
check(wic->CreateDecoderFromStream(stream.p, nullptr, WICDecodeMetadataCacheOnLoad, decoder.out()));
|
check(wic->CreateDecoderFromStream(stream.p, nullptr, WICDecodeMetadataCacheOnLoad, decoder.out()));
|
||||||
Com<IWICBitmapFrameDecode> frame;
|
Com<IWICBitmapFrameDecode> frame;
|
||||||
|
|||||||
+18
-1
@@ -13,7 +13,7 @@ class PasteProbe
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
std::wstring status = L"not-requested";
|
std::wstring status = L"not-requested";
|
||||||
PasteProbe(bool enabled, const std::wstring &original)
|
PasteProbe(bool enabled, HWND target)
|
||||||
{
|
{
|
||||||
if (!enabled)
|
if (!enabled)
|
||||||
return;
|
return;
|
||||||
@@ -25,6 +25,18 @@ class PasteProbe
|
|||||||
automation->put_TransactionTimeout(200);
|
automation->put_TransactionTimeout(200);
|
||||||
if (FAILED(automation->GetFocusedElement(&element)) || !element)
|
if (FAILED(automation->GetFocusedElement(&element)) || !element)
|
||||||
return;
|
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;
|
BOOL password = TRUE;
|
||||||
if (FAILED(element->get_CurrentIsPassword(&password)) || password)
|
if (FAILED(element->get_CurrentIsPassword(&password)) || password)
|
||||||
{
|
{
|
||||||
@@ -35,6 +47,11 @@ class PasteProbe
|
|||||||
(void **)&pattern)) ||
|
(void **)&pattern)) ||
|
||||||
!pattern)
|
!pattern)
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr)
|
||||||
|
: PasteProbe(enabled, target)
|
||||||
|
{
|
||||||
|
if (!pattern) return;
|
||||||
auto selected = read(1, false);
|
auto selected = read(1, false);
|
||||||
auto normalize = [](std::wstring value)
|
auto normalize = [](std::wstring value)
|
||||||
{
|
{
|
||||||
|
|||||||
+70
-8
@@ -159,6 +159,31 @@ void showRequestedWindow(HWND window)
|
|||||||
if (!IsWindowVisible(window))
|
if (!IsWindowVisible(window))
|
||||||
ShowWindow(window, SW_SHOW);
|
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)
|
bool activateWindow(HWND window)
|
||||||
{
|
{
|
||||||
if (!IsWindow(window))
|
if (!IsWindow(window))
|
||||||
@@ -240,15 +265,27 @@ std::wstring processName(HWND window)
|
|||||||
CloseHandle(h);
|
CloseHandle(h);
|
||||||
return ok ? std::filesystem::path(std::wstring(path, n)).stem().wstring() : L"";
|
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);
|
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;
|
Clip c;
|
||||||
size_t total = 0;
|
size_t total = 0;
|
||||||
for (UINT f = EnumClipboardFormats(0); f; f = EnumClipboardFormats(f))
|
for (UINT f = EnumClipboardFormats(0); f; f = EnumClipboardFormats(f))
|
||||||
{
|
{
|
||||||
if (!globalFormat(f))
|
if (!globalFormat(f))
|
||||||
continue;
|
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);
|
HANDLE handle = GetClipboardData(f);
|
||||||
if (!handle)
|
if (!handle)
|
||||||
continue;
|
continue;
|
||||||
@@ -266,8 +303,6 @@ Clip readClipboard(HWND window, size_t limit)
|
|||||||
GlobalUnlock(handle);
|
GlobalUnlock(handle);
|
||||||
if (f >= 0xc000)
|
if (f >= 0xc000)
|
||||||
{
|
{
|
||||||
wchar_t name[256]{};
|
|
||||||
GetClipboardFormatNameW(f, name, 256);
|
|
||||||
format.name = name;
|
format.name = name;
|
||||||
}
|
}
|
||||||
total += size;
|
total += size;
|
||||||
@@ -275,7 +310,8 @@ Clip readClipboard(HWND window, size_t limit)
|
|||||||
}
|
}
|
||||||
return c;
|
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.
|
// Allocate all blocks before replacing any existing data.
|
||||||
std::vector<std::pair<UINT, HGLOBAL>> blocks;
|
std::vector<std::pair<UINT, HGLOBAL>> blocks;
|
||||||
@@ -302,6 +338,8 @@ DWORD writeClipboard(HWND window, const Clip &c)
|
|||||||
blocks.emplace_back(id, h);
|
blocks.emplace_back(id, h);
|
||||||
}
|
}
|
||||||
ClipboardLock lock(window);
|
ClipboardLock lock(window);
|
||||||
|
if (expected && *expected != GetClipboardSequenceNumber())
|
||||||
|
throw std::runtime_error("Clipboard changed before restoring snapshot");
|
||||||
if (!EmptyClipboard())
|
if (!EmptyClipboard())
|
||||||
throw std::runtime_error("Cannot replace clipboard");
|
throw std::runtime_error("Cannot replace clipboard");
|
||||||
for (auto &[id, h] : blocks)
|
for (auto &[id, h] : blocks)
|
||||||
@@ -397,7 +435,7 @@ bool needsSelectionDelay(HWND target)
|
|||||||
{
|
{
|
||||||
const auto name = lower(processName(target));
|
const auto name = lower(processName(target));
|
||||||
return name == L"ms-teams" || name == L"msedgewebview2" ||
|
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)
|
bool selectPrevious(size_t count, const std::function<bool()> &valid)
|
||||||
{
|
{
|
||||||
@@ -407,12 +445,16 @@ bool selectPrevious(size_t count, const std::function<bool()> &valid)
|
|||||||
// Shift+Left events can all use the same caret position and select only one
|
// Shift+Left events can all use the same caret position and select only one
|
||||||
// character. Give each change time to settle before sending the next one.
|
// character. Give each change time to settle before sending the next one.
|
||||||
const auto target = GetForegroundWindow();
|
const auto target = GetForegroundWindow();
|
||||||
|
diagnosticEvent(L"SelectPrevious requested=" + std::to_wstring(count) +
|
||||||
|
L" mode=" + (needsSelectionDelay(target) ? std::wstring(L"paced-25ms") : std::wstring(L"batch")));
|
||||||
if (needsSelectionDelay(target))
|
if (needsSelectionDelay(target))
|
||||||
{
|
{
|
||||||
for (size_t i = 0; i < count; ++i)
|
for (size_t i = 0; i < count; ++i)
|
||||||
{
|
{
|
||||||
if (!valid() || GetForegroundWindow() != target || !chord(VK_LEFT, MOD_SHIFT))
|
if (!valid() || GetForegroundWindow() != target || !chord(VK_LEFT, MOD_SHIFT))
|
||||||
return false;
|
return false;
|
||||||
|
if (i < 32 || i + 1 == count)
|
||||||
|
diagnosticEvent(L"SelectPrevious Shift+Left sent=" + std::to_wstring(i + 1));
|
||||||
Sleep(25);
|
Sleep(25);
|
||||||
}
|
}
|
||||||
return valid() && GetForegroundWindow() == target;
|
return valid() && GetForegroundWindow() == target;
|
||||||
@@ -434,7 +476,10 @@ bool selectPrevious(size_t count, const std::function<bool()> &valid)
|
|||||||
add(VK_LEFT, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP);
|
add(VK_LEFT, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP);
|
||||||
}
|
}
|
||||||
add(VK_SHIFT, KEYEVENTF_KEYUP);
|
add(VK_SHIFT, KEYEVENTF_KEYUP);
|
||||||
if (SendInput((UINT)inputs.size(), inputs.data(), sizeof(INPUT)) != inputs.size())
|
auto sent = SendInput((UINT)inputs.size(), inputs.data(), sizeof(INPUT));
|
||||||
|
diagnosticEvent(L"SelectPrevious batch offset=" + std::to_wstring(offset) + L" eventsRequested=" +
|
||||||
|
std::to_wstring(inputs.size()) + L" eventsSent=" + std::to_wstring(sent));
|
||||||
|
if (sent != inputs.size())
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return valid();
|
return valid();
|
||||||
@@ -572,10 +617,25 @@ std::recursive_mutex logGate;
|
|||||||
bool loggingEnabled = false;
|
bool loggingEnabled = false;
|
||||||
DiagnosticBuffer diagnosticBuffer;
|
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)
|
std::wstring DiagnosticBuffer::record(const std::wstring &message, bool problem, ULONGLONG now)
|
||||||
{
|
{
|
||||||
while (!entries.empty() && (entries.size() >= 40 || now - entries.front().first > 30000))
|
expire(now);
|
||||||
entries.pop_front();
|
while (entries.size() >= 128) entries.pop_front();
|
||||||
entries.emplace_back(now, message);
|
entries.emplace_back(now, message);
|
||||||
if (!problem)
|
if (!problem)
|
||||||
return {};
|
return {};
|
||||||
@@ -673,3 +733,5 @@ void log(const std::wstring &message)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} // namespace ks
|
} // 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 switchWindowLayout(HWND, HKL, const std::function<bool()> &valid);
|
||||||
bool activateWindow(HWND);
|
bool activateWindow(HWND);
|
||||||
void showRequestedWindow(HWND);
|
void showRequestedWindow(HWND);
|
||||||
|
void showMenuAccessKeys(HMENU);
|
||||||
bool ownsClipboard(HWND);
|
bool ownsClipboard(HWND);
|
||||||
bool webViewDescendant(DWORD owner, DWORD host,
|
bool webViewDescendant(DWORD owner, DWORD host,
|
||||||
const std::function<std::optional<std::pair<DWORD, std::wstring>>(DWORD)> &read);
|
const std::function<std::optional<std::pair<DWORD, std::wstring>>(DWORD)> &read);
|
||||||
std::wstring processName(HWND);
|
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 writeClipboard(HWND, const Clip &);
|
||||||
|
DWORD writeClipboardGuarded(HWND, const Clip &, std::optional<DWORD> expected);
|
||||||
Clip textClip(const std::wstring &);
|
Clip textClip(const std::wstring &);
|
||||||
bool chord(WORD key, UINT modifiers = 0);
|
bool chord(WORD key, UINT modifiers = 0);
|
||||||
// Process-local marker, shared by every KSwitcher input producer (not an authentication token).
|
// 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;
|
std::deque<std::pair<ULONGLONG, std::wstring>> entries;
|
||||||
public:
|
public:
|
||||||
|
size_t expire(ULONGLONG now);
|
||||||
std::wstring record(const std::wstring &message, bool problem, ULONGLONG now);
|
std::wstring record(const std::wstring &message, bool problem, ULONGLONG now);
|
||||||
void clear() { entries.clear(); }
|
void clear() { entries.clear(); }
|
||||||
};
|
};
|
||||||
void setLoggingEnabled(bool enabled);
|
void setLoggingEnabled(bool enabled);
|
||||||
|
void expireDiagnostics(ULONGLONG now);
|
||||||
void diagnosticEvent(const std::wstring &message, bool problem = false);
|
void diagnosticEvent(const std::wstring &message, bool problem = false);
|
||||||
void diagnosticOperation(const std::string &json);
|
void diagnosticOperation(const std::string &json);
|
||||||
std::wstring readDiagnosticLog(bool previous);
|
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;
|
return 0;
|
||||||
}
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
std::string richPreview(const Clip &clip)
|
std::string richPreview(const Clip &clip, bool plainFallback)
|
||||||
{
|
{
|
||||||
for (const auto &f : clip.formats)
|
for (const auto &f : clip.formats)
|
||||||
if (f.name == L"Rich Text Format" && f.data.size() <= 65536)
|
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();
|
auto text = clip.text();
|
||||||
if (text.size() > 4096)
|
if (text.size() > 4096)
|
||||||
text.resize(4096);
|
text.resize(4096);
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
#include "platform.h"
|
#include "platform.h"
|
||||||
namespace ks
|
namespace ks
|
||||||
{
|
{
|
||||||
std::string richPreview(const Clip &);
|
std::string richPreview(const Clip &, bool plainFallback = true);
|
||||||
HWND createRichText(HWND parent, int id, bool visible);
|
HWND createRichText(HWND parent, int id, bool visible);
|
||||||
bool setRichText(HWND, const std::string &);
|
bool setRichText(HWND, const std::string &);
|
||||||
} // namespace ks
|
} // namespace ks
|
||||||
+366
-41
@@ -1,4 +1,5 @@
|
|||||||
#include "screenshot.h"
|
#include "screenshot.h"
|
||||||
|
#include "stroke_improvement.h"
|
||||||
#include "ocr.h"
|
#include "ocr.h"
|
||||||
#include "../resources/resource.h"
|
#include "../resources/resource.h"
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
@@ -53,7 +54,7 @@ bool confirmScreenshotClose(HWND owner)
|
|||||||
// If Windows cannot display the confirmation, keep the screenshot open.
|
// If Windows cannot display the confirmation, keep the screenshot open.
|
||||||
return SUCCEEDED(result) && button==IDYES;
|
return SUCCEEDED(result) && button==IDYES;
|
||||||
}
|
}
|
||||||
constexpr int ToolIds[]{27,10,11,22,23,24,25,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
|
struct Surface
|
||||||
{
|
{
|
||||||
HDC dc = CreateCompatibleDC(nullptr);
|
HDC dc = CreateCompatibleDC(nullptr);
|
||||||
@@ -123,7 +124,7 @@ bool chooseTextFont(HWND owner,Mark &m)
|
|||||||
m.fontWeight=font.lfWeight; m.fontItalic=font.lfItalic!=0;
|
m.fontWeight=font.lfWeight; m.fontItalic=font.lfItalic!=0;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
constexpr int CursorTools[]{10,11,22,23,24,25,19};
|
constexpr int CursorTools[]{10,11,22,23,24,25,36,37,38,19};
|
||||||
HCURSOR makeToolCursor(int tool,int size)
|
HCURSOR makeToolCursor(int tool,int size)
|
||||||
{
|
{
|
||||||
// Monochrome AND/XOR cursor: white outline keeps the glyph visible on dark images.
|
// Monochrome AND/XOR cursor: white outline keeps the glyph visible on dark images.
|
||||||
@@ -147,7 +148,10 @@ HCURSOR makeToolCursor(int tool,int size)
|
|||||||
case 22: line(18,29,29,18); break;
|
case 22: line(18,29,29,18); break;
|
||||||
case 23: Rectangle(dc,x(17),y(18),x(30),y(29)); 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 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 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; }
|
||||||
case 19:
|
case 19:
|
||||||
line(18,25,25,18); line(25,18,29,22); line(29,22,22,29);
|
line(18,25,25,18); line(25,18,29,22); line(29,22,22,29);
|
||||||
line(22,29,18,25); line(18,25,17,30); line(17,30,22,29); break;
|
line(22,29,18,25); line(18,25,17,30); line(17,30,22,29); break;
|
||||||
@@ -174,17 +178,25 @@ struct Capture
|
|||||||
Mark textDefaults{};
|
Mark textDefaults{};
|
||||||
ScreenshotShape shape=ScreenshotShape::None;
|
ScreenshotShape shape=ScreenshotShape::None;
|
||||||
LineStyle lineStyle=LineStyle::Solid;
|
LineStyle lineStyle=LineStyle::Solid;
|
||||||
|
int smoothing=25;
|
||||||
|
bool smoothingDrag=false;
|
||||||
LineEnds arrowEnds=LineEnds::End, freehandEnds=LineEnds::None;
|
LineEnds arrowEnds=LineEnds::End, freehandEnds=LineEnds::None;
|
||||||
COLORREF currentColor=RGB(225,42,50);
|
COLORREF currentColor=RGB(225,42,50);
|
||||||
COLORREF customColors[16]{};
|
COLORREF customColors[16]{};
|
||||||
Mark stroke{};
|
Mark stroke{};
|
||||||
bool strokeConstrained{};
|
bool strokeConstrained{};
|
||||||
|
bool strokeUsedConstraint{};
|
||||||
size_t strokeAnchor{};
|
size_t strokeAnchor{};
|
||||||
int strokeAxis{}; // 0 = not chosen, 1 = horizontal, 2 = vertical, 3/4 = diagonals.
|
int strokeAxis{}; // 0 = not chosen, 1 = horizontal, 2 = vertical, 3/4 = diagonals.
|
||||||
bool strokeAxisSettled{};
|
bool strokeAxisSettled{};
|
||||||
std::vector<POINT> strokeMotion;
|
std::vector<POINT> strokeMotion;
|
||||||
POINT start{}, end{};
|
POINT start{}, end{};
|
||||||
RECT selection{}, view{};
|
RECT selection{}, view{};
|
||||||
|
RECT canvas{};
|
||||||
|
double zoom=1,panX=0,panY=0;
|
||||||
|
bool panning=false;
|
||||||
|
POINT panOrigin{};
|
||||||
|
int zoomWheelDelta=0;
|
||||||
std::vector<Mark> marks;
|
std::vector<Mark> marks;
|
||||||
ScreenshotHistory history;
|
ScreenshotHistory history;
|
||||||
HWND editor{}, inlineText{};
|
HWND editor{}, inlineText{};
|
||||||
@@ -243,9 +255,10 @@ void updateStatus(Capture &c)
|
|||||||
if(c.hoveredTool==28) text=L"Save (Ctrl+S) | Save As... (Ctrl+Shift+S)";
|
if(c.hoveredTool==28) text=L"Save (Ctrl+S) | Save As... (Ctrl+Shift+S)";
|
||||||
}
|
}
|
||||||
else if(c.inlineText) text=L"Text: Enter = new line | Ctrl+Enter = apply | Esc = cancel";
|
else if(c.inlineText) text=L"Text: Enter = new line | Ctrl+Enter = apply | Esc = cancel";
|
||||||
else if(part==MarkPart::Rotation) text=L"Drag to rotate text | Hold Shift for 15-degree steps";
|
else if(part==MarkPart::Rotation) text=L"Drag to rotate | Hold Shift for 15-degree steps";
|
||||||
else if(part==MarkPart::Thickness) text=L"Drag to change thickness | Mouse wheel over object = size";
|
else if(part==MarkPart::Thickness) text=L"Drag to change thickness | Mouse wheel over object = size";
|
||||||
else if(part==MarkPart::Radius) text=L"Drag to resize the number | Mouse wheel = diameter";
|
else if(part==MarkPart::Radius) text=L"Drag to resize the number | Mouse wheel = diameter";
|
||||||
|
else if(part>=MarkPart::Vertex0 && part<=MarkPart::Vertex2) text=L"Drag triangle vertex | Other vertices stay fixed";
|
||||||
else if(part==MarkPart::Start || part==MarkPart::End) text=L"Drag handle to resize | Endpoints can snap to objects and other arrows";
|
else if(part==MarkPart::Start || part==MarkPart::End) text=L"Drag handle to resize | Endpoints can snap to objects and other arrows";
|
||||||
else if(c.selected>=0) {
|
else if(c.selected>=0) {
|
||||||
const auto &m=c.marks[c.selected];
|
const auto &m=c.marks[c.selected];
|
||||||
@@ -257,9 +270,12 @@ void updateStatus(Capture &c)
|
|||||||
else if(c.pointer) text=L"Pointer (V): select and edit objects | Drag handles = geometry or thickness | Empty space clears selection";
|
else if(c.pointer) text=L"Pointer (V): select and edit objects | Drag handles = geometry or thickness | Empty space clears selection";
|
||||||
else if(c.textTool) text=L"Text (T): click the image to type | Double-click existing text to edit";
|
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.highlight) text=L"Highlight (H): drag to paint | Ctrl+drag = paint over an object | V = pointer";
|
||||||
else if(c.freehand) text=L"Freehand (F): Shift = 45-degree steps; move >50 px off line to turn | Ctrl = draw over objects";
|
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 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";
|
else text=L"Number (N): click to add | V = select and edit | Ctrl+C = copy screenshot";
|
||||||
|
text=L"Zoom: "+std::to_wstring(int(std::lround(100.0*(c.view.right-c.view.left)/c.image->width)))+
|
||||||
|
L"% (Ctrl +/- / wheel; Ctrl+0: fit; middle drag: pan) | "+text;
|
||||||
if(text!=c.statusText) {
|
if(text!=c.statusText) {
|
||||||
c.statusText=std::move(text);
|
c.statusText=std::move(text);
|
||||||
SendMessageW(status,SB_SETTEXTW,0,(LPARAM)c.statusText.c_str());
|
SendMessageW(status,SB_SETTEXTW,0,(LPARAM)c.statusText.c_str());
|
||||||
@@ -299,6 +315,12 @@ void positionInlineText(Capture &c)
|
|||||||
int width=std::min(std::max(120,MulDiv(bounds.right-bounds.left,viewWidth,c.image->width)+24),std::max(32,int(client.right)-x));
|
int width=std::min(std::max(120,MulDiv(bounds.right-bounds.left,viewWidth,c.image->width)+24),std::max(32,int(client.right)-x));
|
||||||
int height=std::min(std::max(40,MulDiv(bounds.bottom-bounds.top,viewWidth,c.image->width)+24),std::max(32,int(client.bottom)-c.statusHeight-y));
|
int height=std::min(std::max(40,MulDiv(bounds.bottom-bounds.top,viewWidth,c.image->width)+24),std::max(32,int(client.bottom)-c.statusHeight-y));
|
||||||
SetWindowPos(c.inlineText,nullptr,x-2,y-2,width,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
SetWindowPos(c.inlineText,nullptr,x-2,y-2,width,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||||
|
RECT editorBounds{x-2,y-2,x-2+width,y-2+height},visible{};
|
||||||
|
IntersectRect(&visible,&editorBounds,&c.canvas);
|
||||||
|
auto clip=IsRectEmpty(&visible)?CreateRectRgn(0,0,0,0):
|
||||||
|
CreateRectRgn(visible.left-editorBounds.left,visible.top-editorBounds.top,
|
||||||
|
visible.right-editorBounds.left,visible.bottom-editorBounds.top);
|
||||||
|
if(!SetWindowRgn(c.inlineText,clip,TRUE)) DeleteObject(clip);
|
||||||
}
|
}
|
||||||
Mark textStyleDefaults(const Mark &source)
|
Mark textStyleDefaults(const Mark &source)
|
||||||
{
|
{
|
||||||
@@ -339,6 +361,10 @@ void finishInlineText(HWND w,Capture &c,bool commit)
|
|||||||
}
|
}
|
||||||
LRESULT CALLBACK inlineTextProc(HWND w,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
LRESULT CALLBACK inlineTextProc(HWND w,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||||
{
|
{
|
||||||
|
if(msg==WM_KEYDOWN && (GetKeyState(VK_CONTROL)&0x8000) &&
|
||||||
|
(wp==VK_OEM_PLUS || wp==VK_ADD || wp==VK_OEM_MINUS || wp==VK_SUBTRACT || wp=='0' || wp==VK_NUMPAD0)) {
|
||||||
|
SendMessageW(GetParent(w),msg,wp,lp); return 0;
|
||||||
|
}
|
||||||
if(msg==WM_KEYDOWN && wp=='S' && (GetKeyState(VK_CONTROL)&0x8000)) {
|
if(msg==WM_KEYDOWN && wp=='S' && (GetKeyState(VK_CONTROL)&0x8000)) {
|
||||||
PostMessageW(GetParent(w),WM_COMMAND,(GetKeyState(VK_SHIFT)&0x8000)?29:28,0); return 0;
|
PostMessageW(GetParent(w),WM_COMMAND,(GetKeyState(VK_SHIFT)&0x8000)?29:28,0); return 0;
|
||||||
}
|
}
|
||||||
@@ -372,9 +398,55 @@ void beginMarkText(HWND w,Capture &c,int index)
|
|||||||
beginInlineText(w,c,label,index); c.editingLabel=true;
|
beginInlineText(w,c,label,index); c.editingLabel=true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
POINT rotateShapePoint(const Mark &m,POINT p,double direction=1)
|
||||||
|
{
|
||||||
|
if(m.shape==ScreenshotShape::None || m.rotation==0) return p;
|
||||||
|
double cx=(m.from.x+m.to.x)/2.0,cy=(m.from.y+m.to.y)/2.0;
|
||||||
|
double a=direction*m.rotation*3.141592653589793/180,cs=std::cos(a),sn=std::sin(a);
|
||||||
|
return {LONG(std::lround(cx+(p.x-cx)*cs-(p.y-cy)*sn)),
|
||||||
|
LONG(std::lround(cy+(p.x-cx)*sn+(p.y-cy)*cs))};
|
||||||
|
}
|
||||||
|
std::vector<POINT> shapeOutline(const Mark &m)
|
||||||
|
{
|
||||||
|
auto points=m.points;
|
||||||
|
if(points.empty()) {
|
||||||
|
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)
|
||||||
|
points={{r.left+(r.right-r.left)/4,r.top},{r.right-(r.right-r.left)/4,r.top},
|
||||||
|
{r.right,r.bottom},{r.left,r.bottom},{r.left+(r.right-r.left)/4,r.top}};
|
||||||
|
else {
|
||||||
|
for(int i=0;i<180;++i) {
|
||||||
|
double a=i*2*3.141592653589793/180;
|
||||||
|
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.top+r.bottom)/2.0+(r.bottom-r.top)/2.0*std::sin(a)))});
|
||||||
|
}
|
||||||
|
points.push_back(points.front());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for(auto &p:points) p=rotateShapePoint(m,p);
|
||||||
|
return points;
|
||||||
|
}
|
||||||
RECT markBounds(const Mark &m)
|
RECT markBounds(const Mark &m)
|
||||||
{
|
{
|
||||||
if(m.isText()) return screenshotTextBounds(m);
|
if(m.isText()) return screenshotTextBounds(m);
|
||||||
|
if(m.shape!=ScreenshotShape::None && m.rotation!=0) {
|
||||||
|
auto points=shapeOutline(m); RECT r{points[0].x,points[0].y,points[0].x,points[0].y};
|
||||||
|
for(auto p:points) { r.left=std::min(r.left,p.x); r.right=std::max(r.right,p.x);
|
||||||
|
r.top=std::min(r.top,p.y); r.bottom=std::max(r.bottom,p.y); }
|
||||||
|
return r;
|
||||||
|
}
|
||||||
RECT r=region(m.from,m.to);
|
RECT r=region(m.from,m.to);
|
||||||
for(auto p:m.points) {
|
for(auto p:m.points) {
|
||||||
r.left=std::min(r.left,p.x); r.top=std::min(r.top,p.y);
|
r.left=std::min(r.left,p.x); r.top=std::min(r.top,p.y);
|
||||||
@@ -386,7 +458,7 @@ std::pair<POINT,POINT> thicknessSegment(const Mark &m)
|
|||||||
{
|
{
|
||||||
if(m.shape!=ScreenshotShape::None) {
|
if(m.shape!=ScreenshotShape::None) {
|
||||||
auto r=region(m.from,m.to);
|
auto r=region(m.from,m.to);
|
||||||
return {{r.right,r.top},{r.left,r.top}};
|
return {rotateShapePoint(m,{r.right,r.top}),rotateShapePoint(m,{r.left,r.top})};
|
||||||
}
|
}
|
||||||
if(m.freehand && m.points.size()>1) {
|
if(m.freehand && m.points.size()>1) {
|
||||||
size_t index=(m.points.size()-1)/2;
|
size_t index=(m.points.size()-1)/2;
|
||||||
@@ -490,7 +562,10 @@ void drawMarks(HDC dc, const std::vector<Mark> &marks, const Mark *preview = nul
|
|||||||
if(m.shape!=ScreenshotShape::None) {
|
if(m.shape!=ScreenshotShape::None) {
|
||||||
auto hollow=SelectObject(dc,GetStockObject(HOLLOW_BRUSH));
|
auto hollow=SelectObject(dc,GetStockObject(HOLLOW_BRUSH));
|
||||||
auto r=region(m.from,m.to);
|
auto r=region(m.from,m.to);
|
||||||
if(m.shape==ScreenshotShape::Rectangle) Rectangle(dc,r.left,r.top,r.right+1,r.bottom+1);
|
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);
|
||||||
else Ellipse(dc,r.left,r.top,r.right+1,r.bottom+1);
|
else Ellipse(dc,r.left,r.top,r.right+1,r.bottom+1);
|
||||||
SelectObject(dc,hollow);
|
SelectObject(dc,hollow);
|
||||||
SelectObject(dc,previousPen); DeleteObject(arrowPen);
|
SelectObject(dc,previousPen); DeleteObject(arrowPen);
|
||||||
@@ -557,6 +632,13 @@ bool selectedLine(const Capture &c)
|
|||||||
}
|
}
|
||||||
void syncLineOptions(HWND w,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,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());
|
EnableWindow(GetDlgItem(w,35),c.selected>=0 && c.marks[c.selected].isLine());
|
||||||
bool selected=selectedLine(c),enabled=selected || c.arrow || c.freehand;
|
bool selected=selectedLine(c),enabled=selected || c.arrow || c.freehand;
|
||||||
@@ -605,7 +687,7 @@ void layout(HWND w, Capture &c)
|
|||||||
RECT statusRect{}; GetWindowRect(status,&statusRect);
|
RECT statusRect{}; GetWindowRect(status,&statusRect);
|
||||||
c.statusHeight=statusRect.bottom-statusRect.top;
|
c.statusHeight=statusRect.bottom-statusRect.top;
|
||||||
r.bottom-=c.statusHeight;
|
r.bottom-=c.statusHeight;
|
||||||
const int positions[]{8,44,80,116,152,188,224,260,296,332,368,416,452,500};
|
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));
|
static_assert(std::size(positions)==std::size(ToolIds));
|
||||||
for (size_t i = 0; i < std::size(ToolIds); ++i)
|
for (size_t i = 0; i < std::size(ToolIds); ++i)
|
||||||
{
|
{
|
||||||
@@ -614,10 +696,14 @@ void layout(HWND w, Capture &c)
|
|||||||
MulDiv(32,dpi,96),MulDiv(32,dpi,96),TRUE);
|
MulDiv(32,dpi,96),MulDiv(32,dpi,96),TRUE);
|
||||||
}
|
}
|
||||||
SendDlgItemMessageW(w,28,WM_SETFONT,(WPARAM)c.font,TRUE);
|
SendDlgItemMessageW(w,28,WM_SETFONT,(WPARAM)c.font,TRUE);
|
||||||
MoveWindow(GetDlgItem(w,28),MulDiv(540,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);
|
MulDiv(78,dpi,96),MulDiv(32,dpi,96),TRUE);
|
||||||
c.panelHeight=c.unit+MulDiv(40,dpi,96);
|
c.panelHeight=c.unit+MulDiv(80,dpi,96);
|
||||||
for(int id:{30,31,32,33,34,35}) SendDlgItemMessageW(w,id,WM_SETFONT,(WPARAM)c.font,TRUE);
|
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,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,30),MulDiv(80,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(150,dpi,96),MulDiv(180,dpi,96),TRUE);
|
||||||
MoveWindow(GetDlgItem(w,33),MulDiv(248,dpi,96),c.unit+MulDiv(6,dpi,96),MulDiv(40,dpi,96),MulDiv(24,dpi,96),TRUE);
|
MoveWindow(GetDlgItem(w,33),MulDiv(248,dpi,96),c.unit+MulDiv(6,dpi,96),MulDiv(40,dpi,96),MulDiv(24,dpi,96),TRUE);
|
||||||
@@ -625,13 +711,35 @@ void layout(HWND w, Capture &c)
|
|||||||
MoveWindow(GetDlgItem(w,34),MulDiv(480,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(28,dpi,96),MulDiv(28,dpi,96),TRUE);
|
MoveWindow(GetDlgItem(w,34),MulDiv(480,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(28,dpi,96),MulDiv(28,dpi,96),TRUE);
|
||||||
MoveWindow(GetDlgItem(w,35),MulDiv(516,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(28,dpi,96),MulDiv(28,dpi,96),TRUE);
|
MoveWindow(GetDlgItem(w,35),MulDiv(516,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(28,dpi,96),MulDiv(28,dpi,96),TRUE);
|
||||||
syncLineOptions(w,c);
|
syncLineOptions(w,c);
|
||||||
double ratio = std::min({1.0, double(std::max(1L,r.right-16))/c.image->width,
|
c.canvas={0,c.panelHeight,r.right,std::max(LONG(c.panelHeight+1),r.bottom)};
|
||||||
|
double ratio = c.zoom*std::min({1.0, double(std::max(1L,r.right-16))/c.image->width,
|
||||||
double(std::max(1L,r.bottom-c.panelHeight-16))/c.image->height});
|
double(std::max(1L,r.bottom-c.panelHeight-16))/c.image->height});
|
||||||
int width = int(c.image->width*ratio), height = int(c.image->height*ratio);
|
int width = std::max(1,int(std::lround(c.image->width*ratio))), height = std::max(1,int(std::lround(c.image->height*ratio)));
|
||||||
c.view = {(r.right-width)/2, c.panelHeight+(r.bottom-c.panelHeight-height)/2,
|
double maxX=std::max(0.0,(width-double(c.canvas.right-c.canvas.left))/2);
|
||||||
(r.right+width)/2, c.panelHeight+(r.bottom-c.panelHeight+height)/2};
|
double maxY=std::max(0.0,(height-double(c.canvas.bottom-c.canvas.top))/2);
|
||||||
|
c.panX=std::clamp(c.panX,-maxX,maxX); c.panY=std::clamp(c.panY,-maxY,maxY);
|
||||||
|
LONG x=LONG(std::lround((r.right-width)/2.0+c.panX));
|
||||||
|
LONG y=LONG(std::lround(c.panelHeight+(r.bottom-c.panelHeight-height)/2.0+c.panY));
|
||||||
|
c.view = {x,y,x+width,y+height};
|
||||||
InvalidateRect(w, nullptr, FALSE);
|
InvalidateRect(w, nullptr, FALSE);
|
||||||
}
|
}
|
||||||
|
void zoomCanvas(HWND w,Capture &c,double factor,POINT anchor,bool reset=false)
|
||||||
|
{
|
||||||
|
if(!c.editing || c.dragging || c.panning) return;
|
||||||
|
double u=double(anchor.x-c.view.left)/std::max(1L,c.view.right-c.view.left);
|
||||||
|
double v=double(anchor.y-c.view.top)/std::max(1L,c.view.bottom-c.view.top);
|
||||||
|
double next=reset?1.0:std::clamp(c.zoom*factor,.1,16.0);
|
||||||
|
if(next==c.zoom && !reset) return;
|
||||||
|
c.zoom=next;
|
||||||
|
if(reset) c.panX=c.panY=0;
|
||||||
|
layout(w,c);
|
||||||
|
if(!reset) {
|
||||||
|
c.panX+=anchor.x-(c.view.left+u*(c.view.right-c.view.left));
|
||||||
|
c.panY+=anchor.y-(c.view.top+v*(c.view.bottom-c.view.top));
|
||||||
|
layout(w,c);
|
||||||
|
}
|
||||||
|
positionInlineText(c); updateStatus(c); InvalidateRect(w,nullptr,FALSE);
|
||||||
|
}
|
||||||
POINT imagePoint(Capture &c, POINT p, bool clamp = true)
|
POINT imagePoint(Capture &c, POINT p, bool clamp = true)
|
||||||
{
|
{
|
||||||
POINT result{MulDiv(p.x-c.view.left,c.image->width,std::max(1L,c.view.right-c.view.left)),
|
POINT result{MulDiv(p.x-c.view.left,c.image->width,std::max(1L,c.view.right-c.view.left)),
|
||||||
@@ -659,6 +767,10 @@ std::pair<int,MarkPart> markAt(Capture &c, POINT p)
|
|||||||
if(c.selected>=0)
|
if(c.selected>=0)
|
||||||
{
|
{
|
||||||
const auto &m=c.marks[c.selected];
|
const auto &m=c.marks[c.selected];
|
||||||
|
if(m.shape!=ScreenshotShape::None) {
|
||||||
|
auto grip=screenshotShapeRotationHandle(m,double(c.unit)*c.image->width/std::max(1L,c.view.right-c.view.left));
|
||||||
|
if(std::hypot(double(p.x-grip.x),double(p.y-grip.y))<=tolerance) return {c.selected,MarkPart::Rotation};
|
||||||
|
}
|
||||||
if(m.isText() || (m.isLine() && !m.label.empty())) {
|
if(m.isText() || (m.isLine() && !m.label.empty())) {
|
||||||
auto text=m.isText()?m:screenshotArrowLabel(m);
|
auto text=m.isText()?m:screenshotArrowLabel(m);
|
||||||
auto grip=screenshotTextRotationHandle(text,double(c.unit*0.6)*c.image->width/std::max(1L,c.view.right-c.view.left));
|
auto grip=screenshotTextRotationHandle(text,double(c.unit*0.6)*c.image->width/std::max(1L,c.view.right-c.view.left));
|
||||||
@@ -682,7 +794,7 @@ HCURSOR toolCursor(const Capture &c)
|
|||||||
if(c.pointer) return LoadCursorW(nullptr,IDC_ARROW);
|
if(c.pointer) return LoadCursorW(nullptr,IDC_ARROW);
|
||||||
if(c.textTool) return LoadCursorW(nullptr,IDC_IBEAM);
|
if(c.textTool) return LoadCursorW(nullptr,IDC_IBEAM);
|
||||||
if(c.freehand && c.pencilCursor) return c.pencilCursor;
|
if(c.freehand && c.pencilCursor) return c.pencilCursor;
|
||||||
int tool=c.highlight?19:c.straight?22: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)
|
for(size_t i=0;i<std::size(CursorTools);++i)
|
||||||
if(CursorTools[i]==tool && c.drawingCursors[i]) return c.drawingCursors[i];
|
if(CursorTools[i]==tool && c.drawingCursors[i]) return c.drawingCursors[i];
|
||||||
return LoadCursorW(nullptr,IDC_CROSS);
|
return LoadCursorW(nullptr,IDC_CROSS);
|
||||||
@@ -693,12 +805,14 @@ HCURSOR actionCursor(const Capture &c,std::pair<int,MarkPart> hit,bool inside)
|
|||||||
LPCWSTR cursor=nullptr;
|
LPCWSTR cursor=nullptr;
|
||||||
if(hit.second==MarkPart::Body || hit.second==MarkPart::Label) cursor=IDC_SIZEALL;
|
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::Rotation) cursor=IDC_HAND;
|
||||||
else if(hit.second==MarkPart::Radius) cursor=IDC_SIZEWE;
|
else if(hit.second>=MarkPart::Vertex0 && hit.second<=MarkPart::Vertex2) cursor=IDC_SIZEALL;
|
||||||
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];
|
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));
|
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;
|
int axis=(int(std::lround(angle/(3.141592653589793/4)))+8)%4;
|
||||||
const LPCWSTR cursors[]{IDC_SIZEWE,IDC_SIZENWSE,IDC_SIZENS,IDC_SIZENESW};
|
const LPCWSTR cursors[]{IDC_SIZEWE,IDC_SIZENWSE,IDC_SIZENS,IDC_SIZENESW};
|
||||||
cursor=cursors[axis];
|
cursor=cursors[axis];
|
||||||
@@ -708,7 +822,7 @@ HCURSOR actionCursor(const Capture &c,std::pair<int,MarkPart> hit,bool inside)
|
|||||||
void captureCursor(HWND w, Capture &c)
|
void captureCursor(HWND w, Capture &c)
|
||||||
{
|
{
|
||||||
POINT p; GetCursorPos(&p); ScreenToClient(w,&p);
|
POINT p; GetCursorPos(&p); ScreenToClient(w,&p);
|
||||||
bool inside=PtInRect(&c.view,p)!=FALSE;
|
bool inside=PtInRect(&c.view,p) && PtInRect(&c.canvas,p);
|
||||||
auto hit=c.editing?(c.dragging?std::pair{c.selected,c.part}:markAt(c,imagePoint(c,p,false))):std::pair{-1,MarkPart::None};
|
auto hit=c.editing?(c.dragging?std::pair{c.selected,c.part}:markAt(c,imagePoint(c,p,false))):std::pair{-1,MarkPart::None};
|
||||||
if(!c.dragging && !inside && hit.second!=MarkPart::Thickness && hit.second!=MarkPart::Rotation) hit={-1,MarkPart::None};
|
if(!c.dragging && !inside && hit.second!=MarkPart::Thickness && hit.second!=MarkPart::Rotation) hit={-1,MarkPart::None};
|
||||||
SetCursor(actionCursor(c,hit,inside || c.dragging));
|
SetCursor(actionCursor(c,hit,inside || c.dragging));
|
||||||
@@ -764,7 +878,18 @@ void drawHandles(HDC dc, const Capture &c)
|
|||||||
handle({m.from.x+m.radius,m.from.y});
|
handle({m.from.x+m.radius,m.from.y});
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
handle(m.from); handle(m.to);
|
if(m.shape==ScreenshotShape::Triangle) {
|
||||||
|
auto vertices=shapeOutline(m);
|
||||||
|
for(size_t i=0;i<3;++i) handle(vertices[i]);
|
||||||
|
} else { handle(rotateShapePoint(m,m.from)); handle(rotateShapePoint(m,m.to)); }
|
||||||
|
if(m.shape!=ScreenshotShape::None) {
|
||||||
|
auto r=region(m.from,m.to);
|
||||||
|
auto top=point(rotateShapePoint(m,{(r.left+r.right)/2,r.top}));
|
||||||
|
auto grip=screenshotShapeRotationHandle(m,double(c.unit)*c.image->width/std::max(1L,c.view.right-c.view.left));
|
||||||
|
auto end=point(grip); MoveToEx(dc,top.x,top.y,nullptr); LineTo(dc,end.x,end.y);
|
||||||
|
int radius=std::max(4,c.unit/8);
|
||||||
|
Ellipse(dc,end.x-radius,end.y-radius,end.x+radius+1,end.y+radius+1);
|
||||||
|
}
|
||||||
auto [from,to]=thicknessSegment(m);
|
auto [from,to]=thicknessSegment(m);
|
||||||
auto mid=point({(from.x+to.x)/2,(from.y+to.y)/2});
|
auto mid=point({(from.x+to.x)/2,(from.y+to.y)/2});
|
||||||
auto grip=thicknessHandle(c,m),end=point(grip);
|
auto grip=thicknessHandle(c,m),end=point(grip);
|
||||||
@@ -780,7 +905,8 @@ void drawTool(const DRAWITEMSTRUCT &item, const Capture &c)
|
|||||||
RECT r=item.rcItem;
|
RECT r=item.rcItem;
|
||||||
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)||
|
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==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==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==38 && c.shape==ScreenshotShape::Arc);
|
||||||
bool disabled=item.itemState&ODS_DISABLED;
|
bool disabled=item.itemState&ODS_DISABLED;
|
||||||
POINT mouse; GetCursorPos(&mouse); ScreenToClient(item.hwndItem,&mouse);
|
POINT mouse; GetCursorPos(&mouse); ScreenToClient(item.hwndItem,&mouse);
|
||||||
bool hover=PtInRect(&r,mouse) && !disabled;
|
bool hover=PtInRect(&r,mouse) && !disabled;
|
||||||
@@ -794,7 +920,17 @@ void drawTool(const DRAWITEMSTRUCT &item, const Capture &c)
|
|||||||
RoundRect(dc,r.left,r.top,r.right,r.bottom,corner,corner);
|
RoundRect(dc,r.left,r.top,r.right,r.bottom,corner,corner);
|
||||||
SelectObject(dc,oldPen); SelectObject(dc,oldBrush); DeleteObject(pen); DeleteObject(brush);
|
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;
|
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==27?(HICON)LoadCursorW(nullptr,IDC_ARROW):c.toolIcons[disabled?2:active?1:0][iconIndex];
|
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==38) Arc(dc,cx-s,cy-s,cx+s,cy+3*s,cx+s,cy+s,cx-s,cy+s);
|
||||||
|
else if(item.CtlID==36) { POINT vertices[]{{cx,cy-s},{cx+s,cy+s},{cx-s,cy+s},{cx,cy-s}}; Polyline(dc,vertices,4); }
|
||||||
|
else { POINT vertices[]{{cx-s/2,cy-s},{cx+s/2,cy-s},{cx+s,cy+s},{cx-s,cy+s},{cx-s/2,cy-s}}; Polyline(dc,vertices,5); }
|
||||||
|
SelectObject(dc,previous); DeleteObject(trianglePen);
|
||||||
|
}
|
||||||
if(icon) DrawIconEx(dc,(r.right-c.iconSize)/2,(r.bottom-c.iconSize)/2,icon,c.iconSize,c.iconSize,0,nullptr,DI_NORMAL);
|
if(icon) DrawIconEx(dc,(r.right-c.iconSize)/2,(r.bottom-c.iconSize)/2,icon,c.iconSize,c.iconSize,0,nullptr,DI_NORMAL);
|
||||||
if(item.CtlID==20) {
|
if(item.CtlID==20) {
|
||||||
auto color=c.selected>=0?c.marks[c.selected].color:c.currentColor;
|
auto color=c.selected>=0?c.marks[c.selected].color:c.currentColor;
|
||||||
@@ -913,7 +1049,7 @@ void edit(HWND w, Capture &c)
|
|||||||
InitCommonControlsEx(&statusControls);
|
InitCommonControlsEx(&statusControls);
|
||||||
CreateWindowExW(0,STATUSCLASSNAMEW,L"",WS_CHILD|WS_VISIBLE|SBARS_TOOLTIPS,
|
CreateWindowExW(0,STATUSCLASSNAMEW,L"",WS_CHILD|WS_VISIBLE|SBARS_TOOLTIPS,
|
||||||
0,0,0,0,w,(HMENU)50,c.app.instance,nullptr);
|
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"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)"};
|
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));
|
static_assert(std::size(labels)==std::size(ToolIds));
|
||||||
auto saveButton=CreateWindowW(L"BUTTON",L"Save...",WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_PUSHBUTTON,
|
auto saveButton=CreateWindowW(L"BUTTON",L"Save...",WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_PUSHBUTTON,
|
||||||
@@ -949,6 +1085,14 @@ void edit(HWND w, Capture &c)
|
|||||||
SetWindowSubclass(labelButton,toolHover,1,0);
|
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");
|
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);
|
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();
|
c.syncHistory();
|
||||||
auto work = monitor.rcWork;
|
auto work = monitor.rcWork;
|
||||||
SetWindowPos(w,HWND_NOTOPMOST,work.left+20,work.top+20,
|
SetWindowPos(w,HWND_NOTOPMOST,work.left+20,work.top+20,
|
||||||
@@ -1008,7 +1152,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case WM_DRAWITEM:
|
case WM_DRAWITEM:
|
||||||
if((wp>=10 && wp<=13) || (wp>=18 && wp<=27) || wp==34 || wp==35) { 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;
|
break;
|
||||||
case WM_CTLCOLORSTATIC:
|
case WM_CTLCOLORSTATIC:
|
||||||
SetBkColor((HDC)wp,RGB(255,255,255)); SetTextColor((HDC)wp,RGB(51,65,85));
|
SetBkColor((HDC)wp,RGB(255,255,255)); SetTextColor((HDC)wp,RGB(51,65,85));
|
||||||
@@ -1017,6 +1161,21 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
case WM_SETCURSOR:
|
case WM_SETCURSOR:
|
||||||
if ((HWND)wp==w && LOWORD(lp)==HTCLIENT) { captureCursor(w,*c); return TRUE; }
|
if ((HWND)wp==w && LOWORD(lp)==HTCLIENT) { captureCursor(w,*c); return TRUE; }
|
||||||
break;
|
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:
|
case WM_COMMAND:
|
||||||
if(LOWORD(wp)==40) {
|
if(LOWORD(wp)==40) {
|
||||||
if(c->inlineText && HIWORD(wp)==EN_CHANGE) { readInlineText(*c); positionInlineText(*c); }
|
if(c->inlineText && HIWORD(wp)==EN_CHANGE) { readInlineText(*c); positionInlineText(*c); }
|
||||||
@@ -1024,6 +1183,17 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
if (c->dragging) 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) {
|
if(LOWORD(wp)==35) {
|
||||||
finishInlineText(w,*c,true);
|
finishInlineText(w,*c,true);
|
||||||
if(c->selected>=0 && c->marks[c->selected].isLine()) beginMarkText(w,*c,c->selected);
|
if(c->selected>=0 && c->marks[c->selected].isLine()) beginMarkText(w,*c,c->selected);
|
||||||
@@ -1102,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; }
|
if(changed) { c->copied=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; }
|
||||||
c->syncHistory();
|
c->syncHistory();
|
||||||
}
|
}
|
||||||
if (LOWORD(wp)==10 || LOWORD(wp)==11 || LOWORD(wp)==19 || (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->pointer=LOWORD(wp)==27;
|
||||||
c->arrow = LOWORD(wp)==11 || (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->straight=LOWORD(wp)==22;
|
||||||
c->textTool=LOWORD(wp)==26;
|
c->textTool=LOWORD(wp)==26;
|
||||||
c->shape=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->selected=-1; c->selectedLabel=false;
|
||||||
c->highlight=LOWORD(wp)==19;
|
c->highlight=LOWORD(wp)==19;
|
||||||
c->freehand=LOWORD(wp)==21;
|
c->freehand=LOWORD(wp)==21;
|
||||||
@@ -1119,12 +1289,16 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
InvalidateRect(GetDlgItem(w,19),nullptr,FALSE);
|
InvalidateRect(GetDlgItem(w,19),nullptr,FALSE);
|
||||||
InvalidateRect(GetDlgItem(w,21),nullptr,FALSE);
|
InvalidateRect(GetDlgItem(w,21),nullptr,FALSE);
|
||||||
for(int id=22;id<=27;++id) InvalidateRect(GetDlgItem(w,id),nullptr,FALSE);
|
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;
|
SetFocus(w); captureCursor(w,*c); InvalidateRect(w,nullptr,FALSE); return 0;
|
||||||
case WM_KEYDOWN:
|
case WM_KEYDOWN:
|
||||||
if(wp==VK_SHIFT && c->editing && c->dragging && c->freehand && c->part==MarkPart::None && !c->strokeConstrained) {
|
if(wp==VK_SHIFT && c->editing && c->dragging && c->freehand && c->part==MarkPart::None && !c->strokeConstrained) {
|
||||||
c->strokeConstrained=true;
|
c->strokeConstrained=true;
|
||||||
|
c->strokeUsedConstraint=true;
|
||||||
c->strokeAnchor=c->stroke.points.size()-1;
|
c->strokeAnchor=c->stroke.points.size()-1;
|
||||||
c->strokeAxis=0;
|
c->strokeAxis=0;
|
||||||
c->strokeAxisSettled=false;
|
c->strokeAxisSettled=false;
|
||||||
@@ -1136,6 +1310,12 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
}
|
}
|
||||||
if (c->editing && !c->dragging)
|
if (c->editing && !c->dragging)
|
||||||
{
|
{
|
||||||
|
if((GetKeyState(VK_CONTROL)&0x8000) &&
|
||||||
|
(wp==VK_OEM_PLUS || wp==VK_ADD || wp==VK_OEM_MINUS || wp==VK_SUBTRACT || wp=='0' || wp==VK_NUMPAD0)) {
|
||||||
|
POINT center{(c->canvas.left+c->canvas.right)/2,(c->canvas.top+c->canvas.bottom)/2};
|
||||||
|
zoomCanvas(w,*c,wp==VK_OEM_MINUS || wp==VK_SUBTRACT?1/1.25:1.25,center,wp=='0' || wp==VK_NUMPAD0);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
if(wp>=VK_LEFT && wp<=VK_DOWN && c->selected>=0 && !c->inlineText) {
|
if(wp>=VK_LEFT && wp<=VK_DOWN && c->selected>=0 && !c->inlineText) {
|
||||||
POINT delta{wp==VK_LEFT?-1L:wp==VK_RIGHT?1L:0L,wp==VK_UP?-1L:wp==VK_DOWN?1L:0L};
|
POINT delta{wp==VK_LEFT?-1L:wp==VK_RIGHT?1L:0L,wp==VK_UP?-1L:wp==VK_DOWN?1L:0L};
|
||||||
const auto &original=c->marks[c->selected];
|
const auto &original=c->marks[c->selected];
|
||||||
@@ -1170,6 +1350,9 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
if(wp=='R') SendMessageW(w,WM_COMMAND,23,0);
|
if(wp=='R') SendMessageW(w,WM_COMMAND,23,0);
|
||||||
if(wp=='O') SendMessageW(w,WM_COMMAND,24,0);
|
if(wp=='O') SendMessageW(w,WM_COMMAND,24,0);
|
||||||
if(wp=='E') SendMessageW(w,WM_COMMAND,25,0);
|
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=='N' || wp=='A') SendMessageW(w,WM_COMMAND,wp=='N'?10:11,0);
|
||||||
if(wp=='H') SendMessageW(w,WM_COMMAND,19,0);
|
if(wp=='H') SendMessageW(w,WM_COMMAND,19,0);
|
||||||
@@ -1194,7 +1377,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
case WM_LBUTTONDBLCLK:
|
case WM_LBUTTONDBLCLK:
|
||||||
if(c->editing && !c->dragging) {
|
if(c->editing && !c->dragging) {
|
||||||
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||||
if(PtInRect(&c->view,p)) {
|
if(PtInRect(&c->view,p) && PtInRect(&c->canvas,p)) {
|
||||||
auto [index,part]=markAt(*c,imagePoint(*c,p));
|
auto [index,part]=markAt(*c,imagePoint(*c,p));
|
||||||
if(index>=0 && (c->marks[index].isText() || c->marks[index].isLine())) {
|
if(index>=0 && (c->marks[index].isText() || c->marks[index].isLine())) {
|
||||||
c->selected=index; beginMarkText(w,*c,index);
|
c->selected=index; beginMarkText(w,*c,index);
|
||||||
@@ -1204,8 +1387,10 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
return 0;
|
return 0;
|
||||||
case WM_LBUTTONDOWN:
|
case WM_LBUTTONDOWN:
|
||||||
{
|
{
|
||||||
|
if(c->panning) return 0;
|
||||||
finishInlineText(w,*c,true);
|
finishInlineText(w,*c,true);
|
||||||
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||||
|
if(c->editing && !PtInRect(&c->canvas,p)) return 0;
|
||||||
auto hitPart=c->editing?markAt(*c,imagePoint(*c,p,false)).second:MarkPart::None;
|
auto hitPart=c->editing?markAt(*c,imagePoint(*c,p,false)).second:MarkPart::None;
|
||||||
bool thickness=hitPart==MarkPart::Thickness || hitPart==MarkPart::Rotation;
|
bool thickness=hitPart==MarkPart::Thickness || hitPart==MarkPart::Rotation;
|
||||||
if (c->editing && !PtInRect(&c->view,p) && !thickness)
|
if (c->editing && !PtInRect(&c->view,p) && !thickness)
|
||||||
@@ -1248,6 +1433,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
c->stroke.freehand=c->freehand; c->stroke.style=c->lineStyle; c->stroke.ends=c->freehandEnds;
|
c->stroke.freehand=c->freehand; c->stroke.style=c->lineStyle; c->stroke.ends=c->freehandEnds;
|
||||||
c->stroke.points.push_back(p);
|
c->stroke.points.push_back(p);
|
||||||
c->strokeConstrained=false;
|
c->strokeConstrained=false;
|
||||||
|
c->strokeUsedConstraint=(wp&MK_SHIFT)!=0;
|
||||||
}
|
}
|
||||||
c->dragging=true; SetCapture(w);
|
c->dragging=true; SetCapture(w);
|
||||||
}
|
}
|
||||||
@@ -1255,8 +1441,17 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
}
|
}
|
||||||
case WM_MOUSEWHEEL:
|
case WM_MOUSEWHEEL:
|
||||||
{
|
{
|
||||||
if(!c->editing || c->dragging) return 0;
|
if(!c->editing || c->dragging || c->panning) return 0;
|
||||||
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; ScreenToClient(w,&p);
|
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; ScreenToClient(w,&p);
|
||||||
|
if(!PtInRect(&c->canvas,p)) return 0;
|
||||||
|
if(GET_KEYSTATE_WPARAM(wp)&MK_CONTROL) {
|
||||||
|
c->wheelDelta=0; c->wheelTarget=-1;
|
||||||
|
c->zoomWheelDelta+=GET_WHEEL_DELTA_WPARAM(wp);
|
||||||
|
int steps=c->zoomWheelDelta/WHEEL_DELTA; c->zoomWheelDelta%=WHEEL_DELTA;
|
||||||
|
if(steps) zoomCanvas(w,*c,std::pow(1.25,steps),p);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
c->zoomWheelDelta=0;
|
||||||
if(!PtInRect(&c->view,p)) return 0;
|
if(!PtInRect(&c->view,p)) return 0;
|
||||||
auto [index,part]=markAt(*c,imagePoint(*c,p));
|
auto [index,part]=markAt(*c,imagePoint(*c,p));
|
||||||
if(index<0) { c->wheelDelta=0; c->wheelTarget=-1; return 0; }
|
if(index<0) { c->wheelDelta=0; c->wheelTarget=-1; return 0; }
|
||||||
@@ -1276,8 +1471,27 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
case WM_MBUTTONDOWN:
|
||||||
|
{
|
||||||
|
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||||
|
if(c->editing && !c->dragging && PtInRect(&c->canvas,p)) {
|
||||||
|
c->panning=true; c->panOrigin=p; SetCapture(w); SetCursor(LoadCursorW(nullptr,IDC_SIZEALL));
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
case WM_MBUTTONUP:
|
||||||
|
if(c->panning) { c->panning=false; ReleaseCapture(); captureCursor(w,*c); }
|
||||||
|
return 0;
|
||||||
case WM_MOUSEMOVE:
|
case WM_MOUSEMOVE:
|
||||||
case WM_LBUTTONUP:
|
case WM_LBUTTONUP:
|
||||||
|
if(c->panning) {
|
||||||
|
if(msg==WM_MOUSEMOVE) {
|
||||||
|
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||||
|
c->panX+=p.x-c->panOrigin.x; c->panY+=p.y-c->panOrigin.y; c->panOrigin=p;
|
||||||
|
layout(w,*c); positionInlineText(*c); SetCursor(LoadCursorW(nullptr,IDC_SIZEALL));
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
if (c->dragging)
|
if (c->dragging)
|
||||||
{
|
{
|
||||||
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||||
@@ -1286,6 +1500,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
c->end=constrainScreenshotShape(c->shape,c->start,c->end,c->image->width,c->image->height);
|
c->end=constrainScreenshotShape(c->shape,c->start,c->end,c->image->width,c->image->height);
|
||||||
if(c->editing && (c->highlight || c->freehand) && c->part==MarkPart::None) {
|
if(c->editing && (c->highlight || c->freehand) && c->part==MarkPart::None) {
|
||||||
bool constrained=c->freehand && ((wp&MK_SHIFT) || (GetKeyState(VK_SHIFT)&0x8000));
|
bool constrained=c->freehand && ((wp&MK_SHIFT) || (GetKeyState(VK_SHIFT)&0x8000));
|
||||||
|
c->strokeUsedConstraint=c->strokeUsedConstraint || constrained;
|
||||||
if(constrained) {
|
if(constrained) {
|
||||||
if(!c->strokeConstrained) {
|
if(!c->strokeConstrained) {
|
||||||
c->strokeAnchor=c->stroke.points.size()-1;
|
c->strokeAnchor=c->stroke.points.size()-1;
|
||||||
@@ -1375,10 +1590,38 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
c->remember(c->marks); c->marks.push_back(std::move(c->stroke));
|
c->remember(c->marks); c->marks.push_back(std::move(c->stroke));
|
||||||
if(c->freehand) {
|
if(c->freehand) {
|
||||||
auto &mark=c->marks.back();
|
auto &mark=c->marks.back();
|
||||||
|
mark.rawPoints=mark.points;
|
||||||
linkScreenshotEndpoint(mark,true,c->start,c->marks,6);
|
linkScreenshotEndpoint(mark,true,c->start,c->marks,6);
|
||||||
linkScreenshotEndpoint(mark,false,c->end,c->marks,6);
|
linkScreenshotEndpoint(mark,false,c->end,c->marks,6);
|
||||||
resolveScreenshotLinks(c->marks);
|
resolveScreenshotLinks(c->marks);
|
||||||
}
|
}
|
||||||
|
if(c->freehand && !c->strokeUsedConstraint &&
|
||||||
|
!c->marks.back().fromNumber && !c->marks.back().toNumber &&
|
||||||
|
!c->marks.back().fromLink.target && !c->marks.back().toLink.target) {
|
||||||
|
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();
|
||||||
|
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) {
|
||||||
|
mark.shape=recognized; mark.freehand=false; mark.ends=LineEnds::None;
|
||||||
|
auto bounds=markBounds(mark);
|
||||||
|
mark.from={bounds.left,bounds.top}; mark.to={bounds.right,bounds.bottom};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
c->selected=int(c->marks.size())-1; c->selectedLabel=false;
|
c->selected=int(c->marks.size())-1; c->selectedLabel=false;
|
||||||
}
|
}
|
||||||
else if (std::hypot(double(c->end.x-c->start.x),double(c->end.y-c->start.y))>=4)
|
else if (std::hypot(double(c->end.x-c->start.x),double(c->end.y-c->start.y))>=4)
|
||||||
@@ -1389,6 +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().style=c->lineStyle; c->marks.back().ends=c->straight || c->shape!=ScreenshotShape::None?LineEnds::None:c->arrowEnds;
|
||||||
c->marks.back().shape=c->shape;
|
c->marks.back().shape=c->shape;
|
||||||
auto &mark=c->marks.back();
|
auto &mark=c->marks.back();
|
||||||
|
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,true,c->start,c->marks,6);
|
||||||
linkScreenshotEndpoint(mark,false,c->end,c->marks,6);
|
linkScreenshotEndpoint(mark,false,c->end,c->marks,6);
|
||||||
resolveScreenshotLinks(c->marks);
|
resolveScreenshotLinks(c->marks);
|
||||||
@@ -1401,6 +1645,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
captureCursor(w,*c);
|
captureCursor(w,*c);
|
||||||
return 0;
|
return 0;
|
||||||
case WM_CAPTURECHANGED:
|
case WM_CAPTURECHANGED:
|
||||||
|
c->panning=false;
|
||||||
if(c->dragging && c->part!=MarkPart::None)
|
if(c->dragging && c->part!=MarkPart::None)
|
||||||
{
|
{
|
||||||
c->marks=std::move(c->beforeDrag); c->part=MarkPart::None;
|
c->marks=std::move(c->beforeDrag); c->part=MarkPart::None;
|
||||||
@@ -1410,7 +1655,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
if (c->editing)
|
if (c->editing)
|
||||||
{
|
{
|
||||||
auto limits = reinterpret_cast<MINMAXINFO *>(lp);
|
auto limits = reinterpret_cast<MINMAXINFO *>(lp);
|
||||||
limits->ptMinTrackSize = {MulDiv(650,GetDpiForWindow(w),96),MulDiv(240,GetDpiForWindow(w),96)};
|
limits->ptMinTrackSize = {MulDiv(766,GetDpiForWindow(w),96),MulDiv(240,GetDpiForWindow(w),96)};
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -1460,7 +1705,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
auto previous=SelectObject(buffer,divider);
|
auto previous=SelectObject(buffer,divider);
|
||||||
MoveToEx(buffer,0,c->panelHeight-1,nullptr); LineTo(buffer,client.right,c->panelHeight-1);
|
MoveToEx(buffer,0,c->panelHeight-1,nullptr); LineTo(buffer,client.right,c->panelHeight-1);
|
||||||
int dpi=GetDpiForWindow(w);
|
int dpi=GetDpiForWindow(w);
|
||||||
for(int x:{368,452}) {
|
for(int x:{440,524}) {
|
||||||
MoveToEx(buffer,MulDiv(x,dpi,96),MulDiv(13,dpi,96),nullptr);
|
MoveToEx(buffer,MulDiv(x,dpi,96),MulDiv(13,dpi,96),nullptr);
|
||||||
LineTo(buffer,MulDiv(x,dpi,96),MulDiv(31,dpi,96));
|
LineTo(buffer,MulDiv(x,dpi,96),MulDiv(31,dpi,96));
|
||||||
}
|
}
|
||||||
@@ -1478,9 +1723,12 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
|||||||
}
|
}
|
||||||
drawMarks(rendered.dc,visibleMarks,c->dragging && c->part==MarkPart::None?((c->highlight || c->freehand)?&c->stroke:&preview):nullptr);
|
drawMarks(rendered.dc,visibleMarks,c->dragging && c->part==MarkPart::None?((c->highlight || c->freehand)?&c->stroke:&preview):nullptr);
|
||||||
SetStretchBltMode(buffer,HALFTONE); SetBrushOrgEx(buffer,0,0,nullptr);
|
SetStretchBltMode(buffer,HALFTONE); SetBrushOrgEx(buffer,0,0,nullptr);
|
||||||
|
int savedCanvas=SaveDC(buffer);
|
||||||
|
IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom);
|
||||||
StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top,
|
StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top,
|
||||||
rendered.dc,0,0,rendered.width,rendered.height,SRCCOPY);
|
rendered.dc,0,0,rendered.width,rendered.height,SRCCOPY);
|
||||||
drawHandles(buffer,*c);
|
drawHandles(buffer,*c);
|
||||||
|
RestoreDC(buffer,savedCanvas);
|
||||||
BitBlt(dc,0,0,width,height,buffer,0,0,SRCCOPY);
|
BitBlt(dc,0,0,width,height,buffer,0,0,SRCCOPY);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1525,6 +1773,11 @@ POINT screenshotTextRotationHandle(const ScreenshotMark &m,double clearance)
|
|||||||
auto r=plainTextBounds(m);
|
auto r=plainTextBounds(m);
|
||||||
return rotateTextPoint(m,{(r.left+r.right)/2,r.top-LONG(std::lround(clearance))});
|
return rotateTextPoint(m,{(r.left+r.right)/2,r.top-LONG(std::lround(clearance))});
|
||||||
}
|
}
|
||||||
|
POINT screenshotShapeRotationHandle(const ScreenshotMark &m,double clearance)
|
||||||
|
{
|
||||||
|
auto r=region(m.from,m.to);
|
||||||
|
return rotateShapePoint(m,{(r.left+r.right)/2,r.top-LONG(std::lround(clearance))});
|
||||||
|
}
|
||||||
ScreenshotMark screenshotArrowLabel(const ScreenshotMark &m)
|
ScreenshotMark screenshotArrowLabel(const ScreenshotMark &m)
|
||||||
{
|
{
|
||||||
ScreenshotMark label{{0,0},{0,0},0};
|
ScreenshotMark label{{0,0},{0,0},0};
|
||||||
@@ -1604,23 +1857,23 @@ void assignMarkIds(std::vector<ScreenshotMark> &marks)
|
|||||||
}
|
}
|
||||||
POINT objectAnchor(const ScreenshotMark &m,const ScreenshotLink &link)
|
POINT objectAnchor(const ScreenshotMark &m,const ScreenshotLink &link)
|
||||||
{
|
{
|
||||||
if(m.isText() || m.shape!=ScreenshotShape::None) {
|
if(m.isText() || (m.shape!=ScreenshotShape::None && m.points.empty())) {
|
||||||
auto r=m.isText()?plainTextBounds(m):region(m.from,m.to);
|
auto r=m.isText()?plainTextBounds(m):region(m.from,m.to);
|
||||||
POINT p{LONG(std::lround(r.left+(r.right-r.left)*link.u)),LONG(std::lround(r.top+(r.bottom-r.top)*link.v))};
|
POINT p{LONG(std::lround(r.left+(r.right-r.left)*link.u)),LONG(std::lround(r.top+(r.bottom-r.top)*link.v))};
|
||||||
return m.isText()?rotateTextPoint(m,p):p;
|
return m.isText()?rotateTextPoint(m,p):rotateShapePoint(m,p);
|
||||||
}
|
}
|
||||||
size_t segments=m.points.size()>1?m.points.size()-1:1;
|
size_t segments=m.points.size()>1?m.points.size()-1:1;
|
||||||
double along=std::clamp(link.u,0.0,1.0)*segments;
|
double along=std::clamp(link.u,0.0,1.0)*segments;
|
||||||
size_t i=std::min(size_t(along),segments-1); double t=along-i;
|
size_t i=std::min(size_t(along),segments-1); double t=along-i;
|
||||||
POINT a=m.points.size()>1?m.points[i]:m.from,b=m.points.size()>1?m.points[i+1]:m.to;
|
POINT a=m.points.size()>1?m.points[i]:m.from,b=m.points.size()>1?m.points[i+1]:m.to;
|
||||||
return {LONG(std::lround(a.x+(b.x-a.x)*t)),LONG(std::lround(a.y+(b.y-a.y)*t))};
|
return rotateShapePoint(m,{LONG(std::lround(a.x+(b.x-a.x)*t)),LONG(std::lround(a.y+(b.y-a.y)*t))});
|
||||||
}
|
}
|
||||||
bool findObjectAnchor(const ScreenshotMark &m,POINT drop,double tolerance,ScreenshotLink &link)
|
bool findObjectAnchor(const ScreenshotMark &m,POINT drop,double tolerance,ScreenshotLink &link)
|
||||||
{
|
{
|
||||||
link={m.id,0,0};
|
link={m.id,0,0};
|
||||||
if(m.isText() || m.shape!=ScreenshotShape::None) {
|
if(m.isText() || (m.shape!=ScreenshotShape::None && m.points.empty())) {
|
||||||
auto r=m.isText()?plainTextBounds(m):region(m.from,m.to);
|
auto r=m.isText()?plainTextBounds(m):region(m.from,m.to);
|
||||||
POINT p=m.isText()?rotateTextPoint(m,drop,-1):drop;
|
POINT p=m.isText()?rotateTextPoint(m,drop,-1):rotateShapePoint(m,drop,-1);
|
||||||
double w=std::max(1L,r.right-r.left),h=std::max(1L,r.bottom-r.top);
|
double w=std::max(1L,r.right-r.left),h=std::max(1L,r.bottom-r.top);
|
||||||
double x=(p.x-r.left)/w,y=(p.y-r.top)/h;
|
double x=(p.x-r.left)/w,y=(p.y-r.top)/h;
|
||||||
bool inside=x>=0 && x<=1 && y>=0 && y<=1;
|
bool inside=x>=0 && x<=1 && y>=0 && y<=1;
|
||||||
@@ -1640,6 +1893,7 @@ bool findObjectAnchor(const ScreenshotMark &m,POINT drop,double tolerance,Screen
|
|||||||
auto anchor=objectAnchor(m,link);
|
auto anchor=objectAnchor(m,link);
|
||||||
return inside || std::hypot(double(drop.x-anchor.x),double(drop.y-anchor.y))<=tolerance;
|
return inside || std::hypot(double(drop.x-anchor.x),double(drop.y-anchor.y))<=tolerance;
|
||||||
}
|
}
|
||||||
|
drop=rotateShapePoint(m,drop,-1);
|
||||||
double best=1e100;
|
double best=1e100;
|
||||||
size_t segments=m.points.size()>1?m.points.size()-1:1;
|
size_t segments=m.points.size()>1?m.points.size()-1:1;
|
||||||
for(size_t i=0;i<segments;++i) {
|
for(size_t i=0;i<segments;++i) {
|
||||||
@@ -1716,7 +1970,14 @@ void resolveScreenshotLinks(std::vector<ScreenshotMark> &marks)
|
|||||||
POINT start=from?from->from:m.from, end=to?to->from:m.to;
|
POINT start=from?from->from:m.from, end=to?to->from:m.to;
|
||||||
if(from) m.from=rim(*from,end,true);
|
if(from) m.from=rim(*from,end,true);
|
||||||
if(to) m.to=rim(*to,start,false);
|
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;
|
state[index]=2;
|
||||||
};
|
};
|
||||||
@@ -1724,6 +1985,13 @@ void resolveScreenshotLinks(std::vector<ScreenshotMark> &marks)
|
|||||||
}
|
}
|
||||||
MarkPart hitScreenshotMark(const ScreenshotMark &m, POINT p, double tolerance)
|
MarkPart hitScreenshotMark(const ScreenshotMark &m, POINT p, double tolerance)
|
||||||
{
|
{
|
||||||
|
if(m.shape==ScreenshotShape::Triangle) {
|
||||||
|
auto vertices=shapeOutline(m);
|
||||||
|
for(int i=0;i<3;++i)
|
||||||
|
if(std::hypot(double(p.x-vertices[i].x),double(p.y-vertices[i].y))<=tolerance)
|
||||||
|
return MarkPart(int(MarkPart::Vertex0)+i);
|
||||||
|
}
|
||||||
|
p=rotateShapePoint(m,p,-1);
|
||||||
if(m.isText()) {
|
if(m.isText()) {
|
||||||
auto r=plainTextBounds(m);
|
auto r=plainTextBounds(m);
|
||||||
auto local=rotateTextPoint(m,p,-1);
|
auto local=rotateTextPoint(m,p,-1);
|
||||||
@@ -1734,8 +2002,10 @@ MarkPart hitScreenshotMark(const ScreenshotMark &m, POINT p, double tolerance)
|
|||||||
auto distance=[](POINT a, POINT b) { return std::hypot(double(a.x-b.x),double(a.y-b.y)); };
|
auto distance=[](POINT a, POINT b) { return std::hypot(double(a.x-b.x),double(a.y-b.y)); };
|
||||||
if(!m.points.empty())
|
if(!m.points.empty())
|
||||||
{
|
{
|
||||||
if(m.freehand && distance(p,m.from)<=tolerance) return MarkPart::Start;
|
if(m.shape!=ScreenshotShape::Triangle) {
|
||||||
if(m.freehand && distance(p,m.to)<=tolerance) return MarkPart::End;
|
if((m.freehand || m.shape!=ScreenshotShape::None) && distance(p,m.from)<=tolerance) return MarkPart::Start;
|
||||||
|
if((m.freehand || m.shape!=ScreenshotShape::None) && distance(p,m.to)<=tolerance) return MarkPart::End;
|
||||||
|
}
|
||||||
double reach=tolerance+std::clamp(m.thickness,m.isHighlight()?4:1,m.isHighlight()?100:30)/2.0;
|
double reach=tolerance+std::clamp(m.thickness,m.isHighlight()?4:1,m.isHighlight()?100:30)/2.0;
|
||||||
POINT from=m.points.front();
|
POINT from=m.points.front();
|
||||||
for(auto to:m.points) {
|
for(auto to:m.points) {
|
||||||
@@ -1789,7 +2059,32 @@ ScreenshotMark dragScreenshotMark(const ScreenshotMark &original, MarkPart part,
|
|||||||
{
|
{
|
||||||
auto m=original;
|
auto m=original;
|
||||||
if(position.x==origin.x && position.y==origin.y) return m;
|
if(position.x==origin.x && position.y==origin.y) return m;
|
||||||
if(part==MarkPart::Rotation && (m.isText() || (m.isLine() && !m.label.empty()))) {
|
if(part>=MarkPart::Vertex0 && part<=MarkPart::Vertex2 && m.shape==ScreenshotShape::Triangle) {
|
||||||
|
if(m.points.empty()) { auto local=m; local.rotation=0; m.points=shapeOutline(local); }
|
||||||
|
size_t index=size_t(int(part)-int(MarkPart::Vertex0)),fixed=(index+1)%3;
|
||||||
|
auto fixedWorld=rotateShapePoint(m,m.points[fixed]);
|
||||||
|
auto vertexWorld=rotateShapePoint(m,m.points[index]);
|
||||||
|
POINT target{std::clamp(vertexWorld.x+position.x-origin.x,0L,LONG(width-1)),
|
||||||
|
std::clamp(vertexWorld.y+position.y-origin.y,0L,LONG(height-1))};
|
||||||
|
m.points[index]=rotateShapePoint(m,target,-1); m.points[3]=m.points[0];
|
||||||
|
RECT bounds{m.points[0].x,m.points[0].y,m.points[0].x,m.points[0].y};
|
||||||
|
for(size_t i=1;i<3;++i) {auto p=m.points[i]; 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);}
|
||||||
|
m.from={bounds.left,bounds.top}; m.to={bounds.right,bounds.bottom};
|
||||||
|
auto shifted=rotateShapePoint(m,m.points[fixed]);
|
||||||
|
LONG dx=fixedWorld.x-shifted.x,dy=fixedWorld.y-shifted.y;
|
||||||
|
m.from.x+=dx; m.to.x+=dx; m.from.y+=dy; m.to.y+=dy;
|
||||||
|
for(auto &p:m.points) {p.x+=dx;p.y+=dy;}
|
||||||
|
}
|
||||||
|
else if(part==MarkPart::Rotation && m.shape!=ScreenshotShape::None) {
|
||||||
|
double cx=(m.from.x+m.to.x)/2.0,cy=(m.from.y+m.to.y)/2.0;
|
||||||
|
if(std::hypot(position.x-cx,position.y-cy)<1) return m;
|
||||||
|
double a=std::atan2(origin.y-cy,origin.x-cx),b=std::atan2(position.y-cy,position.x-cx);
|
||||||
|
m.rotation+=(b-a)*180/3.141592653589793;
|
||||||
|
if(snapRotation) m.rotation=std::round(m.rotation/15)*15;
|
||||||
|
m.rotation=std::remainder(m.rotation,360);
|
||||||
|
}
|
||||||
|
else if(part==MarkPart::Rotation && (m.isText() || (m.isLine() && !m.label.empty()))) {
|
||||||
if(position.x==origin.x && position.y==origin.y) return m;
|
if(position.x==origin.x && position.y==origin.y) return m;
|
||||||
auto text=m.isText()?m:screenshotArrowLabel(m);
|
auto text=m.isText()?m:screenshotArrowLabel(m);
|
||||||
auto r=plainTextBounds(text);
|
auto r=plainTextBounds(text);
|
||||||
@@ -1836,20 +2131,50 @@ ScreenshotMark dragScreenshotMark(const ScreenshotMark &original, MarkPart part,
|
|||||||
return low<=high?std::clamp(delta,low,high):0L;
|
return low<=high?std::clamp(delta,low,high):0L;
|
||||||
};
|
};
|
||||||
auto bounds=markBounds(m);
|
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 dx=shift(position.x-origin.x,bounds.left,bounds.right,width);
|
||||||
LONG dy=shift(position.y-origin.y,bounds.top,bounds.bottom,height);
|
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;
|
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.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)
|
else if(part==MarkPart::Start || part==MarkPart::End)
|
||||||
{
|
{
|
||||||
|
origin=rotateShapePoint(original,origin,-1);
|
||||||
|
position=rotateShapePoint(original,position,-1);
|
||||||
(part==MarkPart::Start?m.fromNumber:m.toNumber)=0;
|
(part==MarkPart::Start?m.fromNumber:m.toNumber)=0;
|
||||||
(part==MarkPart::Start?m.fromLink:m.toLink)={};
|
(part==MarkPart::Start?m.fromLink:m.toLink)={};
|
||||||
auto &endpoint=part==MarkPart::Start?m.from:m.to;
|
auto &endpoint=part==MarkPart::Start?m.from:m.to;
|
||||||
endpoint.x=std::clamp(endpoint.x+position.x-origin.x,0L,LONG(width-1));
|
endpoint.x=std::clamp(endpoint.x+position.x-origin.x,0L,LONG(width-1));
|
||||||
endpoint.y=std::clamp(endpoint.y+position.y-origin.y,0L,LONG(height-1));
|
endpoint.y=std::clamp(endpoint.y+position.y-origin.y,0L,LONG(height-1));
|
||||||
endpoint=constrainScreenshotShape(m.shape,part==MarkPart::Start?m.to:m.from,endpoint,width,height);
|
endpoint=constrainScreenshotShape(m.shape,part==MarkPart::Start?m.to:m.from,endpoint,width,height);
|
||||||
|
if(m.shape!=ScreenshotShape::None && !m.points.empty()) {
|
||||||
|
if(m.from.x==m.to.x || m.from.y==m.to.y) return original;
|
||||||
|
// Resize the entire recognized outline, not just a pencil endpoint.
|
||||||
|
// Keep the opposite corner fixed, including when dragging across it.
|
||||||
|
double oldWidth=original.to.x-original.from.x,oldHeight=original.to.y-original.from.y;
|
||||||
|
for(auto &point:m.points) {
|
||||||
|
double u=oldWidth?(point.x-original.from.x)/oldWidth:0;
|
||||||
|
double v=oldHeight?(point.y-original.from.y)/oldHeight:0;
|
||||||
|
point={LONG(std::lround(m.from.x+u*(m.to.x-m.from.x))),
|
||||||
|
LONG(std::lround(m.from.y+v*(m.to.y-m.from.y)))};
|
||||||
|
}
|
||||||
|
}
|
||||||
if(m.freehand && !m.points.empty()) (part==MarkPart::Start?m.points.front():m.points.back())=endpoint;
|
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);
|
||||||
|
LONG dx=fixedBefore.x-fixedAfter.x,dy=fixedBefore.y-fixedAfter.y;
|
||||||
|
m.from.x+=dx; m.to.x+=dx; m.from.y+=dy; m.to.y+=dy;
|
||||||
|
for(auto &p:m.points) {p.x+=dx;p.y+=dy;}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return m;
|
return m;
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-3
@@ -15,7 +15,7 @@ void showScreenshot(ScreenshotHost &);
|
|||||||
void showScreenshotEditor(ScreenshotHost &,const Clip &);
|
void showScreenshotEditor(ScreenshotHost &,const Clip &);
|
||||||
enum class LineStyle { Solid, Dotted, Dashed, DashDot };
|
enum class LineStyle { Solid, Dotted, Dashed, DashDot };
|
||||||
enum class LineEnds { End, Start, Both, None };
|
enum class LineEnds { End, Start, Both, None };
|
||||||
enum class ScreenshotShape { None, Rectangle, Circle, Ellipse };
|
enum class ScreenshotShape { None, Rectangle, Circle, Ellipse, Triangle, Trapezoid, Arc };
|
||||||
struct ScreenshotOffset { double x, y; };
|
struct ScreenshotOffset { double x, y; };
|
||||||
struct ScreenshotLink {
|
struct ScreenshotLink {
|
||||||
unsigned long long target{};
|
unsigned long long target{};
|
||||||
@@ -39,8 +39,10 @@ struct ScreenshotMark {
|
|||||||
bool labelRotationManual=false;
|
bool labelRotationManual=false;
|
||||||
unsigned long long id{};
|
unsigned long long id{};
|
||||||
ScreenshotLink fromLink, toLink;
|
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 isText() const { return !text.empty(); }
|
||||||
bool isHighlight() const { return !points.empty() && !freehand; }
|
bool isHighlight() const { return !points.empty() && !freehand && shape==ScreenshotShape::None; }
|
||||||
bool isLine() const { return !number && !isText() && !isHighlight() && shape==ScreenshotShape::None; }
|
bool isLine() const { return !number && !isText() && !isHighlight() && shape==ScreenshotShape::None; }
|
||||||
};
|
};
|
||||||
class ScreenshotHistory {
|
class ScreenshotHistory {
|
||||||
@@ -55,7 +57,7 @@ class ScreenshotHistory {
|
|||||||
void resolveScreenshotLinks(std::vector<ScreenshotMark> &);
|
void resolveScreenshotLinks(std::vector<ScreenshotMark> &);
|
||||||
void linkScreenshotEndpoint(ScreenshotMark &, bool start, POINT drop,
|
void linkScreenshotEndpoint(ScreenshotMark &, bool start, POINT drop,
|
||||||
std::vector<ScreenshotMark> &, double tolerance);
|
std::vector<ScreenshotMark> &, double tolerance);
|
||||||
enum class MarkPart { None, Body, Start, End, Radius, Thickness, Rotation, Label };
|
enum class MarkPart { None, Body, Start, End, Radius, Thickness, Rotation, Label, Vertex0, Vertex1, Vertex2 };
|
||||||
POINT screenshotThicknessHandle(const ScreenshotMark &, double clearance = 16);
|
POINT screenshotThicknessHandle(const ScreenshotMark &, double clearance = 16);
|
||||||
ScreenshotMark cloneScreenshotMark(const ScreenshotMark &, const std::vector<ScreenshotMark> &, int width, int height);
|
ScreenshotMark cloneScreenshotMark(const ScreenshotMark &, const std::vector<ScreenshotMark> &, int width, int height);
|
||||||
int nextScreenshotNumber(const std::vector<ScreenshotMark> &);
|
int nextScreenshotNumber(const std::vector<ScreenshotMark> &);
|
||||||
@@ -65,6 +67,7 @@ ScreenshotMark dragScreenshotMark(const ScreenshotMark &, MarkPart, POINT origin
|
|||||||
POINT constrainScreenshotShape(ScreenshotShape, POINT anchor, POINT position, int width, int height);
|
POINT constrainScreenshotShape(ScreenshotShape, POINT anchor, POINT position, int width, int height);
|
||||||
RECT screenshotTextBounds(const ScreenshotMark &);
|
RECT screenshotTextBounds(const ScreenshotMark &);
|
||||||
POINT screenshotTextRotationHandle(const ScreenshotMark &, double clearance=24);
|
POINT screenshotTextRotationHandle(const ScreenshotMark &, double clearance=24);
|
||||||
|
POINT screenshotShapeRotationHandle(const ScreenshotMark &, double clearance=32);
|
||||||
ScreenshotMark screenshotArrowLabel(const ScreenshotMark &);
|
ScreenshotMark screenshotArrowLabel(const ScreenshotMark &);
|
||||||
// Render at source resolution; never reads or writes the system clipboard.
|
// Render at source resolution; never reads or writes the system clipboard.
|
||||||
Clip screenshotClip(HDC source, int width, int height, const std::vector<ScreenshotMark> &marks);
|
Clip screenshotClip(HDC source, int width, int height, const std::vector<ScreenshotMark> &marks);
|
||||||
|
|||||||
@@ -50,6 +50,30 @@ void registerScreenshotNotifications()
|
|||||||
// Notify the shell that notification identity/activation registration changed.
|
// Notify the shell that notification identity/activation registration changed.
|
||||||
SHChangeNotify(SHCNE_ASSOCCHANGED,SHCNF_IDLIST,nullptr,nullptr);
|
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)
|
bool validScreenshotToken(const std::wstring &id)
|
||||||
{
|
{
|
||||||
if(id.size()!=36) return false;
|
if(id.size()!=36) return false;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#include "screenshot.h"
|
#include "screenshot.h"
|
||||||
#include "screenshot_notifications.h"
|
#include "screenshot_notifications.h"
|
||||||
|
#include "storage.h"
|
||||||
#include <commctrl.h>
|
#include <commctrl.h>
|
||||||
#include <shellapi.h>
|
#include <shellapi.h>
|
||||||
#include <roapi.h>
|
#include <roapi.h>
|
||||||
@@ -49,6 +50,18 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
|||||||
std::wstring token;
|
std::wstring token;
|
||||||
bool autoOpenEditor=false, writeLog=false;
|
bool autoOpenEditor=false, writeLog=false;
|
||||||
int argc{}; auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
|
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") {
|
if(argc>1 && std::wstring(argv[argc-1])==L"--write-log") {
|
||||||
writeLog=true; --argc;
|
writeLog=true; --argc;
|
||||||
ks::setLoggingEnabled(true);
|
ks::setLoggingEnabled(true);
|
||||||
|
|||||||
@@ -206,7 +206,7 @@ bool notifyUpdateAvailable(const std::wstring &version)
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
// Reuse the screenshot notification identity, Windows settings and COM activator.
|
// Reuse the screenshot notification identity, Windows settings and COM activator.
|
||||||
registerScreenshotNotifications();
|
registerScreenshotNotificationsInHelper();
|
||||||
ComPtr<Notifications::IToastNotificationManagerStatics> manager;
|
ComPtr<Notifications::IToastNotificationManagerStatics> manager;
|
||||||
String managerClass(L"Windows.UI.Notifications.ToastNotificationManager");
|
String managerClass(L"Windows.UI.Notifications.ToastNotificationManager");
|
||||||
check(RoGetActivationFactory(managerClass.value,IID_PPV_ARGS(&manager)));
|
check(RoGetActivationFactory(managerClass.value,IID_PPV_ARGS(&manager)));
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ namespace ks {
|
|||||||
bool notifyScreenshot(const Clip &);
|
bool notifyScreenshot(const Clip &);
|
||||||
std::string screenshotNotificationError();
|
std::string screenshotNotificationError();
|
||||||
void registerScreenshotNotifications();
|
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();
|
int runScreenshotToastActivator();
|
||||||
DWORD startScreenshotActivationListener();
|
DWORD startScreenshotActivationListener();
|
||||||
bool validScreenshotToken(const std::wstring &);
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+478
-25
@@ -4,10 +4,27 @@
|
|||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <set>
|
#include <set>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
#include <wincrypt.h>
|
||||||
|
|
||||||
namespace ks
|
namespace ks
|
||||||
{
|
{
|
||||||
using Json = nlohmann::json;
|
using Json = nlohmann::json;
|
||||||
|
std::wstring snippetId(const Snippet &snippet)
|
||||||
|
{
|
||||||
|
if (!snippet.id.empty()) return snippet.id;
|
||||||
|
// Deterministic migration of pre-ID profiles on every existing device.
|
||||||
|
std::wstring id = L"legacy-";
|
||||||
|
const wchar_t *hex = L"0123456789abcdef";
|
||||||
|
for (unsigned char c : utf8(lower(snippet.trigger))) { id += hex[c >> 4]; id += hex[c & 15]; }
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
std::wstring newSnippetId()
|
||||||
|
{
|
||||||
|
GUID guid{}; wchar_t text[40]{};
|
||||||
|
if (FAILED(CoCreateGuid(&guid))) throw std::runtime_error("Cannot create snippet ID.");
|
||||||
|
StringFromGUID2(guid, text, 40);
|
||||||
|
return text;
|
||||||
|
}
|
||||||
namespace
|
namespace
|
||||||
{
|
{
|
||||||
Bytes jsonBytes(const Json &j)
|
Bytes jsonBytes(const Json &j)
|
||||||
@@ -44,6 +61,25 @@ bool validId(const std::wstring &id)
|
|||||||
} // namespace
|
} // namespace
|
||||||
void validateSettings(const Settings &s)
|
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)
|
if (s.tesseractPath.size() > 32700 || s.tesseractPath.find_first_of(L"\r\n\"") != s.tesseractPath.npos)
|
||||||
throw std::runtime_error("Invalid Tesseract executable path");
|
throw std::runtime_error("Invalid Tesseract executable path");
|
||||||
if (s.tesseractLanguages.empty() || s.tesseractLanguages.size() > 128 ||
|
if (s.tesseractLanguages.empty() || s.tesseractLanguages.size() > 128 ||
|
||||||
@@ -92,6 +128,21 @@ void validateSettings(const Settings &s)
|
|||||||
throw std::runtime_error("Unsupported auto-correction language");
|
throw std::runtime_error("Unsupported auto-correction language");
|
||||||
if (s.autoNever.size() > 10000 || s.autoExcluded.size() > 1000)
|
if (s.autoNever.size() > 10000 || s.autoExcluded.size() > 1000)
|
||||||
throw std::runtime_error("Too many auto-correction exceptions");
|
throw std::runtime_error("Too many auto-correction exceptions");
|
||||||
|
if (s.autoReplacements.size() > 10000)
|
||||||
|
throw std::runtime_error("Too many automatic replacements");
|
||||||
|
for (const auto &[from, to] : s.autoReplacements)
|
||||||
|
{
|
||||||
|
bool valid = false;
|
||||||
|
for (auto alphabet : {L"abcdefghijklmnopqrstuvwxyz", L"абвгґдеєжзиіїйклмнопрстуфхцчшщьюя",
|
||||||
|
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(std::wstring(alphabet) + L" ") == to.npos &&
|
||||||
|
to.front() != L' ' && to.back() != L' ' && to.find(L" ") == to.npos;
|
||||||
|
if (!valid)
|
||||||
|
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)
|
for (const auto &[language, words] : s.autoWords)
|
||||||
{
|
{
|
||||||
std::wstring alphabet = language == L"en" ? L"abcdefghijklmnopqrstuvwxyz" :
|
std::wstring alphabet = language == L"en" ? L"abcdefghijklmnopqrstuvwxyz" :
|
||||||
@@ -107,13 +158,30 @@ void validateSettings(const Settings &s)
|
|||||||
s.maxImageMiB > 64)
|
s.maxImageMiB > 64)
|
||||||
throw std::runtime_error("History limits: 10–10000 items, 1–2048 MiB total, 1–64 MiB per image");
|
throw std::runtime_error("History limits: 10–10000 items, 1–2048 MiB total, 1–64 MiB per image");
|
||||||
std::set<std::wstring> seen;
|
std::set<std::wstring> seen;
|
||||||
|
std::set<std::wstring> ids;
|
||||||
|
for (const auto &id : s.snippetTombstones)
|
||||||
|
if (id.empty() || id.size() > 600 || !ids.insert(id).second)
|
||||||
|
throw std::runtime_error("Invalid snippet deletion record.");
|
||||||
for (const auto &snippet : s.snippets)
|
for (const auto &snippet : s.snippets)
|
||||||
{
|
{
|
||||||
|
auto id = snippetId(snippet);
|
||||||
|
if (id.size() > 600 || !ids.insert(id).second) throw std::runtime_error("Duplicate snippet ID or deleted snippet.");
|
||||||
if (snippet.trigger.size() < 2 || snippet.trigger.size() > 64 ||
|
if (snippet.trigger.size() < 2 || snippet.trigger.size() > 64 ||
|
||||||
snippet.trigger.find_first_of(L"\r\n\t ") != snippet.trigger.npos)
|
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");
|
throw std::runtime_error("Snippet triggers must contain 2–64 characters without whitespace");
|
||||||
if (!seen.insert(lower(snippet.trigger)).second)
|
if (snippet.apps.size() > 64) throw std::runtime_error("Too many snippet applications");
|
||||||
throw std::runtime_error("Duplicate snippet trigger");
|
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);
|
auto t = parseTemplate(snippet.text);
|
||||||
if (t.text.empty() || t.cursors > 1)
|
if (t.text.empty() || t.cursors > 1)
|
||||||
throw std::runtime_error("Each snippet needs text and at most one {cursor} marker");
|
throw std::runtime_error("Each snippet needs text and at most one {cursor} marker");
|
||||||
@@ -150,6 +218,15 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
|
|||||||
s.elevatedAutostart = j.value("autostartAsAdministrator", false);
|
s.elevatedAutostart = j.value("autostartAsAdministrator", false);
|
||||||
s.awake = j.value("preventScreenLock", false);
|
s.awake = j.value("preventScreenLock", false);
|
||||||
s.autoCorrect = j.value("autoCorrectLayout", false);
|
s.autoCorrect = j.value("autoCorrectLayout", false);
|
||||||
|
s.autoReplace = j.value("autoCorrectReplace", false);
|
||||||
|
s.autoTypos = j.value("autoCorrectTypos", false);
|
||||||
|
if (j.contains("autoCorrectReplacements"))
|
||||||
|
for (auto &[from, to] : j.at("autoCorrectReplacements").items())
|
||||||
|
{
|
||||||
|
auto key = lower(wide(from));
|
||||||
|
if (!s.autoReplacements.emplace(key, lower(wide(to.get<std::string>()))).second)
|
||||||
|
throw std::runtime_error("Duplicate automatic replacement");
|
||||||
|
}
|
||||||
s.autoMaxRank = j.value("autoCorrectMaxRank", 0);
|
s.autoMaxRank = j.value("autoCorrectMaxRank", 0);
|
||||||
s.autoMinLength = j.value("autoCorrectMinLength", 3);
|
s.autoMinLength = j.value("autoCorrectMinLength", 3);
|
||||||
s.autoPrefixChars = str(j, "autoCorrectPrefixChars", s.autoPrefixChars);
|
s.autoPrefixChars = str(j, "autoCorrectPrefixChars", s.autoPrefixChars);
|
||||||
@@ -187,6 +264,16 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
|
|||||||
s.cycle.push_back(w);
|
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"))
|
if (j.contains("layoutHotkeys"))
|
||||||
{
|
{
|
||||||
std::fill(s.direct.begin(), s.direct.end(), L"");
|
std::fill(s.direct.begin(), s.direct.end(), L"");
|
||||||
@@ -203,7 +290,19 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
|
|||||||
}
|
}
|
||||||
if (j.contains("snippets"))
|
if (j.contains("snippets"))
|
||||||
for (auto &sn : j.at("snippets"))
|
for (auto &sn : j.at("snippets"))
|
||||||
s.snippets.push_back({str(sn, "trigger"), str(sn, "text")});
|
{
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
if (j.contains("snippetTombstones"))
|
||||||
|
for (const auto &id : j.at("snippetTombstones")) s.snippetTombstones.push_back(wide(id.get<std::string>()));
|
||||||
validateSettings(s);
|
validateSettings(s);
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
@@ -237,9 +336,17 @@ Bytes encodeSettings(const Settings &s)
|
|||||||
{"screenshotHotkey", utf8(s.screenshot)},
|
{"screenshotHotkey", utf8(s.screenshot)},
|
||||||
{"screenshotAutoOpenEditor", s.screenshotAutoOpenEditor}};
|
{"screenshotAutoOpenEditor", s.screenshotAutoOpenEditor}};
|
||||||
j["layouts"] = Json::array();
|
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)
|
for (auto &id : s.cycle)
|
||||||
j["layouts"].push_back(utf8(id));
|
j["layouts"].push_back(utf8(id));
|
||||||
j["autoCorrectLayout"] = s.autoCorrect;
|
j["autoCorrectLayout"] = s.autoCorrect;
|
||||||
|
j["autoCorrectReplace"] = s.autoReplace;
|
||||||
|
j["autoCorrectTypos"] = s.autoTypos;
|
||||||
|
j["autoCorrectReplacements"] = Json::object();
|
||||||
|
for (const auto &[from, to] : s.autoReplacements)
|
||||||
|
j["autoCorrectReplacements"][utf8(from)] = utf8(to);
|
||||||
j["autoCorrectMaxRank"] = s.autoMaxRank;
|
j["autoCorrectMaxRank"] = s.autoMaxRank;
|
||||||
j["autoCorrectMinLength"] = s.autoMinLength;
|
j["autoCorrectMinLength"] = s.autoMinLength;
|
||||||
j["autoCorrectPrefixChars"] = utf8(s.autoPrefixChars);
|
j["autoCorrectPrefixChars"] = utf8(s.autoPrefixChars);
|
||||||
@@ -264,7 +371,17 @@ Bytes encodeSettings(const Settings &s)
|
|||||||
j["layoutHotkeys"].push_back({{"layoutId", utf8(s.directIds[i])}, {"hotkey", utf8(s.direct[i])}});
|
j["layoutHotkeys"].push_back({{"layoutId", utf8(s.directIds[i])}, {"hotkey", utf8(s.direct[i])}});
|
||||||
j["snippets"] = Json::array();
|
j["snippets"] = Json::array();
|
||||||
for (auto &sn : s.snippets)
|
for (auto &sn : s.snippets)
|
||||||
j["snippets"].push_back({{"trigger", utf8(sn.trigger)}, {"text", utf8(sn.text)}});
|
{
|
||||||
|
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();
|
j["excludedApps"] = Json::array();
|
||||||
for (auto &name : s.excluded)
|
for (auto &name : s.excluded)
|
||||||
j["excludedApps"].push_back(utf8(name));
|
j["excludedApps"].push_back(utf8(name));
|
||||||
@@ -286,6 +403,20 @@ Bytes encodeClip(const Clip &clip)
|
|||||||
}
|
}
|
||||||
return b;
|
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)
|
Clip decodeClip(const Bytes &b)
|
||||||
{
|
{
|
||||||
size_t p = 0;
|
size_t p = 0;
|
||||||
@@ -317,9 +448,17 @@ Clip decodeClip(const Bytes &b)
|
|||||||
History::History(const std::filesystem::path &folder) : folder_(folder)
|
History::History(const std::filesystem::path &folder) : folder_(folder)
|
||||||
{
|
{
|
||||||
std::filesystem::create_directories(folder_);
|
std::filesystem::create_directories(folder_);
|
||||||
|
loadIndex();
|
||||||
|
}
|
||||||
|
void History::loadIndex()
|
||||||
|
{
|
||||||
|
std::vector<Entry> loaded;
|
||||||
auto index = folder_ / L"index.dat";
|
auto index = folder_ / L"index.dat";
|
||||||
if (!std::filesystem::exists(index))
|
if (!std::filesystem::exists(index))
|
||||||
|
{
|
||||||
|
entries_.clear();
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
auto j = parse(unprotect(readFile(index, 16 * 1024 * 1024)));
|
auto j = parse(unprotect(readFile(index, 16 * 1024 * 1024)));
|
||||||
if (!j.is_array() || j.size() > 10000)
|
if (!j.is_array() || j.size() > 10000)
|
||||||
throw std::runtime_error("Invalid history index");
|
throw std::runtime_error("Invalid history index");
|
||||||
@@ -334,8 +473,170 @@ History::History(const std::filesystem::path &folder) : folder_(folder)
|
|||||||
e.value("image", false),
|
e.value("image", false),
|
||||||
e.value("files", false), e.value("ocrState", e.value("image", false) ? 1 : 0),
|
e.value("files", false), e.value("ocrState", e.value("image", false) ? 1 : 0),
|
||||||
str(e, "ocrProfile", L"windows")};
|
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")))
|
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()
|
void History::saveIndex()
|
||||||
@@ -344,12 +645,14 @@ void History::saveIndex()
|
|||||||
for (const auto &e : entries_)
|
for (const auto &e : entries_)
|
||||||
j.push_back({{"id", utf8(e.id)},
|
j.push_back({{"id", utf8(e.id)},
|
||||||
{"preview", utf8(e.preview)},
|
{"preview", utf8(e.preview)},
|
||||||
{"app", utf8(e.app)},
|
{"app", utf8(e.app)}, {"computer", e.computer}, {"computerName", utf8(e.computerName)},
|
||||||
{"bytes", e.bytes},
|
{"bytes", e.bytes},
|
||||||
{"at", e.at},
|
{"at", e.at},
|
||||||
{"pinned", e.pinned},
|
{"pinned", e.pinned},
|
||||||
{"image", e.image},
|
{"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)));
|
atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j)));
|
||||||
}
|
}
|
||||||
std::vector<Entry> History::entries() const
|
std::vector<Entry> History::entries() const
|
||||||
@@ -382,12 +685,10 @@ void History::prune(const Settings &s)
|
|||||||
entries_.erase(entries_.begin() + i);
|
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
|
// OLE DataObject / Ole Private Data change when Snipping Tool republishes
|
||||||
// the same capture. They are transport metadata, not image identity.
|
// the same capture. They are transport metadata, not image identity.
|
||||||
auto image = [](const Clip &c) -> const Format *
|
|
||||||
{
|
|
||||||
if (!c.text().empty())
|
if (!c.text().empty())
|
||||||
return nullptr;
|
return nullptr;
|
||||||
for (const auto &f : c.formats)
|
for (const auto &f : c.formats)
|
||||||
@@ -401,8 +702,42 @@ bool sameClipboardImage(const Clip &a, const Clip &b)
|
|||||||
if (f.id == id && !f.data.empty())
|
if (f.id == id && !f.data.empty())
|
||||||
return &f;
|
return &f;
|
||||||
return nullptr;
|
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)
|
if (!left || !right)
|
||||||
return false;
|
return false;
|
||||||
if (left->id == right->id && left->name == right->name && left->data == right->data)
|
if (left->id == right->id && left->name == right->name && left->data == right->data)
|
||||||
@@ -419,22 +754,47 @@ bool sameClipboardImage(const Clip &a, const Clip &b)
|
|||||||
return false; // Undecodable data is not evidence of a duplicate.
|
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())
|
if (clip.formats.empty() || !clip.size())
|
||||||
return;
|
return;
|
||||||
auto data = encodeClip(clip);
|
auto data = encodeClip(clip);
|
||||||
if (data.size() > uint64_t(s.maxImageMiB) * 1024 * 1024)
|
if (data.size() > uint64_t(s.maxImageMiB) * 1024 * 1024)
|
||||||
return;
|
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_);
|
std::lock_guard lock(mutex_);
|
||||||
// Compare only the newest record; never keep image payloads in the resident index.
|
Entry fingerprints;
|
||||||
if (!entries_.empty())
|
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
|
try
|
||||||
{
|
{
|
||||||
auto previous = load(entries_.front().id);
|
auto &previous = entries_.front();
|
||||||
if (encodeClip(previous) == data || sameClipboardImage(previous, clip))
|
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;
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (...)
|
catch (...)
|
||||||
{
|
{
|
||||||
@@ -449,12 +809,6 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s)
|
|||||||
auto encrypted = protect(data);
|
auto encrypted = protect(data);
|
||||||
atomicWrite(folder_ / (id + L".dat"), encrypted);
|
atomicWrite(folder_ / (id + L".dat"), encrypted);
|
||||||
auto text = clip.text();
|
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())
|
if (text.empty())
|
||||||
text = files ? L"[Files]" : image ? L"[Image]" : L"[Clipboard data]";
|
text = files ? L"[Files]" : image ? L"[Image]" : L"[Clipboard data]";
|
||||||
for (auto &c : text)
|
for (auto &c : text)
|
||||||
@@ -467,7 +821,8 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s)
|
|||||||
entries_.insert(entries_.begin(),
|
entries_.insert(entries_.begin(),
|
||||||
Entry{id, text, app, encrypted.size(),
|
Entry{id, text, app, encrypted.size(),
|
||||||
(uint64_t(now.dwHighDateTime) << 32) | now.dwLowDateTime, false, image, files,
|
(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);
|
prune(s);
|
||||||
saveIndex();
|
saveIndex();
|
||||||
}
|
}
|
||||||
@@ -506,6 +861,103 @@ void History::clear()
|
|||||||
std::filesystem::remove(folder_ / (e.id + L".ocr"), ec);
|
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)
|
bool History::saveOcr(const std::wstring &id, const std::optional<std::wstring> &text, const Settings &settings)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(mutex_);
|
std::lock_guard lock(mutex_);
|
||||||
@@ -546,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");
|
if (bytes.empty() || bytes.front() != 1) throw std::runtime_error("Invalid OCR text format");
|
||||||
return wide(std::string(bytes.begin() + 1, bytes.end()));
|
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();
|
auto items = entries();
|
||||||
|
if (pinnedOnly) std::erase_if(items, [](const Entry &entry) { return !entry.pinned; });
|
||||||
if (query.empty())
|
if (query.empty())
|
||||||
return items;
|
return items;
|
||||||
auto q = lower(query);
|
auto q = lower(query);
|
||||||
|
|||||||
+32
-2
@@ -1,8 +1,10 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "platform.h"
|
#include "platform.h"
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
|
#include <functional>
|
||||||
namespace ks
|
namespace ks
|
||||||
{
|
{
|
||||||
|
struct Pixels;
|
||||||
Settings loadSettings(const std::filesystem::path &, const std::vector<Layout> &);
|
Settings loadSettings(const std::filesystem::path &, const std::vector<Layout> &);
|
||||||
Settings decodeSettings(const Bytes &, const std::vector<Layout> &);
|
Settings decodeSettings(const Bytes &, const std::vector<Layout> &);
|
||||||
Bytes encodeSettings(const Settings &);
|
Bytes encodeSettings(const Settings &);
|
||||||
@@ -15,6 +17,9 @@ struct Entry
|
|||||||
bool pinned{}, image{}, files{};
|
bool pinned{}, image{}, files{};
|
||||||
int ocrState{}; // 0: legacy/not applicable, 1: pending, 2: saved, 3: failed
|
int ocrState{}; // 0: legacy/not applicable, 1: pending, 2: saved, 3: failed
|
||||||
std::wstring ocrProfile = L"windows";
|
std::wstring ocrProfile = L"windows";
|
||||||
|
std::string contentHash, imageHash, pixelHash;
|
||||||
|
std::string computer;
|
||||||
|
std::wstring computerName;
|
||||||
};
|
};
|
||||||
class History
|
class History
|
||||||
{
|
{
|
||||||
@@ -22,21 +27,46 @@ class History
|
|||||||
std::vector<Entry> entries_;
|
std::vector<Entry> entries_;
|
||||||
mutable std::mutex mutex_;
|
mutable std::mutex mutex_;
|
||||||
void saveIndex();
|
void saveIndex();
|
||||||
|
void loadIndex();
|
||||||
void prune(const Settings &);
|
void prune(const Settings &);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit History(const std::filesystem::path &);
|
explicit History(const std::filesystem::path &);
|
||||||
|
void reload();
|
||||||
std::vector<Entry> entries() const;
|
std::vector<Entry> entries() const;
|
||||||
Clip load(const std::wstring &id) 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 &);
|
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;
|
std::optional<std::wstring> ocrText(const std::wstring &id, const std::wstring &profile = L"") const;
|
||||||
void remove(const std::wstring &);
|
void remove(const std::wstring &);
|
||||||
void pin(const std::wstring &);
|
void pin(const std::wstring &);
|
||||||
void clear();
|
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 encodeClip(const Clip &);
|
||||||
|
Bytes selectionClipboardIdentity(const Clip &);
|
||||||
Clip decodeClip(const Bytes &);
|
Clip decodeClip(const Bytes &);
|
||||||
bool sameClipboardImage(const Clip &, const Clip &);
|
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
|
} // namespace ks
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "screenshot.h"
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace ks::stroke_detail {
|
||||||
|
struct Point { double x, y; };
|
||||||
|
inline double distance(Point a, Point b) { return std::hypot(a.x-b.x,a.y-b.y); }
|
||||||
|
inline double length(const std::vector<Point> &p) {
|
||||||
|
double total=0;
|
||||||
|
for(size_t i=1;i<p.size();++i) total+=distance(p[i-1],p[i]);
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
// Arc-length sampling makes fitting independent of mouse speed and bounds its cost.
|
||||||
|
inline std::vector<Point> sample(const std::vector<Point> &p, size_t count) {
|
||||||
|
std::vector<Point> out{p.front()};
|
||||||
|
double step=length(p)/(count-1), traversed=0;
|
||||||
|
size_t segment=1;
|
||||||
|
for(size_t i=1;i+1<count;++i) {
|
||||||
|
double target=i*step;
|
||||||
|
while(segment+1<p.size() && traversed+distance(p[segment-1],p[segment])<target) {
|
||||||
|
traversed+=distance(p[segment-1],p[segment]); ++segment;
|
||||||
|
}
|
||||||
|
double span=distance(p[segment-1],p[segment]);
|
||||||
|
double t=span>0?(target-traversed)/span:0;
|
||||||
|
out.push_back({p[segment-1].x+t*(p[segment].x-p[segment-1].x),
|
||||||
|
p[segment-1].y+t*(p[segment].y-p[segment-1].y)});
|
||||||
|
}
|
||||||
|
out.push_back(p.back()); return out;
|
||||||
|
}
|
||||||
|
inline double segmentDistance(Point p, Point a, Point b) {
|
||||||
|
double dx=b.x-a.x,dy=b.y-a.y,den=dx*dx+dy*dy;
|
||||||
|
double t=den?std::clamp(((p.x-a.x)*dx+(p.y-a.y)*dy)/den,0.0,1.0):0;
|
||||||
|
return distance(p,{a.x+t*dx,a.y+t*dy});
|
||||||
|
}
|
||||||
|
inline double cross(Point a, Point b, Point c) { return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x); }
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
bool *straightLine=nullptr) {
|
||||||
|
if(shape) *shape=ScreenshotShape::None;
|
||||||
|
if(straightLine) *straightLine=false;
|
||||||
|
using namespace stroke_detail;
|
||||||
|
if(input.size()<3) return {};
|
||||||
|
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()>=3) {
|
||||||
|
double span=distance(raw.front(),raw.back());
|
||||||
|
if(span>=24 && total<=span*1.35) {
|
||||||
|
double tolerance=std::clamp(span*.03,2.0,6.0),maximum=0,backtracking=0,previous=0;
|
||||||
|
Point a=raw.front(),b=raw.back();
|
||||||
|
// Check every original point so a short excursion cannot disappear in resampling.
|
||||||
|
for(auto p:raw) {
|
||||||
|
maximum=std::max(maximum,segmentDistance(p,a,b));
|
||||||
|
double along=((p.x-a.x)*(b.x-a.x)+(p.y-a.y)*(b.y-a.y))/span;
|
||||||
|
backtracking+=std::max(0.0,previous-along); previous=along;
|
||||||
|
}
|
||||||
|
double squared=0;
|
||||||
|
for(auto p:sample(raw,64)) { double d=segmentDistance(p,a,b); squared+=d*d; }
|
||||||
|
if(maximum<=tolerance && std::sqrt(squared/64)<=tolerance*.7 &&
|
||||||
|
backtracking<=std::max(2.0,span*.02)) {
|
||||||
|
if(straightLine) *straightLine=true;
|
||||||
|
return {input.front(),input.back()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(raw.size()<5 || total<16) return {};
|
||||||
|
auto points=sample(raw,128);
|
||||||
|
double left=points[0].x,right=left,top=points[0].y,bottom=top;
|
||||||
|
for(auto p:points) { left=std::min(left,p.x); right=std::max(right,p.x); top=std::min(top,p.y); bottom=std::max(bottom,p.y); }
|
||||||
|
double scale=std::min(right-left,bottom-top);
|
||||||
|
std::vector<Point> best;
|
||||||
|
double bestScore=1e30;
|
||||||
|
double gap=distance(raw.front(),raw.back());
|
||||||
|
if(scale>=20 && gap<=scale*.5) {
|
||||||
|
auto consider=[&](std::vector<Point> candidate, ScreenshotShape kind=ScreenshotShape::Rectangle) {
|
||||||
|
bool oval=kind==ScreenshotShape::Circle || kind==ScreenshotShape::Ellipse;
|
||||||
|
if(!oval && gap>scale*.22) return;
|
||||||
|
double perimeter=length(candidate);
|
||||||
|
if(total<perimeter*.82 || total>perimeter*1.25) return;
|
||||||
|
auto probes=sample(candidate,128);
|
||||||
|
double sum=0,maximum=0;
|
||||||
|
auto measure=[&](const std::vector<Point> &a,const std::vector<Point> &b) {
|
||||||
|
for(auto p:a) {
|
||||||
|
double d=1e30;
|
||||||
|
for(size_t i=1;i<b.size();++i) d=std::min(d,segmentDistance(p,b[i-1],b[i]));
|
||||||
|
sum+=d*d; maximum=std::max(maximum,d);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
measure(points,candidate); measure(probes,points);
|
||||||
|
double score=std::sqrt(sum/256);
|
||||||
|
if(maximum<=std::max(3.0,scale*(oval?.22:.12)) && score<=std::max(1.5,scale*(oval?.085:.055)) && score<bestScore) {
|
||||||
|
bestScore=score; best=std::move(candidate);
|
||||||
|
if(shape) *shape=kind;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Fit oriented bounding boxes; testing angles also handles tilted ovals.
|
||||||
|
for(int degrees=0;degrees<180;degrees+=5) {
|
||||||
|
double angle=degrees*3.141592653589793/180,cs=std::cos(angle),sn=std::sin(angle);
|
||||||
|
double x0=1e30,y0=x0,x1=-x0,y1=-x0;
|
||||||
|
for(auto p:points) {
|
||||||
|
double x=p.x*cs+p.y*sn,y=-p.x*sn+p.y*cs;
|
||||||
|
x0=std::min(x0,x); x1=std::max(x1,x); y0=std::min(y0,y); y1=std::max(y1,y);
|
||||||
|
}
|
||||||
|
auto world=[&](double x,double y)->Point { return {x*cs-y*sn,x*sn+y*cs}; };
|
||||||
|
consider({world(x0,y0),world(x1,y0),world(x1,y1),world(x0,y1),world(x0,y0)});
|
||||||
|
double rx=(x1-x0)/2,ry=(y1-y0)/2;
|
||||||
|
double cx=(x0+x1)/2,cy=(y0+y1)/2;
|
||||||
|
std::vector<Point> local;
|
||||||
|
for(auto p:points) local.push_back({p.x*cs+p.y*sn,-p.x*sn+p.y*cs});
|
||||||
|
// Fit four sides to their supporting samples. Extremal bounds exaggerate
|
||||||
|
// crooked corners and can unfairly make an oval score better than a box.
|
||||||
|
double sides[]{x0,x1,y0,y1};
|
||||||
|
bool supported=true;
|
||||||
|
for(int iteration=0;iteration<6;++iteration) {
|
||||||
|
double sums[4]{}; int counts[4]{};
|
||||||
|
for(auto p:local) {
|
||||||
|
double distances[]{std::abs(p.x-sides[0]),std::abs(p.x-sides[1]),
|
||||||
|
std::abs(p.y-sides[2]),std::abs(p.y-sides[3])};
|
||||||
|
auto side=std::min_element(distances,distances+4)-distances;
|
||||||
|
sums[side]+=side<2?p.x:p.y; ++counts[side];
|
||||||
|
}
|
||||||
|
for(int side=0;side<4;++side) {
|
||||||
|
if(counts[side]<10) { supported=false; break; }
|
||||||
|
sides[side]=sums[side]/counts[side];
|
||||||
|
}
|
||||||
|
if(!supported) break;
|
||||||
|
}
|
||||||
|
if(supported && sides[1]-sides[0]>=16 && sides[3]-sides[2]>=16)
|
||||||
|
consider({world(sides[0],sides[2]),world(sides[1],sides[2]),
|
||||||
|
world(sides[1],sides[3]),world(sides[0],sides[3]),world(sides[0],sides[2])});
|
||||||
|
// Fit the whole gesture instead of letting a single mouse wobble set the bounds.
|
||||||
|
auto error=[&](double x,double y,double a,double b) {
|
||||||
|
if(a<8 || b<8) return 1e30;
|
||||||
|
double sum=0;
|
||||||
|
for(auto p:local) {
|
||||||
|
double u=(p.x-x)/a,v=(p.y-y)/b,r=std::hypot(u,v);
|
||||||
|
double normal=std::hypot(u/a,v/b);
|
||||||
|
double d=normal>1e-9?(r-1)*r/normal:std::min(a,b);
|
||||||
|
sum+=d*d;
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
};
|
||||||
|
double fit=error(cx,cy,rx,ry),step=std::max(rx,ry)*.08;
|
||||||
|
for(int iteration=0;iteration<10;++iteration) {
|
||||||
|
for(int parameter=0;parameter<4;++parameter) for(int sign:{-1,1}) {
|
||||||
|
double values[]{cx,cy,rx,ry}; values[parameter]+=sign*step;
|
||||||
|
double next=error(values[0],values[1],values[2],values[3]);
|
||||||
|
if(next<fit) { fit=next; cx=values[0]; cy=values[1]; rx=values[2]; ry=values[3]; }
|
||||||
|
}
|
||||||
|
step*=.65;
|
||||||
|
}
|
||||||
|
// Require almost one complete turn, with little retracing. This admits a small
|
||||||
|
// closing gap or overshoot but rejects C-shaped arcs, spirals and scribbles.
|
||||||
|
double turn=0,travel=0;
|
||||||
|
for(size_t i=1;i<local.size();++i) {
|
||||||
|
double a=std::atan2((local[i-1].y-cy)/ry,(local[i-1].x-cx)/rx);
|
||||||
|
double b=std::atan2((local[i].y-cy)/ry,(local[i].x-cx)/rx);
|
||||||
|
double delta=std::remainder(b-a,2*3.141592653589793);
|
||||||
|
turn+=delta; travel+=std::abs(delta);
|
||||||
|
}
|
||||||
|
if(std::abs(turn)<5.4 || std::abs(turn)>7.1 || travel-std::abs(turn)>.65) continue;
|
||||||
|
// Near-circular gestures become true circles.
|
||||||
|
bool circle=std::abs(rx-ry)<=std::max(rx,ry)*.12;
|
||||||
|
if(circle) rx=ry=(rx+ry)/2;
|
||||||
|
std::vector<Point> oval;
|
||||||
|
for(int i=0;i<96;++i) {
|
||||||
|
double t=i*2*3.141592653589793/96;
|
||||||
|
oval.push_back(world(cx+rx*std::cos(t),cy+ry*std::sin(t)));
|
||||||
|
}
|
||||||
|
oval.push_back(oval.front()); consider(std::move(oval),circle?ScreenshotShape::Circle:ScreenshotShape::Ellipse);
|
||||||
|
}
|
||||||
|
auto sorted=points;
|
||||||
|
std::sort(sorted.begin(),sorted.end(),[](Point a,Point b){return a.x<b.x || (a.x==b.x && a.y<b.y);});
|
||||||
|
std::vector<Point> hull;
|
||||||
|
for(auto p:sorted) {
|
||||||
|
while(hull.size()>1 && cross(hull[hull.size()-2],hull.back(),p)<=0) hull.pop_back();
|
||||||
|
hull.push_back(p);
|
||||||
|
}
|
||||||
|
size_t lower=hull.size();
|
||||||
|
for(size_t i=sorted.size()-1;i-->0;) {
|
||||||
|
auto p=sorted[i];
|
||||||
|
while(hull.size()>lower && cross(hull[hull.size()-2],hull.back(),p)<=0) hull.pop_back();
|
||||||
|
hull.push_back(p);
|
||||||
|
}
|
||||||
|
hull.pop_back();
|
||||||
|
while(hull.size()>3) {
|
||||||
|
if(hull.size()==4 && bestScore>scale*.035) {
|
||||||
|
// Opposite edges must already be nearly parallel; retain their unequal
|
||||||
|
// lengths and fit a shared direction instead of accepting any quadrilateral.
|
||||||
|
for(size_t i=0;i<2;++i) {
|
||||||
|
Point a=hull[i],b=hull[i+1],c=hull[(i+2)%4],d=hull[(i+3)%4];
|
||||||
|
double ab=distance(a,b),cd=distance(c,d);
|
||||||
|
if(std::min(ab,cd)<16 || std::min(ab,cd)/std::max(ab,cd)>.8) continue;
|
||||||
|
Point u{(b.x-a.x)/ab,(b.y-a.y)/ab},v{(c.x-d.x)/cd,(c.y-d.y)/cd};
|
||||||
|
if(u.x*v.x+u.y*v.y<.96) continue;
|
||||||
|
double norm=std::hypot(u.x+v.x,u.y+v.y);
|
||||||
|
Point axis{(u.x+v.x)/norm,(u.y+v.y)/norm};
|
||||||
|
auto along=[&](Point p){return p.x*axis.x+p.y*axis.y;};
|
||||||
|
auto across=[&](Point p){return -p.x*axis.y+p.y*axis.x;};
|
||||||
|
double y0=(across(a)+across(b))/2,y1=(across(c)+across(d))/2;
|
||||||
|
if(std::abs(y1-y0)<20) continue;
|
||||||
|
auto fit=[&](Point p,double y)->Point {double x=along(p);return {x*axis.x-y*axis.y,x*axis.y+y*axis.x};};
|
||||||
|
std::vector<Point> candidate{fit(a,y0),fit(b,y0),fit(c,y1),fit(d,y1),fit(a,y0)};
|
||||||
|
consider(std::move(candidate),ScreenshotShape::Trapezoid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
size_t remove=0; double area=1e30;
|
||||||
|
for(size_t i=0;i<hull.size();++i) {
|
||||||
|
double a=std::abs(cross(hull[(i+hull.size()-1)%hull.size()],hull[i],hull[(i+1)%hull.size()]));
|
||||||
|
if(a<area) { area=a; remove=i; }
|
||||||
|
}
|
||||||
|
hull.erase(hull.begin()+remove);
|
||||||
|
}
|
||||||
|
if(hull.size()==3) { hull.push_back(hull.front()); consider(hull,ScreenshotShape::Triangle); }
|
||||||
|
}
|
||||||
|
if(best.empty()) {
|
||||||
|
// A small spatial filter suppresses jitter without moving endpoints or flattening broad curves.
|
||||||
|
best=sample(raw,size_t(std::clamp(std::ceil(total/2)+1,5.0,2048.0)));
|
||||||
|
auto original=best;
|
||||||
|
for(size_t i=1;i+1<best.size();++i)
|
||||||
|
best[i]={(original[i-1].x+2*original[i].x+original[i+1].x)/4,
|
||||||
|
(original[i-1].y+2*original[i].y+original[i+1].y)/4};
|
||||||
|
}
|
||||||
|
std::vector<POINT> result;
|
||||||
|
for(auto p:best) {
|
||||||
|
POINT q{LONG(std::lround(p.x)),LONG(std::lround(p.y))};
|
||||||
|
if(result.empty() || result.back().x!=q.x || result.back().y!=q.y) result.push_back(q);
|
||||||
|
}
|
||||||
|
if(result.size()==input.size() && std::equal(result.begin(),result.end(),input.begin(),
|
||||||
|
[](POINT a,POINT b){return a.x==b.x && a.y==b.y;})) return {};
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
+359
@@ -0,0 +1,359 @@
|
|||||||
|
#include "sync.h"
|
||||||
|
#include "json.hpp"
|
||||||
|
#include <winhttp.h>
|
||||||
|
#include <wincred.h>
|
||||||
|
#include <set>
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
namespace ks
|
||||||
|
{
|
||||||
|
using Json = nlohmann::json;
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
constexpr size_t Limit = 4 * 1024 * 1024;
|
||||||
|
Bytes bytes(const Json &j) { auto s = j.dump(); return {s.begin(), s.end()}; }
|
||||||
|
Json parse(const Bytes &b) { return Json::parse(b.begin(), b.end()); }
|
||||||
|
Json configJson(const SyncConfig &c)
|
||||||
|
{
|
||||||
|
return {{"enabled", c.enabled}, {"provider", utf8(c.provider)}, {"server", utf8(c.server)},
|
||||||
|
{"mount", utf8(c.mount)}, {"path", utf8(c.path)}, {"authMount", utf8(c.authMount)},
|
||||||
|
{"username", utf8(c.username)}, {"keepLocalLayouts", c.keepLocalLayouts}};
|
||||||
|
}
|
||||||
|
std::wstring credentialName(const SyncConfig &c)
|
||||||
|
{
|
||||||
|
return L"KSwitcher.Sync/" + c.server + L"/" + c.authMount + L"/" + c.username;
|
||||||
|
}
|
||||||
|
bool safePath(const std::wstring &s)
|
||||||
|
{
|
||||||
|
if (s.empty() || s.size() > 512 || s.front() == '/' || s.back() == '/' ||
|
||||||
|
s.find(L"//") != s.npos) return false;
|
||||||
|
return s.find_first_not_of(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-/") == s.npos;
|
||||||
|
}
|
||||||
|
struct HttpHandle
|
||||||
|
{
|
||||||
|
HINTERNET h{};
|
||||||
|
~HttpHandle() { if (h) WinHttpCloseHandle(h); }
|
||||||
|
};
|
||||||
|
class OpenBao final : public SyncProvider
|
||||||
|
{
|
||||||
|
SyncConfig config;
|
||||||
|
SyncTransport transport;
|
||||||
|
std::wstring token;
|
||||||
|
Json response(unsigned status, const Bytes &result, bool missing)
|
||||||
|
{
|
||||||
|
if (result.size() > Limit) throw std::runtime_error("OpenBao response is too large.");
|
||||||
|
if (status == 404 && missing)
|
||||||
|
{
|
||||||
|
auto j = result.empty() ? Json::object() : parse(result);
|
||||||
|
if (j.contains("data") && !j["data"].is_null())
|
||||||
|
throw std::runtime_error("Remote profile is deleted. Restore it in OpenBao first.");
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
if (status == 401 || status == 403) throw std::runtime_error("OpenBao denied access. Check login and profile policy.");
|
||||||
|
if (status == 400) throw std::runtime_error("OpenBao rejected the write or its version changed. Sync again; check KV v2 configuration.");
|
||||||
|
if (status < 200 || status >= 300) throw std::runtime_error("OpenBao HTTP error " + std::to_string(status) + ".");
|
||||||
|
return result.empty() ? Json::object() : parse(result);
|
||||||
|
}
|
||||||
|
Json request(const wchar_t *method, const std::wstring &path, const Json *body = nullptr, bool missing = false)
|
||||||
|
{
|
||||||
|
if (transport)
|
||||||
|
{
|
||||||
|
auto reply = transport(method, path, token, body ? bytes(*body) : Bytes{});
|
||||||
|
return response(reply.status, reply.body, missing);
|
||||||
|
}
|
||||||
|
URL_COMPONENTS url{sizeof(url)};
|
||||||
|
url.dwHostNameLength = url.dwUrlPathLength = url.dwExtraInfoLength = (DWORD)-1;
|
||||||
|
if (!WinHttpCrackUrl(config.server.c_str(), 0, 0, &url)) throw std::runtime_error("Invalid server URL.");
|
||||||
|
std::wstring host(url.lpszHostName, url.dwHostNameLength);
|
||||||
|
HttpHandle session{WinHttpOpen(L"KSwitcher Sync/1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
|
||||||
|
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)};
|
||||||
|
if (!session.h || !WinHttpSetTimeouts(session.h, 5000, 5000, 5000, 5000))
|
||||||
|
throw std::runtime_error("Cannot initialize sync connection.");
|
||||||
|
HttpHandle connection{WinHttpConnect(session.h, host.c_str(), url.nPort, 0)};
|
||||||
|
HttpHandle req{connection.h ? WinHttpOpenRequest(connection.h, method, path.c_str(), nullptr,
|
||||||
|
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr};
|
||||||
|
DWORD redirects = WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
|
||||||
|
if (!req.h || !WinHttpSetOption(req.h, WINHTTP_OPTION_REDIRECT_POLICY, &redirects, sizeof(redirects)))
|
||||||
|
throw std::runtime_error("Cannot initialize sync request.");
|
||||||
|
std::wstring headers = L"Content-Type: application/json\r\n";
|
||||||
|
if (!token.empty()) headers += L"X-Vault-Token: " + token + L"\r\n";
|
||||||
|
std::string payload = body ? body->dump() : "";
|
||||||
|
bool sent = WinHttpSendRequest(req.h, headers.c_str(), (DWORD)-1,
|
||||||
|
payload.empty() ? WINHTTP_NO_REQUEST_DATA : payload.data(), (DWORD)payload.size(), (DWORD)payload.size(), 0);
|
||||||
|
if (!payload.empty()) SecureZeroMemory(payload.data(), payload.size());
|
||||||
|
if (!sent || !WinHttpReceiveResponse(req.h, nullptr))
|
||||||
|
throw std::runtime_error("OpenBao connection failed. Check network, HTTPS certificate and server address.");
|
||||||
|
DWORD status{}, length = sizeof(status);
|
||||||
|
if (!WinHttpQueryHeaders(req.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
|
||||||
|
WINHTTP_HEADER_NAME_BY_INDEX, &status, &length, WINHTTP_NO_HEADER_INDEX))
|
||||||
|
throw std::runtime_error("Cannot read OpenBao response.");
|
||||||
|
Bytes result;
|
||||||
|
ULONGLONG deadline = GetTickCount64() + 15000;
|
||||||
|
for (;;)
|
||||||
|
{
|
||||||
|
unsigned char chunk[8192]; DWORD received{};
|
||||||
|
if (GetTickCount64() > deadline || !WinHttpReadData(req.h, chunk, sizeof(chunk), &received))
|
||||||
|
throw std::runtime_error("OpenBao response timed out.");
|
||||||
|
if (!received) break;
|
||||||
|
if (result.size() + received > Limit) throw std::runtime_error("OpenBao response is too large.");
|
||||||
|
result.insert(result.end(), chunk, chunk + received);
|
||||||
|
}
|
||||||
|
return response(status, result, missing);
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
explicit OpenBao(const SyncConfig &c, SyncTransport t) : config(c), transport(std::move(t))
|
||||||
|
{
|
||||||
|
validateSyncConfig(c);
|
||||||
|
PCREDENTIALW credential{};
|
||||||
|
if (!CredReadW(credentialName(c).c_str(), CRED_TYPE_GENERIC, 0, &credential))
|
||||||
|
throw std::runtime_error("Sign in: no saved password for this server and user.");
|
||||||
|
std::string password(reinterpret_cast<char *>(credential->CredentialBlob), credential->CredentialBlobSize);
|
||||||
|
SecureZeroMemory(credential->CredentialBlob, credential->CredentialBlobSize);
|
||||||
|
CredFree(credential);
|
||||||
|
Json login{{"password", password}};
|
||||||
|
SecureZeroMemory(password.data(), password.size());
|
||||||
|
Json response;
|
||||||
|
try { response = request(L"POST", L"/v1/auth/" + c.authMount + L"/login/" + c.username, &login); }
|
||||||
|
catch (...) { auto &p = login["password"].get_ref<std::string &>(); SecureZeroMemory(p.data(), p.size()); throw; }
|
||||||
|
auto &p = login["password"].get_ref<std::string &>(); SecureZeroMemory(p.data(), p.size());
|
||||||
|
token = wide(response.at("auth").at("client_token").get<std::string>());
|
||||||
|
if (token.empty() || token.find_first_of(L"\r\n") != token.npos)
|
||||||
|
throw std::runtime_error("Invalid OpenBao authentication response.");
|
||||||
|
}
|
||||||
|
~OpenBao() override
|
||||||
|
{
|
||||||
|
if (token.empty()) return;
|
||||||
|
// Sessions are scoped to a sync attempt; do not accumulate login tokens.
|
||||||
|
try { request(L"POST", L"/v1/auth/token/revoke-self"); } catch (...) {}
|
||||||
|
SecureZeroMemory(token.data(), token.size() * sizeof(wchar_t));
|
||||||
|
}
|
||||||
|
SyncDocument read() override
|
||||||
|
{
|
||||||
|
auto j = request(L"GET", L"/v1/" + config.mount + L"/data/" + config.path, nullptr, true);
|
||||||
|
if (j.is_null()) return {};
|
||||||
|
const auto &data = j.at("data");
|
||||||
|
if (!data.at("metadata").value("deletion_time", std::string()).empty() ||
|
||||||
|
data.at("metadata").value("destroyed", false))
|
||||||
|
throw std::runtime_error("Remote profile is deleted or destroyed.");
|
||||||
|
auto payload = data.at("data");
|
||||||
|
if (payload.value("syncSchema", 0) != 1 && payload.value("syncSchema", 0) != 2) throw std::runtime_error("Unsupported remote sync format.");
|
||||||
|
return {data.at("metadata").at("version").get<uint64_t>(), bytes(payload.at("settings"))};
|
||||||
|
}
|
||||||
|
uint64_t write(const Bytes &settings, uint64_t revision) override
|
||||||
|
{
|
||||||
|
Json body{{"options", {{"cas", revision}}}, {"data", {{"syncSchema", 2}, {"settings", parse(settings)}}}};
|
||||||
|
auto response = request(L"POST", L"/v1/" + config.mount + L"/data/" + config.path, &body);
|
||||||
|
return response.at("data").at("version").get<uint64_t>();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
bool syncVisible(const std::filesystem::path &root) { return std::filesystem::exists(root / L"sync.json"); }
|
||||||
|
SyncConfig loadSyncConfig(const std::filesystem::path &root)
|
||||||
|
{
|
||||||
|
SyncConfig c;
|
||||||
|
if (!syncVisible(root)) return c;
|
||||||
|
auto j = parse(readFile(root / L"sync.json", 16384));
|
||||||
|
c.enabled = j.value("enabled", false);
|
||||||
|
c.keepLocalLayouts = j.value("keepLocalLayouts", false);
|
||||||
|
c.provider = wide(j.value("provider", "openbao"));
|
||||||
|
c.server = wide(j.value("server", ""));
|
||||||
|
c.mount = wide(j.value("mount", "kswitcher"));
|
||||||
|
c.path = wide(j.value("path", "personal/settings"));
|
||||||
|
c.authMount = wide(j.value("authMount", "userpass"));
|
||||||
|
c.username = wide(j.value("username", ""));
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
void validateSyncConfig(const SyncConfig &c)
|
||||||
|
{
|
||||||
|
if (c.provider != L"openbao") throw std::runtime_error("Unsupported sync provider.");
|
||||||
|
URL_COMPONENTS url{sizeof(url)};
|
||||||
|
url.dwHostNameLength = url.dwUrlPathLength = url.dwExtraInfoLength = url.dwUserNameLength = url.dwPasswordLength = (DWORD)-1;
|
||||||
|
if (c.server.size() > 1024 || !WinHttpCrackUrl(c.server.c_str(), 0, 0, &url) ||
|
||||||
|
url.nScheme != INTERNET_SCHEME_HTTPS || !url.dwHostNameLength || url.dwUserNameLength ||
|
||||||
|
url.dwPasswordLength || url.dwExtraInfoLength ||
|
||||||
|
(url.dwUrlPathLength && std::wstring(url.lpszUrlPath, url.dwUrlPathLength) != L"/"))
|
||||||
|
throw std::runtime_error("Server must be an HTTPS origin, for example https://bao.example.com (no path or credentials).");
|
||||||
|
bool userValid = !c.username.empty() && c.username.size() <= 256 && c.username != L"." && c.username != L".." &&
|
||||||
|
c.username.find_first_not_of(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.@") == c.username.npos;
|
||||||
|
if (!safePath(c.mount) || !safePath(c.path) || !safePath(c.authMount) || !userValid)
|
||||||
|
throw std::runtime_error("Use letters, numbers, underscores and hyphens in paths and login; / is allowed only in paths.");
|
||||||
|
if (credentialName(c).size() > CRED_MAX_GENERIC_TARGET_NAME_LENGTH)
|
||||||
|
throw std::runtime_error("Sync connection name is too long.");
|
||||||
|
}
|
||||||
|
void saveSyncConfig(const std::filesystem::path &root, const SyncConfig &c)
|
||||||
|
{
|
||||||
|
if (c.enabled) validateSyncConfig(c);
|
||||||
|
atomicWrite(root / L"sync.json", bytes(configJson(c)));
|
||||||
|
}
|
||||||
|
void saveSyncPassword(const SyncConfig &c, const std::wstring &password)
|
||||||
|
{
|
||||||
|
validateSyncConfig(c);
|
||||||
|
auto secret = utf8(password);
|
||||||
|
if (secret.empty() || secret.size() > CRED_MAX_CREDENTIAL_BLOB_SIZE) throw std::runtime_error("Password is empty or too long.");
|
||||||
|
auto target = credentialName(c);
|
||||||
|
CREDENTIALW credential{}; credential.Type = CRED_TYPE_GENERIC; credential.TargetName = target.data();
|
||||||
|
credential.UserName = const_cast<wchar_t *>(c.username.c_str());
|
||||||
|
credential.CredentialBlob = reinterpret_cast<BYTE *>(secret.data());
|
||||||
|
credential.CredentialBlobSize = (DWORD)secret.size(); credential.Persist = CRED_PERSIST_LOCAL_MACHINE;
|
||||||
|
bool ok = CredWriteW(&credential, 0) != 0;
|
||||||
|
SecureZeroMemory(secret.data(), secret.size());
|
||||||
|
if (!ok) throw std::runtime_error("Cannot save password in Windows Credential Manager.");
|
||||||
|
}
|
||||||
|
void forgetSyncPassword(const SyncConfig &c)
|
||||||
|
{
|
||||||
|
if (!CredDeleteW(credentialName(c).c_str(), CRED_TYPE_GENERIC, 0) && GetLastError() != ERROR_NOT_FOUND)
|
||||||
|
throw std::runtime_error("Cannot remove saved sync password.");
|
||||||
|
}
|
||||||
|
std::unique_ptr<SyncProvider> makeSyncProvider(const SyncConfig &c, SyncTransport transport)
|
||||||
|
{
|
||||||
|
return std::make_unique<OpenBao>(c, std::move(transport));
|
||||||
|
}
|
||||||
|
namespace { Json canonicalProfile(Json); }
|
||||||
|
Bytes sharedSyncSettings(const Settings &s)
|
||||||
|
{
|
||||||
|
auto j = parse(encodeSettings(s));
|
||||||
|
// Windows may enumerate the same installed layouts in a different order on
|
||||||
|
// another PC. Binding order is not user intent (unlike the layout cycle).
|
||||||
|
auto &bindings = j["layoutHotkeys"];
|
||||||
|
std::sort(bindings.begin(), bindings.end(), [](const Json &a, const Json &b) {
|
||||||
|
return a.at("layoutId").get<std::string>() < b.at("layoutId").get<std::string>();
|
||||||
|
});
|
||||||
|
for (auto key : {"startWithSystem", "autostartAsAdministrator", "tesseractPath", "useTesseract",
|
||||||
|
"historyEnabled", "maxItems", "maxTotalMegabytes", "maxImageMegabytes", "writeLog", "preventScreenLock"}) j.erase(key);
|
||||||
|
return bytes(canonicalProfile(j));
|
||||||
|
}
|
||||||
|
Settings restoreSyncSettings(const Bytes &shared, const Settings &local, const std::vector<Layout> &layouts, bool keepLocalLayouts)
|
||||||
|
{
|
||||||
|
auto j = parse(shared), original = parse(encodeSettings(local));
|
||||||
|
if (!j.contains("snippetTombstones")) j["snippetTombstones"] = Json::array();
|
||||||
|
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.");
|
||||||
|
for (auto it = j.begin(); it != j.end(); ++it)
|
||||||
|
if (!allowed.contains(it.key())) throw std::runtime_error("Remote profile contains unsupported or local-only fields.");
|
||||||
|
if (j.size() != allowed.size()) throw std::runtime_error("Remote profile is incomplete.");
|
||||||
|
std::set<std::string> installed;
|
||||||
|
for (const auto &layout : layouts) installed.insert(utf8(layout.id));
|
||||||
|
std::set<std::string> missing;
|
||||||
|
for (const auto &id : j.at("layouts"))
|
||||||
|
if (!installed.contains(id.get<std::string>())) missing.insert(id.get<std::string>());
|
||||||
|
for (const auto &key : j.at("layoutHotkeys"))
|
||||||
|
if (!installed.contains(key.at("layoutId").get<std::string>())) missing.insert(key.at("layoutId").get<std::string>());
|
||||||
|
if (!keepLocalLayouts && !missing.empty())
|
||||||
|
{
|
||||||
|
std::wstring message = L"Missing keyboard layouts on this PC: ";
|
||||||
|
for (const auto &id : missing)
|
||||||
|
{
|
||||||
|
auto code = id.starts_with("win:") ? id.substr(4) : id;
|
||||||
|
wchar_t language[128]{};
|
||||||
|
if (code.size() == 8 && code.find_first_not_of("0123456789abcdefABCDEF") == code.npos)
|
||||||
|
GetLocaleInfoW(MAKELCID(LOWORD(std::stoul(code, nullptr, 16)), SORT_DEFAULT), LOCALE_SENGLISHLANGUAGENAME,
|
||||||
|
language, 128);
|
||||||
|
if (message.back() != L' ') message += L"; ";
|
||||||
|
message += (language[0] ? std::wstring(language) : L"Unknown layout") + L" [" + wide(id) + L"]";
|
||||||
|
}
|
||||||
|
message += L". Install these exact layouts, or enable 'Keep this PC's layouts' below and sync other settings.";
|
||||||
|
throw std::runtime_error(utf8(message));
|
||||||
|
}
|
||||||
|
if (keepLocalLayouts)
|
||||||
|
for (auto key : {"layouts", "layoutHotkeys"}) j[key] = original.at(key);
|
||||||
|
original.update(j);
|
||||||
|
return decodeSettings(bytes(original), layouts);
|
||||||
|
}
|
||||||
|
#include "sync_merge.inl"
|
||||||
|
SyncResult synchronize(SyncProvider &provider, const Bytes &base, const Bytes &local, SyncAction action,
|
||||||
|
const std::function<void(const Bytes &)> &validate, const std::vector<SyncChoice> &choices, bool keepLocalLayouts)
|
||||||
|
{
|
||||||
|
if (local.size() > Limit) throw std::runtime_error("Settings exceed the sync size limit.");
|
||||||
|
if (validate) validate(local);
|
||||||
|
auto remote = provider.read();
|
||||||
|
if (!remote.revision)
|
||||||
|
{
|
||||||
|
if (action != SyncAction::Upload) throw std::runtime_error("No remote profile. Choose Upload local to create it.");
|
||||||
|
return {true, local, provider.write(local, 0), L"Uploaded new profile."};
|
||||||
|
}
|
||||||
|
if (validate && action != SyncAction::Upload) validate(remote.settings);
|
||||||
|
auto mergeLocal = local, mergeBase = base;
|
||||||
|
if (keepLocalLayouts)
|
||||||
|
{
|
||||||
|
// Never upload a locally filtered projection over another PC's layout setup.
|
||||||
|
const auto remoteJson = parse(remote.settings);
|
||||||
|
auto preserve = [&](const Bytes &profile)
|
||||||
|
{
|
||||||
|
auto j = parse(profile);
|
||||||
|
for (auto key : {"layouts", "layoutHotkeys"}) j[key] = remoteJson.at(key);
|
||||||
|
return bytes(j);
|
||||||
|
};
|
||||||
|
mergeLocal = preserve(local);
|
||||||
|
if (!base.empty()) mergeBase = preserve(base);
|
||||||
|
}
|
||||||
|
SyncMerge merged;
|
||||||
|
if (action == SyncAction::Automatic) merged = mergeSyncProfile(mergeBase, mergeLocal, remote.settings, choices);
|
||||||
|
else
|
||||||
|
{
|
||||||
|
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); }
|
||||||
|
auto revision = remote.revision;
|
||||||
|
if (parse(merged.remote) != parse(remote.settings) && action != SyncAction::Download) revision = provider.write(merged.remote, revision);
|
||||||
|
return {true, merged.local, revision,
|
||||||
|
merged.conflicts.empty() ? L"Synchronized. Server version " + std::to_wstring(revision) + L"." :
|
||||||
|
L"Other changes synchronized. Resolve " + std::to_wstring(merged.conflicts.size()) + L" conflicting setting(s).",
|
||||||
|
merged.base, merged.conflicts};
|
||||||
|
}
|
||||||
|
Bytes encodeSyncConflicts(const std::vector<SyncConflict> &conflicts)
|
||||||
|
{
|
||||||
|
Json j = Json::array();
|
||||||
|
for (const auto &c : conflicts) j.push_back({{"key", c.key}, {"label", utf8(c.label)}, {"local", parse(c.local)}, {"remote", parse(c.remote)}});
|
||||||
|
return bytes(j);
|
||||||
|
}
|
||||||
|
std::vector<SyncConflict> decodeSyncConflicts(const Bytes &data)
|
||||||
|
{
|
||||||
|
std::vector<SyncConflict> result;
|
||||||
|
for (const auto &c : parse(data)) result.push_back({c.at("key"), wide(c.at("label").get<std::string>()), bytes(c.at("local")), bytes(c.at("remote"))});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
Bytes encodeSyncChoices(const std::vector<SyncChoice> &choices)
|
||||||
|
{
|
||||||
|
Json j = Json::array();
|
||||||
|
for (const auto &c : choices) j.push_back({{"conflict", parse(encodeSyncConflicts({c.conflict})).at(0)}, {"useLocal", c.useLocal}});
|
||||||
|
return bytes(j);
|
||||||
|
}
|
||||||
|
std::vector<SyncChoice> decodeSyncChoices(const Bytes &data)
|
||||||
|
{
|
||||||
|
auto j = parse(data);
|
||||||
|
if (!j.is_array() || j.size() > 10000) throw std::runtime_error("Invalid conflict choices.");
|
||||||
|
std::vector<SyncChoice> result;
|
||||||
|
for (const auto &c : j) result.push_back({decodeSyncConflicts(bytes(Json::array({c.at("conflict")}))).at(0), c.at("useLocal").get<bool>()});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
std::wstring syncValueText(const Bytes &data)
|
||||||
|
{
|
||||||
|
auto j = parse(data);
|
||||||
|
if (j.is_null()) return L"(not present)";
|
||||||
|
if (tombstone(j)) return L"(deleted)";
|
||||||
|
return wide(j.is_string() ? j.get<std::string>() : j.dump(2));
|
||||||
|
}
|
||||||
|
Bytes loadSyncBase(const std::filesystem::path &root, const SyncConfig &c)
|
||||||
|
{
|
||||||
|
auto path = root / L"sync-base.bin";
|
||||||
|
if (!std::filesystem::exists(path)) return {};
|
||||||
|
auto j = parse(unprotect(readFile(path, Limit + 65536)));
|
||||||
|
auto connection = j.at("connection");
|
||||||
|
if (!connection.contains("keepLocalLayouts")) connection["keepLocalLayouts"] = false;
|
||||||
|
return connection == configJson(c) ? bytes(j.at("settings")) : Bytes{};
|
||||||
|
}
|
||||||
|
void saveSyncBase(const std::filesystem::path &root, const SyncConfig &c, const Bytes &base)
|
||||||
|
{
|
||||||
|
atomicWrite(root / L"sync-base.bin", protect(bytes({{"connection", configJson(c)}, {"settings", parse(base)}})));
|
||||||
|
}
|
||||||
|
}
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "storage.h"
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
namespace ks
|
||||||
|
{
|
||||||
|
struct SyncConfig
|
||||||
|
{
|
||||||
|
bool enabled{};
|
||||||
|
bool keepLocalLayouts{};
|
||||||
|
std::wstring provider = L"openbao", server, mount = L"kswitcher",
|
||||||
|
path = L"personal/settings", authMount = L"userpass", username;
|
||||||
|
bool operator==(const SyncConfig &) const = default;
|
||||||
|
};
|
||||||
|
bool syncVisible(const std::filesystem::path &);
|
||||||
|
SyncConfig loadSyncConfig(const std::filesystem::path &);
|
||||||
|
void saveSyncConfig(const std::filesystem::path &, const SyncConfig &);
|
||||||
|
void validateSyncConfig(const SyncConfig &);
|
||||||
|
void saveSyncPassword(const SyncConfig &, const std::wstring &);
|
||||||
|
void forgetSyncPassword(const SyncConfig &);
|
||||||
|
struct SyncDocument { uint64_t revision{}; Bytes settings; };
|
||||||
|
class SyncProvider
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
virtual ~SyncProvider() = default;
|
||||||
|
virtual SyncDocument read() = 0;
|
||||||
|
virtual uint64_t write(const Bytes &, uint64_t expectedRevision) = 0;
|
||||||
|
};
|
||||||
|
struct SyncHttpResponse { unsigned status{}; Bytes body; };
|
||||||
|
using SyncTransport = std::function<SyncHttpResponse(const std::wstring &method, const std::wstring &path,
|
||||||
|
const std::wstring &token, const Bytes &body)>;
|
||||||
|
// An injectable transport permits protocol regression tests without a live vault.
|
||||||
|
std::unique_ptr<SyncProvider> makeSyncProvider(const SyncConfig &, SyncTransport transport = {});
|
||||||
|
inline constexpr ULONGLONG SyncIntervalMs = 10 * 60 * 1000;
|
||||||
|
struct SyncConflict
|
||||||
|
{
|
||||||
|
std::string key;
|
||||||
|
std::wstring label;
|
||||||
|
Bytes local, remote;
|
||||||
|
};
|
||||||
|
struct SyncChoice { SyncConflict conflict; bool useLocal{}; };
|
||||||
|
Bytes encodeSyncConflicts(const std::vector<SyncConflict> &);
|
||||||
|
std::vector<SyncConflict> decodeSyncConflicts(const Bytes &);
|
||||||
|
Bytes encodeSyncChoices(const std::vector<SyncChoice> &);
|
||||||
|
std::vector<SyncChoice> decodeSyncChoices(const Bytes &);
|
||||||
|
std::wstring syncValueText(const Bytes &);
|
||||||
|
struct SyncMerge
|
||||||
|
{
|
||||||
|
Bytes local, remote, base;
|
||||||
|
std::vector<SyncConflict> conflicts;
|
||||||
|
};
|
||||||
|
SyncMerge mergeSyncProfile(const Bytes &base, const Bytes &local, const Bytes &remote,
|
||||||
|
const std::vector<SyncChoice> &choices = {});
|
||||||
|
Bytes mergeSyncSettings(const Bytes &base, const Bytes &local, const Bytes &remote);
|
||||||
|
Bytes sharedSyncSettings(const Settings &);
|
||||||
|
Settings restoreSyncSettings(const Bytes &, const Settings &, const std::vector<Layout> &, bool keepLocalLayouts = false);
|
||||||
|
enum class SyncAction { Automatic, Download, Upload };
|
||||||
|
struct SyncResult
|
||||||
|
{
|
||||||
|
bool success{};
|
||||||
|
Bytes settings;
|
||||||
|
uint64_t revision{};
|
||||||
|
std::wstring status;
|
||||||
|
Bytes base;
|
||||||
|
std::vector<SyncConflict> conflicts;
|
||||||
|
};
|
||||||
|
SyncResult synchronize(SyncProvider &, const Bytes &base, const Bytes &local, SyncAction,
|
||||||
|
const std::function<void(const Bytes &)> &validate = {}, const std::vector<SyncChoice> &choices = {},
|
||||||
|
bool keepLocalLayouts = false);
|
||||||
|
Bytes loadSyncBase(const std::filesystem::path &, const SyncConfig &);
|
||||||
|
void saveSyncBase(const std::filesystem::path &, const SyncConfig &, const Bytes &);
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
// Three-way merge operates on individual values; unresolved values retain their
|
||||||
|
// respective local/remote versions and their old common ancestor.
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
Json normalizeProfile(Json j)
|
||||||
|
{
|
||||||
|
if (!j.contains("autoCorrectReplace")) j["autoCorrectReplace"] = false;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
Json treeProfile(const Json &source)
|
||||||
|
{
|
||||||
|
auto j = normalizeProfile(source);
|
||||||
|
Json items = Json::object();
|
||||||
|
for (const auto &sn : j.at("snippets"))
|
||||||
|
{
|
||||||
|
auto id = sn.at("id").get<std::string>();
|
||||||
|
if (items.contains(id)) throw std::runtime_error("Duplicate snippet ID.");
|
||||||
|
items[id] = sn;
|
||||||
|
}
|
||||||
|
for (const auto &id : j.at("snippetTombstones"))
|
||||||
|
{
|
||||||
|
auto key = id.get<std::string>();
|
||||||
|
if (items.contains(key)) throw std::runtime_error("Duplicate or deleted snippet ID.");
|
||||||
|
items[key] = {{"$deleted", true}};
|
||||||
|
}
|
||||||
|
j["snippets"] = items;
|
||||||
|
j.erase("snippetTombstones");
|
||||||
|
items = Json::object();
|
||||||
|
for (const auto &binding : j.at("layoutHotkeys")) items[binding.at("layoutId").get<std::string>()] = binding.at("hotkey");
|
||||||
|
j["layoutHotkeys"] = items;
|
||||||
|
for (auto key : {"excludedApps", "autoCorrectNever", "autoCorrectExcludedApps"})
|
||||||
|
{
|
||||||
|
items = Json::object();
|
||||||
|
for (const auto &item : j.at(key)) items[item.get<std::string>()] = true;
|
||||||
|
j[key] = items;
|
||||||
|
}
|
||||||
|
for (auto &language : j.at("autoCorrectWords").items())
|
||||||
|
{
|
||||||
|
items = Json::object();
|
||||||
|
for (const auto &word : language.value()) items[word.get<std::string>()] = true;
|
||||||
|
language.value() = items;
|
||||||
|
}
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
Json flatProfile(Json j)
|
||||||
|
{
|
||||||
|
auto &replacements = j["autoCorrectReplacements"];
|
||||||
|
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())
|
||||||
|
{
|
||||||
|
if (item.is_null()) continue;
|
||||||
|
if (item.value("$deleted", false)) deleted.push_back(id);
|
||||||
|
else snippets.push_back(item);
|
||||||
|
}
|
||||||
|
j["snippets"] = snippets; j["snippetTombstones"] = deleted;
|
||||||
|
Json bindings = Json::array();
|
||||||
|
for (const auto &[id, hotkey] : j.at("layoutHotkeys").items())
|
||||||
|
if (!hotkey.is_null()) bindings.push_back({{"layoutId", id}, {"hotkey", hotkey}});
|
||||||
|
j["layoutHotkeys"] = bindings;
|
||||||
|
for (auto key : {"excludedApps", "autoCorrectNever", "autoCorrectExcludedApps"})
|
||||||
|
{
|
||||||
|
Json list = Json::array();
|
||||||
|
for (const auto &[item, present] : j.at(key).items()) if (present == true) list.push_back(item);
|
||||||
|
j[key] = list;
|
||||||
|
}
|
||||||
|
for (auto &language : j.at("autoCorrectWords").items())
|
||||||
|
{
|
||||||
|
Json list = Json::array();
|
||||||
|
if (language.value().is_object())
|
||||||
|
for (const auto &[word, present] : language.value().items()) if (present == true) list.push_back(word);
|
||||||
|
language.value() = list;
|
||||||
|
}
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
std::string pointerKey(const std::string &s)
|
||||||
|
{
|
||||||
|
std::string out;
|
||||||
|
for (char c : s) out += c == '~' ? "~0" : c == '/' ? "~1" : std::string(1, c);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
Json canonicalProfile(Json j) { return flatProfile(treeProfile(j)); }
|
||||||
|
std::wstring fieldLabel(const std::string &key)
|
||||||
|
{
|
||||||
|
static const std::map<std::string, std::wstring> labels{
|
||||||
|
{"toggleHotkey", L"Next layout shortcut"}, {"caseHotkey", L"Change case shortcut"},
|
||||||
|
{"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"},
|
||||||
|
{"autoCorrectReplace", L"Custom automatic replacements"}, {"autoCorrectTypos", L"Dictionary typo correction"},
|
||||||
|
{"autoCorrectReplacements", L"Replacement pairs"},
|
||||||
|
{"autoCorrectPrefixChars", L"Punctuation before words"}, {"autoCorrectSuffixChars", L"Punctuation after words"},
|
||||||
|
{"screenshotAutoOpenEditor", L"Open screenshot editor"}, {"tesseractLanguages", L"OCR languages"},
|
||||||
|
{"trigger", L"Trigger"}, {"text", L"Text"}};
|
||||||
|
auto it = labels.find(key); return it == labels.end() ? wide(key) : it->second;
|
||||||
|
}
|
||||||
|
struct MergeNode { Json local, remote, base; };
|
||||||
|
bool tombstone(const Json &j) { return j.is_object() && j.value("$deleted", false); }
|
||||||
|
MergeNode mergeNode(const Json &b, const Json &l, const Json &r, const std::string &path,
|
||||||
|
const std::wstring &label, const std::vector<SyncChoice> &choices, std::vector<SyncConflict> &conflicts,
|
||||||
|
const std::set<std::string> &forced)
|
||||||
|
{
|
||||||
|
if (l == r) return {l, l, l};
|
||||||
|
for (const auto &choice : choices)
|
||||||
|
if (choice.conflict.key == path && parse(choice.conflict.local) == l && parse(choice.conflict.remote) == r)
|
||||||
|
{
|
||||||
|
auto selected = choice.useLocal ? l : r;
|
||||||
|
if (selected.is_null() && path.starts_with("/snippets/") && path.find('/', 10) == std::string::npos)
|
||||||
|
selected = {{"$deleted", true}};
|
||||||
|
return {selected, selected, selected};
|
||||||
|
}
|
||||||
|
if (forced.contains(path))
|
||||||
|
{
|
||||||
|
conflicts.push_back({path, label + L" (duplicate trigger or shortcut)", bytes(l), bytes(r)});
|
||||||
|
return {l, r, b};
|
||||||
|
}
|
||||||
|
bool forcedChild = std::any_of(forced.begin(), forced.end(), [&](const std::string &key) { return key.starts_with(path + "/"); });
|
||||||
|
if (!forcedChild && l == b) return {r, r, r};
|
||||||
|
if (!forcedChild && r == b) return {l, l, l};
|
||||||
|
if (l.is_object() && r.is_object() && (b.is_object() || b.is_null()) && !tombstone(l) && !tombstone(r) && !tombstone(b))
|
||||||
|
{
|
||||||
|
MergeNode out{Json::object(), Json::object(), Json::object()};
|
||||||
|
std::set<std::string> keys;
|
||||||
|
for (const auto *j : {&b, &l, &r}) if (j->is_object()) for (auto it = j->begin(); it != j->end(); ++it) keys.insert(it.key());
|
||||||
|
for (const auto &key : keys)
|
||||||
|
{
|
||||||
|
auto get = [&](const Json &j) { return j.is_object() && j.contains(key) ? j.at(key) : Json(); };
|
||||||
|
auto childLabel = label.empty() ? fieldLabel(key) : label + L" / " + fieldLabel(key);
|
||||||
|
if (path == "/snippets")
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
conflicts.push_back({path, label, bytes(l), bytes(r)});
|
||||||
|
return {l, r, b};
|
||||||
|
}
|
||||||
|
void collisionPaths(const Json &j, std::set<std::string> &paths)
|
||||||
|
{
|
||||||
|
std::map<std::wstring, std::string> triggers;
|
||||||
|
for (const auto &[id, sn] : j.at("snippets").items())
|
||||||
|
{
|
||||||
|
if (sn.is_null() || tombstone(sn)) continue;
|
||||||
|
auto path = "/snippets/" + pointerKey(id);
|
||||||
|
auto key = lower(wide(sn.at("trigger").get<std::string>()));
|
||||||
|
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) {
|
||||||
|
if (!text.is_string()) return;
|
||||||
|
auto hotkey = Hotkey::parse(wide(text.get<std::string>()));
|
||||||
|
if (!hotkey || !hotkey->key) return;
|
||||||
|
auto [it, inserted] = shortcuts.emplace(std::make_pair(hotkey->modifiers, hotkey->key), path);
|
||||||
|
if (!inserted) { paths.insert(path); paths.insert(it->second); }
|
||||||
|
};
|
||||||
|
for (const auto *key : {"toggleHotkey", "caseHotkey", "translitHotkey", "undoHotkey", "clipboardHotkey", "screenshotHotkey"}) add(j.at(key), std::string("/") + key);
|
||||||
|
for (const auto &[id, key] : j.at("layoutHotkeys").items()) add(key, "/layoutHotkeys/" + pointerKey(id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SyncMerge mergeSyncProfile(const Bytes &base, const Bytes &local, const Bytes &remote, const std::vector<SyncChoice> &choices)
|
||||||
|
{
|
||||||
|
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));
|
||||||
|
SyncMerge result;
|
||||||
|
auto merged = mergeNode(b, l, r, "", L"", choices, result.conflicts, {});
|
||||||
|
std::set<std::string> collisions;
|
||||||
|
collisionPaths(merged.local, collisions); collisionPaths(merged.remote, collisions);
|
||||||
|
if (!collisions.empty())
|
||||||
|
{
|
||||||
|
result.conflicts.clear();
|
||||||
|
merged = mergeNode(b, l, r, "", L"", choices, result.conflicts, collisions);
|
||||||
|
}
|
||||||
|
result.local = bytes(flatProfile(merged.local));
|
||||||
|
result.remote = bytes(flatProfile(merged.remote));
|
||||||
|
result.base = bytes(flatProfile(merged.base));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
Bytes mergeSyncSettings(const Bytes &base, const Bytes &local, const Bytes &remote)
|
||||||
|
{
|
||||||
|
auto result = mergeSyncProfile(base, local, remote);
|
||||||
|
if (!result.conflicts.empty()) throw std::runtime_error("Conflicting setting: " + result.conflicts.front().key);
|
||||||
|
return result.local;
|
||||||
|
}
|
||||||
+633
-118
File diff suppressed because it is too large.
Load diff
+163
@@ -0,0 +1,163 @@
|
|||||||
|
// 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);
|
||||||
|
std::wstring state=L"Not paired";
|
||||||
|
if(peer.at("paired").get<bool>()){
|
||||||
|
bool connected=next.value("inputReady",nlohmann::json::object()).contains(id);
|
||||||
|
state=connected?L"Pair saved — input connected":
|
||||||
|
!next.value("shareInput",false)?L"Pair saved — input disabled here":
|
||||||
|
!peer.value("online",false)?L"Pair saved — computer offline":L"Pair saved — input not connected";
|
||||||
|
}
|
||||||
|
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"] — "+state);
|
||||||
|
}
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
+9
-9
@@ -309,18 +309,18 @@ void showLogs(App &app)
|
|||||||
SendMessageW(choice, CB_ADDSTRING, 0, (LPARAM)L"Current log — kswitcher.log");
|
SendMessageW(choice, CB_ADDSTRING, 0, (LPARAM)L"Current log — kswitcher.log");
|
||||||
SendMessageW(choice, CB_ADDSTRING, 0, (LPARAM)L"Previous log — kswitcher.log.1");
|
SendMessageW(choice, CB_ADDSTRING, 0, (LPARAM)L"Previous log — kswitcher.log.1");
|
||||||
SendMessageW(choice, CB_SETCURSEL, 0, 0);
|
SendMessageW(choice, CB_SETCURSEL, 0, 0);
|
||||||
button(w, L"Refresh", LogRefresh, 310, 14, 100);
|
button(w, L"&Refresh", LogRefresh, 310, 14, 100);
|
||||||
button(w, L"Copy selected", LogCopy, 424, 14, 140);
|
button(w, L"&Copy selected", LogCopy, 424, 14, 140);
|
||||||
button(w, L"Clear log", LogClear, 578, 14, 100);
|
button(w, L"Clear &log", LogClear, 578, 14, 100);
|
||||||
control(w, L"STATIC", L"", 0, LogStatus, 16, 49, 1068, 22);
|
control(w, L"STATIC", L"", 0, LogStatus, 16, 49, 1068, 22);
|
||||||
label(w, L"Program", 16, 78, 170);
|
label(w, L"&Program", 16, 78, 170);
|
||||||
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, LogProgram, 16, 101, 174, 300);
|
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, LogProgram, 16, 101, 174, 300);
|
||||||
label(w, L"Command", 206, 78, 200);
|
label(w, L"Co&mmand", 206, 78, 200);
|
||||||
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, LogCommand, 206, 101, 204, 300);
|
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, LogCommand, 206, 101, 204, 300);
|
||||||
label(w, L"Result", 426, 78, 300);
|
label(w, L"Res&ult", 426, 78, 300);
|
||||||
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, LogResult, 426, 101, 310, 300);
|
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, LogResult, 426, 101, 310, 300);
|
||||||
checkbox(w, L"Only problems", LogProblems, 752, 102, 166);
|
checkbox(w, L"&Only problems", LogProblems, 752, 102, 166);
|
||||||
button(w, L"Reset filters", LogReset, 938, 98, 146);
|
button(w, L"Reset &filters", LogReset, 938, 98, 146);
|
||||||
INITCOMMONCONTROLSEX common{sizeof(common), ICC_LISTVIEW_CLASSES};
|
INITCOMMONCONTROLSEX common{sizeof(common), ICC_LISTVIEW_CLASSES};
|
||||||
InitCommonControlsEx(&common);
|
InitCommonControlsEx(&common);
|
||||||
auto list = control(w, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SHOWSELALWAYS,
|
auto list = control(w, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SHOWSELALWAYS,
|
||||||
@@ -344,7 +344,7 @@ void showLogs(App &app)
|
|||||||
w, L"STATIC",
|
w, L"STATIC",
|
||||||
L"Click a column to sort. Select an operation for details. Ctrl+C copies selected operations.", 0, 0,
|
L"Click a column to sort. Select an operation for details. Ctrl+C copies selected operations.", 0, 0,
|
||||||
16, 712, 860, 22);
|
16, 712, 860, 22);
|
||||||
button(w, L"Close", IDCANCEL, 974, 708, 110);
|
button(w, L"Clos&e", IDCANCEL, 974, 708, 110);
|
||||||
auto *layout = windowLayoutState(w);
|
auto *layout = windowLayoutState(w);
|
||||||
layout->stretch = list;
|
layout->stretch = list;
|
||||||
layout->details = details;
|
layout->details = details;
|
||||||
|
|||||||
+149
@@ -0,0 +1,149 @@
|
|||||||
|
#include "ui_sync_conflicts.inl"
|
||||||
|
struct SyncView { HWND parent; App *app; };
|
||||||
|
void updateSyncControls(HWND w, App &app)
|
||||||
|
{
|
||||||
|
bool enabled = checked(w, 601);
|
||||||
|
bool savedEnabled = loadSyncConfig(app.data).enabled;
|
||||||
|
for (int id : {602, 603, 604, 605, 606, 607, 610, 611, 613})
|
||||||
|
EnableWindow(GetDlgItem(w, id), enabled);
|
||||||
|
EnableWindow(GetDlgItem(w, 612), enabled && savedEnabled);
|
||||||
|
EnableWindow(GetDlgItem(w, IDOK), enabled || savedEnabled);
|
||||||
|
value(w, IDOK, enabled ? L"&Save / Sign in / Sync" : L"&Save");
|
||||||
|
std::wstring status;
|
||||||
|
if (!enabled)
|
||||||
|
status = savedEnabled ? L"Click Save to disable synchronization." :
|
||||||
|
L"Synchronization is disabled. Enable it above to configure and sync.";
|
||||||
|
else if (!savedEnabled)
|
||||||
|
status = L"Configure the connection, then click Save / Sign in / Sync to enable synchronization.";
|
||||||
|
else
|
||||||
|
status = app.syncCommand();
|
||||||
|
if (value(w, 608) != status) value(w, 608, status);
|
||||||
|
}
|
||||||
|
SyncConfig syncFields(HWND w)
|
||||||
|
{
|
||||||
|
SyncConfig c;
|
||||||
|
c.enabled = checked(w, 601);
|
||||||
|
c.keepLocalLayouts = checked(w, 613);
|
||||||
|
c.server = value(w, 602);
|
||||||
|
while (!c.server.empty() && c.server.back() == L'/') c.server.pop_back();
|
||||||
|
c.username = lower(value(w, 603)); c.mount = value(w, 605);
|
||||||
|
c.path = value(w, 606); c.authMount = value(w, 607);
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
LRESULT CALLBACK syncProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||||
|
{
|
||||||
|
if (msg == WM_DPICHANGED) { resizeForDpi(w, wp, lp); return 0; }
|
||||||
|
auto *v = reinterpret_cast<SyncView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||||
|
if (!v) return DefWindowProcW(w, msg, wp, lp);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (msg == WM_TIMER)
|
||||||
|
{
|
||||||
|
updateSyncControls(w, *v->app);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (msg == WM_COMMAND)
|
||||||
|
{
|
||||||
|
int id = LOWORD(wp);
|
||||||
|
if (id == 601 && HIWORD(wp) == BN_CLICKED)
|
||||||
|
{
|
||||||
|
updateSyncControls(w, *v->app);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if ((id == IDOK || id == 610 || id == 611 || id == 612) &&
|
||||||
|
!IsWindowEnabled(GetDlgItem(w, id))) return 0;
|
||||||
|
if (id == 612) { showSyncConflicts(w, *v->app); return 0; }
|
||||||
|
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
|
||||||
|
if (id == 609)
|
||||||
|
{
|
||||||
|
auto c = loadSyncConfig(v->app->data);
|
||||||
|
c.enabled = false;
|
||||||
|
saveSyncConfig(v->app->data, c);
|
||||||
|
forgetSyncPassword(c);
|
||||||
|
check(w, 601, false);
|
||||||
|
value(w, 604, L"");
|
||||||
|
updateSyncControls(w, *v->app);
|
||||||
|
value(w, 608, L"Disabled. Saved password removed. An in-flight server request may still finish.");
|
||||||
|
KillTimer(w, 1);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (id == IDOK || id == 610 || id == 611)
|
||||||
|
{
|
||||||
|
if (!checked(w, 601))
|
||||||
|
{
|
||||||
|
if (id != IDOK) return 0;
|
||||||
|
auto c = loadSyncConfig(v->app->data);
|
||||||
|
c.enabled = false;
|
||||||
|
saveSyncConfig(v->app->data, c);
|
||||||
|
value(w, 604, L"");
|
||||||
|
updateSyncControls(w, *v->app);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (id != IDOK && MessageBoxW(w, id == 610 ?
|
||||||
|
L"Replace this PC's shared settings with the remote profile? A local backup will be saved. Unsaved edits in Settings are not included." :
|
||||||
|
L"Replace the remote profile with this PC's saved settings? OpenBao retains older versions according to its retention policy. Unsaved edits are not included.",
|
||||||
|
L"Resolve synchronization", MB_YESNO | MB_ICONWARNING) != IDYES) return 0;
|
||||||
|
auto c = syncFields(w);
|
||||||
|
if (c.enabled) validateSyncConfig(c);
|
||||||
|
auto password = value(w, 604);
|
||||||
|
try { if (!password.empty()) saveSyncPassword(c, password); }
|
||||||
|
catch (...) { SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t)); throw; }
|
||||||
|
SecureZeroMemory(password.data(), password.size() * sizeof(wchar_t));
|
||||||
|
value(w, 604, L"");
|
||||||
|
saveSyncConfig(v->app->data, c);
|
||||||
|
value(w, 608, v->app->syncCommand(id == 610 ? 2 : id == 611 ? 3 : 1));
|
||||||
|
updateSyncControls(w, *v->app);
|
||||||
|
SetTimer(w, 1, 1000, nullptr);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (const std::exception &e)
|
||||||
|
{
|
||||||
|
// Never display parser exceptions containing connection file contents.
|
||||||
|
value(w, 608, L"Unable to complete sync action. Check connection fields and saved configuration.");
|
||||||
|
if (dynamic_cast<const std::runtime_error *>(&e))
|
||||||
|
value(w, 608, wide(e.what()));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
|
||||||
|
if (msg == WM_NCDESTROY)
|
||||||
|
{
|
||||||
|
KillTimer(w, 1);
|
||||||
|
EnableWindow(v->parent, TRUE); SetForegroundWindow(v->parent);
|
||||||
|
disposeFont(w); delete v; SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||||
|
}
|
||||||
|
return DefWindowProcW(w, msg, wp, lp);
|
||||||
|
}
|
||||||
|
void showSyncOptions(HWND parent, App &app)
|
||||||
|
{
|
||||||
|
auto c = loadSyncConfig(app.data);
|
||||||
|
HWND w = makeWindow(app, L"KSwitcher.Sync", L"Settings synchronization - OpenBao", syncProc, 660, 672);
|
||||||
|
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
|
||||||
|
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)new SyncView{parent, &app});
|
||||||
|
checkbox(w, L"&Enable synchronization with your OpenBao (KV v2)", 601, 18, 18, 620);
|
||||||
|
check(w, 601, c.enabled);
|
||||||
|
label(w, L"Se&rver (HTTPS)", 18, 60, 160); edit(w, 602, 190, 56, 450); value(w, 602, c.server);
|
||||||
|
label(w, L"User&name", 18, 100, 160); edit(w, 603, 190, 96, 450); value(w, 603, c.username);
|
||||||
|
label(w, L"&Password", 18, 140, 160); edit(w, 604, 190, 136, 450, 25, ES_AUTOHSCROLL | ES_PASSWORD);
|
||||||
|
label(w, L"Leave password blank to use the saved Windows credential.", 190, 166, 450);
|
||||||
|
label(w, L"KV v2 &mount", 18, 210, 160); edit(w, 605, 190, 206, 450); value(w, 605, c.mount);
|
||||||
|
label(w, L"Profile pa&th", 18, 250, 160); edit(w, 606, 190, 246, 450); value(w, 606, c.path);
|
||||||
|
label(w, L"&Login mount", 18, 290, 160); edit(w, 607, 190, 286, 450); value(w, 607, c.authMount);
|
||||||
|
label(w, L"Sync uses saved settings. Close and reopen Settings after downloading changes.", 18, 330, 622);
|
||||||
|
edit(w, 608, 18, 362, 622, 76, ES_MULTILINE | ES_READONLY | WS_VSCROLL | ES_AUTOVSCROLL);
|
||||||
|
value(w, 608, app.syncCommand());
|
||||||
|
checkbox(w, L"&Keep this PC's layouts and layout shortcuts (sync other settings)", 613, 18, 446, 622);
|
||||||
|
check(w, 613, c.keepLocalLayouts);
|
||||||
|
button(w, L"&Save / Sign in / Sync", IDOK, 18, 484, 200);
|
||||||
|
button(w, L"&Download remote", 610, 230, 484, 195);
|
||||||
|
button(w, L"&Upload local", 611, 437, 484, 203);
|
||||||
|
button(w, L"Resolve &individual conflicts...", 612, 18, 530, 300);
|
||||||
|
label(w, L"Background check: every 10 minutes", 330, 534, 310);
|
||||||
|
button(w, L"Disconnect / &forget password", 609, 18, 582, 290);
|
||||||
|
button(w, L"&Close", IDCANCEL, 540, 582, 100);
|
||||||
|
updateSyncControls(w, app);
|
||||||
|
EnableWindow(parent, FALSE);
|
||||||
|
SetTimer(w, 1, 1000, nullptr);
|
||||||
|
showRequestedWindow(w); SetForegroundWindow(w);
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
struct SyncConflictView
|
||||||
|
{
|
||||||
|
HWND parent;
|
||||||
|
App *app;
|
||||||
|
std::vector<SyncConflict> conflicts;
|
||||||
|
std::map<size_t, bool> choices;
|
||||||
|
};
|
||||||
|
void showConflictValues(HWND w, SyncConflictView *v)
|
||||||
|
{
|
||||||
|
int selected = (int)SendDlgItemMessageW(w, 620, LB_GETCURSEL, 0, 0);
|
||||||
|
if (selected < 0 || selected >= (int)v->conflicts.size()) return;
|
||||||
|
const auto &c = v->conflicts[selected];
|
||||||
|
value(w, 621, syncValueText(c.local)); value(w, 622, syncValueText(c.remote));
|
||||||
|
}
|
||||||
|
LRESULT CALLBACK syncConflictsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||||||
|
{
|
||||||
|
if (msg == WM_DPICHANGED) { resizeForDpi(w, wp, lp); return 0; }
|
||||||
|
auto *v = reinterpret_cast<SyncConflictView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||||||
|
if (!v) return DefWindowProcW(w, msg, wp, lp);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (msg == WM_COMMAND)
|
||||||
|
{
|
||||||
|
int id = LOWORD(wp);
|
||||||
|
if (id == 620 && HIWORD(wp) == LBN_SELCHANGE) { showConflictValues(w, v); return 0; }
|
||||||
|
if (id == 623 || id == 624)
|
||||||
|
{
|
||||||
|
int selected = (int)SendDlgItemMessageW(w, 620, LB_GETCURSEL, 0, 0);
|
||||||
|
if (selected < 0 || selected >= (int)v->conflicts.size()) return 0;
|
||||||
|
v->choices[selected] = id == 623;
|
||||||
|
auto text = v->conflicts[selected].label + (id == 623 ? L" [This PC]" : L" [Server]");
|
||||||
|
SendDlgItemMessageW(w, 620, LB_DELETESTRING, selected, 0);
|
||||||
|
SendDlgItemMessageW(w, 620, LB_INSERTSTRING, selected, (LPARAM)text.c_str());
|
||||||
|
SendDlgItemMessageW(w, 620, LB_SETCURSEL, selected, 0);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (id == IDOK)
|
||||||
|
{
|
||||||
|
if (v->choices.empty()) throw std::runtime_error("Select a setting and choose This PC or Server first.");
|
||||||
|
std::vector<SyncChoice> choices;
|
||||||
|
for (const auto &[index, local] : v->choices) choices.push_back({v->conflicts.at(index), local});
|
||||||
|
auto status = v->app->syncCommand(4, choices);
|
||||||
|
value(v->parent, 608, status);
|
||||||
|
if (status != L"Connecting to OpenBao...") throw std::runtime_error(utf8(status));
|
||||||
|
DestroyWindow(w); return 0;
|
||||||
|
}
|
||||||
|
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (const std::exception &e) { error(w, e); return 0; }
|
||||||
|
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
|
||||||
|
if (msg == WM_NCDESTROY)
|
||||||
|
{
|
||||||
|
EnableWindow(v->parent, TRUE); SetForegroundWindow(v->parent);
|
||||||
|
disposeFont(w); delete v; SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||||||
|
}
|
||||||
|
return DefWindowProcW(w, msg, wp, lp);
|
||||||
|
}
|
||||||
|
void showSyncConflicts(HWND parent, App &app)
|
||||||
|
{
|
||||||
|
auto conflicts = decodeSyncConflicts(app.syncConflictData());
|
||||||
|
if (conflicts.empty()) { value(parent, 608, L"No pending conflicts. Run Sync to check for changes."); return; }
|
||||||
|
HWND w = makeWindow(app, L"KSwitcher.SyncConflicts", L"Resolve individual settings", syncConflictsProc, 800, 560);
|
||||||
|
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
|
||||||
|
auto *v = new SyncConflictView{parent, &app, std::move(conflicts), {}};
|
||||||
|
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
|
||||||
|
label(w, L"Choose a value for each conflicting setting. Other changes are already synchronized.", 18, 16, 760);
|
||||||
|
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | WS_BORDER, 620, 18, 48, 760, 130);
|
||||||
|
for (const auto &c : v->conflicts) SendDlgItemMessageW(w, 620, LB_ADDSTRING, 0, (LPARAM)c.label.c_str());
|
||||||
|
label(w, L"This PC", 18, 190, 360); label(w, L"Server", 410, 190, 368);
|
||||||
|
edit(w, 621, 18, 220, 368, 180, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL);
|
||||||
|
edit(w, 622, 410, 220, 368, 180, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL);
|
||||||
|
button(w, L"Use this &PC for selected setting", 623, 18, 412, 368);
|
||||||
|
button(w, L"Use &server for selected setting", 624, 410, 412, 368);
|
||||||
|
label(w, L"Unselected conflicts stay pending. Changed values will be checked again before saving.", 18, 454, 760);
|
||||||
|
button(w, L"&Apply choices", IDOK, 526, 488, 140);
|
||||||
|
button(w, L"&Cancel", IDCANCEL, 678, 488, 100);
|
||||||
|
SendDlgItemMessageW(w, 620, LB_SETCURSEL, 0, 0); showConflictValues(w, v);
|
||||||
|
EnableWindow(parent, FALSE); showRequestedWindow(w); SetForegroundWindow(w);
|
||||||
|
}
|
||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
#include "platform.h"
|
#include "platform.h"
|
||||||
namespace ks
|
namespace ks
|
||||||
{
|
{
|
||||||
inline constexpr wchar_t AppVersion[] = L"0.6.23";
|
inline constexpr wchar_t AppVersion[] = L"0.6.58";
|
||||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 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,377 @@
|
|||||||
|
#include "app.h"
|
||||||
|
#include "ocr.h"
|
||||||
|
#include "screenshot.h"
|
||||||
|
#include "lan_pairing.h"
|
||||||
|
#include <iostream>
|
||||||
|
#include <commctrl.h>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
HWND findTestWindow(LPCWSTR className, LPCWSTR title)
|
||||||
|
{
|
||||||
|
HWND window=nullptr;
|
||||||
|
while((window=FindWindowExW(nullptr,window,className,title))) {
|
||||||
|
DWORD process{}; GetWindowThreadProcessId(window,&process);
|
||||||
|
if(process==GetCurrentProcessId()) return window;
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
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=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
|
||||||
|
require(ocr!=nullptr,"OCR preferences open");
|
||||||
|
wchar_t languages[128]{}; GetDlgItemTextW(ocr,503,languages,128);
|
||||||
|
SetDlgItemTextW(ocr,503,L"eng");
|
||||||
|
SendMessageW(ocr,WM_COMMAND,IDCANCEL,0);
|
||||||
|
require(!saveEnabled(),"cancelled child changes leave Settings clean");
|
||||||
|
SendMessageW(parent,WM_COMMAND,257,0);
|
||||||
|
ocr=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
|
||||||
|
SetDlgItemTextW(ocr,503,std::wstring(languages)==L"eng"?L"ukr":L"eng");
|
||||||
|
SendMessageW(ocr,WM_COMMAND,IDOK,0);
|
||||||
|
require(!IsWindow(ocr) && saveEnabled(),"accepted OCR edits enable parent Save");
|
||||||
|
SendMessageW(parent,WM_COMMAND,257,0);
|
||||||
|
ocr=findTestWindow(L"KSwitcher.OcrOptions",nullptr);
|
||||||
|
SetDlgItemTextW(ocr,503,languages);
|
||||||
|
SendMessageW(ocr,WM_COMMAND,IDOK,0);
|
||||||
|
require(!saveEnabled(),"reverting OCR draft in child clears parent dirty state");
|
||||||
|
SendMessageW(parent,WM_COMMAND,255,0);
|
||||||
|
HWND automatic=findTestWindow(L"KSwitcher.AutoOptions",nullptr);
|
||||||
|
require(automatic!=nullptr,"automatic correction preferences open");
|
||||||
|
bool replace=IsDlgButtonChecked(automatic,414)==BST_CHECKED;
|
||||||
|
CheckDlgButton(automatic,414,replace?BST_UNCHECKED:BST_CHECKED);
|
||||||
|
SendMessageW(automatic,WM_COMMAND,IDOK,0);
|
||||||
|
require(!IsWindow(automatic) && saveEnabled(),"accepted auto-correction edits enable Save");
|
||||||
|
SendMessageW(parent,WM_COMMAND,255,0);
|
||||||
|
automatic=findTestWindow(L"KSwitcher.AutoOptions",nullptr);
|
||||||
|
CheckDlgButton(automatic,414,replace?BST_CHECKED:BST_UNCHECKED);
|
||||||
|
SendMessageW(automatic,WM_COMMAND,IDOK,0);
|
||||||
|
require(!saveEnabled(),"reverting auto-correction draft disables Save");
|
||||||
|
HWND tabs = GetDlgItem(parent, 260);
|
||||||
|
require(tabs && TabCtrl_GetItemCount(tabs) == 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 = findTestWindow(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 = findTestWindow(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 = findTestWindow(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=findTestWindow(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=findTestWindow(L"KSwitcher.LAN",nullptr);
|
||||||
|
require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"single saved pair selected automatically when opening LAN settings");
|
||||||
|
wchar_t pairState[512]{};SendDlgItemMessageW(lan,702,LB_GETTEXT,0,(LPARAM)pairState);
|
||||||
|
require(std::wstring(pairState).find(L"Pair saved — input disabled here")!=std::wstring::npos,"saved pairing does not imply an active input connection");
|
||||||
|
require(!IsWindowEnabled(GetDlgItem(lan,705))&&!IsWindowEnabled(GetDlgItem(lan,703))&&!IsWindowEnabled(GetDlgItem(lan,704)),"saved pair disables pairing and code controls");
|
||||||
|
SendDlgItemMessageW(lan,702,LB_SETCURSEL,-1,0);
|
||||||
|
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=findTestWindow(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 | ||||||