Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01f44d22b5 | ||
|
|
c78090f7d4 | ||
|
|
0d797c4f35 | ||
|
|
b6eaa2c85d | ||
|
|
72024c3385 | ||
|
|
d60ef626f0 | ||
|
|
e144cd6607 | ||
|
|
05a3f7a8f4 | ||
|
|
12b8f5090c | ||
|
|
19d574edcf | ||
|
|
3840744819 | ||
|
|
94e8ba4304 | ||
|
|
edb1440be0 | ||
|
|
8ef13ca9bd | ||
|
|
c0eca89738 | ||
|
|
0b6709495b | ||
|
|
5f0c51b557 | ||
|
|
733b6deefa | ||
|
|
b3a1e762ec | ||
|
|
219bdd4883 | ||
|
|
d018b91397 | ||
|
|
2d4df0daa8 | ||
|
|
773df250a4 | ||
|
|
b5924feb23 | ||
|
|
c285505d79 | ||
|
|
2e1b0446bc | ||
|
|
5ac3735db3 | ||
|
|
03984705fe | ||
|
|
dedc42f0db | ||
|
|
e5d639a72f | ||
|
|
4d68c80409 | ||
|
|
6af042a524 | ||
|
|
b28789a4f5 | ||
|
|
eaae5389d9 | ||
|
|
88b8536116 | ||
|
|
b8997d1dd2 | ||
|
|
1926bce15f | ||
|
|
afddcafdac | ||
|
|
21d28a0f6d | ||
|
|
f73dce7bb3 | ||
|
|
3c5f59ed91 | ||
|
|
e50fbbc119 | ||
|
|
6c5b09132f | ||
|
|
92774881ed | ||
|
|
353f4c2919 | ||
|
|
733f1b0fc9 | ||
|
|
878ae8fce8 | ||
|
|
edd9b2b3f9 | ||
|
|
36b0002404 | ||
|
|
8ffafde12a | ||
|
|
2bd325d294 | ||
|
|
d4c4f9be76 | ||
|
|
af388be4a7 | ||
|
|
3efdd2ef06 | ||
|
|
01b467e149 | ||
|
|
cf2dd6c419 | ||
|
|
293c5fd47e | ||
|
|
1dd6d75596 | ||
|
|
1aa23636ea | ||
|
|
886532f831 | ||
|
|
abaf73a050 | ||
|
|
b16e50bee9 | ||
|
|
3ed17fa6e8 | ||
|
|
a1df56177d | ||
|
|
09db0e1051 | ||
|
|
e1d8343c32 | ||
|
|
1ecd57a5e4 | ||
|
|
1ba169874a | ||
|
|
3037f9840e | ||
|
|
6b3a382f70 | ||
|
|
ef4438359f | ||
|
|
d2082f1593 | ||
|
|
57ccb2322d | ||
|
|
710d0cd591 | ||
|
|
8b53392b20 | ||
|
|
2824bef442 | ||
|
|
a8cf51002d | ||
|
|
0298e98bbe | ||
|
|
cc6a832c73 | ||
|
|
7873b1afda | ||
|
|
0f9e62abf2 | ||
|
|
3b4bc3f3b9 | ||
|
|
9649248dae | ||
|
|
47541dabc4 | ||
|
|
59a07d91dc | ||
|
|
9f37549a6c | ||
|
|
badb789e19 | ||
|
|
d80dfb0b91 | ||
|
|
eefa3e0baf | ||
|
|
1cd351a356 | ||
|
|
31958ee448 | ||
|
|
f3803e32b4 | ||
|
|
2f96efb2e6 | ||
|
|
05b648f110 | ||
|
|
6e0246f0e5 | ||
|
|
bcd8d2bc1f | ||
|
|
012af57aae | ||
|
|
8e608533da | ||
|
|
ad06cf48fe | ||
|
|
5bee16e403 | ||
|
|
5721aa0cdf | ||
|
|
55b8de9051 | ||
|
|
1d560903f6 | ||
|
|
b1d2ef3363 | ||
|
|
2ecffae995 | ||
|
|
eb481edafe | ||
|
|
dc57c12c52 | ||
|
|
4983d044de | ||
|
|
a30d43753f | ||
|
|
8cb601f267 | ||
|
|
0f6b88dd90 | ||
|
|
b1eddda20d | ||
|
|
1a5b25830c | ||
|
|
a0fc043d6a | ||
|
|
8d3f48e924 | ||
|
|
9a6fc10c6b | ||
|
|
4c825738bd | ||
|
|
627ab5ae24 | ||
|
|
904e379ffe | ||
|
|
ff2ebb0117 | ||
|
|
4b144dad2f | ||
|
|
e78c092b88 | ||
|
|
a4b9e28a7b | ||
|
|
5fb00122c6 | ||
|
|
545473c69d | ||
|
|
376e33dcf9 | ||
|
|
ba8514625d | ||
|
|
9f59fd3293 | ||
|
|
e8ae0c3001 | ||
|
|
b7f8abbe39 | ||
|
|
444843778d | ||
|
|
2e0b58ccf5 | ||
|
|
ee7b4edda8 | ||
|
|
733127f0dd | ||
|
|
4cd3104201 | ||
|
|
384a93dfea | ||
|
|
1407b4d260 | ||
|
|
3bcbfeee15 | ||
|
|
3117b2d9c8 | ||
|
|
47e9de5326 | ||
|
|
ac6700deba | ||
|
|
d68ac1a685 | ||
|
|
007b1827ac | ||
|
|
4ccf70b7c1 | ||
|
|
437fb48240 | ||
|
|
80adc2bd7d | ||
|
|
4926871177 | ||
|
|
9cfd58578e | ||
|
|
4841d1c095 | ||
|
|
86a8aeea3f | ||
|
|
8879776f21 | ||
|
|
d98e0b8378 | ||
|
|
c51e9d41d8 | ||
|
|
e9a3615a10 | ||
|
|
765acc2326 | ||
|
|
d361ecfbc7 | ||
|
|
11fe80c506 | ||
|
|
124a56feef | ||
|
|
88791e6e36 | ||
|
|
dd54f8d4dc | ||
|
|
2214c5229d | ||
|
|
758559e9ef | ||
|
|
345e3af81c | ||
|
|
e3022a2e99 | ||
|
|
2fbd31d412 | ||
|
|
a3f298d26a | ||
|
|
be40130126 | ||
|
|
6d31d70b2a | ||
|
|
d990428ea7 | ||
|
|
7c2282502f | ||
|
|
4f13d783f5 | ||
|
|
20ee6bc57d | ||
|
|
95453735e4 | ||
|
|
0d75619fe7 | ||
|
|
81f76b7b22 | ||
|
|
13e55dcbf3 | ||
|
|
9eaa2dea1c | ||
|
|
f6f1a7e66e | ||
|
|
512082d1cc | ||
|
|
d8fa32d670 | ||
|
|
0903544bd2 | ||
|
|
4ec0191dbb | ||
|
|
9c99d394e9 | ||
|
|
46469da034 | ||
|
|
bfcc7b59bc | ||
|
|
ff56e1f988 | ||
|
|
885600df50 | ||
|
|
96bccac11e | ||
|
|
36041ee202 | ||
|
|
1433a5c71f | ||
|
|
b6d0612a5b | ||
|
|
cf16597f8a | ||
|
|
ce5dc1c3f3 | ||
|
|
d6863abb22 | ||
|
|
e1b2fca51a | ||
|
|
557f4a402d | ||
|
|
07f402b00b | ||
|
|
97b7370b08 | ||
|
|
96894cbed3 | ||
|
|
84f8eff236 | ||
|
|
e23bfee1d6 | ||
|
|
2da68946d7 | ||
|
|
7fd8f72d2f | ||
|
|
dbcbdf34b3 | ||
|
|
84db13e13f | ||
|
|
892968f429 | ||
|
|
47109439f9 | ||
|
|
e92288e34d | ||
|
|
5a8f763fb2 | ||
|
|
024d109739 | ||
|
|
8aa16cb021 | ||
|
|
d63dae1828 | ||
|
|
69a2a7ec39 | ||
|
|
677f8ed8aa | ||
|
|
49f85d549e | ||
|
|
ca041bd7b9 | ||
|
|
7d304e61c4 | ||
|
|
b3f8eb7b72 | ||
|
|
7de8790284 | ||
|
|
06004ed0c7 | ||
|
|
c1e7964fdd | ||
|
|
483da0307a | ||
|
|
be714bc039 | ||
|
|
6ce9469ce7 | ||
|
|
2ea41beb46 | ||
|
|
101f6f5ed8 | ||
|
|
aeab2cf283 | ||
|
|
92d491dff3 |
No files matched your search
@@ -4,5 +4,6 @@
|
||||
/.vs/
|
||||
/.idea/
|
||||
/dist/
|
||||
/Release/KSwitcher-win-x64.zip
|
||||
/build-output.txt
|
||||
*.user
|
||||
@@ -0,0 +1,73 @@
|
||||
# Project instructions
|
||||
|
||||
## Reuse shared code
|
||||
|
||||
Reuse existing shared code wherever possible. When the same behavior,
|
||||
component, or logic is needed in two or more places, extract it into a
|
||||
shared component or function and use it at every applicable call site.
|
||||
|
||||
## Mandatory Wiki updates for every release
|
||||
|
||||
A release is not complete until the published project Wiki reflects that release.
|
||||
Apply this rule to every release, including patch releases and bug-fix-only releases.
|
||||
|
||||
Wiki: https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki
|
||||
|
||||
1. Confirm the release version from `CMakeLists.txt`, the release tag and
|
||||
`Release/README.md`. Use the complete version (for example, `v0.6.17`) and
|
||||
preserve the release channel rules in `README.md`.
|
||||
2. Update the latest-version information on the Wiki home pages and any other
|
||||
pages identifying the current release. Update release dates, download links
|
||||
and upgrade instructions where needed. Keep historical version references
|
||||
and compatibility bridge instructions when they are still accurate.
|
||||
3. Review the changes since the last release documented in the Wiki, not just
|
||||
the immediately preceding release. Bring the relevant feature pages up to
|
||||
date with the shipped behavior: new, changed and removed functionality,
|
||||
settings, shortcuts, defaults, limitations and troubleshooting. Update
|
||||
screenshots or examples when they no longer match the application.
|
||||
For bug-fix-only releases, check whether documented behavior or workarounds
|
||||
need correction; do not invent feature changes.
|
||||
4. Keep English and Ukrainian pages synchronized, including `Home` and
|
||||
`Home-uk`, and preserve working translation and navigation links.
|
||||
5. Publish the Wiki changes as part of the release workflow. Read back the
|
||||
published pages and verify the current version, feature descriptions,
|
||||
download links and translation links. A local Wiki edit alone is not enough.
|
||||
6. In the release completion report, link the updated Wiki pages and summarize
|
||||
the documentation changes. If Wiki publication or verification is blocked,
|
||||
explicitly report the outstanding step and do not claim the release workflow
|
||||
is complete.
|
||||
|
||||
Updating only the release notes or changing only the Wiki version number does
|
||||
not satisfy this rule; the current functionality must also be reviewed.
|
||||
|
||||
## Gitea issue authentication
|
||||
|
||||
For Gitea issue API requests from this checkout, use the project token stored
|
||||
with Windows DPAPI in `kswitcher-gitea-token.dpapi` under the directory returned
|
||||
by `git rev-parse --absolute-git-dir`. Read it with PowerShell
|
||||
`Get-Content -LiteralPath $tokenFile | ConvertTo-SecureString` and use it only
|
||||
for the Gitea authorization header. Keep the token out of tracked files and
|
||||
command output.
|
||||
|
||||
## KSwitcher Files UI
|
||||
|
||||
Before changing the file manager UI, read [FILES-UI.md](FILES-UI.md).
|
||||
Reuse the shared dialog rendering and layout helpers. Update the document
|
||||
when an agreed UI requirement changes.
|
||||
Verify visible changes in a rendered window. For rendering regressions,
|
||||
add an automated check that fails on the reported appearance and run it
|
||||
before handing off a new build.
|
||||
|
||||
## Link changes to Gitea issues
|
||||
|
||||
For commits that implement a Gitea issue, include `Refs #<number>` in the
|
||||
commit message body. In a pull request, use `Fixes #<number>` when merging
|
||||
fully resolves the issue, or `Refs #<number>` when the work is partial.
|
||||
Use the existing issue for follow-up commits on the same change.
|
||||
|
||||
Assign each new issue to the [KSwitcher project board](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/projects/8)
|
||||
using its default column, and verify that the issue appears on the board.
|
||||
|
||||
Use Markdown headings, lists, and bold emphasis to make issue descriptions
|
||||
easy to scan. Embed relevant screenshots as Markdown images using their
|
||||
Gitea attachment URLs, and verify that the images render in the description.
|
||||
@@ -1,15 +1,58 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.4.2 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.112 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
add_library(kscore src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp)
|
||||
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
|
||||
src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
|
||||
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico")
|
||||
include(cmake/FilesTextLibraries.cmake)
|
||||
set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files")
|
||||
target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
|
||||
find_program(KSWITCHER_POWERSHELL NAMES pwsh powershell REQUIRED)
|
||||
add_custom_target(KSwitcherTerminalAssets
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tools/stage-files-terminal.ps1"
|
||||
-Destination "$<TARGET_FILE_DIR:KSwitcherFiles>"
|
||||
VERBATIM)
|
||||
add_dependencies(KSwitcherFiles KSwitcherTerminalAssets)
|
||||
add_custom_target(check-files-search-arrow
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_search_arrow.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>"
|
||||
DEPENDS KSwitcherFiles
|
||||
VERBATIM)
|
||||
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
|
||||
else()
|
||||
target_link_options(KSwitcherFiles PRIVATE -municode -static)
|
||||
endif()
|
||||
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_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp)
|
||||
target_link_libraries(KSwitcherFiles PRIVATE kscore)
|
||||
target_include_directories(kscore PUBLIC src PRIVATE vendor)
|
||||
target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
|
||||
target_link_libraries(kscore PUBLIC user32 shell32 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.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore)
|
||||
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1")
|
||||
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
|
||||
target_link_libraries(KSwitcher PRIVATE kscore)
|
||||
add_executable(KSwitcherConfig WIN32 src/config_main.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
@@ -17,42 +60,231 @@ set_target_properties(KSwitcherConfig PROPERTIES OUTPUT_NAME "KSwitcher.Config")
|
||||
target_compile_definitions(KSwitcherConfig PRIVATE KS_CONFIG_APP)
|
||||
target_link_libraries(KSwitcherConfig PRIVATE kscore)
|
||||
add_executable(KSwitcherTests tests/tests.cpp)
|
||||
target_include_directories(KSwitcherTests PRIVATE vendor)
|
||||
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)
|
||||
target_link_libraries(KSwitcherScrollTests PRIVATE kscore)
|
||||
target_link_libraries(KSwitcherTests PRIVATE kscore)
|
||||
add_executable(KSwitcherIntegration tests/integration.cpp src/app.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)
|
||||
add_executable(KSwitcherInputTests tests/input.cpp src/app.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
# Opt-in interactive fixture: requires an installed Far Manager.
|
||||
add_executable(KSwitcherFarSnippetTests WIN32 tests/far_snippets.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherFarSnippetTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherFarSnippetTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherFarSnippetTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherFarSnippetTests PRIVATE -municode -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_executable(KSwitcherInputTests tests/input.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherInputTests PRIVATE kscore)
|
||||
add_executable(KSwitcherScreenshotUITests tests/screenshot_ui.cpp src/app.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES)
|
||||
add_executable(KSwitcherScreenshotUITests tests/screenshot_ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherScreenshotUITests PRIVATE kscore)
|
||||
target_compile_definitions(KSwitcherScreenshotUITests PRIVATE KS_SCREENSHOT_RESOURCES)
|
||||
add_executable(KSwitcherScreenshot WIN32 src/screenshot_main.cpp src/screenshot_notifications.cpp src/screenshot_activation.cpp src/screenshot.cpp resources/app.rc)
|
||||
set_target_properties(KSwitcherScreenshot PROPERTIES OUTPUT_NAME "KSwitcher.Screenshot")
|
||||
target_compile_definitions(KSwitcherScreenshot PRIVATE KS_SCREENSHOT_RESOURCES)
|
||||
target_link_libraries(KSwitcherScreenshot PRIVATE kscore)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherScreenshotUITests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherScreenshotUITests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherScreenshotUITests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_executable(KSwitcherOcrTests tests/ocr.cpp)
|
||||
add_executable(KSwitcherOcrTests tests/ocr.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
|
||||
target_link_libraries(KSwitcherOcrTests PRIVATE kscore)
|
||||
add_dependencies(KSwitcherOcrTests KSwitcherScreenshot)
|
||||
if(MSVC)
|
||||
set_property(TARGET kscore KSwitcher KSwitcherConfig KSwitcherTests 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(KSwitcher PRIVATE /W4 /utf-8)
|
||||
target_compile_options(KSwitcherConfig PRIVATE /W4 /utf-8)
|
||||
target_compile_options(KSwitcherScreenshot PRIVATE /W4 /utf-8)
|
||||
else()
|
||||
target_link_options(KSwitcher PRIVATE -municode -static -static-libgcc -static-libstdc++)
|
||||
target_link_options(KSwitcherConfig PRIVATE -municode -static -static-libgcc -static-libstdc++)
|
||||
target_link_options(KSwitcherScreenshot PRIVATE -municode -static -static-libgcc -static-libstdc++)
|
||||
target_link_options(KSwitcherTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
target_link_options(KSwitcherScrollTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
target_link_options(KSwitcherIntegration PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
target_link_options(KSwitcherInputTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
target_link_options(KSwitcherOcrTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
enable_testing()
|
||||
add_executable(KSwitcherFilesTextTests tests/files_text_document.cpp src/files_text_document.cpp)
|
||||
target_include_directories(KSwitcherFilesTextTests PRIVATE src)
|
||||
target_compile_definitions(KSwitcherFilesTextTests PRIVATE UNICODE _UNICODE NOMINMAX WIN32_LEAN_AND_MEAN)
|
||||
target_link_libraries(KSwitcherFilesTextTests PRIVATE ole32)
|
||||
if(NOT MSVC)
|
||||
target_link_options(KSwitcherFilesTextTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME files-text-document COMMAND KSwitcherFilesTextTests)
|
||||
add_executable(KSwitcherFilesModalTests tests/files_modal_dialog.cpp)
|
||||
target_include_directories(KSwitcherFilesModalTests PRIVATE src)
|
||||
target_link_libraries(KSwitcherFilesModalTests PRIVATE user32 comctl32)
|
||||
if(NOT MSVC)
|
||||
target_link_options(KSwitcherFilesModalTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME files-modal-dialog COMMAND KSwitcherFilesModalTests)
|
||||
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(KSwitcherLanFilesTests tests/lan_files.cpp)
|
||||
target_link_libraries(KSwitcherLanFilesTests PRIVATE kscore)
|
||||
add_test(NAME lan-files-regressions COMMAND KSwitcherLanFilesTests)
|
||||
add_executable(KSwitcherFilesActivationFixture tests/files_activation_fixture.cpp)
|
||||
if(NOT MSVC)
|
||||
target_link_options(KSwitcherFilesActivationFixture PRIVATE -municode -static)
|
||||
endif()
|
||||
add_test(NAME files-activation-and-refresh
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>")
|
||||
set_tests_properties(files-activation-and-refresh PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
|
||||
add_test(NAME files-system-open
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
|
||||
-SystemOpenOnly)
|
||||
set_tests_properties(files-system-open PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
|
||||
find_program(KSWITCHER_NODE NAMES node)
|
||||
if(KSWITCHER_NODE)
|
||||
add_test(NAME files-terminal-enter
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
|
||||
-TerminalOnly -Node "${KSWITCHER_NODE}")
|
||||
set_tests_properties(files-terminal-enter PROPERTIES RUN_SERIAL TRUE TIMEOUT 90)
|
||||
add_executable(KSwitcherFilesMarkdownLanFixture WIN32 tests/files_markdown_lan.cpp
|
||||
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
|
||||
target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText)
|
||||
add_dependencies(KSwitcherFilesMarkdownLanFixture KSwitcherTerminalAssets)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesMarkdownLanFixture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
target_compile_options(KSwitcherFilesMarkdownLanFixture PRIVATE /utf-8)
|
||||
else()
|
||||
target_link_options(KSwitcherFilesMarkdownLanFixture PRIVATE -municode -static)
|
||||
endif()
|
||||
add_test(NAME files-markdown-viewer
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_markdown.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Node "${KSWITCHER_NODE}"
|
||||
-LanFixture "$<TARGET_FILE:KSwitcherFilesMarkdownLanFixture>")
|
||||
set_tests_properties(files-markdown-viewer PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
|
||||
endif()
|
||||
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_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout)
|
||||
set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
|
||||
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
|
||||
target_link_libraries(KSwitcherHistoryHostTests PRIVATE kscore psapi)
|
||||
set_target_properties(KSwitcherHistoryHostTests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/history-host-fixture-$<CONFIG>")
|
||||
add_dependencies(KSwitcherHistoryHostTests KSwitcher KSwitcherScreenshot)
|
||||
add_custom_command(TARGET KSwitcherHistoryHostTests POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy "$<TARGET_FILE:KSwitcher>" "$<TARGET_FILE_DIR:KSwitcherHistoryHostTests>/KSwitcher.exe"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy "$<TARGET_FILE:KSwitcherScreenshot>" "$<TARGET_FILE_DIR:KSwitcherHistoryHostTests>/KSwitcher.Screenshot.exe"
|
||||
COMMAND ${CMAKE_COMMAND} -E touch "$<TARGET_FILE_DIR:KSwitcherHistoryHostTests>/.local-dev")
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherHistoryHostTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherHistoryHostTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherHistoryHostTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_executable(KSwitcherClipboardSnapshotTests tests/clipboard_snapshot.cpp)
|
||||
target_link_libraries(KSwitcherClipboardSnapshotTests PRIVATE kscore psapi)
|
||||
add_dependencies(KSwitcherClipboardSnapshotTests KSwitcherScreenshot)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherClipboardSnapshotTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherClipboardSnapshotTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherClipboardSnapshotTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_executable(KSwitcherImageCaptureTests tests/image_capture.cpp)
|
||||
target_link_libraries(KSwitcherImageCaptureTests PRIVATE kscore)
|
||||
add_dependencies(KSwitcherImageCaptureTests KSwitcherScreenshot)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherImageCaptureTests PRIVATE /utf-8)
|
||||
set_property(TARGET KSwitcherImageCaptureTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherImageCaptureTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
# Explicit interactive test: stop the resident first so its clipboard listener
|
||||
# does not capture the test fixtures. Like KSwitcherIntegration, not part of ctest.
|
||||
add_executable(KSwitcherDictionaryTests tests/dictionary.cpp)
|
||||
target_link_libraries(KSwitcherDictionaryTests PRIVATE kscore psapi)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherDictionaryTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherDictionaryTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME dictionary-regressions COMMAND KSwitcherDictionaryTests)
|
||||
set_tests_properties(dictionary-regressions PROPERTIES WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
add_test(NAME sync-regressions COMMAND KSwitcherSyncTests)
|
||||
add_test(NAME native-regressions COMMAND KSwitcherTests)
|
||||
add_executable(KSwitcherUtilitiesTests tests/utilities.cpp)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherUtilitiesTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherUtilitiesTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME utilities-regressions COMMAND KSwitcherUtilitiesTests)
|
||||
add_test(NAME stayhere-lifecycle COMMAND powershell -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/stayhere.ps1" -Executable "$<TARGET_FILE:StayHereTest>")
|
||||
add_test(NAME scroll-regressions COMMAND KSwitcherScrollTests)
|
||||
add_test(NAME input-regressions COMMAND KSwitcherInputTests)
|
||||
add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests)
|
||||
add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --save-only)
|
||||
add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$<TARGET_FILE:KSwitcher>")
|
||||
set_tests_properties(native-regressions PROPERTIES WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
install(TARGETS KSwitcher KSwitcherConfig RUNTIME DESTINATION .)
|
||||
install(TARGETS KSwitcher KSwitcherConfig KSwitcherScreenshot KSwitcherFiles RUNTIME DESTINATION .)
|
||||
install(FILES LICENSE vendor/json-LICENSE.txt DESTINATION .)
|
||||
|
||||
add_custom_command(TARGET KSwitcher POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/dictionaries" "$<TARGET_FILE_DIR:KSwitcher>/dictionaries")
|
||||
install(DIRECTORY dictionaries DESTINATION .)
|
||||
|
||||
add_executable(KSwitcherLanClipboardTests tests/lan_clipboard.cpp)
|
||||
target_link_libraries(KSwitcherLanClipboardTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherLanClipboardTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherLanClipboardTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME lan-clipboard-regressions COMMAND KSwitcherLanClipboardTests)
|
||||
|
||||
add_executable(KSwitcherSettingsMergeTests tests/settings_merge.cpp)
|
||||
target_link_libraries(KSwitcherSettingsMergeTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherSettingsMergeTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherSettingsMergeTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME settings-save-merge COMMAND KSwitcherSettingsMergeTests)
|
||||
@@ -0,0 +1,435 @@
|
||||
# Оформлення KSwitcher Files
|
||||
|
||||
Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far.
|
||||
Іконка головного вікна показує дві сині панелі з бірюзовою рамкою та виділеним рядком.
|
||||
|
||||
Власні модальні діалоги панелей, редактора й переглядача використовують
|
||||
`FilesModalDialog`. Escape і клік поза діалогом у клієнтській області Files
|
||||
виконують Cancel, а фокус повертається до елемента, з якого відкрили діалог.
|
||||
Кліки на робочому столі та в інших застосунках залишають діалог відкритим.
|
||||
Заголовок і рамка вікна-власника доступні, а діалог рухається разом із
|
||||
власником. Діалог центрується відносно власника та звужується разом із ним
|
||||
до власної мінімальної ширини. Поки діалог відкритий, ширина власника
|
||||
обмежена цією мінімальною шириною з відступами.
|
||||
Це діє і для вкладених діалогів. Під час файлової операції Cancel спершу
|
||||
просить підтвердити переривання.
|
||||
|
||||
Спільне повідомлення Files підлаштовується під заголовок і кількість рядків.
|
||||
Висота діалогу залежить від видимого вмісту. Приховані та порожні секції
|
||||
не займають місця. Перед завершенням змін перевір коротке повідомлення й
|
||||
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
|
||||
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
|
||||
Панелі, списки попапів і довгі повідомлення використовують вузьку смугу
|
||||
прокрутки зі стрілками вгорі й унизу та крапковою доріжкою. Відтінки доріжки
|
||||
й повзунка залежать від фону, на якому вони малюються. Повзунок світліший
|
||||
за доріжку й показує положення та розмір видимої частини списку.
|
||||
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
|
||||
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
|
||||
Warning і початковий фокус на No.
|
||||
|
||||
## Скорочення
|
||||
|
||||
- У меню Files і його списках, що випадають, стрілки вгору й вниз
|
||||
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
|
||||
|
||||
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
|
||||
документ — у програмі, призначеній для його типу у Windows. EXE запускається
|
||||
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
|
||||
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
|
||||
панелі LAN, спочатку скопіюй його до локальної папки.
|
||||
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
|
||||
елемент через Windows.
|
||||
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
|
||||
|
||||
- У головному вікні клавіатурний фокус залишається в командному рядку.
|
||||
Tab без модифікаторів перемикає активну панель, а клік вибирає рядок.
|
||||
Ctrl+U міняє видимі панелі місцями разом із їхніми папками, режимами,
|
||||
курсорами й позначками. Активна панель залишається активною на новому боці.
|
||||
Page Up і Page Down пересувають курсор у панелі. Стрілки вгору й вниз
|
||||
керують панеллю, коли список підказок закритий.
|
||||
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
|
||||
командний рядок порожній.
|
||||
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
|
||||
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
|
||||
текст із буфера обміну в позицію курсора або замінюють виділення.
|
||||
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
|
||||
виконує команду одразу. Коли рядок
|
||||
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
|
||||
Enter передає порожній рядок у термінал.
|
||||
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
|
||||
командного рядка й виконують відповідну дію за тими самими правилами.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
- Під час набору локальної команди над полем з’являються підказки PowerShell.
|
||||
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
|
||||
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
|
||||
та шляхи відносно робочої папки термінала або активної панелі до запуску
|
||||
термінала. Після `cd ` список пропонує папки,
|
||||
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
|
||||
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
|
||||
Enter вставляє виділену, а клік вставляє підказку під вказівником.
|
||||
Щоб виконати команду після вставлення, натисни Enter ще раз.
|
||||
Escape закриває список зі збереженням тексту. Без списку Escape очищає
|
||||
рядок, а Tab перемикає панель, якщо панелі відкриті. Доступні підказки стандартної локальної
|
||||
сесії PowerShell, включно з програмами з PATH. Для команд без аргументів,
|
||||
як-от `cls`, список не пропонує шляхи.
|
||||
Для `dotnet` підкоманди й параметри підказує встановлений .NET SDK.
|
||||
Для `git` підкоманди, параметри й доречні назви гілок бере штатний
|
||||
скрипт Git for Windows. Підказки використовують локальні дані репозиторію.
|
||||
- Довідник Windows Commands надає офлайн підказки ключів і підкоманд для
|
||||
системних утиліт. Наприклад, `ipconfig /re` пропонує `/release` і `/renew`,
|
||||
`reg q` пропонує `query`, а `cmd /c dir /` пропонує ключі `dir` для CMD.
|
||||
Каталог також підказує вкладені підкоманди та значення, перелічені в
|
||||
синтаксисі. Наприклад, `netsh interface ipv4 show co` пропонує `config`,
|
||||
а `schtasks /query /fo ` пропонує `CSV`, `LIST` і `TABLE`. F1 у командному
|
||||
рядку відкриває статтю Microsoft Learn для поточної команди чи підкоманди.
|
||||
Якщо ввести `dir` безпосередньо у Files, PowerShell підказує власні параметри.
|
||||
Після `ipconfig /renew ` або `ipconfig /release ` список підказує назви
|
||||
локальних адаптерів із DHCP для IPv4. Назви з пробілами вставляються в лапках.
|
||||
- Коли курсор у кінці рядка, список спочатку показує до 5 різних
|
||||
останніх команд з історії, які починаються з набраного тексту.
|
||||
Вибір підставляє всю команду. Підказки з історії доступні й у LAN-панелі.
|
||||
|
||||
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
|
||||
що й клавіша F8.
|
||||
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
|
||||
а назви дій темні на бірюзових сегментах.
|
||||
- У віддаленій панелі Enter запускає введену команду PowerShell на
|
||||
спареному ПК в поточному каталозі цієї панелі. Вивід і код завершення
|
||||
з’являються в терміналі Files як текст. Службовий прогрес PowerShell
|
||||
приховано. Кожна команда запускається окремо,
|
||||
тому змінні середовища й `cd` між командами не зберігаються. Escape
|
||||
в порожньому командному рядку скасовує поточну віддалену команду.
|
||||
- На ПК, який приймає команди, увімкніть **Options → Command line →
|
||||
Command history → Allow paired PCs to run PowerShell commands here**.
|
||||
Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Команди
|
||||
запускаються без підвищених прав. Для цієї функції оновіть обидва ПК.
|
||||
- **F9 → Commands → Hibernate remote PC** доступна для активної LAN-панелі.
|
||||
У підтвердженні показується ім’я цільового ПК. На цільовому ПК ввімкніть
|
||||
**Options → Command line → Command history → Allow paired PCs to hibernate this PC**.
|
||||
Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Для цієї дії
|
||||
потрібні оновлення на обох ПК і ввімкнена гібернація Windows.
|
||||
- У **Change drive** (Alt+F1 або Alt+F2) підкреслена дія **Wake** є праворуч
|
||||
від стану офлайн-ПК. Клік по слову або Enter з фокусом на дії надсилає пакет.
|
||||
Статус відображається на тлі списку. Для текстових дій усередині рядків
|
||||
використовуй спільний компонент `InlineListAction` для малювання, фокуса
|
||||
й обробки кліків. KSwitcher
|
||||
має зберегти MAC-адресу мережевого адаптера. Оновіть KSwitcher та дайте
|
||||
обом ПК побачити один одного в локальній мережі. На цільовому ПК потрібна
|
||||
підтримка Wake-on-LAN у прошивці та налаштуваннях адаптера. Рядок стану
|
||||
повідомляє про надсилання пакета або відсутність збереженої MAC-адреси.
|
||||
- **F9 → Commands → Update remote KSwitcher** запускає штатне оновлення для
|
||||
ПК активної LAN-панелі. Підтвердження з іменем ПК показується у Files
|
||||
відправника. На цільовому ПК потрібен дозвіл **Options → Command line →
|
||||
Command history → Allow paired PCs to update KSwitcher here**. Після
|
||||
перевірки нового стабільного пакета оновлювач без запитань закриває
|
||||
KSwitcher, Files, Config і редактори скриншотів цієї інсталяції.
|
||||
Незбережені зміни у примусово закритих вікнах втрачаються.
|
||||
Закриття процесів і результат записуються до `kswitcher.log`.
|
||||
|
||||
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
|
||||
курсора командного рядка або замінює виділення. Подвійні лапки додаються
|
||||
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
|
||||
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
|
||||
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу
|
||||
активна панель показує «Loading folder…» і зберігає попередній список до
|
||||
завершення сканування. Після переходу оновлюються шлях і список цієї панелі
|
||||
та командний рядок. Сусідня панель не перемальовується через цей перехід.
|
||||
Якщо надійшов новіший запит, результат попереднього
|
||||
сканування пропускається. Після підтвердження UAC очікування списку
|
||||
від підвищеного процесу теж відбувається у фоні.
|
||||
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
|
||||
зберігаються для наявних елементів, а підраховані через F3 розміри папок
|
||||
скидаються. F2 також виконує цю дію.
|
||||
- Ctrl+C і Ctrl+Insert копіюють виділений текст із виводу термінала.
|
||||
- За відсутності виділення у виводі Ctrl+C копіює весь введений у командний
|
||||
рядок текст, навіть коли виділено лише його частину.
|
||||
- Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок
|
||||
порожній, копіюються імена позначених файлів і папок активної панелі в
|
||||
порядку відображення, по одному на рядок. Якщо позначок немає, копіюється
|
||||
ім’я під курсором. Шляхи й рядок `..` пропускаються.
|
||||
|
||||
- Ctrl+E підставляє останню команду. Повторне натискання
|
||||
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
|
||||
з групуванням за датами. Enter або подвійний клік у списку підставляє вибрану
|
||||
команду в поле. Для запуску натисни Enter у самому полі.
|
||||
- Історія зберігає 1000 останніх непорожніх команд, надісланих із поля KSwitcher
|
||||
Files, включно з повторами. Вона зберігається локально в профілі Windows між
|
||||
запусками. Options → Command line → Command history змінює обидві комбінації,
|
||||
перевіряє конфлікти та дозволяє відновити типові значення.
|
||||
- Ширина історії підлаштовується під найдовшу команду в межах робочої області
|
||||
монітора. Рядок, який не вміщується, закінчується трьома крапками. Вибір
|
||||
підставляє до командного рядка повний текст.
|
||||
- Пошук в історії фільтрує команди за всіма введеними словами, незалежно від
|
||||
регістру. Збіги за текстом або датою йдуть перед тематичними. Тематичні
|
||||
ключові слова визначаються локально й використовуються лише для пошуку,
|
||||
зокрема в раніше збережених записах. Кожна команда відображається один
|
||||
раз, за датою останнього запуску.
|
||||
- Історія використовує оформлення діалогів Delete і Copy та спільне поле Far.
|
||||
Підпис, поле й список вирівнюються за відступами Dialog frame. Рядки команд
|
||||
і роздільники дат мають власний внутрішній відступ.
|
||||
Вікно історії бірюзове, поле пошуку сіро-бірюзове. Поки історія відкрита,
|
||||
дії в панелях, меню й командному рядку заблоковано. Заголовок і рамка
|
||||
головного вікна доступні для переміщення, зміни розміру та керування вікном.
|
||||
Escape або клік у Files поза діалогом закриває історію. Заголовок і рамка головного
|
||||
вікна залишають історію відкритою під час керування вікном.
|
||||
Історія центрується відносно головного вікна й рухається разом із ним.
|
||||
Tab циклічно переводить фокус між пошуком і списком.
|
||||
Стрілка вгору або вниз із пошуку одразу пересуває вибір у списку.
|
||||
Висота списку залежить від кількості результатів. Коли місця бракує,
|
||||
прокручується список.
|
||||
|
||||
- Alt із символом шукає початок назви файлу чи папки. Після першого збігу
|
||||
внизу активної панелі відкривається компактне поле Search у подвійній рамці.
|
||||
Наступні символи можна набирати без Alt. Пошук враховує поточну розкладку
|
||||
та ігнорує регістр. Backspace прибирає останній символ, Escape закриває пошук,
|
||||
а Enter відкриває поточний елемент.
|
||||
- F9 перемикає головне меню Files. Після закриття фокус повертається в командний рядок. Коли меню відкрите, Alt з літерою верхнього рівня відкриває відповідний пункт.
|
||||
- Коли головне меню відкрите, L, F, C, O та R відкривають Left, Files, Commands, Options та Right. У підменю підсвічена літера викликає відповідну команду. Літери унікальні в межах поточного рівня. Усталені мнемоніки мають пріоритет, зокрема X для Exit.
|
||||
- У Commands лінії відокремлюють навігацію панелі, перегляд і редагування
|
||||
та керування віддаленим ПК. Остання група з’являється разом зі своїм
|
||||
роздільником лише в активній LAN-панелі. Роздільники пропускаються під
|
||||
час навігації й не реагують на клік.
|
||||
- Глобальне скорочення **Open KSwitcher Files** можна змінити або очистити в налаштуваннях. Для профілю без цього поля пропонується Ctrl+Alt+F, якщо Windows реєструє комбінацію і вона вільна серед прив’язок KSwitcher.
|
||||
- Глобальне скорочення повертає до відкритого вікна Files у поточній сесії Windows або запускає Files, якщо такого вікна немає. Пункт **Files** у треї відкриває нове вікно.
|
||||
|
||||
- Ctrl+Shift+0–9 відкриває діалог Title і Path із поточною папкою. OK додає запис без дублювання, Escape скасовує. Title необов’язковий, порожнє значення показує шлях. Записи LAN зберігають ID ПК, а редагування Path залишає запис на тому самому ПК.
|
||||
- Ctrl+0–9 відкриває лише папки, призначені натиснутій цифрі. Єдина папка відкривається одразу. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
|
||||
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options.
|
||||
|
||||
## Налаштування Files
|
||||
|
||||
### Переглядач і редактор
|
||||
|
||||
- F3 відкриває поточний локальний файл у вбудованому переглядачі лише
|
||||
для читання. F4 відкриває спільне вікно в режимі редагування. Alt+F3
|
||||
відкриває файл у програмі, призначеній Windows для цього типу, а Alt+F4
|
||||
викликає зареєстровану дію Edit. Ці команди також є в меню Commands.
|
||||
F10 або × закривають головне вікно Files. Вбудовані Viewer та Editor
|
||||
відкриваються в окремих немодальних вікнах. Редактор має іконку олівця,
|
||||
переглядач — іконку ока. Ці іконки видно в заголовку, в Alt+Tab і в окремих
|
||||
групах на панелі завдань Windows. F6 змінює іконку й групу поточного вікна.
|
||||
При повторному відкритті Files пропонує перейти до вже
|
||||
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
|
||||
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
|
||||
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
|
||||
Помилка збереження залишає відкритим редактор зі змінами.
|
||||
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
|
||||
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
|
||||
порядку. Коли відкрито лише Files, активна панель не змінюється.
|
||||
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
|
||||
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
|
||||
із підсвічуванням Markdown.
|
||||
HTML усередині Markdown підтримує таблиці, текстове форматування, посилання,
|
||||
відносні зображення й окремі стилі, зокрема `white-space: nowrap` у клітинках.
|
||||
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
|
||||
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
|
||||
Вихідний текст приховано, доки Markdown і Mermaid готують перегляд.
|
||||
Звичайний клік відкриває внутрішнє посилання в тому самому вікні,
|
||||
Shift+клік відкриває окреме вікно. Назад і вперед працюють через стрілки
|
||||
перегляду, бічні кнопки миші й Alt+←/→. Ctrl+W закриває перегляд.
|
||||
Ctrl+F або кнопка пошуку відкриває пошук у відрендерованому документі.
|
||||
Пошук без урахування регістру показує кількість збігів і підсвічує поточний.
|
||||
Enter і F3 переходять до наступного збігу, а Shift+Enter і Shift+F3 — до
|
||||
попереднього, циклічно. Escape спочатку закриває поле пошуку.
|
||||
Коли локальний Markdown оновлюється на диску, відкритий перегляд
|
||||
перерендерюється зі збереженням позиції прокрутки.
|
||||
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
|
||||
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
|
||||
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
|
||||
8 МіБ, F3 відкриває текстовий перегляд.
|
||||
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
|
||||
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
|
||||
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
|
||||
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
|
||||
junction не обходяться. Недоступний вміст позначається як частковий результат.
|
||||
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
|
||||
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
|
||||
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
|
||||
копії, Files відхиляє запис і залишає зміни в редакторі. Для F4 оновіть
|
||||
KSwitcher також на віддаленому ПК. Alt+F3 і Alt+F4 потребують локальної копії.
|
||||
- Вікно використовує той самий шрифт і розмір, що й файлові панелі,
|
||||
синю палітру Far за замовчуванням,
|
||||
рядок стану згори й підказки клавіш унизу. Інформація про файл
|
||||
вирівняна праворуч. Режим (Edit або View) стоїть у дужках після імені,
|
||||
далі йдуть кодування, синтаксис, позиція курсора й сторінка великого файла.
|
||||
Номери рядків показані приглушеним кольором з невеликим відступом від тексту.
|
||||
Меню редактора й переглядача використовують моноширинний шрифт і кольори
|
||||
обраної схеми. У FAR (blue) написи верхнього меню чорні, поточний пункт
|
||||
має чорне тло, а літери доступу жовті. F9 відкриває меню, Alt з літерою
|
||||
доступу відкриває потрібний розділ. Редактор позначає незбережені зміни зірочкою.
|
||||
Esc і F10 закривають незмінений файл одразу. Якщо вміст змінився,
|
||||
діалог Far пропонує Save, Discard або Cancel.
|
||||
- Syntax → Automatic визначає синтаксис за іменем, розширенням або
|
||||
shebang. Відомі типи включають C#, C/C++, JavaScript/TypeScript,
|
||||
HTML, XML, CSS, SQL, Python, PowerShell, Bash, JSON, YAML, TOML і Markdown.
|
||||
У меню Syntax можна вибрати будь-який вбудований лексер Lexilla або Plain text.
|
||||
Стан багаторядкової конструкції починається заново на межі сторінки.
|
||||
- Ctrl+PgUp/PgDn перемикають сторінки, F5 переходить до заданої сторінки,
|
||||
Ctrl+Shift+Home/End відкривають першу й останню. Ctrl+F шукає в поточній
|
||||
сторінці, F3 повторює пошук. Ctrl+A виділяє поточну сторінку.
|
||||
Історія Undo/Redo діє в межах відкритої сторінки.
|
||||
- Початкова сторінка займає близько 1 МіБ файла. Для вставок і редагування
|
||||
сторінка може вирости до 8 МіБ у UTF-8. Зміни інших сторінок тимчасово
|
||||
зберігаються на диску. F2 або Ctrl+S потоково записують нову копію в
|
||||
папку файла, тож збереження потребує вільного місця для цієї копії.
|
||||
UTF-8 із BOM або без нього та UTF-16 LE/BE із BOM зберігають своє
|
||||
кодування. Нередаговані байти копіюються без перетворення.
|
||||
- Команда Options у панелях, редакторі й переглядачі відкриває один діалог
|
||||
KSwitcher Files Options. Розділи Viewer та Editor зберігають окремі профілі.
|
||||
**Viewer → Markdown** задає максимальну ширину документа (0 — усе вікно),
|
||||
гарнітуру та розмір основного тексту. Порожня гарнітура використовує системний
|
||||
шрифт. Apply одразу оновлює відкриті перегляди Markdown.
|
||||
Після повторного відкриття Options відновлюється останній розділ, зокрема
|
||||
після Cancel. Пошуковий запит і чернетка змін не зберігаються.
|
||||
З редактора або переглядача діалог відкриває відповідний розділ. Apply
|
||||
застосовує зміни до відкритих вікон, Cancel відкидає незастосовану чернетку.
|
||||
Доступні перенесення рядків, номери рядків, показ пробілів і
|
||||
кінців рядків, підсвічування поточного рядка, ширина табуляції від 1 до 16,
|
||||
схеми FAR (blue), Dark і Light та власні кольори. Save scheme у розділі
|
||||
Viewer або Editor додає поточну палітру до спільного списку схем. Apply
|
||||
зберігає її та робить доступною в обох розділах. У редакторі також можна
|
||||
ввімкнути вставлення пробілів замість табуляцій і автоматичні відступи,
|
||||
а також вибрати символи кінця для нових рядків.
|
||||
- Діалоги пошуку й переходу до сторінки використовують подвійні рамки та
|
||||
кнопки Files. Search має компактний розмір, сіре тло, бірюзове поле та окремі кнопки
|
||||
Find previous і Find next. Word і Selection підставляють у поле слово
|
||||
під курсором або однорядкове виділення. Поле має висоту одного рядка
|
||||
й вертикально центрований текст. Стрілка біля поля або Alt+Down
|
||||
відкриває історію з групуванням за датами. Вибір запису підставляє
|
||||
запит у поле. Editor і Viewer спільно зберігають до 100 останніх
|
||||
різних запитів між запусками. Спільний шрифт панелей, меню й тексту змінюється в
|
||||
Options → Appearance → Font. Редактор і переглядач отримують новий
|
||||
шрифт після Apply.
|
||||
|
||||
### Параметри файлових панелей
|
||||
|
||||
- Options у головному меню спочатку прибирає смугу меню й одразу відкриває стандартний діалог Windows. Ліворуч є пошук за назвою категорії чи параметра й дерево результатів. Вибір дочірнього вузла відкриває лише його редактор праворуч. Пошук за назвою окремої властивості відкриває вузол, що її містить. Перемикання вузлів зберігає незастосовані зміни.
|
||||
- File panel modes має вузли Panel layout, Wide panel columns і Status line columns. У Colors кожен колір має власний вузол. В Appearance шрифт редагується у вузлі Font. Діалог змінює розмір від розміру, який вміщує всі параметри. Ширина лівої навігації стала, дерево росте по висоті, а права область використовує додатковий простір. OK, Cancel та Apply лишаються внизу праворуч.
|
||||
- Reset selected to defaults скидає вибраний рівень дерева. Корінь All settings скидає всі параметри, навіть коли пошук приховує частину дерева. У редакторах із кількома параметрами Reset property скидає лише вибрану властивість. Скидання змінює чернетку до Apply або OK. Стандартний Panel background — `#000080`.
|
||||
- Apply доступна, коли чернетка відрізняється від застосованих налаштувань. Після Apply або повернення всіх значень до застосованих вона вимикається. Apply одразу зберігає зміни й перемальовує панелі за відкритим діалогом. OK робить те саме й закриває діалог. Cancel і Escape відкидають зміни після останнього Apply та повертають фокус до командного рядка.
|
||||
|
||||
- Colors → File type styles налаштовує текст, фон, підкреслення й закреслення для правил за розширенням і групи System and hidden. Розширення можна вибрати зі списку Windows або додати вручну з крапкою чи без неї. Вони зберігаються в KSwitcher, незалежно від асоціацій Windows. Курсор, позначки й результат передачі зберігають свої сигнальні кольори. Кольори правила можна перевизначити окремо для звичайного рядка, позначки Insert, курсора у фокусі та курсора без фокуса. Позначка має пріоритет над курсором, а підсвічування передачі має пріоритет над кольорами курсора. Без перевизначення стан зберігає звичайний вигляд панелі. Мініпанель унизу редактора одразу показує всі чотири стани на синтетичних рядках до Apply.
|
||||
|
||||
- Нижня область показує живе прев’ю для кольорів, шрифту, режимів панелей, широких колонок і рядка стану. Для Popup background, Menu selection і Command bar зразок показує відповідний елемент. Прев’ю читає чернетку, зокрема після Reset, і не потребує реальних файлів. Воно заповнює простір від останнього видимого елемента редактора до нижніх кнопок зі сталими відступами. Зі зміною розміру росте область зразка, а рядки зберігають масштаб шрифту.
|
||||
|
||||
- Підписи File type, Windows extension or custom extension і Row state стоять над відповідними полями зі спільним лівим краєм. Ширина списків враховує найдовші значення, шрифт, DPI й доступне місце. Add і Remove стоять одразу після своїх полів.
|
||||
|
||||
- Початковий набір правил охоплює EXE, Markdown, системні й приховані елементи, архіви, зображення, аудіо й відео, офісні документи й PDF, код і скрипти. Збережений набір правил завантажується як є, включно з видаленими правилами. Reset у File type styles відновлює весь початковий набір у чернетці.
|
||||
|
||||
## Панелі
|
||||
|
||||
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
|
||||
у відкритих локальних папках. Фокус залишається там, де був, а курсор
|
||||
лишається на поточному елементі, якщо той ще існує.
|
||||
|
||||
- У Change drive повідомлення No paired computers з’являється після
|
||||
успішної відповіді з порожнім списком. Збої локального запиту до
|
||||
KSwitcher відображаються окремо.
|
||||
|
||||
- Якщо команда у вбудованому PowerShell змінює поточну папку,
|
||||
панель, з якої надіслано команду, переходить до цієї папки.
|
||||
|
||||
- Коли список LAN-дисків змінює розмір меню Change drive, рамка й список
|
||||
змінюють позицію разом. Рамка повністю перемальовується після зміни
|
||||
розміру, а список має однаковий внутрішній відступ зліва і справа.
|
||||
- Тайм-аут запиту дисків відображається як Connection timed out. Якщо
|
||||
ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий
|
||||
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows.
|
||||
|
||||
- Застосовані налаштування Files одразу підхоплюють інші відкриті вікна.
|
||||
Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
|
||||
редагували набір стилів файлів, відкрий Options заново, щоб побачити свіжі правила.
|
||||
|
||||
- Типовий колір тексту для ZIP-архівів — світлий коралово-рожевий.
|
||||
|
||||
- Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК.
|
||||
|
||||
- Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно.
|
||||
- F5, F6, F8 і Shift+Delete у віддалених панелях використовують спільні підтвердження, попередження й прогрес. F5/F6 працюють із файлами та деревами папок між локальними й віддаленими панелями, зокрема між двома різними ПК. Між шляхами одного віддаленого ПК вміст копіюється на ньому. F8 використовує кошик того ПК, на якому лежить файл.
|
||||
- Після розриву з’єднання повтори F5 або F6 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення.
|
||||
|
||||
- F7, пункт Files → Make folder і кнопка F7 Mkdir відкривають модальний діалог Far. Стрілка біля імені та Alt+Down відкривають історію успішних введень. Link type має варіанти none, directory junction і symbolic link. Поле Target активне для посилань і приймає абсолютний шлях або шлях від поточної папки. У віддаленій панелі посилання створюється на віддаленому ПК, а symbolic link залежить від дозволів Windows на цьому ПК.
|
||||
- Process multiple names дозволяє розділити імена комами або крапками з комою. Якщо такий символ є частиною імені, візьми ім’я в подвійні лапки. Діалог створює елементи у поточному каталозі, оновлює панель і ставить курсор на останній створений елемент. При помилці в середині списку вже створені елементи зберігаються.
|
||||
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
|
||||
|
||||
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
|
||||
|
||||
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
|
||||
|
||||
## Спільні елементи діалогів
|
||||
|
||||
- Власні діалоги Files блокують дії панелей і командного рядка, залишаючи
|
||||
системний заголовок і рамку головного вікна доступними. Клік у Files поза діалогом
|
||||
діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває
|
||||
підтвердження скасування. Перелік і обробка файлів виконуються у фоновому
|
||||
потоці. Діалог залишається доступним під час очікування файлового вводу-виводу.
|
||||
Скасування перевіряється між кроками операції та під час передачі блоків.
|
||||
|
||||
- Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No.
|
||||
|
||||
- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання.
|
||||
- Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку.
|
||||
- Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення.
|
||||
- У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок.
|
||||
- Модальні діалоги редактора й переглядача використовують той самий шрифт, що й діалоги операцій Files. Розміри полів і кнопок враховують метрики цього шрифту.
|
||||
- Нижні секції з кнопками у Copy, Warning і вікні прогресу мають однакову висоту, прив’язану до висоти рядка шрифту. Використовуй `layoutDialogButtons` для такої секції та `centerDialogRow` для інших рядків між роздільниками. Межі секції визначають положення рядка.
|
||||
- Search і спільні нижні секції Far використовують компактні проміжки між рядками й кнопками, прив’язані до метрик моноширинного шрифту. У Search висота кнопки дорівнює висоті одного рядка.
|
||||
- Нижні кнопки Far групуються по центру. Їхня ширина залежить від напису й дужок, а проміжок між ними становить приблизно половину символу.
|
||||
- Прапорці Far у Search, Copy і попередженнях використовують спільний компонент. У фокусі короткий системний курсор блимає між дужками, а тло рядка зберігає колір діалогу.
|
||||
- У Copy і Rename/Move шлях перевіряється у фоновому потоці, і в цей час
|
||||
діалог можна скасувати. Помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
|
||||
- Помилки копіювання, переміщення й видалення показуються в червоному
|
||||
модальному діалозі Far із причиною помилки та кнопкою OK.
|
||||
- Якщо локальне перейменування або видалення заблоковане, кнопка Processes… відкриває
|
||||
список процесів із назвою та PID. Перевірка папки включає вкладені елементи.
|
||||
End process завершує вибраний процес після окремого підтвердження, після
|
||||
чого список оновлюється. Якщо Windows обмежила доступ або перевірку
|
||||
великої папки завершено частково, про це повідомляється в діалозі.
|
||||
Операцію можна повторити після звільнення файла чи папки.
|
||||
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
|
||||
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
|
||||
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
|
||||
- Випадаючі списки й поля Far мають висоту одного рядка шрифту. Бірюзове поле прилягає до сірої ділянки завширшки один символ із темною, вертикально центрованою стрілкою. Make folder, Search і Copy використовують спільне малювання стрілки. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус.
|
||||
- Розкриті списки й історія Far використовують спільний попап із бірюзовим тлом, світлою рамкою та чорним вибраним рядком. Попап прилягає до обох країв бірюзового поля, стрілка лишається праворуч за межами списку. Історія групується за датами. Довгі списки прокручуються, Enter вибирає рядок, Escape закриває список і повертає фокус до поля.
|
||||
- Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів.
|
||||
|
||||
## Діалог Copy
|
||||
|
||||
- Вирівнюй підпис Existing files по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені.
|
||||
- Зберігай однакові проміжки від верхнього роздільника до поля імені й до списку. Підпис, поля та прапорець мають читатися повністю.
|
||||
- Відступ після прапорця до нижнього роздільника дорівнює відступу від верхнього роздільника до списку.
|
||||
- Кнопки Copy та Cancel стоять по центру компактної нижньої секції. Висота кнопок має вміщати весь текст поточного шрифту.
|
||||
|
||||
## Вікно прогресу копіювання
|
||||
|
||||
- F6 використовує спільне оформлення діалогів Copy і прогресу. Заголовок підтвердження — Rename/Move, кнопка за замовчуванням — Rename, заголовок прогресу — Move.
|
||||
- Поле призначення F6 початково містить шлях іншої панелі. Для одного елемента просте ім’я задає перейменування в поточній папці. Для кількох елементів діалог показує їх кількість і приймає один шлях до папки.
|
||||
|
||||
- Секції поточного файла й загального прогресу мають однаковий вертикальний відступ від вмісту до верхньої та нижньої ліній. Cancel стоїть по центру спільної нижньої секції.
|
||||
- Обидві шкали займають усю ширину вмісту. Відсотки показуються по центру шкали, а її висота враховує поточний шрифт.
|
||||
|
||||
## Попередження про конфлікт
|
||||
|
||||
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
|
||||
час останньої зміни окремо для вхідного файла та файла в папці призначення.
|
||||
|
||||
- Після розрахунку остаточної висоти центр Warning збігається з центром вікна прогресу.
|
||||
- Remember choice стоїть по вертикальному центру власної секції. Кнопки Overwrite, Skip і Cancel стоять по центру нижньої секції.
|
||||
- Tab проходить Remember choice, Overwrite, Skip і Cancel. Стрілки вліво та вправо циклічно перемикають три кнопки в порядку їх розташування.
|
||||
- Стрілки вгору й вниз переходять між сусідніми секціями з інтерактивними елементами. У Warning стрілка вгору з ряду кнопок переводить фокус на Remember choice, а вниз із прапорця — на Overwrite.
|
||||
|
||||
## Видалення
|
||||
|
||||
- F8 показує сіре підтвердження з дією Move. Shift+Delete і підтвердження непорожньої папки мають темно-червоне тло. Вікно прогресу видалення має сіре тло, як у Copy.
|
||||
- Escape у початковому підтвердженні повертає фокус до командного рядка. Поточний рядок активної панелі зберігається, а стрілки одразу працюють.
|
||||
- F8 переміщує підтверджені елементи в кошик Windows. Shift+Delete видаляє підтверджене дерево від вкладених елементів до батьківської папки. Прогрес і підсумок окремо показують успішні, пропущені й невдалі дії.
|
||||
- Cancel і Esc у вікні прогресу відкривають спільне червоне підтвердження скасування. Yes зупиняє операцію, а No або Esc у підтвердженні повертає до прогресу. Початковий фокус стоїть на No.
|
||||
|
||||
## Перевірка змін
|
||||
|
||||
Відкрий Copy і Warning в одній збірці та порівняй висоту нижніх секцій, центрування, повноту підписів і видимість фокуса. Перевір Tab, стрілки й Esc. Після узгодження нового правила онови відповідний розділ цього документа.
|
||||
@@ -0,0 +1,170 @@
|
||||
# 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.
|
||||
|
||||
## Files and diagnostic logs
|
||||
|
||||
In **Settings → Computers → Manage computers…**, select an online paired
|
||||
computer and choose **Send file…**. Both computers need a build with file transfer.
|
||||
Files up to 16 MiB travel over encrypted LAN. On the destination, open
|
||||
**Incoming files…** to save or discard each file. The save dialog suggests the
|
||||
original filename. KSwitcher shows a Windows notification when a file is ready
|
||||
to save, and its tray tooltip shows the pending count. Pending files are held
|
||||
in memory until saved, discarded, or KSwitcher closes.
|
||||
|
||||
To retrieve the current or rotated diagnostic log, enable **Allow paired
|
||||
computers to download diagnostic logs** on the computer that owns the logs.
|
||||
This setting defaults to off. On the requesting PC, select that computer and
|
||||
choose **Download log…** or **Previous log…**. Diagnostic logs may contain
|
||||
text copied from applications.
|
||||
|
||||
### MCP
|
||||
|
||||
In **Settings → MCP**, choose **Copy configuration** and paste the block into
|
||||
Codex's `~/.codex/config.toml`. It starts the MCP server over stdio with the
|
||||
absolute path to `KSwitcher.Config.exe` and the `--mcp` argument.
|
||||
`list_log_computers` returns paired computer IDs and availability.
|
||||
`read_diagnostic_log` reads the latest 100 lines by default (1–500 with
|
||||
`lines`). Use `offset` to skip newer lines and page backward. Set `previous` to read the rotated log. Omit `peer` for the
|
||||
local log or pass a paired computer ID for a remote log. Remote reads need
|
||||
the local resident process running and log downloads enabled on the remote PC.
|
||||
|
||||
## Set up multiple computers
|
||||
|
||||
1. Install the v0.6.58 or newer on every participating PC. Input protocol v2 requires all participants to update; earlier one-pair builds cannot connect. Preserve local data; do not copy pairing identities between PCs.
|
||||
2. Open **Settings → Computers → Manage computers…** and enable discovery on both PCs.
|
||||
Only running LAN-enabled KSwitcher instances appear, not generic network devices.
|
||||
The computer list and pairing controls are on the left, the monitor grid and
|
||||
input sharing are on the right, and file, log and help actions are below.
|
||||
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.
|
||||
|
||||
Input first tries TCP in the usual direction, then reverse TCP after 1.5 seconds.
|
||||
If TCP has not authenticated after 5 seconds, the lower-ID peer negotiates an
|
||||
encrypted UDP input session on the existing discovery socket (UDP 45883).
|
||||
UDP uses fresh session challenges, authenticated encryption, ordered event
|
||||
numbers, acknowledgements and bounded retries; duplicated packets do not repeat
|
||||
key presses. Two seconds without authenticated traffic or acknowledgement
|
||||
progress closes the session and returns control locally. A working UDP session
|
||||
stays on UDP until disconnected; it does not oscillate between transports.
|
||||
Both PCs must run an updated build to use all fallback methods. Older peers can
|
||||
still use the original TCP protocol. No extra ports or external relay are used.
|
||||
|
||||
After 15 seconds without a connection, the UI points to **Connection help**.
|
||||
The help window can copy PowerShell commands for the actual resident EXE path,
|
||||
including a path containing apostrophes. Run each PC's own command in an
|
||||
administrator PowerShell on that PC. These commands permit inbound TCP 45884
|
||||
and UDP 45883 only from the local subnet; the program does not execute them.
|
||||
Moving the EXE may require a new application firewall rule. A timeout alone
|
||||
does not establish that the firewall is the cause: check that input sharing is
|
||||
enabled on both PCs and that both are running the intended copy.
|
||||
|
||||
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.
|
||||
@@ -1,35 +1,465 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.4.1 — 2026-10-28
|
||||
## v0.6.112 — 2026-11-17
|
||||
|
||||
- Fix Settings spacing around Screen capture, automatic layout correction and layout controls.
|
||||
- Verify update checksums through .NET SHA-256 without requiring the PowerShell Get-FileHash command. This fixes updates from processes launched with a conflicting PowerShell module environment.
|
||||
- Capture a rectangular screen region with Win+Shift+S (configurable), with dimmed selection and independent editor windows.
|
||||
- Annotate screenshots with numbered markers, arrows, straight/freehand lines, highlights, rectangles, circles, ellipses and inline text.
|
||||
- Edit color, line style, arrowheads, thickness, font and size. Link arrow endpoints to markers and attach captions.
|
||||
- Captions follow line angle and keep their relative offset until manually rotated. Text rotation supports Shift snapping in 15-degree steps.
|
||||
- Move objects one pixel with arrow keys; clone with Ctrl+D; undo/redo edits. Numbered markers reuse gaps.
|
||||
- Compact Lucide toolbar, contextual status bar, pencil cursor and confirmation before discarding an uncopied screenshot. Escape no longer closes the editor.
|
||||
- Preserve the separate on-demand configurator and configurable capture shortcut.
|
||||
In KSwitcher Files, **Ctrl+Shift+Tab** cycles backward through Files, Editor, and Viewer windows. **Ctrl+Tab** cycles forward. Both shortcuts wrap at the ends of the window list, including in the Markdown preview.
|
||||
|
||||
Verified: 173 native checks, 379 input/rendering checks, screenshot editor UI integration checks,
|
||||
29 updater checks, including missing Get-FileHash coverage, and package validation.
|
||||
**Українською.**
|
||||
|
||||
**Upgrade from v0.3.0 or v0.4.0:** use Update in the tray menu. Both executables are supported.
|
||||
If an older updater reports missing `Get-FileHash`, restart KSwitcher normally from Explorer
|
||||
(outside a PowerShell 7 session) or install this ZIP manually once. v0.4.1 removes that dependency.
|
||||
**Upgrade from v0.2.3 or earlier:** install manually once because those updaters reject the additional configurator EXE.
|
||||
Exit KSwitcher and extract the entire ZIP into its installation folder. Keep personal `data/` and customized dictionaries.
|
||||
У KSwitcher Files **Ctrl+Shift+Tab** обходить вікна Files, редактора й переглядача у зворотному порядку. **Ctrl+Tab** обходить їх у прямому порядку. Обидві комбінації працюють циклічно, зокрема в перегляді Markdown.
|
||||
|
||||
Download **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**. The package contains both executables,
|
||||
offline dictionaries, documentation and license notices; no personal settings or clipboard history.
|
||||
## v0.6.111 — 2026-11-17
|
||||
|
||||
Build and package:
|
||||
- KSwitcher Files updates a panel as soon as its background folder scan finishes.
|
||||
- **Ctrl+U** swaps the panels, keeping their folders, view modes, cursors, marked items, and active panel together. Use **Tab** by itself to switch the active panel. **Ctrl+Tab** cycles between Files, Editor, and Viewer windows.
|
||||
- Panels and scrollable Files popups share a Far-style scrollbar with up and down arrows, a dotted track, and a thumb lighter than its background.
|
||||
|
||||
```powershell
|
||||
.\build.ps1 -Stage -Test
|
||||
.\package.ps1 -PublishRelease
|
||||
```
|
||||
**Українською.**
|
||||
|
||||
Commit the archive, checksum and sources together. Publish both assets on a stable release whose
|
||||
tag matches the executable version.
|
||||
- KSwitcher Files оновлює панель одразу після завершення фонового читання папки.
|
||||
- **Ctrl+U** міняє панелі місцями разом із папками, режимами перегляду, курсорами й позначками. Активна панель залишається активною на новому боці. Для перемикання активної панелі натисніть **Tab** без модифікаторів. **Ctrl+Tab** перемикає вікна Files, редактора й переглядача.
|
||||
- Панелі та попапи з прокруткою у Files мають спільний скролбар у стилі Far зі стрілками вгорі й унизу, крапковою доріжкою та повзунком, світлішим за фон.
|
||||
|
||||
## v0.6.110 — 2026-11-17
|
||||
|
||||
Entering a folder or returning to its parent in KSwitcher Files refreshes the affected panel and the command line without repainting the other panel.
|
||||
|
||||
Auto-correction can preserve all uppercase letters when correcting to a word in **My dictionary**. With `qa` in the English personal dictionary and **Minimum word length** set to 2 or lower, typing `ЙФ` and pressing Space yields `QA`.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Під час входу в папку або повернення до батьківської папки KSwitcher Files оновлює потрібну панель і командний рядок. Сусідня панель більше не перемальовується через цей перехід.
|
||||
|
||||
Автокорекція зберігає верхній регістр для слів з **My dictionary**. Якщо в особистому словнику English є `qa`, а **Minimum word length** дорівнює 2 або менше, після пробілу `ЙФ` виправиться на `QA`.
|
||||
|
||||
## v0.6.109 — 2026-11-17
|
||||
|
||||
**Ctrl+0–9** in KSwitcher Files opens the assigned folder or shows only the folders assigned to that digit. **Ctrl+F1** selects Brief and **Ctrl+F2** selects Wide in the active panel. **Ctrl+F3–F12** are reserved for other panel modes. If command history used a Ctrl+function shortcut, set a new binding under **Options → Command line → Command history**.
|
||||
|
||||
**My dictionary** accepts hyphens between letters, for example `test-mt` and `dev-mt`. Enter the correct spelling in the dictionary for its language, then click **OK → Save**. Update all PCs that share settings before syncing hyphenated entries.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У KSwitcher Files **Ctrl+0–9** відкриває призначену папку або показує лише папки, призначені натиснутій цифрі. **Ctrl+F1** вмикає Brief, а **Ctrl+F2** вмикає Wide в активній панелі. **Ctrl+F3–F12** зарезервовані для інших режимів панелей. Якщо історія команд використовувала Ctrl із функціональною клавішею, задайте нову комбінацію в **Options → Command line → Command history**.
|
||||
|
||||
**My dictionary** приймає дефіси між літерами, наприклад `test-mt` і `dev-mt`. Введіть правильне написання у словник відповідної мови й натисніть **OK → Save**. Перед синхронізацією слів із дефісами оновіть усі ПК, які обмінюються налаштуваннями.
|
||||
|
||||
## v0.6.108 — 2026-11-17
|
||||
|
||||
KSwitcher Files adds **Wake** beside the offline status of a paired PC in **Change drive** (Alt+F1 or Alt+F2). Click **Wake** or focus it with the arrow keys and press **Enter**. The status bar reports whether KSwitcher sent the Wake-on-LAN packet.
|
||||
|
||||
Update both PCs and let them discover each other once while the target is online so KSwitcher can save its network adapter’s MAC address. Enable Wake-on-LAN on the target. Ethernet is the most reliable option. Wi-Fi requires compatible Wake on Wireless LAN hardware and drivers.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У KSwitcher Files біля статусу спареного офлайн-ПК у меню **Change drive** (Alt+F1 або Alt+F2) є дія **Wake**. Клацніть **Wake** або виберіть її стрілками й натисніть **Enter**. Рядок стану повідомить, чи вдалося надіслати пакет Wake-on-LAN.
|
||||
|
||||
Оновіть обидва ПК і дайте їм один раз побачити один одного, поки цільовий ПК увімкнено, щоб KSwitcher зберіг MAC-адресу його мережевого адаптера. Увімкніть Wake-on-LAN на цільовому ПК. Найнадійніше підключення через Ethernet. Для Wi-Fi потрібна підтримка Wake on Wireless LAN з боку обладнання й драйвера.
|
||||
|
||||
## v0.6.107 — 2026-11-16
|
||||
|
||||
KSwitcher Files suggests recent commands, PowerShell commands and parameters, and paths as you type. The list works with the panes visible or hidden. Use **Up** or **Down** to select, **Tab** or **Enter** on a selected suggestion to insert it, and **Escape** to close the list. Press **F1** in the command line to open the Microsoft Learn article for a documented Windows command or subcommand.
|
||||
|
||||
The offline Windows command catalog includes nested syntax and documented choices such as `schtasks /query /fo LIST`. After `ipconfig /renew ` or `ipconfig /release `, Files suggests local IPv4 adapters configured for DHCP. With Git for Windows, Git completion includes options and matching branch names. With the .NET SDK, `dotnet` completion delegates to the CLI. The main Files window has a new blue two-pane icon inspired by FAR.
|
||||
|
||||
**Українською.**
|
||||
|
||||
KSwitcher Files підказує недавні команди з історії, команди й параметри PowerShell та шляхи під час набору. Список працює з відкритими й прихованими панелями. Стрілки **↑** і **↓** вибирають підказку, **Tab** або **Enter** на вибраній підказці вставляє її, а **Escape** закриває список. **F1** у командному рядку відкриває статтю Microsoft Learn для документованої команди чи підкоманди Windows.
|
||||
|
||||
Офлайн-каталог команд Windows містить вкладений синтаксис і документовані значення, наприклад `schtasks /query /fo LIST`. Після `ipconfig /renew ` або `ipconfig /release ` Files підказує локальні адаптери з DHCP для IPv4. За наявності Git for Windows підказки Git включають параметри й відповідні назви гілок. За наявності .NET SDK підказки для `dotnet` надає сама утиліта. Головне вікно Files має нову синю іконку з двома панелями в стилі FAR.
|
||||
|
||||
## v0.6.106 — 2026-11-16
|
||||
|
||||
Files scans local and LAN folders and runs copy, move, rename and delete in the background. Copy and Rename/Move validate destinations in the background. A failed operation opens a red Far-style dialog. For local sharing violations, **Processes…** shows possible blockers and **End process** ends the selected process after confirmation. Retry **F6**, **F8**, or **Shift+Delete** after releasing the item.
|
||||
|
||||
The screenshot editor repaints the affected area while dragging. History reuses separate OCR and thumbnail helpers, and Windows OCR scales images to the engine’s size limit. Shortcut and snippet processing does less work on keystrokes, and LAN transfers wait for a timeout before retrying unacknowledged chunks.
|
||||
|
||||
**Write log** defaults to off for new settings. Existing explicit choices still apply. When enabled, diagnostic logs can contain typed or copied text.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Files сканує локальні й LAN-каталоги та виконує копіювання, переміщення, перейменування й видалення у фоні. Copy і Rename/Move перевіряють шлях у фоні. Помилки операцій відкривають червоний діалог у стилі Far. При локальному блокуванні **Processes…** показує можливі процеси, а **End process** завершує вибраний процес після підтвердження. Після звільнення повторіть **F6**, **F8** або **Shift+Delete**.
|
||||
|
||||
Редактор скриншотів перемальовує змінену область під час перетягування. Історія повторно використовує окремі процеси OCR і мініатюр, а Windows OCR масштабує зображення до ліміту рушія. Обробка хоткеїв і сніпетів виконує менше роботи під час набору. LAN-передача повторно надсилає непідтверджені блоки після тайм-ауту.
|
||||
|
||||
**Write log** вимкнено за замовчуванням для нових налаштувань. Явно збережений вибір продовжує діяти. Увімкнений журнал може містити введений або скопійований текст.
|
||||
|
||||
## v0.6.105 — 2026-11-16
|
||||
|
||||
KSwitcher Files gives the Editor a pencil icon and the Viewer an eye icon. The two modes have separate taskbar groups, and **F6** switches the icon and group in the same window. On a PC running KSwitcher as administrator, LAN PowerShell commands such as `dir` now start with standard user rights. This fixes the `0xC0000142` startup failure on that path. This release replaces v0.6.104.
|
||||
|
||||
**Українською.** Редактор KSwitcher Files має іконку олівця, а переглядач — іконку ока. Режими мають окремі групи на панелі завдань Windows, і **F6** перемикає іконку й групу в тому самому вікні. Якщо KSwitcher на ПК-отримувачі запущено від адміністратора, команди PowerShell через LAN, зокрема `dir`, запускаються з правами звичайного користувача. Виправлено помилку запуску `0xC0000142` у цьому сценарії. Цей реліз замінює v0.6.104.
|
||||
|
||||
## v0.6.104 — 2026-11-16
|
||||
|
||||
**Ctrl+F** or the search icon opens search in the rendered KSwitcher Files Markdown preview. Search ignores case and highlights the current match. **Enter** or **F3** moves to the next match, and **Shift+Enter** or **Shift+F3** moves back. **Escape** closes the search first. This release includes the HTML, Markdown appearance, Options and terminal copy updates from v0.6.103.
|
||||
|
||||
**Українською.** **Ctrl+F** або піктограма пошуку відкриває пошук у відрендерованому Markdown у KSwitcher Files. Пошук ігнорує регістр і підсвічує поточний збіг. **Enter** або **F3** переходить до наступного збігу, а **Shift+Enter** або **Shift+F3** повертає до попереднього. **Escape** спочатку закриває пошук. Реліз включає підтримку HTML, налаштування вигляду Markdown, запам’ятовування розділу Options і копіювання з термінала з v0.6.103.
|
||||
|
||||
## v0.6.103 — 2026-11-16
|
||||
|
||||
The KSwitcher Files Markdown preview renders embedded HTML tables and inline styles such as `white-space: nowrap`. **Options → Viewer → Markdown** sets the preview width, font family and font size. Files Options reopens the last section. **Ctrl+C** and **Ctrl+Insert** copy selected terminal output. This release replaces v0.6.102.
|
||||
|
||||
**Українською.** Перегляд Markdown у KSwitcher Files відображає вбудовані HTML-таблиці й стилі, зокрема `white-space: nowrap`. У **Options → Viewer → Markdown** можна задати ширину перегляду, гарнітуру й розмір шрифту. Options відкриває останній відвіданий розділ. **Ctrl+C** і **Ctrl+Insert** копіюють виділений текст із виводу термінала. Цей реліз замінює v0.6.102.
|
||||
|
||||
## v0.6.102 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Ctrl+Insert copies the full command line when it contains text. With an empty command line, it copies names from the active pane. The LAN host returns Windows PowerShell startup errors without waiting for a system error dialog. Files explains DLL initialization failure `0xC0000142` and accepts another command. This release replaces v0.6.101.
|
||||
|
||||
**Українською.** У KSwitcher Files Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок порожній, копіюються імена з активної панелі. ПК, який приймає LAN-команду, повертає помилки запуску Windows PowerShell без очікування системного діалогу. Files пояснює помилку ініціалізації DLL `0xC0000142` і знову приймає команди. Цей реліз замінює v0.6.101.
|
||||
|
||||
## v0.6.101 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Enter opens the selected item when the command line is empty, including when focus is in the terminal output. The Computers window places pairing and the monitor grid side by side so the bottom actions fit at high display scaling. This release replaces v0.6.100.
|
||||
|
||||
**Українською.** У KSwitcher Files Enter відкриває вибраний елемент, коли командний рядок порожній, зокрема коли фокус у виводі термінала. У вікні Computers спарювання та схема моніторів розташовані поруч, тож нижні дії поміщаються і при високому масштабі. Цей реліз замінює v0.6.100.
|
||||
|
||||
## v0.6.100 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Enter and Shift+Enter submit the command line when focus is in the terminal output. The terminal scrolls to the latest output when a command is submitted. While a LAN command is still running, Files shows how to cancel it and keeps the next command in the input field. This release replaces v0.6.99.
|
||||
|
||||
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують введену команду, коли фокус у виводі термінала. Під час запуску команди термінал прокручується до останнього виводу. Поки виконується LAN-команда, Files показує, як її скасувати, і зберігає наступну команду в полі вводу. Цей реліз замінює v0.6.99.
|
||||
|
||||
## v0.6.99 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Enter and Shift+Enter run the command in the command line, including when the file panes are hidden. With visible panes and an empty command line, the keys act on the selected item. A command reveals the terminal output if it was hidden. This release replaces v0.6.98.
|
||||
|
||||
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують команду з командного рядка, зокрема коли файлові панелі приховані. Коли панелі видимі й рядок порожній, клавіші діють на вибраний елемент. Якщо вивід термінала приховано, команда відкриває його. Цей реліз замінює v0.6.98.
|
||||
|
||||
## v0.6.98 — 2026-11-16
|
||||
|
||||
In Files, Enter opens folders in the current pane, uses the Windows default action for local files, and runs BAT and CMD in the embedded terminal. Shift+Enter opens local folders in File Explorer and passes files, including BAT and CMD, to Windows. It preserves the draft command. Left and Right clear the previous cursor highlight when jumping to the first or last row. The FAR-style key bar uses gray key labels on black and dark action names on teal.
|
||||
|
||||
**Українською.** У Files Enter відкриває папки в поточній панелі, викликає стандартну дію Windows для локальних файлів, а BAT і CMD запускає у вбудованому терміналі. Shift+Enter відкриває локальні папки у Провіднику й передає файли, зокрема BAT і CMD, Windows. Чернетка команди зберігається. Стрілки вліво й вправо скидають старе підсвічування при переході до першого чи останнього рядка. Нижній рядок клавіш у стилі FAR має сірі позначення клавіш на чорному тлі й темні назви дій на бірюзовому.
|
||||
|
||||
## v0.6.97 — 2026-11-16
|
||||
|
||||
KSwitcher Files clears the highlight from the previous cursor row after a selection change and highlights the new row. It keeps the targeted repaint introduced in v0.6.96. This release replaces v0.6.96.
|
||||
|
||||
**Українською.** KSwitcher Files знімає підсвічування з попереднього рядка курсора після зміни вибору й виділяє новий рядок. Панель і далі перемальовує лише потрібні рядки. Цей реліз замінює v0.6.96.
|
||||
|
||||
## v0.6.96 — 2026-11-16
|
||||
|
||||
Clicking a file row in Files now redraws only the affected cursor rows, including when switching panes. The key bar adds **F8 Delete**, which opens the same confirmation as pressing F8.
|
||||
|
||||
**Українською.** Клік по рядку у Files перемальовує лише рядки курсора, зокрема при переході на іншу панель. У нижньому рядку клавіш є **F8 Delete**, що відкриває той самий діалог підтвердження, що й клавіша F8.
|
||||
|
||||
## v0.6.95 — 2026-11-16
|
||||
|
||||
Files shows Markdown after rendering completes, refreshes local previews when the file changes on disk, and opens internal links in the same window. Shift+click opens a separate window. The arrow controls, mouse side buttons and Alt+Left/Right navigate history. Ctrl+W closes the viewer. Ctrl+Tab cycles through Files and its open editors and viewers. Up and Down wrap in Files menus and drop-downs. Manual and LAN updates close Files, editors, Settings and bundled StayHere from the target installation before replacing its files. Save open work before updating. When installing this release with an older updater, close Files and its separate windows first. This release replaces v0.6.94.
|
||||
|
||||
**Українською.** Files показує Markdown після рендерингу й автоматично оновлює локальний перегляд після змін на диску. Внутрішні посилання відкриваються в тому самому вікні, Shift+клік — в окремому. Історією керують стрілки перегляду, бічні кнопки миші та Alt+←/→. Ctrl+W закриває перегляд. Ctrl+Tab циклічно перемикає Files та відкриті редактори й переглядачі. Стрілки вгору й вниз циклічно проходять меню та розкривні списки. Ручне оновлення й оновлення через LAN закривають Files, редактори, Settings і вбудований StayHere цільової інсталяції перед заміною файлів. Збережіть відкриті правки перед оновленням. Якщо цей реліз встановлює старий оновлювач, спочатку закрийте Files та його окремі вікна. Цей реліз замінює v0.6.94.
|
||||
|
||||
## v0.6.94 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, F3 renders Markdown with offline Mermaid diagrams, tables, and interactive task lists. Relative links and images work for local and LAN documents. Checkbox changes last for the current preview. F4 opens the syntax-highlighted text editor and F6 switches between View and Edit in the same window, prompting before leaving unsaved edits.
|
||||
|
||||
**Українською.** У KSwitcher Files клавіша F3 відкриває форматований Markdown із діаграмами Mermaid, таблицями та інтерактивними списками завдань. Mermaid працює офлайн. Відносні посилання й зображення працюють для локальних і LAN-файлів. Відмітки чекбоксів діють у поточному сеансі перегляду. F4 відкриває редактор із підсвічуванням синтаксису, а F6 перемикає перегляд і редагування в тому самому вікні. Якщо є незбережені зміни, Files пропонує їх зберегти.
|
||||
|
||||
## v0.6.93 — 2026-11-16
|
||||
|
||||
In Files, Ctrl+R refreshes the active pane as in FAR Manager. The menu and key bar show Ctrl+R. F2 also refreshes the pane. Refresh preserves marks and the cursor where possible, and clears folder sizes calculated with F3.
|
||||
|
||||
**Українською.** У Files Ctrl+R перечитує активну панель, як у FAR Manager. Комбінація показана в меню та рядку клавіш. F2 також перечитує панель. Перечитування зберігає позначки й курсор для наявних елементів і скидає розміри папок, підраховані через F3.
|
||||
|
||||
## v0.6.92 — 2026-11-16
|
||||
|
||||
In Files, F3 on a folder measures file sizes throughout the directory tree. If folders are marked, Files measures each marked folder separately. Results appear in the Size column in Wide mode. F3 on a file opens the viewer even when folders are marked. Folder sizing runs in the background and supports LAN panes.
|
||||
|
||||
**Українською.** У Files F3 на папці підраховує сумарний розмір файлів у всьому дереві. Якщо позначено папки, Files рахує розмір кожної окремо. Результат з’являється в колонці Size у широкому режимі. F3 на файлі відкриває переглядач, навіть коли позначено папки. Підрахунок виконується у фоні й підтримує LAN-панелі.
|
||||
|
||||
## v0.6.91 — 2026-11-16
|
||||
|
||||
Ctrl+Insert copies the marked file and folder names from the active pane, one per line. Without marks, it copies the name under the cursor. LAN Files retries opening TCP 45885 if the port is busy at startup, and Change drive retries failed drive queries. A remote update request waits for an in-progress update check. The updater identifies and closes companion processes from its installation, including Files running from an update backup, and records confirmed exits in the journal.
|
||||
|
||||
**Українською.** Ctrl+Insert копіює імена позначених файлів і папок активної панелі, по одному на рядок. Якщо позначок немає, копіюється ім’я під курсором. LAN Files повторює відкриття TCP 45885, якщо порт зайнятий під час старту, а Change drive повторює невдалі запити дисків. Запит віддаленого оновлення чекає завершення поточної перевірки. Оновлювач визначає й закриває процеси своєї інсталяції, зокрема Files із резервної папки, і записує підтверджене завершення в журнал.
|
||||
|
||||
## v0.6.90 — 2026-11-16
|
||||
|
||||
Files groups Commands into navigation, viewing and editing, and remote PC actions. The remote group appears in an active LAN pane. Shared notices fit their contents and show a scrollbar only when needed. Remote hibernation and update confirmations use a compact red warning with No focused by default.
|
||||
|
||||
**Українською.** Меню Commands у Files групує навігацію, перегляд і редагування та дії для віддаленого ПК. Віддалена група доступна в активній LAN-панелі. Спільні повідомлення підлаштовуються під вміст і показують прокрутку лише за потреби. Гібернація та віддалене оновлення використовують компактне червоне підтвердження з фокусом на No.
|
||||
|
||||
## v0.6.89 — 2026-11-16
|
||||
|
||||
In Files, Commands now offers **Hibernate remote PC** and **Update remote KSwitcher** for the active LAN pane. The target PC has separate, default-off permissions for each action. Unattended updates verify the stable package, close the target installation's Files, Config and screenshot windows, and restart KSwitcher. Forced closure discards unsaved changes. The target journal records closed processes and the update result.
|
||||
|
||||
**Українською.** У меню Commands з’явилися **Hibernate remote PC** і **Update remote KSwitcher** для активної LAN-панелі. На цільовому ПК кожна дія має окремий дозвіл, вимкнений за замовчуванням. Оновлювач перевіряє стабільний пакет, без запитань закриває Files, Config і редактори скриншотів цієї інсталяції та перезапускає KSwitcher. Примусове закриття відкидає незбережені зміни. Журнал цільового ПК фіксує закриті процеси й результат оновлення.
|
||||
|
||||
## v0.6.88 — 2026-11-16
|
||||
|
||||
In Files, Ctrl+Enter inserts the name of the file or folder under the active pane cursor into the command line. An open Files window can still request the LAN peer list after KSwitcher updates and restarts.
|
||||
|
||||
**Українською.** У Files Ctrl+Enter вставляє в командний рядок назву файла або папки під курсором активної панелі. Відкрите вікно Files і далі може отримувати список LAN-комп’ютерів після оновлення та автоматичного перезапуску KSwitcher.
|
||||
|
||||
|
||||
## v0.6.87 — 2026-11-15
|
||||
|
||||
Remote PowerShell in Files now displays errors as text and hides progress metadata. Update the PC that runs the commands to remove raw CLIXML from terminal output. This release supersedes v0.6.86.
|
||||
|
||||
**Українською.** Віддалений PowerShell у Files тепер показує помилки як текст і приховує службові повідомлення прогресу. Щоб прибрати сирий CLIXML із термінала, оновіть ПК, який виконує команди. Цей реліз замінює v0.6.86.
|
||||
|
||||
## v0.6.86 — 2026-11-15
|
||||
|
||||
The Files editor applies its palette before the text area appears. In a LAN pane, enter a PowerShell command to run it in that pane’s directory on the paired PC. The Files terminal displays output and the exit code. On the remote PC, enable **Allow paired PCs to run PowerShell commands here** in **Files → Options → Command line → Command history**. Both PCs need v0.6.86 or later.
|
||||
|
||||
**Українською.** Редактор Files застосовує палітру до появи текстового поля. У панелі LAN введена команда PowerShell виконується в каталозі цієї панелі на спареному ПК. Термінал Files показує вивід і код завершення. На віддаленому ПК увімкніть **Allow paired PCs to run PowerShell commands here** у **Files → Options → Command line → Command history**. На обох ПК потрібен v0.6.86 або новіший.
|
||||
|
||||
## v0.6.85 — 2026-11-15
|
||||
|
||||
Files viewer and editor windows now run independently with separate Windows taskbar buttons. Reopening a file offers to switch to its existing window. F3 and F4 work in LAN panes. The editor downloads files in the background and checks the remote file before replacing it on save. Update KSwitcher on the remote PC for writeback.
|
||||
|
||||
**Українською.** Переглядач і редактор Files працюють в окремих вікнах із власними кнопками на панелі завдань Windows. При повторному відкритті Files пропонує перейти до наявного вікна. F3 і F4 працюють у панелях LAN. Редактор завантажує файл у фоні та перевіряє віддалений файл перед записом. Для збереження оновіть KSwitcher також на віддаленому ПК.
|
||||
|
||||
## v0.6.84 — 2026-11-15
|
||||
|
||||
KSwitcher Files adds an internal viewer on F3 and editor on F4 with syntax highlighting, paged access to large text files, and shared search history. Alt+F3 and Alt+F4 open external applications. Files Options now includes viewer and editor settings, including tab width and the FAR (blue) color scheme. F7 creates folders and directory links, supports multiple names, and remembers successful inputs. Far-style dialogs share focus, resizing and keyboard behavior.
|
||||
|
||||
**Українською.** У KSwitcher Files з’явилися вбудований переглядач по F3 і редактор по F4 з підсвічуванням синтаксису, посторінковою роботою з великими текстовими файлами та спільною історією пошуку. Alt+F3 і Alt+F4 відкривають зовнішні програми. Спільні Options містять параметри переглядача й редактора, зокрема ширину табуляції та схему FAR (blue). F7 створює папки й посилання на каталоги, підтримує кілька імен і запам’ятовує успішні введення. Модальні діалоги Far мають спільну поведінку фокуса, зміни розміру й клавіатурної навігації.
|
||||
|
||||
## v0.6.83 — 2026-11-15
|
||||
|
||||
In KSwitcher Files, the command line keeps keyboard focus while Tab switches panes and Up, Down, Page Up, and Page Down move the active pane's cursor. Ctrl+F inserts the full path under the cursor, using double quotes only for paths with spaces. Ctrl+C copies the entire command line. Alt plus a character starts a filename or folder search. After the first match, type without Alt in the Search popup at the bottom of the active pane. F9 opens the menu.
|
||||
|
||||
**Українською.** У KSwitcher Files клавіатурний фокус залишається в командному рядку. Tab перемикає панелі, а стрілки вгору й вниз, Page Up і Page Down пересувають курсор активної панелі. Ctrl+F вставляє повний шлях під курсором і додає подвійні лапки лише до шляхів із пробілами. Ctrl+C копіює весь командний рядок. Alt із символом починає пошук файлу чи папки за назвою. Після першого збігу уточнюйте запит без Alt у полі Search внизу активної панелі. F9 відкриває меню.
|
||||
|
||||
## v0.6.82 — 2026-11-14
|
||||
|
||||
Enter and double-click open folders in the current pane, open local documents with their Windows default apps, and launch EXE files in separate processes. BAT and CMD files run in the existing embedded PowerShell session, and their output appears below the panes. Both local panes refresh when files are created, modified, or deleted externally and preserve focus.
|
||||
|
||||
**Українською.** Enter і подвійний клік відкривають папки в поточній панелі та локальні документи у стандартних програмах Windows. EXE запускаються окремими процесами, а BAT і CMD виконуються в поточній сесії вбудованого PowerShell із виводом під панелями. Обидві локальні панелі підхоплюють створення, зміну й видалення файлів ззовні та зберігають фокус.
|
||||
|
||||
## v0.6.81 — 2026-11-14
|
||||
|
||||
Ctrl+8 lists all folder shortcuts. Press Enter to open a folder, F4 to edit the shortcut, or Delete to remove it. Ctrl+Alt+F brings an open Files window forward.
|
||||
|
||||
**Українською.** Ctrl+8 показує всі ярлики папок. Enter відкриває папку, F4 редагує ярлик, Delete видаляє його. Ctrl+Alt+F повертає до відкритого вікна Files.
|
||||
|
||||
## v0.6.80 — 2026-11-14
|
||||
|
||||
Includes the Files updates from v0.6.79. Change drive now explains why the local peer lookup failed and shows No paired computers only when the response is empty.
|
||||
|
||||
**Українською.** Випуск включає зміни Files із v0.6.79. Change drive показує конкретну причину збою запиту пар. No paired computers з’являється лише після успішної порожньої відповіді.
|
||||
|
||||
## v0.6.79 — 2026-11-14
|
||||
|
||||
In KSwitcher Files, changing directory in PowerShell updates the panel
|
||||
that sent the command. The global Files shortcut brings an open window to
|
||||
the foreground. Change drive redraws its frame when LAN drives arrive and
|
||||
shows a short timeout message. Files writes LAN lookup errors to its own log.
|
||||
|
||||
**Українською.** Зміна каталогу в PowerShell оновлює панель, з якої
|
||||
надіслано команду. Глобальна клавіша Files повертає до відкритого вікна.
|
||||
Change drive перемальовує рамку після появи LAN-дисків і показує коротке
|
||||
повідомлення про тайм-аут. Files записує помилки LAN у власний журнал.
|
||||
|
||||
## v0.6.78 — 2026-11-14
|
||||
|
||||
The Windows package includes KSwitcher Files, a two-panel file manager with
|
||||
local and paired LAN drives, folder shortcuts, an embedded PowerShell terminal,
|
||||
and searchable command history. Applied Files settings update other open
|
||||
instances immediately.
|
||||
|
||||
**Українською.** До пакета для Windows входить KSwitcher Files, двопанельний
|
||||
файловий менеджер із локальними дисками й дисками спарених ПК, ярликами папок,
|
||||
вбудованим PowerShell та пошуком в історії команд. Застосовані налаштування
|
||||
Files одразу підхоплюють інші відкриті вікна.
|
||||
|
||||
## v0.6.77 — 2026-11-13
|
||||
|
||||
The screenshot editor remembers the local pencil smoothing default across
|
||||
restarts. Adjust the slider with no pencil stroke selected, or use **Apply to
|
||||
all**, to save the value for new strokes. Adjusting a selected stroke changes
|
||||
only that stroke.
|
||||
|
||||
**Українською.** Редактор скріншотів зберігає типове згладжування олівця на
|
||||
цьому ПК та відновлює його після перезапуску. Змініть повзунок без виділеного
|
||||
штриха олівця або натисніть **Apply to all**, щоб запам’ятати значення для
|
||||
нових штрихів. Зміна виділеного штриха впливає лише на нього.
|
||||
|
||||
## v0.6.76 — 2026-11-13
|
||||
|
||||
Incoming LAN files suggest their original filename when saved. KSwitcher shows
|
||||
a Windows tray notification when a file is ready to save, and the tray tooltip
|
||||
shows the pending count.
|
||||
|
||||
**Українською.** Під час збереження вхідного LAN-файлу пропонується його
|
||||
оригінальна назва. KSwitcher показує сповіщення в треї, коли файл готовий
|
||||
до збереження. Підказка іконки показує кількість файлів у черзі.
|
||||
|
||||
## v0.6.75 — 2026-11-13
|
||||
|
||||
Conversion cancels earlier when input changes and skips restoring an untouched
|
||||
clipboard. Diagnostic records identify the active conversion behind `busy`,
|
||||
separate clipboard and paste verification timings, and retain a text-free
|
||||
summary of verified pastes that take at least two seconds. MCP log reads
|
||||
support `offset` to page backward.
|
||||
|
||||
**Українською.** Конвертація раніше скасовується після зміни вводу й пропускає
|
||||
відновлення буфера, якщо його не змінювала. Діагностика показує активну спробу
|
||||
для `busy`, окремий час роботи з буфером і перевірки вставки, а також зберігає
|
||||
підсумок перевірених вставок від двох секунд без скопійованого тексту. У MCP
|
||||
параметр `offset` дає змогу читати старіші рядки.
|
||||
|
||||
Explicit replacements now accept digits and internal apostrophes in the source word, for example нав1язав=навʼязав. Invalid entries identify the offending pair.
|
||||
|
||||
**Українською.** Явні заміни підтримують цифри й внутрішні апострофи у вихідному слові, наприклад нав1язав=навʼязав. Повідомлення про помилку показує проблемну пару.
|
||||
|
||||
## v0.6.74 — 2026-11-13
|
||||
|
||||
- Send files up to 16 MiB to a selected paired PC over encrypted LAN. Save or discard them from **Incoming files**.
|
||||
- Download current and previous diagnostic logs from paired PCs that explicitly allow remote log downloads.
|
||||
- Copy the Codex configuration from **Settings → MCP**. The MCP server lists paired PCs and reads local or remote diagnostic logs.
|
||||
- Search contacts in the **Languages for a chat** table. **Copy selected** in Diagnostics now uses normal clipboard synchronization.
|
||||
|
||||
**Українською.** Передавайте файли до 16 МіБ вибраному спареному ПК зашифрованою локальною мережею. У **Incoming files** можна зберегти або відхилити файл. Поточний і попередній журнали доступні для завантаження після ввімкнення відповідного дозволу на віддаленому ПК. У **Settings → MCP** можна скопіювати конфігурацію Codex для читання локальних і віддалених журналів. У таблиці **Languages for a chat** додано пошук контактів, а **Copy selected** у діагностиці тепер проходить через звичайну синхронізацію буфера.
|
||||
|
||||
## v0.6.73 — 2026-11-13
|
||||
|
||||
After moving KSwitcher, launch it from its current folder. If Windows autostart
|
||||
still points to the old location, KSwitcher updates the path automatically when
|
||||
the previous executable is missing and the process has sufficient rights. If
|
||||
the previous copy may still be in use or the repair needs administrator approval,
|
||||
choose **Update autostart path** and confirm UAC if prompted. To check again,
|
||||
click **Save** in Settings without changing the autostart options.
|
||||
|
||||
**Українською.** Після перенесення KSwitcher запустіть його з нової папки.
|
||||
Якщо автозапуск і далі вказує на старий шлях, KSwitcher виправить його
|
||||
автоматично, коли старий файл відсутній і прав достатньо. Якщо стара копія
|
||||
ще може використовуватися або потрібні права адміністратора, натисніть
|
||||
**Update autostart path** і підтвердьте UAC, якщо з’явиться запит. Для повторної
|
||||
перевірки натисніть **Save** у налаштуваннях без зміни параметрів автозапуску.
|
||||
|
||||
## v0.6.72 — 2026-11-12
|
||||
|
||||
Edit snippets directly in **Settings → Snippets**. **Save snippets** applies
|
||||
snippet edits independently of the settings draft. Find OCR options in
|
||||
**Clipboard** and open backup and synchronization, paired computers, and
|
||||
logging from **Sync**, **Computers**, and **Diagnostics**, respectively.
|
||||
|
||||
**Українською.** Редагуйте сніпети безпосередньо у **Settings → Snippets**.
|
||||
Кнопка **Save snippets** зберігає їх окремо від чернетки налаштувань.
|
||||
Параметри OCR тепер у **Clipboard**. Для синхронізації, спарених ПК та
|
||||
журналу є вкладки **Sync**, **Computers** і **Diagnostics**.
|
||||
|
||||
## v0.6.71 — 2026-11-12
|
||||
|
||||
After navigating snippet suggestions with **↑ / ↓**, press **Enter** to
|
||||
insert the selected snippet and close the list. The editor does not receive
|
||||
that keypress. If you have not navigated the list, **Enter** still goes to
|
||||
the editor. **Tab** and mouse selection also work.
|
||||
|
||||
KSwitcher skips suggestions when VS Code's EditContext supplies the bounds
|
||||
of the whole line in place of the text caret. See the [FAQ](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/FAQ)
|
||||
for the VS Code workaround.
|
||||
|
||||
**Українською.** Після вибору підказки клавішами **↑ / ↓** натисніть
|
||||
**Enter**, щоб вставити сніпет і закрити список. Редактор не отримує це
|
||||
натискання. Якщо ви не переміщалися списком, **Enter** і далі надходить
|
||||
до редактора. Також можна вибрати сніпет через **Tab** або мишею.
|
||||
|
||||
KSwitcher приховує підказки, коли EditContext у VS Code повертає координати
|
||||
всього рядка замість текстового курсора. Обхідний шлях описано у [FAQ українською](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/FAQ-uk).
|
||||
|
||||
## v0.6.70 — 2026-11-12
|
||||
|
||||
Snippet suggestions are anchored to the text caret. KSwitcher uses the
|
||||
editor's caret location or text accessibility information, including for
|
||||
thin carets and wrapped text. If the editor provides no caret position,
|
||||
the list stays hidden. Full triggers continue to expand automatically.
|
||||
|
||||
**Українською.** Підказки сніпетів прив’язані до текстового курсора.
|
||||
KSwitcher використовує координати курсора або дані доступності редактора,
|
||||
зокрема для тонкого курсора й перенесених рядків. Якщо редактор не надає
|
||||
позицію текстового курсора, список не відкривається. Повні тригери й далі
|
||||
спрацьовують автоматично.
|
||||
|
||||
## v0.6.69 — 2026-11-12
|
||||
|
||||
Snippet autocomplete opens beside the text caret as soon as you type `;` at
|
||||
the start of a trigger. Other triggers offer suggestions after three
|
||||
characters. The list stays open while you type, resizes to fit the matching
|
||||
triggers, and respects application restrictions. Use **↑ / ↓** and **Tab** or
|
||||
click a suggestion to insert it. Press **Esc** to dismiss the list. Full
|
||||
triggers still expand automatically.
|
||||
|
||||
**Українською.** Автодоповнення сніпетів відкривається біля текстового курсора,
|
||||
щойно ви вводите `;` на початку тригера. Для інших тригерів підказки
|
||||
з’являються після трьох символів. Список залишається відкритим під час набору,
|
||||
підлаштовує ширину під відповідні тригери й враховує обмеження за програмами.
|
||||
Виберіть сніпет клавішами **↑ / ↓** і **Tab** або мишею. **Esc** закриває
|
||||
список. Повні тригери й далі спрацьовують автоматично.
|
||||
|
||||
## v0.6.68 — 2026-11-12
|
||||
|
||||
With **Start with Windows** and **Start with Windows as administrator** enabled,
|
||||
opening the regular KSwitcher after exiting a development build requests
|
||||
administrator approval when needed. UAC prompts on the secure desktop still
|
||||
require local input.
|
||||
|
||||
**Українською.** Якщо ввімкнено **Start with Windows** і **Start with Windows as administrator**,
|
||||
звичайний KSwitcher після закриття dev-збірки за потреби запитує запуск від
|
||||
адміністратора. Запити UAC на захищеному робочому столі підтверджуйте
|
||||
безпосередньо на цьому ПК.
|
||||
|
||||
## v0.6.67 — 2026-11-12
|
||||
|
||||
Mouse buttons and wheel actions now use the profiles on the PC receiving
|
||||
input through KSwitcher Computers or Mouse Without Borders. Update the
|
||||
receiving PC and configure its actions in **Settings → Mouse**.
|
||||
|
||||
**Українською.** Кнопки й коліщатко тепер працюють за профілями ПК,
|
||||
який отримує ввід через KSwitcher Computers або Mouse Without Borders.
|
||||
Оновіть цей ПК і налаштуйте дії в **Settings → Mouse**.
|
||||
|
||||
## v0.6.66 — 2026-11-12
|
||||
|
||||
If Windows rejects registration of the notification-area icon at sign-in or
|
||||
after Explorer restarts, KSwitcher retries about once a second until the
|
||||
icon is registered. Settings become accessible from the icon without
|
||||
restarting KSwitcher.
|
||||
|
||||
**Українською.** Якщо Windows не приймає значок KSwitcher в області
|
||||
сповіщень під час входу або після перезапуску Провідника, KSwitcher
|
||||
повторює спробу приблизно щосекунди. Коли значок з’явиться, з нього
|
||||
можна відкрити налаштування без перезапуску KSwitcher.
|
||||
|
||||
## v0.6.65 — 2026-11-12
|
||||
|
||||
Use **Settings → Mouse → +** beside **Mouse events** to capture and name a
|
||||
vertical or horizontal wheel direction. Capturing a known button or an
|
||||
already registered direction selects its existing row. A new signal is
|
||||
accepted only when Windows delivers it through both the test and runtime
|
||||
input paths. A configured wheel action replaces scrolling for that direction
|
||||
where the profile applies.
|
||||
|
||||
OpenBao now backs up all KSwitcher Settings, including mouse events, bindings,
|
||||
application profiles, startup, clipboard history limits, and OCR preferences.
|
||||
Update all clients that share a server profile before syncing. Downloading an
|
||||
older backup preserves local settings for fields it never included. After
|
||||
reinstalling Windows, reconnect to OpenBao and choose **Download remote**.
|
||||
Executable paths and optional OCR software must still be available on the
|
||||
restored PC. Clipboard contents and Windows credentials stay on the device.
|
||||
|
||||
**Українською.** У **Settings → Mouse** натисни **+** біля **Mouse events**,
|
||||
щоб додати напрямок прокручування. Відомий сигнал виділить наявний рядок.
|
||||
OpenBao тепер зберігає всі налаштування KSwitcher, зокрема профілі миші,
|
||||
OCR й автозапуск. Перед синхронізацією онови всі клієнти спільного профілю.
|
||||
Після перевстановлення Windows підключись до OpenBao й натисни
|
||||
**Download remote**.
|
||||
|
||||
## v0.6.64 — 2026-11-12
|
||||
|
||||
The new **Settings → Mouse** tab lets you assign actions to mouse buttons and supported double-clicks. Use **Global** for fallback actions and create profiles for one or more applications. Edit a profile with a double-click, and enable or disable it with the **Active** checkbox. Choose applications by pointing at a window or opening an executable or shortcut.
|
||||
|
||||
Actions include keyboard combinations, browser navigation, launching applications, and system volume. Volume actions have a configurable step and an on-screen indicator. When Windows reports separate press and release events, holding the button repeats the volume change at increasing speed.
|
||||
|
||||
Use **Test mouse buttons here** to check which events Windows delivers. Mouse profiles are stored on the current PC. The configurator also keeps fixed-size settings dialogs fitted when moving them between displays with different scaling.
|
||||
|
||||
## Upgrade
|
||||
|
||||
Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
|
||||
|
||||
For a manual upgrade, exit KSwitcher and its configurator and screenshot editors, then extract the entire **KSwitcher-win-x64.zip** into its installation folder. Verify it with **SHA256SUMS.txt**. Keep personal data, customized dictionaries and tools. Keep the three KSwitcher executables together.
|
||||
|
||||
See the [English Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home) or [Українська Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk).
|
||||
@@ -1 +1 @@
|
||||
7f0ee55eb5b56a6227431c1951ac2751208d3d0c7c34e4d1d616e180c37b1d9f KSwitcher-win-x64.zip
|
||||
8ac71477b90b4a8893c43e000d77d53df57db63c07f0d4784820c5563b106218 KSwitcher-win-x64.zip
|
||||
@@ -0,0 +1,166 @@
|
||||
{
|
||||
"version": "0.6.112",
|
||||
"schema": 1,
|
||||
"files": [
|
||||
{
|
||||
"sha256": "53c3f9aeca02136acbd2ec3c187ee858cb5f60a2f1bf5641ee264e062f73653f",
|
||||
"path": "KSwitcher.exe",
|
||||
"size": 2479104
|
||||
},
|
||||
{
|
||||
"sha256": "c4dbd247e48fd1d37744d280c2fd948c3355eb3507324ae79adc0dcd24ef5469",
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"size": 2458112
|
||||
},
|
||||
{
|
||||
"sha256": "30e8dbe575b3705ae379fda30174e0a486ef5605ec582dd81e01b121180c127b",
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"size": 3060224
|
||||
},
|
||||
{
|
||||
"sha256": "b45ff37c0f279dcf142606c282b73cf3403cb026c4800beea216fd532bc5993f",
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"size": 4214272
|
||||
},
|
||||
{
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"path": "WebView2Loader.dll",
|
||||
"size": 194912
|
||||
},
|
||||
{
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"size": 1103
|
||||
},
|
||||
{
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"path": "terminal/addon-fit.js",
|
||||
"size": 1521
|
||||
},
|
||||
{
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"path": "terminal/index.html",
|
||||
"size": 527
|
||||
},
|
||||
{
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"size": 1073
|
||||
},
|
||||
{
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"path": "terminal/markdown-it.js",
|
||||
"size": 100786
|
||||
},
|
||||
{
|
||||
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c",
|
||||
"path": "terminal/markdown.html",
|
||||
"size": 3530
|
||||
},
|
||||
{
|
||||
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763",
|
||||
"path": "terminal/markdown.js",
|
||||
"size": 15014
|
||||
},
|
||||
{
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"size": 1089
|
||||
},
|
||||
{
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"path": "terminal/mermaid.js",
|
||||
"size": 5537838
|
||||
},
|
||||
{
|
||||
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a",
|
||||
"path": "terminal/terminal.js",
|
||||
"size": 5033
|
||||
},
|
||||
{
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"size": 1261
|
||||
},
|
||||
{
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"path": "terminal/xterm.css",
|
||||
"size": 7112
|
||||
},
|
||||
{
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"path": "terminal/xterm.js",
|
||||
"size": 488663
|
||||
},
|
||||
{
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"path": "LICENSE",
|
||||
"size": 4401
|
||||
},
|
||||
{
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"path": "json-LICENSE.txt",
|
||||
"size": 1096
|
||||
},
|
||||
{
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"path": "files-text-license.txt",
|
||||
"size": 883
|
||||
},
|
||||
{
|
||||
"sha256": "fcbd14b6190dc2a3575a4bc4be7229540c647022cb038d33ec4ac22176c67a9e",
|
||||
"path": "README.md",
|
||||
"size": 95289
|
||||
},
|
||||
{
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"size": 11577
|
||||
},
|
||||
{
|
||||
"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": "f1cd3477fc3e64ed26986b86d85472ca0780963b225231ab575489d4fa82e01b",
|
||||
"path": "tools/StayHere.exe",
|
||||
"size": 133120
|
||||
},
|
||||
{
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"path": "tools/StayHere-README.md",
|
||||
"size": 2796
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
param([switch]$Test, [switch]$Integration, [switch]$Ocr, [switch]$Stage)
|
||||
param([switch]$Test, [switch]$Integration, [switch]$Ocr, [switch]$Stage, [switch]$Far)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = $PSScriptRoot
|
||||
$compiler = Join-Path $root '.tools\w64devkit\bin\g++.exe'
|
||||
@@ -10,11 +10,19 @@ $outDir = Join-Path $root 'build'
|
||||
New-Item -ItemType Directory -Force $outDir | Out-Null
|
||||
$executablePath = if ($Stage) { Join-Path $outDir 'staged\KSwitcher.exe' } else { Join-Path $outDir 'KSwitcher.exe' }
|
||||
New-Item -ItemType Directory -Force (Split-Path $executablePath) | Out-Null
|
||||
Set-Content -LiteralPath (Join-Path $outDir '.local-dev') -Value 'Local development build' -Encoding ascii
|
||||
Set-Content -LiteralPath (Join-Path (Split-Path $executablePath) '.local-dev') -Value 'Local development build' -Encoding ascii
|
||||
Push-Location $root
|
||||
try {
|
||||
$common = @('-std=c++20','-Os','-DNDEBUG','-DUNICODE','-D_UNICODE','-DWIN32_LEAN_AND_MEAN','-DNOMINMAX','-D_WIN32_WINNT=0x0A00','-Wall','-Wextra','-Wno-missing-field-initializers','-Isrc','-Ivendor','-ffunction-sections','-fdata-sections')
|
||||
$libs = @('-luser32','-lshell32','-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','app','ui','main','configuration','config_main')) {
|
||||
$libs = @('-lws2_32','-lbcrypt','-liphlpapi','-lwinhttp','-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore')
|
||||
$utilityDirectory = Join-Path (Split-Path $executablePath) 'tools'
|
||||
New-Item -ItemType Directory -Force $utilityDirectory,build/release/tools | Out-Null
|
||||
$stayHere = Join-Path $utilityDirectory 'StayHere.exe'
|
||||
& $compiler @common -Werror -mwindows -municode -static -s utilities/StayHere/main.cpp -luser32 -lshell32 -lgdi32 -lwtsapi32 -o $stayHere
|
||||
if ($LASTEXITCODE) { throw 'StayHere build failed' }
|
||||
Copy-Item -LiteralPath $stayHere -Destination build/release/tools/StayHere.exe -Force
|
||||
foreach ($name in @('lan_files','lan_channel','lan_input','lan','lan_pairing','core','platform','autostart','autocorrect','storage','sync','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) {
|
||||
& $compiler @common -c "src/$name.cpp" -o "build/$name.o"
|
||||
if ($LASTEXITCODE) { throw "Compilation failed: $name" }
|
||||
}
|
||||
@@ -24,40 +32,145 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Configurator UI compilation failed' }
|
||||
& windres --codepage=65001 resources/app.rc -O coff -o build/app-res.o
|
||||
if ($LASTEXITCODE) { throw 'Resource compilation failed' }
|
||||
& windres --codepage=65001 -DKS_SCREENSHOT_RESOURCES resources/app.rc -O coff -o build/screenshot-res.o
|
||||
if ($LASTEXITCODE) { throw 'Screenshot resource compilation failed' }
|
||||
New-Item -ItemType Directory -Force build/release | Out-Null
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o @libs -o $executablePath
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o @libs -o $executablePath
|
||||
if ($LASTEXITCODE) { throw 'Link failed' }
|
||||
Copy-Item -LiteralPath $executablePath -Destination build/release/KSwitcher.exe -Force
|
||||
$configPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Config.exe'
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/core.o build/platform.o build/storage.o build/ocr.o build/configuration.o build/config_main.o build/ui-config.o build/app-res.o @libs -o $configPath
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o build/configuration.o build/config_main.o build/ui-config.o build/app-res.o @libs -o $configPath
|
||||
if ($LASTEXITCODE) { throw 'Configurator link failed' }
|
||||
Copy-Item -LiteralPath $configPath -Destination build/release/KSwitcher.Config.exe -Force
|
||||
$screenshotPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Screenshot.exe'
|
||||
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/ocr.o build/screenshot.o build/screenshot_notifications.o build/screenshot_activation.o build/screenshot_main.o build/screenshot-res.o @libs -o $screenshotPath
|
||||
if ($LASTEXITCODE) { throw 'Screenshot link failed' }
|
||||
Copy-Item -LiteralPath $screenshotPath -Destination build/release/KSwitcher.Screenshot.exe -Force
|
||||
$filesPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Files.exe'
|
||||
$filesBuild = Join-Path $outDir 'files-cmake'
|
||||
& cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel
|
||||
if ($LASTEXITCODE) { throw 'File manager configuration failed' }
|
||||
& cmake --build $filesBuild --target KSwitcherFiles --parallel 8
|
||||
if ($LASTEXITCODE) { throw 'File manager build failed' }
|
||||
Copy-Item -LiteralPath (Join-Path $filesBuild 'KSwitcher.Files.exe') -Destination $filesPath -Force
|
||||
& strip $filesPath
|
||||
if ($LASTEXITCODE) { throw 'File manager stripping failed' }
|
||||
& "$root/tools/stage-files-terminal.ps1" -Destination (Split-Path $filesPath) | Out-Null
|
||||
& "$root/tools/stage-files-terminal.ps1" -Destination build/release | Out-Null
|
||||
Copy-Item -LiteralPath $filesPath -Destination build/release/KSwitcher.Files.exe -Force
|
||||
if ($Test) {
|
||||
& $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
|
||||
& cmake --build $filesBuild --target KSwitcherFilesTextTests
|
||||
if ($LASTEXITCODE) { throw 'Files text test build failed' }
|
||||
& (Join-Path $filesBuild 'KSwitcherFilesTextTests.exe')
|
||||
if ($LASTEXITCODE) { throw 'Files text tests failed' }
|
||||
& $compiler @common -Werror tests/settings_merge.cpp build/sync.o build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
|
||||
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_files.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 tests/lan_files.cpp build/lan_files.o build/lan_channel.o build/lan_pairing.o build/core.o build/platform.o @libs -static -s -o build/KSwitcherLanFilesTests.exe
|
||||
if ($LASTEXITCODE) { throw 'LAN file test build failed' }
|
||||
& .\build\KSwitcherLanFilesTests.exe
|
||||
if ($LASTEXITCODE) { throw 'LAN file 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_files.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_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o @libs -static -s -o build/KSwitcherSyncTests.exe
|
||||
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
|
||||
if ($LASTEXITCODE) { throw 'Scroll test build failed' }
|
||||
& .\build\KSwitcherScrollTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Scroll tests failed' }
|
||||
& $compiler @common tests/tests.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o @libs -static -s -o build/KSwitcherTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Test build failed' }
|
||||
& .\build\KSwitcherTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Tests failed' }
|
||||
& $compiler @common tests/input.cpp build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/app.o build/configuration.o build/ui.o build/app-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_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Input test build failed' }
|
||||
& .\build\KSwitcherInputTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Input tests failed' }
|
||||
& $compiler @common tests/screenshot_ui.cpp build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/ocr.o build/richtext.o build/update.o build/app.o build/configuration.o build/ui.o build/app-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_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe
|
||||
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_files.o build/lan_pairing.o build/core.o build/platform.o build/ocr.o build/screenshot-res.o @libs -static -s -o build/KSwitcherScreenshotUITests.exe
|
||||
if ($LASTEXITCODE) { throw 'Screenshot UI test build failed' }
|
||||
& .\build\KSwitcherScreenshotUITests.exe
|
||||
if ($LASTEXITCODE) { throw 'Screenshot UI tests failed' }
|
||||
& .\build\KSwitcherScreenshotUITests.exe --save-only
|
||||
if ($LASTEXITCODE) { throw 'Screenshot save tests failed' }
|
||||
$registrationTest = Join-Path (Split-Path $executablePath) 'KSwitcherRegistrationTests.exe'
|
||||
try {
|
||||
& $compiler @common tests/screenshot_registration.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o @libs -static '-Wl,--gc-sections' -s -o $registrationTest
|
||||
if ($LASTEXITCODE) { throw 'Screenshot registration test build failed' }
|
||||
& $registrationTest
|
||||
if ($LASTEXITCODE) { throw 'Screenshot registration tests failed' }
|
||||
} finally { Remove-Item -LiteralPath $registrationTest -ErrorAction SilentlyContinue }
|
||||
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File tests/update.ps1 -Executable $executablePath
|
||||
if ($LASTEXITCODE) { throw 'Updater tests failed' }
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File tests/update_progress.ps1
|
||||
if ($LASTEXITCODE) { throw 'Updater progress UI tests failed' }
|
||||
}
|
||||
if ($Far) {
|
||||
& $compiler @common tests/far_snippets.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -mwindows -municode -static -s -o build/KSwitcherFarSnippetTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Far snippet test build failed' }
|
||||
$fixture = Start-Process -FilePath (Join-Path $outDir 'KSwitcherFarSnippetTests.exe') -WindowStyle Hidden -Wait -PassThru
|
||||
Get-Content -LiteralPath (Join-Path $outDir 'far-snippets.log')
|
||||
if ($fixture.ExitCode) { throw 'Far snippet tests failed' }
|
||||
}
|
||||
if ($Integration) {
|
||||
& $compiler @common tests/integration.cpp build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/app.o build/configuration.o build/ui.o build/app-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_files.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_files.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_files.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_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherIntegration.exe
|
||||
if ($LASTEXITCODE) { throw 'Integration test build failed' }
|
||||
& .\build\KSwitcherIntegration.exe
|
||||
if ($LASTEXITCODE) { throw 'Integration tests failed' }
|
||||
}
|
||||
if ($Ocr) {
|
||||
& $compiler @common tests/ocr.cpp build/core.o build/platform.o build/ocr.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_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o $ocrTest
|
||||
if ($LASTEXITCODE) { throw 'OCR test build failed' }
|
||||
& .\build\KSwitcherOcrTests.exe
|
||||
& $ocrTest
|
||||
if ($LASTEXITCODE) { throw 'OCR tests failed' }
|
||||
}
|
||||
foreach ($folder in @('build/dictionaries','build/release/dictionaries','build/staged/dictionaries')) {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
include(FetchContent)
|
||||
FetchContent_Declare(scintilla
|
||||
URL https://www.scintilla.org/scintilla569.zip
|
||||
URL_HASH SHA256=fddc637afa6e3a9205a5ad67c777d711a921ed2797d792f3034010c1be1539d6
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
|
||||
FetchContent_Declare(lexilla
|
||||
URL https://www.scintilla.org/lexilla555.zip
|
||||
URL_HASH SHA256=713ada097b7da0594638e2c5723d8dea486653c23ec2e0c12631df7e5b7f0991
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
|
||||
FetchContent_MakeAvailable(scintilla lexilla)
|
||||
|
||||
file(GLOB scintilla_sources "${scintilla_SOURCE_DIR}/src/*.cxx" "${scintilla_SOURCE_DIR}/win32/*.cxx")
|
||||
list(FILTER scintilla_sources EXCLUDE REGEX "/ScintillaDLL\\.cxx$")
|
||||
file(GLOB lexilla_sources "${lexilla_SOURCE_DIR}/lexlib/*.cxx" "${lexilla_SOURCE_DIR}/lexers/*.cxx")
|
||||
add_library(KSwitcherFilesText STATIC ${scintilla_sources} ${lexilla_sources}
|
||||
"${lexilla_SOURCE_DIR}/src/Lexilla.cxx")
|
||||
target_include_directories(KSwitcherFilesText
|
||||
PUBLIC "${scintilla_SOURCE_DIR}/include" "${lexilla_SOURCE_DIR}/include"
|
||||
PRIVATE "${scintilla_SOURCE_DIR}/src" "${lexilla_SOURCE_DIR}/lexlib")
|
||||
target_compile_definitions(KSwitcherFilesText PRIVATE UNICODE _UNICODE NOMINMAX LEXILLA_NO_EXPORT)
|
||||
target_link_libraries(KSwitcherFilesText PRIVATE imm32 ole32 oleaut32 msimg32)
|
||||
target_link_libraries(KSwitcherFiles PRIVATE KSwitcherFilesText)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesText KSwitcherFiles PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
target_compile_options(KSwitcherFilesText PRIVATE /utf-8)
|
||||
endif()
|
||||
@@ -17,9 +17,19 @@ replace counts with original frequency ranks, sort lexically. Reproduce with
|
||||
hashes. The lists contain word forms from subtitles, not a complete spelling
|
||||
or grammar dictionary. Recognition can miss names, jargon and uncommon forms.
|
||||
|
||||
File format: UTF-8 word, TAB, positive original frequency rank, newline.
|
||||
Supplemental Ukrainian vocabulary: `реліз`, `поточні`. These additions use rank 50001,
|
||||
after the upstream 50k list, rather than claiming a measured corpus frequency.
|
||||
They are included with the default unlimited rank setting and recorded in sources.json.
|
||||
|
||||
File format: UTF-8 word, TAB, positive frequency rank (or supplemental rank), newline.
|
||||
All entries protect known words. The frequency rank limit in Auto-correction options defaults to 0
|
||||
(entire dictionary); a positive limit only permits correction candidates at or below that rank.
|
||||
Personal words may use rank 1. Keep entries lowercase, unique and sorted, with a Tab separator.
|
||||
Prefer Settings > Auto-correction options > My dictionary for personal words.
|
||||
Enter correct spellings in the matching language field, separated by commas or new lines.
|
||||
These words are stored in settings, survive dictionary updates, and need no ranks or sorting.
|
||||
Click OK, then Save in Settings to apply them.
|
||||
|
||||
For advanced file edits, personal words may use rank 1. Keep entries lowercase with a Tab separator.
|
||||
Words may be appended: loading sorts entries and merges duplicates using the lowest rank.
|
||||
Save the UTF-8 file, then click OK in Auto-correction options and Save in Settings to reload it.
|
||||
Back up edited files before replacing dictionaries with a new distribution.
|
||||
@@ -9,9 +9,13 @@
|
||||
"uk": {
|
||||
"source": "https://raw.githubusercontent.com/hermitdave/FrequencyWords/525f9b560de45753a5ea01069454e72e9aa541c6/content/2016/uk/uk_50k.txt",
|
||||
"sourceSha256": "9548b79a608d33f39c5546037a69117d679730b1fda08dd0ce67c043dbf3335a",
|
||||
"words": 42549,
|
||||
"bytes": 898210,
|
||||
"sha256": "b4104898dcccbc1331ec01e9cd690e30285fe58481460e47438e973964d09802"
|
||||
"words": 42551,
|
||||
"bytes": 898248,
|
||||
"sha256": "caeb097749d4afc84b68ad96b3d7dfb6a6569561cd32ccce0bee94a13b43ba86",
|
||||
"supplementalWords": {
|
||||
"\u0440\u0435\u043b\u0456\u0437": 50001,
|
||||
"\u043f\u043e\u0442\u043e\u0447\u043d\u0456": 50001
|
||||
}
|
||||
},
|
||||
"ru": {
|
||||
"source": "https://raw.githubusercontent.com/hermitdave/FrequencyWords/525f9b560de45753a5ea01069454e72e9aa541c6/content/2016/ru/ru_50k.txt",
|
||||
|
||||
@@ -27337,6 +27337,7 @@
|
||||
поторопись 9062
|
||||
поторопитесь 20656
|
||||
поторопиться 15390
|
||||
поточні 50001
|
||||
потрапив 4168
|
||||
потрапила 7383
|
||||
потрапили 6631
|
||||
@@ -31207,6 +31208,7 @@
|
||||
релігію 26138
|
||||
релігія 22202
|
||||
релігії 23427
|
||||
реліз 50001
|
||||
рембо 28603
|
||||
ремень 23872
|
||||
ремені 28385
|
||||
|
||||
@@ -5,20 +5,47 @@ $destination = Join-Path $root 'dist\KSwitcher'
|
||||
New-Item -ItemType Directory -Force $destination | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $root 'build\release\KSwitcher.exe') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'build\release\KSwitcher.Config.exe') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'build\release\KSwitcher.Screenshot.exe') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'build\release\KSwitcher.Files.exe') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'build\release\WebView2Loader.dll') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'build\release\terminal') -Destination $destination -Recurse -Force
|
||||
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 'resources\files-text-license.txt') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'LAN-PREVIEW.md') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'dictionaries') -Destination $destination -Recurse -Force
|
||||
New-Item -ItemType Directory -Force (Join-Path $destination 'tools') | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') -Destination (Join-Path $destination 'tools\README.txt') -Force
|
||||
Copy-Item -LiteralPath (Join-Path $root 'build\release\tools\StayHere.exe') -Destination (Join-Path $destination 'tools\StayHere.exe') -Force
|
||||
Copy-Item -LiteralPath (Join-Path $root 'utilities\StayHere\README.md') -Destination (Join-Path $destination 'tools\StayHere-README.md') -Force
|
||||
# Enumerate the distributable files explicitly; do not include a user's data directory.
|
||||
$files = @('KSwitcher.exe','KSwitcher.Config.exe','LICENSE','json-LICENSE.txt','README.md','dictionaries') | ForEach-Object { Join-Path $destination $_ }
|
||||
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ }
|
||||
$entries = foreach ($path in $files) {
|
||||
foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) {
|
||||
@{path=$file.FullName.Substring($destination.Length+1).Replace('\','/'); size=$file.Length; sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||
}
|
||||
}
|
||||
$version=[Diagnostics.FileVersionInfo]::GetVersionInfo((Join-Path $destination 'KSwitcher.exe')).FileVersion
|
||||
$manifest=Join-Path $destination 'release-files.json'
|
||||
@{schema=1; version=$version; files=@($entries)} | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $manifest -Encoding utf8
|
||||
$files += $manifest
|
||||
$archive = Join-Path $root 'dist\KSwitcher-win-x64.zip'
|
||||
Compress-Archive -LiteralPath $files -DestinationPath $archive -Force
|
||||
Get-FileHash -LiteralPath $archive -Algorithm SHA256
|
||||
# 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() }
|
||||
$archiveHash = Get-FileHash -LiteralPath $archive -Algorithm SHA256
|
||||
$archiveHash
|
||||
if ($PublishRelease) {
|
||||
$release = Join-Path $root 'Release'
|
||||
New-Item -ItemType Directory -Force $release | Out-Null
|
||||
$published = Join-Path $release 'KSwitcher-win-x64.zip'
|
||||
Copy-Item -LiteralPath $archive -Destination $published -Force
|
||||
$hash = (Get-FileHash -LiteralPath $published -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
$hash = $archiveHash.Hash.ToLowerInvariant()
|
||||
"$hash KSwitcher-win-x64.zip" | Set-Content -LiteralPath (Join-Path $release 'SHA256SUMS.txt') -Encoding ascii
|
||||
}
|
||||
@@ -2,12 +2,15 @@
|
||||
#include <windows.h>
|
||||
#include "resource.h"
|
||||
IDI_KSWITCHER ICON "kswitcher.ico"
|
||||
#ifdef KS_SCREENSHOT_RESOURCES
|
||||
IDI_SCREENSHOT_QUESTION ICON "icons/question.ico"
|
||||
IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
#endif
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
201 RCDATA "update.ps1"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 0,4,2,0
|
||||
PRODUCTVERSION 0,4,2,0
|
||||
FILEVERSION 0,6,112,0
|
||||
PRODUCTVERSION 0,6,112,0
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
BEGIN
|
||||
@@ -17,7 +20,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
||||
VALUE "ProductName", "KSwitcher"
|
||||
VALUE "FileVersion", "0.4.2"
|
||||
VALUE "FileVersion", "0.6.112"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
@@ -25,6 +28,7 @@ BEGIN
|
||||
VALUE "Translation", 0x409, 1200
|
||||
END
|
||||
END
|
||||
#ifdef KS_SCREENSHOT_RESOURCES
|
||||
300 ICON "icons/lucide/circle-dot-normal.ico"
|
||||
310 ICON "icons/lucide/circle-dot-active.ico"
|
||||
320 ICON "icons/lucide/circle-dot-disabled.ico"
|
||||
@@ -73,3 +77,5 @@ END
|
||||
405 ICON "icons/lucide/a-large-small-normal.ico"
|
||||
415 ICON "icons/lucide/a-large-small-active.ico"
|
||||
425 ICON "icons/lucide/a-large-small-disabled.ico"
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,20 @@
|
||||
License for Lexilla, Scintilla, and SciTE
|
||||
|
||||
Copyright 1998-2021 by Neil Hodgson <[email protected]>
|
||||
|
||||
All Rights Reserved
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted,
|
||||
provided that the above copyright notice appear in all copies and that
|
||||
both that copyright notice and this permission notice appear in
|
||||
supporting documentation.
|
||||
|
||||
NEIL HODGSON DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
|
||||
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS, IN NO EVENT SHALL NEIL HODGSON BE LIABLE FOR ANY
|
||||
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
|
||||
OR PERFORMANCE OF THIS SOFTWARE.
|
||||
@@ -0,0 +1,309 @@
|
||||
#pragma code_page(65001)
|
||||
#include <windows.h>
|
||||
#include <commctrl.h>
|
||||
#include "resource.h"
|
||||
|
||||
#define FAR_EDIT(id, mode, x, y, width, height) \
|
||||
CONTROL "", id, "KSwitcher.Files.FarEdit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height
|
||||
|
||||
1 ICON "kswitcher-files.ico"
|
||||
IDI_FILES_VIEWER ICON "kswitcher-files-viewer.ico"
|
||||
IDI_FILES_EDITOR ICON "kswitcher-files-editor.ico"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
601 RCDATA "files-text-license.txt"
|
||||
|
||||
602 DIALOGEX 0, 0, 230, 85
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Page number", 101, 18, 21, 194, 12
|
||||
FAR_EDIT(100, ES_NUMBER, 18, 38, 194, 16)
|
||||
CONTROL "&Go", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 53, 59, 60, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 117, 59, 60, 17
|
||||
END
|
||||
|
||||
604 DIALOGEX 0, 0, 268, 101
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
CONTROL "&Search for", 109, "Static", SS_OWNERDRAW, 18, 17, 130, 12
|
||||
FAR_EDIT(100, 0, 18, 30, 241, 14)
|
||||
CONTROL "↓", 108, "Button", BS_OWNERDRAW | WS_TABSTOP, 259, 30, 11, 14
|
||||
CONTROL "W&ord", 106, "Button", BS_OWNERDRAW | WS_TABSTOP, 160, 14, 49, 15
|
||||
CONTROL "Se&lection", 107, "Button", BS_OWNERDRAW | WS_TABSTOP, 212, 14, 58, 15
|
||||
CONTROL "", 104, "Static", NOT WS_VISIBLE, 18, 51, 1, 1
|
||||
AUTOCHECKBOX "&Case sensitive", 101, 18, 52, 110, 12
|
||||
AUTOCHECKBOX "&Whole words", 102, 18, 64, 110, 12
|
||||
CONTROL "", 105, "Static", NOT WS_VISIBLE, 18, 81, 1, 1
|
||||
CONTROL "Find pre&vious", 103, "Button", BS_OWNERDRAW | WS_TABSTOP, 33, 80, 83, 15
|
||||
CONTROL "Find &next", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 121, 80, 76, 15
|
||||
CONTROL "Canc&el", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 202, 80, 53, 15
|
||||
END
|
||||
|
||||
603 DIALOGEX 0, 0, 230, 72
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Save changes to this file?", -1, 18, 23, 194, 12, SS_CENTER
|
||||
CONTROL "&Save", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 17, 42, 60, 17
|
||||
CONTROL "&Discard", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 42, 66, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
|
||||
END
|
||||
|
||||
607 DIALOGEX 0, 0, 185, 57
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL, 14, 16, 157, 13
|
||||
AUTOCHECKBOX "&Remember for this session", 101, 14, 30, 157, 13, NOT WS_VISIBLE
|
||||
CONTROL "", 102, "Static", NOT WS_VISIBLE, 14, 35, 1, 1
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
|
||||
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
|
||||
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
|
||||
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
|
||||
END
|
||||
|
||||
609 DIALOGEX 0, 0, 350, 135
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 430, 14, 17, 322, 20
|
||||
LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
CONTROL "", 432, "Static", NOT WS_VISIBLE, 14, 108, 1, 1
|
||||
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 56, 110, 80, 16
|
||||
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 140, 110, 74, 16
|
||||
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 218, 110, 65, 16
|
||||
END
|
||||
|
||||
608 DIALOGEX 0, 0, 220, 67
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Save color scheme"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "Scheme &name", -1, 8, 8, 204, 10
|
||||
EDITTEXT 100, 8, 21, 204, 14, ES_AUTOHSCROLL
|
||||
DEFPUSHBUTTON "Save", IDOK, 105, 44, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 162, 44, 50, 14
|
||||
END
|
||||
|
||||
101 DIALOGEX 0, 0, 397, 310
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN
|
||||
CAPTION "KSwitcher Files Options"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "&Search settings", -1, 8, 8, 113, 10
|
||||
EDITTEXT 270, 8, 21, 113, 14, ES_AUTOHSCROLL
|
||||
CONTROL "", 271, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 8, 40, 113, 240
|
||||
LTEXT "", 272, 131, 8, 253, 12
|
||||
AUTOCHECKBOX "Left panel: &Wide", 273, 132, 27, 115, 12
|
||||
AUTOCHECKBOX "Right panel: W&ide", 274, 251, 27, 125, 12
|
||||
GROUPBOX "Wide panel columns", 275, 129, 27, 259, 59
|
||||
LTEXT "Size column &width (6–16 characters)", 276, 138, 44, 175, 10
|
||||
EDITTEXT 201, 335, 41, 43, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
AUTOCHECKBOX "&Align file extensions", 202, 138, 64, 108, 12
|
||||
AUTOCHECKBOX "Align &folder extensions", 204, 252, 64, 125, 12
|
||||
GROUPBOX "Status line columns", 277, 129, 27, 259, 46
|
||||
AUTOCHECKBOX "Show &details", 203, 138, 40, 100, 12
|
||||
AUTOCHECKBOX "Name", 205, 138, 55, 47, 12
|
||||
AUTOCHECKBOX "Size", 206, 196, 55, 42, 12
|
||||
AUTOCHECKBOX "Date", 207, 254, 55, 45, 12
|
||||
AUTOCHECKBOX "Time", 208, 312, 55, 45, 12
|
||||
PUSHBUTTON "Change &color…", 279, 131, 48, 82, 15
|
||||
LTEXT "", 280, 222, 50, 155, 12
|
||||
LTEXT "", 281, 131, 30, 254, 14
|
||||
PUSHBUTTON "Change &font…", 282, 131, 52, 82, 15
|
||||
LTEXT "&Outer padding (px at 96 DPI)", 302, 131, 31, 173, 12
|
||||
COMBOBOX 303, 311, 28, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "&Inner padding (px at 96 DPI)", 304, 131, 54, 173, 12
|
||||
COMBOBOX 305, 311, 51, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "&Row text padding (characters)", 306, 131, 77, 173, 12
|
||||
COMBOBOX 307, 311, 74, 56, 76, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "Previous command", 320, 131, 30, 120, 12
|
||||
CONTROL "", 321, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 27, 110, 15
|
||||
LTEXT "Open command history", 322, 131, 53, 120, 12
|
||||
CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15
|
||||
AUTOCHECKBOX "Allow &paired PCs to run PowerShell commands here", 370, 131, 79, 250, 14
|
||||
AUTOCHECKBOX "Allow paired PCs to &hibernate this PC", 371, 131, 95, 250, 14
|
||||
AUTOCHECKBOX "Allow paired PCs to &update KSwitcher here", 372, 131, 111, 250, 14
|
||||
PUSHBUTTON "Reset selected to defaults", 284, 131, 181, 125, 15
|
||||
COMBOBOX 285, 131, 183, 139, 95, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "Reset property", 286, 278, 183, 108, 15
|
||||
LTEXT "File type", 287, 131, 26, 75, 10
|
||||
COMBOBOX 288, 131, 38, 151, 100, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "&Remove", 289, 290, 38, 77, 14
|
||||
LTEXT "Windows extension or custom extension", 290, 131, 63, 246, 10
|
||||
COMBOBOX 291, 131, 75, 151, 108, CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "A&dd", 292, 290, 75, 77, 14
|
||||
LTEXT "Row state", 300, 131, 100, 72, 10
|
||||
COMBOBOX 301, 131, 112, 174, 80, CBS_DROPDOWNLIST | WS_TABSTOP
|
||||
PUSHBUTTON "&Foreground…", 293, 131, 135, 78, 14
|
||||
PUSHBUTTON "&Background…", 294, 216, 135, 78, 14
|
||||
PUSHBUTTON "&Inherit colors", 295, 301, 135, 83, 14
|
||||
LTEXT "", 296, 131, 152, 253, 13
|
||||
AUTOCHECKBOX "&Underline", 297, 131, 166, 80, 12
|
||||
AUTOCHECKBOX "Stri&kethrough", 298, 218, 166, 100, 12
|
||||
CONTROL "Settings preview", 299, "Static", SS_OWNERDRAW | WS_BORDER, 131, 202, 253, 81
|
||||
AUTOCHECKBOX "&Wrap lines", 350, 131, 28, 118, 12
|
||||
AUTOCHECKBOX "&Line numbers", 351, 257, 28, 125, 12
|
||||
AUTOCHECKBOX "Show &whitespace and line endings", 352, 131, 45, 118, 12
|
||||
AUTOCHECKBOX "&Highlight current line", 353, 257, 45, 125, 12
|
||||
AUTOCHECKBOX "Insert &spaces for tabs", 354, 131, 62, 118, 12
|
||||
AUTOCHECKBOX "Auto &indent", 355, 257, 62, 125, 12
|
||||
LTEXT "&Tab width", 356, 131, 84, 118, 10
|
||||
COMBOBOX 357, 257, 81, 125, 100, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "Line &endings for new lines", 358, 131, 104, 118, 10
|
||||
COMBOBOX 359, 257, 101, 125, 77, CBS_DROPDOWNLIST | WS_TABSTOP
|
||||
LTEXT "Color sc&heme", 362, 131, 125, 118, 10
|
||||
COMBOBOX 363, 257, 122, 125, 67, CBS_DROPDOWNLIST | WS_TABSTOP
|
||||
LTEXT "Customize &color", 364, 131, 145, 118, 10
|
||||
COMBOBOX 365, 257, 142, 125, 116, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
|
||||
LTEXT "", 367, 345, 184, 45, 12
|
||||
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
|
||||
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
|
||||
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12
|
||||
EDITTEXT 376, 131, 68, 168, 14, ES_AUTOHSCROLL
|
||||
PUSHBUTTON "Choose &font…", 377, 306, 68, 76, 14
|
||||
LTEXT "Font &size (8–72 pt)", 378, 131, 99, 184, 12
|
||||
EDITTEXT 379, 318, 96, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
|
||||
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
|
||||
END
|
||||
|
||||
102 DIALOGEX 0, 0, 350, 110
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Copy"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Copy to", 210, 14, 15, 322, 12, SS_PATHELLIPSIS
|
||||
FAR_EDIT(211, 0, 14, 29, 322, 18)
|
||||
LTEXT "Existing files:", 212, 14, 57, 122, 14, SS_CENTERIMAGE
|
||||
COMBOBOX 213, 140, 57, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
|
||||
AUTOCHECKBOX "Also ask on read-only files", 214, 14, 77, 322, 14
|
||||
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 92, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 92, 86, 18
|
||||
END
|
||||
|
||||
103 DIALOGEX 0, 0, 460, 126
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Copying"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Counting files...", 220, 12, 16, 436, 12, SS_OWNERDRAW
|
||||
LTEXT "", 221, 12, 31, 436, 12, SS_OWNERDRAW
|
||||
CONTROL "", 222, "msctls_progress32", PBS_SMOOTH, 12, 46, 436, 14
|
||||
LTEXT "Files:", 224, 12, 63, 436, 12
|
||||
LTEXT "Bytes:", 225, 12, 77, 436, 12
|
||||
CONTROL "", 226, "msctls_progress32", PBS_SMOOTH, 12, 91, 436, 14
|
||||
LTEXT "", 228, 12, 60, 1, 1
|
||||
LTEXT "", 229, 12, 104, 1, 1
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 187, 106, 86, 18
|
||||
END
|
||||
|
||||
104 DIALOGEX 0, 0, 360, 139
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Warning"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 230, 12, 16, 336, 12
|
||||
LTEXT "", 231, 12, 33, 336, 12, SS_PATHELLIPSIS
|
||||
LTEXT "", 233, 12, 55, 1, 1
|
||||
LTEXT "New", 329, 12, 58, 65, 13
|
||||
RTEXT "", 330, 78, 58, 270, 13
|
||||
LTEXT "Existing", 331, 12, 72, 65, 13
|
||||
RTEXT "", 332, 78, 72, 270, 13
|
||||
LTEXT "", 333, 12, 88, 1, 1
|
||||
LTEXT "", 234, 12, 114, 1, 1
|
||||
AUTOCHECKBOX "Remember choice", 232, 12, 90, 336, 18
|
||||
CONTROL "&Overwrite", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 122, 110, 18
|
||||
CONTROL "&Skip", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 158, 122, 68, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 232, 122, 86, 18
|
||||
END
|
||||
|
||||
105 DIALOGEX 0, 0, 310, 65
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Cancel copy"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
CTEXT "Do you really want to cancel copying?", 235, 12, 17, 286, 16, SS_CENTERIMAGE
|
||||
LTEXT "", 236, 12, 38, 1, 1
|
||||
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 83, 42, 68, 18
|
||||
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 159, 42, 68, 18
|
||||
END
|
||||
|
||||
106 DIALOGEX 0, 0, 400, 190
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Delete"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 240, 14, 14, 372, 16
|
||||
LTEXT "", 241, 14, 32, 372, 122, SS_NOPREFIX
|
||||
LTEXT "", 243, 14, 177, 1, 1
|
||||
CONTROL "&Move", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 37, 178, 86, 18
|
||||
CONTROL "&All", 244, "Button", BS_OWNERDRAW | WS_TABSTOP, 129, 178, 63, 18
|
||||
CONTROL "&Skip", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 197, 178, 63, 18
|
||||
CONTROL "Skip a&ll", 249, "Button", BS_OWNERDRAW | WS_TABSTOP, 197, 178, 94, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 265, 178, 79, 18
|
||||
END
|
||||
|
||||
107 DIALOGEX 0, 0, 400, 82
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Deleting"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Scanning...", 245, 14, 15, 372, 14, SS_PATHELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 246, 14, 31, 372, 14
|
||||
CONTROL "", 247, "msctls_progress32", PBS_SMOOTH, 14, 48, 372, 18
|
||||
LTEXT "", 248, 14, 73, 1, 1
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 157, 74, 86, 18
|
||||
END
|
||||
108 DIALOGEX 0, 0, 264, 110
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
CONTROL "Create the &folder:", 360, "Static", SS_OWNERDRAW, 14, 15, 236, 12
|
||||
FAR_EDIT(361, 0, 14, 27, 225, 16)
|
||||
CONTROL "↓", 363, "Button", BS_OWNERDRAW | WS_TABSTOP, 239, 27, 11, 16
|
||||
CONTROL "", 362, "Static", NOT WS_VISIBLE, 14, 48, 1, 1
|
||||
CONTROL "&Link type:", 364, "Static", SS_OWNERDRAW, 14, 51, 73, 12
|
||||
COMBOBOX 365, 90, 48, 160, 64, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
|
||||
CONTROL "&Target:", 366, "Static", SS_OWNERDRAW, 14, 65, 73, 12
|
||||
FAR_EDIT(367, 0, 90, 63, 160, 16)
|
||||
AUTOCHECKBOX "Process &multiple names", 368, 14, 79, 236, 13
|
||||
CONTROL "", 369, "Static", NOT WS_VISIBLE, 14, 96, 1, 1
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 97, 54, 15
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 97, 60, 15
|
||||
END
|
||||
|
||||
109 DIALOGEX 0, 0, 250, 85
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
CAPTION "Folder shortcuts"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
CONTROL "", 310, "ListBox", LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP, 8, 14, 234, 50
|
||||
END
|
||||
|
||||
110 DIALOGEX 0, 0, 370, 116
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Folder shortcuts"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Title", 316, 16, 18, 338, 12
|
||||
FAR_EDIT(314, ES_LEFT, 16, 31, 338, 15)
|
||||
LTEXT "&Path", 317, 16, 49, 338, 12
|
||||
FAR_EDIT(211, ES_LEFT, 16, 62, 338, 15)
|
||||
LTEXT "", 315, 10, 82, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 97, 86, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 187, 86, 86, 18
|
||||
END
|
||||
|
||||
111 DIALOGEX 0, 0, 385, 220
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
FONT 9, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Search commands or topics", 326, 12, 14, 361, 12
|
||||
FAR_EDIT(325, 0, 12, 28, 361, 16)
|
||||
LISTBOX 324, 12, 49, 361, 155, LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
END
|
||||
|
After Width: | Height: | Size: 57 KiB |
@@ -0,0 +1,14 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48">
|
||||
<defs>
|
||||
<linearGradient id="blue" x1="8" y1="4" x2="36" y2="44" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#38bdf8"/>
|
||||
<stop offset=".55" stop-color="#1687e8"/>
|
||||
<stop offset="1" stop-color="#2563eb"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<circle cx="24" cy="25" r="21" fill="#1e40af" opacity=".12"/>
|
||||
<circle cx="24" cy="23" r="21" fill="url(#blue)"/>
|
||||
<circle cx="24" cy="23" r="20.5" fill="none" stroke="white" stroke-opacity=".25"/>
|
||||
<path d="M18 17.5c0-3.1 2.5-5 6-5s6 2 6 5c0 4.8-6 4.8-6 9" fill="none" stroke="white" stroke-width="3.5" stroke-linecap="round"/>
|
||||
<circle cx="24" cy="33" r="2" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 711 B |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
@@ -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.
|
||||
@@ -1,3 +1,6 @@
|
||||
#pragma once
|
||||
#define IDI_KSWITCHER 101
|
||||
#define IDI_SCREENSHOT_QUESTION 102
|
||||
#define IDI_FILES_VIEWER 103
|
||||
#define IDI_FILES_EDITOR 104
|
||||
#define IDC_SCREENSHOT_PENCIL 500
|
||||
|
After Width: | Height: | Size: 71 KiB |
@@ -0,0 +1,22 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="330" viewBox="0 0 960 330">
|
||||
<rect x="1" y="1" width="958" height="328" rx="24" fill="#F5F3FF" stroke="#DDD6FE" stroke-width="2"/>
|
||||
<g font-family="Segoe UI" fill="#241B46">
|
||||
<text x="40" y="58" font-size="20" font-weight="600" fill="#4F46E5">KSwitcher / Support development</text>
|
||||
<text x="40" y="115" font-size="35" font-weight="700">KSwitcher part of your day?</text>
|
||||
<text x="40" y="159" font-size="35" font-weight="700">Buy the developer a coffee.</text>
|
||||
<text x="40" y="202" font-size="20" fill="#655B7C">Your donation helps the tool keep growing.</text>
|
||||
<rect x="40" y="238" width="350" height="54" rx="12" fill="#4F46E5"/>
|
||||
<text x="215" y="272" text-anchor="middle" font-size="20" font-weight="600" fill="white">Support via monobank</text>
|
||||
</g>
|
||||
<g transform="translate(759 48) rotate(10 66 66)">
|
||||
<rect y="8" width="132" height="132" rx="26" fill="#C4B5FD"/>
|
||||
<rect width="132" height="132" rx="26" fill="#4F46E5"/>
|
||||
<g transform="translate(14 14) scale(3.25)"><path d="M8 7H12V25H8ZM11 15L22 6L25 9L14 18Z" fill="white"/><path d="M11 14L25 24L22 27L10 18Z" fill="#5EEAD4"/></g>
|
||||
</g>
|
||||
<g transform="translate(699 172) rotate(-8 67 60)">
|
||||
<rect y="7" width="142" height="115" rx="22" fill="#C4B5FD"/>
|
||||
<rect width="142" height="115" rx="22" fill="white" stroke="#DDD6FE" stroke-width="2"/>
|
||||
<g stroke="#4F46E5" stroke-width="5" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M43 41H92V66Q92 83 75 83H60Q43 83 43 66Z"/>
|
||||
<path d="M92 46H99Q115 46 111 58Q108 67 92 66M37 92H100M56 28V18M69 28V18M82 28V18"/>
|
||||
</g></g></svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 70 KiB |
@@ -0,0 +1,22 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="330" viewBox="0 0 960 330">
|
||||
<rect x="1" y="1" width="958" height="328" rx="24" fill="#F5F3FF" stroke="#DDD6FE" stroke-width="2"/>
|
||||
<g font-family="Segoe UI" fill="#241B46">
|
||||
<text x="40" y="58" font-size="20" font-weight="600" fill="#4F46E5">KSwitcher / Підтримати розробку</text>
|
||||
<text x="40" y="115" font-size="35" font-weight="700">KSwitcher щодня під рукою?</text>
|
||||
<text x="40" y="159" font-size="35" font-weight="700">Пригостіть розробника кавою.</text>
|
||||
<text x="40" y="202" font-size="20" fill="#655B7C">Ваш донат допомагає розвивати інструмент.</text>
|
||||
<rect x="40" y="238" width="350" height="54" rx="12" fill="#4F46E5"/>
|
||||
<text x="215" y="272" text-anchor="middle" font-size="20" font-weight="600" fill="white">Підтримати через monobank</text>
|
||||
</g>
|
||||
<g transform="translate(759 48) rotate(10 66 66)">
|
||||
<rect y="8" width="132" height="132" rx="26" fill="#C4B5FD"/>
|
||||
<rect width="132" height="132" rx="26" fill="#4F46E5"/>
|
||||
<g transform="translate(14 14) scale(3.25)"><path d="M8 7H12V25H8ZM11 15L22 6L25 9L14 18Z" fill="white"/><path d="M11 14L25 24L22 27L10 18Z" fill="#5EEAD4"/></g>
|
||||
</g>
|
||||
<g transform="translate(699 172) rotate(-8 67 60)">
|
||||
<rect y="7" width="142" height="115" rx="22" fill="#C4B5FD"/>
|
||||
<rect width="142" height="115" rx="22" fill="white" stroke="#DDD6FE" stroke-width="2"/>
|
||||
<g stroke="#4F46E5" stroke-width="5" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M43 41H92V66Q92 83 75 83H60Q43 83 43 66Z"/>
|
||||
<path d="M92 46H99Q115 46 111 58Q108 67 92 66M37 92H100M56 28V18M69 28V18M82 28V18"/>
|
||||
</g></g></svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'">
|
||||
<title>PowerShell terminal</title>
|
||||
<link rel="stylesheet" href="xterm.css">
|
||||
<style>
|
||||
html, body, #terminal { width:100%; height:100%; margin:0; overflow:hidden; background:#181818; }
|
||||
</style>
|
||||
<div id="terminal"></div>
|
||||
<script src="xterm.js"></script>
|
||||
<script src="addon-fit.js"></script>
|
||||
<script src="terminal.js"></script>
|
||||
</html>
|
||||
@@ -0,0 +1,56 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'">
|
||||
<title>Markdown preview</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; font: 16px/1.55 system-ui, sans-serif; }
|
||||
:root:not(.rendered) body { visibility: hidden; }
|
||||
body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
|
||||
main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); }
|
||||
nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; }
|
||||
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
|
||||
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
|
||||
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
|
||||
nav button:hover:not(:disabled) { text-decoration: underline; }
|
||||
nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
#search { margin-inline-start: auto; display: flex; align-items: center; gap: .35em;
|
||||
flex: 0 1 22em; min-width: 0; max-width: 100%; }
|
||||
#search[hidden] { display: none; }
|
||||
#search-query { box-sizing: border-box; flex: 1; min-width: 0; width: 0; font: inherit; }
|
||||
#search-status { white-space: nowrap; font-size: .8em; }
|
||||
::highlight(markdown-search-active) { background: #ffab45; color: #171717; }
|
||||
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
|
||||
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
|
||||
a { color: LinkText; }
|
||||
pre, table, figure { overflow: auto; }
|
||||
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
|
||||
pre { padding: .75em; }
|
||||
code { padding: .1em .25em; }
|
||||
pre code { padding: 0; background: none; }
|
||||
blockquote { margin-left: 0; padding-left: 1em; border-left: 3px solid GrayText; }
|
||||
table { display: block; border-collapse: collapse; }
|
||||
th, td { border: 1px solid GrayText; padding: .3em .65em; }
|
||||
img, svg { max-width: 100%; height: auto; }
|
||||
figure { margin: 1em 0; }
|
||||
.task { list-style: none; }
|
||||
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
|
||||
</style>
|
||||
<nav aria-label="Markdown preview">
|
||||
<button id="back" type="button" title="Back (Alt+Left)" aria-label="Back" disabled>←</button>
|
||||
<button id="forward" type="button" title="Forward (Alt+Right)" aria-label="Forward" disabled>→</button>
|
||||
<button id="search-open" type="button" title="Find (Ctrl+F)" aria-label="Find in document" aria-controls="search" aria-expanded="false">⌕</button>
|
||||
<div id="search" role="search" hidden>
|
||||
<input id="search-query" type="search" aria-label="Find in document" placeholder="Find in document" autocomplete="off">
|
||||
<output id="search-status" for="search-query" aria-live="polite"></output>
|
||||
<button id="search-previous" type="button" title="Previous match (Shift+Enter)" aria-label="Previous match" disabled>↑</button>
|
||||
<button id="search-next" type="button" title="Next match (Enter)" aria-label="Next match" disabled>↓</button>
|
||||
<button id="search-close" type="button" title="Close search (Esc)" aria-label="Close search">×</button>
|
||||
</div>
|
||||
</nav>
|
||||
<main></main>
|
||||
<script src="markdown-it.js"></script>
|
||||
<script src="mermaid.js"></script>
|
||||
<script src="markdown.js"></script>
|
||||
</html>
|
||||
@@ -0,0 +1,327 @@
|
||||
'use strict';
|
||||
|
||||
const bridge = window.chrome.webview;
|
||||
const content = document.querySelector('main');
|
||||
const back = document.querySelector('#back');
|
||||
const forward = document.querySelector('#forward');
|
||||
const searchOpen = document.querySelector('#search-open');
|
||||
const search = document.querySelector('#search');
|
||||
const searchQuery = document.querySelector('#search-query');
|
||||
const searchStatus = document.querySelector('#search-status');
|
||||
const searchPrevious = document.querySelector('#search-previous');
|
||||
const searchNext = document.querySelector('#search-next');
|
||||
const markdown = markdownit({ html: true, linkify: true });
|
||||
let generation = 0;
|
||||
let images = [];
|
||||
let matches = [];
|
||||
let activeMatch = -1;
|
||||
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: 'strict',
|
||||
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
|
||||
suppressErrorRendering: true,
|
||||
flowchart: { htmlLabels: false }
|
||||
});
|
||||
|
||||
markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
|
||||
for (let i = 2; i < tokens.length; ++i) {
|
||||
const token = tokens[i];
|
||||
if (token.type !== 'inline' || tokens[i - 1].type !== 'paragraph_open' ||
|
||||
tokens[i - 2].type !== 'list_item_open') continue;
|
||||
const text = token.children[0];
|
||||
const marker = text?.type === 'text' && /^\[([ xX])\][ \t]+/.exec(text.content);
|
||||
if (!marker) continue;
|
||||
text.content = text.content.slice(marker[0].length);
|
||||
const box = new text.constructor('task_checkbox', '', 0);
|
||||
box.checked = marker[1] !== ' ';
|
||||
box.content = token.content.slice(marker[0].length);
|
||||
token.children.unshift(box);
|
||||
tokens[i - 2].attrJoin('class', 'task');
|
||||
}
|
||||
});
|
||||
markdown.renderer.rules.task_checkbox = (tokens, i) =>
|
||||
'<input type="checkbox" aria-label="' + markdown.utils.escapeHtml(tokens[i].content) + '"' +
|
||||
(tokens[i].checked ? ' checked' : '') + '>';
|
||||
markdown.renderer.rules.image = (tokens, i) => {
|
||||
const token = tokens[i];
|
||||
const alt = markdown.renderer.renderInlineAsText(token.children, markdown.options, {});
|
||||
const escape = markdown.utils.escapeHtml;
|
||||
return '<img alt="' + escape(alt) + '" data-path="' + escape(token.attrGet('src')) + '">';
|
||||
};
|
||||
|
||||
const htmlTags = new Set(`a abbr address article aside b blockquote br caption code col colgroup dd del
|
||||
details div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hr i img input ins kbd li
|
||||
mark ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
|
||||
tr u ul var wbr`.split(/\s+/));
|
||||
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
|
||||
const tagAttributes = {
|
||||
a: ['href'], col: ['span'], colgroup: ['span'], details: ['open'], img: ['alt', 'width', 'height'],
|
||||
input: ['type', 'checked', 'disabled'], ol: ['start', 'reversed', 'type'], li: ['value'],
|
||||
td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan', 'scope'], time: ['datetime']
|
||||
};
|
||||
const inlineStyles = ['white-space', 'text-align', 'vertical-align', 'color', 'background-color',
|
||||
'font-weight', 'font-style', 'text-decoration-line', 'width', 'max-width'];
|
||||
|
||||
function relativeResource(path) {
|
||||
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
|
||||
}
|
||||
|
||||
function renderContent(text) {
|
||||
// Parse in an inert template and allow only document markup before attaching it to the preview.
|
||||
const template = document.createElement('template');
|
||||
template.innerHTML = markdown.render(text);
|
||||
for (const element of template.content.querySelectorAll('*')) {
|
||||
const tag = element.localName;
|
||||
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
|
||||
(tag === 'input' && element.type !== 'checkbox')) {
|
||||
element.remove();
|
||||
continue;
|
||||
}
|
||||
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
|
||||
const styles = element.hasAttribute('style')
|
||||
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
|
||||
for (const { name } of [...element.attributes]) {
|
||||
if (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name)) element.removeAttribute(name);
|
||||
}
|
||||
for (const [name, value] of styles) {
|
||||
if (value) element.style.setProperty(name, value);
|
||||
}
|
||||
if (relativeResource(imagePath)) element.dataset.path = imagePath;
|
||||
if (tag === 'a' && element.hasAttribute('href')) {
|
||||
const path = element.getAttribute('href').trim();
|
||||
if (relativeResource(path) || /^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i.test(path)) element.setAttribute('href', path);
|
||||
else element.removeAttribute('href');
|
||||
}
|
||||
}
|
||||
content.replaceChildren(template.content);
|
||||
}
|
||||
|
||||
function send(action, options = {}) {
|
||||
bridge.postMessage(JSON.stringify({ action, ...options }));
|
||||
}
|
||||
|
||||
function scrollToHeading(fragment) {
|
||||
if (!fragment) { window.scrollTo(0, 0); return; }
|
||||
try { content.querySelector('#' + CSS.escape(decodeURIComponent(fragment)))?.scrollIntoView(); } catch {}
|
||||
}
|
||||
|
||||
function restorePosition({ fragment, scroll }) {
|
||||
if (typeof scroll === 'number') window.scrollTo(0, scroll);
|
||||
else scrollToHeading(fragment);
|
||||
}
|
||||
|
||||
function navigate(action) {
|
||||
const button = action === 'back' ? back : forward;
|
||||
if (!button.disabled) send(action, { scroll: Math.round(window.scrollY) });
|
||||
}
|
||||
|
||||
back.addEventListener('click', () => navigate('back'));
|
||||
forward.addEventListener('click', () => navigate('forward'));
|
||||
|
||||
function updateSearch(reveal = true) {
|
||||
matches = [];
|
||||
activeMatch = -1;
|
||||
const query = searchQuery.value.trim();
|
||||
if (query) {
|
||||
const pattern = query.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
|
||||
const expression = new RegExp(pattern, 'giu');
|
||||
const blockTags = 'article,aside,blockquote,caption,dd,div,dt,figcaption,footer,h1,h2,h3,h4,h5,h6,header,li,p,pre,section,summary,td,th,text';
|
||||
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
|
||||
let block = null;
|
||||
let parts = [];
|
||||
let text = '';
|
||||
const searchBlock = () => {
|
||||
let first = 0;
|
||||
let last = 0;
|
||||
for (const match of text.matchAll(expression)) {
|
||||
const end = match.index + match[0].length;
|
||||
while (parts[first].end <= match.index) ++first;
|
||||
last = Math.max(last, first);
|
||||
while (parts[last].end < end) ++last;
|
||||
matches.push([parts[first].node, match.index - parts[first].start,
|
||||
parts[last].node, end - parts[last].start]);
|
||||
}
|
||||
parts = [];
|
||||
text = '';
|
||||
};
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
const element = node.parentElement;
|
||||
if (!node.length || element.closest('style,svg title,svg desc,svg defs') ||
|
||||
!element.checkVisibility({ visibilityProperty: true })) continue;
|
||||
const nextBlock = element.closest(blockTags);
|
||||
if (block !== nextBlock) searchBlock();
|
||||
block = nextBlock;
|
||||
const start = text.length;
|
||||
text += node.data;
|
||||
parts.push({ node, start, end: text.length });
|
||||
}
|
||||
searchBlock();
|
||||
}
|
||||
showSearchMatch(matches.length ? 0 : -1, reveal);
|
||||
}
|
||||
|
||||
function showSearchMatch(index, reveal) {
|
||||
activeMatch = index;
|
||||
searchPrevious.disabled = searchNext.disabled = matches.length < 2;
|
||||
searchStatus.value = !searchQuery.value.trim() ? '' : index < 0 ? 'No matches' : (index + 1) + ' / ' + matches.length;
|
||||
CSS.highlights.delete('markdown-search-active');
|
||||
if (index < 0) return;
|
||||
const [start, from, end, to] = matches[index];
|
||||
const range = new Range();
|
||||
range.setStart(start, from);
|
||||
range.setEnd(end, to);
|
||||
CSS.highlights.set('markdown-search-active', new Highlight(range));
|
||||
if (!reveal) return;
|
||||
const rect = range.getBoundingClientRect();
|
||||
const toolbarBottom = search.parentElement.getBoundingClientRect().bottom;
|
||||
if (rect.top < toolbarBottom || rect.bottom > innerHeight) {
|
||||
scrollBy(0, rect.top - Math.max(toolbarBottom, innerHeight / 2));
|
||||
}
|
||||
const scroller = start.parentElement.closest('pre, table');
|
||||
if (scroller) {
|
||||
const bounds = scroller.getBoundingClientRect();
|
||||
if (rect.left < bounds.left || rect.right > bounds.right) {
|
||||
scroller.scrollLeft += rect.left - bounds.left;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openSearch() {
|
||||
search.hidden = false;
|
||||
searchOpen.setAttribute('aria-expanded', 'true');
|
||||
searchQuery.focus({ preventScroll: true });
|
||||
searchQuery.select();
|
||||
}
|
||||
|
||||
function closeSearch() {
|
||||
if (search.hidden) return false;
|
||||
const hadFocus = search.contains(document.activeElement);
|
||||
search.hidden = true;
|
||||
searchOpen.setAttribute('aria-expanded', 'false');
|
||||
searchQuery.value = '';
|
||||
updateSearch();
|
||||
if (hadFocus) searchOpen.focus({ preventScroll: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
function stepSearch(direction) {
|
||||
if (search.hidden) openSearch();
|
||||
else if (matches.length) showSearchMatch((activeMatch + direction + matches.length) % matches.length, true);
|
||||
}
|
||||
|
||||
searchOpen.addEventListener('click', openSearch);
|
||||
document.querySelector('#search-close').addEventListener('click', closeSearch);
|
||||
searchQuery.addEventListener('input', () => updateSearch());
|
||||
searchPrevious.addEventListener('click', () => stepSearch(-1));
|
||||
searchNext.addEventListener('click', () => stepSearch(1));
|
||||
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
|
||||
|
||||
async function render({ text, fragment, scroll, title, keepPosition }) {
|
||||
const current = ++generation;
|
||||
if (keepPosition) scroll = window.scrollY;
|
||||
else closeSearch();
|
||||
document.documentElement.classList.remove('rendered');
|
||||
document.title = title;
|
||||
renderContent(text);
|
||||
const headings = new Set();
|
||||
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
|
||||
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
||||
let id = base;
|
||||
for (let n = 1; headings.has(id); ++n) id = base + '-' + n;
|
||||
heading.id = id;
|
||||
headings.add(id);
|
||||
}
|
||||
images = Array.from(content.querySelectorAll('img[data-path]'));
|
||||
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
|
||||
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
|
||||
for (const [index, block] of blocks.entries()) {
|
||||
try {
|
||||
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
|
||||
if (current !== generation) return;
|
||||
const figure = document.createElement('figure');
|
||||
figure.innerHTML = svg;
|
||||
block.parentElement.replaceWith(figure);
|
||||
} catch {
|
||||
if (current !== generation) return;
|
||||
const caption = document.createElement('div');
|
||||
caption.textContent = 'Invalid Mermaid diagram';
|
||||
block.parentElement.before(caption);
|
||||
}
|
||||
}
|
||||
restorePosition({ fragment, scroll });
|
||||
document.documentElement.classList.add('rendered');
|
||||
if (!search.hidden) updateSearch(false);
|
||||
send('rendered');
|
||||
}
|
||||
|
||||
content.addEventListener('click', event => {
|
||||
const link = event.target.closest('a');
|
||||
if (!link) return;
|
||||
event.preventDefault();
|
||||
const path = link.getAttribute('href');
|
||||
if (!path || event.ctrlKey || event.metaKey || link.closest('svg')) return;
|
||||
send('link', { path, newWindow: event.shiftKey, scroll: Math.round(window.scrollY) });
|
||||
});
|
||||
|
||||
document.addEventListener('pointerup', event => {
|
||||
if (event.button !== 3 && event.button !== 4) return;
|
||||
event.preventDefault();
|
||||
navigate(event.button === 3 ? 'back' : 'forward');
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.isComposing) return;
|
||||
if (event.ctrlKey && !event.altKey && event.key.toLowerCase() === 'f') {
|
||||
event.preventDefault();
|
||||
openSearch();
|
||||
} else if (event.key === 'F3' || (event.key === 'Enter' && event.target === searchQuery)) {
|
||||
event.preventDefault();
|
||||
stepSearch(event.shiftKey ? -1 : 1);
|
||||
} else if (event.key === 'Escape' && closeSearch()) {
|
||||
event.preventDefault();
|
||||
} else if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
|
||||
event.preventDefault();
|
||||
send('cycle', {reverse: event.shiftKey});
|
||||
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
|
||||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
navigate(['ArrowLeft', 'BrowserBack'].includes(event.key) ? 'back' : 'forward');
|
||||
} else if (event.key === 'F6' || event.key === 'Escape' || event.key === 'F10' ||
|
||||
(event.ctrlKey && event.key.toLowerCase() === 'w')) {
|
||||
event.preventDefault();
|
||||
send(event.key === 'F6' ? 'edit' : 'close');
|
||||
}
|
||||
});
|
||||
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
const message = JSON.parse(data);
|
||||
if (message.action === 'clear') {
|
||||
++generation;
|
||||
closeSearch();
|
||||
document.documentElement.classList.remove('rendered');
|
||||
content.replaceChildren();
|
||||
}
|
||||
if (message.action === 'render') void render(message).catch(() => send('failed'));
|
||||
if (message.action === 'appearance') {
|
||||
const style = document.documentElement.style;
|
||||
style.setProperty('--markdown-width', message.width ? message.width + 'px' : 'none');
|
||||
style.setProperty('--markdown-font-size', message.fontSize + 'pt');
|
||||
style.setProperty('--markdown-font', message.font ? CSS.escape(message.font) + ', system-ui, sans-serif' : 'system-ui, sans-serif');
|
||||
}
|
||||
if (message.action === 'anchor') restorePosition(message);
|
||||
if (message.action === 'find') openSearch();
|
||||
if (message.action === 'find-next') stepSearch(message.previous ? -1 : 1);
|
||||
if (message.action === 'escape' && !closeSearch()) send('close');
|
||||
if (message.action === 'back' || message.action === 'forward') navigate(message.action);
|
||||
if (message.action === 'history') {
|
||||
back.disabled = !message.back;
|
||||
forward.disabled = !message.forward;
|
||||
}
|
||||
if (message.action === 'image' && message.generation === generation && images[message.index]) {
|
||||
const image = images[message.index];
|
||||
if (message.source) image.src = message.source;
|
||||
else image.title = 'Image unavailable';
|
||||
}
|
||||
});
|
||||
bridge.postMessage('ready');
|
||||
@@ -0,0 +1,138 @@
|
||||
const bridge = window.chrome.webview;
|
||||
const terminal = new Terminal({
|
||||
fontFamily: 'Consolas, monospace',
|
||||
fontSize: 16,
|
||||
cursorBlink: false,
|
||||
disableStdin: true,
|
||||
theme: { background: '#181818', foreground: '#e8e8e8' },
|
||||
});
|
||||
const fit = new FitAddon.FitAddon();
|
||||
terminal.parser.registerOscHandler(633, data => {
|
||||
const prefix = 'ks-directory:';
|
||||
if (!data.startsWith(prefix)) return false;
|
||||
try {
|
||||
bridge.postMessage('directory:' + decodeURIComponent(data.slice(prefix.length)));
|
||||
} catch {
|
||||
bridge.postMessage('directory:');
|
||||
}
|
||||
return true;
|
||||
});
|
||||
terminal.loadAddon(fit);
|
||||
const host = document.getElementById('terminal');
|
||||
terminal.open(host);
|
||||
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
|
||||
host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true);
|
||||
const screen = host.querySelector('.xterm-screen');
|
||||
let traceEnabled = false;
|
||||
let traceBudget = 4096;
|
||||
let outputTraceBudget = 256;
|
||||
let traceOutput = false;
|
||||
let currentOffset = 0;
|
||||
function trace(phase) {
|
||||
if (!traceEnabled || traceBudget <= 0) return;
|
||||
traceBudget--;
|
||||
const buffer = terminal.buffer.active;
|
||||
bridge.postMessage(`trace:${phase},${host.clientHeight},${terminal.rows},${buffer.viewportY},${buffer.baseY},${Math.round(currentOffset)}`);
|
||||
}
|
||||
function anchorOutput() {
|
||||
const buffer = terminal.buffer.active;
|
||||
let offset = 0;
|
||||
if (buffer.type === 'normal' && buffer.viewportY === buffer.baseY) {
|
||||
let last = 0;
|
||||
for (let row = terminal.rows - 1; row >= 0; row--) {
|
||||
if (buffer.getLine(buffer.baseY + row)?.translateToString(true)) {
|
||||
last = row;
|
||||
break;
|
||||
}
|
||||
}
|
||||
offset = Math.max(0, terminal.rows - 1 - last) * screen.offsetHeight / terminal.rows;
|
||||
}
|
||||
screen.style.transform = `translateY(${offset}px)`;
|
||||
currentOffset = offset;
|
||||
trace(2);
|
||||
}
|
||||
terminal.attachCustomKeyEventHandler(event => {
|
||||
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
|
||||
if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter');
|
||||
event.preventDefault();
|
||||
return false;
|
||||
}
|
||||
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) return true;
|
||||
if (event.code === 'KeyO') bridge.postMessage('toggle');
|
||||
else if (event.code === 'ArrowUp') bridge.postMessage('grow');
|
||||
else if (event.code === 'ArrowDown') bridge.postMessage('shrink');
|
||||
else if (event.code === 'KeyF' || event.code === 'KeyC') {
|
||||
if (!event.repeat) bridge.postMessage(event.code === 'KeyF' ? 'insert-path' : 'copy-command-line');
|
||||
}
|
||||
else if (event.key === 'Enter') {
|
||||
if (!event.repeat) bridge.postMessage('insert-name');
|
||||
}
|
||||
else if (event.key === 'Insert') {
|
||||
if (!event.repeat) bridge.postMessage('copy-command-line-or-panel-names');
|
||||
}
|
||||
else if (event.code === 'KeyR') {
|
||||
if (!event.repeat) bridge.postMessage('refresh-panel');
|
||||
}
|
||||
else return true;
|
||||
event.preventDefault();
|
||||
return false;
|
||||
});
|
||||
const reportSize = () => bridge.postMessage(`size:${terminal.cols},${terminal.rows}`);
|
||||
terminal.onResize(reportSize);
|
||||
terminal.onScroll(() => {
|
||||
trace(3);
|
||||
anchorOutput();
|
||||
});
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
if (data === 'clear-selection') {
|
||||
terminal.clearSelection();
|
||||
return;
|
||||
}
|
||||
if (data === 'scroll-bottom') {
|
||||
terminal.scrollToBottom();
|
||||
anchorOutput();
|
||||
return;
|
||||
}
|
||||
if (data === 'trace:on' || data === 'trace:output') {
|
||||
traceEnabled = true;
|
||||
traceOutput = data === 'trace:output';
|
||||
trace(2);
|
||||
return;
|
||||
}
|
||||
const font = /^font:(\d+):(\d+):([01]):(.*)$/u.exec(data);
|
||||
if (font) {
|
||||
const [, points, weight, italic, family] = font;
|
||||
const quotedFamily = family.replace(/["\\]/g, '\\$&');
|
||||
terminal.options.fontFamily = `"${quotedFamily}", monospace`;
|
||||
terminal.options.fontSize = Number(points) * 96 / 720;
|
||||
terminal.options.fontWeight = Number(weight);
|
||||
host.style.fontStyle = italic === '1' ? 'italic' : 'normal';
|
||||
fit.fit();
|
||||
anchorOutput();
|
||||
return;
|
||||
}
|
||||
const bytes = new Uint8Array(data.length / 2);
|
||||
for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(data.slice(2*i, 2*i+2), 16);
|
||||
terminal.write(bytes, () => {
|
||||
anchorOutput();
|
||||
if (traceOutput && outputTraceBudget > 0) {
|
||||
outputTraceBudget--;
|
||||
const buffer = terminal.buffer.active;
|
||||
const lines = Array.from({ length: terminal.rows }, (_, row) =>
|
||||
buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? '');
|
||||
bridge.postMessage('output:' + lines.join('\n').trimEnd());
|
||||
}
|
||||
});
|
||||
});
|
||||
new ResizeObserver(() => {
|
||||
const buffer = terminal.buffer.active;
|
||||
const wasAtBottom = buffer.viewportY === buffer.baseY;
|
||||
trace(0);
|
||||
fit.fit();
|
||||
trace(1);
|
||||
if (wasAtBottom) terminal.scrollToBottom();
|
||||
requestAnimationFrame(anchorOutput);
|
||||
}).observe(host);
|
||||
bridge.postMessage('ready');
|
||||
fit.fit();
|
||||
reportSize();
|
||||
@@ -3,10 +3,193 @@
|
||||
[string]$CurrentVersion, [string]$ExpectedVersion,
|
||||
[string]$InstallDirectory, [string]$WorkDirectory,
|
||||
[int]$ParentProcessId, [string]$ReadyEvent,
|
||||
[switch]$ShowProgress,
|
||||
[switch]$Unattended, [string]$Journal,
|
||||
[switch]$Library
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$script:progressWindow = $null
|
||||
|
||||
function Start-UpdateProgress {
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
if (!('KSwitcherUpdateProgress' -as [type])) {
|
||||
Add-Type -ReferencedAssemblies System.Windows.Forms,System.Drawing -TypeDefinition @'
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Threading;
|
||||
using System.Windows.Forms;
|
||||
using System.Drawing.Drawing2D;
|
||||
using System.Runtime.InteropServices;
|
||||
public sealed class UpdateMeter : Control {
|
||||
public int Percent = -1;
|
||||
private int position;
|
||||
private readonly System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer { Interval = 35 };
|
||||
public UpdateMeter() {
|
||||
DoubleBuffered = true;
|
||||
timer.Tick += delegate { if (Percent < 0) { position = (position + 5) % Math.Max(1,Width); Invalidate(); } };
|
||||
timer.Start();
|
||||
}
|
||||
protected override void OnPaint(PaintEventArgs e) {
|
||||
using(var track = new SolidBrush(Color.FromArgb(232,234,241))) e.Graphics.FillRectangle(track,0,0,Width,Height);
|
||||
using(var fill = new SolidBrush(Color.FromArgb(79,70,229))) {
|
||||
if(Percent < 0) e.Graphics.FillRectangle(fill,position-Width/4,0,Width/4,Height);
|
||||
else e.Graphics.FillRectangle(fill,0,0,Width*Percent/100,Height);
|
||||
}
|
||||
}
|
||||
protected override void Dispose(bool disposing) { if(disposing) timer.Dispose(); base.Dispose(disposing); }
|
||||
}
|
||||
public sealed class UpdateSteps : Control {
|
||||
public int Current = -1;
|
||||
public bool Complete;
|
||||
public UpdateSteps() { DoubleBuffered = true; }
|
||||
protected override void OnPaint(PaintEventArgs e) {
|
||||
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
string[] names = {"Download","Verify","Install","Restart"};
|
||||
for(int i=0;i<4;i++) {
|
||||
int x = i*(Width-80)/3;
|
||||
Color color = Complete || i<=Current ? Color.FromArgb(79,70,229) : Color.FromArgb(135,141,158);
|
||||
using(var pen = new Pen(Color.FromArgb(231,233,240)))
|
||||
if(i<3) e.Graphics.DrawLine(pen,x+22,8,x+(Width-80)/3-10,8);
|
||||
using(var brush = new SolidBrush(color)) {
|
||||
if(Complete || i<Current) {
|
||||
e.Graphics.FillEllipse(brush,x,0,16,16);
|
||||
using(var pen = new Pen(Color.White,1.6f)) e.Graphics.DrawLines(pen,new Point[]{new Point(x+4,8),new Point(x+7,11),new Point(x+12,5)});
|
||||
} else {
|
||||
using(var pen = new Pen(color,i==Current?2:1)) e.Graphics.DrawEllipse(pen,x+1,1,14,14);
|
||||
if(i==Current) e.Graphics.FillEllipse(brush,x+5,5,6,6);
|
||||
}
|
||||
e.Graphics.DrawString(names[i],Font,brush,x,26);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed class KSwitcherUpdateProgress : IDisposable {
|
||||
private Form form;
|
||||
private Label stage, detail, percentage, footer;
|
||||
private UpdateMeter progress;
|
||||
private UpdateSteps steps;
|
||||
private Button done, close;
|
||||
private bool closing;
|
||||
private Exception failure;
|
||||
private readonly ManualResetEvent ready = new ManualResetEvent(false);
|
||||
private readonly Thread thread;
|
||||
[DllImport("user32.dll")] private static extern bool ReleaseCapture();
|
||||
[DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr h,int m,IntPtr w,IntPtr l);
|
||||
[DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(IntPtr h,int a,ref int v,int size);
|
||||
private void Drag(object sender,MouseEventArgs e) { if(e.Button==MouseButtons.Left) { ReleaseCapture(); SendMessage(form.Handle,0xA1,(IntPtr)2,IntPtr.Zero); } }
|
||||
public KSwitcherUpdateProgress() {
|
||||
thread = new Thread(delegate() {
|
||||
try {
|
||||
Application.EnableVisualStyles();
|
||||
form = new Form { Text = "KSwitcher Update", ClientSize = new Size(540,350), BackColor = Color.White,
|
||||
ForeColor = Color.FromArgb(32,36,48), StartPosition = FormStartPosition.CenterScreen,
|
||||
FormBorderStyle = FormBorderStyle.None, Font = new Font("Segoe UI",10), AutoScaleMode = AutoScaleMode.Dpi };
|
||||
var logo = new Panel { Location = new Point(28,24), Size = new Size(34,34), BackColor = Color.FromArgb(79,70,229) };
|
||||
logo.Paint += delegate(object sender,PaintEventArgs e) {
|
||||
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
using(var pen = new Pen(Color.White,4)) { e.Graphics.DrawLine(pen,10,8,10,26); e.Graphics.DrawLine(pen,11,17,25,7); }
|
||||
using(var pen = new Pen(Color.FromArgb(94,234,212),4)) e.Graphics.DrawLine(pen,12,17,25,27);
|
||||
};
|
||||
var brand = new Label { Text = "KSwitcher", Location = new Point(74,22), Size = new Size(260,24), Font = new Font("Segoe UI Semibold",11) };
|
||||
var caption = new Label { Text = "Application update", Location = new Point(74,45), Size = new Size(260,20), ForeColor = Color.FromArgb(111,117,134), Font = new Font("Segoe UI",9) };
|
||||
var minimize = new Button { Text = "\u2013", AccessibleName = "Minimize", Location = new Point(452,20), Size = new Size(32,32), FlatStyle = FlatStyle.Flat, TabStop = false };
|
||||
minimize.FlatAppearance.BorderSize = 0; minimize.Click += delegate { form.WindowState = FormWindowState.Minimized; };
|
||||
close = new Button { Text = "\u00d7", AccessibleName = "Close", Location = new Point(490,20), Size = new Size(32,32), FlatStyle = FlatStyle.Flat, Enabled = false };
|
||||
close.FlatAppearance.BorderSize = 0; close.Click += delegate { form.Close(); };
|
||||
stage = new Label { Text = "Checking for updates", Location = new Point(28,98), Size = new Size(414,36), Font = new Font("Segoe UI Semibold",20) };
|
||||
percentage = new Label { Location = new Point(440,104), Size = new Size(72,30), TextAlign = ContentAlignment.MiddleRight, ForeColor = Color.FromArgb(79,70,229), Font = new Font("Segoe UI Semibold",16) };
|
||||
detail = new Label { Text = "Connecting to the release server", Location = new Point(28,148), Size = new Size(484,42), ForeColor = Color.FromArgb(111,117,134) };
|
||||
progress = new UpdateMeter { Location = new Point(28,202), Size = new Size(484,6), AccessibleName = "Update progress" };
|
||||
steps = new UpdateSteps { Location = new Point(28,230), Size = new Size(484,48), Font = new Font("Segoe UI",9) };
|
||||
var bottom = new Panel { Location = new Point(1,296), Size = new Size(538,53), BackColor = Color.FromArgb(247,248,251) };
|
||||
footer = new Label { Text = "Your settings and history stay with you.", Location = new Point(27,18), Size = new Size(350,22), ForeColor = Color.FromArgb(111,117,134), Font = new Font("Segoe UI",9) };
|
||||
done = new Button { Text = "Done", Location = new Point(410,9), Size = new Size(100,34), BackColor = Color.FromArgb(79,70,229), ForeColor = Color.White, FlatStyle = FlatStyle.Flat, Visible = false };
|
||||
done.FlatAppearance.BorderSize = 0; done.Click += delegate { form.Close(); };
|
||||
bottom.Controls.AddRange(new Control[]{footer,done});
|
||||
form.Controls.AddRange(new Control[]{logo,brand,caption,minimize,close,stage,percentage,detail,progress,steps,bottom});
|
||||
form.MouseDown += Drag; logo.MouseDown += Drag; brand.MouseDown += Drag; caption.MouseDown += Drag;
|
||||
form.Paint += delegate(object sender,PaintEventArgs e) { using(var pen = new Pen(Color.FromArgb(220,223,232))) e.Graphics.DrawRectangle(pen,0,0,form.ClientSize.Width-1,form.ClientSize.Height-1); };
|
||||
form.FormClosing += delegate(object sender, FormClosingEventArgs e) { if (!closing) e.Cancel = true; };
|
||||
form.Shown += delegate { int rounded=2; try { DwmSetWindowAttribute(form.Handle,33,ref rounded,4); } catch { } ready.Set(); };
|
||||
Application.Run(form);
|
||||
} catch(Exception e) { failure = e; ready.Set(); }
|
||||
});
|
||||
thread.IsBackground = true;
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
if (!ready.WaitOne(10000)) throw new Exception("Update progress window did not start.");
|
||||
if (failure != null) throw new Exception("Cannot display update progress.",failure);
|
||||
}
|
||||
public void Report(string title, string text, int percent) {
|
||||
if (form == null || form.IsDisposed) return;
|
||||
form.BeginInvoke((Action)delegate {
|
||||
stage.Text = title; detail.Text = text;
|
||||
progress.Percent = percent < 0 ? -1 : Math.Max(0,Math.Min(100,percent));
|
||||
percentage.Text = percent < 0 ? "" : progress.Percent+"%";
|
||||
int separator = text.IndexOf("% - ");
|
||||
if(separator>=0) detail.Text = text.Substring(separator+4)+" downloaded";
|
||||
if(title.StartsWith("Downloading")) steps.Current=0;
|
||||
else if(title.StartsWith("Verifying") || title.StartsWith("Preparing")) steps.Current=1;
|
||||
else if(title.StartsWith("Installing") || title.StartsWith("Closing")) steps.Current=2;
|
||||
else if(title.StartsWith("Restarting")) steps.Current=3;
|
||||
progress.Invalidate(); steps.Invalidate();
|
||||
});
|
||||
}
|
||||
public void SavePreview(string path) {
|
||||
form.Invoke((Action)delegate {
|
||||
using(var bitmap = new Bitmap(form.Width,form.Height)) {
|
||||
form.DrawToBitmap(bitmap,new Rectangle(0,0,bitmap.Width,bitmap.Height));
|
||||
bitmap.Save(path,System.Drawing.Imaging.ImageFormat.Png);
|
||||
}
|
||||
});
|
||||
}
|
||||
public string Status { get { return (string)form.Invoke((Func<string>)delegate { return stage.Text; }); } }
|
||||
public int Percent { get { return (int)form.Invoke((Func<int>)delegate { return progress.Percent; }); } }
|
||||
public void Finish(string title, string text, bool success) {
|
||||
form.Invoke((Action)delegate {
|
||||
closing = true;
|
||||
stage.Text = title; detail.Text = text;
|
||||
progress.Percent = success ? 100 : 0; percentage.Text = success ? "100%" : "";
|
||||
steps.Complete = success;
|
||||
if(!success) {
|
||||
detail.Visible = false; steps.Visible = false;
|
||||
var result = new TextBox { Text = text, Location = new Point(28,148), Size = new Size(484,126),
|
||||
Multiline = true, ReadOnly = true, BorderStyle = BorderStyle.None,
|
||||
BackColor = Color.White, ScrollBars = ScrollBars.Vertical };
|
||||
form.Controls.Add(result); result.BringToFront(); progress.Visible = false;
|
||||
}
|
||||
footer.Text = success ? "Your settings and history are preserved." : "Review the details above.";
|
||||
close.Enabled = true; done.Visible = true;
|
||||
form.AcceptButton = done; form.CancelButton = done;
|
||||
progress.Invalidate(); steps.Invalidate();
|
||||
});
|
||||
}
|
||||
public void WaitForClose() { thread.Join(); }
|
||||
public void Dispose() {
|
||||
if (form != null && !form.IsDisposed)
|
||||
form.BeginInvoke((Action)delegate { closing = true; form.Close(); });
|
||||
thread.Join(3000);
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
$script:progressWindow = New-Object KSwitcherUpdateProgress
|
||||
}
|
||||
function Show-UpdateProgress([string]$Stage,[string]$Detail,[int]$Percent = -1) {
|
||||
if ($script:progressWindow) {
|
||||
try { $script:progressWindow.Report($Stage,$Detail,$Percent) }
|
||||
catch { Write-Warning 'Could not refresh update progress.' }
|
||||
}
|
||||
}
|
||||
function Complete-UpdateProgress([string]$Title,[string]$Detail,[bool]$Success) {
|
||||
if ($script:progressWindow) {
|
||||
try { $script:progressWindow.Finish($Title,$Detail,$Success); return $true }
|
||||
catch { Write-Warning 'Could not display the update result.' }
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
function Get-StableVersion([string]$Tag) {
|
||||
if ($Tag -notmatch '^(?:v|release-v)?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$') { return $null }
|
||||
@@ -20,7 +203,7 @@ function Assert-ReleaseUrl([string]$Url) {
|
||||
throw 'Release asset URL is outside the KSwitcher repository.'
|
||||
}
|
||||
}
|
||||
function Receive-File([string]$Url,[string]$Path,[long]$Limit) {
|
||||
function Receive-File([string]$Url,[string]$Path,[long]$Limit,[string]$ProgressLabel = '') {
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$request = [Net.HttpWebRequest]::Create($Url)
|
||||
$request.AllowAutoRedirect = $false
|
||||
@@ -36,11 +219,20 @@ function Receive-File([string]$Url,[string]$Path,[long]$Limit) {
|
||||
$buffer = New-Object byte[] 65536
|
||||
$total = 0L
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(60)
|
||||
$lastProgress = [DateTime]::MinValue
|
||||
while (($count = $inputStream.Read($buffer,0,$buffer.Length)) -gt 0) {
|
||||
$total += $count
|
||||
if ($total -gt $Limit -or [DateTime]::UtcNow -gt $deadline) { throw 'Download exceeded size or time limit.' }
|
||||
$outputStream.Write($buffer,0,$count)
|
||||
if ($ProgressLabel -and ([DateTime]::UtcNow - $lastProgress).TotalMilliseconds -ge 100) {
|
||||
$percent = if ($response.ContentLength -gt 0) { [int][Math]::Min(100,100.0*$total/$response.ContentLength) } else { -1 }
|
||||
$detail = if ($percent -ge 0) { '{0}% - {1:N1} / {2:N1} MB' -f $percent,($total/1MB),($response.ContentLength/1MB) } else { '{0:N1} MB received' -f ($total/1MB) }
|
||||
Show-UpdateProgress $ProgressLabel $detail $percent
|
||||
$lastProgress = [DateTime]::UtcNow
|
||||
}
|
||||
}
|
||||
if ($response.ContentLength -ge 0 -and $total -ne $response.ContentLength) { throw 'The download ended before the complete file was received.' }
|
||||
if ($ProgressLabel) { Show-UpdateProgress $ProgressLabel ('Downloaded {0:N1} MB' -f ($total/1MB)) 100 }
|
||||
} finally {
|
||||
if ($outputStream) { $outputStream.Dispose() }
|
||||
if ($inputStream) { $inputStream.Dispose() }
|
||||
@@ -217,11 +409,60 @@ function Undo-Files([string]$Target,[string]$Backup,[Collections.Generic.List[st
|
||||
function Write-Result($Value) {
|
||||
$Value | ConvertTo-Json -Compress | Set-Content -LiteralPath (Join-Path $WorkDirectory 'result.json') -Encoding UTF8
|
||||
}
|
||||
function Write-UpdateJournal([string]$Message) {
|
||||
if (!$Journal) { return }
|
||||
$label = if ($Unattended) { 'LAN update' } else { 'Update' }
|
||||
[IO.File]::AppendAllText($Journal, "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ${label}: $Message`n",
|
||||
[Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
function Stop-UpdateCompanions([string]$Directory) {
|
||||
if (!('KSwitcherUpdateProcessImage' -as [type])) {
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
public static class KSwitcherUpdateProcessImage {
|
||||
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
||||
[DllImport("kernel32.dll", CharSet=CharSet.Unicode)]
|
||||
static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder image, ref int length);
|
||||
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
||||
|
||||
public static string Read(int pid) {
|
||||
var process = OpenProcess(0x1000, false, pid);
|
||||
if (process == IntPtr.Zero) return null;
|
||||
try {
|
||||
var length = 32768;
|
||||
var image = new StringBuilder(length);
|
||||
return QueryFullProcessImageName(process, 0, image, ref length) ? image.ToString() : null;
|
||||
} finally { CloseHandle(process); }
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
$root = [IO.Path]::GetFullPath($Directory).TrimEnd('\')
|
||||
$prefix = [regex]::Escape($root + '\')
|
||||
$pattern = '^' + $prefix + '(?:\.kswitcher-update-[0-9a-f]{32}\\backup\\)?(?:KSwitcher(?:\.(?:Config|Screenshot|Files))?\.exe|tools\\StayHere\.exe)$'
|
||||
foreach ($process in @(Get-Process 'KSwitcher','KSwitcher.Config','KSwitcher.Screenshot','KSwitcher.Files','StayHere' -ErrorAction SilentlyContinue)) {
|
||||
$image = [KSwitcherUpdateProcessImage]::Read($process.Id)
|
||||
if (!$image -and !$process.HasExited) {
|
||||
Write-UpdateJournal "Could not identify $($process.ProcessName) (PID $($process.Id))."
|
||||
}
|
||||
if ($image -notmatch $pattern) { continue }
|
||||
Write-UpdateJournal "Closing $($process.ProcessName) (PID $($process.Id))."
|
||||
if (!$process.HasExited) {
|
||||
try { $process.Kill() } catch { if (!$process.HasExited) { throw } }
|
||||
if (!$process.WaitForExit(10000)) { throw "Could not close $($process.ProcessName) (PID $($process.Id))." }
|
||||
}
|
||||
Write-UpdateJournal "Closed $($process.ProcessName) (PID $($process.Id))."
|
||||
}
|
||||
}
|
||||
if ($Library) { return }
|
||||
$transaction = $null; $parentProcess = $null; $ready = $null; $started = $null
|
||||
$changed = [Collections.Generic.List[string]]::new()
|
||||
$parentExited = $false; $success = $false; $preserveBackup = $false; $child = $null
|
||||
$parentExited = $false; $success = $false; $preserveBackup = $false; $child = $null; $uiFinished = $false
|
||||
try {
|
||||
if (!$Unattended -and ($ShowProgress -or $Mode -eq 'Install')) { Start-UpdateProgress }
|
||||
$current = Get-StableVersion $CurrentVersion
|
||||
if (!$current) { throw 'Invalid installed version.' }
|
||||
if ($Mode -eq 'Install') {
|
||||
@@ -234,33 +475,49 @@ try {
|
||||
$metadata = Join-Path $WorkDirectory 'releases.json'
|
||||
Receive-File 'https://gitea.hrynco.com/api/v1/repos/hrynco/hrynco-kswitcher/releases?limit=100' $metadata 2MB
|
||||
$release = Select-Release (Get-Content -LiteralPath $metadata -Raw | ConvertFrom-Json) $current
|
||||
if (!$release) { Write-Result @{state='current'}; exit 0 }
|
||||
if (!$release) {
|
||||
if ($Unattended) { Write-UpdateJournal "No newer stable release is available ($CurrentVersion)." }
|
||||
Write-Result @{state='current'}; exit 0
|
||||
}
|
||||
if ($Mode -eq 'Check') { Write-Result @{state='available';version=$release.version}; exit 0 }
|
||||
if ($ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' }
|
||||
if (!$Unattended -and $ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' }
|
||||
Assert-PlainDirectory $InstallDirectory
|
||||
$transaction = Join-Path $InstallDirectory ('.kswitcher-update-'+[guid]::NewGuid().ToString('N'))
|
||||
$stage = Join-Path $transaction 'stage'; $backup = Join-Path $transaction 'backup'
|
||||
[IO.Directory]::CreateDirectory($stage) | Out-Null
|
||||
$archive = Join-Path $WorkDirectory 'release.zip'; $checksum = Join-Path $WorkDirectory 'SHA256SUMS.txt'
|
||||
Receive-File $release.zip $archive 50MB
|
||||
Show-UpdateProgress 'Downloading update' $release.version 0
|
||||
Receive-File $release.zip $archive 50MB 'Downloading update'
|
||||
Show-UpdateProgress 'Verifying download' 'Checking the archive SHA-256 checksum'
|
||||
Receive-File $release.checksum $checksum 64KB
|
||||
Assert-Checksum $archive $checksum
|
||||
Show-UpdateProgress 'Preparing installation' 'Validating and unpacking the release files'
|
||||
Expand-Release $archive $stage (Get-StableVersion $release.version)
|
||||
$screenshotPath = [IO.Path]::GetFullPath((Join-Path $InstallDirectory 'KSwitcher.Screenshot.exe'))
|
||||
if (Get-Process 'KSwitcher.Screenshot' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $screenshotPath }) { throw 'Close screenshot editors before installing an update.' }
|
||||
Write-UpdateJournal "Verified $($release.version). Closing KSwitcher (PID $ParentProcessId)."
|
||||
Write-Result @{state='prepared';version=$release.version}
|
||||
Show-UpdateProgress 'Closing KSwitcher' 'Waiting for the running application to exit safely'
|
||||
$ready.Set() | Out-Null
|
||||
if (!$parentProcess.WaitForExit(120000)) { throw 'KSwitcher did not exit; the installed files were not changed.' }
|
||||
$parentExited = $true
|
||||
Write-UpdateJournal "Closed KSwitcher (PID $ParentProcessId)."
|
||||
Show-UpdateProgress 'Closing KSwitcher components' 'Closing Files, editors, Settings and StayHere'
|
||||
Stop-UpdateCompanions $InstallDirectory
|
||||
Show-UpdateProgress 'Installing update' 'Replacing application files; keeping your personal data'
|
||||
Install-Files $stage $InstallDirectory $backup $changed
|
||||
$startedName = 'Local\KSwitcher.Update.Started.'+[guid]::NewGuid().ToString('N')
|
||||
$started = [Threading.EventWaitHandle]::new($false,[Threading.EventResetMode]::ManualReset,$startedName)
|
||||
Show-UpdateProgress 'Restarting KSwitcher' 'Waiting for the updated application to confirm startup'
|
||||
$child = Start-Process -FilePath (Join-Path $InstallDirectory 'KSwitcher.exe') -ArgumentList "--update-ready-event=$startedName" -WorkingDirectory $InstallDirectory -WindowStyle Hidden -PassThru
|
||||
if (!$started.WaitOne(30000) -or $child.HasExited) { throw 'The updated application did not confirm startup.' }
|
||||
$success = $true
|
||||
try { Write-UpdateJournal "Completed $($release.version). KSwitcher restarted." } catch {}
|
||||
if ($script:progressWindow) {
|
||||
$uiFinished = Complete-UpdateProgress 'Update completed' "KSwitcher $(Get-StableVersion $release.version) is now running." $true
|
||||
}
|
||||
} catch {
|
||||
$message = $_.Exception.Message
|
||||
if ($parentExited) {
|
||||
Show-UpdateProgress 'Restoring previous version' 'The update failed; recovering the previous installation'
|
||||
try {
|
||||
if ($child -and !$child.HasExited) { $child.Kill(); $child.WaitForExit() }
|
||||
Undo-Files $InstallDirectory $backup $changed
|
||||
@@ -272,9 +529,14 @@ try {
|
||||
}
|
||||
}
|
||||
Write-Result @{state='error';error=$message}
|
||||
if ($ready -and $ready.WaitOne(0)) {
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
[Windows.Forms.MessageBox]::Show($message,'KSwitcher update failed') | Out-Null
|
||||
try { Write-UpdateJournal "Failed. $($message -replace '[\r\n]+',' ')" } catch {}
|
||||
if (!$Unattended -and $ready -and $ready.WaitOne(0)) {
|
||||
if ($script:progressWindow) {
|
||||
$uiFinished = Complete-UpdateProgress 'Update failed' $message $false
|
||||
} else {
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
[Windows.Forms.MessageBox]::Show($message,'KSwitcher update failed') | Out-Null
|
||||
}
|
||||
}
|
||||
exit 1
|
||||
} finally {
|
||||
@@ -291,4 +553,8 @@ try {
|
||||
Remove-Item -LiteralPath $WorkDirectory -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
if ($script:progressWindow) {
|
||||
if ($uiFinished) { $script:progressWindow.WaitForClose() }
|
||||
$script:progressWindow.Dispose(); $script:progressWindow = $null
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,11 @@
|
||||
#include "autocorrect.h"
|
||||
#include "storage.h"
|
||||
#include "update.h"
|
||||
#include "sync.h"
|
||||
#include "chat_context.h"
|
||||
#include "lan.h"
|
||||
#include "mouse_buttons.h"
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
@@ -16,6 +21,7 @@ inline constexpr UINT TrayMessage = WM_APP + 1, ErrorMessage = WM_APP + 2, Histo
|
||||
inline constexpr int Toggle = 1, Case = 2, Translit = 3, Undo = 4, ShowHistory = 5, AutoCorrect = 6,
|
||||
Screenshot = 7, Direct = 100;
|
||||
inline constexpr UINT AutoCorrectMessage = WM_APP + 6;
|
||||
inline constexpr UINT ReplayTypingMessage = WM_APP + 30;
|
||||
inline constexpr UINT CaptureHotkeyMessage = WM_APP + 5;
|
||||
struct LastTransform
|
||||
{
|
||||
@@ -31,14 +37,21 @@ class App
|
||||
{
|
||||
public:
|
||||
HWND window{}, historyWindow{}, settingsWindow{}, snippetsWindow{};
|
||||
HWND historyService{}; // Non-null only in the short-lived history UI process.
|
||||
bool isolateHistory{};
|
||||
unsigned historyEntryWindows{};
|
||||
std::wstring historySelection, historyTop, historyQuery;
|
||||
bool historyPinnedOnly{};
|
||||
std::vector<std::string> historyComputers;
|
||||
HINSTANCE instance{};
|
||||
std::filesystem::path data;
|
||||
std::vector<Layout> layouts;
|
||||
Settings settings;
|
||||
std::unique_ptr<History> history;
|
||||
AutoCorrector autoCorrector;
|
||||
AutoCorrector autoPredictor; // Preloaded, hook-thread-only lookup; no file access while typing.
|
||||
std::atomic<bool> busy{false}, suspended{false};
|
||||
std::atomic<DWORD> ownSequence{0};
|
||||
std::atomic<DWORD> ownSequence{0}, lanSequence{0};
|
||||
std::atomic<uint64_t> inputVersion{0};
|
||||
std::atomic<ULONGLONG> pauseUntil{0};
|
||||
HWND pasteTarget{};
|
||||
@@ -52,15 +65,18 @@ class App
|
||||
bool smoke{};
|
||||
int startCommand{};
|
||||
std::wstring updateStartupEvent;
|
||||
App(HINSTANCE, bool = false, const std::filesystem::path &dataRoot = {});
|
||||
App(HINSTANCE, bool = false, const std::filesystem::path &dataRoot = {}, HWND historyService = nullptr);
|
||||
~App();
|
||||
int execute();
|
||||
void dispatch(int);
|
||||
void transform(int, int snippet = -1);
|
||||
void transform(int, int snippet = -1, size_t snippetLength = 0, HWND snippetEditor = nullptr);
|
||||
void pasteEntry(std::wstring, bool plain);
|
||||
void recognizeEntry(std::wstring);
|
||||
void captureHistory();
|
||||
void publishClipboard(Clip, const std::wstring &);
|
||||
void receiveClipboard();
|
||||
void enqueue(std::function<void()>);
|
||||
void enqueueHistorySearch(std::function<void()>);
|
||||
void report(const std::wstring &);
|
||||
void trayMenu();
|
||||
void addTray();
|
||||
@@ -68,39 +84,137 @@ class App
|
||||
void applySettings(const Settings &);
|
||||
void reloadLayouts();
|
||||
void clearHistory();
|
||||
void openHistoryProcess();
|
||||
void refreshHistoryProcess();
|
||||
void remoteHistory(const char *action, const std::wstring &id = {}, bool plain = false);
|
||||
LRESULT historyRequest(HWND, const COPYDATASTRUCT &);
|
||||
void saveHistoryView(const std::wstring &, const std::wstring &, const std::wstring &, bool);
|
||||
void clearLog(bool previous);
|
||||
void setHotkeyCapture(HWND);
|
||||
bool isHotkey(DWORD, UINT);
|
||||
void keyboard(const KBDLLHOOKSTRUCT &, UINT modifiers);
|
||||
bool handleKeyboard(const KBDLLHOOKSTRUCT &, bool down, UINT modifiers);
|
||||
void resetInput();
|
||||
void resetLanInput();
|
||||
void checkUpdate(bool interactive, bool install = false, const std::wstring &version = {});
|
||||
std::wstring syncCommand(int action = 0, const std::vector<SyncChoice> &choices = {});
|
||||
Bytes syncConflictData();
|
||||
Bytes lanCommand(const Bytes &);
|
||||
void pollSync();
|
||||
static App *current;
|
||||
|
||||
private:
|
||||
friend struct InputRegressionAccess;
|
||||
void releaseIdleMemory(ULONGLONG now);
|
||||
void applySettings(const Settings &, bool validateOcrInstallation);
|
||||
void checkAutostartPath();
|
||||
bool checkingAutostartPath{};
|
||||
HHOOK keyboardHook{}, mouseHook{};
|
||||
struct MousePress
|
||||
{
|
||||
HWND target{};
|
||||
POINT point{};
|
||||
ULONGLONG started{};
|
||||
MouseAction action;
|
||||
bool held{}, waitForSecond{};
|
||||
};
|
||||
std::array<MousePress, std::size(MouseButtonNames)> mousePresses{};
|
||||
std::array<MousePress, std::size(MouseButtonNames)> pendingMouseClicks{};
|
||||
std::deque<MousePress> mouseActions;
|
||||
HWND mouseWheelTarget{};
|
||||
int mouseWheelSignal{-1}, mouseWheelRemainder{};
|
||||
void queueMouseAction(MousePress);
|
||||
void flushMouseClicks();
|
||||
void beginMouseVolume(int button);
|
||||
void repeatMouseVolume(int button);
|
||||
bool volumeButtonHeld() const;
|
||||
void dispatchMouseActions();
|
||||
std::unique_ptr<LanService> lanService;
|
||||
HANDLE historyProcess{};
|
||||
std::mutex jobsMutex;
|
||||
std::condition_variable jobsReady;
|
||||
std::deque<std::function<void()>> jobs;
|
||||
std::thread worker;
|
||||
HANDLE notificationRegistration{};
|
||||
std::thread historySearchWorker;
|
||||
std::condition_variable historySearchReady;
|
||||
std::function<void()> pendingHistorySearch;
|
||||
std::thread historyOcrWorker;
|
||||
std::condition_variable historyOcrReady;
|
||||
bool historyOcrRequested{};
|
||||
Settings historyOcrSettings;
|
||||
void scheduleHistoryOcr(const Settings &);
|
||||
std::thread updateWorker;
|
||||
bool updateRunning{}, installingUpdate{};
|
||||
std::wstring availableUpdate;
|
||||
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{}, lanUpdatePending{};
|
||||
std::wstring availableUpdate, notifiedUpdate;
|
||||
bool (*updateNotifier)(const std::wstring &){};
|
||||
bool stop{};
|
||||
UINT taskbarCreated{};
|
||||
uint64_t pendingAutoVersion{};
|
||||
bool trayRetryPending{};
|
||||
uint64_t transformAttempt{}, previousAttemptVersion{};
|
||||
size_t incomingLanFileCount{};
|
||||
bool incomingFileBalloon{};
|
||||
std::atomic<uint64_t> activeTransformAttempt{};
|
||||
ULONGLONG previousAttemptAt{};
|
||||
HWND previousAttemptWindow{};
|
||||
int previousAttemptCommand{}, repeatAttempts{};
|
||||
std::vector<std::pair<int, Hotkey>> hookBindings;
|
||||
Hotkey registeredFilesHotkey{};
|
||||
int filesHotkeyId{};
|
||||
HotkeyHook hotkeyHook;
|
||||
ChatSwitchHook chatSwitchHook;
|
||||
HWND chatWindow{};
|
||||
std::wstring activeChat, activeChatTitle;
|
||||
void refreshChatContext();
|
||||
void switchChatLayout(bool reverse);
|
||||
HWND typingTarget{};
|
||||
bool autoPending{};
|
||||
int snippetPending = -1;
|
||||
size_t snippetPendingLength{};
|
||||
HWND snippetPendingEditor{};
|
||||
bool snippetTyping{};
|
||||
HWND snippetPopup{}, snippetTarget{}, snippetFocus{};
|
||||
uint64_t snippetPopupVersion{};
|
||||
size_t snippetPrefixLength{}, snippetSelection{};
|
||||
bool snippetNavigated{};
|
||||
int snippetRowHeight{};
|
||||
UINT snippetDpi{96};
|
||||
RECT snippetPopupAnchor{};
|
||||
bool snippetCaretPending{};
|
||||
std::optional<RECT> snippetCaret;
|
||||
std::vector<std::pair<std::wstring, std::vector<std::wstring>>> snippetTriggers;
|
||||
std::vector<size_t> snippetMatches;
|
||||
std::array<bool, 256> snippetKeys{};
|
||||
void matchSnippets(HWND, bool expandExact);
|
||||
bool queueSnippet(HWND, size_t index, size_t length, HWND editor = nullptr);
|
||||
void showSnippetPopup();
|
||||
void placeSnippetPopup(RECT);
|
||||
void hideSnippetPopup();
|
||||
bool snippetPopupCurrent() const;
|
||||
bool handleSnippetKey(DWORD, UINT);
|
||||
void selectSnippet(size_t);
|
||||
static LRESULT CALLBACK snippetPopupProc(HWND, UINT, WPARAM, LPARAM);
|
||||
std::vector<INPUT> deferredTyping;
|
||||
bool beginTypingDeferral(HWND, uint64_t, bool snippet = false);
|
||||
void replayTyping();
|
||||
static LRESULT CALLBACK windowProc(HWND, UINT, WPARAM, LPARAM);
|
||||
static LRESULT CALLBACK keyProc(int, WPARAM, LPARAM);
|
||||
static LRESULT keyboardAfterHooks(int, WPARAM, LPARAM, LRESULT);
|
||||
static LRESULT CALLBACK mouseProc(int, WPARAM, LPARAM);
|
||||
};
|
||||
void showHistory(App &);
|
||||
void showScreenshot(App &);
|
||||
void showHistory(App &, bool visible = true);
|
||||
void launchScreenshot(App &);
|
||||
void launchScreenshotEditor(App &, const Clip &);
|
||||
void refreshHistory(App &);
|
||||
void showSettings(App &, bool visible = true);
|
||||
void showLogs(App &);
|
||||
|
||||
@@ -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,116 @@
|
||||
// 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 syncStatus = L"Sync did not start. Wait for the current text operation to finish, then try again.";
|
||||
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 = action == 2 ? L"Downloading remote settings from OpenBao..." :
|
||||
action == 3 ? L"Uploading local settings to OpenBao..." : 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()); }
|
||||
if (!result.success)
|
||||
result.status = std::wstring(action == 2 ? L"Download failed. Local settings were not changed. " :
|
||||
action == 3 ? L"Upload failed. " : L"Synchronization failed. ") + result.status;
|
||||
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));
|
||||
// A restored OCR configuration can precede the optional local installation.
|
||||
applySettings(next, false);
|
||||
syncStatus += L" Changes applied on this PC; local backup saved.";
|
||||
}
|
||||
else syncStatus += result.conflicts.empty() ? L" This PC's settings are already up to date; no local changes needed." :
|
||||
L" No local settings were changed; conflicts still need your choice.";
|
||||
saveSyncBase(data, syncConnection, result.base.empty() ? result.settings : result.base);
|
||||
if (result.downloaded)
|
||||
{
|
||||
if (settingsWindow) SendMessageW(settingsWindow, ConfigSettingsDownloaded, 0, 0);
|
||||
if (auto config = FindWindowW(L"KSwitcher.Config", nullptr);
|
||||
config && configurationPeer(config, L"KSwitcher.Config.exe"))
|
||||
PostMessageW(config, ConfigSettingsDownloaded, 0, 0);
|
||||
}
|
||||
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; }
|
||||
}
|
||||
@@ -34,81 +34,169 @@ std::wstring layoutLanguage(const Layout &layout)
|
||||
return {};
|
||||
}
|
||||
}
|
||||
bool safeAutoWord(const std::wstring &word, int minimumLength)
|
||||
bool safeAutoWord(const std::wstring &word, int minimumLength, bool allowUppercase)
|
||||
{
|
||||
if (minimumLength < 1 || minimumLength > 32 || word.size() < (size_t)minimumLength || word.size() > 32 ||
|
||||
!std::all_of(word.begin(), word.end(), letter))
|
||||
return false;
|
||||
auto small = lower(word);
|
||||
return word == small || (word.substr(1) == small.substr(1) && word != upper(word));
|
||||
const bool allUppercase = word == upper(word);
|
||||
return word == small || (allUppercase ? allowUppercase : word.substr(1) == small.substr(1));
|
||||
}
|
||||
std::string_view AutoCorrector::Dictionary::word(size_t index) const
|
||||
namespace {
|
||||
constexpr size_t DictionaryBlockWords = 32;
|
||||
}
|
||||
std::string_view AutoCorrector::Dictionary::word(size_t block) const
|
||||
{
|
||||
auto start = offsets[index];
|
||||
auto end = bytes.find('\t', start);
|
||||
return std::string_view(bytes).substr(start, end - start);
|
||||
size_t start = offsets[block];
|
||||
// Every block starts with a complete word (zero shared prefix).
|
||||
size_t length = static_cast<unsigned char>(bytes[start++]) & 15;
|
||||
if (length == 15) length = static_cast<unsigned char>(bytes[start++]);
|
||||
return std::string_view(bytes).substr(start, length);
|
||||
}
|
||||
AutoCorrector::Dictionary::Dictionary(const std::filesystem::path &path)
|
||||
{
|
||||
auto raw = readFile(path, 2 * 1024 * 1024);
|
||||
bytes.assign(raw.begin(), raw.end());
|
||||
for (size_t start = 0; start < bytes.size();)
|
||||
const auto raw = readFile(path, 2 * 1024 * 1024);
|
||||
const std::string_view source(reinterpret_cast<const char *>(raw.data()), raw.size());
|
||||
std::vector<uint32_t> lines;
|
||||
lines.reserve(std::count(source.begin(), source.end(), '\n') + 1);
|
||||
for (size_t start = 0; start < source.size();)
|
||||
{
|
||||
auto end = bytes.find('\n', start);
|
||||
if (end == bytes.npos)
|
||||
end = bytes.size();
|
||||
auto tab = bytes.find('\t', start);
|
||||
if (tab == bytes.npos || tab >= end || tab == start || tab - start > 160)
|
||||
auto end = source.find('\n', start);
|
||||
if (end == source.npos) end = source.size();
|
||||
auto tab = source.find('\t', start);
|
||||
if (tab == source.npos || tab >= end || tab == start || tab - start > 160)
|
||||
throw std::runtime_error("Invalid auto-correction dictionary");
|
||||
int rank{};
|
||||
auto rankEnd = end > tab + 1 && bytes[end - 1] == '\r' ? end - 1 : end;
|
||||
auto parse = std::from_chars(bytes.data() + tab + 1, bytes.data() + rankEnd, rank);
|
||||
if (parse.ec != std::errc() || parse.ptr != bytes.data() + rankEnd || rank <= 0)
|
||||
auto rankEnd = end > tab + 1 && source[end - 1] == '\r' ? end - 1 : end;
|
||||
auto parse = std::from_chars(source.data() + tab + 1, source.data() + rankEnd, rank);
|
||||
if (parse.ec != std::errc() || parse.ptr != source.data() + rankEnd || rank <= 0)
|
||||
throw std::runtime_error("Invalid dictionary rank");
|
||||
offsets.push_back((uint32_t)start);
|
||||
lines.push_back(static_cast<uint32_t>(start));
|
||||
start = end + 1;
|
||||
}
|
||||
if (offsets.empty())
|
||||
throw std::runtime_error("Empty auto-correction dictionary");
|
||||
for (size_t i = 1; i < offsets.size(); ++i)
|
||||
if (word(i - 1) >= word(i))
|
||||
throw std::runtime_error("Dictionary must be uniquely sorted");
|
||||
offsets.shrink_to_fit();
|
||||
bytes.shrink_to_fit();
|
||||
if (lines.empty()) throw std::runtime_error("Empty auto-correction dictionary");
|
||||
auto entry = [&](uint32_t offset) { return source.substr(offset, source.find('\t', offset) - offset); };
|
||||
auto frequency = [&](uint32_t offset) {
|
||||
int rank{};
|
||||
auto start = offset + entry(offset).size() + 1;
|
||||
std::from_chars(source.data() + start, source.data() + source.size(), rank);
|
||||
return rank;
|
||||
};
|
||||
std::sort(lines.begin(), lines.end(), [&](uint32_t a, uint32_t b) {
|
||||
return entry(a) == entry(b) ? frequency(a) < frequency(b) : entry(a) < entry(b);
|
||||
});
|
||||
lines.erase(std::unique(lines.begin(), lines.end(), [&](uint32_t a, uint32_t b) {
|
||||
return entry(a) == entry(b);
|
||||
}), lines.end());
|
||||
offsets.reserve((lines.size() + DictionaryBlockWords - 1) / DictionaryBlockWords);
|
||||
std::string_view previous;
|
||||
// Allocate the packed payload exactly once. Geometric growth and a final
|
||||
// shrink otherwise leave discarded buffers in the resident process heap.
|
||||
size_t packedSize = 0;
|
||||
for (size_t i = 0; i < lines.size(); ++i)
|
||||
{
|
||||
auto current = entry(lines[i]);
|
||||
size_t prefix = 0;
|
||||
if (i % DictionaryBlockWords != 0)
|
||||
while (prefix < std::min(previous.size(), current.size()) && previous[prefix] == current[prefix]) ++prefix;
|
||||
auto suffix = current.size() - prefix;
|
||||
packedSize += 1 + (prefix >= 15) + (suffix >= 15) + suffix + 2;
|
||||
auto rank = static_cast<uint32_t>(frequency(lines[i]));
|
||||
if (rank >= 65535)
|
||||
do { ++packedSize; rank >>= 7; } while (rank);
|
||||
previous = current;
|
||||
}
|
||||
bytes.reserve(packedSize);
|
||||
previous = {};
|
||||
for (size_t i = 0; i < lines.size(); ++i)
|
||||
{
|
||||
auto current = entry(lines[i]);
|
||||
size_t prefix = 0;
|
||||
if (i % DictionaryBlockWords == 0)
|
||||
offsets.push_back(static_cast<uint32_t>(bytes.size()));
|
||||
else
|
||||
while (prefix < std::min(previous.size(), current.size()) && previous[prefix] == current[prefix]) ++prefix;
|
||||
size_t suffix = current.size() - prefix;
|
||||
bytes.push_back(static_cast<char>((std::min(prefix, size_t(15)) << 4) | std::min(suffix, size_t(15))));
|
||||
if (prefix >= 15) bytes.push_back(static_cast<char>(prefix));
|
||||
if (suffix >= 15) bytes.push_back(static_cast<char>(suffix));
|
||||
bytes.append(current.substr(prefix));
|
||||
auto rank = static_cast<uint32_t>(frequency(lines[i]));
|
||||
auto shortRank = std::min(rank, uint32_t(65535));
|
||||
bytes.push_back(static_cast<char>(shortRank & 255));
|
||||
bytes.push_back(static_cast<char>(shortRank >> 8));
|
||||
if (rank >= 65535)
|
||||
do {
|
||||
auto next = rank & 127;
|
||||
rank >>= 7;
|
||||
bytes.push_back(static_cast<char>(next | (rank ? 128 : 0)));
|
||||
} while (rank);
|
||||
previous = current;
|
||||
}
|
||||
}
|
||||
int AutoCorrector::Dictionary::rank(const std::wstring &text) const
|
||||
{
|
||||
auto key = utf8(lower(text));
|
||||
size_t begin = 0, end = offsets.size();
|
||||
// Find the last block whose first word is <= the search key.
|
||||
while (begin < end)
|
||||
{
|
||||
auto mid = begin + (end - begin) / 2;
|
||||
if (word(mid) < key)
|
||||
begin = mid + 1;
|
||||
else
|
||||
end = mid;
|
||||
if (word(mid) <= key) begin = mid + 1;
|
||||
else end = mid;
|
||||
}
|
||||
if (begin == offsets.size() || word(begin) != key)
|
||||
return 0;
|
||||
auto start = offsets[begin] + word(begin).size() + 1;
|
||||
int rank{};
|
||||
std::from_chars(bytes.data() + start, bytes.data() + bytes.size(), rank);
|
||||
return rank;
|
||||
if (!begin) return 0;
|
||||
size_t block = begin - 1;
|
||||
size_t at = offsets[block];
|
||||
const size_t limit = begin < offsets.size() ? offsets[begin] : bytes.size();
|
||||
char decoded[160]; // The loader validates lengths; lookup never allocates a decoded word.
|
||||
while (at < limit)
|
||||
{
|
||||
auto lengths = static_cast<unsigned char>(bytes[at++]);
|
||||
size_t prefix = lengths >> 4, suffix = lengths & 15;
|
||||
if (prefix == 15) prefix = static_cast<unsigned char>(bytes[at++]);
|
||||
if (suffix == 15) suffix = static_cast<unsigned char>(bytes[at++]);
|
||||
memcpy(decoded + prefix, bytes.data() + at, suffix);
|
||||
at += suffix;
|
||||
uint32_t rank = static_cast<unsigned char>(bytes[at]) |
|
||||
(uint32_t(static_cast<unsigned char>(bytes[at + 1])) << 8);
|
||||
at += 2;
|
||||
if (rank == 65535) {
|
||||
rank = 0;
|
||||
uint32_t shift = 0;
|
||||
unsigned char part;
|
||||
do {
|
||||
part = static_cast<unsigned char>(bytes[at++]);
|
||||
rank |= uint32_t(part & 127) << shift;
|
||||
shift += 7;
|
||||
} while (part & 128);
|
||||
}
|
||||
auto compared = std::string_view(decoded, size_t(prefix) + suffix).compare(key);
|
||||
if (compared == 0) return static_cast<int>(rank);
|
||||
if (compared > 0) return 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
void AutoCorrector::configure(const std::filesystem::path &folder, const std::vector<std::wstring> &wanted)
|
||||
{
|
||||
if (languages == wanted)
|
||||
return;
|
||||
std::map<std::wstring, Dictionary> next;
|
||||
std::map<std::wstring, std::shared_ptr<const Dictionary>> next;
|
||||
for (auto &lang : wanted)
|
||||
{
|
||||
if (lang != L"en" && lang != L"uk" && lang != L"ru")
|
||||
throw std::runtime_error("Unsupported dictionary language");
|
||||
next.emplace(lang, Dictionary(folder / (lang + L".txt")));
|
||||
next.emplace(lang, std::make_shared<const Dictionary>(folder / (lang + L".txt")));
|
||||
}
|
||||
dictionaries = std::move(next);
|
||||
languages = wanted;
|
||||
}
|
||||
void AutoCorrector::shareDictionaries(const AutoCorrector &source)
|
||||
{
|
||||
dictionaries = source.dictionaries;
|
||||
languages = source.languages;
|
||||
}
|
||||
void AutoCorrector::reject(std::wstring word, const Settings &settings)
|
||||
{
|
||||
while (!word.empty() && openingDelimiter(word.front(), settings))
|
||||
@@ -123,7 +211,7 @@ size_t AutoCorrector::memoryBytes() const
|
||||
{
|
||||
size_t bytes = 0;
|
||||
for (auto &[language, d] : dictionaries)
|
||||
bytes += d.bytes.capacity() + d.offsets.capacity() * sizeof(uint32_t);
|
||||
bytes += d->bytes.capacity() + d->offsets.capacity() * sizeof(uint32_t);
|
||||
return bytes;
|
||||
}
|
||||
std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed, int source,
|
||||
@@ -143,7 +231,11 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
||||
suffix.insert(suffix.begin(), word.back());
|
||||
word.pop_back();
|
||||
}
|
||||
if (!safeAutoWord(word, settings.autoMinLength) || suffix.size() > 6 || rejected.contains(lower(word)))
|
||||
// Punctuation keys can be letters in the target layout (for example ',' -> 'б').
|
||||
// Validate letters and capitalization after conversion, not before it.
|
||||
if (settings.autoMinLength < 1 || settings.autoMinLength > 32 ||
|
||||
word.size() < (size_t)settings.autoMinLength || word.size() > 32 ||
|
||||
suffix.size() > 6 || rejected.contains(lower(word)))
|
||||
return {};
|
||||
for (auto &never : settings.autoNever)
|
||||
if (lower(never) == lower(word))
|
||||
@@ -151,12 +243,44 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
||||
auto sourceLanguage = layoutLanguage(layouts[source]);
|
||||
if (!dictionaries.contains(sourceLanguage))
|
||||
return {};
|
||||
const std::wstring alphabet = sourceLanguage == L"en" ? L"abcdefghijklmnopqrstuvwxyz" :
|
||||
sourceLanguage == L"uk" ? L"абвгґдеєжзиіїйклмнопрстуфхцчшщьюя" : L"абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
|
||||
auto small = lower(word);
|
||||
bool inCycle = std::find(settings.cycle.begin(), settings.cycle.end(), layouts[source].id) != settings.cycle.end();
|
||||
bool sameLanguage = safeAutoWord(word, settings.autoMinLength) &&
|
||||
small.find_first_not_of(alphabet) == small.npos && inCycle;
|
||||
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 && inCycle)
|
||||
{
|
||||
auto replacement = settings.autoReplacements.find(small);
|
||||
if (replacement != settings.autoReplacements.end() &&
|
||||
(word == small || (word.substr(1) == small.substr(1) && word != upper(word))) &&
|
||||
validAutoReplacementSource(small, alphabet) &&
|
||||
validAutoCorrection(replacement->second, alphabet))
|
||||
return sameLayout(replacement->second);
|
||||
}
|
||||
auto personal = [&](const std::wstring &language, const std::wstring &candidate)
|
||||
{
|
||||
auto found = settings.autoWords.find(language);
|
||||
return found != settings.autoWords.end() &&
|
||||
std::any_of(found->second.begin(), found->second.end(), [&](const std::wstring &known)
|
||||
{ return lower(known) == lower(candidate); });
|
||||
};
|
||||
// Valid words from either selected language are never changed.
|
||||
for (auto &[language, d] : dictionaries)
|
||||
if (d.rank(word))
|
||||
if (d->rank(word) || personal(language, word))
|
||||
return {};
|
||||
std::optional<AutoSuggestion> candidate;
|
||||
int matches = 0;
|
||||
std::optional<std::wstring> matchedText;
|
||||
auto priority = [&](int layout)
|
||||
{
|
||||
auto language = layoutLanguage(layouts[layout]);
|
||||
return std::find(settings.autoLanguages.begin(), settings.autoLanguages.end(), language) - settings.autoLanguages.begin();
|
||||
};
|
||||
for (int i = 0; i < (int)layouts.size(); ++i)
|
||||
{
|
||||
if (i == source || !layouts[i].convertible ||
|
||||
@@ -166,17 +290,72 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
|
||||
if (dictionary == dictionaries.end())
|
||||
continue;
|
||||
auto converted = convert(word, layouts[source], layouts[i], true);
|
||||
if (converted == word || !safeAutoWord(converted, settings.autoMinLength))
|
||||
if (converted == word)
|
||||
continue;
|
||||
int rank = dictionary->second.rank(converted);
|
||||
const bool knownPersonal = personal(dictionary->first, converted);
|
||||
auto letters = converted;
|
||||
if (knownPersonal)
|
||||
std::erase(letters, L'-');
|
||||
if (!safeAutoWord(letters, settings.autoMinLength, knownPersonal))
|
||||
continue;
|
||||
int rank = knownPersonal ? 1 : dictionary->second->rank(converted);
|
||||
if (!rank)
|
||||
continue;
|
||||
if (++matches > 1)
|
||||
if (matchedText && *matchedText != converted)
|
||||
return {};
|
||||
if (settings.autoMaxRank == 0 || rank <= settings.autoMaxRank)
|
||||
matchedText = converted;
|
||||
if ((settings.autoMaxRank == 0 || rank <= settings.autoMaxRank) &&
|
||||
(!candidate || priority(i) < priority(candidate->target)))
|
||||
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,
|
||||
const Layout &physical, const Settings &settings)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
#include "platform.h"
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <string_view>
|
||||
namespace ks
|
||||
@@ -11,30 +12,37 @@ struct AutoSuggestion
|
||||
std::wstring text;
|
||||
};
|
||||
std::wstring layoutLanguage(const Layout &);
|
||||
bool safeAutoWord(const std::wstring &, int minimumLength = 3);
|
||||
bool safeAutoWord(const std::wstring &, int minimumLength = 3, bool allowUppercase = false);
|
||||
bool autoClosingSelection(const std::wstring &, const Settings & = {});
|
||||
int matchAutoInput(const Run &, const std::wstring &, const std::vector<Layout> &, const Layout &,
|
||||
const Settings & = {});
|
||||
bool autoCorrectionAllowed(HWND, const Settings &);
|
||||
class AutoCorrector
|
||||
{
|
||||
friend struct AutoCorrectorRegressionAccess;
|
||||
struct Dictionary
|
||||
{
|
||||
// Front-coded UTF-8 words in independently searchable blocks of 32.
|
||||
// Prefix/suffix lengths share a byte (15 escapes to a full byte length).
|
||||
// Ranks use two bytes; 65535 escapes to a varint for larger custom ranks.
|
||||
std::string bytes;
|
||||
std::vector<uint32_t> offsets;
|
||||
std::string_view word(size_t) const;
|
||||
explicit Dictionary(const std::filesystem::path &);
|
||||
int rank(const std::wstring &) const;
|
||||
};
|
||||
std::map<std::wstring, Dictionary> dictionaries;
|
||||
std::map<std::wstring, std::shared_ptr<const Dictionary>> dictionaries;
|
||||
std::vector<std::wstring> languages;
|
||||
std::set<std::wstring> rejected;
|
||||
|
||||
public:
|
||||
void configure(const std::filesystem::path &, const std::vector<std::wstring> &);
|
||||
// Share immutable dictionary storage, keeping each consumer's undo rejections private.
|
||||
void shareDictionaries(const AutoCorrector &);
|
||||
std::optional<AutoSuggestion> suggest(const std::wstring &, int source, const std::vector<Layout> &,
|
||||
const Settings &) const;
|
||||
void reject(std::wstring word, const Settings & = {});
|
||||
// Referenced dictionary payload, including shared storage (do not sum across consumers).
|
||||
size_t memoryBytes() const;
|
||||
};
|
||||
} // namespace ks
|
||||
@@ -27,6 +27,7 @@ template <class T> struct Com
|
||||
struct Str
|
||||
{
|
||||
BSTR value;
|
||||
Str() : value(nullptr) {}
|
||||
Str(const wchar_t *s) : value(SysAllocString(s))
|
||||
{
|
||||
if (!value)
|
||||
@@ -51,10 +52,108 @@ bool missing(HRESULT hr)
|
||||
{
|
||||
return hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
|
||||
}
|
||||
constexpr wchar_t RunKey[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
||||
|
||||
HRESULT openTaskFolder(Com<ITaskService> &service, Com<ITaskFolder> &folder)
|
||||
{
|
||||
HRESULT hr = CoCreateInstance(CLSID_TaskScheduler, nullptr, CLSCTX_INPROC_SERVER, IID_ITaskService,
|
||||
(void **)service.out());
|
||||
VARIANT empty;
|
||||
VariantInit(&empty);
|
||||
if (SUCCEEDED(hr))
|
||||
hr = service->Connect(empty, empty, empty, empty);
|
||||
if (SUCCEEDED(hr))
|
||||
hr = service->GetFolder(Str(L"\\"), folder.out());
|
||||
return hr;
|
||||
}
|
||||
|
||||
bool sameAccount(const wchar_t *account)
|
||||
{
|
||||
auto sid = currentUserSid();
|
||||
if (sid == account)
|
||||
return true;
|
||||
DWORD sidSize{}, domainSize{};
|
||||
SID_NAME_USE use{};
|
||||
LookupAccountNameW(nullptr, account, nullptr, &sidSize, nullptr, &domainSize, &use);
|
||||
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
|
||||
return false;
|
||||
Bytes accountSid(sidSize);
|
||||
std::wstring domain(domainSize, L'\0');
|
||||
if (!LookupAccountNameW(nullptr, account, accountSid.data(), &sidSize, domain.data(), &domainSize, &use))
|
||||
return false;
|
||||
LPWSTR accountSidText{};
|
||||
if (!ConvertSidToStringSidW(accountSid.data(), &accountSidText))
|
||||
return false;
|
||||
bool same = sid == accountSidText;
|
||||
LocalFree(accountSidText);
|
||||
return same;
|
||||
}
|
||||
|
||||
std::wstring registeredTaskPath()
|
||||
{
|
||||
Com<ITaskService> service;
|
||||
Com<ITaskFolder> folder;
|
||||
check(openTaskFolder(service, folder));
|
||||
Com<IRegisteredTask> task;
|
||||
auto hr = folder->GetTask(Str(L"KSwitcher"), task.out());
|
||||
if (missing(hr))
|
||||
return {};
|
||||
check(hr);
|
||||
VARIANT_BOOL enabled{};
|
||||
check(task->get_Enabled(&enabled));
|
||||
if (!enabled)
|
||||
return {};
|
||||
|
||||
Com<ITaskDefinition> definition;
|
||||
Com<IPrincipal> principal;
|
||||
Str user;
|
||||
check(task->get_Definition(definition.out()));
|
||||
check(definition->get_Principal(principal.out()));
|
||||
check(principal->get_UserId(&user.value));
|
||||
if (!user.value || !sameAccount(user.value))
|
||||
return {};
|
||||
|
||||
Com<IActionCollection> actions;
|
||||
LONG count{};
|
||||
check(definition->get_Actions(actions.out()));
|
||||
check(actions->get_Count(&count));
|
||||
if (count != 1)
|
||||
return {};
|
||||
Com<IAction> action;
|
||||
check(actions->get_Item(1, action.out()));
|
||||
TASK_ACTION_TYPE type{};
|
||||
check(action->get_Type(&type));
|
||||
if (type != TASK_ACTION_EXEC)
|
||||
return {};
|
||||
Com<IExecAction> exec;
|
||||
Str path, arguments;
|
||||
check(action->QueryInterface(IID_IExecAction, (void **)exec.out()));
|
||||
check(exec->get_Arguments(&arguments.value));
|
||||
check(exec->get_Path(&path.value));
|
||||
return path.value && (!arguments.value || !*arguments.value) ? path.value : L"";
|
||||
}
|
||||
|
||||
std::wstring registeredRunPath()
|
||||
{
|
||||
DWORD size{};
|
||||
auto status = RegGetValueW(HKEY_CURRENT_USER, RunKey, L"KSwitcher", RRF_RT_REG_SZ, nullptr, nullptr, &size);
|
||||
if (status == ERROR_FILE_NOT_FOUND || status == ERROR_UNSUPPORTED_TYPE)
|
||||
return {};
|
||||
check(HRESULT_FROM_WIN32(status));
|
||||
std::wstring command(size / sizeof(wchar_t), L'\0');
|
||||
check(HRESULT_FROM_WIN32(RegGetValueW(HKEY_CURRENT_USER, RunKey, L"KSwitcher", RRF_RT_REG_SZ, nullptr,
|
||||
command.data(), &size)));
|
||||
command.resize(wcslen(command.c_str()));
|
||||
// KSwitcher writes a quoted executable path with no arguments.
|
||||
if (command.size() >= 2 && command.front() == L'"' && command.find(L'"', 1) == command.size() - 1)
|
||||
return command.substr(1, command.size() - 2);
|
||||
return {};
|
||||
}
|
||||
|
||||
void runEntry(bool enabled)
|
||||
{
|
||||
HKEY key{};
|
||||
if (RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, nullptr,
|
||||
if (RegCreateKeyExW(HKEY_CURRENT_USER, RunKey, 0, nullptr,
|
||||
0, KEY_SET_VALUE, nullptr, &key, nullptr) != ERROR_SUCCESS)
|
||||
throw std::runtime_error("Cannot access autostart settings");
|
||||
auto command = L"\"" + executable() + L"\"";
|
||||
@@ -66,6 +165,27 @@ void runEntry(bool enabled)
|
||||
throw std::runtime_error("Cannot save autostart settings");
|
||||
}
|
||||
} // namespace
|
||||
std::wstring staleAutostartPath(bool elevated)
|
||||
{
|
||||
auto registered = elevated ? registeredTaskPath() : registeredRunPath();
|
||||
auto path = std::filesystem::path(registered);
|
||||
if (!path.is_absolute() || _wcsicmp(path.filename().c_str(), L"KSwitcher.exe") != 0)
|
||||
return {};
|
||||
auto current = executable();
|
||||
std::error_code error;
|
||||
if (_wcsicmp(registered.c_str(), current.c_str()) == 0 || std::filesystem::equivalent(path, current, error))
|
||||
return {};
|
||||
return registered;
|
||||
}
|
||||
|
||||
void repairAutostartPath(bool elevated)
|
||||
{
|
||||
if (elevated)
|
||||
setAutostart(true, true);
|
||||
else
|
||||
runEntry(true);
|
||||
}
|
||||
|
||||
std::wstring currentUserSid()
|
||||
{
|
||||
HANDLE token{};
|
||||
@@ -88,13 +208,10 @@ std::wstring currentUserSid()
|
||||
void configureAutostart(int mode)
|
||||
{
|
||||
Com<ITaskService> service;
|
||||
check(CoCreateInstance(CLSID_TaskScheduler, nullptr, CLSCTX_INPROC_SERVER, IID_ITaskService,
|
||||
(void **)service.out()));
|
||||
Com<ITaskFolder> folder;
|
||||
check(openTaskFolder(service, folder));
|
||||
VARIANT empty;
|
||||
VariantInit(&empty);
|
||||
check(service->Connect(empty, empty, empty, empty));
|
||||
Com<ITaskFolder> folder;
|
||||
check(service->GetFolder(Str(L"\\"), folder.out()));
|
||||
Com<IRegisteredTask> existing;
|
||||
HRESULT found = folder->GetTask(Str(L"KSwitcher"), existing.out());
|
||||
if (FAILED(found) && !missing(found))
|
||||
@@ -158,16 +275,9 @@ void setAutostart(bool enabled, bool elevated)
|
||||
if (mode != 2)
|
||||
{
|
||||
Com<ITaskService> service;
|
||||
HRESULT hr = CoCreateInstance(CLSID_TaskScheduler, nullptr, CLSCTX_INPROC_SERVER, IID_ITaskService,
|
||||
(void **)service.out());
|
||||
VARIANT empty;
|
||||
VariantInit(&empty);
|
||||
Com<ITaskFolder> folder;
|
||||
HRESULT hr = openTaskFolder(service, folder);
|
||||
Com<IRegisteredTask> task;
|
||||
if (SUCCEEDED(hr))
|
||||
hr = service->Connect(empty, empty, empty, empty);
|
||||
if (SUCCEEDED(hr))
|
||||
hr = service->GetFolder(Str(L"\\"), folder.out());
|
||||
if (SUCCEEDED(hr))
|
||||
hr = folder->GetTask(Str(L"KSwitcher"), task.out());
|
||||
if (missing(hr))
|
||||
|
||||
@@ -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,149 @@
|
||||
#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::wstring applicationName(std::wstring process)
|
||||
{
|
||||
process = lower(process);
|
||||
if (process.ends_with(L".exe")) process.resize(process.size() - 4);
|
||||
return process;
|
||||
}
|
||||
inline const AppLanguageSet *applicationLanguageSet(const Settings &settings, const std::wstring &process)
|
||||
{
|
||||
auto name = applicationName(process);
|
||||
if (name.empty()) return nullptr;
|
||||
for (const auto &[label, set] : settings.appLanguageSets)
|
||||
for (const auto &app : set.applications)
|
||||
if (applicationName(app) == name) return &set;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
inline std::wstring languageProfileKey(const Settings &settings, HWND window, const std::wstring &chat)
|
||||
{
|
||||
if (!chat.empty() && settings.chatCycles.contains(chat)) return chat;
|
||||
if (settings.appLanguageSets.empty()) return {};
|
||||
auto app = applicationName(processName(window));
|
||||
return applicationLanguageSet(settings, app) ? L"app\n" + app : L"";
|
||||
}
|
||||
inline std::wstring windowLanguageProfileKey(const Settings &settings, HWND window)
|
||||
{
|
||||
return window ? languageProfileKey(settings, window, settings.chatCycles.empty() ? L"" : windowChatKey(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);
|
||||
const std::vector<std::wstring> *cycle = found == settings.chatCycles.end() ? nullptr : &found->second;
|
||||
if (key.starts_with(L"app\n"))
|
||||
if (auto set = applicationLanguageSet(settings, key.substr(4))) cycle = &set->languages;
|
||||
if (!cycle) return settings.cycle;
|
||||
std::vector<std::wstring> result;
|
||||
for (const auto &id : *cycle)
|
||||
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];
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "configuration.h"
|
||||
#include <commctrl.h>
|
||||
#include <cstring>
|
||||
#include "mcp_logs.h"
|
||||
|
||||
namespace ks
|
||||
{
|
||||
@@ -52,11 +53,25 @@ LRESULT CALLBACK controller(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
if (message == ConfigSettingsDownloaded)
|
||||
{
|
||||
try
|
||||
{
|
||||
app->settings = decodeSettings(request(*app, ConfigRead), app->layouts);
|
||||
if (app->settingsWindow) SendMessageW(app->settingsWindow, ConfigSettingsDownloaded, 0, 0);
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
MessageBoxW(app->settingsWindow, wide(e.what()).c_str(), L"Unable to refresh downloaded settings", MB_OK | MB_ICONERROR);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (message == WM_APP + 20)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (wp == 21) showSnippets(*app);
|
||||
else if (wp == 22) showLogs(*app);
|
||||
else showSettings(*app);
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
@@ -69,6 +84,7 @@ LRESULT CALLBACK controller(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
if (app->settingsWindow) DestroyWindow(app->settingsWindow);
|
||||
if (app->snippetsWindow) DestroyWindow(app->snippetsWindow);
|
||||
if (app->logWindow) DestroyWindow(app->logWindow);
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
}
|
||||
@@ -77,15 +93,17 @@ LRESULT CALLBACK controller(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
// The configurator owns no history store, dictionaries, worker or input hooks.
|
||||
// All mutations are validated and committed by the resident process.
|
||||
App::App(HINSTANCE h, bool, const std::filesystem::path &) : instance(h)
|
||||
App::App(HINSTANCE h, bool, const std::filesystem::path &, HWND) : instance(h)
|
||||
{
|
||||
current = this;
|
||||
data = dataDirectory();
|
||||
layouts = readLayouts();
|
||||
}
|
||||
App::~App()
|
||||
{
|
||||
if (settingsWindow) DestroyWindow(settingsWindow);
|
||||
if (snippetsWindow) DestroyWindow(snippetsWindow);
|
||||
if (logWindow) DestroyWindow(logWindow);
|
||||
if (window) DestroyWindow(window);
|
||||
current = nullptr;
|
||||
}
|
||||
@@ -98,7 +116,16 @@ void App::applySettings(const Settings &next)
|
||||
memcpy(payload.data(), &length, sizeof(length));
|
||||
payload.insert(payload.end(), before.begin(), before.end());
|
||||
payload.insert(payload.end(), after.begin(), after.end());
|
||||
settings = decodeSettings(request(*this, ConfigSave, payload), layouts);
|
||||
Bytes saved;
|
||||
try {saved=request(*this,ConfigSave,payload);}
|
||||
catch(const std::exception &error){
|
||||
if(!std::string(error.what()).starts_with("Settings conflict: "))throw;
|
||||
auto text=wide(error.what())+L"\n\nThese settings changed both here and in KSwitcher.\nKeep your edits for these settings? Other changes will be preserved.\n\nNo leaves this window open with all your edits.";
|
||||
if(MessageBoxW(settingsWindow?settingsWindow:snippetsWindow,text.c_str(),L"Save conflicting settings",MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2)!=IDYES)
|
||||
throw std::runtime_error("Not saved. Your edits are still in this window.");
|
||||
saved=request(*this,ConfigSaveEdited,payload);
|
||||
}
|
||||
settings=decodeSettings(saved,layouts);
|
||||
}
|
||||
void App::reloadLayouts()
|
||||
{
|
||||
@@ -107,6 +134,14 @@ void App::reloadLayouts()
|
||||
settings = decodeSettings(bytes, layouts);
|
||||
}
|
||||
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)
|
||||
{
|
||||
hotkeyCapture = field;
|
||||
@@ -120,9 +155,29 @@ void App::setHotkeyCapture(HWND field)
|
||||
if (field) MessageBoxW(settingsWindow, wide(e.what()).c_str(), L"Shortcut capture unavailable", MB_OK | MB_ICONWARNING);
|
||||
}
|
||||
}
|
||||
void showLogs(App &app) { request(app, ConfigLogs); }
|
||||
void App::clearLog(bool previous) { request(*this, ConfigClearLog, Bytes{static_cast<unsigned char>(previous)}); }
|
||||
|
||||
int runConfigurator(HINSTANCE instance, bool snippets)
|
||||
int runMcpConfigurator(HINSTANCE instance)
|
||||
{
|
||||
App app(instance);
|
||||
WNDCLASSW cls{};
|
||||
cls.lpfnWndProc = controller;
|
||||
cls.hInstance = instance;
|
||||
cls.lpszClassName = L"KSwitcher.Config.MCP";
|
||||
RegisterClassW(&cls);
|
||||
app.window = CreateWindowExW(0, cls.lpszClassName, L"", 0, 0, 0, 0, 0,
|
||||
HWND_MESSAGE, nullptr, instance, nullptr);
|
||||
auto result = runLogMcp([&](const Bytes &payload)
|
||||
{
|
||||
service = FindWindowW(L"KSwitcher.Main", L"KSwitcher");
|
||||
if (!app.window || !service) throw std::runtime_error("Start KSwitcher before reading remote logs.");
|
||||
return request(app, ConfigLan, payload);
|
||||
});
|
||||
if (app.window) DestroyWindow(app.window);
|
||||
return result;
|
||||
}
|
||||
|
||||
int runConfigurator(HINSTANCE instance, bool snippets, bool logs)
|
||||
{
|
||||
HANDLE singleton = CreateMutexW(nullptr, TRUE, L"Local\\KSwitcher.Config.Singleton");
|
||||
if (!singleton) throw std::runtime_error("Cannot create configurator instance lock.");
|
||||
@@ -140,7 +195,7 @@ int runConfigurator(HINSTANCE instance, bool snippets)
|
||||
throw std::runtime_error("The configurator is starting or belongs to another installation. Try again shortly.");
|
||||
DWORD pid{}; GetWindowThreadProcessId(window, &pid);
|
||||
AllowSetForegroundWindow(pid);
|
||||
PostMessageW(window, WM_APP + 20, snippets ? 21 : 20, 0);
|
||||
PostMessageW(window, WM_APP + 20, logs ? 22 : snippets ? 21 : 20, 0);
|
||||
return 0;
|
||||
}
|
||||
service = FindWindowW(L"KSwitcher.Main", L"KSwitcher");
|
||||
@@ -169,17 +224,25 @@ int runConfigurator(HINSTANCE instance, bool snippets)
|
||||
0, 0, 0, 0, nullptr, nullptr, instance, nullptr);
|
||||
if (!app.window) throw std::runtime_error("Cannot create configurator window.");
|
||||
app.settings = decodeSettings(request(app, ConfigRead), app.layouts);
|
||||
if (snippets) showSnippets(app); else showSettings(app);
|
||||
setLoggingEnabled(app.settings.writeLog);
|
||||
if (logs) showLogs(app); else if (snippets) showSnippets(app); else showSettings(app);
|
||||
MSG message;
|
||||
while ((app.settingsWindow || app.snippetsWindow) && GetMessageW(&message, nullptr, 0, 0) > 0)
|
||||
while ((app.settingsWindow || app.snippetsWindow || app.logWindow) && GetMessageW(&message, nullptr, 0, 0) > 0)
|
||||
{
|
||||
if (app.settingsWindow && !IsWindowEnabled(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 (app.settingsWindow && IsDialogMessageW(app.settingsWindow, &message)) continue;
|
||||
if (app.snippetsWindow && IsDialogMessageW(app.snippetsWindow, &message)) continue;
|
||||
if (app.logWindow && IsDialogMessageW(app.logWindow, &message)) continue;
|
||||
TranslateMessage(&message); DispatchMessageW(&message);
|
||||
}
|
||||
return 0;
|
||||
@@ -193,8 +256,10 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||
{
|
||||
int count{}; auto args = CommandLineToArgvW(GetCommandLineW(), &count);
|
||||
bool snippets = count > 1 && std::wstring(args[1]) == L"--snippets";
|
||||
bool logs = count > 1 && std::wstring(args[1]) == L"--logs";
|
||||
bool mcp = count > 1 && std::wstring(args[1]) == L"--mcp";
|
||||
LocalFree(args);
|
||||
result = ks::runConfigurator(instance, snippets);
|
||||
result = mcp ? ks::runMcpConfigurator(instance) : ks::runConfigurator(instance, snippets, logs);
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
|
||||
@@ -1,25 +1,35 @@
|
||||
#include "configuration.h"
|
||||
#include "settings_merge.h"
|
||||
#include "../vendor/json.hpp"
|
||||
#include <cstring>
|
||||
namespace ks
|
||||
{
|
||||
bool configurationPeer(HWND window, const wchar_t *filename)
|
||||
namespace
|
||||
{
|
||||
std::filesystem::path processImage(HWND window)
|
||||
{
|
||||
DWORD pid{};
|
||||
GetWindowThreadProcessId(window, &pid);
|
||||
HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
|
||||
if (!process) return false;
|
||||
if (!process) return {};
|
||||
wchar_t path[32768]; DWORD count = std::size(path);
|
||||
bool ok = QueryFullProcessImageNameW(process, 0, path, &count) != 0;
|
||||
CloseHandle(process);
|
||||
auto expected = std::filesystem::path(executable()).parent_path() / filename;
|
||||
return ok && _wcsicmp(path, expected.c_str()) == 0;
|
||||
return ok ? std::filesystem::path(path) : std::filesystem::path{};
|
||||
}
|
||||
void launchConfiguration(App &app, bool snippets)
|
||||
}
|
||||
|
||||
bool configurationPeer(HWND window, const wchar_t *filename)
|
||||
{
|
||||
const auto expected = std::filesystem::path(executable()).parent_path() / filename;
|
||||
return _wcsicmp(processImage(window).c_str(), expected.c_str()) == 0;
|
||||
}
|
||||
void launchConfiguration(App &app, bool snippets, bool logs)
|
||||
{
|
||||
auto path = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Config.exe";
|
||||
if (!std::filesystem::exists(path))
|
||||
throw std::runtime_error("KSwitcher.Config.exe is missing. Extract the complete application package.");
|
||||
auto command = L"\"" + path.wstring() + L"\"" + (snippets ? L" --snippets" : L"");
|
||||
auto command = L"\"" + path.wstring() + L"\"" + (logs ? L" --logs" : snippets ? L" --snippets" : L"");
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
PROCESS_INFORMATION process{};
|
||||
if (!CreateProcessW(path.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr,
|
||||
@@ -32,7 +42,11 @@ void launchConfiguration(App &app, bool snippets)
|
||||
}
|
||||
LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &message)
|
||||
{
|
||||
if (!configurationPeer(sender, L"KSwitcher.Config.exe") || message.cbData > ConfigLimit ||
|
||||
const bool filesPeers = message.dwData == FilesLanPeers;
|
||||
const bool knownSender = filesPeers
|
||||
? isFilesPeerImage(processImage(sender), std::filesystem::path(executable()).parent_path())
|
||||
: configurationPeer(sender, L"KSwitcher.Config.exe");
|
||||
if (!knownSender || message.cbData > ConfigLimit ||
|
||||
(message.cbData && !message.lpData)) return FALSE;
|
||||
Bytes reply;
|
||||
bool ok = false;
|
||||
@@ -40,7 +54,51 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
||||
{
|
||||
switch (message.dwData)
|
||||
{
|
||||
case FilesLanPeers:
|
||||
{
|
||||
if(message.cbData) return FALSE;
|
||||
const std::string request=R"({"action":"filesPeers"})";
|
||||
const auto snapshot=nlohmann::json::parse(app.lanCommand(Bytes(request.begin(),request.end())));
|
||||
auto paired=nlohmann::json::array();
|
||||
for(const auto &peer:snapshot.at("peers"))
|
||||
{
|
||||
if(!peer.value("paired",false)) continue;
|
||||
const auto name=wide(peer.at("name").get<std::string>());
|
||||
if(name.empty() || name.find_first_of(std::wstring_view(L"\0\r\n\t",4))!=name.npos) continue;
|
||||
paired.push_back({{"id",peer.at("id")},{"name",peer.at("name")},{"address",peer.at("address")},{"filesBrowse",peer.value("filesBrowse",false)}});
|
||||
}
|
||||
const auto encoded=paired.dump();
|
||||
reply.assign(encoded.begin(),encoded.end());
|
||||
break;
|
||||
}
|
||||
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 ConfigSaveEdited:
|
||||
{
|
||||
if (app.busy) throw std::runtime_error("Wait for the current text operation to finish.");
|
||||
if (message.cbData < sizeof(DWORD)) throw std::runtime_error("Invalid settings request.");
|
||||
@@ -48,11 +106,10 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
||||
memcpy(&length, message.lpData, sizeof(length));
|
||||
if (length > message.cbData - sizeof(length)) throw std::runtime_error("Invalid settings snapshot.");
|
||||
auto begin = static_cast<const unsigned char *>(message.lpData) + sizeof(length);
|
||||
if (Bytes(begin, begin + length) != encodeSettings(app.settings))
|
||||
throw std::runtime_error("Settings changed in KSwitcher. Close and reopen the configurator before saving.");
|
||||
Bytes next(begin + length, static_cast<const unsigned char *>(message.lpData) + message.cbData);
|
||||
if (next.empty()) throw std::runtime_error("Empty settings request.");
|
||||
app.applySettings(decodeSettings(next, app.layouts));
|
||||
auto merged=mergeConfigurationSettings(Bytes(begin,begin+length),next,encodeSettings(app.settings),message.dwData==ConfigSaveEdited);
|
||||
app.applySettings(decodeSettings(merged, app.layouts));
|
||||
reply = encodeSettings(app.settings);
|
||||
break;
|
||||
}
|
||||
@@ -80,6 +137,11 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
||||
case ConfigLogs:
|
||||
PostMessageW(app.window, WM_HOTKEY, 22, 0);
|
||||
break;
|
||||
case ConfigClearLog:
|
||||
if (message.cbData != 1 || *static_cast<const unsigned char *>(message.lpData) > 1)
|
||||
throw std::runtime_error("Invalid log selection.");
|
||||
app.clearLog(*static_cast<const unsigned char *>(message.lpData) != 0);
|
||||
break;
|
||||
default: return FALSE;
|
||||
}
|
||||
ok = true;
|
||||
@@ -89,7 +151,8 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
|
||||
std::string text = error.what();
|
||||
reply.assign(text.begin(), text.end());
|
||||
}
|
||||
COPYDATASTRUCT response{ConfigReply, (DWORD)reply.size(), reply.data()};
|
||||
if(filesPeers && !ok) return FALSE;
|
||||
COPYDATASTRUCT response{filesPeers?FilesLanPeersReply:ConfigReply, (DWORD)reply.size(), reply.data()};
|
||||
DWORD_PTR received{};
|
||||
if (!SendMessageTimeoutW(sender, WM_COPYDATA, (WPARAM)app.window, (LPARAM)&response,
|
||||
SMTO_ABORTIFHUNG, 2000, &received)) return FALSE;
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
#pragma once
|
||||
#include "app.h"
|
||||
#include "files_lan_ipc.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr UINT ConfigSettingsDownloaded = WM_APP + 24;
|
||||
inline constexpr ULONG_PTR ConfigRead = 0x4b530100, ConfigSave = ConfigRead + 1,
|
||||
ConfigLayouts = ConfigRead + 2, ConfigClearHistory = ConfigRead + 3,
|
||||
ConfigCapture = ConfigRead + 4, ConfigLogs = ConfigRead + 5,
|
||||
ConfigReply = ConfigRead + 6;
|
||||
ConfigReply = ConfigRead + 6, ConfigClearLog = ConfigRead + 7,
|
||||
ConfigSync = ConfigRead + 8, ConfigSyncConflicts = ConfigRead + 9,
|
||||
ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigEnd = FilesLanPeers + 1;
|
||||
inline constexpr size_t ConfigLimit = 8 * 1024 * 1024;
|
||||
bool configurationPeer(HWND, const wchar_t *filename);
|
||||
void launchConfiguration(App &, bool snippets = false);
|
||||
void launchConfiguration(App &, bool snippets = false, bool logs = false);
|
||||
LRESULT configurationRequest(App &, HWND sender, const COPYDATASTRUCT &);
|
||||
}
|
||||
@@ -3,9 +3,53 @@
|
||||
#include <cwctype>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
|
||||
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;
|
||||
}
|
||||
static bool validSeparatedWord(const std::wstring &text, const std::wstring &alphabet,
|
||||
std::wstring_view separators)
|
||||
{
|
||||
if (text.empty() || text.size() > 32) return false;
|
||||
auto isLetter = [&](wchar_t c) { return alphabet.find(c) != alphabet.npos; };
|
||||
for (size_t i = 0; i < text.size(); ++i)
|
||||
{
|
||||
if (isLetter(text[i])) continue;
|
||||
if (separators.find(text[i]) == separators.npos)
|
||||
return false;
|
||||
if (i == 0 || i + 1 == text.size() || !isLetter(text[i - 1]) || !isLetter(text[i + 1]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet)
|
||||
{
|
||||
return validSeparatedWord(text, alphabet, L" '\u2019\u02bc");
|
||||
}
|
||||
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet)
|
||||
{
|
||||
return validSeparatedWord(lower(text), alphabet, L"-");
|
||||
}
|
||||
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet)
|
||||
{
|
||||
return text.find(L' ') == text.npos && text.find_first_of(alphabet) != text.npos &&
|
||||
validAutoCorrection(text, alphabet + L"0123456789");
|
||||
}
|
||||
int HotkeyHook::update(UINT key, bool down, UINT modifiers,
|
||||
const std::vector<std::pair<int, Hotkey>> &bindings)
|
||||
{
|
||||
@@ -148,6 +192,26 @@ std::wstring convertTo(const std::wstring &text, const std::vector<Layout> &layo
|
||||
}
|
||||
return best < 0 ? text : convert(text, layouts[best], to);
|
||||
}
|
||||
int nextConversionLayout(const std::wstring &text, const std::vector<Layout> &layouts,
|
||||
const std::vector<int> &cycle, int hint)
|
||||
{
|
||||
if (cycle.empty())
|
||||
return -1;
|
||||
int source = detect(text, layouts, hint);
|
||||
if (source < 0)
|
||||
source = hint;
|
||||
auto it = std::find(cycle.begin(), cycle.end(), source);
|
||||
size_t start = it == cycle.end() ? 0 : (size_t(it - cycle.begin()) + 1) % cycle.size();
|
||||
// Compare every candidate with the original input, never an intermediate conversion.
|
||||
// Bound the search so digits, whitespace and identical layouts cannot loop forever.
|
||||
for (size_t offset = 0; offset < cycle.size(); ++offset)
|
||||
{
|
||||
int target = cycle[(start + offset) % cycle.size()];
|
||||
if (target != source && convertTo(text, layouts, target, hint) != text)
|
||||
return target;
|
||||
}
|
||||
return cycle[start];
|
||||
}
|
||||
std::wstring cycleCase(const std::wstring &text)
|
||||
{
|
||||
if (text == upper(text))
|
||||
@@ -261,7 +325,17 @@ Template parseTemplate(const std::wstring &text)
|
||||
size_t cursor = std::wstring::npos;
|
||||
for (size_t i = 0; i < text.size();)
|
||||
{
|
||||
if (text.compare(i, 10, L"{{cursor}}\0", 10) == 0)
|
||||
if (text.compare(i, 9, L"{{enter}}") == 0)
|
||||
{
|
||||
t.text += L"{enter}";
|
||||
i += 9;
|
||||
}
|
||||
else if (text.compare(i, 7, L"{enter}") == 0)
|
||||
{
|
||||
++t.enters;
|
||||
i += 7;
|
||||
}
|
||||
else if (text.compare(i, 10, L"{{cursor}}\0", 10) == 0)
|
||||
{
|
||||
t.text += L"{cursor}";
|
||||
i += 10;
|
||||
@@ -449,6 +523,14 @@ void Run::backspace(HWND w, ULONGLONG now)
|
||||
keys.pop_back();
|
||||
at = now;
|
||||
}
|
||||
int Run::matchSuffix(const std::wstring &text, const std::vector<Layout> &layouts, const Layout &physical) const
|
||||
{
|
||||
if (text.empty() || text.size() >= keys.size() || overflow)
|
||||
return -1;
|
||||
Run tail = *this;
|
||||
tail.keys = keys.substr(keys.size() - text.size());
|
||||
return tail.match(text, layouts, physical);
|
||||
}
|
||||
int Run::match(const std::wstring &text, const std::vector<Layout> &layouts, const Layout &physical) const
|
||||
{
|
||||
if (text.size() != keys.size() || overflow)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <windows.h>
|
||||
@@ -18,21 +20,33 @@ struct Layout
|
||||
bool hasLetter(wchar_t ch) const;
|
||||
};
|
||||
bool letter(wchar_t ch);
|
||||
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet);
|
||||
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet);
|
||||
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet);
|
||||
std::wstring lower(std::wstring text);
|
||||
std::wstring upper(std::wstring text);
|
||||
std::wstring convert(const std::wstring &, const Layout &, const Layout &, bool force = false);
|
||||
int detect(const std::wstring &, const std::vector<Layout> &, int preferred = -1);
|
||||
std::wstring convertTo(const std::wstring &, const std::vector<Layout> &, int target, int hint);
|
||||
int nextConversionLayout(const std::wstring &, const std::vector<Layout> &,
|
||||
const std::vector<int> &cycle, int hint);
|
||||
std::wstring cycleCase(const std::wstring &);
|
||||
std::wstring transliterate(const std::wstring &);
|
||||
struct Snippet
|
||||
{
|
||||
std::wstring trigger, text;
|
||||
std::wstring id;
|
||||
std::vector<std::wstring> apps; // Empty means everywhere; executable names without .exe.
|
||||
};
|
||||
std::wstring snippetAppName(std::wstring);
|
||||
int snippetAppPriority(const Snippet &, const std::wstring &process);
|
||||
std::wstring snippetId(const Snippet &);
|
||||
std::wstring newSnippetId();
|
||||
struct Template
|
||||
{
|
||||
std::wstring text, suffix;
|
||||
int cursors = 0;
|
||||
int enters = 0;
|
||||
};
|
||||
Template parseTemplate(const std::wstring &);
|
||||
struct Hotkey
|
||||
@@ -42,28 +56,60 @@ struct Hotkey
|
||||
static std::optional<Hotkey> parse(std::wstring);
|
||||
std::wstring format() const;
|
||||
};
|
||||
struct AppLanguageSet
|
||||
{
|
||||
std::vector<std::wstring> languages, applications;
|
||||
bool operator==(const AppLanguageSet &) const = default;
|
||||
};
|
||||
enum class MouseActionType { Standard, Shortcut, Back, Forward, VolumeUp, VolumeDown, Mute, Launch };
|
||||
inline constexpr int DefaultMouseVolumeStep = 4;
|
||||
struct MouseAction
|
||||
{
|
||||
MouseActionType type = MouseActionType::Standard;
|
||||
Hotkey shortcut;
|
||||
std::wstring executable;
|
||||
std::set<std::wstring> applications{};
|
||||
int volumeStep = DefaultMouseVolumeStep;
|
||||
bool operator==(const MouseAction &) const = default;
|
||||
};
|
||||
struct Settings
|
||||
{
|
||||
bool recent = true, switchLayout = true, history = true, autostart = false, awake = false;
|
||||
bool elevatedAutostart = false;
|
||||
bool autoCorrect = false;
|
||||
bool writeLog = true;
|
||||
bool autoReplace = false, autoTypos = false;
|
||||
std::map<std::wstring, std::wstring> autoReplacements;
|
||||
bool writeLog = false;
|
||||
bool screenshotAutoOpenEditor = false;
|
||||
bool useTesseract = false;
|
||||
std::wstring tesseractPath;
|
||||
std::wstring tesseractLanguages = L"ukr+eng+rus";
|
||||
int autoMaxRank = 0;
|
||||
int autoMinLength = 3;
|
||||
std::wstring autoPrefixChars = L"([{«“‘\"";
|
||||
std::wstring autoSuffixChars = L")]}»”’\".,!?:;";
|
||||
std::vector<std::wstring> autoLanguages{L"en", L"uk"};
|
||||
std::vector<std::wstring> autoNever;
|
||||
std::map<std::wstring, std::vector<std::wstring>> autoWords;
|
||||
std::vector<std::wstring> autoExcluded{
|
||||
L"Code", L"rider64", L"devenv", L"WindowsTerminal", L"cmd", L"powershell", L"pwsh",
|
||||
L"Far", L"ConEmu64", L"putty", L"KeePass", L"KeePassXC", L"1Password", L"Bitwarden"};
|
||||
int maxItems = 500, maxMiB = 200, maxImageMiB = 20;
|
||||
std::wstring toggle = L"Ctrl+Alt+Shift+Space", casing = L"Ctrl+Alt+Shift+C",
|
||||
translit = L"Ctrl+Alt+Shift+T", undo = L"Ctrl+Alt+Shift+Z", clipboard = L"Ctrl+Shift+V",
|
||||
translit = L"Ctrl+Alt+Shift+T", undo = L"Ctrl+Alt+Shift+Z", clipboard = L"Win+V",
|
||||
screenshot = L"Win+Shift+S";
|
||||
std::optional<std::wstring> filesHotkey;
|
||||
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::map<std::wstring, AppLanguageSet> appLanguageSets;
|
||||
std::map<std::wstring, std::map<std::wstring, MouseAction>> mouseBindings;
|
||||
std::map<std::wstring, std::wstring> customMouseEvents;
|
||||
std::set<std::wstring> disabledMouseProfiles;
|
||||
std::map<std::wstring, std::set<std::wstring>> mouseProfileApplications;
|
||||
std::vector<std::wstring> excluded{L"KeePass", L"KeePassXC", L"1Password", L"Bitwarden"};
|
||||
std::vector<Snippet> snippets;
|
||||
std::vector<std::wstring> snippetTombstones;
|
||||
};
|
||||
// Consume repeats and key-up for intercepted chords, even if settings change.
|
||||
struct HotkeyHook
|
||||
@@ -85,5 +131,6 @@ struct Run
|
||||
void record(wchar_t, HWND, HKL, ULONGLONG);
|
||||
void backspace(HWND, ULONGLONG);
|
||||
int match(const std::wstring &, const std::vector<Layout> &, const Layout &physical) const;
|
||||
int matchSuffix(const std::wstring &, const std::vector<Layout> &, const Layout &physical) const;
|
||||
};
|
||||
} // namespace ks
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
#include "../vendor/json.hpp"
|
||||
#include "platform.h"
|
||||
#include <sstream>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
using DiagnosticJson = nlohmann::json;
|
||||
struct OperationLogRow
|
||||
{
|
||||
std::wstring time, process, command, source, target, outcome, details;
|
||||
bool problem = true;
|
||||
};
|
||||
inline std::vector<OperationLogRow> parseOperationLog(const std::wstring &contents)
|
||||
{
|
||||
std::vector<OperationLogRow> rows;
|
||||
std::wistringstream stream(contents);
|
||||
std::wstring line;
|
||||
OperationLogRow *legacy = nullptr;
|
||||
while (std::getline(stream, line))
|
||||
{
|
||||
if (!line.empty() && line.back() == L'\r')
|
||||
line.pop_back();
|
||||
if (line.empty())
|
||||
continue;
|
||||
auto marker = line.find(L" Operation {");
|
||||
if (marker != line.npos)
|
||||
{
|
||||
try
|
||||
{
|
||||
auto j = DiagnosticJson::parse(utf8(line.substr(marker + 11)));
|
||||
auto field = [&](const char *key) { return wide(j.value(key, std::string{})); };
|
||||
OperationLogRow row{line.substr(0, marker), field("process"), field("command"),
|
||||
field("source"), field("target"), field("outcome")};
|
||||
row.problem = j.value("problem", true);
|
||||
row.details =
|
||||
L"Operation: " + field("attempt") + L"\r\nResult: " + row.outcome +
|
||||
L"\r\nVerification: " + field("verification") + L"\r\nElapsed: " +
|
||||
std::to_wstring(j.value("elapsedMs", 0ULL)) + L" ms\r\n\r\nOriginal:\r\n" +
|
||||
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: " +
|
||||
(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("textTruncated", false) ? L"yes (4096 UTF-16 units per field)" : L"no") +
|
||||
L"\r\n\r\nContext and stages:\r\n" + field("context");
|
||||
for (size_t at = 0; (at = row.details.find(L'\n', at)) != row.details.npos; ++at)
|
||||
if (at == 0 || row.details[at - 1] != L'\r')
|
||||
row.details.insert(at++, 1, L'\r');
|
||||
rows.push_back(std::move(row));
|
||||
legacy = nullptr;
|
||||
continue;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
} // Preserve malformed and old records for diagnosis.
|
||||
}
|
||||
if (line.front() != L' ' || !legacy)
|
||||
{
|
||||
rows.push_back({L"", L"", L"Legacy / event", L"", L"", L"Unstructured event", line});
|
||||
legacy = &rows.back();
|
||||
}
|
||||
else
|
||||
legacy->details += L"\r\n" + line;
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
inline std::wstring conversionReadbackOutcome(const std::wstring &actual, const std::wstring &original,
|
||||
const std::wstring &expected)
|
||||
{
|
||||
if (actual == expected)
|
||||
return L"Paste verified";
|
||||
if (actual == original)
|
||||
return L"Original text remained";
|
||||
return L"Readback differs";
|
||||
}
|
||||
} // namespace ks
|
||||
@@ -0,0 +1,321 @@
|
||||
#pragma once
|
||||
|
||||
#include "platform.h"
|
||||
#include "files_powershell.h"
|
||||
#include "files_windows_command_catalog.h"
|
||||
#include "../vendor/json.hpp"
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
class CommandCompletion
|
||||
{
|
||||
public:
|
||||
using Json = nlohmann::json;
|
||||
|
||||
CommandCompletion() = default;
|
||||
CommandCompletion(const CommandCompletion &) = delete;
|
||||
CommandCompletion &operator=(const CommandCompletion &) = delete;
|
||||
~CommandCompletion() { close(); }
|
||||
|
||||
bool request(const std::wstring &line, DWORD caret, const std::wstring &directory)
|
||||
{
|
||||
auto message=Json{{"line",utf8(line)},{"caret",caret},{"directory",utf8(directory)}}.dump(
|
||||
-1,' ',true,Json::error_handler_t::replace)+"\n";
|
||||
if(message.size()>32768 || (!process && !start())) return false;
|
||||
if(!write(message))
|
||||
{
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
deadline=GetTickCount64()+5000;
|
||||
return true;
|
||||
}
|
||||
|
||||
// An empty optional means the request is still running.
|
||||
std::optional<Json> poll()
|
||||
{
|
||||
DWORD available{},count{};
|
||||
char chunk[8192];
|
||||
if(!PeekNamedPipe(output,nullptr,0,nullptr,&available,nullptr) ||
|
||||
GetTickCount64()>=deadline || pending.size()>1024*1024)
|
||||
{
|
||||
close();
|
||||
return Json{};
|
||||
}
|
||||
if(available && ReadFile(output,chunk,std::min<DWORD>(available,sizeof(chunk)),&count,nullptr))
|
||||
pending.append(chunk,count);
|
||||
const auto end=pending.find('\n');
|
||||
if(end==pending.npos) return {};
|
||||
auto result=Json::parse(pending.begin(),pending.begin()+end,nullptr,false);
|
||||
pending.erase(0,end+1);
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
HANDLE process{},input{},output{},job{};
|
||||
ULONGLONG deadline{};
|
||||
std::string pending;
|
||||
|
||||
bool write(std::string_view message)
|
||||
{
|
||||
DWORD written{};
|
||||
return WriteFile(input,message.data(),static_cast<DWORD>(message.size()),&written,nullptr) &&
|
||||
written==message.size();
|
||||
}
|
||||
|
||||
bool start()
|
||||
{
|
||||
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
|
||||
HANDLE childInput{},childOutput{};
|
||||
std::string catalog;
|
||||
for(const auto row:windowsCommandCatalog) catalog.append(row).push_back('\n');
|
||||
const auto initial=Json{{"catalog",std::move(catalog)}}.dump()+"\n";
|
||||
const auto inputCapacity=static_cast<DWORD>(initial.size()+32768);
|
||||
const bool pipes=CreatePipe(&childInput,&input,&inheritable,inputCapacity) &&
|
||||
CreatePipe(&output,&childOutput,&inheritable,65536) &&
|
||||
SetHandleInformation(input,HANDLE_FLAG_INHERIT,0) &&
|
||||
SetHandleInformation(output,HANDLE_FLAG_INHERIT,0);
|
||||
const bool started=pipes && launch(childInput,childOutput) && write(initial);
|
||||
if(childInput) CloseHandle(childInput);
|
||||
if(childOutput) CloseHandle(childOutput);
|
||||
if(!started) close();
|
||||
return started;
|
||||
}
|
||||
|
||||
bool launch(HANDLE childInput,HANDLE childOutput)
|
||||
{
|
||||
const auto shell=windowsPowerShell();
|
||||
if(shell.empty()) return false;
|
||||
// The request is data on stdin. PowerShell parses it for completion in this separate session.
|
||||
wchar_t command[]=LR"PS(powershell.exe -NoLogo -NoProfile -NonInteractive -Command "
|
||||
$ProgressPreference = 'SilentlyContinue';
|
||||
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);
|
||||
function Get-CompletedArguments($command, $position, $includeCurrent) {
|
||||
foreach ($element in ($command.CommandElements | Select-Object -Skip 1)) {
|
||||
if ($element.Extent.EndOffset -gt $position -or
|
||||
(!$includeCurrent -and $element.Extent.EndOffset -eq $position)) { break }
|
||||
if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
|
||||
$element.Value;
|
||||
} else { $element.Extent.Text }
|
||||
}
|
||||
}
|
||||
|
||||
function New-ArgumentCompletion([string]$value) {
|
||||
$text = $value;
|
||||
if ($value.StartsWith('@') -or $value -notmatch '^[\p{L}\p{M}\p{N}._/@:+,=\-]+$') {
|
||||
$quote = [string][char]39;
|
||||
$text = $quote + [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($value) + $quote;
|
||||
}
|
||||
[System.Management.Automation.CompletionResult]::new($text, $value, 'ParameterValue', $value)
|
||||
}
|
||||
|
||||
function Get-DhcpAdapterNames {
|
||||
foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
|
||||
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
|
||||
try {
|
||||
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
$initial = ConvertFrom-Json -InputObject ([Console]::ReadLine());
|
||||
$windowsCommands = @{};
|
||||
$windowsHelp = @{};
|
||||
foreach ($row in ($initial.catalog -split '\r?\n')) {
|
||||
if (!$row) { continue }
|
||||
$name, $values, $article = $row.Split([char]9, 3);
|
||||
$windowsCommands[$name] = if ($values) { $values.Split(' ') } else { @() };
|
||||
if ($article) { $windowsHelp[$name] = $article }
|
||||
}
|
||||
$windowsRoots = @($windowsCommands.Keys | Where-Object { !($_.Contains(' ')) } | Sort-Object);
|
||||
$windowsPrograms = @(foreach ($name in $windowsRoots) { $name; $name + '.exe'; $name + '.com' });
|
||||
function Get-WindowsCommandContext($command, $position, $includeCurrent) {
|
||||
if (!$command) { return }
|
||||
$invoked = $command.GetCommandName();
|
||||
if (!$invoked -or !$windowsCommands.ContainsKey([IO.Path]::GetFileNameWithoutExtension($invoked))) { return }
|
||||
$resolved = Get-Command -Name ([WildcardPattern]::Escape($invoked)) -ErrorAction SilentlyContinue |
|
||||
Select-Object -First 1;
|
||||
if ($resolved -is [System.Management.Automation.AliasInfo]) { $resolved = $resolved.ResolvedCommand }
|
||||
if ($resolved -isnot [System.Management.Automation.ApplicationInfo]) { return }
|
||||
$name = [IO.Path]::GetFileNameWithoutExtension($resolved.Name);
|
||||
$arguments = @(Get-CompletedArguments $command $position $includeCurrent);
|
||||
$values = $null;
|
||||
if ($name -eq 'cmd') {
|
||||
for ($i = 0; $i -lt $arguments.Count; ++$i) {
|
||||
if ($arguments[$i] -notin '/c', '/k') { continue }
|
||||
if ($i + 1 -lt $arguments.Count) {
|
||||
$name = [IO.Path]::GetFileNameWithoutExtension($arguments[$i + 1]);
|
||||
$arguments = @($arguments | Select-Object -Skip ($i + 2));
|
||||
} else { $values = $windowsRoots }
|
||||
break
|
||||
}
|
||||
}
|
||||
$root = $name;
|
||||
$article = $windowsHelp[$name];
|
||||
if (!$values) {
|
||||
foreach ($argument in $arguments) {
|
||||
$child = $name + ' ' + $argument;
|
||||
if (!$windowsCommands.ContainsKey($child)) { break }
|
||||
$name = $child;
|
||||
if ($windowsHelp[$name]) { $article = $windowsHelp[$name] }
|
||||
}
|
||||
$values = $windowsCommands[$name];
|
||||
}
|
||||
@{ root = $root; values = $values; arguments = $arguments; article = $article }
|
||||
}
|
||||
|
||||
Register-ArgumentCompleter -Native -CommandName $windowsPrograms -ScriptBlock {
|
||||
param($word, $command, $position)
|
||||
$context = Get-WindowsCommandContext $command $position $false;
|
||||
if (!$context) { return }
|
||||
if ($context.root -eq 'ipconfig' -and $context.arguments.Count -and
|
||||
$context.arguments[0] -in '/renew','/release') {
|
||||
$script:adapterArguments = $true;
|
||||
if ($context.arguments.Count -ne 1) { return }
|
||||
$prefix = ([string]$word).Trim([char[]]@([char]39, [char]34));
|
||||
foreach ($adapterName in (Get-DhcpAdapterNames | Sort-Object -Unique)) {
|
||||
if ($adapterName.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
New-ArgumentCompletion $adapterName
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if ($word -eq '?') { $word = '/?' }
|
||||
foreach ($value in $context.values) {
|
||||
if ($value.StartsWith([string]$word, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
[System.Management.Automation.CompletionResult]::new($value)
|
||||
}
|
||||
}
|
||||
};
|
||||
Register-ArgumentCompleter -Native -CommandName dotnet,dotnet.exe -ScriptBlock {
|
||||
param($word, $command, $position)
|
||||
$offset = $position - $command.Extent.StartOffset;
|
||||
dotnet.exe complete --position $offset $command.ToString() 2>$null | ForEach-Object {
|
||||
[System.Management.Automation.CompletionResult]::new($_)
|
||||
}
|
||||
};
|
||||
function Find-GitCompletionTools {
|
||||
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1;
|
||||
if (!$git) { return }
|
||||
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source));
|
||||
for ($level = 0; $location -and $level -lt 3; ++$level) {
|
||||
$root = $location.FullName;
|
||||
$location = $location.Parent;
|
||||
$bash = Join-Path $root 'usr/bin/bash.exe';
|
||||
if (![IO.File]::Exists($bash)) { continue }
|
||||
foreach ($architecture in 'mingw64', 'mingw32', 'clangarm64') {
|
||||
$script = Join-Path $root ($architecture + '/share/git/completion/git-completion.bash');
|
||||
if ([IO.File]::Exists($script)) { return @{ bash = $bash; script = $script } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Send words as data to Git for Windows. Backslash-quote escapes are for Windows PowerShell's native argv.
|
||||
$gitCompletionRunner = @'
|
||||
export GIT_ALLOW_PROTOCOL= GIT_TERMINAL_PROMPT=0
|
||||
mapfile -t input
|
||||
for i in ~${!input[@]}~; do input[i]=~${input[i]%$'\r'}~; done
|
||||
source ~${input[0]}~ || exit
|
||||
words=(~${input[@]:1}~)
|
||||
cword=$(( ${#words[@]} - 1 ))
|
||||
cur=${words[cword]}
|
||||
prev=${words[cword-1]}
|
||||
__git_main
|
||||
if (( ${#COMPREPLY[@]} )); then printf '%s\n' ~${COMPREPLY[@]}~; fi
|
||||
'@.Replace('~', ('\' + [char]34));
|
||||
$OutputEncoding = [Console]::OutputEncoding;
|
||||
Register-ArgumentCompleter -Native -CommandName git,git.exe -ScriptBlock {
|
||||
param($word, $command, $position)
|
||||
if (!$script:gitCompletionTools) { $script:gitCompletionTools = Find-GitCompletionTools }
|
||||
if (!$script:gitCompletionTools) { return }
|
||||
$arguments = @('git') + @(Get-CompletedArguments $command $position) + @([string]$word);
|
||||
@($script:gitCompletionTools.script) + $arguments |
|
||||
& $script:gitCompletionTools.bash --noprofile --norc -p -c $gitCompletionRunner 2>$null |
|
||||
ForEach-Object {
|
||||
$value = $_.TrimEnd();
|
||||
if ($value) { New-ArgumentCompletion $value }
|
||||
}
|
||||
};
|
||||
function Get-CompletionCommand($request) {
|
||||
$prefix = $request.line.Substring(0, $request.caret).TrimEnd();
|
||||
$ast = [System.Management.Automation.Language.Parser]::ParseInput($prefix, [ref]$null, [ref]$null);
|
||||
$ast.FindAll({
|
||||
param($node)
|
||||
$node -is [System.Management.Automation.Language.CommandAst] -and
|
||||
$node.Extent.EndOffset -eq $prefix.Length
|
||||
}, $true) | Select-Object -Last 1;
|
||||
}
|
||||
function Test-NoCommandArguments($command) {
|
||||
if (!$command) { return $false }
|
||||
$name = $command.GetCommandName();
|
||||
if (!$name) { return $false }
|
||||
$info = Get-Command -Name ([WildcardPattern]::Escape($name)) -ErrorAction SilentlyContinue;
|
||||
if ($info -is [System.Management.Automation.AliasInfo]) { $info = $info.ResolvedCommand }
|
||||
return ($info -is [System.Management.Automation.FunctionInfo] -or
|
||||
$info -is [System.Management.Automation.CmdletInfo]) -and $info.Parameters.Count -eq 0;
|
||||
}
|
||||
while ($null -ne ($line = [Console]::ReadLine())) {
|
||||
try {
|
||||
$request = ConvertFrom-Json -InputObject $line -ErrorAction Stop;
|
||||
Set-Location -LiteralPath $request.directory -ErrorAction Stop;
|
||||
$script:adapterArguments = $false;
|
||||
$command = Get-CompletionCommand $request;
|
||||
$context = Get-WindowsCommandContext $command $request.caret $true;
|
||||
$result = TabExpansion2 -inputScript $request.line -cursorColumn $request.caret;
|
||||
$candidates = $result.CompletionMatches;
|
||||
if ($candidates.Count -and $candidates[0].ResultType -in 'ProviderItem','ProviderContainer' -and
|
||||
($script:adapterArguments -or (Test-NoCommandArguments $command))) {
|
||||
$candidates = $candidates | Where-Object { $_.ResultType -notin 'ProviderItem','ProviderContainer' };
|
||||
}
|
||||
$items = @($candidates | Select-Object -First 100 | ForEach-Object {
|
||||
@{ label = $_.ListItemText; text = $_.CompletionText; directory = ($_.ResultType -eq 'ProviderContainer') }
|
||||
});
|
||||
$reply = @{ index = $result.ReplacementIndex; length = $result.ReplacementLength;
|
||||
matches = $items; article = [string]$context.article };
|
||||
[Console]::WriteLine((ConvertTo-Json -InputObject $reply -Compress -Depth 4));
|
||||
} catch { [Console]::WriteLine('{}') }
|
||||
}")PS";
|
||||
|
||||
job=CreateJobObjectW(nullptr,nullptr);
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
|
||||
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if(!job || !SetInformationJobObject(job,JobObjectExtendedLimitInformation,&limits,sizeof(limits))) return false;
|
||||
|
||||
SIZE_T bytes{};
|
||||
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
|
||||
std::vector<unsigned char> storage(bytes);
|
||||
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes)) return false;
|
||||
HANDLE inherited[]{childInput,childOutput};
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb=sizeof(startup);
|
||||
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
|
||||
startup.StartupInfo.hStdInput=childInput;
|
||||
startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=childOutput;
|
||||
startup.lpAttributeList=attributes;
|
||||
PROCESS_INFORMATION child{};
|
||||
const bool started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
inherited,sizeof(inherited),nullptr,nullptr) &&
|
||||
CreateProcessW(shell.c_str(),command,nullptr,nullptr,TRUE,
|
||||
CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,
|
||||
nullptr,nullptr,&startup.StartupInfo,&child);
|
||||
DeleteProcThreadAttributeList(attributes);
|
||||
if(!started) return false;
|
||||
process=child.hProcess;
|
||||
const bool running=AssignProcessToJobObject(job,process) && ResumeThread(child.hThread)!=DWORD(-1);
|
||||
if(!running) TerminateProcess(process,1);
|
||||
CloseHandle(child.hThread);
|
||||
return running;
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
for(const auto handle:{job,input,output,process})
|
||||
if(handle) CloseHandle(handle);
|
||||
job=input=output=process=nullptr;
|
||||
pending.clear();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)};
|
||||
auto commandHistoryKeys=defaultHistoryKeys;
|
||||
constexpr size_t commandHistoryLimit=1000;
|
||||
|
||||
bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
{
|
||||
if(keys[0]==keys[1]) return false;
|
||||
return std::all_of(keys.begin(),keys.end(),[](WORD binding)
|
||||
{
|
||||
const auto key=LOBYTE(binding), modifiers=HIBYTE(binding);
|
||||
const bool letter=key>='A' && key<='Z';
|
||||
const bool function=key>=VK_F1 && key<=VK_F12;
|
||||
if(!letter && !function) return false;
|
||||
if(modifiers==HOTKEYF_CONTROL)
|
||||
return letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y';
|
||||
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
std::array<WORD,2> optionHistoryKeys(HWND dialog)
|
||||
{
|
||||
return {static_cast<WORD>(SendDlgItemMessageW(dialog,321,HKM_GETHOTKEY,0,0)),
|
||||
static_cast<WORD>(SendDlgItemMessageW(dialog,323,HKM_GETHOTKEY,0,0))};
|
||||
}
|
||||
|
||||
void setOptionHistoryKeys(HWND dialog,const std::array<WORD,2> &keys)
|
||||
{
|
||||
SendDlgItemMessageW(dialog,321,HKM_SETHOTKEY,keys[0],0);
|
||||
SendDlgItemMessageW(dialog,323,HKM_SETHOTKEY,keys[1],0);
|
||||
}
|
||||
|
||||
void loadCommandHistoryKeys()
|
||||
{
|
||||
const std::array<WORD,2> keys{static_cast<WORD>(preference(L"PreviousCommandKey",defaultHistoryKeys[0])),
|
||||
static_cast<WORD>(preference(L"CommandHistoryKey",defaultHistoryKeys[1]))};
|
||||
commandHistoryKeys=validHistoryKeys(keys)?keys:defaultHistoryKeys;
|
||||
}
|
||||
|
||||
void loadCommandHistory()
|
||||
{
|
||||
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)
|
||||
!=ERROR_SUCCESS || bytes>16*1024*1024 || bytes%sizeof(wchar_t)) return;
|
||||
std::wstring data(bytes/sizeof(wchar_t),L'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)
|
||||
!=ERROR_SUCCESS) return;
|
||||
size_t start{};
|
||||
while(start<data.size())
|
||||
{
|
||||
const auto dateEnd=data.find(L'\0',start);
|
||||
if(dateEnd==std::wstring::npos) break;
|
||||
const auto commandEnd=data.find(L'\0',dateEnd+1);
|
||||
if(commandEnd==std::wstring::npos) break;
|
||||
terminalHistory.push_back({data.substr(start,dateEnd-start),data.substr(dateEnd+1,commandEnd-dateEnd-1)});
|
||||
start=commandEnd+1;
|
||||
}
|
||||
terminalHistoryIndex=terminalHistory.size();
|
||||
}
|
||||
|
||||
void rememberCommand(const std::wstring &command)
|
||||
{
|
||||
terminalHistory.push_back({ks::files::historyDate(),command});
|
||||
if(terminalHistory.size()>commandHistoryLimit) terminalHistory.erase(terminalHistory.begin());
|
||||
std::wstring data;
|
||||
for(const auto &entry:terminalHistory)
|
||||
{
|
||||
data.append(entry.date).push_back(L'\0');
|
||||
data.append(entry.command).push_back(L'\0');
|
||||
}
|
||||
if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()*sizeof(wchar_t)))!=ERROR_SUCCESS)
|
||||
setStatus(L"Could not save command history.");
|
||||
refreshCommandHistory();
|
||||
}
|
||||
|
||||
void recallCommand(size_t index)
|
||||
{
|
||||
terminalHistoryIndex=index;
|
||||
SetWindowTextW(terminalInput,index<terminalHistory.size()?terminalHistory[index].command.c_str():L"");
|
||||
SetFocus(terminalInput);
|
||||
SendMessageW(terminalInput,EM_SETSEL,-2,-1);
|
||||
}
|
||||
|
||||
void showCommandHistory(HWND owner);
|
||||
|
||||
bool handleCommandHistoryKey(HWND window,const MSG &message)
|
||||
{
|
||||
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
|
||||
if((GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000)) return false;
|
||||
const BYTE modifiers=((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0) |
|
||||
((GetKeyState(VK_MENU)&0x8000)?HOTKEYF_ALT:0) | ((GetKeyState(VK_SHIFT)&0x8000)?HOTKEYF_SHIFT:0);
|
||||
const auto binding=MAKEWORD(message.wParam,modifiers);
|
||||
if(binding==commandHistoryKeys[0] && (message.hwnd==terminalInput ||
|
||||
message.hwnd==panels[0].list || message.hwnd==panels[1].list))
|
||||
{
|
||||
if(terminalHistoryIndex) recallCommand(terminalHistoryIndex-1);
|
||||
return true;
|
||||
}
|
||||
if(binding!=commandHistoryKeys[1]) return false;
|
||||
if(!(message.lParam&(1LL<<30))) showCommandHistory(window);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
constexpr int historyList=324;
|
||||
|
||||
constexpr int historySearch=325;
|
||||
constexpr COLORREF historySearchSurface=RGB(132,177,177);
|
||||
constexpr int historySearchLabel=326;
|
||||
HWND commandHistoryWindow{};
|
||||
|
||||
std::wstring historyLower(std::wstring value)
|
||||
{
|
||||
if(!value.empty()) CharLowerBuffW(value.data(),static_cast<DWORD>(value.size()));
|
||||
return value;
|
||||
}
|
||||
|
||||
std::wstring_view commandTopicKeywords(const std::wstring &command)
|
||||
{
|
||||
const auto start=command.find_first_not_of(L" \t");
|
||||
if(start==command.npos) return L"";
|
||||
const auto end=command.find_first_of(L" \t",start);
|
||||
auto tool=command.substr(start,end-start);
|
||||
if(tool.ends_with(L".exe")) tool.resize(tool.size()-4);
|
||||
const auto args=end==command.npos?L"":command.substr(end);
|
||||
if(tool==L"ipconfig" && args.find(L"/flushdns")!=args.npos)
|
||||
return L"network tools мережа dns flush clear cache очистити кеш";
|
||||
if(tool==L"nslookup" || tool==L"resolve-dnsname")
|
||||
return L"network tools мережа dns lookup запит";
|
||||
if(tool==L"ping" || tool==L"tracert" || tool==L"ipconfig" || tool==L"test-netconnection" ||
|
||||
tool==L"netstat" || tool==L"curl" || tool==L"invoke-webrequest")
|
||||
return L"network tools мережа з’єднання connectivity address адреса";
|
||||
if(tool==L"cls" || tool==L"clear" || tool==L"clear-host")
|
||||
return L"terminal clear screen очистити екран консоль";
|
||||
if(tool==L"git")
|
||||
{
|
||||
const auto first=args.find_first_not_of(L" \t");
|
||||
const auto action=first==args.npos?L"":args.substr(first,args.find_first_of(L" \t",first)-first);
|
||||
if(action==L"pull" || action==L"fetch" || action==L"update")
|
||||
return L"git version control repository update fetch pull оновити репозиторій синхронізація";
|
||||
return L"git version control repository репозиторій контроль версій";
|
||||
}
|
||||
return L"";
|
||||
}
|
||||
|
||||
void populateCommandHistory(HWND dialog)
|
||||
{
|
||||
const auto search=GetDlgItem(dialog,historySearch);
|
||||
std::wstring query(GetWindowTextLengthW(search)+1,L'\0');
|
||||
query.resize(GetWindowTextW(search,query.data(),static_cast<int>(query.size())));
|
||||
query=historyLower(std::move(query));
|
||||
std::wistringstream stream(query);
|
||||
std::vector<std::wstring> words;
|
||||
for(std::wstring word;stream>>word;) words.push_back(word);
|
||||
|
||||
const auto list=GetDlgItem(dialog,historyList);
|
||||
SendMessageW(list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
const auto add=[&](const std::wstring &label,LPARAM index)
|
||||
{
|
||||
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
if(row>=0) SendMessageW(list,LB_SETITEMDATA,row,index);
|
||||
return row;
|
||||
};
|
||||
std::array<std::vector<size_t>,2> matches;
|
||||
std::set<std::wstring_view> seen;
|
||||
for(size_t index=terminalHistory.size();index-- > 0;)
|
||||
{
|
||||
const auto &entry=terminalHistory[index];
|
||||
if(!seen.insert(entry.command).second) continue;
|
||||
const auto command=historyLower(entry.command);
|
||||
const auto containsAll=[&](const std::wstring &text)
|
||||
{
|
||||
return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;});
|
||||
};
|
||||
if(containsAll(command+L" "+entry.date))
|
||||
{
|
||||
matches[0].push_back(index);
|
||||
continue;
|
||||
}
|
||||
const auto keywords=commandTopicKeywords(command);
|
||||
if(!keywords.empty() && containsAll(command+L" "+entry.date+L" "+std::wstring(keywords)))
|
||||
matches[1].push_back(index);
|
||||
}
|
||||
LRESULT selected=LB_ERR;
|
||||
for(const auto &group:matches)
|
||||
{
|
||||
std::wstring lastDate;
|
||||
bool first=true;
|
||||
for(auto match=group.rbegin();match!=group.rend();++match)
|
||||
{
|
||||
const auto index=*match;
|
||||
const auto &entry=terminalHistory[index];
|
||||
const auto &date=entry.date;
|
||||
if(first || date!=lastDate) add(date,-1);
|
||||
first=false;
|
||||
lastDate=date;
|
||||
const auto row=add(entry.command,index);
|
||||
if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row;
|
||||
}
|
||||
}
|
||||
if(selected==LB_ERR) add(words.empty()?L"No commands yet":L"No matching commands",-2);
|
||||
else SendMessageW(list,LB_SETCURSEL,selected,0);
|
||||
SendMessageW(list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(list,nullptr,TRUE);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK historySearchKeys(HWND search,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_GETDLGCODE)
|
||||
{
|
||||
const auto code=DefSubclassProc(search,message,key,flags);
|
||||
if(key==VK_TAB || key==VK_ESCAPE) return code&~DLGC_WANTALLKEYS;
|
||||
if(key==VK_RETURN) return code|DLGC_WANTMESSAGE;
|
||||
return code|DLGC_WANTARROWS;
|
||||
}
|
||||
if(message==WM_KEYDOWN && key==VK_RETURN)
|
||||
{
|
||||
SendMessageW(GetParent(search),WM_COMMAND,IDOK,0);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_KEYDOWN && (key==VK_UP || key==VK_DOWN))
|
||||
{
|
||||
const auto list=GetDlgItem(GetParent(search),historyList);
|
||||
SetFocus(list);
|
||||
SendMessageW(list,message,key,flags);
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(search,message,key,flags);
|
||||
}
|
||||
|
||||
|
||||
int historyRowInset(UINT dpi)
|
||||
{
|
||||
return std::max(MulDiv(4,dpi,96),dialogFrameMetrics(dpi).inner)+dialogRowTextInset(cellWidth);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_GETDLGCODE && wp==VK_RETURN)
|
||||
return DefSubclassProc(list,message,wp,lp)|DLGC_WANTMESSAGE;
|
||||
if(message==WM_KEYDOWN && wp==VK_RETURN)
|
||||
{
|
||||
SendMessageW(GetParent(list),WM_COMMAND,IDOK,0);
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(list,message,wp,lp);
|
||||
}
|
||||
|
||||
void sizeCommandHistory(HWND dialog,HWND list)
|
||||
{
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
RECT ownerBounds{};
|
||||
if(!GetWindowRect(owner,&ownerBounds) || IsIconic(owner)) return;
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
if(!GetMonitorInfoW(MonitorFromWindow(owner,MONITOR_DEFAULTTONEAREST),&monitor)) return;
|
||||
RECT area{};
|
||||
if(!IntersectRect(&area,&ownerBounds,&monitor.rcWork)) area=monitor.rcWork;
|
||||
|
||||
const auto dc=GetDC(list);
|
||||
if(!dc) return;
|
||||
const auto previous=SelectObject(dc,mono);
|
||||
LONG longest{};
|
||||
for(const auto &entry:terminalHistory)
|
||||
{
|
||||
SIZE size{};
|
||||
if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast<int>(entry.command.size()),&size))
|
||||
longest=std::max(longest,size.cx);
|
||||
}
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(list,dc);
|
||||
|
||||
const auto dpi=GetDpiForWindow(dialog);
|
||||
const auto frame=dialogFrameMetrics(dpi);
|
||||
const int inset=frame.content();
|
||||
const int top=dialogListInset(frame,textHeight);
|
||||
const int gap=MulDiv(4,dpi,96);
|
||||
const int listTop=top+2*textHeight+2*gap;
|
||||
const LONG desired=std::max<LONG>(MulDiv(320,dpi,96),
|
||||
longest+2*cellWidth+2*historyRowInset(dpi)+scrollBarWidth(list))+2*inset;
|
||||
const auto target=std::min(desired,area.right-area.left);
|
||||
const auto rows=std::max<LRESULT>(1,SendMessageW(list,LB_GETCOUNT,0,0));
|
||||
RECT listWindow{},listClient{};
|
||||
GetWindowRect(list,&listWindow);
|
||||
GetClientRect(list,&listClient);
|
||||
const auto listBorder=listWindow.bottom-listWindow.top-listClient.bottom;
|
||||
const auto height=std::min<LONG>(listTop+rows*textHeight+listBorder+inset,
|
||||
area.bottom-area.top);
|
||||
const auto left=std::clamp((ownerBounds.left+ownerBounds.right-target)/2,area.left,area.right-target);
|
||||
const auto y=std::clamp((ownerBounds.top+ownerBounds.bottom-height)/2,area.top,area.bottom-height);
|
||||
SetWindowPos(dialog,nullptr,left,y,target,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
const auto place=[&](HWND control,int rowTop,int rowHeight)
|
||||
{
|
||||
SetWindowPos(control,nullptr,inset,rowTop,std::max(1L,target-2*inset),rowHeight,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
};
|
||||
place(GetDlgItem(dialog,historySearchLabel),top,textHeight);
|
||||
place(GetDlgItem(dialog,historySearch),top+textHeight+gap,textHeight);
|
||||
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-scrollBarWidth(list)),
|
||||
std::max(1L,height-listTop-inset),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
GetClientRect(list,&listClient);
|
||||
if(rows*textHeight<=listClient.bottom) SendMessageW(list,LB_SETTOPINDEX,0,0);
|
||||
InvalidateRect(dialog,nullptr,FALSE);
|
||||
FilesModalDialog::refreshLayout(dialog);
|
||||
}
|
||||
|
||||
void layoutOpenCommandHistory()
|
||||
{
|
||||
if(commandHistoryWindow)
|
||||
sizeCommandHistory(commandHistoryWindow,GetDlgItem(commandHistoryWindow,historyList));
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
commandHistoryWindow=dialog;
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareCopyDialog(dialog);
|
||||
const auto list=GetDlgItem(dialog,historyList);
|
||||
SetWindowSubclass(list,historyListScroll,1,0);
|
||||
installScrollBar(list,dialog);
|
||||
SendMessageW(list,WM_SETFONT,reinterpret_cast<WPARAM>(mono),TRUE);
|
||||
SendMessageW(list,LB_SETITEMHEIGHT,0,std::max(1,textHeight));
|
||||
const auto search=GetDlgItem(dialog,historySearch);
|
||||
SendDlgItemMessageW(dialog,historySearchLabel,WM_SETFONT,reinterpret_cast<WPARAM>(mono),TRUE);
|
||||
SetWindowSubclass(search,historySearchKeys,1,0);
|
||||
populateCommandHistory(dialog);
|
||||
sizeCommandHistory(dialog,list);
|
||||
SetFocus(search);
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==historySearch && HIWORD(wp)==EN_CHANGE)
|
||||
{
|
||||
populateCommandHistory(dialog);
|
||||
sizeCommandHistory(dialog,GetDlgItem(dialog,historyList));
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_NCDESTROY && commandHistoryWindow==dialog)
|
||||
commandHistoryWindow=nullptr;
|
||||
if(message==WM_CTLCOLORLISTBOX || message==WM_CTLCOLOREDIT)
|
||||
{
|
||||
const auto dc=reinterpret_cast<HDC>(wp);
|
||||
const bool search=message==WM_CTLCOLOREDIT;
|
||||
SetTextColor(dc,search?RGB(0,0,0):colors[Text]);
|
||||
const auto background=search?historySearchSurface:colors[Dialog];
|
||||
SetBkColor(dc,background);
|
||||
if(search) SetDCBrushColor(dc,background);
|
||||
return reinterpret_cast<INT_PTR>(search?GetStockObject(DC_BRUSH):teal);
|
||||
}
|
||||
if(message!=WM_DRAWITEM || wp!=historyList)
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" History ",false,{},true,
|
||||
GetDlgItem(dialog,historyList)))
|
||||
return painted;
|
||||
if(message==WM_DRAWITEM && wp==historyList)
|
||||
{
|
||||
const auto &item=*reinterpret_cast<DRAWITEMSTRUCT*>(lp);
|
||||
if(item.itemID==UINT(-1)) return TRUE;
|
||||
const auto count=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
|
||||
if(count<0) return TRUE;
|
||||
std::wstring label(static_cast<size_t>(count)+1,L'\0');
|
||||
SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()));
|
||||
label.resize(count);
|
||||
const bool selected=(item.itemState&ODS_SELECTED)!=0 && item.itemData<terminalHistory.size();
|
||||
const auto background=colors[selected?Selection:Dialog];
|
||||
const auto ink=colors[Text];
|
||||
if(item.itemData==static_cast<ULONG_PTR>(-1))
|
||||
{
|
||||
auto bounds=item.rcItem;
|
||||
InflateRect(&bounds,-historyRowInset(GetDpiForWindow(dialog)),0);
|
||||
const auto saved=SaveDC(item.hDC);
|
||||
SelectObject(item.hDC,mono);
|
||||
SetBkColor(item.hDC,background);
|
||||
SetTextColor(item.hDC,ink);
|
||||
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&bounds,nullptr,0,nullptr);
|
||||
const auto middle=(bounds.top+bounds.bottom)/2;
|
||||
RECT rule{bounds.left,middle,bounds.right,middle+1};
|
||||
SetBkColor(item.hDC,ink);
|
||||
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&rule,nullptr,0,nullptr);
|
||||
SIZE size{};
|
||||
GetTextExtentPoint32W(item.hDC,label.c_str(),static_cast<int>(label.size()),&size);
|
||||
const auto left=(bounds.left+bounds.right-size.cx)/2;
|
||||
RECT caption{left-cellWidth,bounds.top,left+size.cx+cellWidth,bounds.bottom};
|
||||
SetBkColor(item.hDC,background);
|
||||
ExtTextOutW(item.hDC,left,middle-size.cy/2,ETO_OPAQUE,&caption,label.c_str(),
|
||||
static_cast<UINT>(label.size()),nullptr);
|
||||
RestoreDC(item.hDC,saved);
|
||||
}
|
||||
else paintDialogListRow(item.hDC,item.rcItem,label,mono,ink,background,
|
||||
historyRowInset(GetDpiForWindow(dialog)),DT_END_ELLIPSIS);
|
||||
if(selected && (item.itemState&ODS_FOCUS)) DrawFocusRect(item.hDC,&item.rcItem);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND && (LOWORD(wp)==IDOK || (LOWORD(wp)==historyList && HIWORD(wp)==LBN_DBLCLK)))
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,historyList,LB_GETCURSEL,0,0);
|
||||
const auto index=SendDlgItemMessageW(dialog,historyList,LB_GETITEMDATA,row,0);
|
||||
if(index>=0 && static_cast<size_t>(index)<terminalHistory.size())
|
||||
{
|
||||
auto &choice=*reinterpret_cast<size_t *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
choice=static_cast<size_t>(index);
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void refreshCommandHistory()
|
||||
{
|
||||
if(commandHistoryWindow) populateCommandHistory(commandHistoryWindow);
|
||||
layoutOpenCommandHistory();
|
||||
}
|
||||
|
||||
void showCommandHistory(HWND owner)
|
||||
{
|
||||
if(commandHistoryWindow) return;
|
||||
size_t choice{};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(111),owner,commandHistoryDialog,
|
||||
reinterpret_cast<LPARAM>(&choice))==IDOK)
|
||||
recallCommand(choice);
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
HWND activeFilesDialog{};
|
||||
HHOOK filesDialogMouseHook{};
|
||||
|
||||
bool filesMouseDown(UINT message)
|
||||
{
|
||||
return message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN ||
|
||||
message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN;
|
||||
}
|
||||
|
||||
bool handleFilesDialogClick(HWND dialog,HWND clicked,POINT point)
|
||||
{
|
||||
if(!clicked || clicked==dialog || IsChild(dialog,clicked) ||
|
||||
GetAncestor(clicked,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER))
|
||||
return false;
|
||||
|
||||
wchar_t windowClass[16]{};
|
||||
if(GetClassNameW(clicked,windowClass,16) && std::wstring_view(windowClass)==L"#32768")
|
||||
{
|
||||
GUITHREADINFO thread{sizeof(thread)};
|
||||
if(GetGUIThreadInfo(GetWindowThreadProcessId(dialog,nullptr),&thread) &&
|
||||
(thread.hwndMenuOwner==dialog || IsChild(dialog,thread.hwndMenuOwner)))
|
||||
return false;
|
||||
}
|
||||
// System pickers and dropdowns owned by this dialog handle their own input.
|
||||
for(auto popup=GetAncestor(clicked,GA_ROOT);popup;popup=GetWindow(popup,GW_OWNER))
|
||||
if(popup==dialog || IsChild(dialog,popup)) return false;
|
||||
for(auto owner=GetWindow(dialog,GW_OWNER);owner;owner=GetWindow(owner,GW_OWNER))
|
||||
{
|
||||
if(clicked!=owner) continue;
|
||||
RECT client{};
|
||||
GetClientRect(owner,&client);
|
||||
ScreenToClient(owner,&point);
|
||||
if(!PtInRect(&client,point)) return false;
|
||||
break;
|
||||
}
|
||||
if(const auto dropdown=static_cast<HWND>(GetPropW(dialog,ks::files::farDropDownProperty)))
|
||||
return PostMessageW(dropdown,WM_CLOSE,0,0)!=FALSE;
|
||||
return PostMessageW(dialog,WM_COMMAND,IDCANCEL,0)!=FALSE;
|
||||
}
|
||||
|
||||
LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data)
|
||||
{
|
||||
const auto dialog=activeFilesDialog;
|
||||
if(code==HC_ACTION && dialog && IsWindowVisible(dialog) && filesMouseDown(static_cast<UINT>(message)))
|
||||
{
|
||||
const auto point=reinterpret_cast<const MSLLHOOKSTRUCT*>(data)->pt;
|
||||
if(handleFilesDialogClick(dialog,WindowFromPoint(point),point)) return 1;
|
||||
}
|
||||
return CallNextHookEx(nullptr,code,message,data);
|
||||
}
|
||||
|
||||
class FilesModalDialog
|
||||
{
|
||||
public:
|
||||
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
|
||||
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument)
|
||||
{
|
||||
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
|
||||
}
|
||||
|
||||
~FilesModalDialog() { close(); }
|
||||
FilesModalDialog(const FilesModalDialog &)=delete;
|
||||
FilesModalDialog &operator=(const FilesModalDialog &)=delete;
|
||||
|
||||
HWND window() const { return window_; }
|
||||
|
||||
static HWND activeFor(HWND owner)
|
||||
{
|
||||
const auto root=GetAncestor(owner,GA_ROOTOWNER);
|
||||
for(auto dialog=activeFilesDialog;dialog;)
|
||||
{
|
||||
if(GetAncestor(dialog,GA_ROOTOWNER)==root) return dialog;
|
||||
const auto *state=reinterpret_cast<const FilesModalDialog *>(GetPropW(dialog,stateProperty_));
|
||||
dialog=state?state->previous_:nullptr;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static void fitWidthToOwner(HWND dialog,int minimum,void (*layout)(HWND))
|
||||
{
|
||||
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
|
||||
RECT bounds{};
|
||||
if(!state || !GetWindowRect(dialog,&bounds)) return;
|
||||
state->preferredWidth_=bounds.right-bounds.left;
|
||||
state->minimumWidth_=minimum;
|
||||
state->layout_=layout;
|
||||
}
|
||||
|
||||
static void refreshLayout(HWND dialog)
|
||||
{
|
||||
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
|
||||
if(!state || !state->entered_ || state->layout_) return;
|
||||
state->captureLayout();
|
||||
state->fitWidth(dialog,state->ownerBounds_);
|
||||
}
|
||||
|
||||
static bool dismissOwned(HWND owner)
|
||||
{
|
||||
const auto dialog=activeFor(owner);
|
||||
for(auto parent=GetWindow(dialog,GW_OWNER);parent;parent=GetWindow(parent,GW_OWNER))
|
||||
if(parent==owner) return PostMessageW(dialog,WM_CLOSE,0,0)!=FALSE;
|
||||
return false;
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
if(!window_ || entered_) return;
|
||||
previous_=activeFilesDialog;
|
||||
activeFilesDialog=window_;
|
||||
entered_=true;
|
||||
if(!filesDialogMouseHook)
|
||||
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
|
||||
if(GetWindowRect(owner_,&ownerBounds_))
|
||||
{
|
||||
if(!layout_) captureLayout();
|
||||
SetWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this),reinterpret_cast<DWORD_PTR>(this));
|
||||
if(ownerBounds_.right-ownerBounds_.left<minimumOwnerWidth() && !IsZoomed(owner_))
|
||||
SetWindowPos(owner_,nullptr,0,0,minimumOwnerWidth(),ownerBounds_.bottom-ownerBounds_.top,
|
||||
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
fitWidth(window_,ownerBounds_,true);
|
||||
}
|
||||
ShowWindow(window_,SW_SHOW);
|
||||
SetActiveWindow(window_);
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
if(entered_ && IsWindow(owner_))
|
||||
RemoveWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this));
|
||||
if(window_ && IsWindow(window_)) DestroyWindow(window_);
|
||||
window_=nullptr;
|
||||
if(!entered_) return;
|
||||
entered_=false;
|
||||
activeFilesDialog=previous_;
|
||||
if(!previous_ && filesDialogMouseHook)
|
||||
{
|
||||
UnhookWindowsHookEx(filesDialogMouseHook);
|
||||
filesDialogMouseHook=nullptr;
|
||||
}
|
||||
if(IsWindow(owner_) && !IsIconic(GetAncestor(owner_,GA_ROOTOWNER)))
|
||||
{
|
||||
SetActiveWindow(owner_);
|
||||
if(IsWindow(focus_) && IsWindowEnabled(focus_) && (focus_==owner_ || IsChild(owner_,focus_)))
|
||||
SetFocus(focus_);
|
||||
}
|
||||
}
|
||||
|
||||
static bool handleMessage(HWND dialog,MSG &message)
|
||||
{
|
||||
if(message.hwnd==dialog || IsChild(dialog,message.hwnd))
|
||||
{
|
||||
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
|
||||
{
|
||||
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
|
||||
return true;
|
||||
}
|
||||
return IsDialogMessageW(dialog,&message)!=FALSE;
|
||||
}
|
||||
if(!message.hwnd || GetAncestor(message.hwnd,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER))
|
||||
return false;
|
||||
const bool input=(message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) ||
|
||||
(message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST) ||
|
||||
message.message==WM_CONTEXTMENU;
|
||||
if(input && (filesMouseDown(message.message) ||
|
||||
(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)))
|
||||
PostMessageW(dialog,WM_COMMAND,IDCANCEL,0);
|
||||
return input;
|
||||
}
|
||||
|
||||
static void finish(HWND dialog,INT_PTR answer)
|
||||
{
|
||||
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
|
||||
if(!state) return;
|
||||
state->result_=answer;
|
||||
state->finished_=true;
|
||||
ShowWindow(dialog,SW_HIDE);
|
||||
}
|
||||
|
||||
static INT_PTR run(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
|
||||
{
|
||||
FilesModalDialog dialog(instance,resource,owner,procedure,argument);
|
||||
if(!dialog.window()) return -1;
|
||||
dialog.show();
|
||||
MSG message{};
|
||||
while(!dialog.finished_ && IsWindow(dialog.window()))
|
||||
{
|
||||
const auto status=GetMessageW(&message,nullptr,0,0);
|
||||
if(status<=0)
|
||||
{
|
||||
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
|
||||
break;
|
||||
}
|
||||
if(handleMessage(dialog.window(),message)) continue;
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
return dialog.result_;
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr wchar_t stateProperty_[]=L"KSwitcher.Files.ModalDialog";
|
||||
HWND window_{},owner_{},focus_{},previous_{};
|
||||
RECT ownerBounds_{};
|
||||
int preferredWidth_{},minimumWidth_{};
|
||||
std::vector<std::pair<HWND,RECT>> controls_;
|
||||
void (*layout_)(HWND){};
|
||||
DLGPROC procedure_;
|
||||
LPARAM argument_;
|
||||
INT_PTR result_=IDCANCEL;
|
||||
bool entered_{},finished_{};
|
||||
|
||||
void captureLayout()
|
||||
{
|
||||
RECT bounds{};
|
||||
GetWindowRect(window_,&bounds);
|
||||
preferredWidth_=bounds.right-bounds.left;
|
||||
minimumWidth_=MulDiv(preferredWidth_,3,4);
|
||||
controls_.clear();
|
||||
if(GetWindowLongPtrW(window_,GWL_STYLE)&WS_THICKFRAME)
|
||||
{
|
||||
MINMAXINFO limits{};
|
||||
SendMessageW(window_,WM_GETMINMAXINFO,0,reinterpret_cast<LPARAM>(&limits));
|
||||
minimumWidth_=std::max<int>(minimumWidth_,limits.ptMinTrackSize.x);
|
||||
return;
|
||||
}
|
||||
const auto dc=GetDC(window_);
|
||||
if(!dc) return;
|
||||
for(auto field=GetWindow(window_,GW_CHILD);field;field=GetWindow(field,GW_HWNDNEXT))
|
||||
{
|
||||
RECT rect{};
|
||||
GetWindowRect(field,&rect);
|
||||
MapWindowPoints(nullptr,window_,reinterpret_cast<POINT *>(&rect),2);
|
||||
wchar_t type[16]{},label[128]{};
|
||||
GetClassNameW(field,type,16);
|
||||
RECT dropdown{};
|
||||
if(lstrcmpiW(type,L"ComboBox")==0 &&
|
||||
SendMessageW(field,CB_GETDROPPEDCONTROLRECT,0,reinterpret_cast<LPARAM>(&dropdown)))
|
||||
rect.bottom=rect.top+dropdown.bottom-dropdown.top;
|
||||
controls_.emplace_back(field,rect);
|
||||
const auto fieldWidth=rect.right-rect.left;
|
||||
if(!(GetWindowLongPtrW(field,GWL_STYLE)&WS_VISIBLE) || fieldWidth<=0) continue;
|
||||
if(lstrcmpiW(type,L"Button")!=0 || !GetWindowTextW(field,label,128)) continue;
|
||||
const auto font=reinterpret_cast<HFONT>(SendMessageW(field,WM_GETFONT,0,0));
|
||||
const auto previous=font?SelectObject(dc,font):nullptr;
|
||||
RECT text{};
|
||||
DrawTextW(dc,label,-1,&text,DT_SINGLELINE|DT_CALCRECT);
|
||||
TEXTMETRICW metrics{};
|
||||
GetTextMetricsW(dc,&metrics);
|
||||
if(previous) SelectObject(dc,previous);
|
||||
const auto needed=std::min(fieldWidth,text.right+4*metrics.tmAveCharWidth);
|
||||
minimumWidth_=std::max(minimumWidth_,static_cast<int>(
|
||||
(preferredWidth_*needed+fieldWidth-1)/fieldWidth));
|
||||
}
|
||||
ReleaseDC(window_,dc);
|
||||
}
|
||||
|
||||
int ownerMargin() const { return MulDiv(12,GetDpiForWindow(owner_),96); }
|
||||
int minimumOwnerWidth() const { return minimumWidth_+2*ownerMargin(); }
|
||||
|
||||
void fitWidth(HWND window,const RECT &owner,bool initial=false)
|
||||
{
|
||||
RECT bounds{};
|
||||
if(!GetWindowRect(window,&bounds)) return;
|
||||
const int width=std::clamp(static_cast<int>(owner.right-owner.left)-2*ownerMargin(),
|
||||
minimumWidth_,std::max(minimumWidth_,preferredWidth_));
|
||||
const int height=bounds.bottom-bounds.top;
|
||||
const int x=(owner.left+owner.right-width)/2;
|
||||
const int y=(owner.top+owner.bottom-height)/2;
|
||||
const bool resized=width!=bounds.right-bounds.left;
|
||||
if(x!=bounds.left || y!=bounds.top || resized)
|
||||
SetWindowPos(window,nullptr,x,y,width,height,SWP_NOZORDER|SWP_NOACTIVATE|
|
||||
(resized?SWP_NOCOPYBITS:0));
|
||||
if(layout_ && (initial || resized)) layout_(window);
|
||||
else if(resized && preferredWidth_>0)
|
||||
for(const auto &[field,rect]:controls_)
|
||||
{
|
||||
const auto left=MulDiv(rect.left,width,preferredWidth_);
|
||||
const auto right=MulDiv(rect.right,width,preferredWidth_);
|
||||
SetWindowPos(field,nullptr,left,rect.top,right-left,rect.bottom-rect.top,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
|
||||
}
|
||||
if(initial || resized) RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK trackOwner(HWND owner,UINT message,WPARAM wp,LPARAM lp,UINT_PTR id,DWORD_PTR data)
|
||||
{
|
||||
auto &dialog=*reinterpret_cast<FilesModalDialog *>(data);
|
||||
if(message==WM_WINDOWPOSCHANGING && !IsIconic(owner))
|
||||
{
|
||||
auto &position=*reinterpret_cast<WINDOWPOS *>(lp);
|
||||
if(!(position.flags&SWP_NOSIZE) && position.cx>0)
|
||||
position.cx=std::max(position.cx,dialog.minimumOwnerWidth());
|
||||
}
|
||||
if(message==WM_NCDESTROY) RemoveWindowSubclass(owner,trackOwner,id);
|
||||
const auto result=DefSubclassProc(owner,message,wp,lp);
|
||||
if(message==WM_GETMINMAXINFO)
|
||||
{
|
||||
auto &limits=*reinterpret_cast<MINMAXINFO *>(lp);
|
||||
limits.ptMinTrackSize.x=std::max<LONG>(limits.ptMinTrackSize.x,dialog.minimumOwnerWidth());
|
||||
return result;
|
||||
}
|
||||
if((message!=WM_MOVE && message!=WM_SIZE) || IsIconic(owner)) return result;
|
||||
RECT ownerBounds{};
|
||||
if(!GetWindowRect(owner,&ownerBounds)) return result;
|
||||
if(EqualRect(&ownerBounds,&dialog.ownerBounds_)) return result;
|
||||
dialog.ownerBounds_=ownerBounds;
|
||||
dialog.fitWidth(dialog.window_,ownerBounds);
|
||||
return result;
|
||||
}
|
||||
|
||||
static INT_PTR CALLBACK dispatchDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
state=reinterpret_cast<FilesModalDialog *>(lp);
|
||||
if(!SetPropW(dialog,stateProperty_,state)) return FALSE;
|
||||
lp=state->argument_;
|
||||
}
|
||||
if(!state) return FALSE;
|
||||
const auto handled=state->procedure_(dialog,message,wp,lp);
|
||||
if(message==WM_NCDESTROY) RemovePropW(dialog,stateProperty_);
|
||||
if(!handled && message==WM_CLOSE)
|
||||
{
|
||||
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
|
||||
return TRUE;
|
||||
}
|
||||
return handled;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <algorithm>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline void paintFarDropDownArrow(HDC dc, const RECT &bounds, HBRUSH surface, COLORREF ink, UINT dpi)
|
||||
{
|
||||
FillRect(dc, &bounds, surface);
|
||||
// Center the drawn pixels. A font's arrow glyph can sit below the center of its line box.
|
||||
const auto halfWidth = std::min((bounds.right - bounds.left - 1) / 2,
|
||||
static_cast<LONG>(MulDiv(3, dpi, 96)));
|
||||
const auto halfHeight = std::min((bounds.bottom - bounds.top - 1) / 2,
|
||||
static_cast<LONG>(MulDiv(5, dpi, 96)));
|
||||
if (halfWidth < 1 || halfHeight < 1) return;
|
||||
const auto x = (bounds.left + bounds.right - 1) / 2;
|
||||
const auto y = (bounds.top + bounds.bottom - 1) / 2;
|
||||
const auto tip = y + halfHeight;
|
||||
const auto head = std::min(halfWidth, halfHeight);
|
||||
for (LONG row = y - halfHeight; row <= tip; ++row)
|
||||
SetPixelV(dc, x, row, ink);
|
||||
for (LONG offset = 1; offset <= head; ++offset)
|
||||
{
|
||||
SetPixelV(dc, x - offset, tip - offset, ink);
|
||||
SetPixelV(dc, x + offset, tip - offset, ink);
|
||||
}
|
||||
}
|
||||
|
||||
inline void paintFarFieldArrow(HDC dc, const RECT &bounds, bool enabled, UINT dpi)
|
||||
{
|
||||
paintFarDropDownArrow(dc, bounds, static_cast<HBRUSH>(GetStockObject(LTGRAY_BRUSH)),
|
||||
enabled ? RGB(0,0,0) : RGB(48,48,48), dpi);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
struct FolderShortcut
|
||||
{
|
||||
fs::path path;
|
||||
std::string peerId;
|
||||
std::wstring peerName,title;
|
||||
};
|
||||
using FolderShortcuts=std::array<std::vector<FolderShortcut>,10>;
|
||||
FolderShortcuts folderShortcuts;
|
||||
constexpr wchar_t folderShortcutsKey[]=L"FolderShortcuts";
|
||||
|
||||
bool sameFolderShortcut(const FolderShortcut &left,const FolderShortcut &right)
|
||||
{
|
||||
return left.peerId==right.peerId &&
|
||||
CompareStringOrdinal(left.path.c_str(),-1,right.path.c_str(),-1,TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
bool saveFolderShortcuts(const FolderShortcuts &shortcuts)
|
||||
{
|
||||
try
|
||||
{
|
||||
auto groups=Json::array();
|
||||
for(const auto &group:shortcuts)
|
||||
{
|
||||
auto rows=Json::array();
|
||||
for(const auto &entry:group)
|
||||
rows.push_back({{"path",ks::utf8(entry.path.native())},{"peer",entry.peerId},
|
||||
{"name",ks::utf8(entry.peerName)},{"title",ks::utf8(entry.title)}});
|
||||
groups.push_back(std::move(rows));
|
||||
}
|
||||
const auto data=groups.dump();
|
||||
return data.size()<=1024*1024 &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
}
|
||||
catch(const std::exception &){return false;}
|
||||
}
|
||||
|
||||
void loadFolderShortcuts()
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>1024*1024) return;
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return;
|
||||
try
|
||||
{
|
||||
const auto groups=Json::parse(data.begin(),data.begin()+bytes);
|
||||
if(!groups.is_array() || groups.size()!=folderShortcuts.size()) return;
|
||||
FolderShortcuts loaded;
|
||||
for(size_t digit=0;digit<loaded.size();++digit)
|
||||
{
|
||||
if(!groups[digit].is_array()) return;
|
||||
for(const auto &row:groups[digit])
|
||||
{
|
||||
FolderShortcut entry{filePath(row.at("path")),row.at("peer"),ks::wide(row.at("name")),ks::wide(row.value("title",""))};
|
||||
if(!entry.path.is_absolute() || entry.path.native().find(L'\0')!=std::wstring::npos) continue;
|
||||
loaded[digit].push_back(std::move(entry));
|
||||
}
|
||||
}
|
||||
folderShortcuts=std::move(loaded);
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
}
|
||||
|
||||
constexpr int shortcutTitle=314,shortcutPath=211;
|
||||
|
||||
struct FolderShortcutEdit
|
||||
{
|
||||
FolderShortcut entry;
|
||||
int digit;
|
||||
std::optional<size_t> index;
|
||||
};
|
||||
|
||||
std::wstring shortcutField(HWND dialog,int id)
|
||||
{
|
||||
const auto field=GetDlgItem(dialog,id);
|
||||
const auto length=GetWindowTextLengthW(field);
|
||||
std::wstring result(static_cast<size_t>(length)+1,L'\0');
|
||||
result.resize(GetWindowTextW(field,result.data(),length+1));
|
||||
return result;
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Folder shortcuts ",false,{315}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &edit=*reinterpret_cast<FolderShortcutEdit*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareCopyDialog(dialog);
|
||||
layoutDialogContent(dialog,316);
|
||||
for(const auto id:{316,317,IDOK,IDCANCEL})
|
||||
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
SendDlgItemMessageW(dialog,shortcutTitle,EM_SETLIMITTEXT,255,0);
|
||||
SendDlgItemMessageW(dialog,shortcutPath,EM_SETLIMITTEXT,32767,0);
|
||||
SetDlgItemTextW(dialog,shortcutTitle,edit.entry.title.c_str());
|
||||
SetDlgItemTextW(dialog,shortcutPath,edit.entry.path.c_str());
|
||||
if(!edit.entry.peerId.empty())
|
||||
SetDlgItemTextW(dialog,317,(L"Path on "+edit.entry.peerName).c_str());
|
||||
layoutDialogButtons(dialog,315,{IDOK,IDCANCEL});
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
|
||||
auto &edit=*reinterpret_cast<FolderShortcutEdit*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
auto path=fs::path(shortcutField(dialog,shortcutPath)).lexically_normal();
|
||||
if(path.has_relative_path() && !path.has_filename()) path=path.parent_path();
|
||||
const auto root=path.root_name().native();
|
||||
const bool lanDrive=root.size()==2 && root[1]==L':' &&
|
||||
((root[0]>=L'A' && root[0]<=L'Z') || (root[0]>=L'a' && root[0]<=L'z'));
|
||||
if(!path.is_absolute() || (!edit.entry.peerId.empty() && !lanDrive))
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter an absolute folder path on the original computer.",L"Folder shortcuts");
|
||||
SetFocus(GetDlgItem(dialog,shortcutPath));
|
||||
return TRUE;
|
||||
}
|
||||
auto entry=edit.entry;
|
||||
entry.path=std::move(path);
|
||||
entry.title=shortcutField(dialog,shortcutTitle);
|
||||
const auto &group=folderShortcuts[edit.digit];
|
||||
for(size_t i=0;i<group.size();++i)
|
||||
if((!edit.index || i!=*edit.index) && sameFolderShortcut(group[i],entry))
|
||||
{
|
||||
showFilesNotice(dialog,L"This folder is already assigned to this digit.",L"Folder shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
auto updated=folderShortcuts;
|
||||
if(edit.index) updated[edit.digit][*edit.index]=std::move(entry);
|
||||
else updated[edit.digit].push_back(std::move(entry));
|
||||
if(!saveFolderShortcuts(updated))
|
||||
{
|
||||
showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
folderShortcuts=std::move(updated);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
|
||||
{
|
||||
return FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(110),owner,
|
||||
folderShortcutEditDialog,reinterpret_cast<LPARAM>(&edit))==IDOK;
|
||||
}
|
||||
|
||||
void addFolderShortcut(const Panel &panel,int digit)
|
||||
{
|
||||
if(panel.directory.empty()) return;
|
||||
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
|
||||
panel.peer?panel.peer->name:L""},digit,{}};
|
||||
if(editFolderShortcut(GetParent(panel.list),edit))
|
||||
setStatus(L"Folder added to Ctrl+"+std::to_wstring(digit)+L".");
|
||||
SetFocus(panel.list);
|
||||
}
|
||||
|
||||
void openFolderShortcut(Panel &panel,const FolderShortcut &entry)
|
||||
{
|
||||
if(entry.peerId.empty())
|
||||
{
|
||||
openOn(panel,entry.path,true,{});
|
||||
return;
|
||||
}
|
||||
queryDrivePeers();
|
||||
const auto peer=std::find_if(drivePeers.begin(),drivePeers.end(),
|
||||
[&](const auto &candidate){return candidate.id==entry.peerId && !candidate.address.empty();});
|
||||
if(peer==drivePeers.end())
|
||||
{
|
||||
setStatus(L"Paired computer unavailable: "+entry.peerName);
|
||||
return;
|
||||
}
|
||||
openOn(panel,entry.path,false,*peer);
|
||||
}
|
||||
|
||||
constexpr int shortcutList=310,quickRemove=313,quickEdit=318,quickInsert=319,quickMoveUp=320,quickMoveDown=321;
|
||||
constexpr wchar_t quickFolderHints[]=L"Ins Del F4 Ctrl+Up Ctrl+Down";
|
||||
struct FolderShortcutView
|
||||
{
|
||||
int digit;
|
||||
std::optional<FolderShortcut> chosen;
|
||||
std::vector<int> digits;
|
||||
int rowHeight{};
|
||||
Panel *panel{};
|
||||
};
|
||||
|
||||
std::wstring shortcutLabel(const FolderShortcut &entry)
|
||||
{
|
||||
return entry.title.empty()?(entry.peerId.empty()?L"":entry.peerName+L" · ")+entry.path.native():entry.title;
|
||||
}
|
||||
|
||||
void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
|
||||
{
|
||||
const auto list=GetDlgItem(dialog,shortcutList);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
view.digits.clear();
|
||||
const auto owner=GetWindow(dialog,GW_OWNER);
|
||||
const auto dc=GetDC(dialog);
|
||||
const auto font=SelectObject(dc,mono);
|
||||
const auto dpi=GetDpiForWindow(dialog);
|
||||
const auto px=[&](int value){return MulDiv(value,dpi,96);};
|
||||
TEXTMETRICW metrics{};
|
||||
GetTextMetricsW(dc,&metrics);
|
||||
view.rowHeight=std::max(1L,metrics.tmHeight);
|
||||
const auto frame=dialogFrameMetrics(dpi);
|
||||
const int inset=frame.content();
|
||||
const int listTop=dialogListInset(frame,view.rowHeight);
|
||||
const auto measure=[&](std::wstring_view label)
|
||||
{
|
||||
SIZE size{};
|
||||
GetTextExtentPoint32W(dc,label.data(),static_cast<int>(label.size()),&size);
|
||||
return static_cast<int>(size.cx);
|
||||
};
|
||||
int width=std::max(measure(L"Folder shortcuts"),measure(view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
|
||||
const int textInset=dialogRowTextInset(cellWidth);
|
||||
const auto add=[&](const std::wstring &label)
|
||||
{
|
||||
width=std::max(width,measure(label)+2*textInset);
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
};
|
||||
if(view.digit<0)
|
||||
{
|
||||
for(int digit=0;digit<10;++digit)
|
||||
if(!folderShortcuts[digit].empty())
|
||||
{
|
||||
view.digits.push_back(digit);
|
||||
add(L"Ctrl+"+std::to_wstring(digit));
|
||||
}
|
||||
}
|
||||
else for(const auto &entry:folderShortcuts[view.digit])
|
||||
add(shortcutLabel(entry));
|
||||
SelectObject(dc,font);
|
||||
ReleaseDC(dialog,dc);
|
||||
MONITORINFO monitor{sizeof(monitor)};
|
||||
GetMonitorInfoW(MonitorFromWindow(owner,MONITOR_DEFAULTTONEAREST),&monitor);
|
||||
const auto &work=monitor.rcWork;
|
||||
RECT parent{};
|
||||
GetWindowRect(owner,&parent);
|
||||
const auto windowWidth=std::max(px(260),static_cast<int>(parent.right-parent.left));
|
||||
const auto windowHeight=std::max(px(140),static_cast<int>(parent.bottom-parent.top));
|
||||
width=std::min(width+scrollBarWidth(list),
|
||||
std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
|
||||
const auto maxRows=std::max(1,(std::min(windowHeight,static_cast<int>(work.bottom-work.top))-2*listTop)/view.rowHeight);
|
||||
const auto count=static_cast<int>(SendMessageW(list,LB_GETCOUNT,0,0));
|
||||
const int rows=std::min(count,maxRows);
|
||||
SendMessageW(list,LB_SETITEMHEIGHT,0,view.rowHeight);
|
||||
const int listHeight=rows*view.rowHeight;
|
||||
const int w=width+2*inset,h=listHeight+2*listTop;
|
||||
const int x=std::clamp(static_cast<int>((parent.left+parent.right-w)/2),
|
||||
static_cast<int>(work.left),std::max(static_cast<int>(work.left),static_cast<int>(work.right)-w));
|
||||
const int y=std::clamp(static_cast<int>((parent.top+parent.bottom-h)/2),
|
||||
static_cast<int>(work.top),std::max(static_cast<int>(work.top),static_cast<int>(work.bottom)-h));
|
||||
SetWindowPos(dialog,nullptr,x,y,w,h,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SetWindowPos(list,nullptr,inset,listTop,std::max(1,width-scrollBarWidth(list)),listHeight,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SendMessageW(list,LB_SETCURSEL,std::clamp(selection,0,std::max(0,count-1)),0);
|
||||
InvalidateRect(dialog,nullptr,TRUE);
|
||||
FilesModalDialog::refreshLayout(dialog);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_KEYDOWN)
|
||||
{
|
||||
int command=0;
|
||||
if(key==VK_RETURN) command=IDOK;
|
||||
if(key==VK_DELETE) command=quickRemove;
|
||||
if(key==VK_F4) command=quickEdit;
|
||||
if(key==VK_INSERT) command=quickInsert;
|
||||
if((key==VK_UP || key==VK_DOWN) && (GetKeyState(VK_CONTROL)&0x8000))
|
||||
command=key==VK_UP?quickMoveUp:quickMoveDown;
|
||||
if(command)
|
||||
{
|
||||
if(!(flags & (1LL<<30))) SendMessageW(GetParent(list),WM_COMMAND,command,0);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return DefSubclassProc(list,message,key,flags);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &view=*reinterpret_cast<FolderShortcutView*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareCopyDialog(dialog);
|
||||
layoutQuickFolders(dialog,view,0);
|
||||
const auto list=GetDlgItem(dialog,shortcutList);
|
||||
SetWindowSubclass(list,quickFolderKeys,1,0);
|
||||
installScrollBar(list,dialog);
|
||||
SetFocus(list);
|
||||
return FALSE;
|
||||
}
|
||||
auto *view=reinterpret_cast<FolderShortcutView*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!view) return FALSE;
|
||||
if(message==WM_DESTROY)
|
||||
{
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_PAINT)
|
||||
{
|
||||
PAINTSTRUCT ps{};
|
||||
const auto dc=BeginPaint(dialog,&ps);
|
||||
RECT client{};
|
||||
GetClientRect(dialog,&client);
|
||||
const auto frame=CreateSolidBrush(colors[Text]);
|
||||
const auto bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),teal,frame);
|
||||
DeleteObject(frame);
|
||||
paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono,
|
||||
view->digit<0?L"Enter Esc":quickFolderHints);
|
||||
paintScrollPosition(dialog,dc,GetDlgItem(dialog,shortcutList),colors[Dialog]);
|
||||
EndPaint(dialog,&ps);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_DRAWITEM && wp==shortcutList)
|
||||
{
|
||||
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT*>(lp);
|
||||
if(item.itemID==UINT(-1)) return TRUE;
|
||||
const auto length=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
|
||||
if(length<0) return TRUE;
|
||||
std::wstring label(static_cast<size_t>(length)+1,L'\0');
|
||||
SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()));
|
||||
const auto background=colors[item.itemState&ODS_SELECTED?Selection:Dialog];
|
||||
paintDialogListRow(item.hDC,item.rcItem,std::wstring_view(label.data(),static_cast<size_t>(length)),
|
||||
mono,colors[Text],background,dialogRowTextInset(cellWidth));
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
const auto action=LOWORD(wp);
|
||||
if(action!=quickRemove && action!=quickEdit && action!=quickInsert && action!=quickMoveUp &&
|
||||
action!=quickMoveDown && action!=IDOK && !(action==shortcutList && HIWORD(wp)==LBN_DBLCLK)) return FALSE;
|
||||
const auto row=SendDlgItemMessageW(dialog,shortcutList,LB_GETCURSEL,0,0);
|
||||
if(view->digit<0)
|
||||
{
|
||||
if((action==IDOK || action==shortcutList) && row>=0 && static_cast<size_t>(row)<view->digits.size())
|
||||
{
|
||||
view->digit=view->digits[row];
|
||||
layoutQuickFolders(dialog,*view,0);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
const auto digit=view->digit;
|
||||
const auto index=static_cast<size_t>(row);
|
||||
const auto &group=folderShortcuts[digit];
|
||||
if(action==quickInsert)
|
||||
{
|
||||
const auto &panel=*view->panel;
|
||||
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
|
||||
panel.peer?panel.peer->name:L""},view->digit,{}};
|
||||
if(!panel.directory.empty() && editFolderShortcut(dialog,edit))
|
||||
layoutQuickFolders(dialog,*view,static_cast<int>(group.size())-1);
|
||||
SetFocus(GetDlgItem(dialog,shortcutList));
|
||||
return TRUE;
|
||||
}
|
||||
if(index>=group.size()) return TRUE;
|
||||
if(action==quickMoveUp || action==quickMoveDown)
|
||||
{
|
||||
const auto target=row+(action==quickMoveUp?-1:1);
|
||||
if(target<0 || static_cast<size_t>(target)>=group.size()) return TRUE;
|
||||
auto updated=folderShortcuts;
|
||||
std::swap(updated[view->digit][row],updated[view->digit][target]);
|
||||
if(!saveFolderShortcuts(updated))
|
||||
showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts");
|
||||
else
|
||||
{
|
||||
folderShortcuts=std::move(updated);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
layoutQuickFolders(dialog,*view,static_cast<int>(target));
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(action==quickEdit)
|
||||
{
|
||||
FolderShortcutEdit edit{group[index],digit,index};
|
||||
if(editFolderShortcut(dialog,edit)) layoutQuickFolders(dialog,*view,static_cast<int>(row));
|
||||
SetFocus(GetDlgItem(dialog,shortcutList));
|
||||
return TRUE;
|
||||
}
|
||||
if(action==quickRemove)
|
||||
{
|
||||
auto updated=folderShortcuts;
|
||||
updated[digit].erase(updated[digit].begin()+index);
|
||||
if(!saveFolderShortcuts(updated))
|
||||
{
|
||||
showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts");
|
||||
return TRUE;
|
||||
}
|
||||
folderShortcuts=std::move(updated);
|
||||
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
|
||||
if(folderShortcuts[digit].empty()) FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
else layoutQuickFolders(dialog,*view,static_cast<int>(row));
|
||||
return TRUE;
|
||||
}
|
||||
view->chosen=group[index];
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
void showFolderShortcuts(Panel &panel,int digit)
|
||||
{
|
||||
if(digit>=0)
|
||||
{
|
||||
const auto &group=folderShortcuts[digit];
|
||||
if(group.empty())
|
||||
{
|
||||
setStatus(L"No folders assigned to Ctrl+"+std::to_wstring(digit)+L".");
|
||||
return;
|
||||
}
|
||||
if(group.size()==1)
|
||||
{
|
||||
openFolderShortcut(panel,group.front());
|
||||
return;
|
||||
}
|
||||
}
|
||||
if(digit<0 && std::all_of(folderShortcuts.begin(),folderShortcuts.end(),[](const auto &group){return group.empty();}))
|
||||
{
|
||||
setStatus(L"No folder shortcuts.");
|
||||
return;
|
||||
}
|
||||
FolderShortcutView view{digit};
|
||||
view.panel=&panel;
|
||||
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list),
|
||||
quickFolderDialog,reinterpret_cast<LPARAM>(&view));
|
||||
SetFocus(panel.list);
|
||||
if(result==IDOK && view.chosen) openFolderShortcut(panel,*view.chosen);
|
||||
else if(result==-1) setStatus(L"Could not open Folder shortcuts.");
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <string>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline std::wstring historyDate()
|
||||
{
|
||||
SYSTEMTIME now{};
|
||||
GetLocalTime(&now);
|
||||
wchar_t date[24]{};
|
||||
GetDateFormatEx(LOCALE_NAME_USER_DEFAULT,0,&now,L"dd.MM.yyyy",date,24,nullptr);
|
||||
return date;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <algorithm>
|
||||
#include <string_view>
|
||||
#include <windowsx.h>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline COLORREF hoverSurface(COLORREF surface)
|
||||
{
|
||||
return RGB(3*GetRValue(surface)/4,3*GetGValue(surface)/4,3*GetBValue(surface)/4);
|
||||
}
|
||||
|
||||
class InlineListAction
|
||||
{
|
||||
std::wstring_view label;
|
||||
LRESULT pressedRow=LB_ERR;
|
||||
|
||||
public:
|
||||
explicit InlineListAction(std::wstring_view text):label(text){}
|
||||
|
||||
RECT bounds(RECT row,int cellWidth) const
|
||||
{
|
||||
row.right-=2*cellWidth;
|
||||
row.left=std::max(row.left,row.right-static_cast<LONG>(label.size()*cellWidth));
|
||||
return row;
|
||||
}
|
||||
|
||||
bool hit(HWND list,LRESULT row,LPARAM point,int cellWidth) const
|
||||
{
|
||||
RECT item{};
|
||||
if(SendMessageW(list,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&item))==LB_ERR) return false;
|
||||
const auto action=bounds(item,cellWidth);
|
||||
return PtInRect(&action,{GET_X_LPARAM(point),GET_Y_LPARAM(point)});
|
||||
}
|
||||
|
||||
void press(HWND list,LRESULT row)
|
||||
{
|
||||
pressedRow=row;
|
||||
SetCapture(list);
|
||||
}
|
||||
|
||||
bool pressed() const { return pressedRow!=LB_ERR; }
|
||||
void cancel() { pressedRow=LB_ERR; }
|
||||
|
||||
bool release(HWND list,LRESULT row,bool overAction)
|
||||
{
|
||||
const bool activate=pressedRow==row && overAction;
|
||||
cancel();
|
||||
if(GetCapture()==list) ReleaseCapture();
|
||||
return activate;
|
||||
}
|
||||
|
||||
void paint(HDC dc,const RECT &action,int textInset,COLORREF ink,COLORREF surface,bool highlighted) const
|
||||
{
|
||||
SetTextColor(dc,ink);
|
||||
SetBkColor(dc,highlighted?hoverSurface(surface):surface);
|
||||
ExtTextOutW(dc,action.left,action.top+textInset,ETO_OPAQUE|ETO_CLIPPED,&action,
|
||||
label.data(),static_cast<UINT>(label.size()),nullptr);
|
||||
TEXTMETRICW metrics{};
|
||||
GetTextMetricsW(dc,&metrics);
|
||||
const LONG underline=std::min(action.bottom-1,action.top+textInset+metrics.tmAscent+1);
|
||||
const RECT line{action.left,underline,action.right,underline+1};
|
||||
SetDCBrushColor(dc,ink);
|
||||
FillRect(dc,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <string_view>
|
||||
|
||||
inline constexpr ULONG_PTR FilesLanPeers = 0x4b53010d;
|
||||
inline constexpr ULONG_PTR FilesLanPeersReply = 0x4b53010e;
|
||||
inline constexpr DWORD FilesLanPeersLimit = 64 * 1024;
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline bool isFilesPeerImage(const std::filesystem::path &image, const std::filesystem::path &install)
|
||||
{
|
||||
if (_wcsicmp(image.filename().c_str(), L"KSwitcher.Files.exe") != 0) return false;
|
||||
const auto directory = image.parent_path();
|
||||
if (_wcsicmp(directory.c_str(), install.c_str()) == 0) return true;
|
||||
|
||||
// Updating moves a still-running Files executable into the transaction backup.
|
||||
// Windows then reports the moved path for its process image.
|
||||
if (_wcsicmp(directory.filename().c_str(), L"backup") != 0) return false;
|
||||
const auto transaction = directory.parent_path();
|
||||
if (_wcsicmp(transaction.parent_path().c_str(), install.c_str()) != 0) return false;
|
||||
constexpr std::wstring_view prefix = L".kswitcher-update-";
|
||||
const auto name = transaction.filename().wstring();
|
||||
if (name.size() != prefix.size() + 32 || _wcsnicmp(name.c_str(), prefix.data(), prefix.size()) != 0)
|
||||
return false;
|
||||
return std::wstring_view(name).substr(prefix.size()).find_first_not_of(L"0123456789abcdefABCDEF")
|
||||
== std::wstring_view::npos;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
bool isSharingError(int error)
|
||||
{
|
||||
return error==ERROR_SHARING_VIOLATION || error==ERROR_LOCK_VIOLATION;
|
||||
}
|
||||
|
||||
constexpr DWORD lockProbeShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
|
||||
constexpr DWORD lockProbeFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
|
||||
|
||||
DWORD probeDeleteAccess(const fs::path &path)
|
||||
{
|
||||
Handle probe{CreateFileW(path.c_str(),DELETE,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)};
|
||||
return probe.value==INVALID_HANDLE_VALUE?GetLastError():ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
struct LockProcess
|
||||
{
|
||||
DWORD pid;
|
||||
FILETIME started{};
|
||||
std::wstring name;
|
||||
};
|
||||
struct LockScan
|
||||
{
|
||||
std::vector<LockProcess> processes;
|
||||
bool incomplete{};
|
||||
};
|
||||
|
||||
LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token stop)
|
||||
{
|
||||
LockScan result;
|
||||
const auto query=reinterpret_cast<decltype(&NtQueryInformationFile)>(
|
||||
GetProcAddress(GetModuleHandleW(L"ntdll.dll"),"NtQueryInformationFile"));
|
||||
if(!query) { result.incomplete=true; return result; }
|
||||
std::set<DWORD> pids;
|
||||
std::vector<ULONG_PTR> buffer(128);
|
||||
const auto inspect=[&](const fs::path &path) {
|
||||
const auto error=probeDeleteAccess(path);
|
||||
if(error==ERROR_SUCCESS) return;
|
||||
if(!isSharingError(error))
|
||||
{
|
||||
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND) result.incomplete=true;
|
||||
return;
|
||||
}
|
||||
Handle file{CreateFileW(path.c_str(),0,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)};
|
||||
if(file.value==INVALID_HANDLE_VALUE) {result.incomplete=true;return;}
|
||||
IO_STATUS_BLOCK status{};
|
||||
// FileProcessIdsUsingFileInformation (47) returns an ULONG count followed by aligned ULONG_PTR PIDs.
|
||||
auto code=query(file.value,&status,buffer.data(),static_cast<ULONG>(buffer.size()*sizeof(ULONG_PTR)),
|
||||
static_cast<FILE_INFORMATION_CLASS>(47));
|
||||
while((static_cast<ULONG>(code)==0xC0000023 || static_cast<ULONG>(code)==0x80000005 ||
|
||||
static_cast<ULONG>(code)==0xC0000004) && buffer.size()<8192)
|
||||
{
|
||||
buffer.resize(buffer.size()*2);
|
||||
code=query(file.value,&status,buffer.data(),static_cast<ULONG>(buffer.size()*sizeof(ULONG_PTR)),
|
||||
static_cast<FILE_INFORMATION_CLASS>(47));
|
||||
}
|
||||
if(code<0 || status.Information<sizeof(ULONG_PTR)) {result.incomplete=true;return;}
|
||||
ULONG count{};
|
||||
memcpy(&count,buffer.data(),sizeof(count));
|
||||
if(count>buffer.size()-1 || size_t(count)+1>status.Information/sizeof(ULONG_PTR))
|
||||
{
|
||||
result.incomplete=true;
|
||||
return;
|
||||
}
|
||||
for(ULONG i=0;i<count;++i)
|
||||
if(const auto pid=buffer[i+1];pid && pid<=MAXDWORD && pid!=GetCurrentProcessId())
|
||||
pids.insert(static_cast<DWORD>(pid));
|
||||
};
|
||||
auto remaining=8192u;
|
||||
const auto deadline=GetTickCount64()+4000;
|
||||
for(const auto &path:paths)
|
||||
{
|
||||
if(stop.stop_requested()) return {};
|
||||
inspect(path);
|
||||
const auto attributes=GetFileAttributesW(path.c_str());
|
||||
if(attributes==INVALID_FILE_ATTRIBUTES || !(attributes&FILE_ATTRIBUTE_DIRECTORY) ||
|
||||
(attributes&FILE_ATTRIBUTE_REPARSE_POINT)) continue;
|
||||
std::error_code error;
|
||||
fs::recursive_directory_iterator it(path,error),end;
|
||||
while(!error && it!=end)
|
||||
{
|
||||
if(stop.stop_requested()) return {};
|
||||
if(!remaining || GetTickCount64()>=deadline) {result.incomplete=true;break;}
|
||||
--remaining;
|
||||
const auto item=it->path();
|
||||
const auto flags=GetFileAttributesW(item.c_str());
|
||||
if(flags==INVALID_FILE_ATTRIBUTES || flags&FILE_ATTRIBUTE_REPARSE_POINT)
|
||||
it.disable_recursion_pending();
|
||||
inspect(item);
|
||||
it.increment(error);
|
||||
}
|
||||
if(error) result.incomplete=true;
|
||||
}
|
||||
for(const auto pid:pids)
|
||||
{
|
||||
Handle process{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,pid)};
|
||||
LockProcess entry{pid};
|
||||
if(process.value)
|
||||
{
|
||||
FILETIME exit{},kernel{},user{};
|
||||
GetProcessTimes(process.value,&entry.started,&exit,&kernel,&user);
|
||||
wchar_t path[32768];
|
||||
DWORD count=std::size(path);
|
||||
if(QueryFullProcessImageNameW(process.value,0,path,&count))
|
||||
entry.name=fs::path(std::wstring_view(path,count)).filename().wstring();
|
||||
}
|
||||
if(entry.name.empty()) entry.name=L"Unknown process";
|
||||
result.processes.push_back(std::move(entry));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
struct LockDialog
|
||||
{
|
||||
std::vector<fs::path> paths;
|
||||
std::vector<LockProcess> processes;
|
||||
std::future<LockScan> scan;
|
||||
std::stop_source stop;
|
||||
};
|
||||
|
||||
constexpr UINT_PTR lockScanTimer=1;
|
||||
|
||||
void refreshLockProcesses(HWND window,LockDialog &state,std::shared_ptr<Handle> terminated={})
|
||||
{
|
||||
if(state.scan.valid()) return;
|
||||
state.processes.clear();
|
||||
SendDlgItemMessageW(window,431,LB_RESETCONTENT,0,0);
|
||||
EnableWindow(GetDlgItem(window,433),FALSE);
|
||||
EnableWindow(GetDlgItem(window,434),FALSE);
|
||||
SetDlgItemTextW(window,430,L"Checking which processes are using the file or folder…");
|
||||
try
|
||||
{
|
||||
std::packaged_task<LockScan()> task([paths=state.paths,stop=state.stop.get_token(),terminated=std::move(terminated)] {
|
||||
if(terminated) WaitForSingleObject(terminated->value,2500);
|
||||
return scanLockProcesses(paths,stop);
|
||||
});
|
||||
auto future=task.get_future();
|
||||
if(!SetTimer(window,lockScanTimer,50,nullptr))
|
||||
throw std::runtime_error("Could not start the process scan.");
|
||||
std::thread(std::move(task)).detach();
|
||||
state.scan=std::move(future);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
KillTimer(window,lockScanTimer);
|
||||
EnableWindow(GetDlgItem(window,434),TRUE);
|
||||
SetDlgItemTextW(window,430,L"Could not start the process scan.");
|
||||
}
|
||||
}
|
||||
|
||||
void endLockProcess(HWND window,LockDialog &state)
|
||||
{
|
||||
const auto index=SendDlgItemMessageW(window,431,LB_GETCURSEL,0,0);
|
||||
if(index<0 || size_t(index)>=state.processes.size()) return;
|
||||
const auto &entry=state.processes[index];
|
||||
auto error=[&](const wchar_t *message) {
|
||||
showFilesNotice(window,message,L"End process",{.tone=FilesNoticeTone::warning});
|
||||
};
|
||||
auto process=std::make_shared<Handle>();
|
||||
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry.pid);
|
||||
FILETIME started{},exited{},kernel{},user{};
|
||||
BOOL critical{};
|
||||
if(!process->value || !(entry.started.dwHighDateTime || entry.started.dwLowDateTime) ||
|
||||
!GetProcessTimes(process->value,&started,&exited,&kernel,&user) ||
|
||||
CompareFileTime(&started,&entry.started)!=0 || !IsProcessCritical(process->value,&critical) || critical)
|
||||
{
|
||||
error(L"This process has exited, is protected, or cannot be identified.");
|
||||
return;
|
||||
}
|
||||
const auto question=L"End "+entry.name+L" (PID "+std::to_wstring(entry.pid)+
|
||||
L")?\r\nUnsaved work in the process may be lost.";
|
||||
if(showFilesNotice(window,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
|
||||
return;
|
||||
if(WaitForSingleObject(process->value,0)==WAIT_TIMEOUT && !TerminateProcess(process->value,1))
|
||||
{
|
||||
const auto message=ks::lastError(L"Could not end the process");
|
||||
error(message.c_str());
|
||||
return;
|
||||
}
|
||||
refreshLockProcesses(window,state,std::move(process));
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(window,DWLP_USER,lp);
|
||||
prepareCopyDialog(window);
|
||||
for(const auto id:{430,431}) SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
const auto list=GetDlgItem(window,431);
|
||||
RECT bounds{};
|
||||
GetWindowRect(list,&bounds);
|
||||
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
|
||||
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
installScrollBar(list,window);
|
||||
layoutDialogButtons(window,432,{433,434,IDOK});
|
||||
SendMessageW(window,DM_SETDEFID,IDOK,0);
|
||||
SetFocus(GetDlgItem(window,IDOK));
|
||||
refreshLockProcesses(window,*reinterpret_cast<LockDialog *>(lp));
|
||||
return FALSE;
|
||||
}
|
||||
auto *data=reinterpret_cast<LockDialog *>(GetWindowLongPtrW(window,DWLP_USER));
|
||||
if(!data) return FALSE;
|
||||
auto &state=*data;
|
||||
if(message==WM_TIMER && wp==lockScanTimer)
|
||||
{
|
||||
if(!state.scan.valid() || state.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
|
||||
return TRUE;
|
||||
KillTimer(window,lockScanTimer);
|
||||
EnableWindow(GetDlgItem(window,434),TRUE);
|
||||
try
|
||||
{
|
||||
auto result=state.scan.get();
|
||||
for(auto &entry:result.processes)
|
||||
{
|
||||
const auto label=entry.name+L" (PID "+std::to_wstring(entry.pid)+L")";
|
||||
if(SendDlgItemMessageW(window,431,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))>=0)
|
||||
state.processes.push_back(std::move(entry));
|
||||
}
|
||||
SetDlgItemTextW(window,430,state.processes.empty()?
|
||||
(result.incomplete?L"No processes found. Some items could not be checked.":L"No locking processes found."):
|
||||
(result.incomplete?L"Possible locking processes. The scan was incomplete.":L"Processes using locked files or folders."));
|
||||
if(!state.processes.empty())
|
||||
{
|
||||
SendDlgItemMessageW(window,431,LB_SETCURSEL,0,0);
|
||||
EnableWindow(GetDlgItem(window,433),TRUE);
|
||||
}
|
||||
}
|
||||
catch(const std::exception &) {SetDlgItemTextW(window,430,L"Could not check for locking processes.");}
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND)
|
||||
{
|
||||
switch(LOWORD(wp))
|
||||
{
|
||||
case 433: endLockProcess(window,state); return TRUE;
|
||||
case 434: refreshLockProcesses(window,state); return TRUE;
|
||||
case IDOK:
|
||||
case IDCANCEL: FilesModalDialog::finish(window,IDCANCEL); return TRUE;
|
||||
}
|
||||
}
|
||||
if(message==WM_CLOSE) {FilesModalDialog::finish(window,IDCANCEL);return TRUE;}
|
||||
return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432},false,GetDlgItem(window,431));
|
||||
}
|
||||
|
||||
void showLockProcesses(HWND owner,std::vector<fs::path> paths)
|
||||
{
|
||||
LockDialog state{std::move(paths)};
|
||||
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,lockProcessesDialog,
|
||||
reinterpret_cast<LPARAM>(&state));
|
||||
state.stop.request_stop();
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
template<class Index, class Selectable>
|
||||
Index adjacentMenuRow(Index current, Index size, int direction, Selectable selectable)
|
||||
{
|
||||
auto row=current;
|
||||
for(Index visited=0;visited<size;++visited)
|
||||
{
|
||||
row+=direction;
|
||||
if(row<0) row=size-1;
|
||||
if(row>=size) row=0;
|
||||
if(selectable(row)) return row;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline void paintMenuAccessKey(HDC dc, const RECT &clip, POINT origin, std::wstring_view title,
|
||||
size_t access, COLORREF ink)
|
||||
{
|
||||
if (access >= title.size()) return;
|
||||
SIZE prefix{};
|
||||
GetTextExtentPoint32W(dc, title.data(), static_cast<int>(access), &prefix);
|
||||
const auto background = SetBkMode(dc, TRANSPARENT);
|
||||
const auto text = SetTextColor(dc, ink);
|
||||
const auto alignment = SetTextAlign(dc, TA_LEFT | TA_TOP);
|
||||
ExtTextOutW(dc, origin.x + prefix.cx, origin.y, ETO_CLIPPED, &clip, title.data() + access, 1, nullptr);
|
||||
SetTextAlign(dc, alignment);
|
||||
SetTextColor(dc, text);
|
||||
SetBkMode(dc, background);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDraft &draft)
|
||||
{
|
||||
const auto dc=item.hDC;
|
||||
const auto saved=SaveDC(dc);
|
||||
if(!saved) return;
|
||||
IntersectClipRect(dc,item.rcItem.left,item.rcItem.top,item.rcItem.right,item.rcItem.bottom);
|
||||
const auto dpi=GetDpiForWindow(item.hwndItem);
|
||||
const auto px=[&](int value){return MulDiv(value,dpi,96);};
|
||||
auto font=draft.font;
|
||||
font.lfHeight=-MulDiv(draft.points,dpi,720);
|
||||
font.lfWidth=0;
|
||||
const auto previewFont=CreateFontIndirectW(&font);
|
||||
SelectObject(dc,previewFont?previewFont:mono);
|
||||
TEXTMETRICW metrics{};
|
||||
GetTextMetricsW(dc,&metrics);
|
||||
const auto rowHeight=std::max<LONG>(px(18),metrics.tmHeight+px(4));
|
||||
const auto &palette=draft.palette;
|
||||
const auto fill=[&](RECT bounds,COLORREF color)
|
||||
{
|
||||
SetBkColor(dc,color);
|
||||
ExtTextOutW(dc,0,0,ETO_OPAQUE|ETO_CLIPPED,&bounds,nullptr,0,nullptr);
|
||||
};
|
||||
const auto row=[&](RECT bounds,std::wstring_view label,COLORREF fg,COLORREF bg,bool right=false)
|
||||
{
|
||||
fill(bounds,bg);
|
||||
bounds.left+=px(5);
|
||||
bounds.right-=px(5);
|
||||
SetBkMode(dc,TRANSPARENT);
|
||||
SetTextColor(dc,fg);
|
||||
DrawTextW(dc,label.data(),static_cast<int>(label.size()),&bounds,
|
||||
DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS|(right?DT_RIGHT:DT_LEFT));
|
||||
};
|
||||
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
|
||||
auto bounds=item.rcItem;
|
||||
fill(bounds,palette[PanelBlue]);
|
||||
|
||||
const auto frame=[&](RECT rect)
|
||||
{
|
||||
SetDCBrushColor(dc,palette[Frame]);
|
||||
FrameRect(dc,&rect,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
InflateRect(&rect,-px(2),-px(2));
|
||||
FrameRect(dc,&rect,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
};
|
||||
const auto panel=[&](RECT panelBounds,bool wide,bool cursor,std::wstring_view path)
|
||||
{
|
||||
frame(panelBounds);
|
||||
InflateRect(&panelBounds,-px(4),-px(4));
|
||||
auto line=panelBounds;
|
||||
line.bottom=line.top+rowHeight;
|
||||
row(line,path,palette[Frame],palette[PanelBlue]);
|
||||
OffsetRect(&line,0,rowHeight);
|
||||
BOOL valid{};
|
||||
const auto input=GetDlgItemInt(dialog,201,&valid,FALSE);
|
||||
const auto columns=valid?std::clamp(input,6u,16u):static_cast<UINT>(sizeWidth);
|
||||
const auto entry=[&](std::wstring_view stem,std::wstring_view ext,bool folder,bool highlight)
|
||||
{
|
||||
const auto bg=highlight?palette[PanelCursor]:palette[PanelBlue];
|
||||
auto name=line;
|
||||
if(wide)
|
||||
{
|
||||
name.right=std::max(name.left+px(20),name.right-static_cast<LONG>(columns+2)*metrics.tmAveCharWidth);
|
||||
name.right=std::min(name.right,line.right);
|
||||
auto amount=line;
|
||||
amount.left=name.right;
|
||||
row(amount,folder?L"Folder":formatSize(48382,columns),palette[Text],bg,true);
|
||||
fill({amount.left,amount.top,amount.left+px(1),amount.bottom},palette[Frame]);
|
||||
}
|
||||
if(wide && checked(folder?204:202) && name.right-name.left>px(70))
|
||||
{
|
||||
auto extension=name;
|
||||
extension.left=extension.right-std::min<LONG>(px(60),(extension.right-extension.left)/2);
|
||||
name.right=extension.left;
|
||||
row(extension,ext,palette[Text],bg,true);
|
||||
row(name,stem,palette[Text],bg);
|
||||
}
|
||||
else row(name,std::wstring(stem)+L"."+std::wstring(ext),palette[Text],bg);
|
||||
OffsetRect(&line,0,rowHeight);
|
||||
};
|
||||
entry(L"report",L"txt",false,cursor);
|
||||
entry(L"examples",L"old",true,false);
|
||||
};
|
||||
|
||||
if(draft.page==Appearance && draft.section==DialogFrame)
|
||||
{
|
||||
InflateRect(&bounds,-px(8),-px(8));
|
||||
const auto framePadding=dialogFrameMetrics(dpi,draft.framePadding);
|
||||
const auto surface=CreateSolidBrush(palette[Dialog]);
|
||||
const auto ink=CreateSolidBrush(palette[Text]);
|
||||
const auto frame=paintDialogFrame(dc,bounds,framePadding,surface,ink);
|
||||
const auto titleFont=previewFont?previewFont:mono;
|
||||
paintDialogFrameCaptions(dc,bounds,frame,L"Folder shortcuts",surface,palette[Text],titleFont);
|
||||
DeleteObject(ink);
|
||||
DeleteObject(surface);
|
||||
auto content=bounds;
|
||||
InflateRect(&content,-framePadding.content(),-dialogListInset(framePadding,metrics.tmHeight));
|
||||
content.bottom=std::min(content.bottom,content.top+rowHeight);
|
||||
if(content.bottom>content.top)
|
||||
paintDialogListRow(dc,content,LR"(C:\Projects\Example\Documents\Archive)",titleFont,
|
||||
palette[Text],palette[Selection],dialogRowTextInset(metrics.tmAveCharWidth,draft.framePadding));
|
||||
}
|
||||
else if(draft.page==PanelColors && (draft.section==Dialog || draft.section==Selection))
|
||||
{
|
||||
InflateRect(&bounds,-px(12),-px(10));
|
||||
const auto maxWidth=px(340);
|
||||
bounds.right=std::min(bounds.right,bounds.left+maxWidth);
|
||||
fill(bounds,palette[Dialog]);
|
||||
frame(bounds);
|
||||
InflateRect(&bounds,-px(5),-px(5));
|
||||
auto line=bounds;
|
||||
line.bottom=line.top+rowHeight;
|
||||
row(line,L"Change drive",palette[Text],palette[Dialog]);
|
||||
OffsetRect(&line,0,rowHeight);
|
||||
row(line,L"C: fixed",palette[Text],palette[Selection]);
|
||||
OffsetRect(&line,0,rowHeight);
|
||||
row(line,L"D: fixed",palette[Text],palette[Dialog]);
|
||||
}
|
||||
else if(draft.page==PanelColors && draft.section==Footer)
|
||||
{
|
||||
auto bar=bounds;
|
||||
bar.top=bar.bottom-rowHeight;
|
||||
row(bar,L"F2 Refresh F3 View F5 Copy F6 Move",palette[Text],palette[Footer]);
|
||||
bounds.bottom=bar.top;
|
||||
panel(bounds,false,false,L"C:\\Example");
|
||||
}
|
||||
else if(draft.page==PanelModes && draft.section==PanelLayout)
|
||||
{
|
||||
auto left=bounds,right=bounds;
|
||||
left.right=(bounds.left+bounds.right)/2;
|
||||
right.left=left.right+px(4);
|
||||
panel(left,checked(273),true,L"C:\\Example");
|
||||
panel(right,checked(274),false,L"D:\\Example");
|
||||
}
|
||||
else if(draft.page==PanelModes && draft.section==StatusColumns)
|
||||
{
|
||||
auto statusRow=bounds;
|
||||
statusRow.top=statusRow.bottom-rowHeight;
|
||||
bounds.bottom=statusRow.top;
|
||||
panel(bounds,true,true,L"C:\\Example");
|
||||
std::wstring label;
|
||||
if(checked(203))
|
||||
{
|
||||
constexpr const wchar_t *values[]{L"report.txt",L"47 KiB",L"2026-11-14",L"10:30"};
|
||||
for(int i=0;i<4;++i)
|
||||
if(checked(205+i))
|
||||
{
|
||||
if(!label.empty()) label+=L" ";
|
||||
label+=values[i];
|
||||
}
|
||||
}
|
||||
row(statusRow,label,palette[Text],palette[PanelBlue]);
|
||||
}
|
||||
else panel(bounds,draft.page==PanelModes || checked(273),
|
||||
draft.page==PanelColors && draft.section==PanelCursor,L"C:\\Example");
|
||||
|
||||
if(draft.page==PanelColors && (draft.section==Text || draft.section==Dialog))
|
||||
{
|
||||
auto field=item.rcItem;
|
||||
InflateRect(&field,-px(12),-px(10));
|
||||
field.right=std::min(field.right,field.left+px(340));
|
||||
field.top+=px(5)+4*rowHeight;
|
||||
field.bottom=field.top+rowHeight+px(6);
|
||||
fill(field,RGB(192,192,192));
|
||||
InflateRect(&field,-px(4),-px(3));
|
||||
row(field,L"C:\\Example",palette[Text],palette[Dialog]);
|
||||
}
|
||||
|
||||
RestoreDC(dc,saved);
|
||||
if(previewFont) DeleteObject(previewFont);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <string>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline std::wstring windowsPowerShell()
|
||||
{
|
||||
wchar_t system[MAX_PATH]{};
|
||||
const auto length=GetSystemDirectoryW(system,MAX_PATH);
|
||||
return length && length<MAX_PATH
|
||||
? std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe" : std::wstring{};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <algorithm>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline int scrollBarWidth(HWND window) {return std::max(7,MulDiv(12,GetDpiForWindow(window),96));}
|
||||
|
||||
inline int scrollArrowHeight(RECT bounds)
|
||||
{
|
||||
return std::min(bounds.right-bounds.left,(bounds.bottom-bounds.top)/3);
|
||||
}
|
||||
|
||||
struct ScrollPosition
|
||||
{
|
||||
int count, visible, top;
|
||||
|
||||
int last() const {return std::max(0,count-visible);}
|
||||
|
||||
RECT thumb(RECT track) const
|
||||
{
|
||||
const auto arrow=scrollArrowHeight(track);
|
||||
track.top+=arrow;
|
||||
track.bottom-=arrow;
|
||||
const int height=track.bottom-track.top;
|
||||
if(height<=0 || !last()) return {};
|
||||
const int size=std::clamp(MulDiv(height,visible,count),std::min(height,arrow),height);
|
||||
track.top+=MulDiv(std::clamp(top,0,last()),height-size,last());
|
||||
track.bottom=track.top+size;
|
||||
return track;
|
||||
}
|
||||
|
||||
int click(RECT track,int y) const
|
||||
{
|
||||
const auto arrow=scrollArrowHeight(track);
|
||||
const auto grip=thumb(track);
|
||||
const int delta=y<track.top+arrow?-1:y>=track.bottom-arrow?1:
|
||||
y<grip.top?-visible:y>=grip.bottom?visible:0;
|
||||
return std::clamp(top+delta,0,last());
|
||||
}
|
||||
|
||||
int drag(RECT track,int y,int offset) const
|
||||
{
|
||||
const auto grip=thumb(track);
|
||||
const auto arrow=scrollArrowHeight(track);
|
||||
const auto travel=track.bottom-track.top-2*arrow-(grip.bottom-grip.top);
|
||||
return travel>0?std::clamp(MulDiv(y-track.top-arrow-offset,last(),travel),0,last()):top;
|
||||
}
|
||||
};
|
||||
|
||||
inline void paintScrollBar(HDC dc,RECT track,ScrollPosition position,COLORREF background)
|
||||
{
|
||||
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
SetDCBrushColor(dc,background);
|
||||
FillRect(dc,&track,brush);
|
||||
if(!position.last()) return;
|
||||
const auto lighter=[&](int divisor){return RGB(GetRValue(background)+(257-GetRValue(background))/divisor,
|
||||
GetGValue(background)+(257-GetGValue(background))/divisor,
|
||||
GetBValue(background)+(257-GetBValue(background))/divisor);};
|
||||
const auto ink=lighter(4),dots=lighter(7);
|
||||
const int height=scrollArrowHeight(track);
|
||||
struct
|
||||
{
|
||||
BITMAPINFOHEADER header{sizeof(BITMAPINFOHEADER),4,4,1,32,BI_RGB};
|
||||
DWORD pixels[16]{};
|
||||
} tile;
|
||||
for(int y=0;y<4;++y)
|
||||
for(int x=0;x<4;++x)
|
||||
{
|
||||
const auto color=y%2==0 && x%2==y/2?dots:background;
|
||||
// DIB pixels are stored bottom-up in BGR order.
|
||||
tile.pixels[(3-y)*4+x]=RGB(GetBValue(color),GetGValue(color),GetRValue(color));
|
||||
}
|
||||
if(const auto pattern=CreateDIBPatternBrushPt(&tile,DIB_RGB_COLORS))
|
||||
{
|
||||
const RECT channel{track.left,track.top+height,track.right,track.bottom-height};
|
||||
POINT origin{};
|
||||
SetBrushOrgEx(dc,channel.left,channel.top,&origin);
|
||||
FillRect(dc,&channel,pattern);
|
||||
SetBrushOrgEx(dc,origin.x,origin.y,nullptr);
|
||||
DeleteObject(pattern);
|
||||
}
|
||||
SetDCBrushColor(dc,ink);
|
||||
const auto thumb=position.thumb(track);
|
||||
FillRect(dc,&thumb,brush);
|
||||
const int middle=(track.left+track.right)/2;
|
||||
const int radius=std::max(0,(height-3)/2);
|
||||
for(int row=0;row<=radius;++row)
|
||||
{
|
||||
const int y=track.top+(height-radius-1)/2+row;
|
||||
const int mirrored=track.bottom-1-(y-track.top);
|
||||
const RECT up{middle-row,y,middle+row+1,y+1};
|
||||
const RECT down{middle-row,mirrored,middle+row+1,mirrored+1};
|
||||
FillRect(dc,&up,brush);
|
||||
FillRect(dc,&down,brush);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
constexpr int fileStyleSection=ColorCount;
|
||||
constexpr int fileStyleRules=288,fileStyleSuggestion=291,fileStylePreview=299,fileStyleState=301;
|
||||
constexpr const wchar_t *fileStyleStateNames[]{L"Normal",L"Marked (Insert)",L"Focused cursor",L"Unfocused cursor"};
|
||||
|
||||
void layoutFileStyleFields(HWND dialog,bool redraw)
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(dialog,&client);
|
||||
RECT spacing{0,0,8,0};
|
||||
MapDialogRect(dialog,&spacing);
|
||||
const auto gap=spacing.right;
|
||||
const auto dpi=GetDpiForWindow(dialog);
|
||||
const auto arrow=GetSystemMetricsForDpi(SM_CXVSCROLL,dpi);
|
||||
const auto border=GetSystemMetricsForDpi(SM_CXEDGE,dpi);
|
||||
const auto flags=SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW;
|
||||
const auto fit=[&](int id,int buttonId)
|
||||
{
|
||||
const auto combo=GetDlgItem(dialog,id);
|
||||
const auto bounds=dialogControlBounds(dialog,id);
|
||||
const auto dc=GetDC(combo);
|
||||
if(!dc) return;
|
||||
const auto previous=SelectObject(dc,reinterpret_cast<HFONT>(SendMessageW(combo,WM_GETFONT,0,0)));
|
||||
SIZE extent{};
|
||||
const std::wstring_view example=L".example";
|
||||
GetTextExtentPoint32W(dc,example.data(),static_cast<int>(example.size()),&extent);
|
||||
LONG longest=extent.cx;
|
||||
const auto count=SendMessageW(combo,CB_GETCOUNT,0,0);
|
||||
for(LRESULT row=0;row<count;++row)
|
||||
{
|
||||
const auto length=SendMessageW(combo,CB_GETLBTEXTLEN,row,0);
|
||||
if(length<=0) continue;
|
||||
std::wstring item(static_cast<size_t>(length)+1,L'\0');
|
||||
if(SendMessageW(combo,CB_GETLBTEXT,row,reinterpret_cast<LPARAM>(item.data()))!=CB_ERR &&
|
||||
GetTextExtentPoint32W(dc,item.data(),static_cast<int>(length),&extent))
|
||||
longest=std::max(longest,extent.cx);
|
||||
}
|
||||
if(previous) SelectObject(dc,previous);
|
||||
ReleaseDC(combo,dc);
|
||||
|
||||
const auto button=buttonId?dialogControlBounds(dialog,buttonId):RECT{};
|
||||
const auto buttonWidth=button.right-button.left;
|
||||
const auto available=client.right-bounds.left-gap-(buttonId?gap+buttonWidth:0);
|
||||
const auto width=std::max(1L,std::min(available,longest+arrow+2*border+gap));
|
||||
RECT dropped{};
|
||||
SendMessageW(combo,CB_GETDROPPEDCONTROLRECT,0,reinterpret_cast<LPARAM>(&dropped));
|
||||
SetWindowPos(combo,nullptr,bounds.left,bounds.top,width,dropped.bottom-dropped.top,flags);
|
||||
if(buttonId)
|
||||
SetWindowPos(GetDlgItem(dialog,buttonId),nullptr,bounds.left+width+gap,button.top,
|
||||
buttonWidth,button.bottom-button.top,flags);
|
||||
};
|
||||
fit(fileStyleRules,289);
|
||||
fit(fileStyleSuggestion,292);
|
||||
fit(fileStyleState,0);
|
||||
if(redraw)
|
||||
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
|
||||
}
|
||||
|
||||
void fillFileStyleSuggestions(HWND dialog)
|
||||
{
|
||||
std::set<std::wstring> extensions;
|
||||
for(DWORD i=0;;++i)
|
||||
{
|
||||
wchar_t name[256]{};
|
||||
DWORD length=std::size(name);
|
||||
const auto result=RegEnumKeyExW(HKEY_CLASSES_ROOT,i,name,&length,nullptr,nullptr,nullptr,nullptr);
|
||||
if(result==ERROR_MORE_DATA) continue;
|
||||
if(result!=ERROR_SUCCESS) break;
|
||||
if(name[0]!=L'.') continue;
|
||||
auto extension=fileStyleExtension(name);
|
||||
if(!extension.empty()) extensions.insert(std::move(extension));
|
||||
}
|
||||
for(const auto &extension:extensions)
|
||||
SendDlgItemMessageW(dialog,fileStyleSuggestion,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(extension.c_str()));
|
||||
SendDlgItemMessageW(dialog,fileStyleSuggestion,CB_LIMITTEXT,255,0);
|
||||
for(const auto label:fileStyleStateNames)
|
||||
SendDlgItemMessageW(dialog,fileStyleState,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
|
||||
SendDlgItemMessageW(dialog,fileStyleState,CB_SETCURSEL,0,0);
|
||||
}
|
||||
|
||||
void updateFileStyleEditor(HWND dialog,OptionsDraft &draft,bool rebuild)
|
||||
{
|
||||
const auto combo=GetDlgItem(dialog,fileStyleRules);
|
||||
if(rebuild)
|
||||
{
|
||||
SendMessageW(combo,CB_RESETCONTENT,0,0);
|
||||
for(const auto &style:draft.styles)
|
||||
{
|
||||
const auto label=style.extension==L"@system-hidden"?L"System and hidden":style.extension.c_str();
|
||||
SendMessageW(combo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
|
||||
}
|
||||
draft.styleIndex=draft.styles.empty()?-1:std::clamp(draft.styleIndex,0,static_cast<int>(draft.styles.size())-1);
|
||||
SendMessageW(combo,CB_SETCURSEL,draft.styleIndex,0);
|
||||
layoutFileStyleFields(dialog,true);
|
||||
}
|
||||
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
|
||||
const bool selected=draft.styleIndex>=0;
|
||||
for(const int id:{289,293,294,295,297,298})
|
||||
EnableWindow(GetDlgItem(dialog,id),selected);
|
||||
if(!selected)
|
||||
{
|
||||
SetDlgItemTextW(dialog,296,L"");
|
||||
CheckDlgButton(dialog,297,BST_UNCHECKED);
|
||||
CheckDlgButton(dialog,298,BST_UNCHECKED);
|
||||
return;
|
||||
}
|
||||
const auto &style=draft.styles[draft.styleIndex];
|
||||
const auto colorLabel=[](std::optional<COLORREF> color)->std::wstring
|
||||
{
|
||||
if(!color) return L"Default";
|
||||
wchar_t hex[8]{};
|
||||
swprintf_s(hex,L"#%02X%02X%02X",unsigned(GetRValue(*color)),unsigned(GetGValue(*color)),unsigned(GetBValue(*color)));
|
||||
return hex;
|
||||
};
|
||||
const auto state=SendDlgItemMessageW(dialog,fileStyleState,CB_GETCURSEL,0,0);
|
||||
const auto fg=state>0?style.states[state-1].foreground:style.foreground;
|
||||
const auto bg=state>0?style.states[state-1].background:style.background;
|
||||
const auto label=L"Foreground: "+colorLabel(fg)+L" Background: "+colorLabel(bg);
|
||||
SetDlgItemTextW(dialog,296,label.c_str());
|
||||
CheckDlgButton(dialog,297,style.underline);
|
||||
CheckDlgButton(dialog,298,style.strikeout);
|
||||
}
|
||||
|
||||
bool addFileStyle(HWND dialog,OptionsDraft &draft)
|
||||
{
|
||||
wchar_t input[256]{};
|
||||
GetDlgItemTextW(dialog,fileStyleSuggestion,input,std::size(input));
|
||||
const auto extension=fileStyleExtension(input);
|
||||
if(extension.empty())
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a file extension such as .txt.",L"File type styles");
|
||||
SetFocus(GetDlgItem(dialog,fileStyleSuggestion));
|
||||
return false;
|
||||
}
|
||||
const auto existing=std::find_if(draft.styles.begin(),draft.styles.end(),
|
||||
[&](const auto &style){return sameFileExtension(style.extension,extension);});
|
||||
if(existing!=draft.styles.end()) draft.styleIndex=static_cast<int>(existing-draft.styles.begin());
|
||||
else
|
||||
{
|
||||
if(draft.styles.size()>=64)
|
||||
{
|
||||
showFilesNotice(dialog,L"The profile can contain up to 64 file type rules.",L"File type styles");
|
||||
return false;
|
||||
}
|
||||
draft.styles.push_back({extension});
|
||||
draft.styleIndex=static_cast<int>(draft.styles.size())-1;
|
||||
}
|
||||
SetDlgItemTextW(dialog,fileStyleSuggestion,L"");
|
||||
updateFileStyleEditor(dialog,draft,true);
|
||||
return true;
|
||||
}
|
||||
|
||||
void paintFileStylePreview(const DRAWITEMSTRUCT &item,const OptionsDraft &draft)
|
||||
{
|
||||
const auto saved=SaveDC(item.hDC);
|
||||
const bool selected=draft.styleIndex>=0 && static_cast<size_t>(draft.styleIndex)<draft.styles.size();
|
||||
const auto extension=selected?std::wstring_view(draft.styles[draft.styleIndex].extension):std::wstring_view{};
|
||||
const bool systemHidden=extension==L"@system-hidden";
|
||||
SetBkColor(item.hDC,draft.palette[PanelBlue]);
|
||||
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&item.rcItem,nullptr,0,nullptr);
|
||||
if(selected)
|
||||
{
|
||||
auto font=draft.font;
|
||||
font.lfHeight=-MulDiv(draft.points,GetDpiForWindow(item.hwndItem),720);
|
||||
font.lfWidth=0;
|
||||
const auto fontHandle=CreateFontIndirectW(&font);
|
||||
if(fontHandle) SelectObject(item.hDC,fontHandle);
|
||||
TEXTMETRICW metrics{};
|
||||
GetTextMetricsW(item.hDC,&metrics);
|
||||
const int height=metrics.tmHeight+MulDiv(4,GetDpiForWindow(item.hwndItem),96);
|
||||
if(fontHandle)
|
||||
{
|
||||
SelectObject(item.hDC,mono?mono:GetStockObject(SYSTEM_FONT));
|
||||
DeleteObject(fontHandle);
|
||||
}
|
||||
IntersectClipRect(item.hDC,item.rcItem.left,item.rcItem.top,item.rcItem.right,item.rcItem.bottom);
|
||||
for(int i=0;i<4;++i)
|
||||
{
|
||||
const auto state=static_cast<FileRowState>(i);
|
||||
const auto background=draft.palette[state==FileRowState::Focused?PanelCursor:PanelBlue];
|
||||
const auto style=resolveFileStyle(extension,!systemHidden,systemHidden,
|
||||
state==FileRowState::Focused || state==FileRowState::Marked,
|
||||
draft.palette[Text],background,draft.styles,state);
|
||||
auto decorated=font;
|
||||
if(style.decorations)
|
||||
{
|
||||
decorated.lfUnderline=(style.decorations&1)!=0;
|
||||
decorated.lfStrikeOut=(style.decorations&2)!=0;
|
||||
}
|
||||
const auto previewFont=CreateFontIndirectW(&decorated);
|
||||
const auto previous=SelectObject(item.hDC,previewFont?previewFont:mono);
|
||||
auto row=item.rcItem;
|
||||
row.top+=i*height;
|
||||
row.bottom=row.top+height;
|
||||
SetBkColor(item.hDC,style.background);
|
||||
ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&row,nullptr,0,nullptr);
|
||||
constexpr const wchar_t *samples[]{L"normal-sample",L"marked-sample",L"focused-cursor",L"unfocused-cursor"};
|
||||
const auto label=std::wstring(samples[i])+(systemHidden?L" (hidden)":std::wstring(extension));
|
||||
row.left+=5;
|
||||
row.right-=5;
|
||||
SetBkMode(item.hDC,TRANSPARENT);
|
||||
SetTextColor(item.hDC,style.foreground);
|
||||
DrawTextW(item.hDC,label.c_str(),static_cast<int>(label.size()),&row,
|
||||
DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS);
|
||||
SelectObject(item.hDC,previous);
|
||||
if(previewFont) DeleteObject(previewFont);
|
||||
}
|
||||
}
|
||||
RestoreDC(item.hDC,saved);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
enum class FileRowState { Normal, Marked, Focused, Unfocused };
|
||||
struct FileStyleColors
|
||||
{
|
||||
std::optional<COLORREF> foreground,background;
|
||||
bool operator==(const FileStyleColors &) const = default;
|
||||
};
|
||||
struct FileStyle
|
||||
{
|
||||
std::wstring extension;
|
||||
std::optional<COLORREF> foreground,background;
|
||||
bool underline{},strikeout{};
|
||||
std::array<FileStyleColors,3> states{};
|
||||
bool operator==(const FileStyle &) const = default;
|
||||
};
|
||||
|
||||
const std::vector<FileStyle> defaultFileStyles{
|
||||
{L"@system-hidden"},{L".exe",RGB(85,255,85)},{L".md",RGB(231,192,247)},
|
||||
{L".7z",RGB(255,210,128)},{L".zip",RGB(255,155,170)},{L".rar",RGB(255,210,128)},
|
||||
{L".tar",RGB(255,210,128)},{L".gz",RGB(255,210,128)},
|
||||
{L".png",RGB(165,230,255)},{L".jpg",RGB(165,230,255)},{L".jpeg",RGB(165,230,255)},
|
||||
{L".gif",RGB(165,230,255)},{L".webp",RGB(165,230,255)},{L".svg",RGB(165,230,255)},
|
||||
{L".mp3",RGB(255,185,216)},{L".wav",RGB(255,185,216)},{L".flac",RGB(255,185,216)},
|
||||
{L".mp4",RGB(255,185,216)},{L".mkv",RGB(255,185,216)},{L".mov",RGB(255,185,216)},
|
||||
{L".pdf",RGB(255,229,168)},{L".docx",RGB(255,229,168)},{L".xlsx",RGB(255,229,168)},
|
||||
{L".pptx",RGB(255,229,168)},{L".odt",RGB(255,229,168)},
|
||||
{L".cpp",RGB(168,247,190)},{L".h",RGB(168,247,190)},{L".cs",RGB(168,247,190)},
|
||||
{L".py",RGB(168,247,190)},{L".js",RGB(168,247,190)},{L".ts",RGB(168,247,190)},
|
||||
{L".ps1",RGB(168,247,190)},{L".bat",RGB(168,247,190)},{L".cmd",RGB(168,247,190)}};
|
||||
std::vector<FileStyle> fileStyles=defaultFileStyles;
|
||||
constexpr wchar_t fileStyleKey[]=L"FileStyles";
|
||||
|
||||
std::wstring fileStyleExtension(std::wstring_view text)
|
||||
{
|
||||
const auto first=text.find_first_not_of(L" \t");
|
||||
if(first==text.npos) return {};
|
||||
auto extension=std::wstring(text.substr(first,text.find_last_not_of(L" \t")-first+1));
|
||||
if(extension.front()!=L'.') extension.insert(0,1,L'.');
|
||||
if(extension.size()<2 || extension.size()>255 ||
|
||||
extension.find_first_of(L". *?\\/:<>|\";\r\n\t",1)!=extension.npos) return {};
|
||||
CharLowerBuffW(extension.data(),static_cast<DWORD>(extension.size()));
|
||||
return extension;
|
||||
}
|
||||
|
||||
bool sameFileExtension(std::wstring_view left,std::wstring_view right)
|
||||
{
|
||||
return !left.empty() && left.size()==right.size() &&
|
||||
CompareStringOrdinal(left.data(),static_cast<int>(left.size()),
|
||||
right.data(),static_cast<int>(right.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
void loadFileStyles()
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>256*1024) return;
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return;
|
||||
try
|
||||
{
|
||||
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
|
||||
if(!rows.is_array() || rows.size()>64) return;
|
||||
std::vector<FileStyle> parsed;
|
||||
for(const auto &row:rows)
|
||||
{
|
||||
FileStyle style{ks::wide(row.at("extension").get<std::string>())};
|
||||
if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return;
|
||||
if(std::any_of(parsed.begin(),parsed.end(),[&](const auto &existing){return existing.extension==style.extension;}))
|
||||
return;
|
||||
const auto color=[&](const char *key)->std::optional<COLORREF>
|
||||
{
|
||||
if(!row.contains(key)) return {};
|
||||
const auto value=row.at(key).get<DWORD>();
|
||||
if(value>0xffffff) throw std::runtime_error("Invalid file style color");
|
||||
return value;
|
||||
};
|
||||
style.foreground=color("foreground");
|
||||
style.background=color("background");
|
||||
style.underline=row.value("underline",false);
|
||||
style.strikeout=row.value("strikeout",false);
|
||||
if(row.contains("states"))
|
||||
{
|
||||
const auto &states=row.at("states");
|
||||
if(!states.is_array() || states.size()!=style.states.size()) return;
|
||||
for(size_t i=0;i<style.states.size();++i)
|
||||
{
|
||||
const auto read=[&](const char *key)->std::optional<COLORREF>
|
||||
{
|
||||
if(!states[i].contains(key)) return {};
|
||||
const auto value=states[i].at(key).get<DWORD>();
|
||||
if(value>0xffffff) throw std::runtime_error("Invalid state color");
|
||||
return value;
|
||||
};
|
||||
style.states[i]={read("foreground"),read("background")};
|
||||
}
|
||||
}
|
||||
parsed.push_back(std::move(style));
|
||||
}
|
||||
fileStyles=std::move(parsed);
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
}
|
||||
|
||||
bool saveFileStyles(const std::vector<FileStyle> &styles)
|
||||
{
|
||||
auto rows=Json::array();
|
||||
for(const auto &style:styles)
|
||||
{
|
||||
Json row{{"extension",ks::utf8(style.extension)},{"underline",style.underline},{"strikeout",style.strikeout}};
|
||||
if(style.foreground) row["foreground"]=*style.foreground;
|
||||
if(style.background) row["background"]=*style.background;
|
||||
row["states"]=Json::array();
|
||||
for(const auto &state:style.states)
|
||||
{
|
||||
auto entry=Json::object();
|
||||
if(state.foreground) entry["foreground"]=*state.foreground;
|
||||
if(state.background) entry["background"]=*state.background;
|
||||
row["states"].push_back(std::move(entry));
|
||||
}
|
||||
rows.push_back(std::move(row));
|
||||
}
|
||||
const auto data=rows.dump();
|
||||
return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
struct FileRowStyle
|
||||
{
|
||||
COLORREF foreground,background;
|
||||
unsigned decorations{};
|
||||
};
|
||||
FileRowStyle resolveFileStyle(std::wstring_view extension,bool file,bool dimmed,bool protectedRow,
|
||||
COLORREF foreground,COLORREF background,const std::vector<FileStyle> &styles=fileStyles,
|
||||
FileRowState state=FileRowState::Normal,bool transferred=false)
|
||||
{
|
||||
FileRowStyle result{foreground,background};
|
||||
const FileStyle *extensionRule=nullptr,*attributeRule=nullptr;
|
||||
for(const auto &style:styles)
|
||||
{
|
||||
if(!file || !sameFileExtension(style.extension,extension)) continue;
|
||||
extensionRule=&style;
|
||||
result.foreground=style.foreground.value_or(result.foreground);
|
||||
if(!protectedRow) result.background=style.background.value_or(result.background);
|
||||
result.decorations=(style.underline?1u:0u)|(style.strikeout?2u:0u);
|
||||
break;
|
||||
}
|
||||
if(dimmed)
|
||||
for(const auto &style:styles)
|
||||
{
|
||||
if(style.extension!=L"@system-hidden") continue;
|
||||
attributeRule=&style;
|
||||
if(style.foreground) result.foreground=*style.foreground;
|
||||
else
|
||||
{
|
||||
const auto fg=result.foreground,bg=result.background;
|
||||
result.foreground=RGB((3*GetRValue(fg)+2*GetRValue(bg))/5,
|
||||
(3*GetGValue(fg)+2*GetGValue(bg))/5,(3*GetBValue(fg)+2*GetBValue(bg))/5);
|
||||
}
|
||||
if(!protectedRow) result.background=style.background.value_or(result.background);
|
||||
result.decorations|=(style.underline?1u:0u)|(style.strikeout?2u:0u);
|
||||
break;
|
||||
}
|
||||
|
||||
if(transferred && state!=FileRowState::Marked)
|
||||
return {RGB(255,223,115),background,result.decorations};
|
||||
if(state==FileRowState::Marked) result.foreground=RGB(255,255,0);
|
||||
if(state!=FileRowState::Normal)
|
||||
{
|
||||
const auto index=static_cast<size_t>(state)-1;
|
||||
for(const auto *rule:{extensionRule,attributeRule})
|
||||
if(rule)
|
||||
{
|
||||
result.foreground=rule->states[index].foreground.value_or(result.foreground);
|
||||
result.background=rule->states[index].background.value_or(result.background);
|
||||
}
|
||||
}
|
||||
if(result.foreground==result.background && state!=FileRowState::Normal)
|
||||
result.foreground=GetRValue(result.background)+GetGValue(result.background)+GetBValue(result.background)>382?RGB(0,0,0):RGB(255,255,255);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
#pragma once
|
||||
|
||||
#include "files_powershell.h"
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
// The reader keeps draining the output pipe while ClosePseudoConsole shuts down.
|
||||
class FilesTerminal
|
||||
{
|
||||
public:
|
||||
~FilesTerminal() { close(); }
|
||||
|
||||
bool start(const wchar_t *directory, COORD size)
|
||||
{
|
||||
if(alive()) return true;
|
||||
close();
|
||||
pending.clear();
|
||||
HANDLE inputRead{}, outputWrite{};
|
||||
if(!CreatePipe(&inputRead,&input,nullptr,0)) return false;
|
||||
if(!CreatePipe(&output,&outputWrite,nullptr,0))
|
||||
{
|
||||
CloseHandle(inputRead);
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
const auto created=CreatePseudoConsole(size,inputRead,outputWrite,0,&console);
|
||||
CloseHandle(inputRead);
|
||||
CloseHandle(outputWrite);
|
||||
if(FAILED(created)) { close(); return false; }
|
||||
reader=std::thread([this]
|
||||
{
|
||||
char buffer[4096];
|
||||
DWORD count{};
|
||||
while(ReadFile(output,buffer,sizeof(buffer),&count,nullptr) && count)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
pending.append(buffer,count);
|
||||
if(pending.size()>1024*1024) pending.erase(0,pending.size()-1024*1024);
|
||||
}
|
||||
});
|
||||
|
||||
SIZE_T bytes{};
|
||||
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
|
||||
std::vector<unsigned char> storage(bytes);
|
||||
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes)) { close(); return false; }
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb=sizeof(startup);
|
||||
startup.lpAttributeList=attributes;
|
||||
PROCESS_INFORMATION info{};
|
||||
wchar_t command[]=L"powershell.exe -NoLogo -NoProfile -NoExit -Command \"Remove-Module PSReadLine -ErrorAction SilentlyContinue; function global:prompt { $location = Get-Location; $path = if ($location.Provider.Name -eq 'FileSystem') { [Uri]::EscapeDataString($location.ProviderPath) }; ([string][char]27) + ']633;ks-directory:' + $path + [char]7 + [char]27 + '[?25l' }; Clear-Host\"";
|
||||
const auto shell=ks::files::windowsPowerShell();
|
||||
const bool started=!shell.empty() &&
|
||||
UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
|
||||
console,sizeof(console),nullptr,nullptr) &&
|
||||
CreateProcessW(shell.c_str(),command,nullptr,nullptr,FALSE,EXTENDED_STARTUPINFO_PRESENT,
|
||||
nullptr,directory,&startup.StartupInfo,&info);
|
||||
DeleteProcThreadAttributeList(attributes);
|
||||
if(!started) { close(); return false; }
|
||||
process=info.hProcess;
|
||||
CloseHandle(info.hThread);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool alive() const { return process && WaitForSingleObject(process,0)==WAIT_TIMEOUT; }
|
||||
|
||||
bool write(const std::wstring &value)
|
||||
{
|
||||
if(!alive()) return false;
|
||||
const int length=WideCharToMultiByte(CP_UTF8,0,value.data(),static_cast<int>(value.size()),
|
||||
nullptr,0,nullptr,nullptr);
|
||||
if(!length) return false;
|
||||
std::string utf8(length,'\0');
|
||||
WideCharToMultiByte(CP_UTF8,0,value.data(),static_cast<int>(value.size()),
|
||||
utf8.data(),length,nullptr,nullptr);
|
||||
DWORD written{};
|
||||
return WriteFile(input,utf8.data(),length,&written,nullptr) && written==utf8.size();
|
||||
}
|
||||
|
||||
void resize(COORD size) { if(console) ResizePseudoConsole(console,size); }
|
||||
|
||||
std::string takeOutput()
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
std::string result;
|
||||
result.swap(pending);
|
||||
return result;
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
if(input) CloseHandle(input);
|
||||
if(console) ClosePseudoConsole(console);
|
||||
if(reader.joinable()) reader.join();
|
||||
if(output) CloseHandle(output);
|
||||
if(process) CloseHandle(process);
|
||||
input=output=process=nullptr;
|
||||
console=nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
HPCON console{};
|
||||
HANDLE input{},output{},process{};
|
||||
std::thread reader;
|
||||
std::mutex mutex;
|
||||
std::string pending;
|
||||
};
|
||||
@@ -0,0 +1,230 @@
|
||||
#pragma once
|
||||
#include <WebView2.h>
|
||||
|
||||
#ifdef __MINGW32__
|
||||
__CRT_UUID_DECL(ICoreWebView2_3, 0xA0D6DF20, 0x3B92, 0x416D, 0xAA, 0x0C, 0x43, 0x7A, 0x9C, 0x72, 0x78, 0x57)
|
||||
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler, 0x4e8a3389, 0xc9d8, 0x4bd2, 0xb6, 0xb5, 0x12, 0x4f, 0xee, 0x6c, 0xc1, 0x4d)
|
||||
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4819f3, 0xc9b7, 0x4260, 0x81, 0x27, 0xc9, 0xf5, 0xbd, 0xe7, 0xf6, 0x8c)
|
||||
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
|
||||
__CRT_UUID_DECL(ICoreWebView2NewWindowRequestedEventHandler, 0xd4c185fe, 0xc81c, 0x4989, 0x97, 0xaf, 0x2d, 0x3f, 0xa7, 0xab, 0x56, 0x51)
|
||||
__CRT_UUID_DECL(ICoreWebView2NavigationStartingEventHandler, 0x9adbe429, 0xf36d, 0x432b, 0x9d, 0xdc, 0xf8, 0x88, 0x1f, 0xbd, 0x76, 0xe3)
|
||||
__CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa79, 0x41a8, 0x8e, 0x44, 0x65, 0x81, 0x1c, 0x76, 0xdc, 0xb2)
|
||||
#endif
|
||||
#include <wrl/client.h>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
template<class Interface, class... Args>
|
||||
class TerminalCallback final : public Interface
|
||||
{
|
||||
ULONG refs=1;
|
||||
std::function<HRESULT(Args...)> invoke;
|
||||
public:
|
||||
explicit TerminalCallback(std::function<HRESULT(Args...)> fn):invoke(std::move(fn)) {}
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **value) override
|
||||
{
|
||||
if(iid!=IID_IUnknown && iid!=__uuidof(Interface)) { *value=nullptr; return E_NOINTERFACE; }
|
||||
*value=static_cast<Interface*>(this);
|
||||
AddRef();
|
||||
return S_OK;
|
||||
}
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; }
|
||||
ULONG STDMETHODCALLTYPE Release() override
|
||||
{
|
||||
const auto remaining=--refs;
|
||||
if(!remaining) delete this;
|
||||
return remaining;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE Invoke(Args... args) override { return invoke(args...); }
|
||||
};
|
||||
|
||||
template<class Interface,class... Args,class Fn>
|
||||
auto terminalCallback(Fn fn)
|
||||
{
|
||||
Microsoft::WRL::ComPtr<Interface> result;
|
||||
result.Attach(new TerminalCallback<Interface,Args...>(std::move(fn)));
|
||||
return result;
|
||||
}
|
||||
|
||||
class FilesTerminalView
|
||||
{
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2Controller> controller;
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2> web;
|
||||
std::shared_ptr<int> lifetime;
|
||||
RECT bounds{};
|
||||
bool ready{};
|
||||
bool visible{};
|
||||
public:
|
||||
~FilesTerminalView() { close(); }
|
||||
void focus()
|
||||
{
|
||||
if(controller) controller->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
|
||||
}
|
||||
void post(const std::wstring &message)
|
||||
{
|
||||
if(ready) web->PostWebMessageAsString(message.c_str());
|
||||
}
|
||||
bool initialized() const { return ready; }
|
||||
void enableTrace(bool output)
|
||||
{
|
||||
if(ready) web->PostWebMessageAsString(output?L"trace:output":L"trace:on");
|
||||
}
|
||||
void setFont(const LOGFONTW &font,int points)
|
||||
{
|
||||
if(!ready) return;
|
||||
const auto message=L"font:"+std::to_wstring(points)+L":"+
|
||||
std::to_wstring(font.lfWeight?font.lfWeight:FW_NORMAL)+L":"+
|
||||
std::to_wstring(font.lfItalic!=0)+L":"+font.lfFaceName;
|
||||
web->PostWebMessageAsString(message.c_str());
|
||||
}
|
||||
void layout(HWND host,bool show,int fullHeight)
|
||||
{
|
||||
RECT area{};
|
||||
GetClientRect(host,&area);
|
||||
area.top=area.bottom-fullHeight;
|
||||
layout(area,show);
|
||||
}
|
||||
void layout(RECT area,bool show)
|
||||
{
|
||||
bounds=area;
|
||||
visible=show;
|
||||
if(!controller) return;
|
||||
RECT current{};
|
||||
if(FAILED(controller->get_Bounds(¤t)) || !EqualRect(¤t,&bounds))
|
||||
controller->put_Bounds(bounds);
|
||||
BOOL currentVisibility{};
|
||||
if(FAILED(controller->get_IsVisible(¤tVisibility)) || !!currentVisibility!=show)
|
||||
controller->put_IsVisible(show);
|
||||
}
|
||||
void close()
|
||||
{
|
||||
lifetime.reset();
|
||||
if(controller) controller->Close();
|
||||
web.Reset();
|
||||
controller.Reset();
|
||||
ready=false;
|
||||
}
|
||||
bool send(const std::string &bytes)
|
||||
{
|
||||
if(!ready) return false;
|
||||
constexpr wchar_t hex[]=L"0123456789abcdef";
|
||||
std::wstring message;
|
||||
message.reserve(bytes.size()*2);
|
||||
for(unsigned char c:bytes)
|
||||
{
|
||||
message+=hex[c>>4];
|
||||
message+=hex[c&15];
|
||||
}
|
||||
return SUCCEEDED(web->PostWebMessageAsString(message.c_str()));
|
||||
}
|
||||
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed,
|
||||
bool markdown=false,std::function<bool(UINT)> handleKey={})
|
||||
{
|
||||
wchar_t exe[MAX_PATH]{};
|
||||
if(!GetModuleFileNameW(nullptr,exe,MAX_PATH)) return false;
|
||||
const auto folder=std::filesystem::path(exe).parent_path();
|
||||
static const auto loader=LoadLibraryExW((folder/L"WebView2Loader.dll").c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
if(!loader) return false;
|
||||
using Create=HRESULT (STDAPICALLTYPE*)(PCWSTR,PCWSTR,ICoreWebView2EnvironmentOptions*,
|
||||
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
|
||||
const auto createEnvironment=reinterpret_cast<Create>(
|
||||
reinterpret_cast<void*>(GetProcAddress(loader,"CreateCoreWebView2EnvironmentWithOptions")));
|
||||
if(!createEnvironment) return false;
|
||||
wchar_t local[MAX_PATH]{};
|
||||
const auto length=GetEnvironmentVariableW(L"LOCALAPPDATA",local,MAX_PATH);
|
||||
if(!length || length>=MAX_PATH) return false;
|
||||
const auto profile=std::filesystem::path(local)/L"KSwitcher"/(markdown?L"MarkdownWebView":L"TerminalWebView");
|
||||
const auto origin=markdown?L"kswitcher-markdown.invalid":L"kswitcher-terminal.invalid";
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
|
||||
const auto assets=folder/L"terminal";
|
||||
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
|
||||
lifetime=std::make_shared<int>(0);
|
||||
const std::weak_ptr<int> alive=lifetime;
|
||||
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
|
||||
HRESULT,ICoreWebView2Environment*>([=,this](HRESULT hr,ICoreWebView2Environment *env)
|
||||
{
|
||||
if(alive.expired()) return S_OK;
|
||||
if(FAILED(hr) || !env) { failed(); return S_OK; }
|
||||
auto completed=terminalCallback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler,
|
||||
HRESULT,ICoreWebView2Controller*>([=,this](HRESULT result,ICoreWebView2Controller *view)
|
||||
{
|
||||
if(alive.expired()) return S_OK;
|
||||
if(FAILED(result) || !view) { failed(); return S_OK; }
|
||||
controller=view;
|
||||
view->get_CoreWebView2(&web);
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
|
||||
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
|
||||
origin,assets.c_str(),COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY)))
|
||||
{ failed(); return S_OK; }
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2Settings> settings;
|
||||
if(SUCCEEDED(web->get_Settings(&settings)))
|
||||
{
|
||||
settings->put_AreDevToolsEnabled(FALSE);
|
||||
settings->put_AreDefaultContextMenusEnabled(FALSE);
|
||||
settings->put_AreHostObjectsAllowed(FALSE);
|
||||
}
|
||||
EventRegistrationToken token{};
|
||||
if(handleKey)
|
||||
{
|
||||
auto accelerator=terminalCallback<ICoreWebView2AcceleratorKeyPressedEventHandler,
|
||||
ICoreWebView2Controller*,ICoreWebView2AcceleratorKeyPressedEventArgs*>(
|
||||
[alive,handleKey](auto*,auto *args)
|
||||
{
|
||||
COREWEBVIEW2_KEY_EVENT_KIND kind{};
|
||||
UINT key{};
|
||||
if(!alive.expired() && SUCCEEDED(args->get_KeyEventKind(&kind)) &&
|
||||
(kind==COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN ||
|
||||
kind==COREWEBVIEW2_KEY_EVENT_KIND_SYSTEM_KEY_DOWN) &&
|
||||
SUCCEEDED(args->get_VirtualKey(&key)) && handleKey(key))
|
||||
args->put_Handled(TRUE);
|
||||
return S_OK;
|
||||
});
|
||||
if(FAILED(view->add_AcceleratorKeyPressed(accelerator.Get(),&token)))
|
||||
{ failed(); return S_OK; }
|
||||
}
|
||||
auto navigation=terminalCallback<ICoreWebView2NavigationStartingEventHandler,
|
||||
ICoreWebView2*,ICoreWebView2NavigationStartingEventArgs*>([uri](auto*,auto *args)
|
||||
{
|
||||
PWSTR address{};
|
||||
if(SUCCEEDED(args->get_Uri(&address)))
|
||||
{
|
||||
args->put_Cancel(uri!=address);
|
||||
CoTaskMemFree(address);
|
||||
}
|
||||
return S_OK;
|
||||
});
|
||||
auto newWindow=terminalCallback<ICoreWebView2NewWindowRequestedEventHandler,
|
||||
ICoreWebView2*,ICoreWebView2NewWindowRequestedEventArgs*>([](auto*,auto *args)
|
||||
{ args->put_Handled(TRUE); return S_OK; });
|
||||
auto messages=terminalCallback<ICoreWebView2WebMessageReceivedEventHandler,
|
||||
ICoreWebView2*,ICoreWebView2WebMessageReceivedEventArgs*>([=,this](auto*,auto *args)
|
||||
{
|
||||
if(alive.expired()) return S_OK;
|
||||
PWSTR source{}, value{};
|
||||
if(SUCCEEDED(args->get_Source(&source)) &&
|
||||
uri==source &&
|
||||
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
|
||||
{
|
||||
if(wcscmp(value,L"ready")==0) ready=true;
|
||||
if(ready) receive(value);
|
||||
}
|
||||
CoTaskMemFree(value);
|
||||
CoTaskMemFree(source);
|
||||
return S_OK;
|
||||
});
|
||||
if(FAILED(web->add_NavigationStarting(navigation.Get(),&token)) ||
|
||||
FAILED(web->add_NewWindowRequested(newWindow.Get(),&token)) ||
|
||||
FAILED(web->add_WebMessageReceived(messages.Get(),&token)) ||
|
||||
FAILED(web->Navigate(uri.c_str())))
|
||||
failed();
|
||||
layout(bounds,visible);
|
||||
return S_OK;
|
||||
});
|
||||
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
|
||||
return S_OK;
|
||||
});
|
||||
return SUCCEEDED(createEnvironment(nullptr,profile.c_str(),nullptr,environment.Get()));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,339 @@
|
||||
#include "files_text_document.h"
|
||||
|
||||
#include <objbase.h>
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[noreturn]] void fail(const char *operation)
|
||||
{
|
||||
throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), operation);
|
||||
}
|
||||
|
||||
struct File
|
||||
{
|
||||
HANDLE handle = INVALID_HANDLE_VALUE;
|
||||
~File() { if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); }
|
||||
HANDLE release() { return std::exchange(handle, INVALID_HANDLE_VALUE); }
|
||||
};
|
||||
|
||||
struct PendingSave
|
||||
{
|
||||
std::filesystem::path path;
|
||||
~PendingSave() { if (!path.empty()) DeleteFileW(path.c_str()); }
|
||||
};
|
||||
|
||||
HANDLE openSource(const std::filesystem::path &path, bool editable)
|
||||
{
|
||||
const auto sharing = FILE_SHARE_READ | FILE_SHARE_DELETE | (editable ? 0 : FILE_SHARE_WRITE);
|
||||
const auto result = CreateFileW(path.c_str(), GENERIC_READ, sharing,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (result == INVALID_HANDLE_VALUE) fail("Open file");
|
||||
return result;
|
||||
}
|
||||
|
||||
uint64_t fileSize(HANDLE file)
|
||||
{
|
||||
LARGE_INTEGER size{};
|
||||
if (!GetFileSizeEx(file, &size)) fail("Read file size");
|
||||
return size.QuadPart;
|
||||
}
|
||||
|
||||
void seek(HANDLE file, uint64_t offset)
|
||||
{
|
||||
LARGE_INTEGER position{};
|
||||
position.QuadPart = static_cast<LONGLONG>(offset);
|
||||
if (!SetFilePointerEx(file, position, nullptr, FILE_BEGIN)) fail("Seek");
|
||||
}
|
||||
|
||||
std::string read(HANDLE file, uint64_t offset, size_t length)
|
||||
{
|
||||
if (!length) return {};
|
||||
seek(file, offset);
|
||||
std::string result(length, '\0');
|
||||
DWORD count{};
|
||||
if (!ReadFile(file, result.data(), static_cast<DWORD>(length), &count, nullptr)) fail("Read file");
|
||||
if (count != length) throw std::runtime_error("The file ended unexpectedly.");
|
||||
return result;
|
||||
}
|
||||
|
||||
void write(HANDLE file, std::string_view bytes)
|
||||
{
|
||||
if (bytes.empty()) return;
|
||||
DWORD written{};
|
||||
if (!WriteFile(file, bytes.data(), static_cast<DWORD>(bytes.size()), &written, nullptr))
|
||||
fail("Write file");
|
||||
if (written != bytes.size()) throw std::runtime_error("The complete block could not be written.");
|
||||
}
|
||||
|
||||
bool sameFile(HANDLE a, HANDLE b)
|
||||
{
|
||||
BY_HANDLE_FILE_INFORMATION first{}, second{};
|
||||
if (!GetFileInformationByHandle(a, &first) || !GetFileInformationByHandle(b, &second))
|
||||
fail("Check file identity");
|
||||
return first.dwVolumeSerialNumber == second.dwVolumeSerialNumber &&
|
||||
first.nFileIndexHigh == second.nFileIndexHigh && first.nFileIndexLow == second.nFileIndexLow;
|
||||
}
|
||||
|
||||
std::filesystem::path temporaryPath(const std::filesystem::path &directory)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if (FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id, name, 40))
|
||||
throw std::runtime_error("Cannot create a temporary file name.");
|
||||
return directory / (std::wstring(L".kswitcher-") + name + L".tmp");
|
||||
}
|
||||
|
||||
std::filesystem::path createTemporary(const std::filesystem::path &directory, File &file, DWORD flags)
|
||||
{
|
||||
auto path = temporaryPath(directory);
|
||||
file.handle = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_NEW, flags, nullptr);
|
||||
if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file");
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(std::move(path)), editable_(editable)
|
||||
{
|
||||
File source{openSource(path_, editable)};
|
||||
if (editable)
|
||||
{
|
||||
std::wstring resolved(32768, L'\0');
|
||||
const auto length = GetFinalPathNameByHandleW(source.handle, resolved.data(),
|
||||
static_cast<DWORD>(resolved.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
|
||||
if (length && length < resolved.size())
|
||||
{
|
||||
resolved.resize(length);
|
||||
path_ = resolved;
|
||||
}
|
||||
}
|
||||
size_ = fileSize(source.handle);
|
||||
const auto prefix = read(source.handle, 0, static_cast<size_t>(std::min<uint64_t>(3, size_)));
|
||||
if (prefix.starts_with("\xef\xbb\xbf")) bom_ = 3;
|
||||
else if (prefix.starts_with("\xff\xfe") || prefix.starts_with("\xfe\xff"))
|
||||
{
|
||||
encoding_ = prefix.starts_with("\xff") ? Encoding::utf16le : Encoding::utf16be;
|
||||
bom_ = 2;
|
||||
if (size_ % 2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
|
||||
}
|
||||
source_ = source.release();
|
||||
}
|
||||
|
||||
TextDocument::~TextDocument()
|
||||
{
|
||||
if (source_ != INVALID_HANDLE_VALUE) CloseHandle(source_);
|
||||
if (spool_ != INVALID_HANDLE_VALUE) CloseHandle(spool_);
|
||||
}
|
||||
|
||||
const wchar_t *TextDocument::encodingName() const
|
||||
{
|
||||
switch (encoding_)
|
||||
{
|
||||
case Encoding::utf16le: return L"UTF-16 LE";
|
||||
case Encoding::utf16be: return L"UTF-16 BE";
|
||||
default: return bom_ ? L"UTF-8 BOM" : L"UTF-8";
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t TextDocument::pages() const
|
||||
{
|
||||
return std::max<uint64_t>(1, (size_ - bom_ + pageBytes - 1) / pageBytes);
|
||||
}
|
||||
|
||||
uint64_t TextDocument::boundary(uint64_t page) const
|
||||
{
|
||||
if (!page) return bom_;
|
||||
if (page >= pages()) return size_;
|
||||
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
|
||||
return boundary(page,source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_);
|
||||
}
|
||||
|
||||
uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
|
||||
{
|
||||
if (!page) return bom_;
|
||||
if (page >= pages()) return size_;
|
||||
|
||||
const auto offset = bom_ + page * pageBytes;
|
||||
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
|
||||
const auto sample = read(source, offset - unit,
|
||||
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
|
||||
const auto getUnit = [&](size_t i) -> unsigned {
|
||||
const auto first = static_cast<unsigned char>(sample[i]);
|
||||
if (unit == 1) return first;
|
||||
const auto second = static_cast<unsigned char>(sample[i + 1]);
|
||||
return encoding_ == Encoding::utf16le ? first | (second << 8) : (first << 8) | second;
|
||||
};
|
||||
if (getUnit(0) == '\n') return offset;
|
||||
for (size_t i = unit; i + unit < sample.size(); i += unit)
|
||||
if (getUnit(i) == '\n') return offset + i;
|
||||
|
||||
size_t i = unit;
|
||||
if (unit == 1)
|
||||
{
|
||||
// Advance past at most one UTF-8 code point, even on malformed input.
|
||||
while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i;
|
||||
}
|
||||
else if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
|
||||
if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit;
|
||||
return offset + i - unit;
|
||||
}
|
||||
|
||||
std::string TextDocument::decode(std::string bytes) const
|
||||
{
|
||||
if (encoding_ == Encoding::utf8 || bytes.empty()) return bytes;
|
||||
std::wstring units;
|
||||
units.resize(bytes.size() / 2);
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
{
|
||||
const auto a = static_cast<unsigned char>(bytes[2 * i]);
|
||||
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
|
||||
units[i] = static_cast<wchar_t>(encoding_ == Encoding::utf16le ? a | (b << 8) : (a << 8) | b);
|
||||
}
|
||||
const auto length = static_cast<int>(units.size());
|
||||
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
|
||||
if (!required) fail("Decode UTF-16");
|
||||
std::string result(required, '\0');
|
||||
if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, result.data(), required, nullptr, nullptr))
|
||||
fail("Decode UTF-16");
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string TextDocument::encode(std::string_view utf8) const
|
||||
{
|
||||
if (encoding_ == Encoding::utf8 || utf8.empty()) return std::string(utf8);
|
||||
const auto length = static_cast<int>(utf8.size());
|
||||
const int required = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, nullptr, 0);
|
||||
if (!required) fail("Encode UTF-16");
|
||||
std::wstring units(required, L'\0');
|
||||
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, units.data(), required))
|
||||
fail("Encode UTF-16");
|
||||
std::string bytes(units.size() * 2, '\0');
|
||||
const int low = encoding_ == Encoding::utf16le ? 0 : 1;
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
{
|
||||
bytes[2 * i + low] = static_cast<char>(units[i] & 0xff);
|
||||
bytes[2 * i + 1 - low] = static_cast<char>(units[i] >> 8);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
std::string TextDocument::readPage(uint64_t page) const
|
||||
{
|
||||
if (const auto it = changes_.find(page); it != changes_.end())
|
||||
return read(spool_, it->second.offset, it->second.size);
|
||||
return readOriginal(page);
|
||||
}
|
||||
|
||||
std::string TextDocument::readOriginal(uint64_t page) const
|
||||
{
|
||||
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
|
||||
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
|
||||
const auto start = boundary(page,source);
|
||||
return decode(read(source, start, static_cast<size_t>(boundary(page + 1,source) - start)));
|
||||
}
|
||||
|
||||
void TextDocument::releaseReadHandle()
|
||||
{
|
||||
if(!editable_ && source_!=INVALID_HANDLE_VALUE)
|
||||
CloseHandle(std::exchange(source_,INVALID_HANDLE_VALUE));
|
||||
}
|
||||
|
||||
bool TextDocument::modifiedWith(uint64_t page, std::string_view current) const
|
||||
{
|
||||
const size_t changesOnPage = changes_.contains(page) ? 1 : 0;
|
||||
return changes_.size() > changesOnPage || current != readOriginal(page);
|
||||
}
|
||||
|
||||
void TextDocument::stage(uint64_t page, std::string_view utf8)
|
||||
{
|
||||
if (!editable_) throw std::logic_error("The file is open for viewing.");
|
||||
if (utf8.size() > editLimit) throw std::runtime_error("The edit exceeds 8 MiB on this page.");
|
||||
if (utf8 == readOriginal(page))
|
||||
{
|
||||
changes_.erase(page);
|
||||
return;
|
||||
}
|
||||
if (spool_ == INVALID_HANDLE_VALUE)
|
||||
{
|
||||
wchar_t directory[32768]{};
|
||||
const auto length = GetTempPathW(static_cast<DWORD>(std::size(directory)), directory);
|
||||
if (!length || length >= std::size(directory)) fail("Locate temporary directory");
|
||||
File file;
|
||||
createTemporary(directory, file, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE);
|
||||
spool_ = file.release();
|
||||
}
|
||||
seek(spool_, spoolSize_);
|
||||
write(spool_, utf8);
|
||||
changes_.insert_or_assign(page, Change{spoolSize_, utf8.size()});
|
||||
spoolSize_ += utf8.size();
|
||||
}
|
||||
|
||||
bool TextDocument::save()
|
||||
{
|
||||
if (!modified()) return true;
|
||||
PendingSave pending;
|
||||
File output;
|
||||
pending.path = createTemporary(path_.parent_path(), output, FILE_ATTRIBUTE_NORMAL);
|
||||
|
||||
uint64_t written{};
|
||||
const auto append = [&](std::string_view bytes) {
|
||||
write(output.handle, bytes);
|
||||
written += bytes.size();
|
||||
};
|
||||
const auto copyUntil = [&](uint64_t &offset, uint64_t end) {
|
||||
while (offset < end)
|
||||
{
|
||||
const auto block = read(source_, offset, static_cast<size_t>(std::min(pageBytes, end - offset)));
|
||||
append(block);
|
||||
offset += block.size();
|
||||
}
|
||||
};
|
||||
uint64_t offset{};
|
||||
for (const auto &[page, change] : changes_)
|
||||
{
|
||||
copyUntil(offset, boundary(page));
|
||||
append(encode(read(spool_, change.offset, change.size)));
|
||||
offset = boundary(page + 1);
|
||||
}
|
||||
copyUntil(offset, size_);
|
||||
if (!FlushFileBuffers(output.handle)) fail("Flush saved file");
|
||||
CloseHandle(output.release());
|
||||
|
||||
// A metadata-only handle survives the rename without blocking ReplaceFile's exclusive open.
|
||||
File replacement{CreateFileW(pending.path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)};
|
||||
if (replacement.handle == INVALID_HANDLE_VALUE) fail("Track replacement file");
|
||||
File current{openSource(path_, true)};
|
||||
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
|
||||
const auto backup = temporaryPath(path_.parent_path());
|
||||
if (!ReplaceFileW(path_.c_str(), pending.path.c_str(), backup.c_str(), 0, nullptr, nullptr))
|
||||
{
|
||||
const auto error = GetLastError();
|
||||
if (GetFileAttributesW(backup.c_str()) != INVALID_FILE_ATTRIBUTES &&
|
||||
!MoveFileExW(backup.c_str(), path_.c_str(), MOVEFILE_WRITE_THROUGH))
|
||||
{
|
||||
const auto location = backup.u8string();
|
||||
throw std::runtime_error("Could not restore the original name after a save error. The original is at " +
|
||||
std::string(location.begin(), location.end()));
|
||||
}
|
||||
SetLastError(error);
|
||||
fail("Replace original file");
|
||||
}
|
||||
pending.path.clear();
|
||||
const auto newSource = ReOpenFile(replacement.handle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, 0);
|
||||
DeleteFileW(backup.c_str());
|
||||
CloseHandle(source_);
|
||||
source_ = newSource;
|
||||
size_ = written;
|
||||
changes_.clear();
|
||||
if (spool_ != INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_, INVALID_HANDLE_VALUE));
|
||||
spoolSize_ = 0;
|
||||
return source_ != INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
class TextDocument
|
||||
{
|
||||
public:
|
||||
static constexpr uint64_t pageBytes = 1024 * 1024;
|
||||
static constexpr size_t editLimit = 8 * pageBytes;
|
||||
|
||||
explicit TextDocument(std::filesystem::path path, bool editable = true);
|
||||
~TextDocument();
|
||||
TextDocument(const TextDocument &) = delete;
|
||||
TextDocument &operator=(const TextDocument &) = delete;
|
||||
|
||||
uint64_t pages() const;
|
||||
uint64_t size() const { return size_; }
|
||||
uint64_t boundary(uint64_t page) const;
|
||||
std::string readPage(uint64_t page) const;
|
||||
void releaseReadHandle();
|
||||
void stage(uint64_t page, std::string_view utf8);
|
||||
bool modified() const { return !changes_.empty(); }
|
||||
bool modifiedWith(uint64_t page, std::string_view current) const;
|
||||
bool save();
|
||||
const wchar_t *encodingName() const;
|
||||
|
||||
private:
|
||||
enum class Encoding { utf8, utf16le, utf16be };
|
||||
struct Change { uint64_t offset; size_t size; };
|
||||
|
||||
std::filesystem::path path_;
|
||||
HANDLE source_ = INVALID_HANDLE_VALUE;
|
||||
HANDLE spool_ = INVALID_HANDLE_VALUE;
|
||||
uint64_t size_{}, spoolSize_{};
|
||||
size_t bom_{};
|
||||
Encoding encoding_ = Encoding::utf8;
|
||||
bool editable_;
|
||||
std::map<uint64_t, Change> changes_;
|
||||
|
||||
std::string decode(std::string bytes) const;
|
||||
uint64_t boundary(uint64_t page,HANDLE source) const;
|
||||
std::string readOriginal(uint64_t page) const;
|
||||
std::string encode(std::string_view utf8) const;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
#include "files_text_language.h"
|
||||
#include "core.h"
|
||||
|
||||
#include <Sci_Position.h>
|
||||
#include <ILexer.h>
|
||||
#include <Lexilla.h>
|
||||
#include <Scintilla.h>
|
||||
#include <SciLexer.h>
|
||||
#include <algorithm>
|
||||
#include <cwctype>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr char cpp[] = "alignas alignof asm auto bool break case catch char char8_t char16_t char32_t class concept const "
|
||||
"consteval constexpr constinit const_cast continue co_await co_return co_yield decltype default delete do double "
|
||||
"dynamic_cast else enum explicit export extern false float for friend goto if inline int long mutable namespace "
|
||||
"new noexcept nullptr operator private protected public register reinterpret_cast requires return short signed "
|
||||
"sizeof static static_assert static_cast struct switch template this thread_local throw true try typedef typeid "
|
||||
"typename union unsigned using virtual void volatile wchar_t while import module";
|
||||
constexpr char csharp[] = "abstract as async await base bool break byte case catch char checked class const continue "
|
||||
"decimal default delegate do double else enum event explicit extern false file finally fixed float for foreach from "
|
||||
"get global goto if implicit in init int interface internal is let lock long namespace new not null object operator "
|
||||
"or out override partial private protected public readonly record ref required return sbyte sealed select set short "
|
||||
"sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unmanaged unsafe "
|
||||
"ushort using value var virtual void volatile when where while with yield";
|
||||
constexpr char javascript[] = "abstract any as async await boolean break case catch class const continue debugger declare "
|
||||
"default delete do else enum export extends false finally for from function get if implements import in infer "
|
||||
"instanceof interface keyof let module namespace never new null number object of override private protected public "
|
||||
"readonly return satisfies set static string super switch symbol this throw true try type typeof undefined unknown "
|
||||
"using var void while with yield";
|
||||
constexpr char java[] = "abstract assert boolean break byte case catch char class const continue default do double else "
|
||||
"enum exports extends final finally float for if implements import instanceof int interface long module native new "
|
||||
"non-sealed null open opens package permits private protected public record requires return sealed short static super "
|
||||
"switch synchronized this throw throws transient true try var void volatile while yield false";
|
||||
constexpr char sql[] = "add alter and any as asc begin between by case check column commit constraint create cross "
|
||||
"database declare default delete desc distinct drop else end except exists fetch foreign from full function grant "
|
||||
"group having in index inner insert intersect into is join left like limit merge not null offset on or order outer "
|
||||
"over partition primary procedure references returning right rollback row select set table then top transaction "
|
||||
"truncate union unique update using values view when where window with";
|
||||
constexpr char python[] = "and as assert async await break class continue def del elif else except False finally for from "
|
||||
"global if import in is lambda match case None nonlocal not or pass raise return True try while with yield";
|
||||
constexpr char ps[] = "begin break catch class continue data define do dynamicparam else elseif end enum exit filter finally "
|
||||
"for foreach from function if in param process return switch throw trap try until using var while workflow";
|
||||
constexpr char shell[] = "alias bg break case cd continue declare do done echo elif else esac eval exec exit export "
|
||||
"false fi for function if in local read readonly return select set shift source test then time trap true type "
|
||||
"typeset ulimit umask unalias unset until wait while";
|
||||
constexpr char rust[] = "as async await break const continue crate dyn else enum extern false fn for if impl in let loop "
|
||||
"match mod move mut pub ref return self Self static struct super trait true type unsafe use where while";
|
||||
constexpr char go[] = "break case chan const continue default defer else fallthrough for func go goto if import interface "
|
||||
"map package range return select struct switch type var nil false true";
|
||||
constexpr char lua[] = "and break do else elseif end false for function goto if in local nil not or repeat return then true until while";
|
||||
constexpr char ruby[] = "BEGIN END alias and begin break case class def defined do else elsif end ensure false for if in "
|
||||
"module next nil not or redo rescue retry return self super then true undef unless until when while yield";
|
||||
constexpr char html[] = "a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption "
|
||||
"cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer "
|
||||
"form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark "
|
||||
"menu meta meter nav noscript object ol optgroup option output p picture pre progress q rp rt ruby s samp script "
|
||||
"search section select slot small source span strong style sub summary sup table tbody td template textarea tfoot "
|
||||
"th thead time title tr track u ul var video wbr accept action alt aria-label async cellpadding charset checked cite "
|
||||
"class content controls defer disabled for height href http-equiv id lang maxlength method multiple name placeholder "
|
||||
"readonly rel required role rows scope selected src srcset style tabindex target type value width";
|
||||
|
||||
struct Mapping
|
||||
{
|
||||
std::wstring_view names;
|
||||
const char *lexer;
|
||||
const char *keywords = "";
|
||||
};
|
||||
constexpr Mapping languages[] = {
|
||||
{L".c .h .cc .cpp .cxx .hh .hpp .hxx .inl .ipp .ixx .cppm .cu .cuh .m .mm .rc .idl .ino", "cpp", cpp},
|
||||
{L".cs .csx .razor.cs", "cpp", csharp},
|
||||
{L".js .jsx .mjs .cjs .ts .tsx .mts .cts .es", "cpp", javascript},
|
||||
{L".java .pde", "cpp", java},
|
||||
{L".kt .kts", "cpp", "abstract actual as break by catch class companion const constructor continue data do else enum "
|
||||
"expect false finally for fun if import in init interface internal is lateinit null object open operator out "
|
||||
"override package private protected public return sealed super suspend this throw true try typealias val var when while"},
|
||||
{L".glsl .vert .frag .geom .hlsl .fx .metal", "cpp", cpp},
|
||||
{L".html .htm .xhtml .shtml .vue .svelte .astro .cshtml .razor .aspx .jsp .php .phtml", "hypertext", html},
|
||||
{L".xml .xsl .xslt .xsd .svg .resx .xaml .csproj .fsproj .vbproj .vcxproj .props .targets .config .nuspec "
|
||||
L".wixproj .wxs .plist .rss .atom .gpx .kml .ui .iml .wsdl .manifest .slnx .axaml", "xml"},
|
||||
{L".css .scss .sass .less", "css", "color background display position width height margin padding border font "
|
||||
"grid flex content gap box-shadow transform animation opacity overflow text-align align-items justify-content"},
|
||||
{L".sql .psql .ddl .dml .mysql", "sql", sql},
|
||||
{L".py .pyw .pyi .rpy sconstruct sconscript", "python", python},
|
||||
{L".json .jsonc .json5 .ipynb .webmanifest .geojson .topojson .code-workspace .sublime-settings .sublime-project",
|
||||
"json", "false null true Infinity NaN"},
|
||||
{L".yaml .yml .eyaml .clang-format .clang-tidy", "yaml", "true false null yes no on off"},
|
||||
{L".toml pipfile uv.lock cargo.lock poetry.lock", "toml", "true false"},
|
||||
{L".md .markdown .mdown .mkd .mdx readme", "markdown"},
|
||||
{L".adoc .asciidoc", "asciidoc"},
|
||||
{L".ini .cfg .conf .properties .url .inf .reg .editorconfig .gitconfig .gitattributes .gitmodules .npmrc .env", "props"},
|
||||
{L".sh .bash .zsh .ksh .bats .bashrc .bash_profile .zshrc .profile configure gradlew mvnw", "bash", shell},
|
||||
{L".ps1 .psm1 .psd1", "powershell", ps},
|
||||
{L".bat .cmd", "batch", "call cd chdir cls copy del dir echo endlocal exit for goto if md mkdir move path pause popd "
|
||||
"pushd rd rem ren rename set setlocal shift start title type"},
|
||||
{L".cmake cmakelists.txt", "cmake", "add_executable add_library add_subdirectory cmake_minimum_required "
|
||||
"configure_file else elseif endforeach endfunction endif endwhile file find_package foreach function if include "
|
||||
"install list message option project set string target_compile_definitions target_include_directories "
|
||||
"target_link_libraries unset while"},
|
||||
{L".mk .mak makefile gnumakefile", "makefile"},
|
||||
{L".rs", "rust", rust}, {L".go", "cpp", go}, {L".lua", "lua", lua}, {L".rb .rake .gemspec gemfile rakefile", "ruby", ruby},
|
||||
{L".dart", "dart", "abstract as assert async await break case class const continue default do else enum extends "
|
||||
"false final finally for if implements import in interface late mixin new null on override return sealed static "
|
||||
"super switch this throw true try typedef var void while with yield"},
|
||||
{L".swift", "cpp", "actor as associatedtype await break case catch class continue default defer deinit do else "
|
||||
"enum extension false for func guard if import in init let nil private protocol public return self some "
|
||||
"static struct super switch throw throws true try typealias var where while"},
|
||||
{L".zig", "zig"}, {L".d .di", "d"}, {L".nim .nims .nimble", "nim"},
|
||||
{L".fs .fsi .fsx", "fsharp"}, {L".ml .mli", "caml"}, {L".sml .sig", "SML"},
|
||||
{L".vb .bas .frm .cls", "vb", "as byref byval class const dim each else elseif end enum for function if implements "
|
||||
"imports inherits interface module new next nothing private property public return select shared sub then try while"},
|
||||
{L".vbs", "vbscript"}, {L".pl .pm .t", "perl"}, {L".r .rprofile", "r"},
|
||||
{L".jl", "julia"}, {L".matlab", "matlab"}, {L".oct", "octave"},
|
||||
{L".tex .sty .ltx", "latex"}, {L".bib", "bib"}, {L".hs", "haskell"}, {L".lhs", "literatehaskell"},
|
||||
{L".lisp .lsp .cl .el .scm .ss .rkt", "lisp"},
|
||||
{L".s .asm .nasm .inc", "asm"}, {L".a68k", "a68k"},
|
||||
{L".v .vh .sv .svh", "verilog"}, {L".vhd .vhdl", "vhdl"},
|
||||
{L".f .for .f77", "f77"}, {L".f90 .f95 .f03 .f08", "fortran"},
|
||||
{L".ada .adb .ads", "ada"}, {L".pas .pp .dpr", "pascal"}, {L".cob .cbl .cpy", "COBOL"},
|
||||
{L".tcl .tk", "tcl"}, {L".coffee .litcoffee", "coffeescript"}, {L".au3", "au3"},
|
||||
{L".st", "smalltalk"}, {L".erl .hrl", "erlang"},
|
||||
{L".purs", "haskell"}, {L".diff .patch", "diff"}, {L".po .pot", "po"},
|
||||
{L".iss", "inno"}, {L".nsi .nsh", "nsis"}, {L".idl3 .odl", "cpp", cpp},
|
||||
{L".dmap", "DMAP"}, {L".dns .zone", "props"}, {L".ihex .hex", "ihex"}, {L".srec .s19 .s28 .s37", "srec"},
|
||||
{L".edifact .edi", "edifact"}, {L".x12", "x12"}, {L".g4", "cpp", java},
|
||||
{L".nix", "nix"}, {L".gd", "gdscript", python}, {L".il", "cil"}, {L".as", "cpp", javascript},
|
||||
{L".frt .fth", "forth"}, {L".e .eif", "eiffel"}, {L".pov .povray", "pov"},
|
||||
{L".rebol .reb", "rebol"}, {L".asn .asn1", "asn1"}, {L".asy", "asy"},
|
||||
{L".raku .rakumod .rakutest .p6 .pm6", "raku"}, {L".bb", "blitzbasic"}, {L".bi", "freebasic"},
|
||||
{L".t2t", "txt2tags"}, {L".troff .roff .man", "troff"},
|
||||
{L".clw", "clarion"}, {L".spice .cir", "spice"},
|
||||
};
|
||||
|
||||
bool containsWord(std::wstring_view words, std::wstring_view key)
|
||||
{
|
||||
if (key.empty()) return false;
|
||||
for (size_t start = 0; start < words.size();)
|
||||
{
|
||||
const auto end = words.find(L' ', start);
|
||||
if (words.substr(start, end == words.npos ? end : end - start) == key) return true;
|
||||
if (end == words.npos) break;
|
||||
start = end + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
TextLanguage detectLanguage(const std::filesystem::path &path, std::string_view firstPage)
|
||||
{
|
||||
auto filename = path.filename().wstring();
|
||||
auto extension = path.extension().wstring();
|
||||
for (auto *value : {&filename, &extension})
|
||||
std::transform(value->begin(), value->end(), value->begin(), [](wchar_t ch) { return std::towlower(ch); });
|
||||
for (const auto &language : languages)
|
||||
if (containsWord(language.names, filename) || containsWord(language.names, extension))
|
||||
return {language.lexer, language.keywords};
|
||||
if (filename.starts_with(L".env.") || extension == L".env") return {"props"};
|
||||
if (firstPage.starts_with("<?xml")) return {"xml"};
|
||||
if (firstPage.starts_with("#!"))
|
||||
{
|
||||
const auto line = firstPage.substr(0, firstPage.find_first_of("\r\n"));
|
||||
for (const auto &[needle, language] : {std::pair{"python", TextLanguage{"python", python}},
|
||||
{"ruby", {"ruby", ruby}}, {"node", {"cpp", javascript}}, {"perl", {"perl"}},
|
||||
{"pwsh", {"powershell", ps}}, {"lua", {"lua", lua}}, {"sh", {"bash", shell}}})
|
||||
if (line.find(needle) != line.npos) return language;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::wstring textLanguageLabel(const TextLanguage &language)
|
||||
{
|
||||
if (language.keywords == csharp) return L"C#";
|
||||
if (language.keywords == javascript) return L"JavaScript / TypeScript";
|
||||
if (language.keywords == java) return L"Java";
|
||||
if (language.keywords == go) return L"Go";
|
||||
if (language.lexer == "cpp") return L"C-family";
|
||||
if (language.lexer == "hypertext") return L"HTML";
|
||||
return language.lexer.empty() ? L"Plain text" : wide(language.lexer);
|
||||
}
|
||||
|
||||
Scintilla::ILexer5 *createTextLexer(const TextLanguage &language)
|
||||
{
|
||||
if (language.lexer.empty()) return nullptr;
|
||||
auto *lexer = CreateLexer(language.lexer.c_str());
|
||||
if (!lexer) return nullptr;
|
||||
const auto *keywords = language.keywords;
|
||||
if (!*keywords)
|
||||
for (const auto &mapping : languages)
|
||||
if (language.lexer == mapping.lexer && *mapping.keywords)
|
||||
{
|
||||
keywords = mapping.keywords;
|
||||
break;
|
||||
}
|
||||
if (*keywords) lexer->WordListSet(0, keywords);
|
||||
if (language.lexer == "hypertext") lexer->WordListSet(1, javascript);
|
||||
if (language.lexer == "json") lexer->PropertySet("lexer.json.allow.comments", "1");
|
||||
if (language.lexer == "cpp" && (language.keywords == javascript || language.keywords == go))
|
||||
{
|
||||
lexer->PropertySet("lexer.cpp.backquoted.strings", language.keywords == javascript ? "2" : "1");
|
||||
if (language.keywords == javascript) lexer->PropertySet("lexer.cpp.regex", "1");
|
||||
}
|
||||
if (language.lexer == "cpp" && language.keywords == csharp)
|
||||
lexer->PropertySet("lexer.cpp.triplequoted.strings", "1");
|
||||
return lexer;
|
||||
}
|
||||
|
||||
TextColor syntaxColor(Scintilla::ILexer5 &lexer, std::string_view name, int style)
|
||||
{
|
||||
if (!style || (style >= STYLE_DEFAULT && style <= STYLE_LASTPREDEFINED)) return TextColor::text;
|
||||
const auto *styleTags = lexer.TagsOfStyle(style);
|
||||
const auto *styleName = lexer.NameOfStyle(style);
|
||||
const std::string_view tags = styleTags ? styleTags : "";
|
||||
const std::string_view token = styleName ? styleName : "";
|
||||
const auto has = [&](std::string_view word) {
|
||||
return tags.find(word) != tags.npos || token.find(word) != token.npos;
|
||||
};
|
||||
if (has("comment")) return TextColor::comment;
|
||||
if (has("string") || has("character") || has("quoted") || has("regex")) return TextColor::string;
|
||||
if (has("number") || has("numeric")) return TextColor::number;
|
||||
if (has("keyword") || has("command") || has("tag") || has("heading") || has("header") ||
|
||||
has("preprocessor") || has("keywordclass")) return TextColor::keyword;
|
||||
if (has("operator") || has("attribute") || has("property") || has("variable") || has("label"))
|
||||
return TextColor::symbol;
|
||||
if (name == "markdown")
|
||||
{
|
||||
if (style >= SCE_MARKDOWN_HEADER1 && style <= SCE_MARKDOWN_HEADER6) return TextColor::keyword;
|
||||
if (style >= SCE_MARKDOWN_CODE && style <= SCE_MARKDOWN_CODEBK) return TextColor::string;
|
||||
return TextColor::symbol;
|
||||
}
|
||||
if (name == "diff")
|
||||
{
|
||||
if (style == SCE_DIFF_ADDED) return TextColor::string;
|
||||
if (style == SCE_DIFF_DELETED) return TextColor::number;
|
||||
if (style == SCE_DIFF_COMMENT) return TextColor::comment;
|
||||
return TextColor::keyword;
|
||||
}
|
||||
if (name == "sql")
|
||||
{
|
||||
if (style >= SCE_SQL_COMMENT && style <= SCE_SQL_COMMENTDOC) return TextColor::comment;
|
||||
if (style == SCE_SQL_NUMBER) return TextColor::number;
|
||||
if (style == SCE_SQL_WORD || style == SCE_SQL_WORD2) return TextColor::keyword;
|
||||
if (style == SCE_SQL_STRING || style == SCE_SQL_CHARACTER) return TextColor::string;
|
||||
}
|
||||
if (name == "json")
|
||||
{
|
||||
if (style == SCE_JSON_LINECOMMENT || style == SCE_JSON_BLOCKCOMMENT) return TextColor::comment;
|
||||
if (style == SCE_JSON_STRING || style == SCE_JSON_STRINGEOL) return TextColor::string;
|
||||
if (style == SCE_JSON_NUMBER) return TextColor::number;
|
||||
if (style == SCE_JSON_KEYWORD || style == SCE_JSON_LDKEYWORD) return TextColor::keyword;
|
||||
}
|
||||
if (name == "css")
|
||||
{
|
||||
if (style == SCE_CSS_COMMENT) return TextColor::comment;
|
||||
if (style == SCE_CSS_DOUBLESTRING || style == SCE_CSS_SINGLESTRING || style == SCE_CSS_VALUE)
|
||||
return TextColor::string;
|
||||
if (style == SCE_CSS_TAG || style == SCE_CSS_DIRECTIVE) return TextColor::keyword;
|
||||
}
|
||||
if (name == "yaml" || name == "toml")
|
||||
{
|
||||
// The two lexers assign the same IDs to these categories.
|
||||
if (style == SCE_YAML_COMMENT) return TextColor::comment;
|
||||
if (style == SCE_YAML_KEYWORD) return TextColor::keyword;
|
||||
if (style == SCE_YAML_NUMBER) return TextColor::number;
|
||||
}
|
||||
if (token.empty()) return TextColor::symbol;
|
||||
return TextColor::text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Scintilla { class ILexer5; }
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
enum class TextColor { background, text, chromebg, chrome, selection, comment, keyword, string, number, symbol,
|
||||
menuText, menuHighlight, menuHighlightText, menuAccessKey, count };
|
||||
|
||||
struct TextLanguage
|
||||
{
|
||||
std::string lexer;
|
||||
const char *keywords = "";
|
||||
};
|
||||
|
||||
TextLanguage detectLanguage(const std::filesystem::path &path, std::string_view firstPage);
|
||||
std::wstring textLanguageLabel(const TextLanguage &language);
|
||||
Scintilla::ILexer5 *createTextLexer(const TextLanguage &language);
|
||||
TextColor syntaxColor(Scintilla::ILexer5 &lexer, std::string_view name, int style);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline constexpr size_t documentColorCount = 10;
|
||||
using TextPalette = std::array<COLORREF, 14>;
|
||||
inline constexpr const wchar_t *textPaletteNames[] = {L"FAR (blue)", L"Dark", L"Light"};
|
||||
inline constexpr TextPalette textPalettes[] = {
|
||||
{RGB(0,0,128), RGB(215,230,255), RGB(0,128,128), RGB(255,255,255), RGB(0,115,115),
|
||||
RGB(143,195,157), RGB(255,235,118), RGB(165,235,255), RGB(255,181,228), RGB(155,214,255),
|
||||
RGB(0,0,0), RGB(0,0,0), RGB(255,255,255), RGB(255,255,0)},
|
||||
{RGB(29,33,38), RGB(234,237,241), RGB(45,60,70), RGB(255,255,255), RGB(42,86,127),
|
||||
RGB(155,185,150), RGB(145,201,255), RGB(241,186,143), RGB(208,170,255), RGB(152,226,218),
|
||||
RGB(255,255,255), RGB(42,86,127), RGB(255,255,255), RGB(255,255,0)},
|
||||
{RGB(255,255,255), RGB(28,35,46), RGB(221,231,237), RGB(25,38,54), RGB(74,104,146),
|
||||
RGB(45,111,70), RGB(103,40,154), RGB(152,52,30), RGB(35,82,156), RGB(0,99,109),
|
||||
RGB(0,0,0), RGB(189,207,223), RGB(0,0,0), RGB(111,77,0)},
|
||||
};
|
||||
inline constexpr const wchar_t *textColorNames[] = {L"Background", L"Text", L"Status background", L"Status text",
|
||||
L"Selection", L"Comment", L"Keyword", L"String", L"Number", L"Symbol",
|
||||
L"Top menu text", L"Selected menu background", L"Selected menu text", L"Menu access key"};
|
||||
|
||||
struct TextPreferences
|
||||
{
|
||||
bool wrap{}, numbers{true}, whitespace{}, tabsAsSpaces{}, autoIndent{true}, caretLine{true};
|
||||
int tabWidth{4}, lineEnding{};
|
||||
std::wstring scheme = textPaletteNames[0];
|
||||
TextPalette colors = textPalettes[0];
|
||||
bool operator==(const TextPreferences &) const = default;
|
||||
};
|
||||
|
||||
// Index 0 is Viewer and index 1 is Editor.
|
||||
using TextPreferencesSet = std::array<TextPreferences, 2>;
|
||||
struct NamedTextPalette
|
||||
{
|
||||
std::wstring name;
|
||||
TextPalette colors;
|
||||
bool operator==(const NamedTextPalette &) const = default;
|
||||
};
|
||||
inline constexpr size_t maxTextPalettes = 48;
|
||||
inline constexpr size_t maxTextPaletteName = 48;
|
||||
struct MarkdownPreferences
|
||||
{
|
||||
unsigned width{960}, fontSize{12};
|
||||
std::wstring font;
|
||||
bool operator==(const MarkdownPreferences &) const = default;
|
||||
};
|
||||
|
||||
struct TextSettings
|
||||
{
|
||||
TextPreferencesSet profiles;
|
||||
std::vector<NamedTextPalette> schemes;
|
||||
MarkdownPreferences markdown;
|
||||
bool operator==(const TextSettings &) const = default;
|
||||
};
|
||||
TextSettings loadTextPreferences();
|
||||
void saveTextPreferences(const TextSettings &settings);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::lan { struct FilesPeer; }
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline constexpr int searchOptionsDivider = 104;
|
||||
inline constexpr int searchButtonsDivider = 105;
|
||||
inline constexpr int searchHistoryButton = 108;
|
||||
inline constexpr wchar_t farDropDownProperty[]=L"KSwitcher.Files.ActiveDropDown";
|
||||
|
||||
struct TextWindowFont
|
||||
{
|
||||
LOGFONTW font;
|
||||
int tenthsOfPoint;
|
||||
};
|
||||
|
||||
struct FarDropDownPalette
|
||||
{
|
||||
COLORREF surface, text, selection;
|
||||
};
|
||||
|
||||
enum class FarHistoryKind { search, folder };
|
||||
struct FarHistoryEntry { std::wstring date,text; };
|
||||
std::vector<FarHistoryEntry> loadFarHistory(FarHistoryKind kind);
|
||||
void rememberFarHistory(FarHistoryKind kind,std::wstring_view text);
|
||||
int chooseFarDropDown(HWND anchor,const std::vector<FarHistoryEntry> &entries,int selected,
|
||||
FarDropDownPalette palette,int rightInset=0);
|
||||
void showFarHistory(HWND dialog,int fieldId,const std::vector<FarHistoryEntry> &history,
|
||||
FarDropDownPalette palette);
|
||||
void installFarHistoryKey(HWND field,int arrowId);
|
||||
|
||||
struct TextDialogs
|
||||
{
|
||||
INT_PTR (*confirmSave)(HWND);
|
||||
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
|
||||
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
|
||||
void (*prepare)(HWND);
|
||||
void (*options)(HWND, bool);
|
||||
void (*message)(HWND, const wchar_t *);
|
||||
TextWindowFont (*readFont)();
|
||||
FarDropDownPalette (*dropDownPalette)();
|
||||
INT_PTR (*run)(HINSTANCE,LPCWSTR,HWND,DLGPROC,LPARAM);
|
||||
void (*finish)(HWND,INT_PTR);
|
||||
bool (*dismissOwned)(HWND);
|
||||
bool (*confirmExisting)(HWND);
|
||||
};
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false);
|
||||
void textWindowOwnerClosed();
|
||||
bool cycleTextWindows(HWND current,bool reverse);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
namespace ks {
|
||||
inline constexpr size_t HistoryThumbnailBudget = 1024 * 1024;
|
||||
inline constexpr size_t HistoryRichTextBudget = 256 * 1024;
|
||||
// Keep the visible working set even in unusually tall windows. Never evict a
|
||||
// visible preview to admit another visible preview: that creates a paint loop.
|
||||
template<class T, class Weight>
|
||||
void trimHistoryPreviews(std::map<std::wstring,T> &cache,
|
||||
const std::set<std::wstring> &visible, size_t limit,
|
||||
size_t byteLimit, Weight weight)
|
||||
{
|
||||
size_t bytes = 0;
|
||||
for (const auto &[id, value] : cache) bytes += weight(value);
|
||||
for(auto it=cache.begin(); (cache.size()>limit || bytes>byteLimit) && it!=cache.end();)
|
||||
if(!visible.contains(it->first)) {
|
||||
bytes -= weight(it->second);
|
||||
it=cache.erase(it);
|
||||
}
|
||||
else ++it;
|
||||
}
|
||||
template<class T>
|
||||
void trimHistoryPreviews(std::map<std::wstring,T> &cache,
|
||||
const std::set<std::wstring> &visible, size_t limit=32)
|
||||
{
|
||||
trimHistoryPreviews(cache, visible, limit, 0, [](const T &) { return size_t{}; });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <iphlpapi.h>
|
||||
#include "lan.h"
|
||||
#include "lan_files.h"
|
||||
#include "lan_pairing.h"
|
||||
#include "lan_mesh.h"
|
||||
#include "lan_clipboard.h"
|
||||
#include "lan_layout.h"
|
||||
#include "lan_network.h"
|
||||
#include "lan_wake.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";
|
||||
}
|
||||
Bytes ipv4Adapters()
|
||||
{
|
||||
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); }
|
||||
if(result!=NO_ERROR) return {};
|
||||
return data;
|
||||
}
|
||||
std::string wakeMacFor(ULONG remote)
|
||||
{
|
||||
DWORD interfaceIndex{};
|
||||
if(GetBestInterface(remote,&interfaceIndex)!=NO_ERROR) return {};
|
||||
auto data=ipv4Adapters();
|
||||
if(data.empty()) return {};
|
||||
for(auto a=reinterpret_cast<const IP_ADAPTER_ADDRESSES*>(data.data());a;a=a->Next)
|
||||
{
|
||||
if(a->IfIndex!=interfaceIndex || a->OperStatus!=IfOperStatusUp || a->PhysicalAddressLength!=6 ||
|
||||
(a->IfType!=IF_TYPE_ETHERNET_CSMACD && a->IfType!=IF_TYPE_IEEE80211)) continue;
|
||||
std::string result;
|
||||
for(size_t i=0;i<a->PhysicalAddressLength;++i)
|
||||
{
|
||||
const auto byte=a->PhysicalAddress[i];
|
||||
result+="0123456789abcdef"[byte>>4];
|
||||
result+="0123456789abcdef"[byte&15];
|
||||
}
|
||||
return lan::wakePacket(result)?result:std::string{};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
std::vector<ULONG> broadcasts()
|
||||
{
|
||||
auto data=ipv4Adapters();
|
||||
std::vector<ULONG> out;
|
||||
if(data.empty()) 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;
|
||||
}
|
||||
}
|
||||
void lan::wakeFilesPeer(const std::string &id)
|
||||
{
|
||||
const auto settings=Json::parse(unprotect(readFile(dataDirectory()/L"lan-pairing.bin",256*1024)));
|
||||
const auto &trusted=settings.at("trusted");
|
||||
if(!settings.value("enabled",false) || !trusted.contains(id))
|
||||
throw std::runtime_error("Enable KSwitcher LAN and select a paired PC.");
|
||||
const auto packet=wakePacket(trusted.at(id).value("wakeMac",""));
|
||||
if(!packet) throw std::runtime_error("No saved MAC address. Run updated KSwitcher on this PC while it is online once.");
|
||||
const auto destinations=broadcasts();
|
||||
if(destinations.empty()) throw std::runtime_error("No local IPv4 network is available.");
|
||||
Network network;
|
||||
WinSocket socket{::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)};
|
||||
if(socket.value==INVALID_SOCKET) socketError();
|
||||
const BOOL broadcast=TRUE;
|
||||
if(setsockopt(socket.value,SOL_SOCKET,SO_BROADCAST,reinterpret_cast<const char*>(&broadcast),sizeof(broadcast)))
|
||||
socketError();
|
||||
bool sent=false;
|
||||
int error=WSAEHOSTUNREACH;
|
||||
for(const auto ip:destinations)
|
||||
{
|
||||
sockaddr_in destination{};
|
||||
destination.sin_family=AF_INET;
|
||||
destination.sin_port=htons(9);
|
||||
destination.sin_addr.s_addr=ip;
|
||||
if(sendto(socket.value,reinterpret_cast<const char*>(packet->data()),static_cast<int>(packet->size()),0,
|
||||
reinterpret_cast<const sockaddr*>(&destination),sizeof(destination))==SOCKET_ERROR)
|
||||
error=WSAGetLastError();
|
||||
else sent=true;
|
||||
}
|
||||
if(!sent) throw std::system_error(error,std::system_category());
|
||||
}
|
||||
|
||||
struct LanService::Impl
|
||||
{
|
||||
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; };
|
||||
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;
|
||||
std::unique_ptr<lan::ClipboardExchange> transfers;
|
||||
std::deque<lan::ClipboardExchange::Delivery> incomingFiles;
|
||||
struct LogDownload {std::string peer, id; uint64_t deadline; Bytes bytes;};
|
||||
std::optional<LogDownload> logDownload;
|
||||
bool shareLogs{};
|
||||
bool enabled{};
|
||||
std::atomic<bool> stopping{false}, refreshFiles{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.";
|
||||
bool inputNeedsHelp{};
|
||||
HWND inputWindow{};std::atomic<bool> inputNotification{false};
|
||||
explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window)
|
||||
{
|
||||
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);
|
||||
shareLogs=j.value("shareLogs",false);
|
||||
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);
|
||||
transfers=std::make_unique<lan::ClipboardExchange>(id,"file-transfer");
|
||||
configureRouter();
|
||||
if(enabled) start();
|
||||
}
|
||||
~Impl() { stop(); }
|
||||
void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted},
|
||||
{"shareInput",shareInput},{"shareLogs",shareLogs},{"inputPeer",inputPeer},{"inputEdge",inputEdge},{"positions",positions}}))); }
|
||||
bool queue(const std::string &peer,lan::InputFrame frame)
|
||||
{
|
||||
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);
|
||||
transfers=std::make_unique<lan::ClipboardExchange>(id,"file-transfer");incomingFiles.clear();logDownload.reset();
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,0,FALSE);
|
||||
}
|
||||
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 receiveTransfers(uint64_t now)
|
||||
{
|
||||
for(auto &item:transfers->deliveries)
|
||||
{
|
||||
if(item.app=="file")
|
||||
{
|
||||
auto end=std::find(item.bytes.begin(),item.bytes.end(),0);
|
||||
if(end!=item.bytes.begin() && end!=item.bytes.end() && end-item.bytes.begin()<=1024 &&
|
||||
item.bytes.end()-end-1<=16*1024*1024)
|
||||
{
|
||||
incomingFiles.push_back(std::move(item));
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),TRUE);
|
||||
}
|
||||
}
|
||||
else if(item.app=="log-request" && item.bytes.size()==33)
|
||||
{
|
||||
std::string request(item.bytes.begin()+1,item.bytes.end());
|
||||
if(!lan::identifier(request)||item.bytes[0]>1)continue;
|
||||
Bytes response{2};
|
||||
if(shareLogs)try
|
||||
{
|
||||
auto log=readFile(path.parent_path()/(item.bytes[0]?L"kswitcher.log.1":L"kswitcher.log"),2*1024*1024);
|
||||
response[0]=0;
|
||||
response.insert(response.end(),log.begin(),log.end());
|
||||
}
|
||||
catch(const std::exception &){response={1};}
|
||||
try{transfers->queue({item.peer},std::move(response),"log-reply-"+request,now);}
|
||||
catch(const std::exception &){}
|
||||
}
|
||||
else if(logDownload && now<logDownload->deadline && logDownload->peer==item.peer &&
|
||||
item.app=="log-reply-"+logDownload->id && item.bytes.size()<=2*1024*1024+1 && logDownload->bytes.empty())
|
||||
logDownload->bytes=std::move(item.bytes);
|
||||
}
|
||||
transfers->deliveries.clear();
|
||||
}
|
||||
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",""));
|
||||
transfers->peerSession(other,j.value("fileSession",""));
|
||||
peer.files=j.value("filesBrowse",false);
|
||||
peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now;
|
||||
if(trusted.contains(other))
|
||||
{
|
||||
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
|
||||
const auto &key=trusted[other].at("key");
|
||||
const auto challenge=heartbeat(id,other,epoch,session);
|
||||
response["proof"]=lan::mac(key,challenge);
|
||||
const auto wakeMac=wakeMacFor(address.sin_addr.s_addr);
|
||||
if(!wakeMac.empty())
|
||||
{
|
||||
response["wakeMac"]=wakeMac;
|
||||
response["wakeProof"]=lan::mac(key,challenge+"|wake|"+wakeMac);
|
||||
}
|
||||
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=="file-transfer" && trusted.contains(other))
|
||||
{
|
||||
size_t retainedBytes=0;
|
||||
for(const auto &item:incomingFiles)retainedBytes+=item.bytes.size();
|
||||
try {transfers->receive(other,trusted.at(other).at("key"),j,now,0,
|
||||
[&](const auto &target,const auto &packet){send(socket,peers.at(target).address,packet);},
|
||||
incomingFiles.size(),retainedBytes);}
|
||||
catch(const std::exception &){return;}
|
||||
receiveTransfers(now);
|
||||
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;
|
||||
auto &entry=trusted.at(other);
|
||||
const auto wakeMac=j.value("wakeMac","");
|
||||
if(lan::wakePacket(wakeMac) && wakeMac!=entry.value("wakeMac","") &&
|
||||
lan::equal(j.value("wakeProof",""),
|
||||
lan::mac(entry.at("key"),heartbeat(other,id,peer.epoch,epoch)+"|wake|"+wakeMac)))
|
||||
{
|
||||
auto previous=entry;
|
||||
entry["wakeMac"]=wakeMac;
|
||||
try {save();}
|
||||
catch(const std::exception &){entry=std::move(previous);}
|
||||
}
|
||||
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="Pair saved automatically. Arrange the monitors, then enable input sharing 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);
|
||||
lan::FilesListener files(id,[&](const std::string &peer)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
return !stopping && trusted.contains(peer)?trusted.at(peer).at("key").get<std::string>():std::string{};
|
||||
},lan::FilesPort,lan::remoteTerminalAllowed,lan::hibernateFromPairedPC,[this]() -> DWORD
|
||||
{
|
||||
if(!lan::remoteUpdateAllowed()) return ERROR_ACCESS_DENIED;
|
||||
if(!inputWindow) return ERROR_INVALID_WINDOW_HANDLE;
|
||||
return PostMessageW(inputWindow,LanUpdateRequestedMessage,0,0)?ERROR_SUCCESS:GetLastError();
|
||||
});
|
||||
hub.datagrams([&](const auto &target,const auto &packet){
|
||||
std::lock_guard lock(mutex);
|
||||
if(shareInput&&trusted.contains(target)&&peers.contains(target))send(socket,peers.at(target).address,packet);
|
||||
});
|
||||
bool filesListening=files.port()!=0;
|
||||
while(!stopping)
|
||||
{
|
||||
files.poll();
|
||||
if(filesListening!=(files.port()!=0))
|
||||
{
|
||||
filesListening=files.port()!=0;
|
||||
nextHello=0;
|
||||
}
|
||||
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);
|
||||
});
|
||||
transfers->poll(trusted,now,[&](const auto &target,const auto &packet){
|
||||
if(peers.contains(target))send(socket,peers.at(target).address,packet);
|
||||
});
|
||||
clipboardActive=clipboard->active()||transfers->active();
|
||||
if(shareInput)for(auto &[peer,entry]:trusted.items())
|
||||
endpoints.push_back({peer,entry.at("key"),peers.contains(peer)?peers.at(peer).address.sin_addr.s_addr:0});
|
||||
if(refreshFiles.exchange(false) || now>=nextHello)
|
||||
{
|
||||
epoch=lan::randomHex(16); // Fresh challenge prevents replayed presence from staying online.
|
||||
auto hello=lan::envelope("hello",id); hello["name"]=name; hello["epoch"]=epoch;hello["clipboardSession"]=clipboard->session();
|
||||
hello["fileSession"]=transfers->session();
|
||||
hello["filesBrowse"]=filesListening;
|
||||
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();inputNeedsHelp=hub.needsHelp();}
|
||||
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);
|
||||
if(j.value("type","")=="input-udp"){
|
||||
bool allowed=false;auto peer=j.value("id","");
|
||||
{std::lock_guard lock(mutex);allowed=shareInput&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
|
||||
if(allowed)hub.receiveDatagram(j,GetTickCount64());
|
||||
}else {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();
|
||||
}
|
||||
std::mutex commandGate;
|
||||
Bytes command(const Bytes &input)
|
||||
{
|
||||
std::lock_guard commandLock(commandGate);
|
||||
auto j=Json::parse(input); auto action=j.value("action","status");
|
||||
if(action=="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::unique_lock lock(mutex);
|
||||
auto now=GetTickCount64();
|
||||
if(action=="filesPeers") refreshFiles=true;
|
||||
if(action=="shareLogs")
|
||||
{
|
||||
bool previous=shareLogs;
|
||||
shareLogs=j.at("enabled");
|
||||
try {save();} catch(...) {shareLogs=previous;throw;}
|
||||
if(!shareLogs)
|
||||
for(const auto &[peer,entry]:trusted.items())transfers->cancel(peer,"log-reply-");
|
||||
}
|
||||
if(action=="sendFile" || action=="requestLog")
|
||||
{
|
||||
auto peer=j.at("peer").get<std::string>();
|
||||
const auto checkPeer = [&] {
|
||||
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
|
||||
now-peers.at(peer).verified>=lan::PeerLifetime)
|
||||
throw std::runtime_error("Select an online paired computer.");
|
||||
if(!transfers->hasSession(peer))
|
||||
throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers.");
|
||||
};
|
||||
checkPeer();
|
||||
if(action=="sendFile")
|
||||
{
|
||||
lock.unlock();
|
||||
auto file=std::filesystem::path(wide(j.at("path").get<std::string>()));
|
||||
auto name=utf8(file.filename().wstring());
|
||||
if(name.empty()||name.size()>1024)throw std::runtime_error("Invalid file name.");
|
||||
Bytes payload(name.begin(),name.end());
|
||||
payload.push_back(0);
|
||||
constexpr size_t fileLimit=16*1024*1024;
|
||||
if(std::filesystem::file_size(file)>fileLimit)throw std::runtime_error("File size limit is 16 MiB.");
|
||||
auto bytes=readFile(file,fileLimit);
|
||||
payload.insert(payload.end(),bytes.begin(),bytes.end());
|
||||
lock.lock();
|
||||
now=GetTickCount64();
|
||||
checkPeer();
|
||||
transfers->queue({peer},std::move(payload),"file",now);
|
||||
return encoded({{"queued",true}});
|
||||
}
|
||||
if(logDownload && now<logDownload->deadline)
|
||||
throw std::runtime_error("A remote log download is already pending.");
|
||||
auto request=lan::randomHex(16);
|
||||
Bytes payload{static_cast<unsigned char>(j.value("previous",false))};
|
||||
payload.insert(payload.end(),request.begin(),request.end());
|
||||
transfers->queue({peer},std::move(payload),"log-request",now);
|
||||
logDownload=LogDownload{peer,request,now+30000,{}};
|
||||
return encoded({{"request",request}});
|
||||
}
|
||||
if(action=="takeLog")
|
||||
{
|
||||
if(!logDownload||logDownload->id!=j.at("request").get<std::string>()||now>=logDownload->deadline)
|
||||
return encoded({{"state","expired"}});
|
||||
if(logDownload->bytes.empty())return encoded({{"state","waiting"}});
|
||||
auto bytes=std::move(logDownload->bytes);
|
||||
logDownload.reset();
|
||||
if(bytes.front()!=0)return encoded({{"state",bytes.front()==2?"denied":"unavailable"}});
|
||||
std::string hex;
|
||||
hex.reserve((bytes.size()-1)*2);
|
||||
for(auto it=bytes.begin()+1;it!=bytes.end();++it)
|
||||
{
|
||||
hex+="0123456789abcdef"[*it>>4];
|
||||
hex+="0123456789abcdef"[*it&15];
|
||||
}
|
||||
return encoded({{"state","ready"},{"logHex",hex}});
|
||||
}
|
||||
if(action=="saveFile"||action=="discardFile")
|
||||
{
|
||||
const auto id=j.at("id").get<std::string>(), peer=j.at("peer").get<std::string>();
|
||||
const auto findFile = [&] {
|
||||
return std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){
|
||||
return file.id==id && file.peer==peer;
|
||||
});
|
||||
};
|
||||
auto found=findFile();
|
||||
if(found==incomingFiles.end())throw std::runtime_error("This file is no longer available.");
|
||||
if(action=="saveFile")
|
||||
{
|
||||
auto start=std::find(found->bytes.begin(),found->bytes.end(),0)+1;
|
||||
const Bytes bytes(start,found->bytes.end());
|
||||
lock.unlock();
|
||||
atomicWrite(wide(j.at("path").get<std::string>()),bytes);
|
||||
lock.lock();
|
||||
found=findFile();
|
||||
}
|
||||
if(found!=incomingFiles.end()) incomingFiles.erase(found);
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
|
||||
}
|
||||
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=="connectionHelp"){
|
||||
auto exe=utf8(executable());std::string quoted;
|
||||
for(char c:exe){quoted+=c;if(c=='\'')quoted+='\'';}
|
||||
auto script="$ksPath = '"+quoted+"'\r\n"
|
||||
"New-NetFirewallRule -DisplayName 'KSwitcher LAN TCP' -Direction Inbound -Action Allow -Program $ksPath -Protocol TCP -LocalPort 45884,45885 -RemoteAddress LocalSubnet -Profile Any\r\n"
|
||||
"New-NetFirewallRule -DisplayName 'KSwitcher LAN UDP' -Direction Inbound -Action Allow -Program $ksPath -Protocol UDP -LocalPort 45883 -RemoteAddress LocalSubnet -Profile Any";
|
||||
return encoded({{"script",script}});
|
||||
}
|
||||
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;}
|
||||
std::erase_if(incomingFiles,[&](const auto &file){return file.peer==peer;});
|
||||
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
|
||||
if(logDownload && logDownload->peer==peer)logDownload.reset();
|
||||
if(pending&&pending->peer==peer)pending.reset();
|
||||
configureRouter();
|
||||
status="Pair removed on this computer.";
|
||||
}
|
||||
Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()},
|
||||
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnected.load()},
|
||||
{"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
|
||||
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
|
||||
result["shareLogs"]=shareLogs;
|
||||
result["files"]=Json::array();
|
||||
result["transferStatus"]=transfers->status;
|
||||
for(const auto &file:incomingFiles)
|
||||
{
|
||||
auto end=std::find(file.bytes.begin(),file.bytes.end(),0);
|
||||
auto filename=utf8(wide(std::string(file.bytes.begin(),end)));
|
||||
result["files"].push_back({{"id",file.id},{"peer",file.peer},{"sender",trusted.at(file.peer).at("name")},
|
||||
{"name",filename},{"size",file.bytes.end()-end-1}});
|
||||
}
|
||||
result["pendingPeer"]=pending&&!pending->confirmed ? pending->peer : "";
|
||||
result["pairSecondsRemaining"]=pending&&!pending->confirmed&&!pending->expired(now)
|
||||
? (lan::PairLifetime-(now-pending->started)+999)/1000 : 0;
|
||||
for(const auto &[peer,p]:peers)
|
||||
{
|
||||
if(action=="filesPeers" && !trusted.contains(peer)) continue;
|
||||
char ip[INET_ADDRSTRLEN]{}; InetNtopA(AF_INET,(void*)&p.address.sin_addr,ip,sizeof(ip));
|
||||
result["peers"].push_back({{"id",peer},{"name",p.name},{"address",ip},{"paired",trusted.contains(peer)},
|
||||
{"verified",p.verified && now-p.verified<lan::PeerLifetime},{"online",true},
|
||||
{"fileTransfer",transfers->hasSession(peer)},{"filesBrowse",p.files}});
|
||||
}
|
||||
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,30 @@
|
||||
#pragma once
|
||||
#include "platform.h"
|
||||
#include <memory>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69;
|
||||
inline constexpr UINT LanFilesChangedMessage=WM_APP+70;
|
||||
inline constexpr UINT LanUpdateRequestedMessage=WM_APP+90;
|
||||
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,324 @@
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include "lan_channel.h"
|
||||
#include "lan_datagram.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,size_t limit)
|
||||
{
|
||||
if(plain.empty()||plain.size()>limit)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,size_t limit)
|
||||
{
|
||||
if(packet.size()<17||packet.size()-16>limit)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...",lastError;
|
||||
int edge;uint16_t port;SOCKET listener=INVALID_SOCKET,socket=INVALID_SOCKET;
|
||||
bool connecting{},authenticated{},helloRead{},managed{};
|
||||
uint64_t changed{},lastRead{},lastPing{},retry{},waitingSince{};
|
||||
bool reverse{};
|
||||
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;waitingSince=0;state=reason;lastError=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(!waitingSince)waitingSince=now;
|
||||
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||(managed&&now-waitingSince>=1500))
|
||||
{
|
||||
reverse=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=reverse?"Trying reverse TCP connection...":"Trying direct TCP connection...";
|
||||
}
|
||||
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;lastError.clear();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->authenticated||!nonblocking(SOCKET(accepted)))return false;
|
||||
// Reverse connection wins a simultaneous connect race. Never replace an
|
||||
// authenticated channel or accept two sockets for the same input stream.
|
||||
if(impl->socket!=INVALID_SOCKET){
|
||||
if(impl->local>impl->peer||!impl->connecting)return false;
|
||||
impl->reset(now,"Accepting reverse TCP connection.");
|
||||
}
|
||||
impl->reverse=impl->local<impl->peer;
|
||||
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->lastError.empty() ? impl->state : impl->lastError+" Retrying automatically.";
|
||||
}
|
||||
void InputChannel::disconnect(){impl->reset(GetTickCount64(),"Input disconnected; local control restored.");}
|
||||
std::string InputChannel::transport()const{return impl->reverse?"reverse TCP":"direct TCP";}
|
||||
struct InputHub::Impl
|
||||
{
|
||||
struct Link { InputEndpoint endpoint;std::unique_ptr<InputChannel> channel;std::unique_ptr<InputDatagram> udp;uint64_t generation{},epoch{},since{},failedSince{};bool udpReady{};std::string lastState; };
|
||||
struct 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;
|
||||
InputHub::SendDatagram sendDatagram;
|
||||
uint64_t currentTime{};
|
||||
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)
|
||||
{
|
||||
currentTime=now;
|
||||
for(auto it=links.begin();it!=links.end();){
|
||||
auto match=std::find_if(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id==it->first&&e.key==it->second.endpoint.key&&e.port==it->second.endpoint.port;});
|
||||
if(match==endpoints.end())it=links.erase(it);else ++it;
|
||||
}
|
||||
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.udp=std::make_unique<InputDatagram>(local,e.id,e.key);link.since=link.failedSince=now;link.epoch=++epoch;links.emplace(e.id,std::move(link));
|
||||
}
|
||||
// Discovery is a hint, not the lifetime of authenticated input sessions.
|
||||
// Keep the last usable address across missed announcements. A new address
|
||||
// is used only once a channel is down, never to tear down working input.
|
||||
for(auto &e:endpoints){if(e.id==local)continue;auto &link=links.at(e.id);
|
||||
if(e.address&&!link.channel->ready()&&e.address!=link.endpoint.address){
|
||||
link.channel->disconnect();link.endpoint.address=e.address;
|
||||
}
|
||||
}
|
||||
bool listenNeeded=!links.empty();
|
||||
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(hello.value("app","")=="KSwitcher-input"&&hello.value("to","")==local&&hello.value("version",0)==2&&link!=links.end()&&!link->second.udp->active()&&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);
|
||||
if(sendDatagram&&!link.channel->ready()&&!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);link.channel->disconnect();frames.clear();}
|
||||
if(link.udp->active()){
|
||||
link.udp->poll(frames,received,now,sendDatagram);
|
||||
if(!link.udp->active()){link.since=now;link.channel->disconnect();received.clear();}
|
||||
}else link.channel->poll(link.endpoint.address,frames,received,now);
|
||||
if(link.udpReady!=link.udp->ready()){link.udpReady=link.udp->ready();link.epoch=++epoch;}
|
||||
bool ready=link.channel->ready()||link.udp->ready();
|
||||
if(ready)link.failedSince=link.since=now;
|
||||
auto state=link.udp->ready()?"Input connected via encrypted UDP.":link.udp->active()?"Trying encrypted UDP over discovery...":link.channel->ready()?"Input connected via "+link.channel->transport()+".":link.channel->status();
|
||||
if(state!=link.lastState){link.lastState=state;log(L"LAN input peer "+wide(id.substr(0,8))+L": "+wide(state));}
|
||||
if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;}
|
||||
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()||l.udp->ready())result[id]=l.epoch;return result;}
|
||||
std::string InputHub::status()const{
|
||||
auto count=ready().size();if(count==impl->links.size()&&count){
|
||||
std::string routes;for(auto &[id,l]:impl->links){if(!routes.empty())routes+=", ";routes+=id.substr(0,8)+": "+(l.udp->ready()?"encrypted UDP":l.channel->transport());}
|
||||
return "Input connected ("+routes+"). Move through a neighboring screen edge.";
|
||||
}
|
||||
if(needsHelp())return "Automatic connection attempts have not succeeded for every PC. Enable input on both PCs. Open Connection help for firewall commands.";
|
||||
if(!impl->error.empty())return impl->error;
|
||||
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready())return l.lastState;
|
||||
return "Waiting for paired computers...";
|
||||
}
|
||||
void InputHub::disconnect(){for(auto &[id,l]:impl->links){l.channel->disconnect();l.udp->reset();l.since=impl->currentTime;}}
|
||||
void InputHub::datagrams(SendDatagram send){impl->sendDatagram=std::move(send);}
|
||||
void InputHub::receiveDatagram(const Json &j,uint64_t now){
|
||||
if(!impl->sendDatagram)return;
|
||||
auto it=impl->links.find(j.value("id",""));if(it==impl->links.end()||it->second.channel->ready())return;
|
||||
auto &link=it->second;bool active=link.udp->active();
|
||||
try{link.udp->receive(j,now,impl->sendDatagram);}catch(const std::exception &){return;}
|
||||
if(!active&&link.udp->active())link.channel->disconnect();
|
||||
}
|
||||
bool InputHub::needsHelp()const{
|
||||
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready()&&impl->currentTime-l.failedSince>=15000)return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
#include "lan_pairing.h"
|
||||
#include <memory>
|
||||
#include <map>
|
||||
#include <functional>
|
||||
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 &,size_t limit=1024);
|
||||
Bytes decryptPayload(const Bytes &,size_t limit=1024);
|
||||
};
|
||||
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();
|
||||
std::string transport()const;
|
||||
};
|
||||
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();
|
||||
using SendDatagram=std::function<void(const std::string &,const Json &)>;
|
||||
void datagrams(SendDatagram);
|
||||
void receiveDatagram(const Json &,uint64_t now);
|
||||
bool needsHelp()const;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
#pragma once
|
||||
#include "lan_channel.h"
|
||||
#include <map>
|
||||
#include <deque>
|
||||
#include <set>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
// Reliable bounded messages over the existing discovery socket.
|
||||
// Every datagram has a fresh directional AES-GCM key; no plaintext transfer
|
||||
// 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{}, sentUpTo{};
|
||||
bool begun{};
|
||||
uint64_t retryAt{}, progress{};
|
||||
void reset(uint64_t now)
|
||||
{
|
||||
ack=sentUpTo=0;
|
||||
begun=false;
|
||||
retryAt=0;
|
||||
progress=now;
|
||||
}
|
||||
};
|
||||
struct Receiving {std::string id,app;Bytes bytes;size_t size{};uint64_t last{};DWORD sequence{};};
|
||||
std::string local, type, domain, 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,domain+local+"|"+peer+"|"+boot+"|"+sessions.at(peer)+"|"+std::to_string(number)+"|"+nonce));
|
||||
auto packet=envelope(type,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,std::string messageType="clipboard")
|
||||
:local(std::move(id)),type(std::move(messageType)),domain("KSwitcher "+type+" v1|")
|
||||
{
|
||||
if(type!="clipboard")status.clear();
|
||||
}
|
||||
const std::string &session()const{return boot;}
|
||||
bool active()const{return !sending.empty();}
|
||||
bool hasSession(const std::string &peer)const{return sessions.contains(peer);}
|
||||
void cancel(const std::string &peer,const std::string &prefix)
|
||||
{
|
||||
auto found=sending.find(peer);
|
||||
if(found==sending.end())return;
|
||||
auto &s=found->second;
|
||||
if(s.queue.empty())return;
|
||||
bool reset=s.queue.front()->app.starts_with(prefix);
|
||||
std::erase_if(s.queue,[&](const auto &item){return item->app.starts_with(prefix);});
|
||||
if(reset)s.reset(GetTickCount64());
|
||||
}
|
||||
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.reset(found->second.progress);
|
||||
if(type!="clipboard"){
|
||||
auto previous=receiving.find(peer);
|
||||
if(previous!=receiving.end()){incomingBytes-=previous->second.size;receiving.erase(previous);}
|
||||
receivedPackets.erase(peer);
|
||||
}
|
||||
}
|
||||
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 transfer 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){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty())s.reset(now);s.queue.push_back(item);}
|
||||
if(!peers.empty())status=type=="clipboard"?"Sending clipboard to "+std::to_string(peers.size())+" paired computers...":"Sending…";
|
||||
}
|
||||
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="Transfer timed out.";it=sending.erase(it);continue;}
|
||||
auto &item=*s.queue.front();
|
||||
const auto limit=std::min(item.bytes.size(),s.ack+Window*Chunk);
|
||||
const bool retry=s.retryAt && now>=s.retryAt;
|
||||
const bool sendBegin=!s.begun && (!s.retryAt || retry);
|
||||
const bool sendChunks=s.begun && (s.sentUpTo<limit || retry);
|
||||
if(sessions.contains(peer) && (sendBegin || sendChunks))
|
||||
{
|
||||
auto key=trusted.at(peer).at("key").template get<std::string>();
|
||||
if(sendBegin)
|
||||
send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}}));
|
||||
else
|
||||
{
|
||||
// ACKs open new slots. Only a timeout retransmits outstanding chunks.
|
||||
if(retry) s.sentUpTo=s.ack;
|
||||
while(s.sentUpTo<limit)
|
||||
{
|
||||
const auto offset=s.sentUpTo;
|
||||
const auto end=std::min(offset+Chunk,item.bytes.size());
|
||||
send(peer,seal(peer,key,{{"op","chunk"},{"item",item.id},{"offset",offset},
|
||||
{"bytes",Json::binary(Bytes(item.bytes.begin()+offset,item.bytes.begin()+end))}}));
|
||||
s.sentUpTo=end;
|
||||
}
|
||||
}
|
||||
if(!s.retryAt || retry) s.retryAt=now+100;
|
||||
}
|
||||
++it;
|
||||
}
|
||||
}
|
||||
template<class Send>void receive(const std::string &peer,const std::string &key,const Json &packet,uint64_t now,DWORD sequence,Send send,
|
||||
size_t retained=0,size_t retainedBytes=0)
|
||||
{
|
||||
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;
|
||||
if(type!="clipboard"&&senderBoot!=sessions.at(peer))return;
|
||||
auto &seen=receivedPackets[peer];
|
||||
if((seen.contains(senderBoot)&&number<=seen.at(senderBoot))||(!seen.contains(senderBoot)&&seen.size()>=1024))return;
|
||||
InputCipher cipher(mac(key,domain+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>();
|
||||
const auto maxAck=s.begun?s.sentUpTo:Window*Chunk;
|
||||
if(item.id!=id||offset>item.bytes.size()||offset<s.ack||offset>maxAck||(offset!=item.bytes.size()&&offset%Chunk))return;
|
||||
if(offset==s.ack&&s.begun)return;
|
||||
s.begun=true;
|
||||
s.ack=offset;
|
||||
s.sentUpTo=std::max(s.sentUpTo,offset);
|
||||
s.progress=now;
|
||||
s.retryAt=offset<s.sentUpTo?now+100:0;
|
||||
if(offset==item.bytes.size()){
|
||||
s.queue.pop_front();
|
||||
s.reset(now);
|
||||
status=type=="clipboard"?"Clipboard delivered.":"Transfer 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+retainedBytes+size>2*Limit||deliveries.size()+retained>=8||
|
||||
(type!="clipboard"&&receiving.size()+retained>=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=type=="clipboard"?"Clipboard received.":"Transfer 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,97 @@
|
||||
#pragma once
|
||||
#include "lan_channel.h"
|
||||
#include <deque>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
// Ordered, bounded input on the discovery socket. Retransmission uses fresh
|
||||
// authenticated packets; event sequence numbers prevent duplicate injection.
|
||||
// Fresh challenge/response nonces bind every reconnect to a new session.
|
||||
class InputDatagram
|
||||
{
|
||||
std::string local,peer,secret,nonce,remote,txKey,rxKey;
|
||||
uint64_t started{},lastRead{},lastSend{},sentNumber{},seenNumber{},nextEvent{1},receivedEvent{},acked{},progress{};
|
||||
bool live{},ackDue{};
|
||||
std::deque<std::pair<uint64_t,InputFrame>> queue;
|
||||
std::vector<InputFrame> incoming;
|
||||
static std::string hex(const Bytes &b){std::string s;for(auto v:b){s+="0123456789abcdef"[v>>4];s+="0123456789abcdef"[v&15];}return s;}
|
||||
static Bytes unhex(const std::string &s){
|
||||
if(s.empty()||s.size()>2080||s.size()%2||s.find_first_not_of("0123456789abcdef")!=s.npos)throw std::runtime_error("Invalid UDP input 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;
|
||||
}
|
||||
std::string proof(const std::string &from,const std::string &to,const std::string &a,const std::string &b)const{
|
||||
return mac(secret,"KSwitcher UDP input v1|"+from+"|"+to+"|"+a+"|"+b);
|
||||
}
|
||||
void keys(){
|
||||
// Handshake proofs are public. Session keys use a separate domain and
|
||||
// must never be the MAC transmitted in a welcome packet.
|
||||
txKey=mac(secret,"KSwitcher UDP input key v1|"+local+"|"+peer+"|"+nonce+"|"+remote);
|
||||
rxKey=mac(secret,"KSwitcher UDP input key v1|"+peer+"|"+local+"|"+remote+"|"+nonce);
|
||||
}
|
||||
public:
|
||||
using Send=InputHub::SendDatagram;
|
||||
explicit InputDatagram(std::string a,std::string b,std::string key):local(std::move(a)),peer(std::move(b)),secret(std::move(key)){}
|
||||
bool active()const{return !nonce.empty();}
|
||||
bool ready()const{return live;}
|
||||
void reset(){nonce.clear();remote.clear();txKey.clear();rxKey.clear();queue.clear();incoming.clear();live=ackDue=false;sentNumber=seenNumber=receivedEvent=acked=lastSend=0;nextEvent=1;}
|
||||
void start(uint64_t now){reset();nonce=randomHex(16);started=lastRead=progress=now;}
|
||||
void receive(const Json &j,uint64_t now,const Send &send)
|
||||
{
|
||||
if(j.value("app","")!="KSwitcher-LAN"||j.value("version",0)!=1||j.value("type","")!="input-udp"||j.value("id","")!=peer||j.value("to","")!=local)return;
|
||||
auto op=j.value("op","");
|
||||
if(op=="hello"){
|
||||
auto other=j.value("nonce","");if(local<peer||!identifier(other)||!equal(j.value("proof",""),proof(peer,local,other,"")))return;
|
||||
if(active()&&remote!=other)return;
|
||||
if(!active()){start(now);remote=other;keys();}
|
||||
auto response=envelope("input-udp",local);response["to"]=peer;response["op"]="welcome";response["nonce"]=nonce;response["echo"]=remote;response["proof"]=proof(local,peer,nonce,remote);send(peer,response);return;
|
||||
}
|
||||
if(op=="welcome"){
|
||||
auto other=j.value("nonce","");
|
||||
if(local>peer||!active()||j.value("echo","")!=nonce||!identifier(other)||!equal(j.value("proof",""),proof(peer,local,other,nonce)))return;
|
||||
if(!remote.empty()&&remote!=other)return;
|
||||
remote=other;keys();ackDue=true;return;
|
||||
}
|
||||
if(op!="data"||rxKey.empty()||j.value("session","")!=nonce||j.value("fromSession","")!=remote)return;
|
||||
auto number=j.value("number",uint64_t{});if(!number||number<=seenNumber)return;
|
||||
InputCipher cipher(mac(rxKey,"packet|"+std::to_string(number)));
|
||||
auto body=Json::from_cbor(cipher.decryptPayload(unhex(j.at("data").get<std::string>())));
|
||||
auto ack=body.at("ack").get<uint64_t>(),first=body.at("first").get<uint64_t>();auto frames=body.at("frames");
|
||||
if(ack>=nextEvent||!frames.is_array()||frames.size()>12||!first)return;
|
||||
std::vector<InputFrame> decoded;
|
||||
for(auto &f:frames){
|
||||
if(!f.is_array()||f.size()!=5)return;
|
||||
auto type=f[0].get<uint32_t>();if(type<uint32_t(InputType::Enter)||type>uint32_t(InputType::Cross))return;
|
||||
decoded.push_back({InputType(type),f[1].get<uint32_t>(),f[2].get<int32_t>(),f[3].get<int32_t>(),f[4].get<int32_t>()});
|
||||
}
|
||||
seenNumber=number;lastRead=now;live=true;
|
||||
if(ack>acked){acked=ack;progress=now;while(!queue.empty()&&queue.front().first<=ack)queue.pop_front();}
|
||||
if(!decoded.empty()){
|
||||
if(first==receivedEvent+1){
|
||||
if(incoming.size()+decoded.size()>512){reset();return;}
|
||||
incoming.insert(incoming.end(),decoded.begin(),decoded.end());receivedEvent+=decoded.size();
|
||||
}
|
||||
ackDue=true;
|
||||
}
|
||||
}
|
||||
void poll(const std::vector<InputFrame> &out,std::vector<InputFrame> &in,uint64_t now,const Send &send)
|
||||
{
|
||||
if(!active())return;
|
||||
if((live&&(now-lastRead>2000||(!queue.empty()&&now-progress>2000)))||(!live&&now-started>3000)){reset();return;}
|
||||
if(live){
|
||||
if(queue.empty()&&!out.empty())progress=now;
|
||||
if(queue.size()+out.size()>512){reset();return;}
|
||||
for(auto &f:out)queue.emplace_back(nextEvent++,f);
|
||||
in.insert(in.end(),incoming.begin(),incoming.end());incoming.clear();
|
||||
}
|
||||
if(remote.empty()){
|
||||
if(!lastSend||now-lastSend>=250){auto j=envelope("input-udp",local);j["to"]=peer;j["op"]="hello";j["nonce"]=nonce;j["proof"]=proof(local,peer,nonce,"");send(peer,j);lastSend=now;}return;
|
||||
}
|
||||
if(!ackDue&&lastSend&&now-lastSend<(queue.empty()?300:50))return;
|
||||
Json frames=Json::array();for(auto &[sequence,f]:queue){frames.push_back(Json::array({uint32_t(f.type),f.token,f.a,f.b,f.c}));if(frames.size()==12)break;}
|
||||
Json body={{"ack",receivedEvent},{"first",queue.empty()?nextEvent:queue.front().first},{"frames",frames}};
|
||||
auto number=++sentNumber;InputCipher cipher(mac(txKey,"packet|"+std::to_string(number)));
|
||||
auto j=envelope("input-udp",local);j["to"]=peer;j["op"]="data";j["number"]=number;j["session"]=remote;j["fromSession"]=nonce;j["data"]=hex(cipher.encryptPayload(Json::to_cbor(body)));
|
||||
send(peer,j);lastSend=now;ackDue=false;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
#include "lan_pairing.h"
|
||||
#include <functional>
|
||||
#include <stop_token>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
inline constexpr uint16_t FilesPort=45885;
|
||||
struct FilesPeer
|
||||
{
|
||||
std::string id, address;
|
||||
std::wstring name;
|
||||
uint16_t port=FilesPort;
|
||||
bool filesBrowse{};
|
||||
};
|
||||
using FileProgress = std::function<bool(uint64_t, uint64_t)>;
|
||||
struct FileRevision { uint64_t size, modified; };
|
||||
inline constexpr size_t FileChunk = 64 * 1024;
|
||||
|
||||
// One connection owns its enumeration, file handles and uncommitted upload.
|
||||
class FilesConnection
|
||||
{
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl;
|
||||
public:
|
||||
explicit FilesConnection(const FilesPeer *peer = nullptr);
|
||||
FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key);
|
||||
~FilesConnection();
|
||||
Json call(const Json &request, const FileProgress &progress = {});
|
||||
};
|
||||
|
||||
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
|
||||
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
|
||||
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr);
|
||||
DWORD runRemoteCommand(FilesConnection &host,const std::filesystem::path &directory,std::wstring_view command,
|
||||
const std::function<void(std::string_view)> &output,std::stop_token stop={});
|
||||
|
||||
class FilesListener
|
||||
{
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl;
|
||||
public:
|
||||
using PairKey = std::function<std::string(const std::string &)>;
|
||||
using TerminalPermission = std::function<bool()>;
|
||||
using HostAction = std::function<DWORD()>;
|
||||
FilesListener(std::string local, PairKey key,uint16_t port=FilesPort,TerminalPermission terminalPermission={},
|
||||
HostAction hibernate={},HostAction update={});
|
||||
uint16_t port() const;
|
||||
~FilesListener();
|
||||
void poll();
|
||||
};
|
||||
|
||||
Json fileRequest(std::string_view action, const std::filesystem::path &path);
|
||||
std::filesystem::path filePath(const Json &path);
|
||||
void checkFileReply(const Json &reply);
|
||||
bool recycleFile(HWND owner, const std::filesystem::path &path);
|
||||
inline constexpr wchar_t remoteTerminalPreference[]=L"AllowRemoteTerminal";
|
||||
bool remoteTerminalAllowed();
|
||||
inline constexpr wchar_t remoteHibernatePreference[]=L"AllowRemoteHibernate";
|
||||
bool remoteHibernateAllowed();
|
||||
DWORD hibernateFromPairedPC();
|
||||
inline constexpr wchar_t remoteUpdatePreference[]=L"AllowRemoteUpdate";
|
||||
bool remoteUpdateAllowed();
|
||||
}
|
||||
@@ -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,22 @@
|
||||
#pragma once
|
||||
|
||||
#include "core.h"
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline Bytes decodeLanLog(const std::string &hex)
|
||||
{
|
||||
auto digit = [](char value) -> unsigned
|
||||
{
|
||||
if (value >= '0' && value <= '9') return value - '0';
|
||||
if (value >= 'a' && value <= 'f') return value - 'a' + 10;
|
||||
throw std::runtime_error("Invalid diagnostic log response.");
|
||||
};
|
||||
if (hex.size() % 2) throw std::runtime_error("Invalid diagnostic log response.");
|
||||
Bytes bytes;
|
||||
bytes.reserve(hex.size() / 2);
|
||||
for (size_t i = 0; i < hex.size(); i += 2)
|
||||
bytes.push_back(static_cast<unsigned char>(digit(hex[i]) * 16 + digit(hex[i + 1])));
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -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,28 @@
|
||||
#pragma once
|
||||
#include <winsock2.h>
|
||||
#include <system_error>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
inline void socketError()
|
||||
{
|
||||
throw std::system_error(WSAGetLastError(),std::system_category());
|
||||
}
|
||||
|
||||
struct WinSocket
|
||||
{
|
||||
SOCKET value=INVALID_SOCKET;
|
||||
~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);}
|
||||
};
|
||||
|
||||
struct Network
|
||||
{
|
||||
Network()
|
||||
{
|
||||
WSADATA data{};
|
||||
if(const auto error=WSAStartup(MAKEWORD(2,2),&data))
|
||||
throw std::system_error(error,std::system_category());
|
||||
}
|
||||
~Network(){WSACleanup();}
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
inline std::optional<std::array<unsigned char,102>> wakePacket(std::string_view mac)
|
||||
{
|
||||
constexpr std::string_view digits="0123456789abcdef";
|
||||
std::array<unsigned char,6> address{};
|
||||
if(mac.size()!=2*address.size()) return {};
|
||||
for(size_t i=0;i<address.size();++i)
|
||||
{
|
||||
const auto high=digits.find(mac[2*i]),low=digits.find(mac[2*i+1]);
|
||||
if(high==digits.npos || low==digits.npos) return {};
|
||||
address[i]=static_cast<unsigned char>(16*high+low);
|
||||
}
|
||||
if((address.front()&1) || std::all_of(address.begin(),address.end(),[](auto byte){return byte==0;}))
|
||||
return {};
|
||||
std::array<unsigned char,102> packet{};
|
||||
std::fill_n(packet.begin(),6,0xff);
|
||||
for(auto next=packet.begin()+6;next!=packet.end();next+=address.size())
|
||||
std::copy(address.begin(),address.end(),next);
|
||||
return packet;
|
||||
}
|
||||
|
||||
void wakeFilesPeer(const std::string &id);
|
||||
}
|
||||
@@ -1,12 +1,63 @@
|
||||
#include "app.h"
|
||||
#include <shellapi.h>
|
||||
#include <shlobj.h>
|
||||
#include "configuration.h"
|
||||
#include "storage.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr std::wstring_view elevatedRestart = L"--elevated-restart=";
|
||||
|
||||
bool shouldElevateOnLaunch()
|
||||
{
|
||||
if (ks::isLocalBuild() || IsUserAnAdmin())
|
||||
return false;
|
||||
try
|
||||
{
|
||||
auto settings = ks::loadSettings(ks::dataDirectory() / L"settings.json", {});
|
||||
if (!settings.autostart || !settings.elevatedAutostart)
|
||||
return false;
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
// The normal startup path handles unreadable settings and reports them.
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
// Let the resident explain the stale path before asking to elevate the repair.
|
||||
return ks::staleAutostartPath(true).empty();
|
||||
}
|
||||
catch (const std::exception &)
|
||||
{
|
||||
// The elevated resident can retry reading the task.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||
{
|
||||
// Inherited by unattended children such as the LAN PowerShell process.
|
||||
SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS);
|
||||
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
int argc{};
|
||||
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
|
||||
std::wstring arg = argc > 1 ? argv[1] : L"";
|
||||
if (argc == 2 && arg.starts_with(L"--history-host=")) {
|
||||
LocalFree(argv);
|
||||
int result = 1;
|
||||
try {
|
||||
auto service = reinterpret_cast<HWND>(uintptr_t(std::stoull(arg.substr(15))));
|
||||
wchar_t name[64]{}; GetClassNameW(service, name, 64);
|
||||
if (std::wstring(name) != L"KSwitcher.Main" || !ks::configurationPeer(service, L"KSwitcher.exe"))
|
||||
throw std::runtime_error("Invalid history service");
|
||||
ks::App app(instance, true, {}, service);
|
||||
result = app.execute();
|
||||
} catch (...) {}
|
||||
CoUninitialize();
|
||||
return result;
|
||||
}
|
||||
if (arg.starts_with(L"--configure-autostart="))
|
||||
{
|
||||
int result = 1;
|
||||
@@ -28,8 +79,28 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||
CoUninitialize();
|
||||
return result;
|
||||
}
|
||||
if (arg.starts_with(elevatedRestart))
|
||||
{
|
||||
bool approved = false;
|
||||
try
|
||||
{
|
||||
approved = argc == 2 && IsUserAnAdmin() && arg.substr(elevatedRestart.size()) == ks::currentUserSid();
|
||||
}
|
||||
catch (const std::exception &) {}
|
||||
if (!approved)
|
||||
{
|
||||
MessageBoxW(nullptr, L"Administrator approval for the same Windows account is required.",
|
||||
L"KSwitcher", MB_OK | MB_ICONERROR);
|
||||
LocalFree(argv);
|
||||
CoUninitialize();
|
||||
return 1;
|
||||
}
|
||||
arg.clear();
|
||||
}
|
||||
HANDLE mutex = CreateMutexW(nullptr, TRUE, L"Local\\KSwitcher.Native.Singleton");
|
||||
bool existing = GetLastError() == ERROR_ALREADY_EXISTS;
|
||||
const DWORD mutexError = GetLastError();
|
||||
// Opening an existing elevated instance's mutex can be denied to a normal process.
|
||||
bool existing = mutexError == ERROR_ALREADY_EXISTS || (!mutex && mutexError == ERROR_ACCESS_DENIED);
|
||||
int cmd = ks::ShowHistory;
|
||||
if (arg == L"--capture")
|
||||
cmd = ks::Screenshot;
|
||||
@@ -45,17 +116,20 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||
cmd = 21;
|
||||
else if (arg == L"--exit")
|
||||
cmd = 99;
|
||||
else if (arg == L"--check-update")
|
||||
cmd = 23;
|
||||
LocalFree(argv);
|
||||
if (existing)
|
||||
{
|
||||
HWND window = FindWindowW(L"KSwitcher.Main", L"KSwitcher");
|
||||
if (window)
|
||||
{
|
||||
if (cmd == 23) { DWORD pid{}; GetWindowThreadProcessId(window, &pid); AllowSetForegroundWindow(pid); }
|
||||
COPYDATASTRUCT data{1, sizeof(cmd), &cmd};
|
||||
DWORD_PTR result{};
|
||||
SendMessageTimeoutW(window, WM_COPYDATA, 0, (LPARAM)&data, SMTO_ABORTIFHUNG, 1000, &result);
|
||||
}
|
||||
CloseHandle(mutex);
|
||||
if (mutex) CloseHandle(mutex);
|
||||
CoUninitialize();
|
||||
return 0;
|
||||
}
|
||||
@@ -68,12 +142,36 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||
int result = 0;
|
||||
try
|
||||
{
|
||||
ks::App app(instance, arg == L"--smoke-test");
|
||||
if (arg.starts_with(L"--update-ready-event="))
|
||||
app.updateStartupEvent = arg.substr(std::wstring(L"--update-ready-event=").size());
|
||||
else if (!arg.empty() && arg != L"--smoke-test")
|
||||
app.startCommand = cmd;
|
||||
result = app.execute();
|
||||
if (argc == 1 && mutex && shouldElevateOnLaunch())
|
||||
{
|
||||
auto file = ks::executable();
|
||||
auto parameters = std::wstring(elevatedRestart) + ks::currentUserSid();
|
||||
// Let the elevated process acquire the singleton before it starts.
|
||||
ReleaseMutex(mutex);
|
||||
CloseHandle(mutex);
|
||||
mutex = nullptr;
|
||||
SHELLEXECUTEINFOW request{sizeof(request)};
|
||||
request.lpVerb = L"runas";
|
||||
request.lpFile = file.c_str();
|
||||
request.lpParameters = parameters.c_str();
|
||||
request.nShow = SW_HIDE;
|
||||
if (!ShellExecuteExW(&request))
|
||||
{
|
||||
if (GetLastError() != ERROR_CANCELLED)
|
||||
throw std::runtime_error("Windows could not restart KSwitcher as administrator.");
|
||||
result = 1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ks::App app(instance, arg == L"--smoke-test");
|
||||
app.isolateHistory = !app.smoke;
|
||||
if (arg.starts_with(L"--update-ready-event="))
|
||||
app.updateStartupEvent = arg.substr(std::wstring(L"--update-ready-event=").size());
|
||||
else if (!arg.empty() && arg != L"--smoke-test")
|
||||
app.startCommand = cmd;
|
||||
result = app.execute();
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
#pragma once
|
||||
|
||||
#include "../vendor/json.hpp"
|
||||
#include "lan_log.h"
|
||||
#include <iostream>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline int runLogMcp(const std::function<Bytes(const Bytes &)> &lan)
|
||||
{
|
||||
using Json = nlohmann::json;
|
||||
auto command = [&](const Json &request)
|
||||
{
|
||||
auto text = request.dump();
|
||||
return Json::parse(lan(Bytes(text.begin(), text.end())));
|
||||
};
|
||||
const Json tools = Json::parse(R"({"tools":[
|
||||
{"name":"list_log_computers","description":"List paired computers that support remote log downloads.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true}},
|
||||
{"name":"read_diagnostic_log","description":"Read KSwitcher diagnostic log lines. Omit peer for the local computer. Use offset to page backward from the newest line.","inputSchema":{"type":"object","properties":{"peer":{"type":"string"},"previous":{"type":"boolean"},"lines":{"type":"integer","minimum":1,"maximum":500,"default":100},"offset":{"type":"integer","minimum":0,"default":0}}},"annotations":{"readOnlyHint":true}}
|
||||
]})");
|
||||
std::string line;
|
||||
while (std::getline(std::cin, line))
|
||||
{
|
||||
Json id, reply;
|
||||
try
|
||||
{
|
||||
auto message = Json::parse(line);
|
||||
if (!message.contains("id")) continue;
|
||||
id = message.at("id");
|
||||
auto method = message.at("method").get<std::string>();
|
||||
if (method == "initialize")
|
||||
{
|
||||
auto version = message.at("params").value("protocolVersion", "");
|
||||
if (version != "2025-03-26" && version != "2025-06-18" && version != "2025-11-25")
|
||||
version = "2025-11-25";
|
||||
reply["result"] = {{"protocolVersion", version}, {"capabilities", {{"tools", Json::object()}}},
|
||||
{"serverInfo", {{"name", "kswitcher-logs"}, {"version", "1.0.0"}}}};
|
||||
}
|
||||
else if (method == "ping") reply["result"] = Json::object();
|
||||
else if (method == "tools/list") reply["result"] = tools;
|
||||
else if (method == "tools/call")
|
||||
{
|
||||
std::string output;
|
||||
bool failed = false;
|
||||
try
|
||||
{
|
||||
auto params = message.at("params");
|
||||
auto arguments = params.value("arguments", Json::object());
|
||||
auto name = params.at("name").get<std::string>();
|
||||
if (name == "list_log_computers")
|
||||
{
|
||||
auto peers = Json::array();
|
||||
for (const auto &peer : command({{"action", "status"}}).at("peers").get<Json::array_t>())
|
||||
if (peer.value("paired", false))
|
||||
peers.push_back({{"id", peer.at("id")}, {"name", peer.at("name")},
|
||||
{"available", peer.value("verified", false) && peer.value("fileTransfer", false)}});
|
||||
output = peers.dump();
|
||||
}
|
||||
else if (name == "read_diagnostic_log")
|
||||
{
|
||||
auto peer = arguments.value("peer", "");
|
||||
bool previous = arguments.value("previous", false);
|
||||
int lines = arguments.value("lines", 100);
|
||||
if (lines < 1 || lines > 500) throw std::runtime_error("lines must be between 1 and 500.");
|
||||
int offset = arguments.value("offset", 0);
|
||||
if (offset < 0) throw std::runtime_error("offset must be nonnegative.");
|
||||
if (peer.empty()) output = utf8(readDiagnosticLog(previous));
|
||||
else
|
||||
{
|
||||
auto request = command({{"action", "requestLog"}, {"peer", peer}, {"previous", previous}}).at("request");
|
||||
for (;;)
|
||||
{
|
||||
auto result = command({{"action", "takeLog"}, {"request", request}});
|
||||
auto state = result.at("state").get<std::string>();
|
||||
if (state == "ready")
|
||||
{
|
||||
auto bytes = decodeLanLog(result.at("logHex"));
|
||||
output.assign(bytes.begin(), bytes.end());
|
||||
break;
|
||||
}
|
||||
if (state == "denied") throw std::runtime_error("Remote log downloads are disabled on that computer.");
|
||||
if (state == "unavailable") throw std::runtime_error("The remote log is unavailable.");
|
||||
if (state != "waiting") throw std::runtime_error("The remote log download timed out.");
|
||||
Sleep(250);
|
||||
}
|
||||
}
|
||||
auto previousLine = [&](size_t end)
|
||||
{
|
||||
if (!end) return size_t{};
|
||||
if (output[end - 1] == '\n') --end;
|
||||
return end ? output.rfind('\n', end - 1) + 1 : size_t{};
|
||||
};
|
||||
size_t end = output.size();
|
||||
while (offset-- > 0 && end) end = previousLine(end);
|
||||
size_t start = end;
|
||||
while (lines-- > 0 && start) start = previousLine(start);
|
||||
output = output.substr(start, end - start);
|
||||
}
|
||||
else throw std::runtime_error("Unknown tool.");
|
||||
}
|
||||
catch (const std::exception &error) { output = error.what(); failed = true; }
|
||||
reply["result"] = {{"content", Json::array({{{"type", "text"}, {"text", output}}})}, {"isError", failed}};
|
||||
}
|
||||
else reply["error"] = {{"code", -32601}, {"message", "Method not found"}};
|
||||
}
|
||||
catch (const std::exception &) { reply["error"] = {{"code", -32600}, {"message", "Invalid request"}}; }
|
||||
reply["jsonrpc"] = "2.0";
|
||||
reply["id"] = id;
|
||||
std::cout << reply.dump(-1, ' ', false, Json::error_handler_t::replace) << std::endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
#pragma once
|
||||
#include "core.h"
|
||||
#include <cstdlib>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr const wchar_t *MouseButtonNames[] = {L"Left", L"Right", L"Middle", L"XButton1", L"XButton2"};
|
||||
inline constexpr const wchar_t *MouseEvents[] = {L"Left", L"Right", L"Middle", L"XButton1", L"XButton2",
|
||||
L"Double left", L"Double right", L"Double middle",
|
||||
L"Wheel up", L"Wheel down", L"Wheel left", L"Wheel right"};
|
||||
inline constexpr int BuiltInMouseEventCount = 8;
|
||||
|
||||
inline int mouseWheelEvent(UINT message, SHORT delta)
|
||||
{
|
||||
if (!delta) return -1;
|
||||
if (message == WM_MOUSEWHEEL) return BuiltInMouseEventCount + (delta < 0);
|
||||
if (message == WM_MOUSEHWHEEL) return BuiltInMouseEventCount + 2 + (delta > 0);
|
||||
return -1;
|
||||
}
|
||||
|
||||
inline int rawMouseSignal(const RAWMOUSE &mouse)
|
||||
{
|
||||
constexpr USHORT downFlags[] = {RI_MOUSE_LEFT_BUTTON_DOWN, RI_MOUSE_RIGHT_BUTTON_DOWN,
|
||||
RI_MOUSE_MIDDLE_BUTTON_DOWN, RI_MOUSE_BUTTON_4_DOWN, RI_MOUSE_BUTTON_5_DOWN};
|
||||
int signal = -1;
|
||||
for (int button = 0; button < static_cast<int>(std::size(downFlags)); ++button)
|
||||
{
|
||||
if (!(mouse.usButtonFlags & downFlags[button])) continue;
|
||||
if (signal >= 0) return -1;
|
||||
signal = button;
|
||||
}
|
||||
const auto wheel = mouse.usButtonFlags & (RI_MOUSE_WHEEL | RI_MOUSE_HWHEEL);
|
||||
if (!wheel) return signal;
|
||||
if (signal >= 0 || wheel == (RI_MOUSE_WHEEL | RI_MOUSE_HWHEEL)) return -1;
|
||||
return mouseWheelEvent(wheel == RI_MOUSE_WHEEL ? WM_MOUSEWHEEL : WM_MOUSEHWHEEL,
|
||||
static_cast<SHORT>(mouse.usButtonData));
|
||||
}
|
||||
|
||||
inline int mouseWheelSteps(int &remainder, SHORT delta)
|
||||
{
|
||||
const int total = remainder + std::abs(static_cast<int>(delta));
|
||||
remainder = total % WHEEL_DELTA;
|
||||
return total / WHEEL_DELTA;
|
||||
}
|
||||
|
||||
inline bool mouseEventEnabled(const Settings &settings, int event)
|
||||
{
|
||||
return event >= 0 && event < static_cast<int>(std::size(MouseEvents)) &&
|
||||
(event < BuiltInMouseEventCount || settings.customMouseEvents.contains(MouseEvents[event]));
|
||||
}
|
||||
|
||||
inline std::wstring mouseEventName(const Settings &settings, int event)
|
||||
{
|
||||
auto name = settings.customMouseEvents.find(MouseEvents[event]);
|
||||
return name == settings.customMouseEvents.end() ? MouseEvents[event] : name->second;
|
||||
}
|
||||
inline constexpr const wchar_t *MouseActions[] = {L"Standard behavior", L"Send key combination", L"Back", L"Forward",
|
||||
L"Volume up", L"Volume down", L"Mute", L"Launch application"};
|
||||
inline constexpr wchar_t GlobalMouseProfile[] = L"*";
|
||||
inline constexpr std::wstring_view NamedMouseProfilePrefix = L"name:";
|
||||
bool validMouseApplication(const std::wstring &app);
|
||||
|
||||
inline bool isNamedMouseProfile(std::wstring_view profile)
|
||||
{
|
||||
return profile.starts_with(NamedMouseProfilePrefix);
|
||||
}
|
||||
|
||||
inline std::wstring mouseProfileName(const std::wstring &profile)
|
||||
{
|
||||
if (profile == GlobalMouseProfile) return L"Global";
|
||||
return isNamedMouseProfile(profile) ? profile.substr(NamedMouseProfilePrefix.size()) : profile;
|
||||
}
|
||||
|
||||
inline bool mouseActionApplies(const MouseAction &action, const std::wstring &app)
|
||||
{
|
||||
return action.applications.empty() || action.applications.contains(app);
|
||||
}
|
||||
inline const std::set<std::wstring> &mouseActionScope(const Settings &settings, const std::wstring &profile,
|
||||
const MouseAction &action)
|
||||
{
|
||||
const auto scope = settings.mouseProfileApplications.find(profile);
|
||||
return scope == settings.mouseProfileApplications.end() ? action.applications : scope->second;
|
||||
}
|
||||
|
||||
inline bool isMouseVolumeAction(const MouseAction *action)
|
||||
{
|
||||
return action && (action->type == MouseActionType::VolumeUp ||
|
||||
action->type == MouseActionType::VolumeDown || action->type == MouseActionType::Mute);
|
||||
}
|
||||
|
||||
inline bool isMouseVolumeStep(MouseActionType action)
|
||||
{
|
||||
return action == MouseActionType::VolumeUp || action == MouseActionType::VolumeDown;
|
||||
}
|
||||
|
||||
inline constexpr UINT MouseVolumeHoldDelay = 350;
|
||||
|
||||
inline UINT mouseVolumeRepeatInterval(ULONGLONG heldFor)
|
||||
{
|
||||
if (heldFor < 1000) return 140;
|
||||
if (heldFor < 2000) return 80;
|
||||
return 40;
|
||||
}
|
||||
|
||||
inline const MouseAction *mouseBinding(const Settings &settings, const std::wstring &app, int event)
|
||||
{
|
||||
auto profile = settings.mouseBindings.find(app);
|
||||
if (profile == settings.mouseBindings.end()) return nullptr;
|
||||
auto action = profile->second.find(MouseEvents[event]);
|
||||
return action == profile->second.end() ? nullptr : &action->second;
|
||||
}
|
||||
|
||||
inline const MouseAction *effectiveMouseAction(const Settings &settings, const std::wstring &app, int event,
|
||||
bool foreground = true, bool *profileScoped = nullptr)
|
||||
{
|
||||
if (profileScoped) *profileScoped = false;
|
||||
if (!mouseEventEnabled(settings, event)) return nullptr;
|
||||
auto *action = mouseBinding(settings, app, event);
|
||||
if (!action)
|
||||
{
|
||||
const MouseAction *unrestricted = nullptr;
|
||||
for (auto profile = settings.mouseBindings.lower_bound(std::wstring(NamedMouseProfilePrefix));
|
||||
profile != settings.mouseBindings.end() && isNamedMouseProfile(profile->first); ++profile)
|
||||
{
|
||||
if (settings.disabledMouseProfiles.contains(profile->first)) continue;
|
||||
const auto binding = profile->second.find(MouseEvents[event]);
|
||||
if (binding == profile->second.end()) continue;
|
||||
const auto &candidate = binding->second;
|
||||
const auto &scope = mouseActionScope(settings, profile->first, candidate);
|
||||
if (foreground && scope.contains(app))
|
||||
{
|
||||
if (profileScoped) *profileScoped = true;
|
||||
return candidate.type == MouseActionType::Standard ? nullptr : &candidate;
|
||||
}
|
||||
if (!unrestricted && scope.empty()) unrestricted = &candidate;
|
||||
}
|
||||
const auto *global = mouseBinding(settings, GlobalMouseProfile, event);
|
||||
if (foreground && global && global->applications.contains(app)) action = global;
|
||||
else if (unrestricted) action = unrestricted;
|
||||
else if (global && global->applications.empty()) action = global;
|
||||
}
|
||||
return action && action->type != MouseActionType::Standard && mouseActionApplies(*action, app) ? action : nullptr;
|
||||
}
|
||||
|
||||
inline bool doubleMouseClick(POINT first, POINT second, ULONGLONG elapsed)
|
||||
{
|
||||
return elapsed <= GetDoubleClickTime() &&
|
||||
std::abs(static_cast<long long>(first.x) - second.x) * 2 <= GetSystemMetrics(SM_CXDOUBLECLK) &&
|
||||
std::abs(static_cast<long long>(first.y) - second.y) * 2 <= GetSystemMetrics(SM_CYDOUBLECLK);
|
||||
}
|
||||
|
||||
inline int mouseButton(UINT message, WORD xbutton)
|
||||
{
|
||||
switch (message)
|
||||
{
|
||||
case WM_LBUTTONDOWN: case WM_LBUTTONUP: return 0;
|
||||
case WM_RBUTTONDOWN: case WM_RBUTTONUP: return 1;
|
||||
case WM_MBUTTONDOWN: case WM_MBUTTONUP: return 2;
|
||||
case WM_XBUTTONDOWN: case WM_XBUTTONUP:
|
||||
if (xbutton == XBUTTON1) return 3;
|
||||
if (xbutton == XBUTTON2) return 4;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
inline bool mouseButtonDown(UINT message)
|
||||
{
|
||||
return message == WM_LBUTTONDOWN || message == WM_RBUTTONDOWN ||
|
||||
message == WM_MBUTTONDOWN || message == WM_XBUTTONDOWN;
|
||||
}
|
||||
}
|
||||