Compare commits

..
Author SHA1 Message Date
agrynco 37f988dea4 Release v0.4.2: bridge legacy clients to manifest-based updates 2026-10-28 22:52:51 +02:00
265 changed files with 1501 additions and 72638 deletions

No files matched your search

-1
View File
@@ -4,6 +4,5 @@
/.vs/
/.idea/
/dist/
/Release/KSwitcher-win-x64.zip
/build-output.txt
*.user
-73
View File
@@ -1,73 +0,0 @@
# 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.
+12 -338
View File
@@ -1,87 +1,15 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.7.4 LANGUAGES C CXX RC)
project(KSwitcher VERSION 0.4.2 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_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.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"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-compare.ico")
include(cmake/FilesTextLibraries.cmake)
include(cmake/FilesArchiveLibraries.cmake)
include(cmake/FilesSshLibrary.cmake)
include(cmake/FilesImageLibraries.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)
add_custom_target(check-files-quick-view
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_quick_view.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>"
DEPENDS KSwitcherFiles
VERBATIM)
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr KSwitcherFilesImage libssh2::libssh2)
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_sources(kscore PRIVATE src/drive_snapshot.cpp src/google_drive.cpp)
foreach(field IN ITEMS ID SECRET)
set(KS_GOOGLE_CLIENT_${field} "$ENV{KSWITCHER_GOOGLE_CLIENT_${field}}")
if(NOT KS_GOOGLE_CLIENT_${field} MATCHES "^[A-Za-z0-9_.-]*$")
message(FATAL_ERROR "Invalid Google OAuth client configuration.")
endif()
endforeach()
configure_file(cmake/google_drive_oauth_config.h.in generated/google_drive_oauth_config.h @ONLY)
target_link_libraries(KSwitcherFiles PRIVATE kscore)
target_include_directories(kscore PUBLIC src PRIVATE vendor "${CMAKE_CURRENT_BINARY_DIR}/generated")
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)
target_include_directories(kscore PUBLIC src PRIVATE vendor)
target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore dwmapi)
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-paused.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-history.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-screenshot.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-help.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-donate.ico")
set_property(SOURCE resources/help.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/help-guide.md"
"${CMAKE_CURRENT_SOURCE_DIR}/README.md"
"${CMAKE_CURRENT_SOURCE_DIR}/FILES-UI.md"
"${CMAKE_CURRENT_SOURCE_DIR}/LAN-PREVIEW.md")
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc resources/help.rc)
target_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_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)
@@ -89,296 +17,42 @@ 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/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
add_executable(KSwitcherIntegration tests/integration.cpp src/app.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
target_link_libraries(KSwitcherIntegration PRIVATE kscore)
# Opt-in interactive fixture: requires an installed Far Manager.
add_executable(KSwitcherFarSnippetTests WIN32 tests/far_snippets.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
target_link_libraries(KSwitcherFarSnippetTests PRIVATE kscore)
if(MSVC)
target_compile_options(KSwitcherFarSnippetTests PRIVATE /utf-8)
set_property(TARGET KSwitcherFarSnippetTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
else()
target_link_options(KSwitcherFarSnippetTests PRIVATE -municode -static -static-libgcc -static-libstdc++)
endif()
add_executable(KSwitcherInputTests tests/input.cpp tests/input_pause.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc resources/help.rc)
add_executable(KSwitcherInputTests tests/input.cpp src/app.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
target_link_libraries(KSwitcherInputTests PRIVATE kscore)
target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES)
add_executable(KSwitcherScreenshotUITests tests/screenshot_ui.cpp resources/app.rc)
add_executable(KSwitcherScreenshotUITests tests/screenshot_ui.cpp src/app.cpp src/configuration.cpp src/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 src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
add_executable(KSwitcherOcrTests tests/ocr.cpp)
target_link_libraries(KSwitcherOcrTests PRIVATE kscore)
add_dependencies(KSwitcherOcrTests KSwitcherScreenshot)
if(MSVC)
set_property(TARGET kscore KSwitcher KSwitcherConfig KSwitcherScreenshot KSwitcherTests KSwitcherScrollTests KSwitcherIntegration KSwitcherInputTests KSwitcherOcrTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
set_property(TARGET kscore KSwitcher KSwitcherConfig KSwitcherTests 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(KSwitcherFilesArchiveTests tests/files_archive.cpp src/files_archive.cpp)
target_include_directories(KSwitcherFilesArchiveTests PRIVATE src)
target_compile_definitions(KSwitcherFilesArchiveTests PRIVATE NOMINMAX)
target_link_libraries(KSwitcherFilesArchiveTests PRIVATE KSwitcherArchive ole32)
if(MSVC)
set_property(TARGET KSwitcherFilesArchiveTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesArchiveTests PRIVATE /utf-8)
elseif(MINGW)
target_link_options(KSwitcherFilesArchiveTests PRIVATE -static)
endif()
add_test(NAME files-archive COMMAND KSwitcherFilesArchiveTests)
add_executable(KSwitcherFilesImageTests tests/files_image.cpp)
target_include_directories(KSwitcherFilesImageTests PRIVATE src)
target_compile_definitions(KSwitcherFilesImageTests PRIVATE NOMINMAX)
target_link_libraries(KSwitcherFilesImageTests PRIVATE KSwitcherFilesImage webp)
if(MSVC)
set_property(TARGET KSwitcherFilesImageTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesImageTests PRIVATE /utf-8)
elseif(MINGW)
target_link_options(KSwitcherFilesImageTests PRIVATE -static)
endif()
add_test(NAME files-image COMMAND KSwitcherFilesImageTests)
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(KSwitcherLanClientsTests tests/lan_clients.cpp)
target_link_libraries(KSwitcherLanClientsTests PRIVATE kscore)
if(NOT MSVC)
target_link_options(KSwitcherLanClientsTests PRIVATE -static)
endif()
add_test(NAME lan-trusted-clients COMMAND KSwitcherLanClientsTests)
set_tests_properties(lan-trusted-clients PROPERTIES TIMEOUT 15)
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)
add_test(NAME files-comparison-splitter
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
add_test(NAME files-smb-password
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_smb_password.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-smb-password PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_test(NAME files-space-analyzer-layout
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-space-analyzer-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 25)
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 KSwitcherFilesImage)
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)
add_test(NAME google-drive-settings-page COMMAND KSwitcherChatProfileTests --google-drive-layout)
set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
target_include_directories(KSwitcherHistoryHostTests PRIVATE vendor)
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_dependencies(KSwitcherInputTests KSwitcherScreenshot)
add_test(NAME clipboard-history-layout COMMAND KSwitcherInputTests --history-layout)
set_tests_properties(clipboard-history-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
add_test(NAME offline-help-window COMMAND KSwitcherInputTests --help-layout)
set_tests_properties(offline-help-window PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
add_test(NAME tray-input-pause COMMAND KSwitcherInputTests --input-pause)
add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests)
add_test(NAME screenshot-editor-layout COMMAND KSwitcherScreenshotUITests --layout-only)
set_tests_properties(screenshot-editor-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --save-only)
add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$<TARGET_FILE:KSwitcher>")
set_tests_properties(native-regressions PROPERTIES WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
install(TARGETS KSwitcher KSwitcherConfig KSwitcherScreenshot KSwitcherFiles RUNTIME DESTINATION .)
install(FILES LICENSE vendor/json-LICENSE.txt resources/files-archive-license.txt resources/files-image-license.txt resources/files-sftp-license.txt DESTINATION .)
install(TARGETS KSwitcher KSwitcherConfig 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)
add_executable(KSwitcherDriveTests tests/drive_snapshot.cpp)
target_include_directories(KSwitcherDriveTests PRIVATE vendor)
target_link_libraries(KSwitcherDriveTests PRIVATE kscore)
if(MSVC)
target_compile_options(KSwitcherDriveTests PRIVATE /utf-8)
set_property(TARGET KSwitcherDriveTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
else()
target_link_options(KSwitcherDriveTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
add_test(NAME google-drive-backup COMMAND KSwitcherDriveTests)
-829
View File
@@ -1,829 +0,0 @@
# Оформлення KSwitcher Files
Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far.
Іконка головного вікна показує дві сині панелі з бірюзовою рамкою та виділеним рядком.
Власні модальні діалоги панелей, редактора й переглядача використовують
`FilesModalDialog`. Escape і клік поза діалогом у клієнтській області Files
виконують Cancel, а фокус повертається до елемента, з якого відкрили діалог.
Кліки на робочому столі та в інших застосунках залишають діалог відкритим.
Заголовок і рамка вікна-власника доступні, а діалог рухається разом із
власником. Діалог центрується відносно власника та звужується разом із ним
до власної мінімальної ширини. Поки діалог відкритий, ширина власника
обмежена цією мінімальною шириною з відступами.
Це діє і для вкладених діалогів. Під час файлової операції Cancel спершу
просить підтвердити переривання.
Спільне повідомлення Files підлаштовується під заголовок і кількість рядків.
Висота діалогу залежить від видимого вмісту. Приховані та порожні секції
не займають місця. Перед завершенням змін перевір коротке повідомлення й
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
Панелі, списки попапів і довгі повідомлення використовують вузьку смугу
прокрутки зі стрілками вгорі й унизу та крапковою доріжкою. Відтінки доріжки
й повзунка залежать від фону, на якому вони малюються. Повзунок світліший
за доріжку й показує положення та розмір видимої частини списку.
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
Warning і початковий фокус на No.
## Скорочення
- **FTP** у меню джерел (Alt+F1 для лівої панелі, Alt+F2 для правої)
відкриває список збережених підключень у вибраній панелі. Shift+F4
додає підключення, F4 редагує виділене, Enter відкриває його.
У формі вкажи назву, сервер, порт (типово 21), ім’я користувача й пароль.
Порожнє ім’я означає анонімний вхід. Паролі зберігаються локально
із захистом Windows DPAPI. Звичайний FTP передає дані без шифрування.
Після підключення панель показує справжній шлях початкового каталогу
сервера. Enter або подвійний клік на `..` відкриває батьківську папку.
У корені рядка `..` немає. Щоб повернутися до списку підключень,
вибери FTP в меню джерел панелі.
Назви файлів і папок передаються в UTF-8. Для старого сервера, який
використовує системну кодову сторінку Windows, увімкни в профілі
**Use Windows encoding for file names** і підключися знову.
Після закриття Files окремо для кожної FTP-панелі зберігаються профіль,
каталог і рядок курсора. При наступному запуску Files відкриває цей каталог
і вибирає попередній рядок, якщо він ще існує. Коли каталог недоступний,
панель показує попередню локальну папку й причину помилки. **Ctrl+R**
повторює підключення. Натискання рядка стану відкриває повну причину
помилки й підтвердження повторної спроби. Вибір іншого джерела скасовує
відновлення.
- F5 копіює поточний або позначені файли й папки між локальною та
підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої
панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі.
Використовуються спільні діалоги Copy, прогресу та конфлікту імен.
Поточний файл записується під тимчасовим ім’ям до завершення передачі.
Для заміни файла FTP-сервер має приймати перейменування поверх нього.
- У підключеній FTP-панелі F3 та Enter відкривають файл у Viewer, а F4
відкриває Editor. Файл завантажується у тимчасову копію у фоні.
F2 в Editor передає зміни назад на FTP. Якщо сервер повідомляє інший
розмір або час зміни файла, запис скасовується, а правки лишаються в редакторі.
- У підключеній FTP-панелі F6 перейменовує один файл або папку в поточному
каталозі. Якщо нове ім’я зайняте, Files показує помилку. F8 запитує
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
- **SFTP** у меню джерел обох панелей відкриває збережені SSH-підключення.
Shift+F4 додає профіль, F4 редагує, Enter підключається. Укажи ім’я
користувача, хост, порт (типово 22) та пароль або повний шлях до ключа.
Поле пароля приймає кодову фразу для ключа. Windows DPAPI захищає
збережений пароль або кодову фразу. Для ключа користувача підходить
незашифрований RSA PEM або ECDSA OpenSSH із файлом .pub поруч.
ECDSA OpenSSH підтримує кодову фразу. Ключ залишається у вказаному файлі.
- У **Test connection** звір SHA‑256-відбиток ключа хоста з адміністратором
сервера та підтвердь довіру. Після цього Files перевіряє вхід. **Save**
зберігає профіль і підтверджений відбиток. Якщо відбиток змінюється,
Files блокує підключення до передачі пароля або підпису.
Для запланованої заміни ключа використовуй **Forget host key**,
а тоді **Test connection** зі звіркою нового відбитка.
- **Jump via** у SFTP-профілі вибирає попередній збережений SSH-профіль
у маршруті. **Direct** підключається напряму. Профіль-посередник може
мати власний **Jump via**. Кожен хост має окремий довірений ключ і
перевіряється до входу. Маршрут підтримує до восьми хостів і перевіряється
на цикли під час збереження. Профіль без доступу до SFTP можна
використовувати для пересилання через SSH.
- На підключеній SFTP-панелі Ctrl+O відкриває інтерактивну SSH-сесію.
Enter після введення команди запускає ту саму сесію з командного рядка.
Після `cd` успішно відкритий каталог відображається в панелі.
Зміна каталогу в панелі також оновлює робочу папку сесії.
Поки команда працює, термінал приймає її інтерактивне введення, зокрема
Ctrl+C. При переході до іншої панелі чи джерела сесія від'єднується.
Для синхронізації потрібні POSIX-оболонка й утиліта `base64` на сервері.
Оболонка та SFTP мають бачити однакові абсолютні шляхи.
- **SFTP server for sudo** у профілі приймає абсолютний шлях до
серверного OpenSSH `sftp-server`. Після відмови в доступі Viewer і
Hex Viewer пропонують один повтор через `sudo` в режимі тільки читання.
F2 в Editor після відмови в доступі до запису показує окремий запит.
Відмова або Esc під час привілейованого запису залишає чернетку в Editor,
якщо заміна файла ще не завершилась. Успішна заміна зберігає POSIX-власника,
групу та біти режиму доступу.
- Серверний адміністратор має окремо дозволити потрібний варіант команди
`sudo -n` для цього облікового запису. Перегляд використовує
`sftp-server -R`, а збереження використовує `sftp-server` без цього
прапорця. Files закриває привілейоване з'єднання після операції, розриву
або тайм-ауту мережевого запиту. Пароль sudo не запитується.
- Для SFTP використовуються ключі хоста ECDSA або RSA з підписом SHA‑2.
F3 і F4 відкривають Viewer та Editor. F2 в Editor перевіряє розмір і час
зміни віддаленого файла перед збереженням. F5 копіює між локальною
та SFTP-панеллю в обидва боки зі спільним прогресом, скасуванням і
підтвердженням конфліктів. Для заміни існуючого файла сервер має
підтримувати атомарне перейменування OpenSSH. Якщо сервер відмовляє
в заміні, Files показує причину й зберігає попередній файл.
- **SMB** у меню джерел обох панелей відкриває збережені підключення.
**New** додає назву й сервер або повний UNC-шлях. **Open** для сервера
показує видимі дискові шари. Відомий прихований шар можна додати як
повний UNC-шлях. Вибір шару або відкриття профілю з UNC-папкою переходить
до цієї папки в панелі, з якої викликали меню.
- Для SMB діють дозволи Windows. **Sign in** використовує вказаний
обліковий запис. Прапорець **Remember in Windows Credential Manager**
типово вимкнений. Коли його ввімкнено, після успішного підключення Windows
зберігає облікові дані для цього профілю. **Remove** видаляє профіль і
його збережені облікові дані після підтвердження.
- Якщо SMB недоступний, повідомлення показує причину й залишає список
підключень відкритим. **Open** повторює спробу. Коли Windows повідомляє
про наявний сеанс до цього сервера з іншим записом, Files пропонує
вибрати той запис або завершити попередній сеанс у Windows.
- **F9 → Commands → Compare files** порівнює два позначені текстові файли
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
FTP- та SFTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
рядків і підсвічуванням вставок, видалень і замін. **Unified** перемикає
на єдину колонку з номерами рядків обох файлів, видаленнями зі знаком −
і вставками зі знаком +. Перемикання зберігає поточний блок.
**Fold unchanged** згортає довгі незмінені ділянки до рядка з лічильником
і залишає до трьох рядків контексту перед і після кожного блока.
У замінених рядках виділяється змінений фрагмент. **Previous** (F7) і
**Next** (F8) переходять між блоками змін в обох поданнях.
Подвійний клік відкриває повний текст пари рядків.
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
Текст файлів і порожня область під ним мають білий фон, рядки
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
У поданні поруч центральний розділювач можна перетягнути мишею. Під час зміни розміру
вікна пропорція колонок зберігається.
Ctrl+колесо змінює масштаб тексту в поточному вікні.
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
на панелі завдань. У **Options → File comparison → Font and colors**
можна окремо налаштувати шрифт, тло, текст і кольори змін.
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
і меню Commands показує поточне призначення.
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
типово пропускаються. Перемикач **Show whitespace changes** показує їх
в обох поданнях і враховує під час згортання.
Вставлені й видалені порожні рядки враховуються завжди.
**Apply to left/right** копіює виділений блок у відповідну сторону.
Порівняння перераховується, а змінену сторону позначає зірочка.
**Undo** або **Ctrl+Z** повертає останню незаписану дію.
**Save left/right** зберігає відповідну сторону, **Ctrl+S** зберігає обидві.
Зовнішня зміна цільового файла зупиняє запис і залишає правки для перегляду.
Закриття зі змінами пропонує Save, Discard або Cancel.
Кнопка розгортання в системному заголовку збільшує вікно порівняння
до робочої області екрана. Повторне натискання відновлює попередній розмір.
Підтримуються UTF-8 і UTF-16 з BOM, до 2 МіБ і 100 000 рядків на файл.
Стилі переносу рядків порівнюються як рівнозначні. Під час запису
зберігаються кодування, BOM і наявні кінці рядків цільового файла.
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP, SFTP і SMB.
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
до закриття меню, навіть коли оновлюється список LAN.
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
документ — у програмі, призначеній для його типу у Windows. EXE запускається
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
панелі LAN, спочатку скопіюй його до локальної папки.
Після успішного відкриття локального файла через Windows його шлях
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
його курсор приховано. При виборі
з історії у командний рядок підставляється команда, яка повторює відкриття.
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
- У головному вікні клавіатурний фокус залишається в командному рядку.
Tab без модифікаторів перемикає активну панель, а клік вибирає рядок.
Ctrl+U міняє видимі панелі місцями разом із їхніми папками, режимами,
курсорами й позначками. Активна панель залишається активною на новому боці.
Page Up і Page Down пересувають курсор у панелі. Стрілки вгору й вниз
керують панеллю, коли список підказок закритий.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Ctrl+← і Ctrl+→ зміщують розділювач видимих панелей на ширину одного символу.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
курсора він мав інше оформлення.
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
текст із буфера обміну в позицію курсора або замінюють виділення.
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
виконує команду одразу. Коли рядок
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
Enter передає порожній рядок у термінал.
У повноекранному терміналі (Ctrl+O) команда редагується в промпті
під виводом. Клік у терміналі повертає курсор у промпт. Стрілки вгору й
вниз без відкритого списку підказок переглядають спільну історію, а після
останньої команди вниз повертає чернетку. Підказки відкриваються біля
курсора. Ctrl+C перериває поточну команду, а за виділеного тексту виводу
копіює виділення. Escape з порожнім промптом також перериває команду.
Локальна команда запускається в папці активної панелі, яку показано
перед командним рядком. Після перемикання панелі або переходу до іншої
папки наступна команда використовує нову папку навіть у вже відкритому
PowerShell. Якщо команда змінює папку (наприклад, через `cd`), панель
переходить до неї, якщо користувач за цей час не змінив її розташування.
Під час запуску термінала область виводу має темне тло, поки WebView2
готує сторінку.
Промпт і текст команди вирівняні по спільній базовій лінії.
- Під час набору локальної команди над полем з’являються підказки 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-панелі.
- Правий клік по локальному файлу чи папці відкриває системне контекстне
меню Windows Shell. Правий клік по вільній області відкриває меню
поточної папки. Клавіша Context Menu або Shift+F10 використовує поточний
рядок. Команда з меню оновлює панель і зберігає папку, курсор та
актуальні позначки. Для LAN, FTP, SFTP, UNC та архівів контекстне меню
показує доступні команди Files.
- **Ctrl+A** або **F9 → Files → Properties** показує властивості поточного
файла чи папки. У локальній панелі можна змінити прапорці **Read-only**,
**Hidden**, **System**, **Archive** та **Not indexed**. **Save** застосовує
лише змінені прапорці й перечитує панель. Помилка Windows з’являється
окремим повідомленням. Прапорці папки застосовуються лише до самої папки.
У LAN, FTP, SFTP, UNC та архіві команда **Properties** також є в
контекстному меню й показує доступні метадані без редагування.
Для SFTP власник відображається як числовий UID, якщо сервер його надає.
- **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+C копіює позначені або поточний локальний
елемент у файловий буфер Windows. Ctrl+V вставляє файли й папки в
поточний локальний каталог через звичайний діалог Copy і показує
конфлікти та прогрес. Клік або навігація у файловій панелі вибирають
файловий контекст. Клік у командному рядку або введення тексту
повертають текстовий контекст Ctrl+C / Ctrl+V.
- **Commands → Copy full path** або **Ctrl+Shift+C** копіює повний шлях
файла чи папки під курсором як текст. У LAN- і FTP-панелях текст включає
адресу віддаленого джерела. Для рядка `..` команда не змінює буфер.
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
курсора командного рядка або замінює виділення. Подвійні лапки додаються
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
відкритої в активній панелі.
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
панелі показує «Reading» з лічильником прочитаних файлів і папок та
підказкою [Esc].
До завершення читання панель зберігає попередній список. Escape зупиняє
сканування активної панелі й відкриває прочитану частину папки. Якщо
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
повторює сканування, щоб отримати повний список. Після переходу
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
панель не перемальовується через цей перехід.
Якщо надійшов новіший запит, результат попереднього
сканування пропускається. Після підтвердження UAC очікування списку
від підвищеного процесу теж відбувається у фоні.
- Якщо Windows відмовляє у правах для F5, F6, F7 або F8 на локальних
дисках, Files пропонує повторити операцію з правами адміністратора.
Після підтвердження UAC допоміжний процес обробляє захищені елементи
поточної операції. Відмова в діалозі або в 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–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10 перемикає List і Tree. Ctrl+F11 перемикає фоновий підрахунок розмірів папок. Brief, Wide, Medium і Full доступні в меню Left/Right та Options → Panel layout.
## Налаштування Files
### Переглядач і редактор
- F3 відкриває поточний локальний файл у вбудованому переглядачі лише
для читання. F4 відкриває спільне вікно в режимі редагування. Alt+F3
відкриває файл у програмі, призначеній Windows для цього типу, а Alt+F4
викликає зареєстровану дію Edit. Ці команди також є в меню Commands.
F10 або × закривають головне вікно Files. Вбудовані Viewer та Editor
відкриваються в окремих немодальних вікнах. Редактор має іконку олівця,
переглядач — іконку ока. Ці іконки видно в заголовку, в Alt+Tab і в окремих
групах на панелі завдань Windows. F6 змінює іконку й групу поточного вікна.
При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
Viewer показує збережену версію, а чернетка зберігається в поточному
вікні з позначкою Draft retained. Повторне F6 повертає правки, сторінку,
виділення й прокрутку.
Для нового файла Viewer показує порожній документ. Закриття вікна
з чернеткою в обох режимах пропонує Save, Discard або Cancel.
- **Shift+F3** або **Commands → View as hex** відкриває файл у Hex Viewer.
**F4** у Viewer перемикає текстовий або форматований перегляд і Hex.
Hex показує 64-бітну адресу, 16 вихідних байтів у рядку й ASCII.
Нульові й недруковані байти видно в hex, а в ASCII їх позначає крапка.
Блоки по 64 КіБ перемикаються через Ctrl+Page Up, Ctrl+Page Down або F5.
Esc повертає до попереднього режиму Viewer або, якщо файл відкрито
напряму в Hex, до файлової панелі.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
порядку. Коли відкрито лише Files, активна панель не змінюється.
- Shift+F4 у локальній панелі відкриває Editor для наявного або нового файла.
Порожнє ім’я підставляє `New_File_<дата>_<час>.txt`. Новий файл з’являється
на диску після збереження. Esc після змін пропонує Save, Discard або Cancel.
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
рядків. Скасування параметрів залишає текст у редакторі.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Клік по чекбоксу
одразу записує позначку у вихідний Markdown. У разі помилки збереження
попередній стан відновлюється. Підписи з'єднань малюються поверх стрілок.
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 працює офлайн і завантажується лише для документів із
діаграмами Mermaid. Якщо WebView2 не завершує запуск, Files один раз
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
позначених папок в інших рядках рахує позначені папки. Без позначок
F3 рахує папку під курсором або відкриває файл. Папки обробляються по черзі,
і результат кожної видно в колонці Size у широкому режимі та в рядку
стану, коли там увімкнено розмір. Це працює і в LAN- та FTP-панелях. Посилання й
junction не обходяться. Недоступний вміст позначається як частковий результат.
Папки, які чекають на підрахунок, мають позначку Queued. Через дві секунди
підрахунку в рядку поточної папки з’являється спінер.
Пересування курсора в списку залишає спінер у рядку папки, яку ще рахують.
Esc скасовує поточний підрахунок і чергу активної панелі, залишаючи
вже обчислені розміри та поточний каталог.
Перехід до іншого каталогу чи джерела панелі скасовує підрахунок.
- Під списком кожної панелі з позначками показано кількість позначених
елементів і їхній сумарний розмір. Файли враховуються одразу, папки — у
міру завершення підрахунку через F3. Позначка ≥ означає, що сума
неповна, а число біля «to measure» показує, скільки позначених папок
ще без розміру.
- 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 діє в межах відкритої сторінки.
- **Ctrl+D** або **Navigate → Add bookmark** у Viewer додає закладку
на рядок локального файла. Номер рахується від початку файла, а назва
необов’язкова. У Markdown номер можна вказати за вихідним текстом.
**Navigate → Bookmarks in this file** і **All bookmarks** відкривають
відповідні списки. **Commands → Viewer bookmarks** у панелях працює,
навіть коли Viewer закрито. Списки зберігаються після перезапуску.
Open переходить до рядка, для Markdown у вихідному тексті. Rename
змінює назву, Remove видаляє закладку. Якщо файл або рядок недоступний,
Files показує повідомлення.
- Початкова сторінка займає близько 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 відновлює весь початковий набір у чернетці.
## Панелі
- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук
файлів у поточній папці та її підпапках. Підтримуються локальні папки,
FTP, SFTP і KSwitcher LAN. Поле приймає повне ім’я або маску без
урахування регістру. `*` відповідає довільній
послідовності символів, `?` — одному символу. Приховані та системні
елементи можна включити прапорцем. У FTP і SFTP це також стосується
імен із крапкою на початку. Пошук не обходить junction та інші посилання
на каталоги, які джерело позначає як посилання. Esc зупиняє обхід.
При скасуванні або втраті з’єднання знайдені файли залишаються в панелі.
Заголовок віддалених результатів показує джерело і початкову папку,
а рядки показують відносний шлях до кожного файла.
Enter або подвійний клік відкриває папку й ставить курсор на файл.
Esc у результатах повертає вихідну папку, курсор і позначки.
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
або поточним файлом. F5 використовує папку іншої панелі як призначення.
У FTP і SFTP F6 перейменовує один результат у його власній папці.
Меню Files і нижній рядок клавіш враховують джерело, виділення та
можливість копіювання в іншу панель. F8 і Shift+Delete використовують звичайні підтвердження.
Успішно перейменовані, переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
з тією самою маскою й видимістю прихованих файлів.
- **Left/Right → Tree view** або Ctrl+F10 перемикає вигляд відповідної
панелі незалежно від Brief і Wide. Enter, подвійний клік чи стрілка біля
папки розкриває або згортає гілку. Стрілки вправо й вліво працюють із
гілкою та її батьківською папкою. Вміст гілки читається у фоні під час
розкриття. Позначки згорнутих гілок залишаються доступними для F5, F6 і F8.
Якщо позначено папку та її вміст, команда обробляє їх одним деревом.
Повернення до List відкриває батьківську папку поточного елемента.
- **Background folder sizes** або Ctrl+F11 вмикає вимірювання видимих папок
у фоні для відповідної панелі. Під час оновлення попереднє число лишається
поруч із символом … . Знак + позначає частковий розмір. Error з’являється,
коли вимірювання недоступне. Якщо попереднє число є, позначка ! відрізняє
його від свіжого результату.
- **Commands → Space Analyzer** показує місткість і вільне місце за даними
Windows перед скануванням. Volume вибирає корінь тому, Folder повертає
поточну локальну папку, Start запускає фоновий аналіз тим самим обходом,
що й підрахунок розмірів F3. Посилання на каталоги всередині області
сканування позначаються як link. Stop залишає часткові результати, а
Rescan повторює аналіз із початку.
- Дерево показує логічний розмір, зайняті байти та частку логічного розміру
від батьківської папки. Знак + позначає частковий підрахунок. Зайняті байти
підсумовуються за файловими записами, включно з окремими іменами для
жорстких посилань. Службові дані файлової системи в цей підсумок не входять.
Відсутні дані про зайняті байти позначаються в рядку стану.
- Treemap показує дочірні елементи вибраної папки прямокутниками,
пропорційними до їхнього логічного розміру. Дрібні елементи доступні в
дереві. Клік по плитці відкриває точний елемент у сусідній панелі. Стрілки
переводять фокус між плитками, Enter відкриває плитку у фокусі.
- Sunburst показує до трьох рівнів вкладеності секторами за логічним
розміром. Клік по сектору та Enter у відповідному рядку списку ведуть
до одного елемента. Обраний рядок підсвічує відповідний сектор.
- Під час аналізу всього NTFS-тому Files використовує індекс MFT за
наявності доступу Windows. Звичайний обхід працює без такого доступу.
Обидва режими перераховують доступні записи каталогів, ураховують
жорсткі посилання за їхніми іменами та позначають недоступні гілки.
- View відкриває вибраний файл у спільному переглядачі Files. Show in
other panel відкриває вибрану папку або ставить курсор на файл у сусідній
панелі. Команди роботи з файлами доступні там. Якщо фільтр приховує
вибраний файл, панель показує його до зміни фільтра або переходу в іншу папку.
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
у відкритих локальних папках. Фокус залишається там, де був, а курсор
лишається на поточному елементі, якщо той ще існує.
- У 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, спільні папки налаштовувати не потрібно.
- Якщо читання LAN-папки переривається через мережеву помилку, Files
зберігає поточний список і до трьох разів повторює читання того самого
ПК, диска й каталогу. Після відновлення курсор залишається на наявному
рядку. Рядок стану показує причину збою й дію **Ctrl+R** для повторної
спроби. Перехід в інший каталог або джерело скасовує попередню спробу.
- 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 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
- **Left/Right → Sort by** та Ctrl+F3, Ctrl+F4, Ctrl+F5 і Ctrl+F6 сортують
відповідну панель за іменем, розширенням, розміром і часом зміни.
Повторний вибір того самого стовпця змінює напрямок. Клік по заголовку
Wide виконує ту саму команду. Стрілка показує поточний напрямок.
Ctrl+F7 перемикає пріоритет папок. За вимкненого пріоритету папки й файли
сортуються разом. Рядок `..` лишається першим. Сортування, напрямок і
пріоритет папок зберігаються окремо для кожної панелі.
- Ctrl+F8 відкриває фільтр імен файлів без урахування регістру. Маска
підтримує `*` і `?` так само, як Find files. Папки залишаються доступними
для навігації. Порожнє поле або `*` вимикає фільтр. Позначки повертаються
для прихованих фільтром елементів, які ще є в поточній папці.
Ctrl+F9 перемикає показ прихованих та системних елементів окремо для
кожної панелі. Типово їх видно. Маска діє до закриття вікна.
- Brief показує імена. Medium додає Size. Wide показує також Ext і
Modified. Full додає Allocated, Links і Owner. Для локальних файлів
Allocated показує зайняте місце, Links — кількість жорстких посилань, а
Owner — власника за даними Windows. Для відсутніх метаданих показується —.
Modified показує місцеву дату. Сортування враховує повний час зміни.
- **Left/Right → Columns** налаштовує видимість стовпців і автоматичну
ширину для поточного режиму. Кожна панель зберігає свій режим і
налаштування Medium, Wide та Full. Автоматична ширина враховує вміст.
У вузькій панелі Name має пріоритет. Межі стовпців збігаються в заголовку
та списку. Стрілки, PgUp, PgDn, Home та End керують рядками в усіх режимах.
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
тексту, Markdown і зображень у сусідній панелі. Перегляд слідує за курсором активної
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
Під час перегляду файлові операції з призначенням у сусідній панелі
пропонують спершу закрити Quick View.
- **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й
вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі
зображення в порядку вихідної панелі на момент відкриття Viewer.
- У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб,
перетягування мишею панорамує збільшене зображення, Fit підганяє його
під область перегляду, а 100% повертає вихідний масштаб. Клавіші 0 і 1
виконують Fit і 100% у сфокусованому перегляді. GIF та анімований WebP
показують перший кадр. Пошкоджені та надто великі файли показують повідомлення.
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
останні відвідані локальні, FTP, SFTP та LAN-папки. Повторний візит підіймає
один запис угору, порядок зберігається після перезапуску. Enter або клік
відкриває шлях у панелі, з якої викликали меню. Віддалені записи містять
шлях і ідентифікатор збереженого FTP- чи SFTP-профілю або спареного ПК. Паролі
зберігаються в захищених налаштуваннях профілів. Delete прибирає вибраний
запис із недавніх.
- Кнопки ← та → переходять назад і вперед в історії відповідної панелі,
зокрема між локальними, FTP, SFTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..`
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі.
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
трикрапка відкриває прихованих предків, а права — приховані папки
попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
а Esc повертає до тих самих панелей і курсора.
- У заголовку FTP- чи SFTP-папки клік по назві профілю відкриває збережені
підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери
та їхні диски. Поле шляху й доповнення працюють у поточному джерелі.
Для FTP абсолютний шлях починається з /.
## Спільні елементи діалогів
- Власні діалоги 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.
- **F9 → Commands → Processes** показує локальні процеси, PID, частку
загальної потужності CPU, робочий набір пам’яті та шлях виконуваного файла.
**Filter** шукає за іменем, шляхом або PID. **Sort** змінює порядок,
**Refresh** робить новий вимір. **Go to file** вибирає виконуваний файл
в активній панелі. **End process** завершує процес лише після підтвердження.
- **F9 → Files → Locking processes** перевіряє поточний локальний елемент або
позначені елементи. Кнопка **Processes…** у повідомленні про заблоковане
перейменування або видалення відкриває той самий список із фільтром за
вихідним шляхом. Для папки перевіряються також її вкладені елементи.
**Go to file** у цьому режимі відкриває виконуваний файл у другій панелі
зі збереженням вихідного файла в першій. Після завершення процесу список
перечитується. Якщо Windows обмежила доступ або перевірка великої папки
завершилася частково, діалог повідомляє про це.
- **F9 → Commands → Git Changes** відкриває зміни Git із кореня або
вкладеної папки локального worktree. Список окремо показує **Staged**,
**Unstaged** та **Untracked**, а сусідня панель відображає diff
вибраного рядка. **Filter** шукає за шляхом. **F3** відкриває поточний
робочий файл у Viewer, **F4** відкриває його в Editor, якщо файл існує.
**Ctrl+R** перечитує Git, **Esc** повертає обидві панелі. Для цього
режиму потрібен Git for Windows. Перегляд залишає Git index без змін.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів 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 повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів.
## Перетягування файлів
- Перетягування з Explorer або іншої локальної панелі відкриває діалог
Drop files із повним шляхом призначення та кнопками Copy, Move і Cancel.
Якщо курсор над папкою, призначенням є ця папка. В інших випадках
призначенням є поточна папка панелі. Cancel або Esc скасовує дію.
- Copy і Move відкривають наявний діалог операції з її параметрами,
перевіркою призначення, розв’язанням конфліктів і прогресом. Віддалені
панелі, результати пошуку й віртуальні елементи Explorer без локального
шляху не підтримують перетягування. Files повідомляє причину в рядку стану.
## Архіви ZIP і 7z
- Enter на локальному архіві відкриває його в поточній панелі. Заголовок панелі починається з Archive і містить ім’я архіву та шлях усередині нього. Enter відкриває папки всередині архіву, а рядок `..`, Alt+Up і Escape піднімають на один рівень. Вихід із кореня повертає курсор на архів.
- F3 відкриває текстовий файл у спільному переглядачі. F5 копіює позначені записи або поточний запис у локальну папку через спільні діалоги Copy, конфлікту та прогресу. F4, F6, F7 і F8 не змінюють вміст архіву.
- Небезпечні шляхи й посилання блокують читання архіву. Для зашифрованих записів та архівів із зашифрованими заголовками Files показує підказку про пароль.
- **Files → Pack files** або **Alt+F5** створює в поточній локальній папці архів із позначених елементів або з поточного елемента. Розширення `.zip` чи `.7z` визначає формат.
- **F5** з локальної панелі в панель архіву та **Ctrl+V** зі списком локальних файлів додають елементи до відкритої папки архіву. Діалог підтвердження попереджає про заміну файлів з однаковими іменами. Скасування або помилка зберігають попередній архів. Режим запису підтримує звичайні ZIP і 7z.
## Діалог 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. Після узгодження нового правила онови відповідний розділ цього документа.
-185
View File
@@ -1,185 +0,0 @@
# 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.
## Trusted LAN clients
Open **Settings → Computers → Manage computers → Trusted clients** and choose **Add client…**. Select the Dirlume executable, confirm, then click **Save** in Settings. Dirlume can list existing LAN pairs, browse their drives, and download regular files using each remote computer’s file-access permissions. Pairing credentials stay in the resident KSwitcher process.
Select an executable, choose **Remove**, then click **Save** to revoke access. Add the executable again after updating it, since KSwitcher checks the approved path and SHA-256 fingerprint.
## Remote files and diagnostic logs
Use **KSwitcher Files → Change drive** or Dirlume with a trusted-client entry
to browse and copy remote files. Starting in v0.7.0, Manage computers
focuses on pairing, shared input and diagnostic logs.
On the computer that owns the logs, enable **Allow paired computers to download
logs** in **Diagnostic logs** (off by default). On the requesting computer,
select the paired PC and choose **Current 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.
In wide windows, the computer list and monitor layout grow side by side.
In narrow windows, they stack above Diagnostic logs. The list identifies
offline pairs, and Connection help appears below the input sharing controls.
3. Match the computer name and instance-ID prefix displayed on the other PC.
Enable discovery and click **Save** on each PC to make peers visible.
Select each other, generate one code, and enter it on both. Click **Pair**, then
**Apply** or **Save** on each PC within two minutes. Use **Apply** to keep the pairing status visible. Spaces, hyphens and uppercase hex are accepted.
4. Pair each physical input source with every destination it must control. For
unrestricted control from any PC, pair every pair of PCs. Drag monitors into
neighboring grid cells and arrange the same physical layout relative to each
local PC. For A → B → C, A sees B at (1,0), C at (2,0); B sees A at (-1,0),
C at (1,0). Enable input sharing and click **Save** on all PCs to apply sharing
and the monitor layout. The input sharing setting covers all pairs.
5. Stop MWB or another mouse/keyboard router on both computers before trying
KSwitcher input sharing, to avoid two tools forwarding the same events.
6. Wait for the authenticated input connection. Move the cursor through the
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.
When input sharing is enabled, the tray icon shows a steady gray dot if all
paired PCs are offline, a pulsing amber dot while a discovered PC is connecting,
a green dot when all online paired PCs are connected, and a red dot if the LAN
worker stops. Hover over the icon to see the connection status and the connected
count when only some paired PCs are connected.
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.
LAN discovery authenticates paired PCs before starting new input connections.
Discovery remains active while all paired PCs are offline and wakes input sharing
when one reappears. An authenticated input connection survives missed discovery
announcements. Once discovery has expired and the channel closes, further input
attempts wait for fresh discovery.
After at least 5 seconds, the lower-ID peer starts encrypted UDP fallback on the
discovery socket (UDP 45883) once its current TCP connection attempt has failed
or reached its 10-second deadline.
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.
+57 -878
View File
File diff suppressed because it is too large. Load diff
+33 -701
View File
@@ -1,703 +1,35 @@
# Latest Windows release
## v0.7.4 — 2026-11-25
- **Settings → Sync → Google Drive** supports automatic synchronization and a dated list of manual backups. Only one automatic provider is active per PC. Restore a selected backup into the Settings draft and review it before pressing **Apply** or **Save**.
- **Help → User guide** opens a searchable offline guide with the current keyboard shortcuts and built-in manuals. The tray also has **Help → About KSwitcher** and a separate coffee icon for **Donate via Monobank**.
- Clipboard history, the screenshot editor and Help have distinct window and taskbar icons. Clipboard history and the screenshot editor use the Settings palette. OCR is a child page under **Clipboard**, and clipboard exclusions can be added using the window picker.
- The editors on **Custom replacements**, **Snippets** and **Mouse** use the available window height. The computer list, monitor layout and action rows on **Manage computers** are aligned.
**Українською.**
- **Settings → Sync → Google Drive** підтримує автосинхронізацію та список ручних резервних копій із датами. На кожному ПК активний лише один автоматичний провайдер. Вибрана копія завантажується в чернетку, яку можна переглянути перед **Apply** або **Save**.
- **Help → User guide** відкриває офлайн-довідку з пошуком, поточними гарячими клавішами та вбудованими посібниками. У треї також є **Help → About KSwitcher** і чашка біля окремого пункту **Donate via Monobank**.
- Історія буфера, редактор скріншотів і довідка мають окремі значки вікон і панелі завдань. Історія та редактор використовують палітру Settings. OCR винесено на дочірню сторінку **Clipboard**, а програми до винятків буфера можна додавати через приціл.
- Редактори **Custom replacements**, **Snippets** і **Mouse** розтягуються за висотою вікна. На **Manage computers** вирівняно список ПК, схему моніторів і ряди дій.
## v0.7.3 — 2026-11-24
- **Apply** commits pending edits across Settings and keeps the current page open. **Save** commits the same edits and closes Settings. **Close** appears when the draft is clean. **Cancel** asks before discarding pending edits.
- Mouse actions, discovery, pairing, monitor positions, input sharing, trusted clients, diagnostic log permissions and the OpenBao connection are part of the Settings draft. For new LAN pairs, enter the same code and choose **Pair**, then **Apply** or **Save**, on both PCs. Use **Sync now** to synchronize with a saved OpenBao connection.
- Settings and the diagnostic log viewer follow the Windows accent and contrast settings.
**Українською.**
- **Apply** зберігає правки всіх розділів Settings і залишає поточну сторінку відкритою. **Save** зберігає ті самі правки й закриває Settings. За відсутності незбережених правок доступна кнопка **Close**. **Cancel** запитує підтвердження перед відкиданням чернетки.
- Дії миші, пошук комп’ютерів, сполучення, розташування моніторів, спільний ввід, довірені клієнти, дозвіл на завантаження журналів і підключення OpenBao входять до чернетки Settings. Для нового сполучення введіть однаковий код і натисніть **Pair**, а тоді **Apply** або **Save** на обох ПК. **Sync now** запускає синхронізацію зі збереженим підключенням OpenBao.
- Settings і переглядач діагностичних журналів враховують акцентний колір і параметри контрастності Windows.
## v0.7.2 — 2026-11-24
Nested entries in the Settings navigation tree have a compact indent that follows Windows display scaling, including when you move Settings between monitors.
**Українською.** Вкладені пункти в дереві налаштувань мають компактний відступ, який враховує масштаб Windows і перераховується при перенесенні вікна між моніторами.
## v0.7.1 — 2026-11-24
OpenBao connection and synchronization actions are now on **Settings → Sync → OpenBao**. Choose **Save and sync** on that page to save the connection and start synchronization. Settings search can find OpenBao fields, and switching sections preserves the connection draft.
**Українською.** Підключення й дії синхронізації OpenBao тепер доступні в **Settings → Sync → OpenBao**. Натисніть **Save and sync** на цій сторінці, щоб зберегти підключення й запустити синхронізацію. Пошук Settings знаходить поля OpenBao, а перехід між розділами зберігає чернетку підключення.
## v0.7.0 — 2026-11-24
- The native Settings window has a resizable navigation tree and a **Search settings** field. Search finds individual settings, highlights matches, and scrolls the selected control into view.
- Settings remembers its window position, size, sidebar width, and last section. Pages adapt to narrower windows. **General → Correction options** groups dictionaries, exceptions, word boundaries, and substitutions.
- **Computers → Manage computers** opens in Settings and groups pairing, input sharing, and diagnostic logs. Use KSwitcher Files or Dirlume for browsing and copying remote files.
**Українською.**
- У нативному вікні Settings з’явилися дерево розділів зі змінною шириною та поле **Search settings**. Пошук знаходить окремі параметри, підсвічує збіги й прокручує до вибраного поля.
- Settings запам’ятовує положення й розмір вікна, ширину дерева та останній розділ. Сторінки підлаштовуються під вузькі вікна. У **General → Correction options** згруповано словники, винятки, межі слів і заміни.
- **Computers → Manage computers** відкривається в Settings і групує спарювання, спільний ввід та діагностичні журнали. Для перегляду й копіювання файлів з іншого ПК використовуйте KSwitcher Files або Dirlume.
## v0.6.132 — 2026-11-23
In **Settings → Snippets**, **Insert macro or marker…** can add cursor and Enter markers, a pause in milliseconds, or a recorded key or key combination. Keys appear as you press them. Release the keys, click **Insert**, and use the main **Save** button to apply snippet edits together with other settings.
Clipboard snapshots track the sequence after Windows prepares delayed formats. A sequence advance caused by the read can no longer abort the text operation. When image backup fails, diagnostics include the helper's error.
**Українською.** У **Settings → Snippets** кнопка **Insert macro or marker…** додає маркери курсора й Enter, паузу в мілісекундах або записану клавішу чи комбінацію. Клавіші видно під час натискання. Відпустіть їх, натисніть **Insert** і збережіть правки головною кнопкою **Save**.
Під час створення копії буфера KSwitcher бере номер послідовності після підготовки відкладених форматів Windows. Зміна номера під час самого читання більше не перериває текстову операцію. Якщо резервне копіювання зображення не вдалося, журнал показує помилку допоміжного процесу.
## v0.6.131 — 2026-11-23
In **Settings → Computers → Manage computers… → Trusted clients**, choose **Add client…** and select Dirlume.exe. Dirlume can then browse drives on computers already paired in KSwitcher and download regular files. Remove the executable to revoke access. After updating Dirlume, add the new executable again.
**Українською.**
У **Settings → Computers → Manage computers… → Trusted clients** натисніть **Add client…** і виберіть Dirlume.exe. У Dirlume можна відкривати диски комп’ютерів, які вже спарені в KSwitcher, і завантажувати файли. Видаліть виконуваний файл зі списку, щоб відкликати доступ. Після оновлення Dirlume додайте новий файл повторно.
## v0.6.130 — 2026-11-22
The tray shows a purple **K** while KSwitcher processes input. Choose **Pause input processing** to see two white pause bars on a gray tile. The purple **K** returns after **Resume input processing** succeeds. If another program still holds a shortcut, the pause bars stay visible.
**Українською.**
Фіолетова **K** у треї означає, що KSwitcher обробляє введення. Після вибору **Pause input processing** з’являються дві білі смуги на сірому тлі. Фіолетова **K** повертається після успішного **Resume input processing**. Якщо інша програма ще утримує гарячу клавішу, значок паузи залишається.
## v0.6.129 — 2026-11-22
Choose **Pause input processing** in the tray to test another keyboard tool. The tooltip shows **Input processing paused** once KSwitcher releases its shortcuts and stops keyboard and mouse actions, snippets, autocorrection, automatic layout switching, LAN input and simulated F15 activity. Clipboard history can still record entries. Choose **Resume input processing** to restore input. If a shortcut is occupied, KSwitcher names it and stays paused until you retry. Restarting KSwitcher also clears the pause.
**Українською.**
Щоб протестувати іншу програму для клавіатури, виберіть **Pause input processing** у треї. Підказка **Input processing paused** з’явиться, коли KSwitcher звільнить гарячі клавіші та призупинить дії клавіатури й миші, сніпети, автокорекцію, автоматичне перемикання розкладки, LAN-керування й імітацію F15. Історія буфера може й далі записувати нові елементи. Виберіть **Resume input processing** для відновлення. Якщо комбінація зайнята, KSwitcher покаже її та залишиться на паузі до повторної спроби. Перезапуск KSwitcher також скидає паузу.
## v0.6.128 — 2026-11-22
In **Settings → Snippets**, drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application, then choose **Save snippets**. Esc cancels a drag. Picking the same application twice adds it only once.
**Українською.**
На вкладці **Settings → Snippets** перетягніть мішень поруч із **Add app** на відкрите вікно, щоб додати його програму. Повторіть для кожної потрібної програми й натисніть **Save snippets**. Esc скасовує перетягування. Повторний вибір програми не створює дубліката.
## v0.6.127 — 2026-11-21
When the snippet popup shows one match, pressing Enter expands it immediately and consumes the key. With several matches, use the arrow keys and then press Enter to confirm.
**Українською.**
Якщо у списку підказок є один збіг, Enter одразу розгортає сніпет. KSwitcher перехоплює це натискання. Якщо збігів кілька, виберіть потрібний стрілками й підтвердьте через Enter.
## v0.6.126 — 2026-11-21 (withdrawn / відкликано)
Snippet macros send the configured keys at the position where they appear. `$skill{pause:500}{enter} Draft text` types the name, waits 500 milliseconds, presses Enter once, then types the remaining text. The focused application handles each key.
**Українською.**
Макроси сніпетів натискають задані клавіші в указаній позиції. `$skill{pause:500}{enter} Текст` вводить назву, чекає 500 мілісекунд, один раз натискає Enter і вводить решту тексту. Кожне натискання обробляє програма у фокусі.
## v0.6.125 — 2026-11-21 (withdrawn / відкликано)
Snippet macros between text segments run before the next segment is inserted. In Codex, `$skill{pause:500}{enter} Draft text` selects the matching skill suggestion and leaves the following text in the composer. Extra Enter markers at the same selection point do not submit the draft. Expansion stops when the suggestion cannot be verified.
**Українською.**
Макроси між частинами сніпета виконуються перед вставленням наступної частини. У Codex `$skill{pause:500}{enter} Текст чернетки` вибирає відповідний скіл із підказок і залишає наступний текст у редакторі. Повторні маркери Enter у тій самій позиції не надсилають чернетку. Якщо підказку не вдалося перевірити, розгортання зупиняється.
## v0.6.124 — 2026-11-21
Snippets can tap keys such as `{{shift}}`, hold combinations such as `{{altr}}+{{ctrl}}`, and wait with `{pause:50}`. After verifying the inserted text and placing `{cursor}`, KSwitcher runs the macros in order. The Snippets tab groups marker buttons and **Macro help…** below the editor, with **Save snippets** at the right.
**Українською.**
Сніпети підтримують окремі клавіші, як-от `{{shift}}`, комбінації на кшталт `{{altr}}+{{ctrl}}` і паузи, як-от `{pause:50}` на 50 мс. KSwitcher виконує макроси за порядком запису після перевірки вставленого тексту й встановлення `{cursor}`. На вкладці **Snippets** кнопки маркерів і **Macro help…** згруповані під редактором, а **Save snippets** розташована праворуч.
## v0.6.123 — 2026-11-20
- The tray shows a steady gray dot when all paired PCs are offline. The amber dot pulses while a discovered PC is connecting. Green means every online paired PC is connected.
- LAN discovery stays active. Once discovery has expired and the last input channel closes, KSwitcher pauses mouse and keyboard connection attempts until a paired PC reappears.
**Українською.**
- Коли всі спаровані ПК офлайн, у треї видно статичну сіру крапку. Жовта крапка пульсує під час підключення до знайденого ПК. Зелена означає, що всі доступні спаровані ПК під’єднані.
- Пошук у LAN продовжує працювати. Коли строк дії підтвердження присутності спливає й останній канал вводу закривається, KSwitcher призупиняє спроби підключення миші та клавіатури до появи спарованого ПК.
## v0.6.122 — 2026-11-20
- LAN mouse and keyboard sharing lets a TCP attempt finish or time out before starting the encrypted UDP fallback.
- The tray icon pulses amber while reconnecting, shows green when all paired PCs are connected, and shows red if the LAN service stops. Hover to see connection status and how many PCs are connected. Diagnostic logs distinguish a declined cursor handoff from returned control.
**Українською.**
- Під час передавання миші та клавіатури KSwitcher чекає завершення TCP-спроби або її тайм-ауту, перш ніж запустити резервне з’єднання через зашифрований UDP.
- Іконка в треї пульсує жовтим під час перепідключення, показує зелену крапку, коли всі спаровані ПК під’єднані, і червону, якщо LAN-модуль зупинився. Наведіть курсор, щоб побачити стан і кількість підключених ПК. У діагностичному журналі видно, коли другий ПК відхилив перехід курсора або повернув керування.
## v0.6.121 — 2026-11-20
KSwitcher Files retries WebView2 startup once when a Markdown preview fails to initialize. If the retry succeeds, the same window displays the formatted document. The Markdown viewer loads the bundled Mermaid library only for documents with Mermaid diagrams.
Snippet expansion now requires a word boundary before the trigger, even after a pause. The same rule applies across keyboard layouts and in Far Manager.
**Українською.**
Якщо перегляд Markdown не запускається, KSwitcher Files один раз повторює запуск WebView2. Після успішної спроби форматований документ з’являється в тому самому вікні. Бібліотека Mermaid завантажується лише для документів із діаграмами Mermaid.
KSwitcher розгортає сніпети, коли тригер відокремлено від попереднього слова. Перевірка діє після паузи, у різних розкладках і у Far Manager.
## v0.6.120 — 2026-11-20
Layout conversion starts faster when the Windows clipboard contains an image. KSwitcher keeps the image and accompanying formats in memory for the duration of the operation. It restores them after conversion if the clipboard still belongs to the operation. A newer copy takes precedence.
**Українською.**
Перетворення розкладки починається швидше, коли в буфері обміну Windows є зображення. KSwitcher тримає зображення й супровідні формати в пам’яті до завершення операції. Копія відновлюється, якщо буфер усе ще належить операції. Новіше копіювання має пріоритет.
## v0.6.119 — 2026-11-18
KSwitcher Files runs local commands in the folder shown at the command prompt. After switching panes or opening a different folder, commands such as `git clone` and relative path suggestions use that folder in the same PowerShell session.
**Українською.**
KSwitcher Files запускає локальні команди в папці, показаній перед командним рядком. Після перемикання панелі або переходу до іншої папки команди на кшталт `git clone` і підказки відносних шляхів використовують цю папку в тій самій сесії PowerShell.
## v0.6.118 — 2026-11-18
- **Shift+F11** opens a side-by-side comparison of two selected text files from local, LAN or FTP panes. The comparison has its own taskbar button, a movable divider, a native toolbar, **F7/F8** change navigation, and **Ctrl+wheel** text zoom. The shortcut, font and colors are configurable in **Options → File comparison**.
- The footer of each file pane shows the number and combined size of marked items, including folders measured by **F3**. **Ctrl+Left/Right** resize the file panes.
- When Windows denies access during a supported local **F5–F8** operation, Files offers to retry with administrator rights through UAC.
- Markdown task checkboxes save their state to the source file. Mermaid flowchart labels appear above the connecting lines.
**Українською.**
- **Shift+F11** відкриває двостороннє порівняння двох вибраних текстових файлів із локальних, LAN- або FTP-панелей. Вікно має власну кнопку на панелі завдань, рухомий розділювач і системний тулбар. **F7/F8** переходять між змінами, **Ctrl+колесо** змінює масштаб тексту. Комбінація, шрифт і кольори налаштовуються в **Options → File comparison**.
- Унизу кожної панелі видно кількість і сумарний розмір позначених елементів, зокрема папок, виміряних через **F3**. **Ctrl+←/→** змінюють ширину панелей.
- Якщо Windows відмовляє в доступі під час підтримуваної локальної операції **F5–F8**, Files пропонує повторити її з правами адміністратора через UAC.
- Чекбокси Markdown зберігають стан у вихідному файлі. Підписи з’єднань у блок-схемах Mermaid відображаються поверх ліній.
## v0.6.117 — 2026-11-18
- KSwitcher Files supports saved FTP connections in both panes. Browse UTF-8 file names, open or edit remote files with **F3/F4**, save with **F2**, copy between a local and FTP pane with **F5**, rename with **F6**, and permanently delete with **F8**.
- **F3** measures folders on local, LAN and FTP panes. On `..` it queues every folder in the current list. Waiting folders show **Queued** and the active folder shows a spinner after two seconds. **Esc** cancels the active pane’s calculation and queue.
- The source menu separates local drives, FTP and KSwitcher LAN. **1** opens FTP and the remaining displayed digits select LAN actions. Wide pane **Size** dividers align, and **Ctrl+F** on `..` inserts the open folder’s path.
**Українською.**
- KSwitcher Files підтримує збережені FTP-підключення в обох панелях. Назви файлів читаються в UTF-8. **F3/F4** відкривають перегляд і редактор, **F2** зберігає зміни, **F5** копіює між локальною та FTP-панелями, **F6** перейменовує, **F8** видаляє без кошика.
- **F3** рахує розмір локальних, LAN- і FTP-папок. На `..` до черги додаються всі папки списку. Папки в черзі мають позначку **Queued**, а біля поточної через дві секунди з’являється спінер. **Esc** скасовує підрахунок і чергу активної панелі.
- Меню джерел розділяє локальні диски, FTP і KSwitcher LAN. **1** відкриває FTP, решта показаних цифр вибирають LAN-дії. Розділювачі колонки **Size** вирівняні, а **Ctrl+F** на `..` вставляє шлях відкритої папки.
## v0.6.116 — 2026-11-17
- Files displays a live count while reading a folder. **Esc** stops the scan and shows the entries already read. **Ctrl+R** reads the folder again. Mouse selection works beyond the first 65,536 rows.
- Files shows the path of files opened through Windows in the terminal and command history. Choosing a history entry still inserts the command that reopens the file. The embedded terminal hides its inactive cursor.
**Українською.**
- Files показує лічильник під час читання папки. **Esc** зупиняє читання й показує вже прочитані записи. **Ctrl+R** перечитує папку. Вибір мишею працює після перших 65 536 рядків.
- Files показує шлях до файла, відкритого через Windows, у терміналі й історії команд. Вибір запису історії підставляє команду для повторного відкриття. Вбудований термінал приховує курсор, коли він неактивний.
## v0.6.115 — 2026-11-17
- **Shift+F4** opens or creates a file in the active local panel. Leave the name blank for a generated `New_File_…txt` name. After editing a draft, **Esc → Save** opens options for the file name, encoding, BOM, and line endings.
- Typing updates the editor status line without repainting the menu or flashing the editor window.
- When **Enter** opens a local file through Windows, Files displays `start 'path'` in the terminal and saves it in command history.
**Українською.**
- **Shift+F4** відкриває або створює файл в активній локальній панелі. Якщо залишити ім’я порожнім, Files підставить `New_File_…txt`. Після редагування чернетки **Esc → Save** відкриває параметри імені, кодування, BOM і кінців рядків.
- Під час набору редактор оновлює рядок стану без перемальовування меню й миготіння вікна.
- Коли **Enter** відкриває локальний файл через Windows, Files показує `start 'шлях'` у терміналі й додає команду до історії.
## v0.6.114 — 2026-11-17
In KSwitcher Files, clicking a row in the inactive pane highlights that row immediately. The previous cursor row in that pane no longer flashes with the active highlight. If it had a custom unfocused cursor color, it returns directly to its normal style.
**Українською.**
У KSwitcher Files клік по рядку неактивної панелі одразу підсвічує вибраний рядок. Попередній рядок курсора цієї панелі більше не блимає активним підсвічуванням. Якщо він мав окремий колір неактивного курсора, рядок одразу повертається до звичайного оформлення.
## v0.6.113 — 2026-11-17
- KSwitcher Files keeps the terminal output area dark while WebView2 initializes. This fixes the white flash during startup.
- The terminal copy regression test checks for a new clipboard write and verifies its contents without first taking clipboard ownership.
**Українською.**
- Під час запуску термінала область виводу KSwitcher Files залишається темною, поки WebView2 готує сторінку. Це усуває білий спалах під час відкриття термінала.
- Тест копіювання з термінала перевіряє новий запис і його вміст без попереднього захоплення буфера обміну.
## v0.6.112 — 2026-11-17
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.
**Українською.**
У KSwitcher Files **Ctrl+Shift+Tab** обходить вікна Files, редактора й переглядача у зворотному порядку. **Ctrl+Tab** обходить їх у прямому порядку. Обидві комбінації працюють циклічно, зокрема в перегляді Markdown.
## v0.6.111 — 2026-11-17
- 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.
**Українською.**
- 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. For v0.3.x–v0.4.1, install the [v0.4.2 bridge](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2) manually first. Close KSwitcher and its editors, extract the bridge ZIP into the installation folder while keeping personal data, dictionaries, and tools, then start v0.4.2 and choose **Update**. v0.2.3 and earlier require manual installation.
For a manual upgrade, save your work and exit KSwitcher, Settings, Files, screenshot editors and bundled StayHere. Verify **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**, then extract the entire ZIP into the installation folder. Keep personal data, customized dictionaries and tools.
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).
## v0.4.1 — 2026-10-28
- 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.
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.
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.
Build and package:
```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.
+1 -1
View File
@@ -1 +1 @@
0209951cbe8c5a202dba12a807895ce7146dc6640f96704f6a4aa9afaa4fd3af KSwitcher-win-x64.zip
7f0ee55eb5b56a6227431c1951ac2751208d3d0c7c34e4d1d616e180c37b1d9f KSwitcher-win-x64.zip
-166
View File
@@ -1,166 +0,0 @@
{
"version": "0.7.4",
"schema": 1,
"files": [
{
"size": 3082752,
"sha256": "31a41c6ecc3387fc9f2b3f228ed64fa916d723654c02dc19bbbb558f94def4b8",
"path": "KSwitcher.exe"
},
{
"size": 2832384,
"sha256": "b993c050a96215aa63be97e9f05764ead13fcaf4b68fbb99f3d2f9a7d49a629a",
"path": "KSwitcher.Config.exe"
},
{
"size": 3187712,
"sha256": "eff5921b9067e0f4805c83d3cea10ddaa32b0b4e29f408b71b1004f78754afb9",
"path": "KSwitcher.Screenshot.exe"
},
{
"size": 4409344,
"sha256": "569d016d1eff9519cd33aa848723cea0365cbebe9333ed390245d098c4074d8e",
"path": "KSwitcher.Files.exe"
},
{
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"path": "WebView2Loader.dll"
},
{
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"path": "terminal/addon-fit-LICENSE.txt"
},
{
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"path": "terminal/addon-fit.js"
},
{
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"path": "terminal/index.html"
},
{
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"path": "terminal/markdown-it-LICENSE.txt"
},
{
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"path": "terminal/markdown-it.js"
},
{
"size": 3599,
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
"path": "terminal/markdown.html"
},
{
"size": 17575,
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
"path": "terminal/markdown.js"
},
{
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"path": "terminal/mermaid-LICENSE.txt"
},
{
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"path": "terminal/mermaid.js"
},
{
"size": 5065,
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"path": "terminal/terminal.js"
},
{
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"path": "terminal/xterm-LICENSE.txt"
},
{
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"path": "terminal/xterm.css"
},
{
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"path": "terminal/xterm.js"
},
{
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"path": "LICENSE"
},
{
"size": 1096,
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"path": "json-LICENSE.txt"
},
{
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"path": "files-text-license.txt"
},
{
"size": 105515,
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01",
"path": "README.md"
},
{
"size": 12804,
"sha256": "f5bfc48e44af14dd6c45f56f689b4034ef1f7bdaca02f9d15ebc32af387366cf",
"path": "LAN-PREVIEW.md"
},
{
"size": 732485,
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"path": "dictionaries/en.txt"
},
{
"size": 20566,
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
},
{
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"path": "dictionaries/README.md"
},
{
"size": 1109134,
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"path": "dictionaries/ru.txt"
},
{
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"path": "dictionaries/sources.json"
},
{
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"path": "dictionaries/uk.txt"
},
{
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"path": "tools/README.txt"
},
{
"size": 133120,
"sha256": "ba891b6cc5d35d26520fa9ad34e136124e90ed10e0cff2f25dedadd0b48fb88e",
"path": "tools/StayHere.exe"
},
{
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"path": "tools/StayHere-README.md"
}
]
}
+11 -146
View File
@@ -1,4 +1,4 @@
param([switch]$Test, [switch]$Integration, [switch]$Ocr, [switch]$Stage, [switch]$Far)
param([switch]$Test, [switch]$Integration, [switch]$Ocr, [switch]$Stage)
$ErrorActionPreference = 'Stop'
$root = $PSScriptRoot
$compiler = Join-Path $root '.tools\w64devkit\bin\g++.exe'
@@ -10,24 +10,11 @@ $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 = @('-lws2_32','-lbcrypt','-liphlpapi','-lwinhttp','-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore','-ldwmapi')
$utilityDirectory = Join-Path (Split-Path $executablePath) 'tools'
New-Item -ItemType Directory -Force $utilityDirectory,build/release/tools | Out-Null
$stayHere = Join-Path $utilityDirectory 'StayHere.exe'
& $compiler @common -Werror -mwindows -municode -static -s utilities/StayHere/main.cpp -luser32 -lshell32 -lgdi32 -lwtsapi32 -o $stayHere
if ($LASTEXITCODE) { throw 'StayHere build failed' }
Copy-Item -LiteralPath $stayHere -Destination build/release/tools/StayHere.exe -Force
$filesBuild = Join-Path $outDir 'files-cmake'
& cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel
if ($LASTEXITCODE) { throw 'CMake configuration failed' }
$common += "-I$(Join-Path $filesBuild 'generated')"
$driveObjects = @('build/drive_snapshot.o','build/google_drive.o')
foreach ($name in @('lan_files','lan_channel','lan_input','lan','lan_pairing','core','platform','autostart','autocorrect','storage','sync','drive_snapshot','google_drive','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) {
$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')) {
& $compiler @common -c "src/$name.cpp" -o "build/$name.o"
if ($LASTEXITCODE) { throw "Compilation failed: $name" }
}
@@ -37,162 +24,40 @@ try {
if ($LASTEXITCODE) { throw 'Configurator UI compilation failed' }
& windres --codepage=65001 resources/app.rc -O coff -o build/app-res.o
if ($LASTEXITCODE) { throw 'Resource compilation failed' }
& windres --codepage=65001 resources/help.rc -O coff -o build/help-res.o
if ($LASTEXITCODE) { throw 'Help resource compilation failed' }
& windres --codepage=65001 -DKS_SCREENSHOT_RESOURCES resources/app.rc -O coff -o build/screenshot-res.o
if ($LASTEXITCODE) { throw 'Screenshot resource compilation failed' }
New-Item -ItemType Directory -Force build/release | Out-Null
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o build/help-res.o @libs -o $executablePath
& $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
if ($LASTEXITCODE) { throw 'Link failed' }
Copy-Item -LiteralPath $executablePath -Destination build/release/KSwitcher.exe -Force
$configPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Config.exe'
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o @driveObjects 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/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
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'
& 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) {
& 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' }
& cmake --build $filesBuild --target KSwitcherFilesArchiveTests
if ($LASTEXITCODE) { throw 'Files archive test build failed' }
& (Join-Path $filesBuild 'KSwitcherFilesArchiveTests.exe')
if ($LASTEXITCODE) { throw 'Files archive tests failed' }
& cmake --build $filesBuild --target KSwitcherFilesImageTests
if ($LASTEXITCODE) { throw 'Files image test build failed' }
& (Join-Path $filesBuild 'KSwitcherFilesImageTests.exe')
if ($LASTEXITCODE) { throw 'Files image tests failed' }
& $compiler @common -Werror tests/settings_merge.cpp build/sync.o @driveObjects build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
if ($LASTEXITCODE) { throw 'Settings merge test build failed' }
& .\build\KSwitcherSettingsMergeTests.exe
if ($LASTEXITCODE) { throw 'Settings merge tests failed' }
& $compiler @common -Werror tests/drive_snapshot.cpp build/sync.o @driveObjects build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherDriveTests.exe
if ($LASTEXITCODE) { throw 'Google Drive snapshot test build failed' }
& .\build\KSwitcherDriveTests.exe
if ($LASTEXITCODE) { throw 'Google Drive snapshot tests failed' }
& $compiler @common -Werror tests/lan_clipboard.cpp build/lan_channel.o build/lan_pairing.o build/core.o build/platform.o @libs -static -s -o build/KSwitcherLanClipboardTests.exe
if ($LASTEXITCODE) { throw 'LAN clipboard test build failed' }
& .\build\KSwitcherLanClipboardTests.exe
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 @driveObjects build/ocr.o @libs -static -s -o build/KSwitcherSyncTests.exe
if ($LASTEXITCODE) { throw 'Sync test build failed' }
& .\build\KSwitcherSyncTests.exe
if ($LASTEXITCODE) { throw 'Sync tests failed' }
& $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 @driveObjects build/ocr.o build/richtext.o build/update.o @libs -static -s -o build/KSwitcherTests.exe
& $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
if ($LASTEXITCODE) { throw 'Test build failed' }
& .\build\KSwitcherTests.exe
if ($LASTEXITCODE) { throw 'Tests failed' }
& $compiler @common tests/input.cpp tests/input_pause.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o build/help-res.o @libs -static -s -o build/KSwitcherInputTests.exe
& $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
if ($LASTEXITCODE) { throw 'Input test build failed' }
& .\build\KSwitcherInputTests.exe
if ($LASTEXITCODE) { throw 'Input tests failed' }
& .\build\KSwitcherInputTests.exe --help-layout
if ($LASTEXITCODE) { throw 'Offline help test failed' }
& .\build\KSwitcherInputTests.exe --input-pause
if ($LASTEXITCODE) { throw 'Tray pause/resume test failed' }
& $compiler @common tests/chat_profiles.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe
if ($LASTEXITCODE) { throw 'Chat profile test build failed' }
& .\build\KSwitcherChatProfileTests.exe
if ($LASTEXITCODE) { throw 'Chat profile tests failed' }
& .\build\KSwitcherChatProfileTests.exe --google-drive-layout
if ($LASTEXITCODE) { throw 'Google Drive Settings test failed' }
& $compiler @common tests/screenshot_ui.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/ocr.o build/screenshot-res.o @libs -static -s -o build/KSwitcherScreenshotUITests.exe
& $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
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 @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -mwindows -municode -static -s -o build/KSwitcherFarSnippetTests.exe
if ($LASTEXITCODE) { throw 'Far snippet test build failed' }
$fixture = Start-Process -FilePath (Join-Path $outDir 'KSwitcherFarSnippetTests.exe') -WindowStyle Hidden -Wait -PassThru
Get-Content -LiteralPath (Join-Path $outDir 'far-snippets.log')
if ($fixture.ExitCode) { throw 'Far snippet tests failed' }
}
if ($Integration) {
$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 @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherIntegration.exe
& $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
if ($LASTEXITCODE) { throw 'Integration test build failed' }
& .\build\KSwitcherIntegration.exe
if ($LASTEXITCODE) { throw 'Integration tests failed' }
}
if ($Ocr) {
$ocrTest = Join-Path (Split-Path $executablePath) 'KSwitcherOcrTests.exe'
& $compiler @common tests/ocr.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o $ocrTest
& $compiler @common tests/ocr.cpp build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherOcrTests.exe
if ($LASTEXITCODE) { throw 'OCR test build failed' }
& $ocrTest
& .\build\KSwitcherOcrTests.exe
if ($LASTEXITCODE) { throw 'OCR tests failed' }
}
foreach ($folder in @('build/dictionaries','build/release/dictionaries','build/staged/dictionaries')) {
-22
View File
@@ -1,22 +0,0 @@
# Apply the exec-channel variant of SFTP initialization to the pinned library.
file(REAL_PATH ".." source_parent)
set(patch_file "${CMAKE_CURRENT_BINARY_DIR}/.kswitcher-sftp-command.patch")
configure_file("${PATCH}" "${patch_file}" @ONLY NEWLINE_STYLE LF)
set(patch_git "${CMAKE_COMMAND}" -E env "GIT_CEILING_DIRECTORIES=${source_parent}" "${GIT}")
execute_process(COMMAND ${patch_git} apply --unidiff-zero --check "${patch_file}"
RESULT_VARIABLE can_apply ERROR_QUIET)
if(can_apply EQUAL 0)
execute_process(COMMAND ${patch_git} apply --unidiff-zero "${patch_file}" COMMAND_ERROR_IS_FATAL ANY)
else()
execute_process(COMMAND ${patch_git} apply --unidiff-zero --reverse --check "${patch_file}"
RESULT_VARIABLE already_applied)
if(NOT already_applied EQUAL 0)
message(FATAL_ERROR "Could not apply the SFTP command patch")
endif()
endif()
file(REMOVE "${patch_file}")
file(STRINGS "include/libssh2_sftp.h" exec_api REGEX "^libssh2_sftp_init_command")
if(NOT exec_api)
message(FATAL_ERROR "The SFTP command API is missing after applying the patch")
endif()
-103
View File
@@ -1,103 +0,0 @@
include(ExternalProject)
# Keep these dependencies private to Files. Build codecs before configuring
# libarchive so its feature checks link the exact libraries that Files ships.
set(archive_deps "${CMAKE_CURRENT_BINARY_DIR}/files-archive")
if(CMAKE_CONFIGURATION_TYPES)
set(archive_configs ${CMAKE_CONFIGURATION_TYPES})
elseif(CMAKE_BUILD_TYPE)
set(archive_configs ${CMAKE_BUILD_TYPE})
else()
set(archive_configs Release)
endif()
add_library(KSwitcherArchive INTERFACE)
target_compile_definitions(KSwitcherArchive INTERFACE LIBARCHIVE_STATIC)
function(build_files_archive config)
set(archive_config "${archive_deps}/${config}")
if(config STREQUAL "Debug")
set(debug_suffix d)
set(runtime_suffix Debug)
endif()
set(archive_lib "${archive_config}/lib")
set(archive_include "${archive_config}/include")
set(archive_cmake_args
"-DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER}"
"-DCMAKE_BUILD_TYPE:STRING=${config}"
"-DCMAKE_TRY_COMPILE_CONFIGURATION:STRING=${config}"
"-DCMAKE_INSTALL_PREFIX:PATH=${archive_config}"
"-DCMAKE_INSTALL_LIBDIR:STRING=lib"
"-DCMAKE_INSTALL_INCLUDEDIR:STRING=include"
"-DCMAKE_MSVC_RUNTIME_LIBRARY:STRING=MultiThreaded${runtime_suffix}"
"-DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW"
"-DBUILD_SHARED_LIBS:BOOL=OFF")
if(MSVC)
set(zlib_name libzs)
else()
set(zlib_name zs)
endif()
set(archive_zlib "${archive_lib}/${CMAKE_STATIC_LIBRARY_PREFIX}${zlib_name}${debug_suffix}${CMAKE_STATIC_LIBRARY_SUFFIX}")
set(archive_lzma "${archive_lib}/${CMAKE_STATIC_LIBRARY_PREFIX}lzma${CMAKE_STATIC_LIBRARY_SUFFIX}")
set(archive_archive "${archive_lib}/${CMAKE_STATIC_LIBRARY_PREFIX}archive${CMAKE_STATIC_LIBRARY_SUFFIX}")
function(files_archive_dependency name url checksum library)
ExternalProject_Add(${name}_${config}
PREFIX "${archive_config}/${name}"
BINARY_DIR "${archive_config}/build/${name}"
STAMP_DIR "${archive_config}/stamp/${name}"
CMAKE_GENERATOR_PLATFORM "${CMAKE_GENERATOR_PLATFORM}"
CMAKE_GENERATOR_TOOLSET "${CMAKE_GENERATOR_TOOLSET}"
URL "${url}"
URL_HASH "SHA256=${checksum}"
DOWNLOAD_EXTRACT_TIMESTAMP FALSE
CMAKE_ARGS ${archive_cmake_args} ${ARGN}
BUILD_COMMAND "${CMAKE_COMMAND}" --build <BINARY_DIR> --config "${config}"
INSTALL_COMMAND "${CMAKE_COMMAND}" --install <BINARY_DIR> --config "${config}"
BUILD_BYPRODUCTS "${library}"
EXCLUDE_FROM_ALL TRUE
LOG_CONFIGURE TRUE
LOG_BUILD TRUE
LOG_INSTALL TRUE
LOG_OUTPUT_ON_FAILURE TRUE)
endfunction()
files_archive_dependency(files_zlib
https://github.com/madler/zlib/releases/download/v1.4/zlib-1.4.tar.gz
02dd159783677a749c04adbdd02b55b8a2bcc7e054f51b76b549199a916ad584
"${archive_zlib}"
-DZLIB_BUILD_SHARED=OFF -DZLIB_BUILD_TESTING=OFF)
files_archive_dependency(files_xz
https://github.com/tukaani-project/xz/releases/download/v5.8.4/xz-5.8.4.tar.gz
0014c7886930454fe8bd4228665b51af55eeae560ea135c9c4cd33f55b2591d9
"${archive_lzma}"
-DBUILD_TESTING=OFF -DXZ_NLS=OFF -DXZ_TOOL_XZ=OFF -DXZ_TOOL_XZDEC=OFF
-DXZ_TOOL_LZMADEC=OFF -DXZ_TOOL_LZMAINFO=OFF -DXZ_TOOL_SCRIPTS=OFF)
files_archive_dependency(files_libarchive
https://github.com/libarchive/libarchive/releases/download/v3.8.11/libarchive-3.8.11.tar.gz
900fe9fc7237c2b04f090f3c3648de8fe597525771f5035016537ce2d667d12b
"${archive_archive}"
"-DZLIB_INCLUDE_DIR:PATH=${archive_include}" "-DZLIB_LIBRARY:FILEPATH=${archive_zlib}"
"-DLIBLZMA_INCLUDE_DIR:PATH=${archive_include}" "-DLIBLZMA_LIBRARY:FILEPATH=${archive_lzma}"
-DENABLE_TAR=OFF -DENABLE_CPIO=OFF -DENABLE_CAT=OFF -DENABLE_UNZIP=OFF
-DENABLE_TEST=OFF -DENABLE_WERROR=OFF -DENABLE_OPENSSL=OFF -DENABLE_MD=OFF
-DMSVC_USE_STATIC_CRT=ON
-DENABLE_LIBB2=OFF -DENABLE_LZ4=OFF -DENABLE_ZSTD=OFF -DENABLE_BZip2=OFF
-DENABLE_LIBXML2=OFF -DENABLE_EXPAT=OFF -DENABLE_WIN32_XMLLITE=OFF
-DENABLE_PCREPOSIX=OFF -DENABLE_PCRE2POSIX=OFF -DENABLE_ICONV=OFF)
add_dependencies(files_libarchive_${config} files_zlib_${config} files_xz_${config})
add_dependencies(KSwitcherArchive files_libarchive_${config})
if(CMAKE_CONFIGURATION_TYPES)
set(config_matches "$<CONFIG:${config}>")
else()
set(config_matches 1)
endif()
target_include_directories(KSwitcherArchive INTERFACE "$<${config_matches}:${archive_include}>")
target_link_libraries(KSwitcherArchive INTERFACE
"$<${config_matches}:${archive_archive};${archive_zlib};${archive_lzma}>")
endfunction()
foreach(config IN LISTS archive_configs)
build_files_archive("${config}")
endforeach()
target_link_libraries(KSwitcherArchive INTERFACE bcrypt)
target_link_libraries(KSwitcherFiles PRIVATE KSwitcherArchive)
-25
View File
@@ -1,25 +0,0 @@
include(FetchContent)
FetchContent_Declare(files_webp
URL https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-1.6.0.tar.gz
URL_HASH SHA256=e4ab7009bf0629fd11982d4c2aa83964cf244cffba7347ecd39019a9e38c4564
DOWNLOAD_EXTRACT_TIMESTAMP FALSE
SOURCE_SUBDIR kswitcher-download-only)
FetchContent_MakeAvailable(files_webp)
function(build_files_webp)
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
foreach(component IN ITEMS ANIM_UTILS CWEBP DWEBP GIF2WEBP IMG2WEBP VWEBP WEBPINFO LIBWEBPMUX WEBPMUX EXTRAS)
set(WEBP_BUILD_${component} OFF)
endforeach()
add_subdirectory("${files_webp_SOURCE_DIR}" "${files_webp_BINARY_DIR}" EXCLUDE_FROM_ALL)
endfunction()
build_files_webp()
add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_view.cpp)
target_compile_definitions(KSwitcherFilesImage PRIVATE NOMINMAX UNICODE _UNICODE _WIN32_WINNT=0x0A00)
target_link_libraries(KSwitcherFilesImage PRIVATE webpdemux windowscodecs msimg32 ole32)
if(MSVC)
set_property(TARGET KSwitcherFilesImage PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesImage PRIVATE /utf-8)
endif()
-26
View File
@@ -1,26 +0,0 @@
include(FetchContent)
find_package(Git REQUIRED)
set(kswitcher_ssh_patch "${CMAKE_CURRENT_LIST_DIR}/libssh2-sftp-command.patch")
file(SHA256 "${kswitcher_ssh_patch}" kswitcher_ssh_patch_hash)
# This revision includes the published SFTP security fixes after the 1.11.1 release.
FetchContent_Declare(kswitcher_libssh2
URL https://codeload.github.com/libssh2/libssh2/tar.gz/dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4
URL_HASH SHA256=67d20d434055faef76439c6829ab253c892fcdd68d9a9c86cf5824bd8366e6eb
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
PATCH_COMMAND "${CMAKE_COMMAND}" "-DGIT=${GIT_EXECUTABLE}"
"-DPATCH=${kswitcher_ssh_patch}" "-DPATCH_HASH=${kswitcher_ssh_patch_hash}"
-P "${CMAKE_CURRENT_LIST_DIR}/ApplyFilesSshPatch.cmake")
function(kswitcher_add_ssh_library)
set(BUILD_STATIC_LIBS ON)
set(BUILD_SHARED_LIBS OFF)
set(BUILD_EXAMPLES OFF)
set(BUILD_TESTING OFF)
set(LIBSSH2_DISABLE_INSTALL ON)
set(LIBSSH2_BUILD_DOCS OFF)
set(CRYPTO_BACKEND WinCNG)
set(ENABLE_ECDSA_WINCNG ON)
FetchContent_MakeAvailable(kswitcher_libssh2)
endfunction()
kswitcher_add_ssh_library()
-26
View File
@@ -1,26 +0,0 @@
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()
-3
View File
@@ -1,3 +0,0 @@
#pragma once
#define KS_GOOGLE_CLIENT_ID "@KS_GOOGLE_CLIENT_ID@"
#define KS_GOOGLE_CLIENT_SECRET "@KS_GOOGLE_CLIENT_SECRET@"
-35
View File
@@ -1,35 +0,0 @@
diff --git a/include/libssh2_sftp.h b/include/libssh2_sftp.h
--- a/include/libssh2_sftp.h
+++ b/include/libssh2_sftp.h
@@ -226,0 +227,2 @@
+LIBSSH2_API LIBSSH2_SFTP *
+libssh2_sftp_init_command(LIBSSH2_SESSION *session, const char *command);
diff --git a/src/sftp.c b/src/sftp.c
--- a/src/sftp.c
+++ b/src/sftp.c
@@ -758 +758,2 @@
-static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session)
+static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session,
+ const char *command)
@@ -811,3 +812,5 @@
- "subsystem",
- sizeof("subsystem") - 1,
- "sftp", sizeof("sftp") - 1);
+ command ? "exec" : "subsystem",
+ command ? 4 : 9,
+ command ? command : "sftp",
+ command ?
+ strlen(command) : 4);
@@ -1011 +1014,2 @@
-LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
+LIBSSH2_SFTP *libssh2_sftp_init_command(LIBSSH2_SESSION *session,
+ const char *command)
@@ -1024 +1028 @@
- BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session));
+ BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session, command));
@@ -1025,0 +1030,5 @@
+}
+
+LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
+{
+ return libssh2_sftp_init_command(session, NULL);
+2 -12
View File
@@ -17,19 +17,9 @@ 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.
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.
File format: UTF-8 word, TAB, positive original frequency 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.
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.
Personal words may use rank 1. Keep entries lowercase, unique and sorted, with a Tab separator.
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.
+3 -7
View File
@@ -9,13 +9,9 @@
"uk": {
"source": "https://raw.githubusercontent.com/hermitdave/FrequencyWords/525f9b560de45753a5ea01069454e72e9aa541c6/content/2016/uk/uk_50k.txt",
"sourceSha256": "9548b79a608d33f39c5546037a69117d679730b1fda08dd0ce67c043dbf3335a",
"words": 42551,
"bytes": 898248,
"sha256": "caeb097749d4afc84b68ad96b3d7dfb6a6569561cd32ccce0bee94a13b43ba86",
"supplementalWords": {
"\u0440\u0435\u043b\u0456\u0437": 50001,
"\u043f\u043e\u0442\u043e\u0447\u043d\u0456": 50001
}
"words": 42549,
"bytes": 898210,
"sha256": "b4104898dcccbc1331ec01e9cd690e30285fe58481460e47438e973964d09802"
},
"ru": {
"source": "https://raw.githubusercontent.com/hermitdave/FrequencyWords/525f9b560de45753a5ea01069454e72e9aa541c6/content/2016/ru/ru_50k.txt",
-2
View File
@@ -27337,7 +27337,6 @@
поторопись 9062
поторопитесь 20656
поторопиться 15390
поточні 50001
потрапив 4168
потрапила 7383
потрапили 6631
@@ -31208,7 +31207,6 @@
релігію 26138
релігія 22202
релігії 23427
реліз 50001
рембо 28603
ремень 23872
ремені 28385
+6 -36
View File
@@ -5,50 +5,20 @@ $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 'resources\files-archive-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-image-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-sftp-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'LAN-PREVIEW.md') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'dictionaries') -Destination $destination -Recurse -Force
New-Item -ItemType Directory -Force (Join-Path $destination 'tools') | Out-Null
Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') -Destination (Join-Path $destination 'tools\README.txt') -Force
Copy-Item -LiteralPath (Join-Path $root 'build\release\tools\StayHere.exe') -Destination (Join-Path $destination 'tools\StayHere.exe') -Force
Copy-Item -LiteralPath (Join-Path $root 'utilities\StayHere\README.md') -Destination (Join-Path $destination 'tools\StayHere-README.md') -Force
# Enumerate the distributable files explicitly; do not include a user's data directory.
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','files-archive-license.txt','files-image-license.txt','files-sftp-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
$files = @('KSwitcher.exe','KSwitcher.Config.exe','LICENSE','json-LICENSE.txt','README.md','dictionaries') | ForEach-Object { Join-Path $destination $_ }
$archive = Join-Path $root 'dist\KSwitcher-win-x64.zip'
# 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
Compress-Archive -LiteralPath $files -DestinationPath $archive -Force
Get-FileHash -LiteralPath $archive -Algorithm SHA256
if ($PublishRelease) {
$release = Join-Path $root 'Release'
New-Item -ItemType Directory -Force $release | Out-Null
$hash = $archiveHash.Hash.ToLowerInvariant()
$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 KSwitcher-win-x64.zip" | Set-Content -LiteralPath (Join-Path $release 'SHA256SUMS.txt') -Encoding ascii
}
+3 -14
View File
@@ -2,20 +2,12 @@
#include <windows.h>
#include "resource.h"
IDI_KSWITCHER ICON "kswitcher.ico"
IDI_KSWITCHER_PAUSED ICON "kswitcher-paused.ico"
IDI_KSWITCHER_HISTORY ICON "kswitcher-history.ico"
IDI_KSWITCHER_SCREENSHOT ICON "kswitcher-screenshot.ico"
IDI_KSWITCHER_HELP ICON "kswitcher-help.ico"
IDI_KSWITCHER_DONATE ICON "kswitcher-donate.ico"
#ifdef KS_SCREENSHOT_RESOURCES
IDI_SCREENSHOT_QUESTION ICON "icons/question.ico"
IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
#endif
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,7,4,0
PRODUCTVERSION 0,7,4,0
FILEVERSION 0,4,2,0
PRODUCTVERSION 0,4,2,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -25,7 +17,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.7.4"
VALUE "FileVersion", "0.4.2"
END
END
BLOCK "VarFileInfo"
@@ -33,7 +25,6 @@ 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"
@@ -82,5 +73,3 @@ 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
-110
View File
@@ -1,110 +0,0 @@
libarchive 3.8.11
https://www.libarchive.org/
The libarchive distribution as a whole is Copyright by Tim Kientzle
and is subject to the copyright notice reproduced at the bottom of
this file.
Each individual file in this distribution should have a clear
copyright/licensing statement at the beginning of the file. If any do
not, please let me know and I will rectify it. The following is
intended to summarize the copyright status of the individual files;
the actual statements in the files are controlling.
* Except as listed below, all C sources (including .c and .h files)
and documentation files are subject to the copyright notice reproduced
at the bottom of this file.
* The following source files are also subject in whole or in part to
a 3-clause UC Regents copyright; please read the individual source
files for details:
libarchive/archive_read_support_filter_compress.c
libarchive/archive_write_add_filter_compress.c
libarchive/mtree.5
* The following source files are in the public domain:
libarchive/archive_parse_date.c
* The following source files are triple-licensed with the ability to choose
from CC0 1.0 Universal, OpenSSL or Apache 2.0 licenses:
libarchive/archive_blake2.h
libarchive/archive_blake2_impl.h
libarchive/archive_blake2s_ref.c
libarchive/archive_blake2sp_ref.c
* The build files---including Makefiles, configure scripts,
and auxiliary scripts used as part of the compile process---have
widely varying licensing terms. Please check individual files before
distributing them to see if those restrictions apply to you.
I intend for all new source code to use the license below and hope over
time to replace code with other licenses with new implementations that
do use the license below. The varying licensing of the build scripts
seems to be an unavoidable mess.
Copyright (c) 2003-2018 <author(s)>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer
in this position and unchanged.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zlib 1.4
https://zlib.net/
Copyright notice:
(C) 1995-2026 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
[email protected] [email protected]
liblzma from XZ Utils 5.8.4
https://tukaani.org/xz/
Copyright (C) The XZ Utils authors and contributors
Permission to use, copy, modify, and/or distribute this
software for any purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 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.
-56
View File
@@ -1,56 +0,0 @@
libwebp 1.6.0
https://developers.google.com/speed/webp
Copyright (c) 2010, Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Google nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Additional IP Rights Grant (Patents)
------------------------------------
"These implementations" means the copyrightable works that implement the WebM
codecs distributed by Google as part of the WebM Project.
Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable (except as stated in this section) patent license to
make, have made, use, offer to sell, sell, import, transfer, and otherwise
run, modify and propagate the contents of these implementations of WebM, where
such license applies only to those patent claims, both currently owned by
Google and acquired in the future, licensable by Google that are necessarily
infringed by these implementations of WebM. This grant does not include claims
that would be infringed only as a consequence of further modification of these
implementations. If you or your agent or exclusive licensee institute or order
or agree to the institution of patent litigation or any other patent
enforcement activity against any entity (including a cross-claim or
counterclaim in a lawsuit) alleging that any of these implementations of WebM
or any code incorporated within any of these implementations of WebM
constitute direct or contributory patent infringement, or inducement of
patent infringement, then any patent rights granted to you under this License
for these implementations of WebM shall terminate as of the date such
litigation is filed.
-40
View File
@@ -1,40 +0,0 @@
libssh2
https://libssh2.org/
Upstream revision dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4
/* Copyright (C) 2004-2007 Sara Golemon <[email protected]>
* Copyright (C) 2005,2006 Mikhail Gusarov <[email protected]>
* Copyright (C) 2006-2007 The Written Word, Inc.
* Copyright (C) 2007 Eli Fant <[email protected]>
* Copyright (C) 2009-2023 Daniel Stenberg
* Copyright (C) 2008, 2009 Simon Josefsson
* Copyright (C) 2000 Markus Friedl
* Copyright (C) 2015 Microsoft Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
-20
View File
@@ -1,20 +0,0 @@
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.
-621
View File
@@ -1,621 +0,0 @@
#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"
IDI_FILES_COMPARE ICON "kswitcher-files-compare.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
611 DIALOGEX 0, 0, 332, 96
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "&Open/create file:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
CONTROL "", 467, "Static", NOT WS_VISIBLE, 14, 72, 1, 1
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 76, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 76, 60, 16
END
612 DIALOGEX 0, 0, 332, 184
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "Save file &as:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
AUTOCHECKBOX "Add signature (&BOM)", 464, 14, 66, 304, 12
CONTROL "", 468, "Static", NOT WS_VISIBLE, 14, 86, 1, 1
LTEXT "Change line breaks to:", 469, 14, 87, 304, 12
AUTORADIOBUTTON "Do &not change", 470, 14, 100, 304, 12, WS_GROUP | WS_TABSTOP
AUTORADIOBUTTON "&Windows (CR LF)", 471, 14, 112, 304, 12
AUTORADIOBUTTON "&Unix (LF)", 472, 14, 124, 304, 12
AUTORADIOBUTTON "&Mac (CR)", 473, 14, 136, 304, 12
CONTROL "", 467, "Static", NOT WS_VISIBLE | WS_GROUP, 14, 155, 1, 1
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 157, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 157, 60, 16
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 "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 129, 38, 51, 15
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
END
613 DIALOGEX 0, 0, 255, 100
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "&Line:", 534, 14, 17, 60, 12
FAR_EDIT(536, ES_NUMBER | WS_BORDER, 75, 16, 166, 14)
LTEXT "&Name (optional):", 537, 14, 37, 227, 12
FAR_EDIT(535, WS_BORDER, 14, 50, 227, 14)
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 76, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 76, 60, 16
END
614 DIALOGEX 0, 0, 418, 166
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 541, 14, 16, 390, 12, SS_PATHELLIPSIS | SS_NOPREFIX
LISTBOX 538, 14, 33, 390, 100, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 83, 140, 58, 16
CONTROL "Re&name", 539, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 140, 58, 16
CONTROL "&Remove", 540, "Button", BS_OWNERDRAW | WS_TABSTOP, 211, 140, 58, 16
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 275, 140, 58, 16
END
609 DIALOGEX 0, 0, 430, 204
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 430, 16, 15, 398, 13, SS_PATHELLIPSIS | SS_NOPREFIX
LTEXT "&Filter", 440, 16, 33, 38, 13
FAR_EDIT(435, 0, 58, 32, 212, 15)
LTEXT "&Sort", 441, 277, 33, 34, 13
COMBOBOX 436, 312, 32, 102, 92, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
LTEXT "", 439, 17, 51, 397, 13, SS_NOPREFIX
LISTBOX 431, 16, 65, 398, 70, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "E&xecutable", 442, 16, 144, 71, 13
FAR_EDIT(438, ES_READONLY, 89, 143, 325, 15)
LTEXT "", 443, 16, 162, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 432, "Static", NOT WS_VISIBLE, 16, 179, 1, 1
CONTROL "&Go to file", 437, "Button", BS_OWNERDRAW | WS_TABSTOP, 35, 185, 90, 16
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 130, 185, 90, 16
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 225, 185, 78, 16
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 308, 185, 72, 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
LTEXT "&Left panel", 506, 132, 27, 108, 11
COMBOBOX 273, 132, 40, 108, 74, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "&Right panel", 507, 251, 27, 117, 11
COMBOBOX 274, 251, 40, 117, 74, CBS_DROPDOWNLIST | WS_TABSTOP
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
LTEXT "", 408, 131, 30, 254, 14
PUSHBUTTON "Change &font…", 409, 131, 49, 82, 15
LTEXT "Comparison &color", 410, 131, 79, 117, 12
COMBOBOX 411, 250, 76, 132, 126, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
PUSHBUTTON "Change color…", 412, 250, 97, 82, 15
LTEXT "", 413, 338, 100, 45, 12
LTEXT "Compare files &shortcut", 414, 131, 130, 117, 12
CONTROL "", 415, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 250, 127, 132, 15
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
112 DIALOGEX 0, 0, 360, 186
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "FTP connection"
FONT 10, "Consolas"
BEGIN
LTEXT "&Name", 381, 16, 18, 328, 12
FAR_EDIT(382, ES_LEFT, 16, 31, 328, 15)
LTEXT "&Server", 383, 16, 49, 250, 12
LTEXT "Por&t", 384, 278, 49, 66, 12
FAR_EDIT(385, ES_LEFT, 16, 62, 250, 15)
FAR_EDIT(386, ES_LEFT | ES_NUMBER, 278, 62, 66, 15)
LTEXT "&User name (blank for anonymous)", 387, 16, 80, 328, 12
FAR_EDIT(388, ES_LEFT, 16, 93, 328, 15)
LTEXT "&Password", 389, 16, 111, 328, 12
EDITTEXT 390, 16, 124, 328, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
AUTOCHECKBOX "Use &Windows encoding for file names", 392, 16, 144, 328, 14
LTEXT "", 391, 10, 161, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 164, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 164, 86, 18
END
113 DIALOGEX 0, 0, 350, 73
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Rename"
FONT 10, "Consolas"
BEGIN
LTEXT "New name in the current FTP folder:", 210, 14, 15, 322, 12
FAR_EDIT(211, 0, 14, 29, 322, 18)
LTEXT "", 217, 10, 49, 1, 1, NOT WS_VISIBLE
CONTROL "&Rename", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 51, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 51, 86, 18
END
114 DIALOGEX 0, 0, 510, 252
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_CLIPCHILDREN
EXSTYLE WS_EX_APPWINDOW
CAPTION "Compare files"
FONT 9, "Segoe UI"
BEGIN
LTEXT "", 400, 4, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 401, 259, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 65, 510, 187
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
LTEXT "", 403, 216, 12, 98, 14
CONTROL "", 408, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 28, 490, 19
END
115 DIALOGEX 0, 0, 290, 58
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Compare files"
FONT 10, "Consolas"
BEGIN
LTEXT "Reading and comparing files...", 548, 14, 15, 262, 13
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
END
116 DIALOGEX 0, 0, 300, 98
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Find files"
FONT 10, "Consolas"
BEGIN
LTEXT "File &name or mask", 483, 16, 18, 268, 12
FAR_EDIT(480, 0, 16, 32, 268, 15)
AUTOCHECKBOX "Include &hidden and system files", 481, 16, 53, 268, 12
LTEXT "", 482, 10, 69, 1, 1, NOT WS_VISIBLE
CONTROL "&Find", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 68, 73, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 73, 80, 17
END
117 DIALOGEX 0, 0, 290, 83
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Go to folder"
FONT 10, "Consolas"
BEGIN
LTEXT "Folder &path (Tab completes)", 486, 16, 18, 258, 12
FAR_EDIT(485, 0, 16, 32, 258, 15)
LTEXT "", 487, 10, 54, 1, 1, NOT WS_VISIBLE
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
END
118 DIALOGEX 0, 0, 420, 209
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Space Analyzer"
FONT 10, "Consolas"
BEGIN
LTEXT "", 488, 16, 15, 353, 13, SS_PATHELLIPSIS
LTEXT "", 495, 16, 28, 353, 13, SS_ENDELLIPSIS
CONTROL "Vo&lume", 496, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 64, 16
CONTROL "Tree&map", 497, "Button", BS_OWNERDRAW | WS_TABSTOP, 84, 43, 64, 16
CONTROL "S&unburst", 499, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 43, 64, 16
LTEXT "Sunburst items", 501, 171, 43, 201, 16, NOT WS_VISIBLE
LISTBOX 500, 171, 60, 201, 105, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | NOT WS_VISIBLE
CONTROL "", 498, "Static", SS_OWNERDRAW | SS_NOTIFY | WS_TABSTOP | NOT WS_VISIBLE, 16, 60, 353, 105
CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131
LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS
LTEXT "", 491, 12, 184, 1, 1, NOT WS_VISIBLE
CONTROL "S&top", 492, "Button", BS_OWNERDRAW | WS_TABSTOP, 22, 189, 46, 16
CONTROL "St&art", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16
CONTROL "&View", 494, "Button", BS_OWNERDRAW | WS_TABSTOP, 126, 189, 46, 16
CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16
END
119 DIALOGEX 0, 0, 260, 197
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Panel columns"
FONT 10, "Consolas"
BEGIN
AUTOCHECKBOX "E&xtension", 510, 18, 18, 224, 13
AUTOCHECKBOX "Si&ze", 511, 18, 36, 224, 13
AUTOCHECKBOX "&Modified", 512, 18, 54, 224, 13
AUTOCHECKBOX "A&llocated bytes", 513, 18, 72, 224, 13
AUTOCHECKBOX "Link cou&nt", 514, 18, 90, 224, 13
AUTOCHECKBOX "&Owner", 515, 18, 108, 224, 13
AUTOCHECKBOX "Automatic column &widths", 516, 18, 135, 224, 13
LTEXT "", 517, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&Apply", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 168, 62, 17
CONTROL "&Reset", 518, "Button", BS_OWNERDRAW | WS_TABSTOP, 88, 168, 74, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 168, 64, 17
END
120 DIALOGEX 0, 0, 290, 82
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Pack files"
FONT 10, "Consolas"
BEGIN
LTEXT "Archive name (.zip or .7z)", 530, 16, 15, 258, 12
FAR_EDIT(531, 0, 16, 32, 258, 15)
LTEXT "", 532, 10, 54, 1, 1, NOT WS_VISIBLE
CONTROL "&Create", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
END
121 DIALOGEX 0, 0, 430, 192
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB connections"
FONT 10, "Consolas"
BEGIN
LTEXT "", 540, 16, 16, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 541, "ListBox", LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP, 16, 31, 398, 103
LTEXT "", 542, 16, 140, 398, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 543, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 19, 166, 56, 17
CONTROL "&New", 544, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 166, 56, 17
CONTROL "&Edit", 545, "Button", BS_OWNERDRAW | WS_TABSTOP, 145, 166, 56, 17
CONTROL "Re&move", 546, "Button", BS_OWNERDRAW | WS_TABSTOP, 208, 166, 56, 17
CONTROL "&Sign in", 547, "Button", BS_OWNERDRAW | WS_TABSTOP, 271, 166, 60, 17
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 338, 166, 56, 17
END
122 DIALOGEX 0, 0, 355, 113
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB connection"
FONT 10, "Consolas"
BEGIN
LTEXT "Connection &name", 550, 16, 15, 323, 12
FAR_EDIT(551, 0, 16, 29, 323, 15)
LTEXT "&Server or UNC folder", 552, 16, 52, 323, 12
FAR_EDIT(553, 0, 16, 66, 323, 15)
LTEXT "", 554, 10, 87, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 93, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 93, 80, 17
END
123 DIALOGEX 0, 0, 355, 153
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB sign in"
FONT 10, "Consolas"
BEGIN
LTEXT "", 555, 16, 15, 323, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "&User name", 556, 16, 32, 323, 12
FAR_EDIT(557, 0, 16, 46, 323, 15)
LTEXT "&Password", 558, 16, 69, 323, 12
EDITTEXT 559, 16, 83, 323, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
AUTOCHECKBOX "&Remember in Windows Credential Manager", 560, 16, 106, 323, 13
LTEXT "", 561, 10, 125, 1, 1, NOT WS_VISIBLE
CONTROL "&Connect", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 132, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 132, 80, 17
END
124 DIALOGEX 0, 0, 420, 207
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SFTP connection"
FONT 10, "Consolas"
BEGIN
LTEXT "Connection &name", 381, 16, 15, 388, 12
FAR_EDIT(382, 0, 16, 28, 388, 15)
LTEXT "Server &host", 383, 16, 49, 292, 12
LTEXT "P&ort", 384, 328, 49, 76, 12
FAR_EDIT(385, 0, 16, 62, 302, 15)
FAR_EDIT(386, ES_NUMBER, 328, 62, 76, 15)
LTEXT "&User name", 387, 16, 83, 182, 12
FAR_EDIT(388, 0, 16, 96, 182, 15)
LTEXT "&Password or key passphrase", 389, 210, 83, 194, 12
EDITTEXT 390, 210, 96, 194, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
LTEXT "Private &key file (optional)", 562, 16, 117, 182, 12
FAR_EDIT(563, 0, 16, 130, 182, 15)
LTEXT "SFTP ser&ver for sudo (optional)", 569, 210, 117, 194, 12
FAR_EDIT(570, 0, 210, 130, 194, 15)
LTEXT "", 566, 16, 153, 218, 14, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "&Jump via", 568, 240, 153, 56, 14
COMBOBOX 567, 298, 150, 106, 90, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "", 391, 10, 175, 1, 1, NOT WS_VISIBLE
CONTROL "&Test connection", 564, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 183, 128, 17
CONTROL "&Forget host key", 565, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 183, 112, 17
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 270, 183, 60, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 336, 183, 67, 17
END
125 DIALOGEX 0, 0, 360, 178
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Properties"
FONT 10, "Consolas"
BEGIN
LTEXT "", 580, 16, 15, 328, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 581, 16, 32, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 582, 16, 45, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 583, 16, 58, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 584, 16, 71, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 585, 16, 84, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 586, 16, 99, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
AUTOCHECKBOX "&Read-only", 587, 16, 114, 106, 13
AUTOCHECKBOX "&Hidden", 588, 128, 114, 106, 13
AUTOCHECKBOX "S&ystem", 589, 240, 114, 104, 13
AUTOCHECKBOX "&Archive", 590, 16, 128, 106, 13
AUTOCHECKBOX "Not &indexed", 591, 128, 128, 106, 13
LTEXT "", 592, 10, 146, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 95, 153, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 185, 153, 80, 17
END
-63
View File
@@ -1,63 +0,0 @@
# Getting started
KSwitcher runs in the Windows notification area. Right-click the KSwitcher icon to open Settings, Clipboard history, Capture screen region, Files, Snippets, Keyboard shortcuts, Tools, Help and other commands. Windows may place the icon under Show hidden icons.
Use Keyboard shortcuts in this help window to see the shortcuts currently configured on this PC. To change them, open Settings → Shortcuts, select a field, press the desired combination and choose Apply or Save.
Choose a topic on the left or search the guide. The detailed manuals are part of the application and can be read offline.
# Keyboard and correction
KSwitcher can switch between installed layouts, convert text typed in the wrong layout, change case, transliterate and undo a recent transformation. Apply a text shortcut to selected text or let KSwitcher work with the recent text detected in the active application. KSwitcher skips transformations when it cannot verify the target or text.
Settings → Languages controls layout order and application or chat profiles. The layouts themselves are installed through Windows. Application and chat rules can narrow the layouts cycled for a particular context.
Settings → General → Correction options controls automatic correction. Its child pages cover offline dictionaries, exceptions, personal dictionaries, word boundaries and custom replacements. For a custom replacement, put one typo=correction pair per line.
# Clipboard history and OCR
Open Clipboard history from the tray or its configured shortcut. Search the list, filter it by computer or select Pinned only. Choose an entry and press Enter to paste, Shift+Enter for plain text, Ctrl+P to pin or unpin, Delete to remove it or Ctrl+O to open the full entry. Ctrl+1 through Ctrl+9 paste entries by position.
Open an image in the screenshot editor or use Copy text from image (OCR) in the context menu. Image text can also be searched once recognized. Settings → Clipboard controls recording, size limits and excluded apps. Settings → Clipboard → Image text recognition controls Windows OCR or optional local Tesseract.
Clear history deletes saved entries, including pinned ones, after confirmation. Use Pause clipboard history in the tray to suspend recording temporarily.
# Screenshots and annotations
Choose Capture screen region from the tray or use the configured shortcut. Drag around the area to capture. The capture is copied, and Settings can open the editor automatically. You can also open an image from Clipboard history.
The editor offers pointer selection, numbered markers, arrows, straight lines, shapes, pencil strokes, highlighting, text, color and undo/redo. Pick a mark with the pointer to edit its geometry or text. Line style, arrowheads and pencil smoothing are available below the toolbar.
Copy sends the annotated screenshot to the clipboard. Save exports a full-resolution PNG. Ctrl+Shift+S chooses another file. Ctrl+mouse wheel zooms, Ctrl+0 fits the image and the middle mouse button pans.
# Snippets and mouse profiles
In Settings → Snippets, add a trigger and its replacement text. Restrict it to specific applications when needed. Insert macro or marker opens the available insertions. The detailed manual describes autocomplete, cursor markers and supported macros.
In Settings → Mouse, create a profile for one or more applications and assign actions to mouse events. The Global profile is the fallback. Use Test mouse buttons here to check what the device reports.
# Settings, backup and sync
Use Apply to save edits and keep Settings open, or Save to save and close. Import loads settings for review before applying them. Export writes settings to a file.
Under Settings → Sync, configure OpenBao or Google Drive. A PC uses one automatic provider at a time. Use Sync now for an immediate sync and Resolve individual conflicts to review conflicting changes when available.
Manual Google Drive copies are separate from the auto-sync profile. Back up saved settings creates a dated copy. Restore selected backup loads that copy into the Settings draft. Review it before applying, especially if automatic sync is on. Google Drive features require a build with OAuth configured.
# Paired computers
Open Settings → Computers → Manage computers. Enable discovery on both PCs and use the same pairing code to connect them. Drag the monitors into position and enable input sharing to move the pointer across shared edges. Each PC can control whether its paired computers may download diagnostic logs.
The paired computers manual explains discovery, trust, sharing, file operations and troubleshooting in more detail.
# KSwitcher Files
Choose Files from the tray. Use the two file panels to browse, move and copy files. The manual covers local and remote locations, FTP, the viewer and editor, comparisons, search, dialogs, the integrated terminal and keyboard operation.
# Tray, updates and diagnostics
Use the tray menu to pause or resume input processing, keep the display awake, pause clipboard history, open the data folder, check for updates or exit. Tools lists supported portable utilities placed in the tools folder.
If a shortcut stops working, check whether input processing is paused and whether another application owns the binding. If a paired PC is missing, check discovery and access on both computers. Settings → Diagnostics and View log in the tray provide logs. Settings → MCP displays management integration settings.
Donate via Monobank opens the project's donation jar in the browser. Choose Help → About KSwitcher to see the running version.
-6
View File
@@ -1,6 +0,0 @@
#include <windows.h>
#include "resource.h"
IDR_HELP_GUIDE RCDATA "help-guide.md"
IDR_HELP_MANUAL RCDATA "../README.md"
IDR_HELP_FILES RCDATA "../FILES-UI.md"
IDR_HELP_COMPUTERS RCDATA "../LAN-PREVIEW.md"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

-14
View File
@@ -1,14 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 711 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

-18
View File
@@ -1,18 +0,0 @@
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.
-13
View File
@@ -1,16 +1,3 @@
#pragma once
#define IDI_KSWITCHER 101
#define IDI_SCREENSHOT_QUESTION 102
#define IDI_FILES_VIEWER 103
#define IDI_FILES_EDITOR 104
#define IDI_FILES_COMPARE 105
#define IDI_KSWITCHER_PAUSED 106
#define IDI_KSWITCHER_HISTORY 107
#define IDI_KSWITCHER_SCREENSHOT 108
#define IDI_KSWITCHER_HELP 109
#define IDI_KSWITCHER_DONATE 110
#define IDC_SCREENSHOT_PENCIL 500
#define IDR_HELP_GUIDE 600
#define IDR_HELP_MANUAL 601
#define IDR_HELP_FILES 602
#define IDR_HELP_COMPUTERS 603
Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

-22
View File
@@ -1,22 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

-22
View File
@@ -1,22 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 1.7 KiB

-14
View File
@@ -1,14 +0,0 @@
<!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>
-60
View File
@@ -1,60 +0,0 @@
<!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; }
:root.quick-view body { padding: 8px 12px; }
:root.quick-view nav { display: none; }
:root.quick-view main > :first-child { margin-block-start: 0; }
:root.quick-view h1 { font-size: 1.4em; }
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
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; }
figure svg .edgeLabel rect { fill: Canvas !important; opacity: 1 !important; stroke: none !important; }
.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="markdown.js"></script>
</html>
-380
View File
@@ -1,380 +0,0 @@
'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;
let taskMarkers = new WeakMap();
let pendingTask;
let previewRevision = 0;
let mermaidReady;
function loadMermaid() {
mermaidReady ??= new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'mermaid.js';
script.onload = resolve;
script.onerror = () => reject(new Error('Could not load Mermaid'));
document.head.append(script);
}).then(() => {
const renderer = window.mermaid;
renderer.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
return renderer;
});
return mermaidReady;
}
markdown.core.ruler.after('inline', 'task_lists', ({ tokens, src, env }) => {
const lines = src.split('\n');
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);
const line = tokens[i - 1].map?.[0];
const sourceMarker = /^[ \t]*(?:>[ \t]*)*(?:[-+*]|\d{1,9}[.)])[ \t]+\[([ xX])\][ \t]+/.exec(lines[line]);
if (sourceMarker) box.source = env.taskKey + ':' + line + ':' + (sourceMarker[0].lastIndexOf('[') + 1);
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' : '') + (tokens[i].source ? ' data-task="' + tokens[i].source + '"' : '') + '>';
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, canSave) {
// Parse in an inert template and allow only document markup before attaching it to the preview.
const template = document.createElement('template');
const taskKey = [...crypto.getRandomValues(new Uint32Array(4))].join('-');
taskMarkers = new WeakMap();
pendingTask = undefined;
template.innerHTML = markdown.render(text, { taskKey });
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 task = tag === 'input' && element.getAttribute('data-task');
if (task && task.startsWith(taskKey + ':')) {
const [, line, column] = task.split(':');
taskMarkers.set(element, { line: Number(line), column: Number(column) });
element.disabled = !canSave;
}
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, revision, canSave, compact }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
else closeSearch();
document.documentElement.classList.remove('rendered');
document.title = title;
document.documentElement.classList.toggle('quick-view', Boolean(compact));
previewRevision = revision;
renderContent(text, canSave);
const headings = new Set();
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, revision }));
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
for (const [index, block] of blocks.entries()) {
try {
const renderer = await loadMermaid();
if (current !== generation) return;
const { svg } = await renderer.render('diagram-' + current + '-' + index, block.textContent);
if (current !== generation) return;
const figure = document.createElement('figure');
figure.innerHTML = svg;
const paths = figure.querySelector('g.edgePaths');
const labels = figure.querySelector('g.edgeLabels');
if (paths && labels && paths.parentNode === labels.parentNode) paths.after(labels);
block.parentElement.replaceWith(figure);
} catch (error) {
if (current !== generation) return;
const caption = document.createElement('div');
caption.textContent = 'Invalid Mermaid diagram';
caption.title = error instanceof Error ? error.message : String(error);
block.parentElement.before(caption);
}
}
restorePosition({ fragment, scroll });
document.documentElement.classList.add('rendered');
if (!search.hidden) updateSearch(false);
send('rendered', { revision });
}
content.addEventListener('change', ({ target }) => {
const marker = taskMarkers.get(target);
if (!marker) return;
if (pendingTask) {
target.checked = !target.checked;
return;
}
pendingTask = { target, checked: target.checked };
send('save-task', { ...marker, revision: previewRevision, checked: target.checked });
});
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', { revision: message.revision }));
if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) {
if (!message.saved) pendingTask.target.checked = !pendingTask.checked;
pendingTask = undefined;
}
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');
-184
View File
@@ -1,184 +0,0 @@
const bridge = window.chrome.webview;
const terminal = new Terminal({
fontFamily: 'Consolas, monospace',
fontSize: 16,
cursorBlink: false,
cursorInactiveStyle: 'none',
theme: { background: '#181818', foreground: '#e8e8e8' },
});
const fit = new FitAddon.FitAddon();
terminal.parser.registerOscHandler(633, data => {
const prefix = 'ks-directory:';
if (data.startsWith('ks-ssh-dir:')) {
bridge.postMessage('ssh-directory:' + data.slice(11));
return true;
}
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()));
const prompt = message => bridge.postMessage('prompt:' + message);
let sshInput = false;
host.addEventListener('pointerup', () => {
if (!sshInput) prompt('focus-input');
}, true);
terminal.onData(text => {
if (sshInput) bridge.postMessage('ssh-input:' + text);
else if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
});
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);
}
const promptKeys = new Set([
'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End',
'Tab', 'Escape', 'Delete', 'Backspace', 'F1',
]);
terminal.attachCustomKeyEventHandler(event => {
if (event.isComposing) return true;
if (sshInput) {
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.metaKey) return true;
const copy = event.code === 'KeyC' && terminal.hasSelection();
if (!copy && (event.shiftKey || event.code !== 'KeyO')) return true;
event.preventDefault();
if (!event.repeat) bridge.postMessage(copy ? 'copy-command-line' : 'toggle');
return false;
}
if (event.type === 'keydown' && promptKeys.has(event.key) &&
!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {
prompt(event.key);
event.preventDefault();
return false;
}
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
if (!event.repeat) prompt(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 === 'ssh-input:on' || data === 'ssh-input:off') {
sshInput = data === 'ssh-input:on';
terminal.options.cursorBlink = sshInput;
terminal.write(sshInput ? '\x1b[?25h' : '\x1b[?25l');
return;
}
if (data === 'ssh-focus') {
terminal.focus();
return;
}
if (data === 'ssh-reset') {
terminal.reset();
terminal.write('\x1b[?25l');
return;
}
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();
+10 -276
View File
@@ -3,193 +3,10 @@
[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 }
@@ -203,7 +20,7 @@ function Assert-ReleaseUrl([string]$Url) {
throw 'Release asset URL is outside the KSwitcher repository.'
}
}
function Receive-File([string]$Url,[string]$Path,[long]$Limit,[string]$ProgressLabel = '') {
function Receive-File([string]$Url,[string]$Path,[long]$Limit) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$request = [Net.HttpWebRequest]::Create($Url)
$request.AllowAutoRedirect = $false
@@ -219,20 +36,11 @@ function Receive-File([string]$Url,[string]$Path,[long]$Limit,[string]$ProgressL
$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() }
@@ -409,60 +217,11 @@ 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; $uiFinished = $false
$parentExited = $false; $success = $false; $preserveBackup = $false; $child = $null
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') {
@@ -475,49 +234,33 @@ 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) {
if ($Unattended) { Write-UpdateJournal "No newer stable release is available ($CurrentVersion)." }
Write-Result @{state='current'}; exit 0
}
if (!$release) { Write-Result @{state='current'}; exit 0 }
if ($Mode -eq 'Check') { Write-Result @{state='available';version=$release.version}; exit 0 }
if (!$Unattended -and $ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' }
if ($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'
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.zip $archive 50MB
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)
Write-UpdateJournal "Verified $($release.version). Closing KSwitcher (PID $ParentProcessId)."
$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-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
@@ -529,14 +272,9 @@ try {
}
}
Write-Result @{state='error';error=$message}
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
}
if ($ready -and $ready.WaitOne(0)) {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.MessageBox]::Show($message,'KSwitcher update failed') | Out-Null
}
exit 1
} finally {
@@ -553,8 +291,4 @@ try {
Remove-Item -LiteralPath $WorkDirectory -Recurse -Force -ErrorAction SilentlyContinue
}
}
if ($script:progressWindow) {
if ($uiFinished) { $script:progressWindow.WaitForClose() }
$script:progressWindow.Dispose(); $script:progressWindow = $null
}
}
+209 -2648
View File
File diff suppressed because it is too large. Load diff
+10 -138
View File
@@ -2,11 +2,6 @@
#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>
@@ -21,7 +16,6 @@ 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
{
@@ -36,22 +30,15 @@ struct LastTransform
class App
{
public:
HWND window{}, historyWindow{}, settingsWindow{}, snippetsWindow{}, helpWindow{};
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;
HWND window{}, historyWindow{}, settingsWindow{}, snippetsWindow{};
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}, lanSequence{0};
std::atomic<DWORD> ownSequence{0};
std::atomic<uint64_t> inputVersion{0};
std::atomic<ULONGLONG> pauseUntil{0};
HWND pasteTarget{};
@@ -65,174 +52,59 @@ class App
bool smoke{};
int startCommand{};
std::wstring updateStartupEvent;
App(HINSTANCE, bool = false, const std::filesystem::path &dataRoot = {}, HWND historyService = nullptr);
App(HINSTANCE, bool = false, const std::filesystem::path &dataRoot = {});
~App();
int execute();
void dispatch(int);
void transform(int, int snippet = -1, size_t snippetLength = 0, HWND snippetEditor = nullptr);
void transform(int, int snippet = -1);
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();
bool registerHotkeys(const Settings &, bool rollback = false);
void applySettings(const Settings &, const Bytes &supplement = {});
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;
friend void commitConfigurationSupplement(App &, const Bytes &);
void releaseIdleMemory(ULONGLONG now);
void applySettings(const Settings &, bool validateOcrInstallation, const std::function<void()> &commit = {});
void checkAutostartPath();
bool checkingAutostartPath{};
HHOOK keyboardHook{}, mouseHook{};
enum class InputState { Active, Pausing, Paused };
std::atomic<InputState> inputState{InputState::Active};
bool installInputHooks();
void releaseInputHooks();
void toggleInputProcessing();
void updateLanInputTimer();
void pollLanInput();
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;
std::thread syncWorker;
std::atomic<bool> syncDone{false};
bool syncRunning{};
ULONGLONG nextSync{}, syncRetryAfter{};
SyncResult syncResult;
SyncConfig syncConnection;
std::string syncDriveKey;
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 updateRunning{}, installingUpdate{};
std::wstring availableUpdate;
bool stop{};
UINT taskbarCreated{};
bool trayRetryPending{};
LanInputConnections trayInput;
bool trayInputPulse{};
HICON trayBaseIcon(int width, int height) const;
bool updateTray(DWORD action);
void refreshTrayInput();
uint64_t pendingAutoVersion{};
uint64_t transformAttempt{}, previousAttemptVersion{};
std::atomic<uint64_t> activeTransformAttempt{};
ULONGLONG previousAttemptAt{};
HWND previousAttemptWindow{};
int previousAttemptCommand{}, repeatAttempts{};
std::vector<std::pair<int, Hotkey>> hookBindings;
std::vector<Hotkey> availableBeforePause;
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 &, bool visible = true);
void launchScreenshot(App &);
void launchScreenshotEditor(App &, const Clip &);
void showHistory(App &);
void showScreenshot(App &);
void refreshHistory(App &);
void showSettings(App &, bool visible = true);
void showLogs(App &);
void showSnippets(App &);
void showShortcuts(App &);
void showHelp(App &);
void showEntry(App &, const std::wstring &);
} // namespace ks
-100
View File
@@ -1,100 +0,0 @@
// 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.
}
-123
View File
@@ -1,123 +0,0 @@
// 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 (!automaticSyncEnabled(c)) return syncStatus = L"Synchronization is disabled.";
validateSyncConfig(c);
if (action == 4 && (c != conflictConnection || choices.empty()))
throw std::runtime_error("Connection changed or no choices selected. Sync again.");
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;
const auto driveKey = syncDriveKey = c.driveEnabled ? googleDriveCredentialKey() : std::string{};
syncSnapshot = encodeSettings(settings);
auto snapshot = settings;
auto availableLayouts = layouts;
syncRunning = true;
syncDone = false;
const auto providerName = std::wstring(automaticSyncProviderName(c));
syncStatus = action == 2 ? L"Downloading remote settings from " + providerName + L"..." :
action == 3 ? L"Uploading local settings to " + providerName + L"..." : L"Connecting to " + providerName + L"...";
nextSync = GetTickCount64() + SyncIntervalMs;
try
{
syncWorker = std::thread([this, c, snapshot, availableLayouts, action, choices, driveKey] {
SyncResult result;
try
{
auto provider = makeSyncProvider(c);
// An explicit choice also repairs a missing/corrupt local baseline.
const bool keepLayouts = c.enabled && c.keepLocalLayouts;
auto base = action == 1 || action == 4 ? loadSyncBase(data, c, driveKey) : Bytes{};
result = synchronize(*provider, base, c.driveEnabled ? sharedDriveSettings(snapshot) : sharedSyncSettings(snapshot),
action == 2 ? SyncAction::Download : action == 3 ? SyncAction::Upload : SyncAction::Automatic,
[&](const Bytes &b) {
if (c.driveEnabled) restoreSharedDriveSettings(b, snapshot, availableLayouts);
else restoreSyncSettings(b, snapshot, availableLayouts, keepLayouts);
}, choices, keepLayouts);
if (result.success && keepLayouts)
result.status += L" Partial sync: this PC's layouts and their shortcuts were kept; server layouts were preserved.";
}
catch (const nlohmann::json::exception &) { result.status = L"Invalid sync data or server response."; }
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 ||
(syncConnection.driveEnabled && googleDriveCredentialKey() != syncDriveKey))
{
syncStatus = L"Local settings or connection changed during sync. Checking again shortly.";
nextSync = GetTickCount64() + 2000;
return;
}
auto next = syncConnection.driveEnabled ? restoreSharedDriveSettings(result.settings, settings, layouts) :
restoreSyncSettings(result.settings, settings, layouts, syncConnection.keepLocalLayouts);
if (encodeSettings(next) != snapshot)
{
atomicWrite(data / L"settings-before-sync.bin", protect(snapshot));
// 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, syncDriveKey);
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 (automaticSyncEnabled(loadSyncConfig(data))) 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; }
}
+46 -225
View File
@@ -34,169 +34,81 @@ std::wstring layoutLanguage(const Layout &layout)
return {};
}
}
bool safeAutoWord(const std::wstring &word, int minimumLength, bool allowUppercase)
bool safeAutoWord(const std::wstring &word, int minimumLength)
{
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);
const bool allUppercase = word == upper(word);
return word == small || (allUppercase ? allowUppercase : word.substr(1) == small.substr(1));
return word == small || (word.substr(1) == small.substr(1) && word != upper(word));
}
namespace {
constexpr size_t DictionaryBlockWords = 32;
}
std::string_view AutoCorrector::Dictionary::word(size_t block) const
std::string_view AutoCorrector::Dictionary::word(size_t index) const
{
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);
auto start = offsets[index];
auto end = bytes.find('\t', start);
return std::string_view(bytes).substr(start, end - start);
}
AutoCorrector::Dictionary::Dictionary(const std::filesystem::path &path)
{
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 raw = readFile(path, 2 * 1024 * 1024);
bytes.assign(raw.begin(), raw.end());
for (size_t start = 0; start < bytes.size();)
{
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)
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)
throw std::runtime_error("Invalid auto-correction dictionary");
int rank{};
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)
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)
throw std::runtime_error("Invalid dictionary rank");
lines.push_back(static_cast<uint32_t>(start));
offsets.push_back((uint32_t)start);
start = end + 1;
}
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;
}
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();
}
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) 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;
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;
}
void AutoCorrector::configure(const std::filesystem::path &folder, const std::vector<std::wstring> &wanted)
{
if (languages == wanted)
return;
std::map<std::wstring, std::shared_ptr<const Dictionary>> next;
std::map<std::wstring, 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, std::make_shared<const Dictionary>(folder / (lang + L".txt")));
next.emplace(lang, 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))
@@ -211,7 +123,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,
@@ -231,11 +143,7 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
suffix.insert(suffix.begin(), word.back());
word.pop_back();
}
// 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)))
if (!safeAutoWord(word, settings.autoMinLength) || suffix.size() > 6 || rejected.contains(lower(word)))
return {};
for (auto &never : settings.autoNever)
if (lower(never) == lower(word))
@@ -243,44 +151,12 @@ 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) || personal(language, word))
if (d.rank(word))
return {};
std::optional<AutoSuggestion> candidate;
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();
};
int matches = 0;
for (int i = 0; i < (int)layouts.size(); ++i)
{
if (i == source || !layouts[i].convertible ||
@@ -290,72 +166,17 @@ 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)
if (converted == word || !safeAutoWord(converted, settings.autoMinLength))
continue;
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);
int rank = dictionary->second.rank(converted);
if (!rank)
continue;
if (matchedText && *matchedText != converted)
if (++matches > 1)
return {};
matchedText = converted;
if ((settings.autoMaxRank == 0 || rank <= settings.autoMaxRank) &&
(!candidate || priority(i) < priority(candidate->target)))
if (settings.autoMaxRank == 0 || rank <= settings.autoMaxRank)
candidate = AutoSuggestion{source, i, prefix + converted + suffix};
}
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 {};
return candidate;
}
int matchAutoInput(const Run &run, const std::wstring &text, const std::vector<Layout> &layouts,
const Layout &physical, const Settings &settings)
+2 -10
View File
@@ -1,7 +1,6 @@
#pragma once
#include "platform.h"
#include <map>
#include <memory>
#include <set>
#include <string_view>
namespace ks
@@ -12,37 +11,30 @@ struct AutoSuggestion
std::wstring text;
};
std::wstring layoutLanguage(const Layout &);
bool safeAutoWord(const std::wstring &, int minimumLength = 3, bool allowUppercase = false);
bool safeAutoWord(const std::wstring &, int minimumLength = 3);
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, std::shared_ptr<const Dictionary>> dictionaries;
std::map<std::wstring, 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
+14 -124
View File
@@ -27,7 +27,6 @@ template <class T> struct Com
struct Str
{
BSTR value;
Str() : value(nullptr) {}
Str(const wchar_t *s) : value(SysAllocString(s))
{
if (!value)
@@ -52,108 +51,10 @@ 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, RunKey, 0, nullptr,
if (RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, nullptr,
0, KEY_SET_VALUE, nullptr, &key, nullptr) != ERROR_SUCCESS)
throw std::runtime_error("Cannot access autostart settings");
auto command = L"\"" + executable() + L"\"";
@@ -165,27 +66,6 @@ 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{};
@@ -208,10 +88,13 @@ std::wstring currentUserSid()
void configureAutostart(int mode)
{
Com<ITaskService> service;
Com<ITaskFolder> folder;
check(openTaskFolder(service, folder));
check(CoCreateInstance(CLSID_TaskScheduler, nullptr, CLSCTX_INPROC_SERVER, IID_ITaskService,
(void **)service.out()));
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))
@@ -275,9 +158,16 @@ 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))
-143
View File
@@ -1,143 +0,0 @@
// 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;}
}
-149
View File
@@ -1,149 +0,0 @@
#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];
}
}
+12 -85
View File
@@ -1,7 +1,6 @@
#include "configuration.h"
#include <commctrl.h>
#include <cstring>
#include "mcp_logs.h"
namespace ks
{
@@ -53,25 +52,11 @@ 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)
@@ -84,7 +69,6 @@ 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;
}
@@ -93,21 +77,19 @@ 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 &, HWND) : instance(h)
App::App(HINSTANCE h, bool, const std::filesystem::path &) : 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;
}
void App::applySettings(const Settings &next, const Bytes &supplement)
void App::applySettings(const Settings &next)
{
validateSettings(next);
auto before = encodeSettings(settings), after = encodeSettings(next);
@@ -115,24 +97,8 @@ void App::applySettings(const Settings &next, const Bytes &supplement)
Bytes payload(sizeof(length));
memcpy(payload.data(), &length, sizeof(length));
payload.insert(payload.end(), before.begin(), before.end());
if (!supplement.empty())
{
DWORD length = (DWORD)after.size();
auto first = reinterpret_cast<const unsigned char *>(&length);
payload.insert(payload.end(), first, first + sizeof(length));
}
payload.insert(payload.end(), after.begin(), after.end());
payload.insert(payload.end(), supplement.begin(), supplement.end());
Bytes saved;
try {saved=request(*this,supplement.empty() ? ConfigSave : ConfigSaveDraft,payload);}
catch(const std::exception &error){
if(!std::string(error.what()).starts_with("Settings conflict: "))throw;
auto text=wide(error.what())+L"\n\nThese settings changed both here and in KSwitcher.\nKeep your edits for these settings? Other changes will be preserved.\n\nNo leaves this window open with all your edits.";
if(MessageBoxW(settingsWindow?settingsWindow:snippetsWindow,text.c_str(),L"Save conflicting settings",MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2)!=IDYES)
throw std::runtime_error("Not saved. Your edits are still in this window.");
saved=request(*this,supplement.empty() ? ConfigSaveEdited : ConfigSaveEditedDraft,payload);
}
settings=decodeSettings(saved,layouts);
settings = decodeSettings(request(*this, ConfigSave, payload), layouts);
}
void App::reloadLayouts()
{
@@ -141,14 +107,6 @@ 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;
@@ -162,29 +120,9 @@ void App::setHotkeyCapture(HWND field)
if (field) MessageBoxW(settingsWindow, wide(e.what()).c_str(), L"Shortcut capture unavailable", MB_OK | MB_ICONWARNING);
}
}
void App::clearLog(bool previous) { request(*this, ConfigClearLog, Bytes{static_cast<unsigned char>(previous)}); }
void showLogs(App &app) { request(app, ConfigLogs); }
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)
int runConfigurator(HINSTANCE instance, bool snippets)
{
HANDLE singleton = CreateMutexW(nullptr, TRUE, L"Local\\KSwitcher.Config.Singleton");
if (!singleton) throw std::runtime_error("Cannot create configurator instance lock.");
@@ -202,7 +140,7 @@ int runConfigurator(HINSTANCE instance, bool snippets, bool logs)
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, logs ? 22 : snippets ? 21 : 20, 0);
PostMessageW(window, WM_APP + 20, snippets ? 21 : 20, 0);
return 0;
}
service = FindWindowW(L"KSwitcher.Main", L"KSwitcher");
@@ -231,26 +169,17 @@ int runConfigurator(HINSTANCE instance, bool snippets, bool logs)
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);
setLoggingEnabled(app.settings.writeLog);
if (logs) showLogs(app); else if (snippets) showSnippets(app); else showSettings(app);
if (snippets) showSnippets(app); else showSettings(app);
MSG message;
while ((app.settingsWindow || app.snippetsWindow || app.logWindow) && GetMessageW(&message, nullptr, 0, 0) > 0)
while ((app.settingsWindow || app.snippetsWindow) && GetMessageW(&message, nullptr, 0, 0) > 0)
{
const auto editor = app.settingsWindow ? app.settingsWindow : app.snippetsWindow;
if (editor && !IsWindowEnabled(editor))
if (app.settingsWindow && !IsWindowEnabled(app.settingsWindow))
{
HWND popup = GetLastActivePopup(editor);
while (!IsWindowEnabled(popup))
{
HWND next = GetLastActivePopup(popup);
if (next == popup) break;
popup = next;
}
if (popup != editor && IsDialogMessageW(popup, &message)) continue;
HWND popup = GetLastActivePopup(app.settingsWindow);
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;
@@ -264,10 +193,8 @@ 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 = mcp ? ks::runMcpConfigurator(instance) : ks::runConfigurator(instance, snippets, logs);
result = ks::runConfigurator(instance, snippets);
}
catch (const std::exception &e)
{
+13 -119
View File
@@ -1,35 +1,25 @@
#include "configuration.h"
#include "settings_merge.h"
#include "../vendor/json.hpp"
#include <cstring>
namespace ks
{
namespace
{
std::filesystem::path processImage(HWND window)
bool configurationPeer(HWND window, const wchar_t *filename)
{
DWORD pid{};
GetWindowThreadProcessId(window, &pid);
HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!process) return {};
if (!process) return false;
wchar_t path[32768]; DWORD count = std::size(path);
bool ok = QueryFullProcessImageNameW(process, 0, path, &count) != 0;
CloseHandle(process);
return ok ? std::filesystem::path(path) : std::filesystem::path{};
auto expected = std::filesystem::path(executable()).parent_path() / filename;
return ok && _wcsicmp(path, expected.c_str()) == 0;
}
}
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)
void launchConfiguration(App &app, bool snippets)
{
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"\"" + (logs ? L" --logs" : snippets ? L" --snippets" : L"");
auto command = L"\"" + path.wstring() + L"\"" + (snippets ? L" --snippets" : L"");
STARTUPINFOW startup{sizeof(startup)};
PROCESS_INFORMATION process{};
if (!CreateProcessW(path.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr,
@@ -40,41 +30,9 @@ void launchConfiguration(App &app, bool snippets, bool logs)
CloseHandle(process.hProcess);
(void)app;
}
void commitConfigurationSupplement(App &app, const Bytes &supplement)
{
const auto draft = nlohmann::json::parse(supplement);
auto commitLan = [&] {
if (!draft.contains("lan")) return;
const auto command = nlohmann::json{{"action", "applySettings"}, {"draft", draft.at("lan")}}.dump();
app.lanCommand(Bytes(command.begin(), command.end()));
};
if (draft.contains("sync"))
{
const auto &sync = draft.at("sync");
const auto config = decodeSyncConfig(sync.at("config").get<Bytes>());
const auto previous = loadSyncConfig(app.data);
if (previous != decodeSyncConfig(sync.at("base").get<Bytes>()))
throw std::runtime_error("The synchronization connection changed. Reopen Settings to edit the current connection.");
const bool switching = previous.enabled != config.enabled || previous.driveEnabled != config.driveEnabled;
if (switching && app.syncRunning)
throw std::runtime_error("Wait for the current synchronization to finish before changing providers.");
applySyncConnection(app.data, config, sync.at("password").get<Bytes>(), sync.at("forget").get<bool>(), commitLan);
if (switching)
{
app.pendingSyncConflicts.clear();
app.syncRetryAfter = 0;
app.syncStatus = automaticSyncEnabled(config) ? L"Waiting to synchronize." : L"Synchronization is disabled.";
}
}
else commitLan();
}
LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &message)
{
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 ||
if (!configurationPeer(sender, L"KSwitcher.Config.exe") || message.cbData > ConfigLimit ||
(message.cbData && !message.lpData)) return FALSE;
Bytes reply;
bool ok = false;
@@ -82,53 +40,7 @@ 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:
case ConfigSaveDraft:
case ConfigSaveEditedDraft:
{
if (app.busy) throw std::runtime_error("Wait for the current text operation to finish.");
if (message.cbData < sizeof(DWORD)) throw std::runtime_error("Invalid settings request.");
@@ -136,23 +48,11 @@ 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);
const auto end = static_cast<const unsigned char *>(message.lpData) + message.cbData;
auto next = begin + length;
auto nextEnd = end;
const bool hasDraft = message.dwData == ConfigSaveDraft || message.dwData == ConfigSaveEditedDraft;
if (hasDraft)
{
DWORD nextLength{};
if (end - next < sizeof(nextLength)) throw std::runtime_error("Invalid settings draft.");
memcpy(&nextLength, next, sizeof(nextLength));
next += sizeof(nextLength);
if (nextLength >= end - next) throw std::runtime_error("Invalid settings draft.");
nextEnd = next + nextLength;
}
if (next == nextEnd) throw std::runtime_error("Empty settings request.");
auto merged = mergeConfigurationSettings(Bytes(begin, begin + length), Bytes(next, nextEnd),
encodeSettings(app.settings), message.dwData == ConfigSaveEdited || message.dwData == ConfigSaveEditedDraft);
app.applySettings(decodeSettings(merged, app.layouts), Bytes(nextEnd, end));
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));
reply = encodeSettings(app.settings);
break;
}
@@ -180,11 +80,6 @@ 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;
@@ -194,8 +89,7 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
std::string text = error.what();
reply.assign(text.begin(), text.end());
}
if(filesPeers && !ok) return FALSE;
COPYDATASTRUCT response{filesPeers?FilesLanPeersReply:ConfigReply, (DWORD)reply.size(), reply.data()};
COPYDATASTRUCT response{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;
+2 -7
View File
@@ -1,18 +1,13 @@
#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, ConfigClearLog = ConfigRead + 7,
ConfigSync = ConfigRead + 8, ConfigSyncConflicts = ConfigRead + 9,
ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigSaveDraft = FilesLanPeersReply + 1, ConfigSaveEditedDraft = ConfigSaveDraft + 1, ConfigEnd = ConfigSaveEditedDraft + 1;
ConfigReply = ConfigRead + 6;
inline constexpr size_t ConfigLimit = 8 * 1024 * 1024;
bool configurationPeer(HWND, const wchar_t *filename);
void commitConfigurationSupplement(App &, const Bytes &);
void launchConfiguration(App &, bool snippets = false, bool logs = false);
void launchConfiguration(App &, bool snippets = false);
LRESULT configurationRequest(App &, HWND sender, const COPYDATASTRUCT &);
}
+50 -242
View File
@@ -3,53 +3,9 @@
#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)
{
@@ -192,26 +148,6 @@ 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))
@@ -319,6 +255,30 @@ std::wstring transliterate(const std::wstring &text)
}
return out;
}
Template parseTemplate(const std::wstring &text)
{
Template t;
size_t cursor = std::wstring::npos;
for (size_t i = 0; i < text.size();)
{
if (text.compare(i, 10, L"{{cursor}}\0", 10) == 0)
{
t.text += L"{cursor}";
i += 10;
}
else if (text.compare(i, 8, L"{cursor}") == 0)
{
cursor = t.text.size();
++t.cursors;
i += 8;
}
else
t.text += text[i++];
}
if (cursor != text.npos)
t.suffix = t.text.substr(cursor);
return t;
}
namespace
{
const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
@@ -343,176 +303,7 @@ const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
{VK_DIVIDE, L"Divide"}, {VK_DECIMAL, L"Decimal"}};
return names;
}
WORD namedKey(const std::wstring &token)
{
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
return upper(token)[0];
if (token.size() == 4 && token.starts_with(L"num") && token[3] >= L'0' && token[3] <= L'9')
return VK_NUMPAD0 + token[3] - L'0';
if (token.size() >= 2 && token[0] == L'f')
{
wchar_t *tail{};
long n = wcstol(token.c_str() + 1, &tail, 10);
if (!*tail && n >= 1 && n <= 24) return static_cast<WORD>(VK_F1 + n - 1);
return 0;
}
for (const auto &[key, name] : namedKeys())
if (lower(name) == token) return static_cast<WORD>(key);
return 0;
}
WORD snippetKey(std::wstring_view name)
{
const auto token = lower(std::wstring(name));
static constexpr std::pair<std::wstring_view, WORD> modifiers[] = {
{L"shift", VK_LSHIFT}, {L"shiftl", VK_LSHIFT}, {L"shiftr", VK_RSHIFT},
{L"ctrl", VK_LCONTROL}, {L"ctrll", VK_LCONTROL}, {L"ctrlr", VK_RCONTROL},
{L"alt", VK_LMENU}, {L"altl", VK_LMENU}, {L"altr", VK_RMENU},
{L"win", VK_LWIN}, {L"winl", VK_LWIN}, {L"winr", VK_RWIN}};
for (const auto &[label, key] : modifiers)
if (label == token) return key;
if (token == L"return") return VK_RETURN;
// The old double-braced Enter marker is still an escape.
return token == L"enter" ? 0 : namedKey(token);
}
struct SnippetMarker
{
std::wstring_view name;
size_t length, depth;
};
std::optional<SnippetMarker> snippetMarker(std::wstring_view input)
{
if (!input.starts_with(L'{')) return {};
size_t depth = 1;
while (depth < 3 && depth < input.size() && input[depth] == L'{') ++depth;
const auto end = input.find_first_of(L"{}", depth);
if (end == input.npos || !input.substr(end).starts_with(std::wstring_view(L"}}}", depth)))
return {};
return SnippetMarker{input.substr(depth, end - depth), end + depth, depth};
}
std::optional<DWORD> snippetPause(std::wstring_view token)
{
constexpr std::wstring_view prefix = L"pause:";
constexpr DWORD maxPause = 10000;
if (!token.starts_with(prefix) || token.size() == prefix.size()) return {};
DWORD duration = 0;
for (wchar_t digit : token.substr(prefix.size()))
{
if (digit < L'0' || digit > L'9') return {};
duration = duration * 10 + (digit - L'0');
if (duration > maxPause) return {};
}
return duration;
}
} // namespace
std::wstring snippetKeyName(WORD key)
{
switch (key)
{
case VK_LSHIFT: return L"Shift";
case VK_RSHIFT: return L"ShiftR";
case VK_LCONTROL: return L"Ctrl";
case VK_RCONTROL: return L"CtrlR";
case VK_LMENU: return L"Alt";
case VK_RMENU: return L"AltR";
case VK_LWIN: return L"Win";
case VK_RWIN: return L"WinR";
default: return Hotkey{0, key}.format();
}
}
std::wstring formatSnippetInsertion(SnippetInsertion type, std::wstring_view parameter)
{
if (type == SnippetInsertion::Cursor) return L"{cursor}";
if (type == SnippetInsertion::Enter) return L"{enter}";
if (type == SnippetInsertion::Pause)
{
auto pause = L"pause:" + std::wstring(parameter);
return snippetPause(pause) ? L"{" + pause + L"}" : std::wstring{};
}
const bool chord = type == SnippetInsertion::Chord;
if (!chord && type != SnippetInsertion::Key) return {};
std::wstring text;
std::vector<WORD> keys;
while (true)
{
const auto end = parameter.find(L'+');
const auto token = parameter.substr(0, end);
const auto first = token.find_first_not_of(L" \t");
if (first == token.npos) return {};
auto name = lower(std::wstring(token.substr(first, token.find_last_not_of(L" \t") - first + 1)));
if (name == L"enter") name = L"return";
const auto key = snippetKey(name);
if (!key || std::find(keys.begin(), keys.end(), key) != keys.end()) return {};
keys.push_back(key);
if (!text.empty()) text += L'+';
text += L"{{" + name + L"}}";
if (end == parameter.npos) break;
if (!chord) return {};
parameter.remove_prefix(end + 1);
}
return chord && keys.size() < 2 ? std::wstring{} : text;
}
Template parseTemplate(const std::wstring &text)
{
Template t;
std::wstring_view remaining(text);
size_t cursor = text.npos;
while (!remaining.empty())
{
const auto marker = snippetMarker(remaining);
if (!marker)
{
t.text += remaining.front();
remaining.remove_prefix(1);
continue;
}
const auto [name, length, depth] = *marker;
const auto pause = depth <= 2 ? snippetPause(name) : std::nullopt;
const WORD key = depth >= 2 ? snippetKey(name) : 0;
const bool legacyEscape = name == L"cursor" || name == L"enter";
if (depth == 1 && name == L"cursor")
{
cursor = t.text.size();
++t.cursors;
}
else if (depth == 1 && name == L"enter")
t.actions.push_back({t.text.size(), std::vector<WORD>{VK_RETURN}});
else if (depth == 1 && pause)
t.actions.push_back({t.text.size(), *pause});
else if (depth == 2 && key)
{
std::vector<WORD> keys{key};
remaining.remove_prefix(length);
while (remaining.starts_with(L'+'))
{
const auto next = snippetMarker(remaining.substr(1));
if (!next || next->depth != 2) break;
const WORD nextKey = snippetKey(next->name);
if (!nextKey) break;
if (std::find(keys.begin(), keys.end(), nextKey) == keys.end())
keys.push_back(nextKey);
remaining.remove_prefix(1 + next->length);
}
t.actions.push_back({t.text.size(), std::move(keys)});
continue;
}
else if ((depth >= 2 && legacyEscape) || (depth == 2 && pause) || (depth == 3 && key))
t.text += remaining.substr(1, length - 2);
else
t.text += remaining.substr(0, length);
remaining.remove_prefix(length);
}
if (cursor != text.npos)
t.suffix = t.text.substr(cursor);
// A leading action has historically followed replacement of the trigger.
// Keep that behavior while allowing actions between text segments.
const auto first = std::find_if(t.actions.begin(), t.actions.end(),
[](const SnippetAction &action) { return action.offset != 0; });
const auto firstText = first == t.actions.end() ? t.text.size() : first->offset;
for (auto it = t.actions.begin(); it != first; ++it)
it->offset = firstText;
return t;
}
std::wstring Hotkey::format() const
{
if (!key)
@@ -558,7 +349,32 @@ std::optional<Hotkey> Hotkey::parse(std::wstring s)
h.modifiers |= MOD_WIN;
else
{
if (h.key || !(h.key = namedKey(token))) return {};
if (h.key)
return {};
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
h.key = upper(token)[0];
else if (token.size() == 4 && token.substr(0, 3) == L"num" && token[3] >= L'0' &&
token[3] <= L'9')
h.key = VK_NUMPAD0 + token[3] - L'0';
else if (token.size() >= 2 && token[0] == L'f')
{
wchar_t *tail{};
long n = wcstol(token.c_str() + 1, &tail, 10);
if (*tail || n < 1 || n > 24)
return {};
h.key = VK_F1 + (UINT)n - 1;
}
else
{
for (auto &[key, name] : namedKeys())
if (lower(name) == token)
{
h.key = key;
break;
}
if (!h.key)
return {};
}
}
if (end == s.npos)
break;
@@ -633,14 +449,6 @@ 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)
+2 -59
View File
@@ -1,11 +1,8 @@
#pragma once
#include <cstdint>
#include <functional>
#include <map>
#include <optional>
#include <set>
#include <string>
#include <variant>
#include <vector>
#include <windows.h>
@@ -21,44 +18,23 @@ 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 SnippetAction
{
size_t offset;
std::variant<std::vector<WORD>, DWORD> value;
bool operator==(const SnippetAction &) const = default;
};
struct Template
{
std::wstring text, suffix;
std::vector<SnippetAction> actions;
int cursors = 0;
};
Template parseTemplate(const std::wstring &);
enum class SnippetInsertion { Cursor, Enter, Pause, Key, Chord };
std::wstring snippetKeyName(WORD);
std::wstring formatSnippetInsertion(SnippetInsertion, std::wstring_view parameter);
struct Hotkey
{
UINT modifiers{}, key{};
@@ -66,60 +42,28 @@ 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 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";
bool writeLog = true;
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"Win+V",
translit = L"Ctrl+Alt+Shift+T", undo = L"Ctrl+Alt+Shift+Z", clipboard = L"Ctrl+Shift+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
@@ -141,6 +85,5 @@ 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
-77
View File
@@ -1,77 +0,0 @@
#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
-495
View File
@@ -1,495 +0,0 @@
#include "google_drive.h"
#include "sync.h"
#include "mouse_buttons.h"
#include "json.hpp"
#include <algorithm>
#include <sstream>
#include <tuple>
namespace ks
{
namespace
{
using Json = nlohmann::json;
constexpr auto NativeFormat = "kswitcher-win32-drive-backup-v1";
constexpr auto PreviewFormat = "kswitcher-drive-backup-v1";
// Select fields explicitly so changes to native serialization cannot expand the backup.
constexpr const char *PortableFields[] = {
"convertLastWord", "switchSystemLayout", "autoCorrectLayout", "autoCorrectReplace", "autoCorrectTypos",
"autoCorrectReplacements", "autoCorrectMaxRank", "autoCorrectMinLength", "autoCorrectPrefixChars",
"autoCorrectSuffixChars", "autoCorrectLanguages", "autoCorrectNever", "autoCorrectExcludedApps",
"autoCorrectWords", "preventScreenLock", "toggleHotkey", "caseHotkey", "translitHotkey", "undoHotkey",
"clipboardHotkey", "screenshotHotkey", "filesHotkey", "screenshotAutoOpenEditor", "historyEnabled",
"maxItems", "maxTotalMegabytes", "maxImageMegabytes", "excludedApps", "useTesseract", "tesseractLanguages",
"layouts", "layoutHotkeys", "chatCycles", "appLanguageSets", "snippets", "mouseBindings",
"mouseProfileApplications", "disabledMouseProfiles", "customMouseEvents"
};
Bytes bytes(const Json &object)
{
const auto text = object.dump();
return {text.begin(), text.end()};
}
Json portableFields(const Json &source)
{
auto result = Json::object();
for (const auto *key : PortableFields)
if (source.contains(key)) result[key] = source.at(key);
return result;
}
bool machineLocalMouseAction(const Json &binding)
{
if (!binding.is_object() || binding.value("action", "") != "Launch application") return false;
return binding.at("executable").get<std::string>().find_first_of("\\/:") != std::string::npos;
}
void excludeMousePaths(Json &settings)
{
if (!settings.contains("mouseBindings")) return;
auto &profiles = settings.at("mouseBindings");
if (!profiles.is_object()) throw std::runtime_error("Invalid mouse profiles.");
for (auto &bindings : profiles)
{
if (!bindings.is_object()) throw std::runtime_error("Invalid mouse actions.");
for (auto action = bindings.begin(); action != bindings.end();)
{
if (machineLocalMouseAction(*action)) action = bindings.erase(action);
else ++action;
}
}
}
void preserveMousePaths(Json &settings, const Json &local)
{
if (!settings.contains("mouseBindings")) return;
for (const auto &[profile, bindings] : local.at("mouseBindings").items())
for (const auto &[event, action] : bindings.items())
{
if (!machineLocalMouseAction(action)) continue;
settings["mouseBindings"][profile][event] = action;
if (!settings.contains("mouseProfileApplications") ||
!settings.at("mouseProfileApplications").is_object())
throw std::runtime_error("Invalid mouse profile applications.");
auto &scopes = settings.at("mouseProfileApplications");
if (local.at("mouseProfileApplications").contains(profile))
scopes[profile] = local.at("mouseProfileApplications").at(profile);
else scopes.erase(profile);
if (local.at("customMouseEvents").contains(event) && !settings.at("customMouseEvents").contains(event))
settings["customMouseEvents"][event] = local.at("customMouseEvents").at(event);
auto &disabled = settings.at("disabledMouseProfiles");
if (!disabled.is_array()) throw std::runtime_error("Invalid disabled mouse profiles.");
const bool wasDisabled = std::find(local.at("disabledMouseProfiles").begin(),
local.at("disabledMouseProfiles").end(), profile) != local.at("disabledMouseProfiles").end();
const auto entry = std::find(disabled.begin(), disabled.end(), profile);
if (wasDisabled && entry == disabled.end()) disabled.push_back(profile);
if (!wasDisabled && entry != disabled.end()) disabled.erase(entry);
}
}
std::vector<std::string> list(const Json &value)
{
if (value.is_array()) return value.get<std::vector<std::string>>();
auto input = wide(value.get<std::string>());
std::replace(input.begin(), input.end(), L',', L' ');
std::wistringstream stream(input);
std::vector<std::string> result;
for (std::wstring item; stream >> item;) result.push_back(utf8(item));
return result;
}
std::string layoutId(const Json &value)
{
auto id = utf8(lower(wide(value.get<std::string>())));
if (id == "english" || id == "en" || id == "us" || id == "00000409") return "win:04090409";
if (id == "ukrainian" || id == "uk" || id == "ua" || id == "00000422") return "win:04220422";
if (id == "russian" || id == "ru" || id == "00000419") return "win:04190419";
if (id == "00000809") return "win:08090809";
return id;
}
Json layoutList(const Json &value)
{
auto result = Json::array();
for (const auto &id : list(value)) result.push_back(layoutId(id));
return result;
}
std::string appName(const Json &value)
{
return utf8(snippetAppName(wide(value.get<std::string>())));
}
void previewLayouts(const Json &options, Json &result)
{
if (options.contains("layouts"))
{
auto &cycle = result["layouts"] = Json::array();
auto &keys = result["layoutHotkeys"] = Json::array();
for (const auto &row : options.at("layouts").get<Json::array_t>())
{
auto id = layoutId(row.at("layout"));
if (row.value("included", true)) cycle.push_back(id);
keys.push_back({{"layoutId", id}, {"hotkey", row.value("shortcut", "")}});
}
}
else if (options.contains("legacySettings"))
{
const auto &legacy = options.at("legacySettings");
if (legacy.contains("layouts")) result["layouts"] = layoutList(legacy.at("layouts"));
if (legacy.contains("layoutHotkeys"))
{
auto &keys = result["layoutHotkeys"] = Json::array();
for (const auto &row : legacy.at("layoutHotkeys").get<Json::array_t>())
keys.push_back({{"layoutId", layoutId(row.at("layoutId"))}, {"hotkey", row.at("hotkey").get<std::string>()}});
}
}
if (options.contains("appLanguages"))
{
auto &profiles = result["appLanguageSets"] = Json::object();
for (const auto &row : options.at("appLanguages").get<Json::array_t>())
{
auto app = appName(row.at("app"));
auto cycle = layoutList(row.at("languages"));
if (!app.empty() && !cycle.empty())
profiles[app] = {{"applications", Json::array({app})}, {"languages", cycle}};
}
}
if (options.contains("chatLanguages"))
{
auto &profiles = result["chatCycles"] = Json::object();
for (const auto &row : options.at("chatLanguages").get<Json::array_t>())
{
auto app = appName(row.at("app"));
auto contact = row.at("contact").get<std::string>();
auto cycle = layoutList(row.at("languages"));
if ((app == "telegram" || app == "telegram-web" || app == "ms-teams" || app == "viber") &&
!contact.empty() && !cycle.empty())
profiles[app + "\n" + contact] = cycle;
}
}
}
void previewSnippets(const Json &settings, const Json &options, Json &result)
{
using SnippetKey = std::tuple<std::string, std::string, std::set<std::string>>;
auto keyFor = [](const Json &row)
{
std::set<std::string> apps;
if (row.contains("apps") && row.value("scoped", true))
for (const auto &app : list(row.at("apps"))) apps.insert(appName(app));
return SnippetKey{row.at("trigger").get<std::string>(), row.at("replacement").get<std::string>(), std::move(apps)};
};
const auto optionRows = options.value("snippets", Json::array()).get<Json::array_t>();
std::map<SnippetKey, std::string> ids;
for (const auto &row : optionRows)
if (row.value("enabled", false) && row.contains("id"))
ids.emplace(keyFor(row), row.at("id").get<std::string>());
Json::array_t rows;
if (settings.contains("snippets") && !settings.at("snippets").is_null())
rows = settings.at("snippets").get<Json::array_t>();
else if (options.contains("snippets"))
rows = optionRows;
else if (settings.contains("snippet"))
rows.push_back(settings.at("snippet"));
else
return;
auto &snippets = result["snippets"] = Json::array();
for (const auto &row : rows)
{
if (!row.value("enabled", false)) continue;
auto key = keyFor(row);
const auto &[trigger, replacement, apps] = key;
Json item{{"trigger", trigger}, {"text", replacement}};
if (!apps.empty()) item["apps"] = apps;
if (row.value("scoped", false) && (!item.contains("apps") || item.at("apps").empty()))
throw std::runtime_error("A scoped snippet needs an application.");
if (row.contains("id")) item["id"] = row.at("id").get<std::string>();
else if (const auto id = ids.find(key); id != ids.end()) item["id"] = id->second;
snippets.push_back(std::move(item));
}
}
void previewMouse(const Json &settings, const Json &options, Json &result)
{
if (!options.contains("mouseProfiles") && !options.contains("mouseActions") &&
!options.contains("mouseEvents") && !settings.contains("mouse")) return;
auto &bindings = result["mouseBindings"] = Json::object();
auto &scopes = result["mouseProfileApplications"] = Json::object();
auto &disabled = result["disabledMouseProfiles"] = Json::array();
auto &custom = result["customMouseEvents"] = Json::object();
constexpr const char *events[] = {"Left click", "Right click", "Middle click", "First side button",
"Second side button", "Left double-click", "Right double-click", "Middle double-click",
"Wheel up", "Wheel down", "Wheel left", "Wheel right"};
static_assert(std::size(events) == std::size(MouseEvents));
std::map<std::string, std::string> signals, profiles{{"*", "*"}, {"default", "*"}};
for (size_t i = 0; i < std::size(events); ++i) signals[events[i]] = utf8(MouseEvents[i]);
for (const auto &row : options.value("mouseEvents", Json::array()).get<Json::array_t>())
{
auto signal = row.value("signal", "");
if (!signals.contains(signal) || !signal.starts_with("Wheel ")) continue;
auto name = row.at("name").get<std::string>();
custom[signal] = name;
signals[name] = signal;
}
for (const auto &row : options.value("mouseProfiles", Json::array()).get<Json::array_t>())
{
auto id = row.at("id").get<std::string>();
auto name = row.at("name").get<std::string>();
auto apps = list(row.value("apps", Json("")));
for (auto &app : apps) app = appName(app);
if (id == "*" || (id == "default" && apps.empty())) continue;
if (id == name && !id.starts_with("name:") && apps.empty() &&
row.value("enabled", true) && validMouseApplication(wide(id)))
{
profiles[id] = id;
continue;
}
auto profile = "name:" + name;
profiles[id] = profile;
bindings[profile] = Json::object();
scopes[profile] = apps;
if (!row.value("enabled", true)) disabled.push_back(profile);
}
auto add = [&](const std::string &profile, const std::string &event, const Json &row)
{
constexpr const char *actions[] = {"Unassigned", "Shortcut", "Back", "Forward", "VolumeUp",
"VolumeDown", "Mute", "Launch"};
static_assert(std::size(actions) == std::size(MouseActions));
auto name = row.at("action").get<std::string>();
auto match = std::find(std::begin(actions), std::end(actions), name);
if (match == std::end(actions)) throw std::runtime_error("Unknown mouse action.");
const auto type = static_cast<MouseActionType>(match - std::begin(actions));
Json binding{{"action", utf8(MouseActions[static_cast<size_t>(type)])}};
if (type == MouseActionType::Shortcut) binding["shortcut"] = row.at("shortcut").get<std::string>();
if (type == MouseActionType::Launch) binding["executable"] = row.at("executable").get<std::string>();
if (isMouseVolumeStep(type)) binding["volumeStep"] = row.value("step", Json(DefaultMouseVolumeStep));
auto apps = list(row.value("apps", Json("")));
for (auto &app : apps) app = appName(app);
if (!apps.empty() && !profile.starts_with("name:")) binding["applications"] = apps;
if (event.starts_with("Wheel ") && !custom.contains(event)) custom[event] = event;
if (!machineLocalMouseAction(binding)) bindings[profile][event] = std::move(binding);
};
const auto rows = options.value("mouseActions", Json::array()).get<Json::array_t>();
for (const auto &row : rows)
{
auto event = row.at("event").get<std::string>();
if (signals.contains(event)) add(profiles.at(row.at("profile").get<std::string>()), signals.at(event), row);
}
const auto mouse = settings.value("mouse", Json::object());
if (rows.empty() && mouse.value("enabled", false))
{
add("*", "XButton1", {{"action", mouse.value("default_action", "Unassigned")}});
auto app = appName(mouse.value("application", ""));
if (!app.empty()) add(app, "XButton1", {{"action", mouse.value("application_action", "Unassigned")}});
}
}
Json previewFields(const Json &profile, const Json &local)
{
const auto &options = profile.at("options");
const auto &settings = profile.at("settings");
if (!options.is_object() || !settings.is_object() || (options.empty() && settings.empty()))
throw std::runtime_error("Invalid preview profile.");
auto result = Json::object();
constexpr std::pair<const char *, const char *> fields[] = {
{"general.conversion.recent", "convertLastWord"}, {"general.conversion.switchLayout", "switchSystemLayout"},
{"general.correction.maxRank", "autoCorrectMaxRank"}, {"general.correction.minLength", "autoCorrectMinLength"},
{"general.correction.prefix", "autoCorrectPrefixChars"}, {"general.correction.suffix", "autoCorrectSuffixChars"},
{"general.correction.autoReplace", "autoCorrectReplace"}, {"general.correction.autoTypos", "autoCorrectTypos"},
{"general.integration.awake", "preventScreenLock"},
{"shortcuts.key-bindings.toggle", "toggleHotkey"}, {"shortcuts.key-bindings.case", "caseHotkey"},
{"shortcuts.key-bindings.transliterate", "translitHotkey"}, {"shortcuts.key-bindings.undo", "undoHotkey"},
{"shortcuts.key-bindings.clipboard", "clipboardHotkey"}, {"shortcuts.key-bindings.capture", "screenshotHotkey"},
{"shortcuts.key-bindings.files", "filesHotkey"}, {"shortcuts.capture.openEditor", "screenshotAutoOpenEditor"},
{"clipboard.history.record", "historyEnabled"}, {"clipboard.history.items", "maxItems"},
{"clipboard.history.capacity", "maxTotalMegabytes"}, {"clipboard.history.perItem", "maxImageMegabytes"},
{"clipboard.ocr.useTesseract", "useTesseract"}, {"clipboard.ocr.tesseractLanguages", "tesseractLanguages"}
};
for (const auto &[from, to] : fields)
if (options.contains(from)) result[to] = options.at(from);
for (const auto &[from, to] : {std::pair{"general.correction.dictionaryLanguages", "autoCorrectLanguages"},
{"general.correction.autoExcluded", "autoCorrectExcludedApps"}, {"clipboard.history.excluded", "excludedApps"}})
if (options.contains(from)) result[to] = list(options.at(from));
if (options.contains("general.correction.autoReplacements"))
{
auto &pairs = result["autoCorrectReplacements"] = Json::object();
std::istringstream lines(options.at("general.correction.autoReplacements").get<std::string>());
for (std::string line; std::getline(lines, line);)
{
auto split = line.find('=');
if (line.find_first_not_of(" \t\r") == line.npos) continue;
if (split == line.npos) throw std::runtime_error("Invalid automatic replacement.");
auto trim = [](std::string text)
{
const auto first = text.find_first_not_of(" \t\r");
return first == text.npos ? std::string{} :
text.substr(first, text.find_last_not_of(" \t\r") - first + 1);
};
if (!pairs.emplace(trim(line.substr(0, split)), trim(line.substr(split + 1))).second)
throw std::runtime_error("Duplicate automatic replacement.");
}
}
if (settings.contains("autocorrect")) result["autoCorrectLayout"] = settings.at("autocorrect");
const auto dictionary = settings.value("personal_dictionary", Json::object());
auto words = local.at("autoCorrectWords");
bool hasWords = false;
for (const auto &[key, language] : {std::pair{"en", "english"}, {"uk", "ukrainian"}, {"ru", "russian"}})
{
const std::string field = std::string("general.correction.words.") + key;
if (options.contains(field)) words[key] = list(options.at(field));
else if (dictionary.contains(language)) words[key] = dictionary.at(language).get<std::vector<std::string>>();
else continue;
hasWords = true;
}
if (hasWords) result["autoCorrectWords"] = std::move(words);
if (options.contains("general.correction.autoNever"))
result["autoCorrectNever"] = list(options.at("general.correction.autoNever"));
else if (dictionary.contains("never")) result["autoCorrectNever"] = list(dictionary.at("never"));
previewLayouts(options, result);
previewSnippets(settings, options, result);
previewMouse(settings, options, result);
if (result.empty()) throw std::runtime_error("No supported preview settings.");
return result;
}
void checkLayouts(const Json &fields, const std::vector<Layout> &layouts)
{
auto check = [&](const std::string &id)
{
const auto w = wide(id);
if (std::none_of(layouts.begin(), layouts.end(), [&](const auto &layout) { return layout.id == w; }))
throw std::runtime_error("Install the keyboard layouts used by this backup in Windows, then try restoring again.");
};
if (fields.contains("layouts"))
for (const auto &id : fields.at("layouts").get<std::vector<std::string>>()) check(id);
if (fields.contains("layoutHotkeys"))
for (const auto &binding : fields.at("layoutHotkeys").get<Json::array_t>())
if (!binding.at("hotkey").get<std::string>().empty()) check(binding.at("layoutId").get<std::string>());
}
void allowRestoredSnippets(Json &settings)
{
std::set<std::string> ids;
for (const auto &item : settings.at("snippets").get<Json::array_t>())
{
auto id = item.value("id", "");
if (id.empty() && (!item.contains("apps") || item.at("apps").empty()))
id = utf8(snippetId({wide(item.at("trigger").get<std::string>()), {}, {}, {}}));
if (!id.empty()) ids.insert(std::move(id));
}
auto tombstones = settings.at("snippetTombstones").get<std::vector<std::string>>();
std::erase_if(tombstones, [&](const auto &id) { return ids.contains(id); });
settings["snippetTombstones"] = std::move(tombstones);
}
Json mergeDriveFields(Json fields, const Json &original)
{
excludeMousePaths(fields);
auto local = original;
local.update(fields);
if (local.contains("filesHotkey") && local.at("filesHotkey").is_null()) local.erase("filesHotkey");
if (fields.contains("mouseBindings")) preserveMousePaths(local, original);
if (fields.contains("snippets")) allowRestoredSnippets(local);
return local;
}
}
Bytes sharedDriveSettings(const Settings &saved)
{
const auto source = Json::parse(sharedSyncSettings(saved));
auto profile = portableFields(source);
excludeMousePaths(profile);
auto &bindings = profile.at("mouseBindings");
for (auto it = bindings.begin(); it != bindings.end();)
// Named profiles can retain their application scope without actions.
if (it->empty() && !isNamedMouseProfile(wide(it.key()))) it = bindings.erase(it);
else ++it;
if (!profile.contains("filesHotkey")) profile["filesHotkey"] = nullptr;
for (const auto *field : {"format", "schemaVersion", "snippetTombstones"}) profile[field] = source.at(field);
return bytes(profile);
}
Settings restoreSharedDriveSettings(const Bytes &shared, const Settings &local, const std::vector<Layout> &layouts)
{
const auto source = Json::parse(shared);
if (!source.is_object() || source.value("format", "") != "kswitcher-settings" ||
source.value("schemaVersion", 0) != 1 || source.size() != std::size(PortableFields) + 3 ||
!source.contains("snippetTombstones"))
throw std::runtime_error("Invalid Google Drive synchronization profile.");
auto fields = portableFields(source);
if (fields.size() != std::size(PortableFields))
throw std::runtime_error("Incomplete Google Drive synchronization profile.");
fields["snippetTombstones"] = source.at("snippetTombstones");
checkLayouts(fields, layouts);
return decodeSettings(bytes(mergeDriveFields(std::move(fields), Json::parse(encodeSettings(local)))), layouts);
}
Bytes encodeDriveBackup(const Settings &saved)
{
auto profile = portableFields(Json::parse(encodeSettings(saved)));
if (!profile.contains("filesHotkey")) profile["filesHotkey"] = nullptr;
excludeMousePaths(profile);
auto result = bytes({{"format", NativeFormat}, {"settings", std::move(profile)}});
if (result.size() > GoogleDriveBackupLimit) throw std::runtime_error("Saved settings exceed the 2 MiB backup limit.");
return result;
}
Settings restoreDriveBackup(const Bytes &backup, const Settings &draft, const std::vector<Layout> &layouts)
{
if (backup.size() > GoogleDriveBackupLimit) throw std::runtime_error("This Drive backup exceeds the 2 MiB limit.");
// Limit nesting before the parser allocates a tree from downloaded data.
const auto document = Json::parse(backup, [](int depth, Json::parse_event_t, Json &)
{
if (depth > 32) throw std::runtime_error("This Drive backup is corrupt.");
return true;
}, false);
if (!document.is_object() || !document.contains("format") || !document.at("format").is_string())
throw std::runtime_error("This Drive backup is corrupt.");
const auto format = document.at("format").get<std::string>();
if (format != NativeFormat && format != PreviewFormat)
throw std::runtime_error("This Drive backup format is unsupported.");
const auto original = Json::parse(encodeSettings(draft));
auto local = original;
Json fields;
try
{
if (format == NativeFormat)
{
const auto &source = document.at("settings");
if (!source.is_object()) throw std::runtime_error("Invalid settings.");
for (const auto *key : PortableFields)
if (!source.contains(key)) throw std::runtime_error("Incomplete settings.");
fields = portableFields(source);
}
else fields = previewFields(document.at("profile"), local);
local = mergeDriveFields(fields, original);
}
catch (const std::exception &)
{
throw std::runtime_error("This Drive backup contains invalid settings.");
}
try
{
checkLayouts(fields, layouts);
}
catch (const Json::exception &)
{
throw std::runtime_error("This Drive backup contains invalid layouts or shortcuts.");
}
try
{
return decodeSettings(bytes(local), layouts);
}
catch (const std::exception &)
{
throw std::runtime_error("This Drive backup contains settings that are invalid or conflict with this PC's settings.");
}
}
}
-523
View File
@@ -1,523 +0,0 @@
#include "files_archive.h"
#include "files_win32_directory.h"
#include "files_win32_replace.h"
#include <objbase.h>
#include <archive.h>
#include <archive_entry.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <memory>
#include <optional>
#include <set>
#include <stdexcept>
#include <string_view>
namespace ks::files
{
namespace fs=std::filesystem;
bool ArchiveNameOrder::operator()(const fs::path &left,const fs::path &right) const
{
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)==CSTR_LESS_THAN;
}
bool isArchivePath(const fs::path &path)
{
const auto extension=path.extension();
return CompareStringOrdinal(extension.c_str(),-1,L".zip",-1,TRUE)==CSTR_EQUAL ||
CompareStringOrdinal(extension.c_str(),-1,L".7z",-1,TRUE)==CSTR_EQUAL;
}
namespace
{
using ArchiveReader=std::unique_ptr<archive,decltype(&archive_read_free)>;
using ArchiveWriter=std::unique_ptr<archive,decltype(&archive_write_free)>;
constexpr std::int64_t archiveEpochOffset=11644473600, archiveTicksPerSecond=10000000;
constexpr char unsafePath[]="The archive contains an unsafe or conflicting path.";
constexpr char encryptedArchive[]="This archive requires a password. Password-protected entries cannot be opened in Files.";
uint64_t archiveTime(bool present,int64_t seconds,long nanos)
{
if(!present || seconds < -archiveEpochOffset || seconds>=INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)
return 0;
return static_cast<uint64_t>((seconds+archiveEpochOffset)*archiveTicksPerSecond+nanos/100);
}
struct ArchiveFileHandle
{
HANDLE value=INVALID_HANDLE_VALUE;
explicit ArchiveFileHandle(HANDLE handle) : value(handle)
{
if(value==INVALID_HANDLE_VALUE) throw std::system_error(GetLastError(),std::system_category());
}
ArchiveFileHandle(const ArchiveFileHandle &)=delete;
ArchiveFileHandle &operator=(const ArchiveFileHandle &)=delete;
~ArchiveFileHandle() {CloseHandle(value);}
};
[[noreturn]] void archiveError(archive *reader)
{
const auto *error=archive_error_string(reader);
std::string detail=error?error:"";
std::transform(detail.begin(),detail.end(),detail.begin(),
[](unsigned char ch){return static_cast<char>(std::tolower(ch));});
if(detail.find("password")!=detail.npos || detail.find("passphrase")!=detail.npos ||
detail.find("encrypted")!=detail.npos) throw std::runtime_error(encryptedArchive);
throw std::runtime_error("Could not read the ZIP or 7z archive.");
}
ArchiveReader openArchive(const fs::path &file)
{
ArchiveReader reader(archive_read_new(),archive_read_free);
if(!reader) throw std::runtime_error("Could not create the archive reader.");
if(archive_read_support_format_zip(reader.get())!=ARCHIVE_OK ||
archive_read_support_format_7zip(reader.get())!=ARCHIVE_OK ||
archive_read_open_filename_w(reader.get(),file.c_str(),64*1024)!=ARCHIVE_OK)
archiveError(reader.get());
return reader;
}
std::pair<fs::path,ArchiveEntry> decodeEntry(archive_entry *entry)
{
const auto *wide=archive_entry_pathname_w(entry);
std::wstring name=wide?wide:L"";
if(name.empty() || name.front()==L'/' || name.front()==L'\\')
throw std::runtime_error(unsafePath);
std::replace(name.begin(),name.end(),L'/',L'\\');
const auto type=archive_entry_filetype(entry);
const bool folder=type==AE_IFDIR;
if((!folder && type!=AE_IFREG) || archive_entry_hardlink_w(entry) || archive_entry_symlink_w(entry))
throw std::runtime_error("The archive contains a link or an unsupported entry type.");
fs::path relative;
for(size_t start=0;start<name.size();)
{
const auto end=name.find(L'\\',start);
const auto component=std::wstring_view(name).substr(start,end==name.npos?end:end-start);
if(component!=L".")
{
if(component.size()>255 || !validWindowsFileName(component))
throw std::runtime_error(unsafePath);
relative/=component;
}
if(end==name.npos) break;
start=end+1;
}
if(relative.empty() && !folder) throw std::runtime_error(unsafePath);
const auto size=archive_entry_size(entry);
if(size<0 || (!folder && !archive_entry_size_is_set(entry)))
throw std::runtime_error("The archive entry has an invalid size.");
ArchiveEntry metadata{
static_cast<uint64_t>(size),
archiveTime(archive_entry_mtime_is_set(entry),archive_entry_mtime(entry),archive_entry_mtime_nsec(entry)),
folder,archive_entry_is_encrypted(entry)!=0};
metadata.created=archiveTime(archive_entry_birthtime_is_set(entry),archive_entry_birthtime(entry),
archive_entry_birthtime_nsec(entry));
metadata.accessed=archiveTime(archive_entry_atime_is_set(entry),archive_entry_atime(entry),archive_entry_atime_nsec(entry));
if(const auto *owner=archive_entry_uname_w(entry)) metadata.owner=owner;
return {relative,std::move(metadata)};
}
void registerEntry(ArchiveEntries &entries,const fs::path &path,const ArchiveEntry &entry)
{
if(path.empty()) return;
const auto [existing,inserted]=entries.try_emplace(path,entry);
if(!inserted)
{
if(existing->first.native()!=path.native() || !entry.directory || !existing->second.directory ||
!existing->second.implicit) throw std::runtime_error(unsafePath);
existing->second=entry;
}
for(auto parent=path.parent_path();!parent.empty();parent=parent.parent_path())
{
const auto [item,fresh]=entries.try_emplace(parent,ArchiveEntry{.directory=true,.implicit=true});
if(fresh) continue;
if(!item->second.directory || item->first.native()!=parent.native()) throw std::runtime_error(unsafePath);
break;
}
}
template<class Visit>
ArchiveEntries walkArchive(const fs::path &file,const Visit &visit)
{
auto reader=openArchive(file);
ArchiveEntries entries;
for(;;)
{
archive_entry *raw=nullptr;
const auto status=archive_read_next_header(reader.get(),&raw);
if(status==ARCHIVE_EOF) return entries;
if(status!=ARCHIVE_OK) archiveError(reader.get());
auto [path,entry]=decodeEntry(raw);
registerEntry(entries,path,entry);
if(!visit(reader.get(),raw,path,entry)) throw std::system_error(ERROR_CANCELLED,std::system_category());
}
}
void writeMember(archive *reader,const ArchiveEntry &entry,const fs::path &output,uint64_t limit,
const ArchiveProgress &progress)
{
if(entry.encrypted) throw std::runtime_error(encryptedArchive);
if(entry.size>limit) throw std::runtime_error("The archive entry is too large to preview.");
const ArchiveFileHandle owned(CreateFileW(output.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,nullptr));
std::array<char,64*1024> buffer{};
uint64_t done=0;
for(;;)
{
if(progress && !progress(done,entry.size)) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto size=archive_read_data(reader,buffer.data(),buffer.size());
if(size<0) archiveError(reader);
if(size==0) break;
if(static_cast<uint64_t>(size)>entry.size-done)
throw std::runtime_error("The archive entry exceeds its declared size.");
DWORD written=0;
if(!WriteFile(owned.value,buffer.data(),static_cast<DWORD>(size),&written,nullptr) ||
written!=static_cast<DWORD>(size))
throw std::system_error(GetLastError(),std::system_category());
done+=written;
}
if(done!=entry.size) throw std::runtime_error("The archive entry is incomplete.");
if(entry.modified)
{
const FILETIME time{static_cast<DWORD>(entry.modified),static_cast<DWORD>(entry.modified>>32)};
if(!SetFileTime(owned.value,nullptr,nullptr,&time))
throw std::system_error(GetLastError(),std::system_category());
}
}
}
ArchiveEntries readArchive(const fs::path &file,std::stop_token stop)
{
return walkArchive(file,[&](auto *,auto *,const auto &,const auto &){return !stop.stop_requested();});
}
ArchiveEntry readArchiveMember(const fs::path &file,const fs::path &member,const fs::path &output,
uint64_t limit,const ArchiveProgress &progress)
{
std::optional<ArchiveEntry> found;
walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry)
{
if(progress && !progress(found?found->size:0,found?found->size:0)) return false;
if(!entry.directory && path==member)
{
writeMember(reader,entry,output,limit,progress);
found=entry;
}
return true;
});
if(!found) throw std::runtime_error("The archive entry is no longer available.");
return *found;
}
void extractArchiveSelection(const fs::path &file,const fs::path &directory,const std::vector<fs::path> &selection,
const fs::path &staging,const ArchiveProgress &progress)
{
const std::set<fs::path> selected(selection.begin(),selection.end());
for(const auto &path:selected)
if(path.empty() || path.parent_path()!=directory) throw std::runtime_error(unsafePath);
const auto wanted=[&](const fs::path &path)
{
for(auto item=path;!item.empty() && item!=directory;item=item.parent_path())
if(selected.contains(item)) return true;
return false;
};
const auto entries=walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry)
{
if(progress && !progress(0,0)) return false;
if(!wanted(path)) return true;
const auto output=staging/path.lexically_relative(directory);
fs::create_directories(entry.directory?output:output.parent_path());
if(!entry.directory) writeMember(reader,entry,output,UINT64_MAX,progress);
return true;
});
for(const auto &path:selected)
if(!entries.contains(path)) throw std::runtime_error("A selected archive entry is no longer available.");
}
namespace
{
BY_HANDLE_FILE_INFORMATION archiveFileInfo(HANDLE file)
{
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file,&info)) throw std::system_error(GetLastError(),std::system_category());
return info;
}
uint64_t archiveFileSize(const BY_HANDLE_FILE_INFORMATION &info)
{
return (uint64_t(info.nFileSizeHigh)<<32)|info.nFileSizeLow;
}
bool sameArchiveFile(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
{
return sameFileIdentity(left,right) && archiveFileSize(left)==archiveFileSize(right) &&
CompareFileTime(&left.ftLastWriteTime,&right.ftLastWriteTime)==0;
}
struct ArchiveTemporaryFile
{
fs::path directory, file;
explicit ArchiveTemporaryFile(const fs::path &parent)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Could not prepare a temporary archive.");
directory=parent/(L".ks-files-pack-"+std::wstring(name));
file=directory/L"archive";
if(!fs::create_directory(directory)) throw std::runtime_error("Could not prepare a temporary archive.");
}
~ArchiveTemporaryFile()
{
std::error_code error;
fs::remove(file,error);
fs::remove(directory,error);
}
};
bool isZip(const fs::path &file)
{
return CompareStringOrdinal(file.extension().c_str(),-1,L".zip",-1,TRUE)==CSTR_EQUAL;
}
HANDLE lockArchiveFolder(const fs::path &directory)
{
const auto lock=directory/L".ks-files-archive-write.lock";
const HANDLE handle=CreateFileW(lock.c_str(),GENERIC_WRITE|DELETE,0,nullptr,CREATE_NEW,
FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr);
if(handle!=INVALID_HANDLE_VALUE) return handle;
const DWORD error=GetLastError();
if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS || error==ERROR_SHARING_VIOLATION)
throw std::runtime_error("Another archive operation is active in this folder.");
throw std::system_error(error,std::system_category());
}
void checkArchiveWrite(int status)
{
if(status!=ARCHIVE_OK) throw std::runtime_error("Could not create the ZIP or 7z data.");
}
ArchiveWriter openArchiveWriter(const fs::path &file,bool zip)
{
ArchiveWriter writer(archive_write_new(),archive_write_free);
if(!writer) throw std::runtime_error("Could not create the archive writer.");
checkArchiveWrite(zip?archive_write_set_format_zip(writer.get()):archive_write_set_format_7zip(writer.get()));
checkArchiveWrite(archive_write_set_options(writer.get(),zip?"hdrcharset=UTF-8":"compression=lzma2"));
checkArchiveWrite(archive_write_open_filename_w(writer.get(),file.c_str()));
return writer;
}
struct ArchiveInput
{
fs::path source;
BY_HANDLE_FILE_INFORMATION info;
};
using ArchiveInputs=std::map<fs::path,ArchiveInput,ArchiveNameOrder>;
void addArchiveInput(ArchiveInputs &inputs,const fs::path &source,const fs::path &member,const fs::path &target,
const std::function<void()> &checkCanceled)
{
checkCanceled();
if(member.empty() || member.filename().native().size()>255 || !validWindowsFileName(member.filename().native()))
throw std::runtime_error("A selected file has a name that cannot be stored safely in the archive.");
std::error_code error;
if(fs::equivalent(source,target,error)) throw std::runtime_error("The archive cannot contain itself.");
if(fs::equivalent(source,target.parent_path(),error))
throw std::runtime_error("Choose an archive location outside the selected folders.");
const ArchiveFileHandle file(CreateFileW(source.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE,
nullptr,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr));
const auto info=archiveFileInfo(file.value);
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT)
throw std::runtime_error("The selection contains a Windows link or reparse point.");
if(!inputs.emplace(member,ArchiveInput{source,info}).second)
throw std::runtime_error("The selection contains conflicting names.");
if(!(info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) return;
for(const auto &child:fs::directory_iterator(source))
addArchiveInput(inputs,child.path(),member/child.path().filename(),target,checkCanceled);
}
template<class Read>
void transferArchiveData(archive *writer,uint64_t size,const Read &read,const std::function<void(uint64_t)> &advance)
{
std::array<char,64*1024> buffer{};
uint64_t bytes=0;
while(bytes<size)
{
const auto count=read(buffer.data(),static_cast<DWORD>(std::min<uint64_t>(size-bytes,buffer.size())));
if(!count) throw std::runtime_error("An archive input ended before its declared size.");
if(archive_write_data(writer,buffer.data(),count)!=static_cast<la_ssize_t>(count))
throw std::runtime_error("Could not write archive contents.");
bytes+=count;
advance(count);
}
if(read(buffer.data(),1)!=0) throw std::runtime_error("An archive input changed size while it was being written.");
checkArchiveWrite(archive_write_finish_entry(writer));
}
void archiveLocalInput(archive *writer,const fs::path &path,const ArchiveInput &input,
const std::function<void(uint64_t)> &advance)
{
const bool folder=(input.info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
std::unique_ptr<archive_entry,decltype(&archive_entry_free)> entry(archive_entry_new(),archive_entry_free);
if(!entry) throw std::runtime_error("Could not create an archive entry.");
const auto name=path.generic_wstring();
archive_entry_copy_pathname_w(entry.get(),name.c_str());
archive_entry_set_filetype(entry.get(),folder?AE_IFDIR:AE_IFREG);
archive_entry_set_perm(entry.get(),folder?0755:0644);
const uint64_t size=folder?0:archiveFileSize(input.info);
archive_entry_set_size(entry.get(),static_cast<la_int64_t>(size));
const auto stamp=(uint64_t(input.info.ftLastWriteTime.dwHighDateTime)<<32)|input.info.ftLastWriteTime.dwLowDateTime;
archive_entry_set_mtime(entry.get(),static_cast<int64_t>(stamp/archiveTicksPerSecond)-archiveEpochOffset,
static_cast<long>((stamp%archiveTicksPerSecond)*100));
if(folder)
{
checkArchiveWrite(archive_write_header(writer,entry.get()));
checkArchiveWrite(archive_write_finish_entry(writer));
return;
}
const ArchiveFileHandle file(CreateFileW(input.source.c_str(),GENERIC_READ,FILE_SHARE_READ,nullptr,OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_SEQUENTIAL_SCAN,nullptr));
const auto current=archiveFileInfo(file.value);
if((current.dwFileAttributes&(FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY)) ||
!sameArchiveFile(input.info,current))
throw std::runtime_error("A selected file changed before it could be added.");
checkArchiveWrite(archive_write_header(writer,entry.get()));
transferArchiveData(writer,size,[&](char *buffer,DWORD goal)
{
DWORD used=0;
if(!ReadFile(file.value,buffer,goal,&used,nullptr))
throw std::system_error(GetLastError(),std::system_category());
return used;
},advance);
}
}
void writeArchive(const fs::path &file,ArchiveWriteMode mode,const fs::path &directory,
const std::vector<fs::path> &sources,const ArchiveProgress &progress)
{
if(!isArchivePath(file)) throw std::runtime_error("Files can write ZIP and 7z archives.");
if(!file.is_absolute() || !validWindowsFileName(file.filename().native()) || sources.empty())
throw std::runtime_error("Select local files and enter a valid archive name.");
for(const auto &part:directory)
if(!validWindowsFileName(part.native())) throw std::runtime_error(unsafePath);
const bool zip=isZip(file);
const bool updating=mode==ArchiveWriteMode::update;
if(!updating && !directory.empty()) throw std::runtime_error("Create a new archive at its root.");
if(!updating && GetFileAttributesW(file.c_str())!=INVALID_FILE_ATTRIBUTES)
throw std::runtime_error("A file or folder with this archive name already exists.");
uint64_t done=0, total=0;
const auto checkCanceled=[&]
{
if(progress && !progress(done,total)) throw std::system_error(ERROR_CANCELLED,std::system_category());
};
const auto advance=[&](uint64_t bytes) {done+=bytes;checkCanceled();};
const auto plan=[&](uint64_t bytes)
{
if(UINT64_MAX-total<bytes) throw std::runtime_error("The selection is too large to archive.");
total+=bytes;
};
ArchiveInputs inputs;
for(const auto &source:sources)
{
if(!source.is_absolute()) throw std::runtime_error("Select files from a local folder.");
addArchiveInput(inputs,source,directory/source.filename(),file,checkCanceled);
}
const ArchiveFileHandle lock(lockArchiveFolder(file.parent_path()));
std::optional<ArchiveFileHandle> original;
BY_HANDLE_FILE_INFORMATION originalInfo{};
ArchiveEntries existing;
if(updating)
{
original.emplace(CreateFileW(file.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT,nullptr));
originalInfo=archiveFileInfo(original->value);
if(originalInfo.dwFileAttributes&(FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_READONLY))
throw std::runtime_error("This archive is read-only or is a Windows link.");
existing=walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry)
{
checkCanceled();
const int expected=zip?ARCHIVE_FORMAT_ZIP:ARCHIVE_FORMAT_7ZIP;
if((archive_format(reader)&ARCHIVE_FORMAT_BASE_MASK)!=expected)
throw std::runtime_error("The archive contents do not match its ZIP or 7z extension.");
if(entry.encrypted) throw std::runtime_error("Password-protected archives cannot be updated in Files.");
if(!entry.directory && !inputs.contains(path)) plan(entry.size);
return true;
});
if(!directory.empty())
{
const auto parent=existing.find(directory);
if(parent==existing.end() || !parent->second.directory || parent->first.native()!=directory.native())
throw std::runtime_error("This folder is no longer present in the archive.");
}
}
auto combined=existing;
for(const auto &[path,input]:inputs)
{
checkCanceled();
const bool folder=(input.info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
if(const auto present=combined.find(path);present!=combined.end())
{
if(present->first.native()!=path.native() || present->second.directory!=folder)
throw std::runtime_error(unsafePath);
}
else registerEntry(combined,path,ArchiveEntry{.directory=folder});
if(!folder) plan(archiveFileSize(input.info));
}
checkCanceled();
const ArchiveTemporaryFile temp(file.parent_path());
auto writer=openArchiveWriter(temp.file,zip);
if(updating)
walkArchive(file,[&](archive *reader,archive_entry *raw,const fs::path &path,const ArchiveEntry &entry)
{
checkCanceled();
if(path.empty() || inputs.contains(path)) return true;
const auto name=path.generic_wstring();
archive_entry_copy_pathname_w(raw,name.c_str());
checkArchiveWrite(archive_write_header(writer.get(),raw));
if(entry.directory) checkArchiveWrite(archive_write_finish_entry(writer.get()));
else transferArchiveData(writer.get(),entry.size,[&](char *buffer,DWORD goal)
{
const auto used=archive_read_data(reader,buffer,goal);
if(used<0) archiveError(reader);
return static_cast<DWORD>(used);
},advance);
return true;
});
for(const auto &[path,input]:inputs)
{
checkCanceled();
archiveLocalInput(writer.get(),path,input,advance);
}
checkArchiveWrite(archive_write_close(writer.get()));
writer.reset();
{
const ArchiveFileHandle completed(CreateFileW(temp.file.c_str(),GENERIC_WRITE,FILE_SHARE_READ,nullptr,
OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr));
if(!FlushFileBuffers(completed.value)) throw std::system_error(GetLastError(),std::system_category());
}
if(updating)
{
const ArchiveFileHandle current(CreateFileW(file.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr));
if(!sameArchiveFile(originalInfo,archiveFileInfo(current.value)))
throw std::runtime_error("The archive changed while it was being updated.");
}
checkCanceled();
if(updating)
{
const auto backup=temp.directory/L"original";
if(const auto error=replaceFileWithBackup(file,temp.file,backup))
throw std::system_error(error,std::system_category());
original.reset();
DeleteFileW(backup.c_str());
}
else if(!MoveFileExW(temp.file.c_str(),file.c_str(),MOVEFILE_WRITE_THROUGH))
throw std::system_error(GetLastError(),std::system_category());
}
}
-40
View File
@@ -1,40 +0,0 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <functional>
#include <map>
#include <stop_token>
#include <string>
#include <vector>
namespace ks::files
{
struct ArchiveNameOrder
{
bool operator()(const std::filesystem::path &left,const std::filesystem::path &right) const;
};
struct ArchiveEntry
{
uint64_t size{}, modified{};
bool directory{}, encrypted{}, implicit{};
uint64_t created{}, accessed{};
std::wstring owner{};
};
using ArchiveEntries=std::map<std::filesystem::path,ArchiveEntry,ArchiveNameOrder>;
using ArchiveProgress=std::function<bool(uint64_t done,uint64_t total)>;
bool isArchivePath(const std::filesystem::path &path);
ArchiveEntries readArchive(const std::filesystem::path &file,std::stop_token stop);
ArchiveEntry readArchiveMember(const std::filesystem::path &file,const std::filesystem::path &member,
const std::filesystem::path &output,uint64_t limit,const ArchiveProgress &progress);
void extractArchiveSelection(const std::filesystem::path &file,const std::filesystem::path &directory,
const std::vector<std::filesystem::path> &selection,const std::filesystem::path &staging,
const ArchiveProgress &progress);
enum class ArchiveWriteMode { create, update };
void writeArchive(const std::filesystem::path &file,ArchiveWriteMode mode,const std::filesystem::path &directory,
const std::vector<std::filesystem::path> &sources,const ArchiveProgress &progress);
}
-154
View File
@@ -1,154 +0,0 @@
INT_PTR CALLBACK archiveNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int field=531, footer=532;
const auto input=GetDlgItem(dialog,field);
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &name=*reinterpret_cast<const std::wstring *>(lp);
prepareTextDialog(dialog);
fitFarEditToLine(input);
SetWindowTextW(input,name.c_str());
SendMessageW(input,EM_SETLIMITTEXT,255,0);
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(input);
SendMessageW(input,EM_SETSEL,0,static_cast<LPARAM>(name.rfind(L'.')));
return FALSE;
}
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Pack files ",false,{footer}))
return painted;
if(message!=WM_COMMAND) return FALSE;
if(LOWORD(wp)==IDCANCEL)
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(LOWORD(wp)!=IDOK) return FALSE;
auto name=dialogFieldText(input);
if(!ks::files::validWindowsFileName(name) || !ks::files::isArchivePath(fs::path(name)))
{
showFilesNotice(dialog,L"Enter a file name ending in .zip or .7z.",L"Archive format",
{.tone=FilesNoticeTone::warning});
SetFocus(input);
return TRUE;
}
auto &result=*reinterpret_cast<std::wstring *>(GetWindowLongPtrW(dialog,DWLP_USER));
result=std::move(name);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
void performArchiveWrite(HWND owner,Panel &panel,const fs::path &archive,ks::files::ArchiveWriteMode mode,
const fs::path &directory,const std::vector<fs::path> &sources)
{
if(copyInProgress || sources.empty()) return;
const bool updating=mode==ks::files::ArchiveWriteMode::update;
CopyProgress progress;
progress.writingArchive=true;
progress.from=sources.size()==1?sources.front():sources.front().parent_path();
progress.to=archive;
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner,
copyProgressDialog,reinterpret_cast<LPARAM>(&progress));
progress.window=dialog.window();
if(!progress.window)
{
setStatus(L"Could not open archive progress.");
return;
}
copyInProgress=true;
activeCopy=&progress;
dialog.show();
bool committed=false;
std::wstring failure;
try
{
progress.ui.run(progress.window,progress.canceled,[&] {
ks::files::writeArchive(archive,mode,directory,sources,[&](uint64_t done,uint64_t total) {
progress.totalBytes=total;
reportCopyProgress(progress,done,total);
return !progress.canceled;
});
committed=true;
});
}
catch(const std::system_error &error)
{
if(error.code().value()!=ERROR_CANCELLED) failure=fileError(error);
}
catch(const std::exception &error) {failure=ks::wide(error.what());}
dialog.close();
activeCopy=nullptr;
copyInProgress=false;
if(progress.closeOwner)
{
PostMessageW(owner,WM_CLOSE,0,0);
return;
}
if(committed)
{
if(!updating)
{
open(panel,panel.directory);
selectPanelPath(panel,archive);
}
for(auto &view:panels)
{
std::error_code error;
if(view.archive && fs::equivalent(view.archive->file,archive,error)) refreshArchive(view);
}
setStatus(updating?L"Archive updated.":L"Archive created.");
}
else if(failure.empty()) setStatus(L"Archive operation canceled.");
else
{
showFileOperationError(owner,updating?L"Archive update failed":L"Archive creation failed",failure);
setStatus(failure);
}
}
void createArchive(HWND owner,Panel &panel)
{
if(panel.peer || panel.ftp || panel.archive || !panel.directory.is_absolute())
{
setStatus(L"Open a local folder to create an archive.");
return;
}
if(panel.scanRequest)
{
setStatus(L"Wait for the panel to finish reading.");
return;
}
const auto selection=selectedPanelPaths(panel);
if(selection.empty())
{
setStatus(L"Select files or folders to pack.");
return;
}
auto stem=(selection.size()==1?selection.front().stem():panel.directory.filename()).wstring();
if(stem.empty()) stem=L"Archive";
auto name=stem+L".zip";
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(120),owner,
archiveNameDialog,reinterpret_cast<LPARAM>(&name))!=IDOK) return;
performArchiveWrite(owner,panel,panel.directory/name,ks::files::ArchiveWriteMode::create,{},selection);
}
void addToArchive(HWND owner,Panel &panel,std::vector<fs::path> sources)
{
if(sources.empty())
{
setStatus(L"Select local files or folders to add.");
return;
}
if(panel.scanRequest || !panel.archive)
{
setStatus(L"Wait for the archive panel to finish reading.");
return;
}
const auto file=panel.archive->file;
auto directory=panel.directory.lexically_relative(file);
if(directory==L".") directory.clear();
const auto question=L"Add the selected items to "+file.filename().native()+L"?\r\nMatching files will be replaced.";
if(showFilesNotice(owner,question.c_str(),L"Add to archive",{.confirm=true})!=IDYES) return;
performArchiveWrite(owner,panel,file,ks::files::ArchiveWriteMode::update,directory,sources);
}
-86
View File
@@ -1,86 +0,0 @@
constexpr DWORD columnFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
std::optional<FILE_STANDARD_INFO> fileStorageInformation(HANDLE file)
{
FILE_STANDARD_INFO result{};
if(GetFileInformationByHandleEx(file,FileStandardInfo,&result,sizeof(result))) return result;
return {};
}
std::optional<uint64_t> allocatedFileBytes(HANDLE file,DWORD attributes,
const std::optional<FILE_STANDARD_INFO> &metadata)
{
if(attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) return {};
if(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))
{
FILE_COMPRESSION_INFO compression{};
if(GetFileInformationByHandleEx(file,FileCompressionInfo,&compression,sizeof(compression)) &&
compression.CompressedFileSize.QuadPart>=0)
return static_cast<uint64_t>(compression.CompressedFileSize.QuadPart);
return {};
}
if(metadata && !metadata->Directory && metadata->AllocationSize.QuadPart>=0)
return static_cast<uint64_t>(metadata->AllocationSize.QuadPart);
return {};
}
std::optional<uint64_t> allocatedFileBytes(const fs::path &path,DWORD attributes)
{
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,
OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return {};
const auto metadata=(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))?
std::optional<FILE_STANDARD_INFO>{}:fileStorageInformation(file.value);
return allocatedFileBytes(file.value,attributes,metadata);
}
std::wstring localOwnerName(const fs::path &path,std::map<std::wstring,std::wstring> &owners)
{
const Handle file{CreateFileW(path.c_str(),READ_CONTROL,columnFileShare,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return {};
PSECURITY_DESCRIPTOR descriptor=nullptr;
PSID owner=nullptr;
const auto result=GetSecurityInfo(file.value,SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,&owner,
nullptr,nullptr,nullptr,&descriptor);
const std::unique_ptr<void,decltype(&LocalFree)> security(descriptor,LocalFree);
if(result!=ERROR_SUCCESS || !owner) return {};
wchar_t *sidText=nullptr;
if(!ConvertSidToStringSidW(owner,&sidText)) return {};
const std::unique_ptr<void,decltype(&LocalFree)> sid(sidText,LocalFree);
if(const auto existing=owners.find(sidText);existing!=owners.end()) return existing->second;
wchar_t name[256]{},domain[256]{};
DWORD nameLength=static_cast<DWORD>(std::size(name)),domainLength=static_cast<DWORD>(std::size(domain));
SID_NAME_USE use{};
std::wstring label=sidText;
if(LookupAccountSidW(nullptr,owner,name,&nameLength,domain,&domainLength,&use))
label=*domain?std::wstring(domain)+L"\\"+name:name;
owners.emplace(sidText,label);
return label;
}
void readLocalColumnMetadata(Panel::ScanResult &result,DWORD mask,std::stop_token stop)
{
std::map<std::wstring,std::wstring> owners;
for(const auto &entry:result.ordered)
{
if(stop.stop_requested()) return;
const auto attributes=result.metadata.at(entry.path).attributes;
ColumnMetadata data;
if(mask&(columnMask(allocationColumn)|columnMask(linkColumn)))
{
const Handle file{CreateFileW(entry.path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,
OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value!=INVALID_HANDLE_VALUE)
{
const auto information=fileStorageInformation(file.value);
if((mask&columnMask(linkColumn)) && information) data.links=information->NumberOfLinks;
if(mask&columnMask(allocationColumn)) data.allocated=allocatedFileBytes(file.value,attributes,information);
}
}
if(mask&columnMask(ownerColumn)) data.owner=localOwnerName(entry.path,owners);
if(!data.owner.empty() || data.allocated || data.links)
result.columnMetadata.emplace(entry.path,std::move(data));
}
}
-321
View File
@@ -1,321 +0,0 @@
#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();
}
};
}
-129
View File
@@ -1,129 +0,0 @@
constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)};
auto commandHistoryKeys=defaultHistoryKeys;
constexpr size_t commandHistoryLimit=1000;
std::wstring commandHistoryLabel(const std::wstring &command)
{
constexpr std::wstring_view prefix=L"start '";
if(!command.starts_with(prefix) || command.size()<=prefix.size() || command.back()!=L'\'')
return command;
const std::wstring_view literal(command.data()+prefix.size(),command.size()-prefix.size()-1);
std::wstring path;
for(size_t i=0;i<literal.size();++i)
{
const auto character=literal[i];
if(character==L'\'' || character==L'\u2018' || character==L'\u2019')
if(++i==literal.size() || literal[i]!=character) return command;
path+=character;
}
return fs::path(path).is_absolute()?path:command;
}
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():terminalHistoryDraft.c_str());
SetFocus(terminalInput);
SendMessageW(terminalInput,EM_SETSEL,-2,-1);
suppressCurrentCompletion();
}
void recallPreviousCommand()
{
if(!terminalHistoryIndex) return;
if(terminalHistoryIndex==terminalHistory.size()) terminalHistoryDraft=terminalInputText();
recallCommand(terminalHistoryIndex-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))
{
recallPreviousCommand();
return true;
}
if(binding!=commandHistoryKeys[1]) return false;
if(!(message.lParam&(1LL<<30))) showCommandHistory(window);
return true;
}
-324
View File
@@ -1,324 +0,0 @@
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" "+historyLower(commandHistoryLabel(entry.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(commandHistoryLabel(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)
{
const auto label=commandHistoryLabel(entry.command);
SIZE size{};
if(GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.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);
}
File diff suppressed because it is too large. Load diff
-81
View File
@@ -1,81 +0,0 @@
#pragma once
#include <algorithm>
#include <string>
#include <string_view>
#include <vector>
namespace ks::files
{
enum class ComparisonEnding { absent, crlf, lf, cr };
inline std::wstring_view comparisonEndingText(ComparisonEnding ending)
{
switch(ending)
{
case ComparisonEnding::crlf: return L"\r\n";
case ComparisonEnding::lf: return L"\n";
case ComparisonEnding::cr: return L"\r";
default: return {};
}
}
struct ComparisonText
{
std::vector<std::wstring> lines;
std::vector<ComparisonEnding> endings;
ComparisonEnding preferred=ComparisonEnding::crlf;
std::wstring joined() const
{
std::wstring result;
for(size_t i=0;i<lines.size();++i)
{
result+=lines[i];
if(i+1<lines.size())
result+=comparisonEndingText(endings[i]==ComparisonEnding::absent?preferred:endings[i]);
}
return result;
}
};
inline ComparisonText splitComparisonText(std::wstring_view contents)
{
ComparisonText result;
if(contents.empty()) return result;
size_t start=0;
while(true)
{
const auto end=contents.find_first_of(L"\r\n",start);
result.lines.emplace_back(contents.substr(start,end==contents.npos?end:end-start));
auto ending=ComparisonEnding::absent;
if(end!=contents.npos)
ending=contents[end]==L'\n'?ComparisonEnding::lf:
end+1<contents.size() && contents[end+1]==L'\n'?ComparisonEnding::crlf:ComparisonEnding::cr;
result.endings.push_back(ending);
if(ending==ComparisonEnding::absent) break;
if(result.endings.size()==1) result.preferred=ending;
start=end+(ending==ComparisonEnding::crlf?2:1);
}
return result;
}
struct ComparisonReplace
{
size_t start{}, count{};
std::vector<std::wstring> lines;
std::vector<ComparisonEnding> endings;
};
inline ComparisonReplace replaceComparisonText(ComparisonText &document,const ComparisonReplace &change)
{
const auto first=document.lines.begin()+change.start, last=first+change.count;
const auto firstEnding=document.endings.begin()+change.start, lastEnding=firstEnding+change.count;
ComparisonReplace reverse{change.start,change.lines.size(),{first,last},{firstEnding,lastEnding}};
document.lines.erase(first,last);
document.lines.insert(document.lines.begin()+change.start,change.lines.begin(),change.lines.end());
document.endings.erase(firstEnding,lastEnding);
document.endings.insert(document.endings.begin()+change.start,change.endings.begin(),change.endings.end());
return reverse;
}
}
-189
View File
@@ -1,189 +0,0 @@
struct ContextPopup
{
HMENU handle=CreatePopupMenu();
~ContextPopup(){if(handle) DestroyMenu(handle);}
};
struct ShellMenuMessages
{
Microsoft::WRL::ComPtr<IContextMenu2> second;
Microsoft::WRL::ComPtr<IContextMenu3> third;
};
LRESULT CALLBACK shellMenuMessage(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR data)
{
if(message==WM_INITMENUPOPUP || message==WM_MENUCHAR ||
((message==WM_DRAWITEM || message==WM_MEASUREITEM) && !wp))
{
const auto &menu=*reinterpret_cast<const ShellMenuMessages*>(data);
LRESULT result{};
if(menu.third && menu.third->HandleMenuMsg2(message,wp,lp,&result)==S_OK) return result;
if(menu.second && message!=WM_MENUCHAR && menu.second->HandleMenuMsg(message,wp,lp)==S_OK)
return message==WM_DRAWITEM || message==WM_MEASUREITEM;
}
return DefSubclassProc(window,message,wp,lp);
}
enum class ShellPanelMenuResult { unavailable, canceled, invoked, rename, failed };
ShellPanelMenuResult showShellPanelMenu(HWND owner,const fs::path &directory,const fs::path &item,POINT screen)
{
const auto &path=item.empty()?directory:item;
PIDLIST_ABSOLUTE raw{};
if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&raw,0,nullptr)) || !raw) return ShellPanelMenuResult::unavailable;
const std::unique_ptr<ITEMIDLIST,decltype(&CoTaskMemFree)> id(raw,CoTaskMemFree);
Microsoft::WRL::ComPtr<IShellFolder> folder;
Microsoft::WRL::ComPtr<IContextMenu> menu;
if(item.empty())
{
Microsoft::WRL::ComPtr<IShellFolder> desktop;
if(FAILED(SHGetDesktopFolder(desktop.GetAddressOf())) ||
FAILED(desktop->BindToObject(id.get(),nullptr,IID_PPV_ARGS(folder.GetAddressOf()))) ||
FAILED(folder->CreateViewObject(owner,IID_PPV_ARGS(menu.GetAddressOf()))))
return ShellPanelMenuResult::unavailable;
}
else
{
PCUITEMID_CHILD child{};
if(FAILED(SHBindToParent(id.get(),IID_PPV_ARGS(folder.GetAddressOf()),&child)) ||
FAILED(folder->GetUIObjectOf(owner,1,&child,IID_IContextMenu,nullptr,
reinterpret_cast<void**>(menu.GetAddressOf()))))
return ShellPanelMenuResult::unavailable;
}
ContextPopup popup;
const auto flags=item.empty()?CMF_NORMAL:CMF_NORMAL|CMF_CANRENAME;
constexpr UINT firstCommand=1,lastCommand=0x7fff;
if(!menu || !popup.handle || FAILED(menu->QueryContextMenu(popup.handle,0,firstCommand,lastCommand,flags)) ||
GetMenuItemCount(popup.handle)<=0) return ShellPanelMenuResult::unavailable;
ShellMenuMessages handler;
if(FAILED(menu.As(&handler.third))) menu.As(&handler.second);
constexpr UINT_PTR subclass=27;
if((handler.third || handler.second) &&
!SetWindowSubclass(owner,shellMenuMessage,subclass,reinterpret_cast<DWORD_PTR>(&handler)))
return ShellPanelMenuResult::unavailable;
const auto choice=static_cast<UINT>(TrackPopupMenuEx(popup.handle,TPM_RETURNCMD|TPM_RIGHTBUTTON,
screen.x,screen.y,owner,nullptr));
RemoveWindowSubclass(owner,shellMenuMessage,subclass);
if(choice<firstCommand || choice>lastCommand) return ShellPanelMenuResult::canceled;
const auto verb=choice-firstCommand;
wchar_t name[64]{};
if(SUCCEEDED(menu->GetCommandString(verb,GCS_VERBW,nullptr,reinterpret_cast<LPSTR>(name),std::size(name))))
{
if(!item.empty() && lstrcmpiW(name,L"rename")==0) return ShellPanelMenuResult::rename;
if(item.empty() && lstrcmpiW(name,L"refresh")==0) return ShellPanelMenuResult::invoked;
}
CMINVOKECOMMANDINFOEX request{sizeof(request)};
request.fMask=CMIC_MASK_UNICODE|CMIC_MASK_NOASYNC|CMIC_MASK_PTINVOKE;
request.hwnd=owner;
request.lpVerb=MAKEINTRESOURCEA(verb);
request.lpVerbW=MAKEINTRESOURCEW(verb);
const auto working=item.empty()?directory:item.parent_path();
request.lpDirectoryW=working.c_str();
request.nShow=SW_SHOWNORMAL;
request.ptInvoke=screen;
const auto result=menu->InvokeCommand(reinterpret_cast<LPCMINVOKECOMMANDINFO>(&request));
if(result==E_ABORT || result==HRESULT_FROM_WIN32(ERROR_CANCELLED)) return ShellPanelMenuResult::canceled;
return SUCCEEDED(result)?ShellPanelMenuResult::invoked:ShellPanelMenuResult::failed;
}
void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
{
const auto owner=GetParent(panel.list);
ContextPopup popup;
if(!popup.handle) return;
constexpr UINT openItem=1,findItems=2,newProfile=3,properties=4;
const auto add=[&](UINT id,const wchar_t *label){AppendMenuW(popup.handle,MF_STRING,id,label);};
if(transferProfileList(panel))
{
if(row!=LB_ERR)
{
add(openItem,L"Connect");
add(112,L"Edit connection");
}
add(newProfile,L"New connection");
}
else
{
if(row!=LB_ERR)
{
const bool folder=panel.sizes[row]==L"Folder";
if(folder || panel.findOrigin) add(openItem,folder?L"Open folder":L"Go to file");
if(!folder && remoteSearchActionAvailable(111)) add(111,L"View");
if(!folder && !panel.archive && remoteSearchActionAvailable(112)) add(112,L"Edit");
const auto &other=panels[1-active];
const bool localDestination=!other.peer && !other.ftp && !other.archive && !other.findOrigin;
const bool canCopy=panel.ftp || panel.archive?localDestination:!other.ftp && !other.archive && !other.findOrigin;
if(canCopy && !other.directory.empty() && remoteSearchActionAvailable(113))
add(113,panel.archive?L"Extract":L"Copy");
if(!panel.archive && (panel.ftp || canCopy) && remoteSearchActionAvailable(114))
add(114,panel.ftp?L"Rename":L"Move");
if(!panel.archive && remoteSearchActionAvailable(117)) add(117,L"Delete");
if(panelItemPropertiesAvailable(panel)) add(properties,L"Properties");
}
else if(!panel.findOrigin && !panel.archive && !panel.directory.empty()) add(115,L"Make folder");
if(!panel.archive && !panel.directory.empty()) add(findItems,L"Find files");
add(110,L"Refresh panel");
}
const auto command=static_cast<UINT>(TrackPopupMenuEx(popup.handle,TPM_RETURNCMD|TPM_RIGHTBUTTON,
screen.x,screen.y,owner,nullptr));
if(command==openItem) enter(panel);
else if(command==findItems) findPanelFiles(owner,panel);
else if(command==newProfile) editTransferProfile(panel,true);
else if(command==properties) showPanelItemProperties(owner,panel);
else if(command) SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0);
}
void showPanelContextMenu(HWND list,LPARAM position)
{
const auto index=GetDlgCtrlID(list)-102;
if(index<0 || index>=static_cast<int>(std::size(panels)) || terminalVisible || !IsWindowVisible(list)) return;
const auto owner=GetParent(list);
if(!commandLineAvailable(owner)) return;
auto &panel=panels[index];
RECT bounds{};
GetClientRect(list,&bounds);
POINT client{};
LRESULT hit=LB_ERR;
if(position==-1)
{
hit=currentPanelRow(panel);
RECT rowBounds{};
if(hit!=LB_ERR && SendMessageW(list,LB_GETITEMRECT,hit,reinterpret_cast<LPARAM>(&rowBounds))!=LB_ERR)
client.y=std::clamp(rowBounds.bottom,0L,std::max(0L,bounds.bottom-1));
client.x=std::min(2L*cellWidth,std::max(0L,bounds.right-1));
}
else
{
client={GET_X_LPARAM(position),GET_Y_LPARAM(position)};
ScreenToClient(list,&client);
if(!PtInRect(&bounds,client)) return;
hit=panelRowAt(list,client,SendMessageW(list,LB_GETTOPINDEX,0,0),panel.rows.size());
if(hit!=LB_ERR)
{
const auto previous=currentPanelRow(panel);
SendMessageW(list,LB_SETCURSEL,hit,0);
invalidatePanelCursorChange(list,previous);
}
}
activatePanel(index);
closePanelSearch();
panelClipboardContext=true;
clearTerminalSelection();
SetFocus(list);
POINT screen=client;
ClientToScreen(list,&screen);
const auto row=hit!=LB_ERR && panel.sizes[hit]!=L"Up"?hit:LB_ERR;
const auto directory=panel.directory;
const auto item=row==LB_ERR?fs::path{}:panel.rows[row];
const bool shell=!panel.peer && !panel.ftp && !panel.archive && !directory.empty() &&
!windowsNetworkPath(directory);
const auto result=shell?showShellPanelMenu(owner,directory,item,screen):ShellPanelMenuResult::unavailable;
if(result==ShellPanelMenuResult::unavailable) showFilesPanelContext(panel,row,screen);
else if(result==ShellPanelMenuResult::rename)
copySelection(owner,panel,panel,true,{item},item.parent_path(),true);
else if(result==ShellPanelMenuResult::invoked && IsWindow(owner) && panel.directory==directory &&
!panel.peer && !panel.ftp && !panel.archive) refreshPanel(panel);
else if(result==ShellPanelMenuResult::failed) setStatus(L"Windows could not complete the Shell command.");
if(IsWindow(owner)) restoreCommandFocus();
}
-348
View File
@@ -1,348 +0,0 @@
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,
bool watchOutsideClicks=true)
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
watchOutsideClicks_(watchOutsideClicks)
{
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;
refreshMouseHook();
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_;
refreshMouseHook();
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);
return dialog.runModal();
}
INT_PTR runModal()
{
if(!window_) return -1;
show();
MSG message{};
while(!finished_ && IsWindow(window_))
{
const auto status=GetMessageW(&message,nullptr,0,0);
if(status<=0)
{
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
break;
}
if(handleMessage(window_,message)) continue;
TranslateMessage(&message);
DispatchMessageW(&message);
}
return 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_{},watchOutsideClicks_;
static void refreshMouseHook()
{
const auto *active=activeFilesDialog?
reinterpret_cast<const FilesModalDialog*>(GetPropW(activeFilesDialog,stateProperty_)):nullptr;
if(active && active->watchOutsideClicks_)
{
if(!filesDialogMouseHook)
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
}
else if(filesDialogMouseHook)
{
UnhookWindowsHookEx(filesDialogMouseHook);
filesDialogMouseHook=nullptr;
}
}
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(IsZoomed(window) || !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;
}
};
-239
View File
@@ -1,239 +0,0 @@
constexpr UINT panelDropReady=WM_APP+33;
struct PanelDrop
{
HWND source{}, target{};
fs::path directory, destination;
std::vector<fs::path> paths;
};
std::optional<PanelDrop> pendingPanelDrop;
HWND draggingPanel{};
std::optional<POINT> panelDragStart;
bool localDropPanel(const Panel &panel)
{
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.archive && panel.directory.is_absolute();
}
LRESULT panelRowAt(HWND window,POINT point,LRESULT top,LRESULT count)
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,MAKELPARAM(point.x,point.y));
// LB_ITEMFROMPOINT only returns the low 16 bits of the row index.
constexpr LRESULT rowRange=1<<16;
auto row=(top&~(rowRange-1))|LOWORD(hit);
if(row<top) row+=rowRange;
RECT bounds{};
return !HIWORD(hit) && row>=0 && row<count &&
SendMessageW(window,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR &&
PtInRect(&bounds,point)?row:LB_ERR;
}
FORMATETC fileDropFormat()
{
return {CF_HDROP,nullptr,DVASPECT_CONTENT,-1,TYMED_HGLOBAL};
}
template<class Interface,class Derived>
class DragInterface : public Interface
{
public:
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **out) override
{
if(!out) return E_POINTER;
*out=nullptr;
if(iid!=IID_IUnknown && iid!=__uuidof(Interface)) return E_NOINTERFACE;
*out=static_cast<Interface *>(this);
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE AddRef() override {return ++references;}
ULONG STDMETHODCALLTYPE Release() override
{
const auto count=--references;
if(!count) delete static_cast<Derived *>(this);
return count;
}
private:
ULONG references{1};
};
class PanelDropTarget final : public DragInterface<IDropTarget,PanelDropTarget>
{
public:
explicit PanelDropTarget(HWND window) : target(window) {}
HRESULT STDMETHODCALLTYPE DragEnter(IDataObject *data,DWORD,POINTL,DWORD *effect) override
{
auto format=fileDropFormat();
filesystem=data->QueryGetData(&format)==S_OK;
return updateEffect(effect);
}
HRESULT STDMETHODCALLTYPE DragOver(DWORD,POINTL,DWORD *effect) override
{
return updateEffect(effect);
}
HRESULT STDMETHODCALLTYPE DragLeave() override
{
filesystem=false;
return S_OK;
}
HRESULT STDMETHODCALLTYPE Drop(IDataObject *data,DWORD,POINTL location,DWORD *effect) override
{
updateEffect(effect);
filesystem=false;
if(*effect==DROPEFFECT_NONE) return S_OK;
*effect=DROPEFFECT_NONE;
auto format=fileDropFormat();
STGMEDIUM medium{};
if(FAILED(data->GetData(&format,&medium)))
{
setStatus(L"Could not read local paths from the drop.");
return S_OK;
}
std::vector<fs::path> paths;
try
{
if(medium.tymed==TYMED_HGLOBAL) paths=ks::fileDropPaths(medium.hGlobal);
}
catch(const std::exception &) {}
ReleaseStgMedium(&medium);
if(paths.empty())
{
setStatus(L"The drop contains no usable file or folder paths.");
return S_OK;
}
try
{
const auto &panel=panels[GetDlgCtrlID(target)-102];
POINT point{location.x,location.y};
ScreenToClient(target,&point);
const auto row=panelRowAt(target,point,SendMessageW(target,LB_GETTOPINDEX,0,0),
static_cast<LRESULT>(panel.rows.size()));
const auto &destination=row!=LB_ERR && panel.sizes[row]==L"Folder"?panel.rows[row]:panel.directory;
pendingPanelDrop=PanelDrop{draggingPanel,target,panel.directory,destination,std::move(paths)};
if(PostMessageW(GetParent(target),panelDropReady,0,0))
{
// Files performs the requested move after confirmation.
*effect=DROPEFFECT_COPY;
}
else pendingPanelDrop.reset();
}
catch(const std::exception &)
{
setStatus(L"Could not prepare the drop.");
}
return S_OK;
}
private:
HRESULT updateEffect(DWORD *effect)
{
const auto allowed=*effect;
*effect=DROPEFFECT_NONE;
if(!filesystem || !(allowed&DROPEFFECT_COPY))
setStatus(L"Drag files or folders from a Windows filesystem.");
else if(target==draggingPanel)
setStatus(L"Drop files onto the other panel.");
else if(!localDropPanel(panels[GetDlgCtrlID(target)-102]))
setStatus(L"Open a local folder in the destination panel before dropping files.");
else if(!copyInProgress && !pendingPanelDrop && !FilesModalDialog::activeFor(GetParent(target)))
*effect=DROPEFFECT_COPY;
return S_OK;
}
HWND target;
bool filesystem{};
};
class PanelDragSource final : public DragInterface<IDropSource,PanelDragSource>
{
public:
HRESULT STDMETHODCALLTYPE QueryContinueDrag(BOOL escape,DWORD keys) override
{
if(escape) return DRAGDROP_S_CANCEL;
return keys&MK_LBUTTON?S_OK:DRAGDROP_S_DROP;
}
HRESULT STDMETHODCALLTYPE GiveFeedback(DWORD) override {return DRAGDROP_S_USEDEFAULTCURSORS;}
};
void beginPanelDrag(HWND window)
{
auto &panel=panels[GetDlgCtrlID(window)-102];
if(!localDropPanel(panel))
{
setStatus(L"Drag files or folders from an open local folder.");
return;
}
auto paths=selectedPanelPaths(panel);
if(paths.empty()) return;
std::vector<PCIDLIST_ABSOLUTE> items;
items.reserve(paths.size());
const auto clear=[&](void *){for(auto item:items) CoTaskMemFree(const_cast<PIDLIST_ABSOLUTE>(item));};
const std::unique_ptr<void,decltype(clear)> cleanup(&items,clear);
for(const auto &path:paths)
{
PIDLIST_ABSOLUTE item{};
if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&item,0,nullptr)))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
items.push_back(item);
}
IShellItemArray *array{};
if(FAILED(SHCreateShellItemArrayFromIDLists(static_cast<UINT>(items.size()),items.data(),&array)))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
IDataObject *data{};
const auto result=array->BindToHandler(nullptr,BHID_DataObject,IID_PPV_ARGS(&data));
array->Release();
if(FAILED(result))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
const auto source=new(std::nothrow) PanelDragSource;
if(source)
{
draggingPanel=window;
DWORD effect{};
DoDragDrop(data,source,DROPEFFECT_COPY,&effect);
draggingPanel=nullptr;
source->Release();
}
data->Release();
}
void performPanelDrop(HWND owner)
{
if(!pendingPanelDrop) return;
auto drop=std::move(*pendingPanelDrop);
pendingPanelDrop.reset();
auto index=GetDlgCtrlID(drop.target)-102;
if(index<0 || index>=static_cast<int>(std::size(panels))) return;
auto &panel=panels[index];
if(!localDropPanel(panel) || panel.directory!=drop.directory || !IsWindowVisible(drop.target))
{
setStatus(L"The destination panel changed. Drop the files again.");
return;
}
if(copyInProgress || FilesModalDialog::activeFor(owner))
{
setStatus(L"Finish the current operation before dropping files.");
return;
}
const auto text=L"Destination folder:\r\n"+drop.destination.native();
const auto answer=showFilesNotice(owner,text.c_str(),L"Drop files",
{.tone=FilesNoticeTone::neutral,.chooseTransfer=true});
if(answer!=IDYES && answer!=IDNO) return;
auto &source=drop.source?panels[GetDlgCtrlID(drop.source)-102]:panel;
activatePanel(index);
panelClipboardContext=true;
copySelection(owner,source,panel,answer==IDNO,std::move(drop.paths),std::move(drop.destination));
}
-35
View File
@@ -1,35 +0,0 @@
#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);
}
}
-202
View File
@@ -1,202 +0,0 @@
constexpr wchar_t operationPipePrefix[]=L"\\\\.\\pipe\\KSwitcher.Files.Operation.";
constexpr DWORD operationMessageLimit=256*1024;
void writeElevationMessage(HANDLE pipe,const Json &message)
{
const auto bytes=message.dump();
requireFileOperation(bytes.size()<=operationMessageLimit,ERROR_BUFFER_OVERFLOW);
DWORD written{};
checkFileOperation(WriteFile(pipe,bytes.data(),static_cast<DWORD>(bytes.size()),&written,nullptr));
requireFileOperation(written==bytes.size(),ERROR_WRITE_FAULT);
}
Json readElevationMessage(HANDLE pipe)
{
std::array<char,operationMessageLimit> bytes;
DWORD read{};
checkFileOperation(ReadFile(pipe,bytes.data(),operationMessageLimit,&read,nullptr));
return Json::parse(bytes.data(),bytes.data()+read);
}
bool localElevationPath(const fs::path &path)
{
const auto root=path.root_name().native();
return path.is_absolute() && root.size()==2 && root[1]==L':' &&
path.native().find(L'\0')==std::wstring::npos && path.has_relative_path() &&
GetDriveTypeW(path.root_path().c_str())!=DRIVE_REMOTE;
}
bool allowedElevationRequest(const Json &request)
{
const auto action=request.at("action").get<std::string>();
if(action!="copy" && action!="move" && action!="mkdir" && action!="mkdir-link" &&
action!="remove" && action!="recycle" && action!="rmdir" && action!="stat" &&
action!="canonical" && action!="list") return false;
if(!localElevationPath(filePath(request.at("path")))) return false;
if(action=="copy" || action=="move" || action=="mkdir-link")
return localElevationPath(filePath(request.at("target")));
return true;
}
DWORD serveElevatedFileOperations(const std::wstring &parent,const std::wstring &pipeName)
{
try
{
if(!IsUserAnAdmin() || !pipeName.starts_with(operationPipePrefix)) return ERROR_ACCESS_DENIED;
DWORD expected{};
for(const auto ch:parent)
{
if(ch<L'0' || ch>L'9' || expected>(MAXDWORD-(ch-L'0'))/10) return ERROR_INVALID_PARAMETER;
expected=expected*10+(ch-L'0');
}
Handle pipe{CreateFileW(pipeName.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr)};
checkFileOperation(pipe.value!=INVALID_HANDLE_VALUE);
ULONG server{};
checkFileOperation(GetNamedPipeServerProcessId(pipe.value,&server));
requireFileOperation(server==expected,ERROR_ACCESS_DENIED);
DWORD mode=PIPE_READMODE_MESSAGE;
checkFileOperation(SetNamedPipeHandleState(pipe.value,&mode,nullptr,nullptr));
FilesConnection listing;
bool more=false;
while(true)
{
const auto request=readElevationMessage(pipe.value);
Json reply;
try
{
const auto action=request.at("action").get<std::string>();
if(action=="listNext" || action=="list")
{
requireFileOperation(action=="listNext"?more:allowedElevationRequest(request),ERROR_ACCESS_DENIED);
more=false;
reply=listing.call(request);
more=reply.value("more",false);
}
else
{
requireFileOperation(allowedElevationRequest(request),ERROR_ACCESS_DENIED);
FilesConnection local;
ULONGLONG lastUpdate{};
reply=local.call(request,[&](uint64_t done,uint64_t total)
{
const auto now=GetTickCount64();
if(lastUpdate && now-lastUpdate<100 && done!=total) return true;
lastUpdate=now;
writeElevationMessage(pipe.value,{{"progress",{done,total}}});
return readElevationMessage(pipe.value).at("continue").get<bool>();
});
}
}
catch(const std::system_error &error) {reply={{"error",error.code().value()}};}
catch(const std::exception &) {reply={{"error",ERROR_INVALID_DATA}};}
writeElevationMessage(pipe.value,reply);
}
}
catch(const std::system_error &error)
{
const auto code=error.code().value();
return code==ERROR_BROKEN_PIPE || code==ERROR_NO_DATA?ERROR_SUCCESS:static_cast<DWORD>(code);
}
catch(const std::exception &) {return ERROR_INVALID_DATA;}
}
class FileOperationElevation
{
HWND owner_;
FileOperationUi *ui_;
std::atomic_bool &canceled_;
ElevatedHelper helper_;
bool connected_{};
DWORD connect()
{
const auto deadline=GetTickCount64()+10000;
while(!canceled_ && GetTickCount64()<deadline)
{
if(ConnectNamedPipe(helper_.pipe.value,nullptr) || GetLastError()==ERROR_PIPE_CONNECTED)
{
ULONG client{};
if(!GetNamedPipeClientProcessId(helper_.pipe.value,&client)) return GetLastError();
if(client!=GetProcessId(helper_.process.value)) return ERROR_ACCESS_DENIED;
DWORD mode=PIPE_READMODE_MESSAGE;
if(!SetNamedPipeHandleState(helper_.pipe.value,&mode,nullptr,nullptr)) return GetLastError();
connected_=true;
return ERROR_SUCCESS;
}
if(WaitForSingleObject(helper_.process.value,20)==WAIT_OBJECT_0)
{
DWORD result{};
if(!GetExitCodeProcess(helper_.process.value,&result)) return GetLastError();
return result?result:ERROR_PIPE_NOT_CONNECTED;
}
}
return canceled_?ERROR_CANCELLED:ERROR_TIMEOUT;
}
DWORD requestConsent(const Json &request)
{
if(canceled_) return ERROR_CANCELLED;
auto paths=filePath(request.at("path")).wstring();
if(request.contains("target")) paths+=L"\r\n"+filePath(request.at("target")).wstring();
const auto question=L"Windows denied access to the following path:\r\n"+paths+
L"\r\n\r\nRetry with administrator rights for the current operation?";
if(showFilesNotice(owner_,question.c_str(),L"Access denied",{.confirm=true})!=IDYES)
return ERROR_CANCELLED;
const auto error=launchElevatedHelper(owner_,operationPipePrefix,L"--elevated-file-operation",
std::to_wstring(GetCurrentProcessId()),helper_);
SetForegroundWindow(owner_);
return error;
}
Json send(const Json &request,const ks::lan::FileProgress &progress={})
{
if(canceled_) return {{"error",ERROR_CANCELLED}};
writeElevationMessage(helper_.pipe.value,request);
for(;;)
{
auto message=readElevationMessage(helper_.pipe.value);
if(!message.contains("progress")) return message;
const auto &value=message.at("progress");
writeElevationMessage(helper_.pipe.value,{{"continue",!canceled_ &&
(!progress || progress(value.at(0).get<uint64_t>(),value.at(1).get<uint64_t>()))}});
}
}
public:
FileOperationElevation(HWND owner,std::atomic_bool &canceled,FileOperationUi *ui=nullptr):
owner_(owner),ui_(ui),canceled_(canceled){}
Json retry(const Json &request,Json reply,const ks::lan::FileProgress &progress={})
{
const auto failure=reply.at("error").get<DWORD>();
if((failure!=ERROR_ACCESS_DENIED && failure!=ERROR_PRIVILEGE_NOT_HELD && failure!=ERROR_ELEVATION_REQUIRED) ||
IsUserAnAdmin() || !allowedElevationRequest(request))
return reply;
if(!connected_)
{
auto error=ui_?ui_->invoke([&]{return requestConsent(request);}):requestConsent(request);
if(error==ERROR_SUCCESS) error=connect();
if(error==ERROR_CANCELLED) canceled_=true;
if(error!=ERROR_SUCCESS) return {{"error",error}};
}
return send(request,progress);
}
Json call(FilesConnection &local,const Json &request,const ks::lan::FileProgress &progress={})
{
return retry(request,local.call(request,progress),progress);
}
void list(FilesConnection &local,const fs::path &path,const FileVisitor &visit)
{
const auto request=fileRequest("list",path);
auto reply=local.call(request);
const bool elevated=reply.at("error")==ERROR_ACCESS_DENIED;
if(elevated) reply=retry(request,std::move(reply));
listFilePages(std::move(reply),path,visit,[&]{
const Json next{{"action","listNext"}};
return elevated?send(next):local.call(next);
});
}
};
-119
View File
@@ -1,119 +0,0 @@
constexpr int findMask=480, findHidden=481, findFooter=482, findLabel=483;
struct FileMaskPrompt
{
Panel::FindOptions options;
bool filter{};
};
INT_PTR CALLBACK fileMaskDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
const auto *prompt=reinterpret_cast<const FileMaskPrompt *>(message==WM_INITDIALOG?lp:GetWindowLongPtrW(dialog,DWLP_USER));
const bool filter=prompt && prompt->filter;
const auto title=filter?L" Panel filter ":L" Find files ";
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,title,false,{findFooter}))
return painted;
if(message==WM_INITDIALOG)
{
const auto &options=prompt->options;
SetWindowLongPtrW(dialog,DWLP_USER,lp);
if(filter)
{
SetWindowTextW(dialog,L"Panel filter");
SetDlgItemTextW(dialog,findLabel,L"File &name or mask (blank clears)");
SetDlgItemTextW(dialog,findHidden,L"Show &hidden and system files");
SetDlgItemTextW(dialog,IDOK,L"&Apply");
}
prepareTextDialog(dialog);
layoutDialogContent(dialog,findLabel);
fitFarEditToLine(GetDlgItem(dialog,findMask));
for(const auto id:{IDOK,IDCANCEL})
{
const auto button=GetDlgItem(dialog,id);
SetWindowPos(button,nullptr,0,0,farDialogButtonWidth(button),textHeight,
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
}
layoutDialogButtons(dialog,findFooter,{IDOK,IDCANCEL});
installFarCheckbox(GetDlgItem(dialog,findHidden),FarCheckboxSurface::gray);
SendDlgItemMessageW(dialog,findMask,EM_SETLIMITTEXT,255,0);
SetDlgItemTextW(dialog,findMask,options.mask.c_str());
CheckDlgButton(dialog,findHidden,options.includeHidden?BST_CHECKED:BST_UNCHECKED);
SetFocus(GetDlgItem(dialog,findMask));
SendDlgItemMessageW(dialog,findMask,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &options=reinterpret_cast<FileMaskPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER))->options;
wchar_t mask[256]{};
GetDlgItemTextW(dialog,findMask,mask,static_cast<int>(std::size(mask)));
if(std::wstring_view(mask).find_first_of(L"/\\:")!=std::wstring_view::npos)
{
showFilesNotice(dialog,L"Enter a file name or mask without a path.",filter?L"Panel filter":L"Find files");
SetFocus(GetDlgItem(dialog,findMask));
return TRUE;
}
options.mask=*mask?mask:L"*";
options.includeHidden=IsDlgButtonChecked(dialog,findHidden)==BST_CHECKED;
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return FALSE;
}
void startFileSearch(Panel &panel,Panel::FindOptions options)
{
if(panel.scanRequest) return;
cancelFolderSizes(panel);
panel.remoteRetry.reset();
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.peer=panel.peer,.statusRevision=statusRevision,
.ftp=panel.ftp,.find=std::move(options)};
startDirectoryScan(panel);
}
bool canFindFiles(const Panel &panel)
{
return !panel.archive && !panel.directory.empty() && !transferProfileList(panel);
}
void findPanelFiles(HWND owner,Panel &panel)
{
if(!canFindFiles(panel))
{
setStatus(L"Find files requires an open folder.");
return;
}
if(panel.scanRequest)
{
setStatus(L"Wait for the current scan to finish.");
return;
}
FileMaskPrompt prompt{panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{}};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
fileMaskDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
startFileSearch(panel,std::move(prompt.options));
}
void editPanelFilter(HWND owner,Panel &panel)
{
if(!panelViewAvailable(panel)) return;
FileMaskPrompt prompt{{panel.view.mask,panel.view.showHidden},true};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
fileMaskDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
auto &options=prompt.options;
if(options.mask==L"*") options.mask.clear();
if(panel.view.mask==options.mask && panel.view.showHidden==options.includeHidden) return;
panel.view.mask=std::move(options.mask);
panel.view.showHidden=options.includeHidden;
updatePanelView(panel);
}
-111
View File
@@ -1,111 +0,0 @@
bool matchesFileMask(std::wstring_view name,std::wstring_view mask)
{
size_t fileIndex=0, maskIndex=0, star=mask.npos, afterStar=0;
while(fileIndex<name.size())
{
if(maskIndex<mask.size() && mask[maskIndex]==L'*')
{
star=maskIndex++;
afterStar=fileIndex;
}
else if(maskIndex<mask.size() &&
(mask[maskIndex]==L'?' || CompareStringOrdinal(name.data()+fileIndex,1,
mask.data()+maskIndex,1,TRUE)==CSTR_EQUAL))
{
++fileIndex;
++maskIndex;
}
else if(star!=mask.npos)
{
maskIndex=star+1;
fileIndex=++afterStar;
}
else return false;
}
return mask.find_first_not_of(L'*',maskIndex)==mask.npos;
}
std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &request,
std::atomic_size_t &entriesRead,std::stop_token stop)
{
auto result=std::make_unique<Panel::ScanResult>();
const bool remote=request.peer || request.ftp;
const auto walk=[&](const auto &listDirectory)
{
std::vector<fs::path> pending{request.directory};
size_t visited=0;
while(!pending.empty() && !stop.stop_requested())
{
const auto directory=std::move(pending.back());
pending.pop_back();
try
{
if(!listDirectory(directory,[&](const fs::path &path,const FileInfo &entry)
{
if(stop.stop_requested()) return false;
if(path.parent_path()!=folderPathWithoutSeparator(directory)) return true;
entriesRead.store(++visited,std::memory_order_relaxed);
const auto name=path.filename().native();
if(!request.find->includeHidden &&
((entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) ||
(request.ftp && name.starts_with(L'.')))) return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
{
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
}
else if((!request.ftp || !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) &&
matchesFileMask(name,request.find->mask) &&
result->metadata.emplace(path,FolderEntryMetadata{
entry.attributes,entry.size,entry.modified}).second)
{
result->files.push_back(path);
if(entry.transfer) result->columnMetadata[path].transfer=entry.transfer;
}
return true;
})) break;
}
catch(const std::system_error &error)
{
if(stop.stop_requested()) break;
const auto code=error.code().value();
if(remote && code!=ERROR_FILE_NOT_FOUND && code!=ERROR_PATH_NOT_FOUND &&
code!=ERROR_ACCESS_DENIED && code!=ERROR_DIRECTORY)
throw;
if(!remote && directory==request.directory)
{
result->failure=L"Cannot search folder: "+directory.native();
return;
}
result->error=ERROR_PARTIAL_COPY;
}
}
};
try
{
if(request.ftp)
{
TransferSession connection(*request.ftp,SftpAccess::normal,stop);
walk([&](const fs::path &directory,const FileVisitor &visit)
{
const auto error=connection.list(directory,visit,stop);
if(error==ERROR_CANCELLED) return false;
requireFileOperation(error==ERROR_SUCCESS || error==ERROR_NO_MORE_FILES,error);
return true;
});
}
else
{
FilesConnection connection(request.peer?&*request.peer:nullptr,stop);
walk([&](const fs::path &directory,const FileVisitor &visit){return listFiles(connection,directory,visit);});
}
}
catch(const std::exception &)
{
if(remote) result->error=ERROR_CONNECTION_ABORTED;
else if(!stop.stop_requested()) result->failure=L"Cannot search folder: "+request.directory.native();
}
if(stop.stop_requested()) result->error=ERROR_CANCELLED;
result->opened=result->failure.empty();
std::sort(result->files.begin(),result->files.end());
return result;
}
-439
View File
@@ -1,439 +0,0 @@
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));
}
return writeFilesJsonPreference(folderShortcutsKey,groups);
}
catch(const std::exception &){return false;}
}
void loadFolderShortcuts()
{
const auto saved=readFilesJsonPreference(folderShortcutsKey);
if(!saved) return;
try
{
const auto &groups=*saved;
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 trimFilesField(std::wstring value)
{
const auto first=value.find_first_not_of(L" \t\r\n");
if(first==value.npos) return {};
return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1);
}
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() || panel.ftp || panel.archive) 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() && !panel.archive && 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.");
}
-346
View File
@@ -1,346 +0,0 @@
enum class TransferProtocol { ftp, sftp };
constexpr unsigned defaultSftpPort=22;
const wchar_t *transferProtocolName(TransferProtocol protocol)
{
return protocol==TransferProtocol::sftp?L"SFTP":L"FTP";
}
struct TransferProfile
{
std::wstring name, host, user;
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
ks::Bytes secret;
bool legacyNames{};
std::string id;
TransferProtocol protocol{};
fs::path privateKey;
std::string hostFingerprint;
std::string jumpProfile;
std::wstring sudoSftpServer;
};
struct TransferProfiles
{
const wchar_t *preference;
std::vector<TransferProfile> rows;
bool loaded{};
};
TransferProfiles &transferProfiles(TransferProtocol protocol)
{
static TransferProfiles ftp{L"FtpProfiles"},sftp{L"SftpProfiles"};
return protocol==TransferProtocol::sftp?sftp:ftp;
}
std::atomic<std::shared_ptr<const std::vector<TransferProfile>>> sshProfiles;
constexpr size_t sshRouteLimit=8;
std::vector<TransferProfile> sshRoute(const TransferProfile &destination,
const std::vector<TransferProfile> &profiles)
{
std::vector<TransferProfile> route{destination};
std::set<std::string> seen{destination.id};
while(!route.back().jumpProfile.empty())
{
const auto &id=route.back().jumpProfile;
if(!seen.insert(id).second) throw std::runtime_error("The SSH jump route contains a loop.");
if(route.size()>=sshRouteLimit) throw std::runtime_error("An SSH route can contain up to eight hosts.");
const auto hop=std::find_if(profiles.begin(),profiles.end(),
[&id](const auto &profile){return profile.id==id;});
if(hop==profiles.end()) throw std::runtime_error("An SSH jump profile is missing. Edit this connection to update its route.");
route.push_back(*hop);
}
std::reverse(route.begin(),route.end());
return route;
}
bool validSudoSftpServer(std::wstring_view path)
{
constexpr std::wstring_view pathCharacters=L"/-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return path.empty() || (path.starts_with(L'/') && path.ends_with(L"/sftp-server") &&
path.size()<=255 && path.find_first_not_of(pathCharacters)==path.npos);
}
constexpr DWORD transferProfilesMaxBytes=1024*1024;
const fs::path ftpRoot=L"\\";
bool isFtpFolderPath(const fs::path &path)
{
return path.has_root_directory() && !path.has_root_name();
}
std::wstring ftpPath(const fs::path &path)
{
auto value=path.native();
std::replace(value.begin(),value.end(),L'\\',L'/');
return value;
}
bool saveTransferProfiles(TransferProtocol protocol,const std::vector<TransferProfile> &profiles)
{
auto rows=Json::array();
for(const auto &profile:profiles)
{
Json row{{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
{"legacyNames",profile.legacyNames},{"id",profile.id}};
if(protocol==TransferProtocol::sftp)
{
row["privateKey"]=ks::utf8(profile.privateKey.native());
row["hostFingerprint"]=profile.hostFingerprint;
row["jumpProfile"]=profile.jumpProfile;
row["sudoSftpServer"]=ks::utf8(profile.sudoSftpServer);
}
rows.push_back(std::move(row));
}
const auto data=rows.dump();
if(data.size()>transferProfilesMaxBytes) return false;
const auto snapshot=protocol==TransferProtocol::sftp?
std::make_shared<const std::vector<TransferProfile>>(profiles):nullptr;
if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))!=ERROR_SUCCESS) return false;
if(snapshot) sshProfiles=snapshot;
return true;
}
bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
{
auto &settings=transferProfiles(protocol);
if(settings.loaded) return true;
DWORD bytes{};
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference,
RRF_RT_REG_BINARY,nullptr,nullptr,&bytes);
if(query==ERROR_FILE_NOT_FOUND)
{
settings.loaded=true;
return true;
}
if(query!=ERROR_SUCCESS || !bytes || bytes>transferProfilesMaxBytes) return false;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference,RRF_RT_REG_BINARY,
nullptr,data.data(),&bytes)!=ERROR_SUCCESS) return false;
try
{
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
if(!rows.is_array()) return false;
std::vector<TransferProfile> profiles;
for(const auto &row:rows)
{
const auto port=row.at("port").get<unsigned>();
if(!port || port>65535) return false;
TransferProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
ks::wide(row.at("user")),static_cast<INTERNET_PORT>(port),row.at("secret").get<ks::Bytes>(),
row.value("legacyNames",false),row.value("id",std::string{}),protocol};
if(profile.id.empty()) profile.id="legacy:"+ks::utf8(profile.name);
if(profile.name.empty() || profile.host.empty()) return false;
if(protocol==TransferProtocol::sftp)
{
profile.privateKey=ks::wide(row.value("privateKey",std::string{}));
profile.hostFingerprint=row.value("hostFingerprint",std::string{});
profile.jumpProfile=row.value("jumpProfile",std::string{});
profile.sudoSftpServer=ks::wide(row.value("sudoSftpServer",std::string{}));
if(!validSudoSftpServer(profile.sudoSftpServer)) return false;
}
profiles.push_back(std::move(profile));
}
if(protocol==TransferProtocol::sftp)
sshProfiles=std::make_shared<const std::vector<TransferProfile>>(profiles);
settings.rows=std::move(profiles);
settings.loaded=true;
return true;
}
catch(const std::exception &) {return false;}
}
const TransferProfile *findTransferProfile(std::string_view id,TransferProtocol protocol=TransferProtocol::ftp)
{
const auto &profiles=transferProfiles(protocol).rows;
const auto profile=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry) {
return entry.id==id;
});
return profile==profiles.end()?nullptr:&*profile;
}
std::wstring transferPassword(const TransferProfile &profile)
{
if(profile.secret.empty()) return {};
auto bytes=ks::unprotect(profile.secret);
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid saved transfer password");
std::wstring password(bytes.size()/sizeof(wchar_t),L'\0');
std::copy(bytes.begin(),bytes.end(),reinterpret_cast<unsigned char*>(password.data()));
SecureZeroMemory(bytes.data(),bytes.size());
return password;
}
struct FtpHandle
{
HINTERNET value{};
~FtpHandle() {if(value) InternetCloseHandle(value);}
explicit FtpHandle(HINTERNET handle=nullptr):value(handle) {}
FtpHandle(const FtpHandle &)=delete;
FtpHandle &operator=(const FtpHandle &)=delete;
};
void requireFileOperation(bool success,DWORD error)
{
if(!success) throw std::system_error(error,std::system_category());
}
void checkFileOperation(bool success)
{
if(!success) requireFileOperation(false,GetLastError());
}
std::wstring ftpFolderError(const std::system_error &error)
{
switch(error.code().value())
{
case ERROR_INTERNET_CANNOT_CONNECT: return L"Cannot reach FTP server.";
case ERROR_INTERNET_NAME_NOT_RESOLVED: return L"FTP host name could not be resolved.";
case ERROR_INTERNET_LOGIN_FAILURE: return L"FTP sign-in failed.";
case ERROR_INTERNET_TIMEOUT: return L"FTP connection timed out.";
default: break;
}
if(error.code().value()==ERROR_INTERNET_EXTENDED_ERROR)
{
DWORD response{},length{};
InternetGetLastResponseInfoW(&response,nullptr,&length);
if(length && length<=2048)
{
std::wstring text(length,L'\0');
if(InternetGetLastResponseInfoW(&response,text.data(),&length))
{
text.resize(length);
text.resize(std::min(text.size(),text.find_first_of(L"\r\n")));
if(!text.empty()) return text;
}
}
return L"The FTP server rejected the request.";
}
wchar_t message[256]{};
const DWORD length=FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS,
GetModuleHandleW(L"wininet.dll"),error.code().value(),0,message,static_cast<DWORD>(std::size(message)),nullptr);
if(!length) return fileError(error);
std::wstring text(message,length);
while(!text.empty() && (text.back()==L'\r' || text.back()==L'\n')) text.pop_back();
return text;
}
class FtpSession
{
FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)};
FtpHandle connection_;
fs::path current_;
UINT nameCodePage_;
public:
explicit FtpSession(const TransferProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8)
{
checkFileOperation(internet_.value!=nullptr);
DWORD timeout=10000, retries=1;
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_TIMEOUT,&timeout,sizeof(timeout));
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_RETRIES,&retries,sizeof(retries));
InternetSetOptionW(internet_.value,INTERNET_OPTION_RECEIVE_TIMEOUT,&timeout,sizeof(timeout));
InternetSetOptionW(internet_.value,INTERNET_OPTION_SEND_TIMEOUT,&timeout,sizeof(timeout));
auto password=transferPassword(profile);
const auto user=profile.user.empty()?(password.empty()?nullptr:L"anonymous"):profile.user.c_str();
connection_.value=InternetConnectW(internet_.value,profile.host.c_str(),profile.port,
user,password.empty()?nullptr:password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
const auto error=GetLastError();
SecureZeroMemory(password.data(),password.size()*sizeof(wchar_t));
requireFileOperation(connection_.value!=nullptr,error);
if(!profile.legacyNames)
FtpCommandA(handle(),FALSE,0,"OPTS UTF8 ON",0,nullptr);
}
HINTERNET handle() const {return connection_.value;}
// WinINet's A entry points transfer FTP pathname bytes without a Unicode conversion.
std::wstring decodeName(std::string_view bytes) const
{
if(bytes.empty()) return {};
const auto length=static_cast<int>(bytes.size());
const auto count=MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,nullptr,0);
if(!count)
throw std::runtime_error("The FTP server returned a name in another encoding. Check the FTP connection's file name encoding.");
std::wstring name(count,L'\0');
checkFileOperation(MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,name.data(),count)>0);
return name;
}
std::string encodeName(const fs::path &path) const
{
const auto name=ftpPath(path);
if(name.empty()) return {};
const auto length=static_cast<int>(name.size());
BOOL substituted=FALSE;
const auto legacy=nameCodePage_!=CP_UTF8;
const auto flags=legacy?WC_NO_BEST_FIT_CHARS:WC_ERR_INVALID_CHARS;
const auto replacement=legacy?&substituted:nullptr;
const auto count=WideCharToMultiByte(nameCodePage_,flags,name.data(),length,nullptr,0,nullptr,replacement);
requireFileOperation(count>0 && !substituted,ERROR_NO_UNICODE_TRANSLATION);
std::string bytes(count,'\0');
checkFileOperation(WideCharToMultiByte(nameCodePage_,flags,name.data(),length,bytes.data(),count,nullptr,replacement)>0);
requireFileOperation(!substituted,ERROR_NO_UNICODE_TRANSLATION);
return bytes;
}
const fs::path &initialDirectory()
{
std::string bytes(32768,'\0');
DWORD length=static_cast<DWORD>(bytes.size());
checkFileOperation(FtpGetCurrentDirectoryA(handle(),bytes.data(),&length));
auto initial=decodeName(bytes.c_str());
if(initial.empty() || initial.front()!=L'/' || initial.find_first_of(L"\\\r\n")!=initial.npos)
throw std::system_error(ERROR_BAD_PATHNAME,std::system_category());
const auto first=initial.find_first_not_of(L'/');
if(first==initial.npos) current_=ftpRoot;
else
{
initial.erase(1,first-1);
std::replace(initial.begin(),initial.end(),L'/',L'\\');
current_=fs::path(initial).lexically_normal();
if(current_.has_relative_path() && !current_.has_filename()) current_=current_.parent_path();
}
return current_;
}
void setDirectory(const fs::path &path)
{
if(current_==path) return;
checkFileOperation(FtpSetCurrentDirectoryA(handle(),encodeName(path).c_str()));
current_=path;
}
};
DWORD listFtpDirectory(FtpSession &session,const fs::path &directory,const FileVisitor &visit,
std::stop_token stop={})
{
if(stop.stop_requested()) return ERROR_CANCELLED;
session.setDirectory(directory);
if(stop.stop_requested()) return ERROR_CANCELLED;
WIN32_FIND_DATAA entry{};
const FtpHandle search{FtpFindFirstFileA(session.handle(),nullptr,&entry,
INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE,0)};
if(!search.value) return GetLastError();
do
{
const auto name=session.decodeName(entry.cFileName);
if(name.empty() || name==L"." || name==L".." || name.find_first_of(L"/\\:\r\n")!=name.npos)
continue;
const auto ftpTime=[](const FILETIME &local) -> uint64_t
{
FILETIME utc{};
if((!local.dwLowDateTime && !local.dwHighDateTime) || !LocalFileTimeToFileTime(&local,&utc)) return 0;
return (uint64_t(utc.dwHighDateTime)<<32)|utc.dwLowDateTime;
};
FileInfo info{entry.dwFileAttributes,(uint64_t(entry.nFileSizeHigh)<<32)|entry.nFileSizeLow,
ftpTime(entry.ftLastWriteTime)};
const TransferItemMetadata details{ftpTime(entry.ftCreationTime),ftpTime(entry.ftLastAccessTime)};
if(details.created || details.accessed) info.transfer=details;
if(!visit(directory/name,info)) return ERROR_CANCELLED;
} while(!stop.stop_requested() && InternetFindNextFileA(search.value,&entry));
return stop.stop_requested()?ERROR_CANCELLED:GetLastError();
}
-192
View File
@@ -1,192 +0,0 @@
FileEntries transferChildren(TransferSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr)
{
FileEntries entries;
const auto error=session.list(directory,[&](const fs::path &path,const FileInfo &info)
{
if(canceled && *canceled) return false;
entries.emplace_back(path,info);
return true;
});
requireFileOperation(error==ERROR_NO_MORE_FILES,error);
return entries;
}
std::optional<FileInfo> transferEntry(const FileEntries &entries,const fs::path &path)
{
const auto entry=std::find_if(entries.begin(),entries.end(),
[&](const auto &item){return item.first==path;});
return entry==entries.end()?std::nullopt:std::optional<FileInfo>(entry->second);
}
struct CopyHost
{
std::optional<FilesConnection> files;
std::optional<TransferSession> ftp;
FileOperationElevation *elevation{};
fs::path listedDirectory;
FileEntries listedEntries;
CopyHost(const FilesPeer *peer,const std::optional<TransferProfile> &profile,FileOperationElevation *admin=nullptr)
{
if(profile) ftp.emplace(*profile);
else files.emplace(peer);
if(!peer && !profile) elevation=admin;
}
Json request(const Json &message,const ks::lan::FileProgress &progress={})
{
return elevation?elevation->call(*files,message,progress):files->call(message,progress);
}
const FileEntries &ftpListing(const fs::path &path,const std::atomic_bool &canceled)
{
if(path!=listedDirectory)
{
listedEntries=transferChildren(*ftp,path,&canceled);
listedDirectory=path;
}
return listedEntries;
}
std::optional<FileInfo> stat(const fs::path &path,const std::atomic_bool &canceled)
{
return ftp?transferEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path)));
}
FileEntries children(const fs::path &path,const std::atomic_bool &canceled)
{
if(ftp) return ftpListing(path,canceled);
if(!elevation) return childrenOf(*files,path);
FileEntries entries;
elevation->list(*files,path,[&](const fs::path &child,const FileInfo &info)
{
if(canceled) return false;
entries.emplace_back(child,info);
return true;
});
return entries;
}
void makeDirectory(const fs::path &path)
{
if(!ftp)
{
checkFileReply(request(fileRequest("mkdir",path)));
return;
}
ftp->makeDirectory(path);
listedDirectory.clear();
}
void remove(const fs::path &path,bool permanent,DWORD attributes,bool readOnly)
{
if(ftp)
{
ftp->remove(path,attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY));
return;
}
auto message=fileRequest(permanent?"remove":"recycle",path);
message["readOnly"]=readOnly;
checkFileReply(request(message));
}
};
void downloadTransferFile(TransferSession &ftp,FilesConnection &local,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress)
{
auto input=ftp.open(source,false);
auto upload=fileRequest("openWrite",target);
upload["transfer"]=ks::lan::randomHex(32);
upload["size"]=info.size;
try
{
const auto output=local.call(upload);
checkFileReply(output);
requireFileOperation(output.value("offset",uint64_t{1})==0,ERROR_FILE_INVALID);
uint64_t done=0;
ks::Bytes bytes(ks::lan::FileChunk);
while(!progress || progress(done,info.size))
{
const auto read=input.read(bytes.data(),bytes.size());
if(!read)
{
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
checkFileReply(local.call({{"action","commit"},{"replace",replace},{"modified",info.modified}}));
return;
}
requireFileOperation(read<=info.size-done,ERROR_FILE_INVALID);
checkFileReply(local.call({{"action","write"},
{"data",Json::binary(ks::Bytes(bytes.begin(),bytes.begin()+read))}}));
done+=read;
}
requireFileOperation(false,ERROR_CANCELLED);
}
catch(...)
{
local.call({{"action","abort"}});
throw;
}
}
FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress,
const ks::files::RemoteTextRevision *expected=nullptr)
{
const auto directory=target.parent_path();
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
auto open=fileRequest("openRead",source);
open["size"]=info.size;
open["modified"]=info.modified;
checkFileReply(local.call(open));
bool staged=false,reading=true;
try
{
uint64_t done=0;
{
auto output=ftp.open(temporary,true);
staged=true;
for(;;)
{
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
const auto packet=local.call({{"action","read"}});
checkFileReply(packet);
const auto &bytes=packet.at("data").get_binary();
if(bytes.empty()) break;
requireFileOperation(bytes.size()<=info.size-done,ERROR_FILE_INVALID);
for(size_t offset=0;offset<bytes.size();)
{
const auto written=output.write(bytes.data()+offset,bytes.size()-offset);
requireFileOperation(written!=0,ERROR_WRITE_FAULT);
offset+=written;
}
done+=bytes.size();
}
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
output.close();
}
checkFileReply(local.call({{"action","closeRead"}}));
reading=false;
const auto entries=transferChildren(ftp,directory);
const auto uploaded=transferEntry(entries,temporary);
requireFileOperation(uploaded && uploaded->size==done,ERROR_WRITE_FAULT);
const auto existing=transferEntry(entries,target);
if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified))
throw std::runtime_error("The "+ks::utf8(ftp.label())+" file changed since it was opened. Your edits are still in the editor.");
if(existing)
{
requireFileOperation(replace && !(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_ALREADY_EXISTS);
ftp.prepareReplacement(temporary,target);
}
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
ftp.rename(temporary,target,existing.has_value());
return *uploaded;
}
catch(...)
{
if(reading) try {local.call({{"action","closeRead"}});} catch(const std::exception &) {}
if(staged) try {ftp.remove(temporary,false);} catch(const std::exception &) {}
throw;
}
}
-324
View File
@@ -1,324 +0,0 @@
namespace transferDialog
{
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566,jumpVia=567,jumpLabel=568;
constexpr int sudoLabel=569,sudoServer=570;
struct Edit
{
TransferProfile profile;
std::optional<size_t> index;
std::wstring pinnedHost;
INTERNET_PORT pinnedPort{};
std::string pin;
std::vector<std::string> jumpChoices;
bool testing{};
std::atomic_bool canceled{};
};
bool sameEndpoint(const Edit &edit,const TransferProfile &profile)
{
return edit.pinnedPort==profile.port && CompareStringOrdinal(edit.pinnedHost.c_str(),-1,
profile.host.c_str(),-1,TRUE)==CSTR_EQUAL;
}
std::wstring connectionTitle(TransferProtocol protocol)
{
return std::wstring(transferProtocolName(protocol))+L" connection";
}
void showHostStatus(HWND dialog,const Edit &edit)
{
TransferProfile current;
current.host=trimFilesField(shortcutField(dialog,host));
BOOL valid{};
current.port=static_cast<INTERNET_PORT>(GetDlgItemInt(dialog,port,&valid,FALSE));
const bool trusted=valid && !edit.pin.empty() && sameEndpoint(edit,current);
const auto message=trusted?L"Trusted "+ks::wide(edit.pin):std::wstring(L"Host key not verified");
SetDlgItemTextW(dialog,hostStatus,message.c_str());
EnableWindow(GetDlgItem(dialog,forgetKey),trusted && !edit.testing);
}
void addJumpChoice(HWND dialog,Edit &edit,const std::wstring &label,const std::string &id)
{
const auto row=SendDlgItemMessageW(dialog,jumpVia,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row==CB_ERR || row==CB_ERRSPACE) return;
edit.jumpChoices.push_back(id);
if(id==edit.profile.jumpProfile) SendDlgItemMessageW(dialog,jumpVia,CB_SETCURSEL,row,0);
}
void populateJumpChoices(HWND dialog,Edit &edit)
{
addJumpChoice(dialog,edit,L"Direct",{});
for(const auto &profile:transferProfiles(TransferProtocol::sftp).rows)
if(profile.id!=edit.profile.id) addJumpChoice(dialog,edit,profile.name,profile.id);
if(SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0)==CB_ERR)
addJumpChoice(dialog,edit,L"Missing profile",edit.profile.jumpProfile);
}
std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
{
TransferProfile profile;
profile.protocol=edit.profile.protocol;
const bool sftp=profile.protocol==TransferProtocol::sftp;
const auto invalid=[&](int field,const wchar_t *message)->std::optional<TransferProfile>
{
showFilesNotice(dialog,message,connectionTitle(profile.protocol).c_str());
SetFocus(GetDlgItem(dialog,field));
return {};
};
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
profile.legacyNames=!sftp && IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
profile.name=trimFilesField(shortcutField(dialog,name));
if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos)
return invalid(name,L"Enter a name for this connection.");
const auto &profiles=transferProfiles(profile.protocol).rows;
for(size_t i=0;i<profiles.size();++i)
if(edit.index!=i && CompareStringOrdinal(profiles[i].name.c_str(),-1,profile.name.c_str(),-1,TRUE)==CSTR_EQUAL)
return invalid(name,L"A connection with this name already exists.");
profile.host=trimFilesField(shortcutField(dialog,host));
if(profile.host.empty() || profile.host.find_first_of(L" /\\@\t\r\n")!=profile.host.npos)
return invalid(host,L"Enter the server host name or IP address.");
const auto value=shortcutField(dialog,port);
const auto number=value.empty() || value.find_first_not_of(L"0123456789")!=value.npos?0:std::stoul(value);
if(!number || number>65535) return invalid(port,L"Enter a port from 1 to 65535.");
profile.port=static_cast<INTERNET_PORT>(number);
profile.user=shortcutField(dialog,user);
if(profile.user.find_first_of(L"\r\n")!=profile.user.npos || (sftp && profile.user.empty()))
return invalid(user,L"Enter the user name on one line.");
if(sftp)
{
profile.privateKey=trimFilesField(shortcutField(dialog,keyFile));
if(!profile.privateKey.empty() && !profile.privateKey.is_absolute())
return invalid(keyFile,L"Enter the full path of the private key file.");
if(sameEndpoint(edit,profile)) profile.hostFingerprint=edit.pin;
profile.sudoSftpServer=trimFilesField(shortcutField(dialog,sudoServer));
if(!validSudoSftpServer(profile.sudoSftpServer))
return invalid(sudoServer,L"Enter the absolute path to sftp-server, for example /usr/lib/openssh/sftp-server.");
const auto choice=SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0);
if(choice>=0 && static_cast<size_t>(choice)<edit.jumpChoices.size())
profile.jumpProfile=edit.jumpChoices[choice];
try {sshRoute(profile,profiles);}
catch(const std::exception &error)
{
return invalid(jumpVia,ks::wide(error.what()).c_str());
}
}
auto plain=shortcutField(dialog,password);
if(!plain.empty())
{
const auto start=reinterpret_cast<const unsigned char*>(plain.data());
ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t));
struct Erase
{
ks::Bytes &bytes;
std::wstring &text;
~Erase()
{
SecureZeroMemory(bytes.data(),bytes.size());
SecureZeroMemory(text.data(),text.size()*sizeof(wchar_t));
}
} erase{bytes,plain};
profile.secret=ks::protect(bytes);
}
return profile;
}
template<class Task>
bool runTest(HWND dialog,Edit &edit,const wchar_t *status,Task task)
{
constexpr int controls[]{name,host,port,user,password,keyFile,jumpVia,sudoServer,testConnection,forgetKey,IDOK};
edit.testing=true;
edit.canceled=false;
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),FALSE);
SetFocus(GetDlgItem(dialog,IDCANCEL));
SetDlgItemTextW(dialog,hostStatus,status);
std::wstring error;
try
{
FileOperationUi worker;
worker.run(dialog,edit.canceled,std::move(task));
}
catch(const std::exception &exception) {error=ks::wide(exception.what());}
edit.testing=false;
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),TRUE);
showHostStatus(dialog,edit);
if(edit.canceled) return false;
if(error.empty()) return true;
showFilesNotice(dialog,error.c_str(),L"SFTP connection test",{.tone=FilesNoticeTone::warning});
return false;
}
void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
{
if(profile.hostFingerprint.empty())
{
std::string fingerprint;
if(!runTest(dialog,edit,L"Reading the SSH host key…",[&] {
const SshConnection probe(profile,true);
fingerprint=probe.fingerprint();
})) return;
const auto prompt=profile.host+L":"+std::to_wstring(profile.port)+L"\r\n"+ks::wide(fingerprint)+
L"\r\n\r\nVerify this fingerprint with the server administrator. Trust this SSH host key?";
if(showFilesNotice(dialog,prompt.c_str(),L"Verify SFTP host key",{.confirm=true})!=IDYES) return;
edit.pinnedHost=profile.host;
edit.pinnedPort=profile.port;
profile.hostFingerprint=edit.pin=std::move(fingerprint);
}
fs::path initial;
if(runTest(dialog,edit,L"Testing the SSH login…",[&] {
SshConnection connection(profile);
const SftpSubsystem sftp(libssh2_sftp_init(connection.session()),libssh2_sftp_shutdown);
if(sftp) initial=sftpInitialDirectory(sftp.get());
}))
{
const auto details=L"Connected to "+profile.host+L".\r\n\r\n"+(initial.empty()?
L"SFTP is unavailable. This profile can still be used as an SSH jump host.":
L"Initial folder "+ftpPath(initial)+L".");
showFilesNotice(dialog,details.c_str(),L"SFTP connection test");
}
}
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *edit=message==WM_INITDIALOG?reinterpret_cast<Edit*>(lp):
reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
const bool sftp=edit && edit->profile.protocol==TransferProtocol::sftp;
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,sftp?L" SFTP connection ":L" FTP connection ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &profile=edit->profile;
prepareCopyDialog(dialog);
layoutDialogContent(dialog,381);
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus,jumpVia,jumpLabel,sudoLabel})
if(const auto control=GetDlgItem(dialog,id)) SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
for(const auto id:{name,host,user,password})
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0);
SetDlgItemTextW(dialog,name,profile.name.c_str());
SetDlgItemTextW(dialog,host,profile.host.c_str());
SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str());
SetDlgItemTextW(dialog,user,profile.user.c_str());
if(sftp)
{
SendDlgItemMessageW(dialog,keyFile,EM_SETLIMITTEXT,32767,0);
SetDlgItemTextW(dialog,keyFile,profile.privateKey.c_str());
SendDlgItemMessageW(dialog,sudoServer,EM_SETLIMITTEXT,255,0);
SetDlgItemTextW(dialog,sudoServer,profile.sudoSftpServer.c_str());
populateJumpChoices(dialog,*edit);
installFarCombo(GetDlgItem(dialog,jumpVia),GetDlgItem(dialog,keyFile));
showHostStatus(dialog,*edit);
layoutDialogButtons(dialog,footer,{testConnection,forgetKey,IDOK,IDCANCEL});
}
else
{
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
}
try
{
auto secret=transferPassword(profile);
SetDlgItemTextW(dialog,password,secret.c_str());
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,389,L"&Secret (re-enter to replace the saved value)");
}
return TRUE;
}
if(!edit) return FALSE;
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
if(edit->testing)
{
edit->canceled=true;
SetDlgItemTextW(dialog,hostStatus,L"Stopping when the current request returns…");
}
else
{
SetDlgItemTextW(dialog,password,L"");
SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0);
FilesModalDialog::finish(dialog,IDCANCEL);
}
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(edit->testing) return TRUE;
const auto command=LOWORD(wp);
if(sftp && HIWORD(wp)==EN_CHANGE && (command==host || command==port))
{
showHostStatus(dialog,*edit);
return TRUE;
}
if(sftp && command==forgetKey)
{
if(showFilesNotice(dialog,L"Forget the trusted key for this endpoint? A new key must be verified before signing in.",
L"SFTP host key",{.confirm=true})==IDYES)
{
edit->pin.clear();
showHostStatus(dialog,*edit);
}
return TRUE;
}
if(command!=IDOK && (!sftp || command!=testConnection)) return FALSE;
try
{
auto profile=readProfile(dialog,*edit);
if(!profile) return TRUE;
if(command==testConnection)
{
testSftp(dialog,*edit,std::move(*profile));
return TRUE;
}
auto &settings=transferProfiles(profile->protocol);
auto updated=settings.rows;
if(edit->index) updated[*edit->index]=std::move(*profile);
else updated.push_back(std::move(*profile));
if(saveTransferProfiles(edit->profile.protocol,updated))
{
settings.rows=std::move(updated);
SetDlgItemTextW(dialog,password,L"");
SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
}
catch(const std::exception &) {}
const auto title=connectionTitle(edit->profile.protocol);
showFilesNotice(dialog,(L"Could not save the "+title+L".").c_str(),title.c_str());
return TRUE;
}
}
void editTransferProfile(Panel &panel,bool create)
{
transferDialog::Edit edit;
const auto protocol=panel.ftp->protocol;
const auto &profiles=transferProfiles(protocol).rows;
edit.profile.protocol=protocol;
if(protocol==TransferProtocol::sftp) edit.profile.port=defaultSftpPort;
if(!create)
{
const auto row=currentPanelRow(panel);
if(row<0 || static_cast<size_t>(row)>=profiles.size()) return;
edit.index=static_cast<size_t>(row);
edit.profile=profiles[*edit.index];
edit.pinnedHost=edit.profile.host;
edit.pinnedPort=edit.profile.port;
edit.pin=edit.profile.hostFingerprint;
}
const auto owner=GetParent(panel.list);
const auto resource=protocol==TransferProtocol::sftp?124:112;
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(resource),owner,
transferDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
for(auto &other:panels)
{
if(!transferProfileList(other) || other.ftp->protocol!=protocol || other.scan.valid()) continue;
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(profiles.size()-1)):fs::path{};
showTransferProfiles(other,protocol,selection);
}
}
-307
View File
@@ -1,307 +0,0 @@
#include "files_git_changes.h"
#include "core.h"
#include "windows_command_line.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <system_error>
#include <tuple>
#include <utility>
namespace ks::files
{
namespace
{
namespace fs=std::filesystem;
struct GitHandle
{
HANDLE value{};
void close()
{
if(value && value!=INVALID_HANDLE_VALUE) CloseHandle(value);
value=nullptr;
}
~GitHandle(){close();}
};
[[noreturn]] void gitWindowsError(const char *operation)
{
throw std::system_error(GetLastError(),std::system_category(),operation);
}
void makeGitPipe(GitHandle &read,GitHandle &write,SECURITY_ATTRIBUTES &inheritable)
{
if(!CreatePipe(&read.value,&write.value,&inheritable,0) ||
!SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0))
gitWindowsError("Could not create the Git output pipe");
}
fs::path locateGit()
{
const DWORD size=GetEnvironmentVariableW(L"PATH",nullptr,0);
std::wstring paths(size,L'\0');
if(size)
{
const auto count=GetEnvironmentVariableW(L"PATH",paths.data(),size);
paths.resize(count<size?count:0);
}
std::wstring_view remaining=paths;
while(!remaining.empty())
{
const auto end=remaining.find(L';');
auto directory=remaining.substr(0,end);
if(directory.size()>=2 && directory.front()==L'"' && directory.back()==L'"')
directory=directory.substr(1,directory.size()-2);
const auto path=fs::path(directory);
if(path.is_absolute())
{
const auto candidate=path/L"git.exe";
const auto attributes=GetFileAttributesW(candidate.c_str());
if(attributes!=INVALID_FILE_ATTRIBUTES && !(attributes&FILE_ATTRIBUTE_DIRECTORY)) return candidate;
}
if(end==remaining.npos) break;
remaining.remove_prefix(end+1);
}
for(const auto key:{HKEY_CURRENT_USER,HKEY_LOCAL_MACHINE})
{
wchar_t install[32768]{};
DWORD bytes=sizeof(install);
if(RegGetValueW(key,L"SOFTWARE\\GitForWindows",L"InstallPath",RRF_RT_REG_SZ,nullptr,install,&bytes)!=ERROR_SUCCESS)
continue;
const auto git=fs::path(install)/L"cmd"/L"git.exe";
if(git.is_absolute() && GetFileAttributesW(git.c_str())!=INVALID_FILE_ATTRIBUTES) return git;
}
throw std::runtime_error("Git for Windows was not found. Install it or add git.exe to PATH.");
}
std::vector<wchar_t> gitEnvironment()
{
const auto environment=GetEnvironmentStringsW();
if(!environment) gitWindowsError("Could not read the environment for Git");
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> owned(environment,FreeEnvironmentStringsW);
constexpr std::wstring_view overrides[]{
L"GIT_DIR",L"GIT_WORK_TREE",L"GIT_COMMON_DIR",L"GIT_INDEX_FILE",L"GIT_PREFIX",
L"GIT_CEILING_DIRECTORIES",L"GIT_GLOB_PATHSPECS",L"GIT_NOGLOB_PATHSPECS",L"GIT_ICASE_PATHSPECS"};
std::vector<wchar_t> result;
for(auto entry=environment;*entry;)
{
const std::wstring_view setting=entry;
const auto name=setting.substr(0,setting.find(L'='));
if(std::none_of(std::begin(overrides),std::end(overrides),[&](std::wstring_view key) {
return name.size()==key.size() &&
CompareStringOrdinal(name.data(),static_cast<int>(name.size()),key.data(),static_cast<int>(key.size()),TRUE)
==CSTR_EQUAL;
}))
result.insert(result.end(),entry,entry+setting.size()+1);
entry+=setting.size()+1;
}
result.push_back(L'\0');
if(result.size()==1) result.push_back(L'\0');
return result;
}
struct GitProcessAttributes
{
std::vector<std::byte> storage;
LPPROC_THREAD_ATTRIBUTE_LIST list{};
explicit GitProcessAttributes(HANDLE (&inherited)[3])
{
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
storage.resize(bytes);
const auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes))
gitWindowsError("Could not initialize the Git process");
if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr))
{
const auto error=GetLastError();
DeleteProcThreadAttributeList(attributes);
throw std::system_error(error,std::system_category(),"Could not set Git process handles");
}
list=attributes;
}
~GitProcessAttributes(){DeleteProcThreadAttributeList(list);}
};
struct GitOutput
{
std::string output, error;
DWORD exitCode{};
};
GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector<std::wstring> &arguments,
size_t maximum,std::stop_token stop)
{
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
auto command=quoteWindowsArgument(git.native())+
L" --no-pager --no-optional-locks --literal-pathspecs -c core.fsmonitor=false -c core.quotePath=false -C "+
quoteWindowsArgument(directory.native());
for(const auto &argument:arguments) command+=L' '+quoteWindowsArgument(argument);
auto environment=gitEnvironment();
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
const GitHandle input{CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr)};
if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input");
GitHandle out,childOut,error,childError;
makeGitPipe(out,childOut,inheritable);
makeGitPipe(error,childError,inheritable);
HANDLE inherited[]{input.value,childOut.value,childError.value};
GitProcessAttributes attributes(inherited);
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput=input.value;
startup.StartupInfo.hStdOutput=childOut.value;
startup.StartupInfo.hStdError=childError.value;
startup.lpAttributeList=attributes.list;
PROCESS_INFORMATION child{};
if(!CreateProcessW(git.c_str(),command.data(),nullptr,nullptr,TRUE,
CREATE_NO_WINDOW|CREATE_SUSPENDED|CREATE_UNICODE_ENVIRONMENT|EXTENDED_STARTUPINFO_PRESENT,
environment.data(),directory.c_str(),&startup.StartupInfo,&child))
gitWindowsError("Could not start Git");
const GitHandle process{child.hProcess},thread{child.hThread};
const GitHandle job{CreateJobObjectW(nullptr,nullptr)};
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(job.value && SetInformationJobObject(job.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))
AssignProcessToJobObject(job.value,process.value);
try
{
if(ResumeThread(thread.value)==DWORD(-1)) gitWindowsError("Could not resume Git");
childOut.close();
childError.close();
GitOutput result;
const auto deadline=GetTickCount64()+15000;
const auto read=[&](HANDLE pipe,std::string &data,size_t limit)
{
DWORD waiting{},readBytes{};
char buffer[8192];
if(!PeekNamedPipe(pipe,nullptr,0,nullptr,&waiting,nullptr))
{
if(GetLastError()==ERROR_BROKEN_PIPE) return false;
gitWindowsError("Could not read Git output");
}
if(!waiting) return false;
if(!ReadFile(pipe,buffer,std::min<DWORD>(waiting,sizeof(buffer)),&readBytes,nullptr))
gitWindowsError("Could not read Git output");
if(data.size()+readBytes>limit) throw std::runtime_error("Git output was too large to display.");
data.append(buffer,readBytes);
return readBytes!=0;
};
for(;;)
{
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
if(GetTickCount64()>=deadline) throw std::runtime_error("Git did not respond in time.");
const bool readOutput=read(out.value,result.output,maximum);
const bool readErrors=read(error.value,result.error,256*1024);
const auto state=WaitForSingleObject(process.value,readOutput || readErrors?0:20);
if(state==WAIT_FAILED) gitWindowsError("Could not wait for Git");
if(state==WAIT_OBJECT_0 && !readOutput && !readErrors)
{
if(read(out.value,result.output,maximum) || read(error.value,result.error,256*1024))
continue;
if(!GetExitCodeProcess(process.value,&result.exitCode)) gitWindowsError("Could not read Git status");
return result;
}
}
}
catch(...)
{
TerminateProcess(process.value,ERROR_CANCELLED);
throw;
}
}
void checkGit(const GitOutput &result,const char *operation,bool allowDifference=false)
{
if(!result.exitCode || (allowDifference && result.exitCode==1)) return;
auto detail=result.error;
while(!detail.empty() && (detail.back()=='\r' || detail.back()=='\n')) detail.pop_back();
throw std::runtime_error(detail.empty()?std::string(operation):std::string(operation)+"\r\n"+detail);
}
std::string_view statusField(std::string_view &input)
{
const auto separator=input.find('\0');
if(separator==input.npos) throw std::runtime_error("Git returned incomplete status output.");
const auto field=input.substr(0,separator);
input.remove_prefix(separator+1);
return field;
}
std::wstring statusPath(std::string_view value)
{
if(value.empty() || value.starts_with('/') || value.find_first_of("\\:")!=value.npos)
throw std::runtime_error("Git returned an unsupported worktree path.");
for(auto suffix=value;!suffix.empty();)
{
const auto slash=suffix.find('/');
const auto part=suffix.substr(0,slash);
if(part=="." || part==".." || part.empty())
throw std::runtime_error("Git returned an unsupported worktree path.");
if(slash==suffix.npos) break;
suffix.remove_prefix(slash+1);
}
return wide(std::string(value));
}
std::vector<GitChange> parseGitStatus(std::string_view output)
{
std::vector<GitChange> result;
while(!output.empty())
{
const auto row=statusField(output);
if(row.size()<4 || row[2]!=' ') throw std::runtime_error("Git returned an invalid status record.");
const auto code=row.substr(0,2);
const auto path=statusPath(row.substr(3));
std::wstring origin;
if(code.find_first_of("RC")!=code.npos) origin=statusPath(statusField(output));
if(code=="??") result.push_back({GitChangeKind::untracked,path,{},L"?"});
else if(code=="DD" || code=="AA" || code.find('U')!=code.npos)
result.push_back({GitChangeKind::unstaged,path,{},wide(std::string(code))});
else
{
if(code[0]!=' ') result.push_back({GitChangeKind::staged,path,origin,std::wstring(1,code[0])});
if(code[1]!=' ') result.push_back({GitChangeKind::unstaged,path,origin,std::wstring(1,code[1])});
}
}
std::sort(result.begin(),result.end(),[](const auto &left,const auto &right) {
return std::tie(left.kind,left.path)<std::tie(right.kind,right.path);
});
return result;
}
}
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop)
{
GitChanges result;
result.executable=locateGit();
auto root=runGit(result.executable,directory,{L"rev-parse",L"--show-toplevel"},64*1024,stop);
checkGit(root,"This folder is not inside a Git worktree.");
while(!root.output.empty() && (root.output.back()=='\r' || root.output.back()=='\n')) root.output.pop_back();
result.root=fs::path(wide(root.output)).make_preferred();
if(!result.root.is_absolute()) throw std::runtime_error("Git returned an invalid worktree root.");
const auto status=runGit(result.executable,result.root,
{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"},8*1024*1024,stop);
checkGit(status,"Could not read Git worktree status.");
result.entries=parseGitStatus(status.output);
return result;
}
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
const GitChange &change,std::stop_token stop)
{
std::vector<std::wstring> args{L"diff",L"--no-color",L"--no-ext-diff",L"--no-textconv",L"--find-renames"};
const bool untracked=change.kind==GitChangeKind::untracked;
if(untracked) args.push_back(L"--no-index");
if(change.kind==GitChangeKind::staged) args.push_back(L"--cached");
args.push_back(L"--");
if(untracked) args.push_back(L"/dev/null");
else if(!change.oldPath.empty()) args.push_back(change.oldPath);
args.push_back(change.path);
auto patch=runGit(git,root,args,2*1024*1024,stop);
checkGit(patch,"Could not read this Git diff.",untracked);
return std::move(patch.output);
}
}
-29
View File
@@ -1,29 +0,0 @@
#pragma once
#include <filesystem>
#include <stop_token>
#include <string>
#include <vector>
namespace ks::files
{
enum class GitChangeKind { staged, unstaged, untracked };
struct GitChange
{
GitChangeKind kind;
std::wstring path;
std::wstring oldPath;
std::wstring flags;
bool operator==(const GitChange &) const = default;
};
struct GitChanges
{
std::filesystem::path executable, root;
std::vector<GitChange> entries;
};
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop);
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
const GitChange &change,std::stop_token stop);
}
-412
View File
@@ -1,412 +0,0 @@
using ks::files::GitChange;
using ks::files::GitChangeKind;
using ks::files::GitChanges;
struct GitChangesView
{
HWND host{},heading{},filterLabel{},filter{},list{},status{},hints{},preview{};
fs::path folder;
GitChanges data;
std::future<GitChanges> refresh;
std::future<std::string> diff;
std::stop_source stopRefresh,stopDiff;
ULONGLONG diffAt{};
std::optional<GitChange> requested;
std::string failure;
};
std::unique_ptr<GitChangesView> gitChangesView;
constexpr wchar_t gitChangesClass[]=L"KSwitcher.Files.GitChanges";
constexpr UINT_PTR gitChangesTimer=1;
constexpr int gitHeading=570,gitFilter=571,gitList=572,gitStatus=573;
const wchar_t *gitChangeKindName(GitChangeKind kind)
{
switch(kind)
{
case GitChangeKind::staged: return L"Staged";
case GitChangeKind::unstaged: return L"Unstaged";
case GitChangeKind::untracked: return L"Untracked";
}
return L"";
}
const GitChange *selectedGitChange(const GitChangesView &view)
{
const auto row=SendMessageW(view.list,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendMessageW(view.list,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<view.data.entries.size()?&view.data.entries[index]:nullptr;
}
std::wstring gitDiffHeading(const GitChange &entry)
{
return std::wstring(gitChangeKindName(entry.kind))+L" diff · "+entry.path;
}
void queueGitDiff(GitChangesView &view)
{
view.stopDiff.request_stop();
view.diff={};
view.diffAt=0;
view.requested.reset();
if(view.refresh.valid())
{
ks::files::previewQuickViewDiff(view.preview,L"Diff · Reading Git changes…",{});
return;
}
if(!view.failure.empty())
{
ks::files::previewQuickViewDiff(view.preview,L"Git status failed",view.failure);
return;
}
if(const auto *entry=selectedGitChange(view))
{
view.requested=*entry;
view.diffAt=GetTickCount64()+100;
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*entry)+L" · Loading…",{});
}
else ks::files::previewQuickViewDiff(view.preview,L"Diff · Select a change",{});
}
void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
{
auto query=dialogFieldText(view.filter);
std::replace(query.begin(),query.end(),L'\\',L'/');
const auto matches=[&](std::wstring_view path)
{
return query.empty() || (!path.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
path.data(),static_cast<int>(path.size()),query.data(),static_cast<int>(query.size()),
nullptr,nullptr,nullptr,0)>=0);
};
SendMessageW(view.list,WM_SETREDRAW,FALSE,0);
SendMessageW(view.list,LB_RESETCONTENT,0,0);
LRESULT selected=0,count=0;
for(size_t index=0;index<view.data.entries.size();++index)
{
const auto &entry=view.data.entries[index];
if(!matches(entry.path) && !matches(entry.oldPath)) continue;
auto state=std::wstring(gitChangeKindName(entry.kind));
state.resize(10,L' ');
state+=entry.flags;
state.resize(13,L' ');
const auto label=state+(entry.oldPath.empty()?entry.path:entry.path+L" ← "+entry.oldPath);
const auto row=SendMessageW(view.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row<0) continue;
++count;
SendMessageW(view.list,LB_SETITEMDATA,row,index);
if(previous && previous->path==entry.path && previous->kind==entry.kind) selected=row;
}
if(count) SendMessageW(view.list,LB_SETCURSEL,selected,0);
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(view.list,nullptr,TRUE);
InvalidateRect(view.host,nullptr,FALSE);
const auto total=view.data.entries.size();
const auto status=view.refresh.valid()?std::wstring(L"Reading Git changes…"):
!view.failure.empty()?L"Could not read Git changes.":
!total?L"No Git changes.":!count?L"No paths match the filter.":
std::to_wstring(count)+(query.empty()?L"":L" of "+std::to_wstring(total))+L" changes";
SetWindowTextW(view.status,status.c_str());
queueGitDiff(view);
}
void refreshGitChanges(GitChangesView &view)
{
if(view.refresh.valid()) return;
view.failure.clear();
view.stopRefresh=std::stop_source{};
try
{
std::packaged_task<GitChanges()> task([folder=view.folder,stop=view.stopRefresh.get_token()] {
return ks::files::readGitChanges(folder,stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.refresh=std::move(pending);
SetWindowTextW(view.status,L"Reading Git changes…");
queueGitDiff(view);
}
catch(const std::exception &)
{
view.failure="Could not start Git.";
renderGitChanges(view);
}
}
void pollGitChanges(GitChangesView &view)
{
using namespace std::chrono_literals;
if(view.refresh.valid() && view.refresh.wait_for(0ms)==std::future_status::ready)
{
const auto *entry=selectedGitChange(view);
const auto selected=entry?std::optional(*entry):std::nullopt;
try
{
view.data=view.refresh.get();
SetWindowTextW(view.heading,(L"Git Changes · "+view.data.root.native()).c_str());
renderGitChanges(view,selected);
}
catch(const std::exception &error)
{
view.data={};
view.failure=error.what();
renderGitChanges(view);
}
}
if(view.diffAt && GetTickCount64()>=view.diffAt)
{
view.diffAt=0;
view.stopDiff=std::stop_source{};
try
{
std::packaged_task<std::string()> task([git=view.data.executable,root=view.data.root,
entry=*view.requested,stop=view.stopDiff.get_token()] {
return ks::files::readGitPatch(git,root,entry,stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.diff=std::move(pending);
}
catch(const std::exception &)
{
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),"Could not start Git diff.");
}
}
if(view.diff.valid() && view.diff.wait_for(0ms)==std::future_status::ready)
{
try
{
const auto patch=view.diff.get();
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),
patch.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(patch));
}
catch(const std::exception &error)
{
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),error.what());
}
}
}
void openGitWorkingFile(GitChangesView &view,bool edit)
{
const auto *entry=selectedGitChange(view);
if(!entry || view.refresh.valid() || !view.failure.empty()) return;
auto relative=fs::path(entry->path);
for(const auto &component:relative)
if(!validFileName(component.native()))
{
SetWindowTextW(view.status,L"This path cannot be opened as a Windows file.");
return;
}
auto path=view.data.root/relative.make_preferred();
const auto attributes=GetFileAttributesW(path.c_str());
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY))
{
SetWindowTextW(view.status,L"No current working file for this change.");
return;
}
const auto owner=GetParent(view.host);
if(!edit && ks::files::isImagePath(path)) ks::files::openImageWindow(owner,{path},path,textWindowDialogs());
else ks::files::openTextWindow(owner,path,edit,textWindowDialogs());
}
void layoutGitChildren(GitChangesView &view)
{
RECT bounds{};
GetClientRect(view.host,&bounds);
const int middle=panelDivider(bounds.right);
const auto place=[](HWND control,int x,int y,int width,int height)
{
SetWindowPos(control,nullptr,x,y,std::max(0,width),std::max(0,height),SWP_NOZORDER|SWP_NOACTIVATE);
};
const int inset=6, top=4, filterLabel=8*cellWidth;
const int filterTop=top+textHeight+6, listTop=filterTop+textHeight+6;
const int bottom=std::max(listTop,static_cast<int>(bounds.bottom)-textHeight-5);
const int leftWidth=std::max(0,middle-2*inset);
place(view.heading,inset,top,leftWidth,textHeight);
place(view.filterLabel,inset,filterTop,filterLabel,textHeight);
place(view.filter,inset+filterLabel,filterTop,leftWidth-filterLabel,textHeight);
place(view.list,inset,listTop,leftWidth-scrollBarWidth(view.list),bottom-listTop);
place(view.status,inset,bottom+3,leftWidth,textHeight);
place(view.preview,middle+inset,top,bounds.right-middle-2*inset,bottom-top);
place(view.hints,middle+inset,bottom+3,bounds.right-middle-2*inset,textHeight);
for(const auto control:{view.heading,view.filterLabel,view.filter,view.list,view.status,view.hints})
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendMessageW(view.list,LB_SETITEMHEIGHT,0,textHeight);
}
LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_NCCREATE)
{
const auto *create=reinterpret_cast<const CREATESTRUCTW *>(lp);
SetWindowLongPtrW(window,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(create->lpCreateParams));
}
const auto view=reinterpret_cast<GitChangesView *>(GetWindowLongPtrW(window,GWLP_USERDATA));
if(!view) return DefWindowProcW(window,message,wp,lp);
switch(message)
{
case WM_CREATE:
{
view->host=window;
const auto make=[&](const wchar_t *type,const wchar_t *text,DWORD style,int id=0)
{
return CreateWindowW(type,text,WS_CHILD|WS_VISIBLE|style,0,0,0,0,window,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
};
view->heading=make(L"STATIC",L"Git Changes",SS_PATHELLIPSIS|SS_NOPREFIX,gitHeading);
view->filterLabel=make(L"STATIC",L"Filter",SS_NOPREFIX);
view->filter=make(farEditClass,L"",ES_MULTILINE|ES_AUTOHSCROLL|WS_TABSTOP,gitFilter);
view->list=make(L"LISTBOX",L"",LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT|LBS_NOTIFY|WS_TABSTOP,gitList);
view->status=make(L"STATIC",L"",SS_ENDELLIPSIS|SS_NOPREFIX,gitStatus);
view->hints=make(L"STATIC",L"F3 View F4 Edit Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX);
try {view->preview=ks::files::createQuickView(window,textWindowDialogs());}
catch(const std::exception &) {}
if(!view->heading || !view->filterLabel || !view->filter || !view->list || !view->status ||
!view->hints || !view->preview || !SetTimer(window,gitChangesTimer,35,nullptr)) return -1;
prepareDialogEdit(view->filter);
SendMessageW(view->filter,EM_SETLIMITTEXT,1024,0);
installScrollBar(view->list,window);
return 0;
}
case WM_SIZE:
if(view->preview) layoutGitChildren(*view);
return 0;
case WM_TIMER:
if(wp==gitChangesTimer) pollGitChanges(*view);
return 0;
case WM_COMMAND:
if(view->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE)
{
const auto *entry=selectedGitChange(*view);
renderGitChanges(*view,entry?std::optional(*entry):std::nullopt);
}
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitDiff(*view);
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_DBLCLK) openGitWorkingFile(*view,false);
return 0;
case WM_MEASUREITEM:
reinterpret_cast<MEASUREITEMSTRUCT *>(lp)->itemHeight=textHeight;
return TRUE;
case WM_DRAWITEM:
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
if(item.itemID==static_cast<UINT>(-1)) return TRUE;
const auto count=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
if(count<0) return TRUE;
std::wstring label(count+1,L'\0');
if(SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()))==LB_ERR)
return TRUE;
const bool selected=item.itemState&ODS_SELECTED;
paintText(item.hDC,item.rcItem,label.c_str(),colors[Text],colors[selected?PanelCursor:PanelBlue]);
return TRUE;
}
case WM_CTLCOLORSTATIC:
case WM_CTLCOLOREDIT:
case WM_CTLCOLORLISTBOX:
{
const auto dc=reinterpret_cast<HDC>(wp);
const bool input=message==WM_CTLCOLOREDIT;
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[input?Dialog:PanelBlue]);
return reinterpret_cast<LRESULT>(input?teal:blue);
}
case WM_PAINT:
{
PAINTSTRUCT paint{};
const auto dc=BeginPaint(window,&paint);
FillRect(dc,&paint.rcPaint,blue);
if(view->list) paintScrollPosition(window,dc,view->list,colors[PanelBlue]);
EndPaint(window,&paint);
return 0;
}
}
return DefWindowProcW(window,message,wp,lp);
}
void layoutGitChanges(HWND window)
{
if(!gitChangesView) return;
RECT bounds{};
GetClientRect(window,&bounds);
SetWindowPos(gitChangesView->host,HWND_TOP,0,0,bounds.right,bounds.bottom,SWP_NOACTIVATE|SWP_SHOWWINDOW);
layoutGitChildren(*gitChangesView);
}
bool showingGitChanges()
{
return static_cast<bool>(gitChangesView);
}
void closeGitChanges(HWND owner,bool restore=true)
{
auto view=std::move(gitChangesView);
if(!view) return;
view->stopRefresh.request_stop();
view->stopDiff.request_stop();
if(IsWindow(view->host)) DestroyWindow(view->host);
if(restore)
{
layout(owner);
restoreCommandFocus();
showFileDetails(panels[active]);
}
}
bool gitChangesAvailable(const Panel &panel)
{
return !terminalVisible && !panel.directory.empty() && !panel.ftp && !panel.peer && !panel.archive &&
!windowsNetworkPath(panel.directory);
}
void openGitChanges(HWND owner,const Panel &panel)
{
if(gitChangesView || !gitChangesAvailable(panel)) return;
const auto instance=GetModuleHandleW(nullptr);
static const bool registered=[instance]
{
WNDCLASSW type{};
type.lpfnWndProc=gitChangesProcedure;
type.hInstance=instance;
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
type.lpszClassName=gitChangesClass;
return RegisterClassW(&type)!=0;
}();
if(!registered) return;
auto view=std::make_unique<GitChangesView>();
view->folder=panel.directory;
if(!CreateWindowW(gitChangesClass,L"Git Changes",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
0,0,0,0,owner,nullptr,instance,view.get()))
{
setStatus(L"Could not open Git Changes.");
return;
}
gitChangesView=std::move(view);
closePanelSearch();
hideCompletion();
layout(owner);
ShowWindow(gitChangesView->preview,SW_SHOWNA);
SetFocus(gitChangesView->list);
refreshGitChanges(*gitChangesView);
}
bool handleGitChangesKey(HWND owner,const MSG &message)
{
auto &view=*gitChangesView;
if(message.message!=WM_KEYDOWN || FilesModalDialog::activeFor(owner) ||
(message.hwnd!=owner && message.hwnd!=view.host && !IsChild(view.host,message.hwnd))) return false;
const auto key=message.wParam;
const bool control=GetKeyState(VK_CONTROL)&0x8000;
const bool alt=GetKeyState(VK_MENU)&0x8000;
if(alt) return false;
if(!control && key==VK_ESCAPE) closeGitChanges(owner);
else if(control && key=='R') refreshGitChanges(view);
else if(control && key=='F') SetFocus(view.filter);
else if(!control && key==VK_TAB) SetFocus(GetFocus()==view.filter?view.list:view.filter);
else if(!control && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list)))
openGitWorkingFile(view,key==VK_F4);
else if(!control && GetFocus()==view.filter &&
(key==VK_UP || key==VK_DOWN || key==VK_PRIOR || key==VK_NEXT))
SendMessageW(view.list,WM_KEYDOWN,key,message.lParam);
else return false;
return true;
}
-16
View File
@@ -1,16 +0,0 @@
#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;
}
}
-157
View File
@@ -1,157 +0,0 @@
#include "files_image_decode.h"
#include <windows.h>
#include <wincodec.h>
#include <webp/decode.h>
#include <webp/demux.h>
#include <cstring>
#include <fstream>
#include <memory>
#include <stdexcept>
namespace ks::files
{
namespace
{
namespace fs=std::filesystem;
constexpr char invalidImage[]="Could not decode the image. The file may be damaged.";
constexpr char largeImage[]="This image is too large to preview.";
enum class ImageFormat { unknown, png, jpeg, gif, webp, bmp };
ImageFormat imageFormat(const fs::path &path)
{
const auto extension=path.extension();
const auto matches=[&](const wchar_t *suffix)
{
return CompareStringOrdinal(extension.c_str(),-1,suffix,-1,TRUE)==CSTR_EQUAL;
};
if(matches(L".png")) return ImageFormat::png;
if(matches(L".jpg") || matches(L".jpeg") || matches(L".jpe")) return ImageFormat::jpeg;
if(matches(L".gif")) return ImageFormat::gif;
if(matches(L".webp")) return ImageFormat::webp;
if(matches(L".bmp")) return ImageFormat::bmp;
return ImageFormat::unknown;
}
void checkImage(HRESULT result)
{
if(FAILED(result)) throw std::runtime_error(invalidImage);
}
void checkImageDimensions(unsigned width,unsigned height)
{
if(!width || !height) throw std::runtime_error(invalidImage);
if(width>16384 || height>16384 || uint64_t(width)*height>32ULL*1024*1024)
throw std::runtime_error(largeImage);
}
void checkImageStop(std::stop_token stop)
{
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
}
template<class T>
struct ImagingObject
{
T *value{};
~ImagingObject() {if(value) value->Release();}
T *operator->() const {return value;}
};
ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop)
{
struct Apartment
{
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
};
const Apartment apartment;
if(apartment.initialized!=RPC_E_CHANGED_MODE) checkImage(apartment.initialized);
ImagingObject<IWICImagingFactory> factory;
checkImage(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
ImagingObject<IWICStream> stream;
checkImage(factory->CreateStream(&stream.value));
checkImage(stream->InitializeFromFilename(file.c_str(),GENERIC_READ));
const auto &container=format==ImageFormat::png?GUID_ContainerFormatPng:
format==ImageFormat::jpeg?GUID_ContainerFormatJpeg:format==ImageFormat::gif?GUID_ContainerFormatGif:
GUID_ContainerFormatBmp;
ImagingObject<IWICBitmapDecoder> decoder;
checkImage(factory->CreateDecoder(container,nullptr,&decoder.value));
checkImage(decoder->Initialize(stream.value,WICDecodeMetadataCacheOnDemand));
ImagingObject<IWICBitmapFrameDecode> frame;
checkImage(decoder->GetFrame(0,&frame.value));
ImageRaster raster;
checkImage(frame->GetSize(&raster.width,&raster.height));
checkImageDimensions(raster.width,raster.height);
checkImageStop(stop);
ImagingObject<IWICFormatConverter> formatConverter;
checkImage(factory->CreateFormatConverter(&formatConverter.value));
checkImage(formatConverter->Initialize(frame.value,GUID_WICPixelFormat32bppPBGRA,WICBitmapDitherTypeNone,
nullptr,0,WICBitmapPaletteTypeCustom));
raster.pixels.resize(size_t(raster.width)*raster.height);
checkImage(formatConverter->CopyPixels(nullptr,raster.width*sizeof(uint32_t),
static_cast<UINT>(raster.pixels.size()*sizeof(uint32_t)),reinterpret_cast<BYTE *>(raster.pixels.data())));
return raster;
}
ImageRaster decodeWebp(const fs::path &file,size_t size,std::stop_token stop)
{
std::vector<uint8_t> bytes(size);
std::ifstream stream(file,std::ios::binary);
if(!stream.read(reinterpret_cast<char *>(bytes.data()),size)) throw std::runtime_error(invalidImage);
WebPBitstreamFeatures info{};
if(WebPGetFeatures(bytes.data(),bytes.size(),&info)!=VP8_STATUS_OK) throw std::runtime_error(invalidImage);
ImageRaster raster{static_cast<unsigned>(info.width),static_cast<unsigned>(info.height)};
checkImageDimensions(raster.width,raster.height);
checkImageStop(stop);
raster.pixels.resize(size_t(raster.width)*raster.height);
auto *output=reinterpret_cast<uint8_t *>(raster.pixels.data());
const auto outputSize=raster.pixels.size()*sizeof(uint32_t);
if(info.has_animation)
{
WebPAnimDecoderOptions options{};
if(!WebPAnimDecoderOptionsInit(&options)) throw std::runtime_error(invalidImage);
options.color_mode=MODE_bgrA;
const WebPData data{bytes.data(),bytes.size()};
const std::unique_ptr<WebPAnimDecoder,decltype(&WebPAnimDecoderDelete)> decoder(
WebPAnimDecoderNew(&data,&options),WebPAnimDecoderDelete);
uint8_t *frame=nullptr;
int timestamp{};
if(!decoder || !WebPAnimDecoderGetNext(decoder.get(),&frame,&timestamp))
throw std::runtime_error(invalidImage);
std::memcpy(output,frame,outputSize);
}
else
{
WebPDecoderConfig config{};
if(!WebPInitDecoderConfig(&config)) throw std::runtime_error(invalidImage);
config.output.colorspace=MODE_bgrA;
config.output.is_external_memory=1;
config.output.u.RGBA={output,static_cast<int>(raster.width*sizeof(uint32_t)),outputSize};
const auto status=WebPDecode(bytes.data(),bytes.size(),&config);
WebPFreeDecBuffer(&config.output);
if(status!=VP8_STATUS_OK) throw std::runtime_error(invalidImage);
}
return raster;
}
}
bool isImagePath(const std::filesystem::path &path)
{
return imageFormat(path)!=ImageFormat::unknown;
}
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop)
{
const auto format=imageFormat(name);
if(format==ImageFormat::unknown) throw std::runtime_error("This image format is not supported.");
checkImageStop(stop);
const auto size=std::filesystem::file_size(contents);
if(size==0) throw std::runtime_error(invalidImage);
if(size>imageSourceLimit) throw std::runtime_error(largeImage);
auto image=format==ImageFormat::webp?decodeWebp(contents,static_cast<size_t>(size),stop):
decodeNativeImage(contents,format,stop);
checkImageStop(stop);
return image;
}
}
-19
View File
@@ -1,19 +0,0 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <stop_token>
#include <vector>
namespace ks::files
{
struct ImageRaster
{
unsigned width{}, height{};
std::vector<uint32_t> pixels;
};
inline constexpr uint64_t imageSourceLimit=96ULL*1024*1024;
bool isImagePath(const std::filesystem::path &path);
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop={});
}
-474
View File
@@ -1,474 +0,0 @@
#include "files_image_view.h"
#include "platform.h"
#include <windowsx.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <future>
#include <map>
#include <memory>
#include <thread>
#include <utility>
namespace ks::files
{
namespace
{
namespace fs=std::filesystem;
constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer";
constexpr UINT_PTR imageTimer=1;
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize };
void fillImageView(HDC dc,const RECT &rect,COLORREF color)
{
SetDCBrushColor(dc,color);
FillRect(dc,&rect,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
struct ImageView
{
HWND window{};
bool embedded{};
ImageViewStyle style;
std::vector<fs::path> images;
size_t position{};
ImageLoad load;
ImageLoadRetry retry;
bool retried{};
std::function<void(HWND)> onClose;
std::array<HWND,6> buttons{};
HFONT font{};
UINT fontDpi{};
HBITMAP bitmap{};
unsigned width{},height{};
fs::path requested;
std::wstring error;
std::future<ImageRaster> reading;
std::stop_source stop;
uint64_t revision{}, started{};
double zoom=1, x{}, y{};
bool fit=true, dragging{};
POINT lastMouse{};
~ImageView()
{
stop.request_stop();
if(bitmap) DeleteObject(bitmap);
if(font) DeleteObject(font);
}
int scale(int pixels) const {return MulDiv(pixels,GetDpiForWindow(window),96);}
RECT viewport() const
{
RECT area{};
GetClientRect(window,&area);
area.top=std::min(area.bottom,static_cast<LONG>(scale(35)));
area.bottom=std::max(area.top,area.bottom-scale(27));
return area;
}
void layout()
{
const auto dpi=GetDpiForWindow(window);
if(fontDpi!=dpi)
{
LOGFONTW definition=style.font;
definition.lfHeight=-MulDiv(style.tenthsOfPoint,dpi,720);
if(const auto next=CreateFontIndirectW(&definition))
{
if(font) DeleteObject(font);
font=next;
fontDpi=dpi;
}
}
RECT bounds{};
GetClientRect(window,&bounds);
const int left=scale(4), gap=scale(3), height=scale(27);
const int count=embedded?4:6;
const int available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
const int unit=std::min(scale(80),available/count);
int x=left;
for(auto button:buttons)
{
if(!button) continue;
SetWindowPos(button,nullptr,x,scale(4),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
x+=unit+gap;
}
clampOffset();
InvalidateRect(window,nullptr,FALSE);
}
void updateButtons() const
{
if(!embedded)
{
EnableWindow(buttons[previous-1],position>0);
EnableWindow(buttons[following-1],position+1<images.size());
}
for(unsigned id=zoomOut;id<=actualSize;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
for(auto button:buttons)
if(button) InvalidateRect(button,nullptr,FALSE);
}
void request(const fs::path &path)
{
if(requested==path) return;
requested=path;
++revision;
stop.request_stop();
retried=false;
error.clear();
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
width=height=0;
fit=true;
x=y=0;
if(!embedded)
{
const auto label=L"Viewer — "+path.filename().wstring();
SetWindowTextW(window,label.c_str());
}
updateButtons();
SetTimer(window,imageTimer,30,nullptr);
InvalidateRect(window,nullptr,FALSE);
}
void show(ImageRaster image)
{
BITMAPINFO info{};
info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth=static_cast<LONG>(image.width);
info.bmiHeader.biHeight=-static_cast<LONG>(image.height);
info.bmiHeader.biPlanes=1;
info.bmiHeader.biBitCount=32;
info.bmiHeader.biCompression=BI_RGB;
void *bits=nullptr;
bitmap=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
if(!bitmap || !bits) throw std::runtime_error("Could not display this image.");
std::memcpy(bits,image.pixels.data(),image.pixels.size()*sizeof(uint32_t));
width=image.width;
height=image.height;
updateButtons();
}
void poll()
{
if(reading.valid())
{
if(reading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
const auto current=revision==started;
if(current) KillTimer(window,imageTimer);
bool retryApproved=false;
try
{
auto image=reading.get();
if(current) show(std::move(image));
}
catch(const std::exception &failure)
{
if(current)
{
if(!retried && retry.approve) retryApproved=retry.approve(window,requested,failure);
if(!retryApproved) error=wide(failure.what());
}
}
if(current && !retryApproved)
{
InvalidateRect(window,nullptr,FALSE);
return;
}
if(retryApproved)
{
retried=true;
SetTimer(window,imageTimer,30,nullptr);
}
}
if(requested.empty())
{
KillTimer(window,imageTimer);
return;
}
stop=std::stop_source{};
started=revision;
std::packaged_task<ImageRaster()> task([path=requested,decoder=retried?retry.load:load,token=stop.get_token()]
{
return decoder?decoder(path,token):decodeImage(path,path,token);
});
reading=task.get_future();
try {std::thread(std::move(task)).detach();}
catch(const std::exception &e)
{
reading={};
error=wide(e.what());
KillTimer(window,imageTimer);
InvalidateRect(window,nullptr,FALSE);
}
}
double factor() const
{
if(!fit || !width || !height) return zoom;
const auto area=viewport();
return std::min({1.0,static_cast<double>(std::max(1L,area.right-area.left))/width,
static_cast<double>(std::max(1L,area.bottom-area.top))/height});
}
void clampOffset()
{
const auto area=viewport();
const auto value=factor();
const auto limitX=std::max(0.0,(width*value-(area.right-area.left))/2);
const auto limitY=std::max(0.0,(height*value-(area.bottom-area.top))/2);
x=std::clamp(x,-limitX,limitX);
y=std::clamp(y,-limitY,limitY);
}
void changeZoom(double multiplier,const POINT *anchor=nullptr)
{
if(!bitmap) return;
const auto before=factor();
fit=false;
zoom=std::clamp(before*multiplier,std::min(0.025,before),16.0);
if(anchor)
{
const auto area=viewport();
const double dx=anchor->x-(area.left+area.right)/2.0;
const double dy=anchor->y-(area.top+area.bottom)/2.0;
x=dx+(x-dx)*zoom/before;
y=dy+(y-dy)*zoom/before;
}
clampOffset();
InvalidateRect(window,nullptr,FALSE);
}
void action(UINT id)
{
if(id==previous && position>0) request(images[--position]);
else if(id==following && position+1<images.size()) request(images[++position]);
else if(id==zoomOut || id==zoomIn) changeZoom(id==zoomIn?1.25:0.8);
else if(id==fitImage || id==actualSize)
{
fit=id==fitImage;
zoom=1;
x=y=0;
InvalidateRect(window,nullptr,FALSE);
}
}
void paintButton(const DRAWITEMSTRUCT &item) const
{
const bool enabled=(item.itemState&ODS_DISABLED)==0;
const auto mix=[](BYTE a,BYTE b){return (int(a)+b)/2;};
const auto foreground=enabled?style.toolbarText:RGB(
mix(GetRValue(style.toolbar),GetRValue(style.toolbarText)),
mix(GetGValue(style.toolbar),GetGValue(style.toolbarText)),
mix(GetBValue(style.toolbar),GetBValue(style.toolbarText)));
fillImageView(item.hDC,item.rcItem,(item.itemState&(ODS_FOCUS|ODS_SELECTED))?style.selection:style.toolbar);
SetDCBrushColor(item.hDC,foreground);
FrameRect(item.hDC,&item.rcItem,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
if(font) SelectObject(item.hDC,font);
SetBkMode(item.hDC,TRANSPARENT);
SetTextColor(item.hDC,foreground);
wchar_t label[24]{};
GetWindowTextW(item.hwndItem,label,static_cast<int>(std::size(label)));
auto labelArea=item.rcItem;
InflateRect(&labelArea,-scale(2),0);
DrawTextW(item.hDC,label,-1,&labelArea,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
}
void paint()
{
PAINTSTRUCT repaint{};
const auto dc=BeginPaint(window,&repaint);
RECT all{};
GetClientRect(window,&all);
const auto area=viewport();
fillImageView(dc,all,style.toolbar);
fillImageView(dc,area,style.background);
if(font) SelectObject(dc,font);
SetBkMode(dc,TRANSPARENT);
SetTextColor(dc,style.text);
if(bitmap)
{
if(const auto source=CreateCompatibleDC(dc))
{
const auto old=SelectObject(source,bitmap);
const auto saved=SaveDC(dc);
IntersectClipRect(dc,area.left,area.top,area.right,area.bottom);
const auto displayWidth=std::max(1L,std::lround(width*factor()));
const auto displayHeight=std::max(1L,std::lround(height*factor()));
const auto left=std::lround((area.left+area.right-displayWidth)/2.0+x);
const auto top=std::lround((area.top+area.bottom-displayHeight)/2.0+y);
const double horizontal=double(displayWidth)/width, vertical=double(displayHeight)/height;
const auto clippedSource=[](LONG edge,LONG start,double ratio,unsigned size,bool end)
{
const auto pixel=(edge-start)/ratio;
return static_cast<int>(std::clamp(end?std::ceil(pixel):std::floor(pixel),0.0,double(size)));
};
const int startX=clippedSource(area.left,left,horizontal,width,false);
const int endX=clippedSource(area.right,left,horizontal,width,true);
const int startY=clippedSource(area.top,top,vertical,height,false);
const int endY=clippedSource(area.bottom,top,vertical,height,true);
const auto destX=left+std::lround(startX*horizontal), destY=top+std::lround(startY*vertical);
AlphaBlend(dc,destX,destY,left+std::lround(endX*horizontal)-destX,top+std::lround(endY*vertical)-destY,
source,startX,startY,endX-startX,endY-startY,{AC_SRC_OVER,0,255,AC_SRC_ALPHA});
if(saved) RestoreDC(dc,saved);
SelectObject(source,old);
DeleteDC(source);
}
}
else if(!requested.empty())
{
auto message=area;
InflateRect(&message,-scale(8),0);
DrawTextW(dc,error.empty()?L"Loading image…":error.c_str(),-1,&message,
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
}
SetTextColor(dc,style.toolbarText);
auto status=requested.filename().wstring();
if(bitmap) status+=L" · "+std::to_wstring(width)+L" × "+std::to_wstring(height)+L" · "+
std::to_wstring(std::lround(factor()*100))+L"%";
RECT footer{scale(8),area.bottom,all.right-scale(8),all.bottom};
DrawTextW(dc,status.c_str(),-1,&footer,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
EndPaint(window,&repaint);
}
};
std::map<HWND,std::shared_ptr<ImageView>> imageViews;
LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_NCCREATE)
{
const auto *created=reinterpret_cast<const CREATESTRUCTW *>(lp);
const auto state=*static_cast<std::shared_ptr<ImageView> *>(created->lpCreateParams);
state->window=window;
imageViews.emplace(window,state);
}
const auto found=imageViews.find(window);
if(found==imageViews.end()) return DefWindowProcW(window,message,wp,lp);
const auto state=found->second;
auto &view=*state;
switch(message)
{
case WM_CREATE:
{
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%"};
for(unsigned id=view.embedded?zoomOut:previous;id<=actualSize;++id)
view.buttons[id-1]=CreateWindowW(L"BUTTON",labels[id-1],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
view.layout();
view.updateButtons();
return 0;
}
case WM_SIZE: view.layout(); return 0;
case WM_DPICHANGED:
if(!view.embedded)
{
const auto &bounds=*reinterpret_cast<const RECT *>(lp);
SetWindowPos(window,nullptr,bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top,
SWP_NOACTIVATE|SWP_NOZORDER);
}
view.layout();
return 0;
case WM_DPICHANGED_AFTERPARENT: view.layout(); return 0;
case WM_ERASEBKGND: return 1;
case WM_PAINT: view.paint(); return 0;
case WM_DRAWITEM: view.paintButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp)); return TRUE;
case WM_TIMER: if(wp==imageTimer) view.poll(); return 0;
case WM_COMMAND:
if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);}
return 0;
case WM_LBUTTONDOWN:
{
const auto area=view.viewport();
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
if(view.bitmap && PtInRect(&area,point))
{
SetFocus(window);
view.dragging=true;
view.lastMouse=point;
SetCapture(window);
}
return 0;
}
case WM_MOUSEMOVE:
if(view.dragging)
{
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
view.x+=point.x-view.lastMouse.x;
view.y+=point.y-view.lastMouse.y;
view.lastMouse=point;
view.clampOffset();
InvalidateRect(window,nullptr,FALSE);
}
return 0;
case WM_LBUTTONUP:
if(view.dragging) ReleaseCapture();
return 0;
case WM_CAPTURECHANGED: view.dragging=false; return 0;
case WM_MOUSEWHEEL:
{
POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
ScreenToClient(window,&point);
view.changeZoom(std::pow(1.25,static_cast<double>(GET_WHEEL_DELTA_WPARAM(wp))/WHEEL_DELTA),&point);
return 0;
}
case WM_KEYDOWN:
if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
else if(wp==VK_SUBTRACT || wp==VK_OEM_MINUS) view.action(zoomOut);
else if(wp=='0') view.action(fitImage);
else if(wp=='1') view.action(actualSize);
else if(!view.embedded && (wp==VK_LEFT || wp==VK_PRIOR)) view.action(previous);
else if(!view.embedded && (wp==VK_RIGHT || wp==VK_NEXT)) view.action(following);
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) DestroyWindow(window);
else break;
return 0;
case WM_NCDESTROY:
imageViews.erase(found);
if(view.onClose) view.onClose(window);
break;
}
return DefWindowProcW(window,message,wp,lp);
}
}
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry)
{
const auto instance=GetModuleHandleW(nullptr);
static const bool registered=[instance]
{
WNDCLASSW type{};
type.hInstance=instance;
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
type.lpfnWndProc=imageProcedure;
type.lpszClassName=imageWindowClass;
return RegisterClassW(&type)!=0;
}();
if(!registered) return nullptr;
auto state=std::make_shared<ImageView>();
state->embedded=embedded;
state->style=style;
state->images=std::move(images);
state->load=std::move(load);
state->retry=std::move(retry);
state->onClose=std::move(onClose);
const auto position=std::find(state->images.begin(),state->images.end(),initial);
if(position!=state->images.end()) state->position=static_cast<size_t>(position-state->images.begin());
RECT bounds{};
if(!embedded) GetWindowRect(owner,&bounds);
const auto window=CreateWindowExW(embedded?0:WS_EX_APPWINDOW,imageWindowClass,embedded?L"Quick View":L"Viewer",
embedded?(WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS):(WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN),
bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top,
embedded?owner:nullptr,nullptr,instance,&state);
if(window) state->request(initial);
return window;
}
void showImageViewFile(HWND window,const std::filesystem::path &path)
{
if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path);
}
}
-28
View File
@@ -1,28 +0,0 @@
#pragma once
#include "files_image_decode.h"
#include <windows.h>
#include <functional>
#include <exception>
namespace ks::files
{
using ImageLoad=std::function<ImageRaster(const std::filesystem::path &,std::stop_token)>;
struct ImageLoadRetry
{
ImageLoad load;
std::function<bool(HWND,const std::filesystem::path &,const std::exception &)> approve;
};
struct ImageViewStyle
{
LOGFONTW font{};
int tenthsOfPoint{};
COLORREF background{}, text{}, toolbar{}, toolbarText{}, selection{};
};
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={});
void showImageViewFile(HWND window,const std::filesystem::path &path);
}
-69
View File
@@ -1,69 +0,0 @@
#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)));
}
};
}
-30
View File
@@ -1,30 +0,0 @@
#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;
}
}
-492
View File
@@ -1,492 +0,0 @@
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 LockScan
{
std::set<DWORD> pids;
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::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())
result.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;
}
return result;
}
struct ProcessIdentity
{
DWORD pid{};
uint64_t started{};
bool operator==(const ProcessIdentity &) const = default;
};
struct ProcessEntry
{
ProcessIdentity identity;
std::wstring name;
fs::path image;
std::optional<uint64_t> workingSet;
std::optional<double> cpu;
};
struct ProcessScan
{
std::vector<ProcessEntry> entries;
bool incomplete{};
};
constexpr uint64_t processTimeTicks(const FILETIME &time)
{
return (uint64_t(time.dwHighDateTime)<<32)|time.dwLowDateTime;
}
struct ProcessTimes
{
uint64_t started, busy;
std::chrono::steady_clock::time_point measured;
};
std::optional<ProcessTimes> readProcessTimes(HANDLE process)
{
FILETIME started{},exited{},kernel{},user{};
if(!GetProcessTimes(process,&started,&exited,&kernel,&user)) return {};
return ProcessTimes{processTimeTicks(started),processTimeTicks(kernel)+processTimeTicks(user),
std::chrono::steady_clock::now()};
}
ProcessScan scanProcesses(const std::vector<fs::path> &files,std::stop_token stop)
{
ProcessScan result;
LockScan locks;
if(!files.empty())
{
locks=scanLockProcesses(files,stop);
result.incomplete=locks.incomplete;
if(locks.pids.empty() || stop.stop_requested()) return result;
}
const Handle snapshot{CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0)};
if(snapshot.value==INVALID_HANDLE_VALUE)
throw std::system_error(GetLastError(),std::system_category());
PROCESSENTRY32W process{sizeof(PROCESSENTRY32W)};
if(!Process32FirstW(snapshot.value,&process))
throw std::system_error(GetLastError(),std::system_category());
do
{
const auto pid=process.th32ProcessID;
if(files.empty() || locks.pids.contains(pid))
result.entries.push_back({{pid},process.szExeFile});
} while(!stop.stop_requested() && Process32NextW(snapshot.value,&process));
if(!stop.stop_requested() && GetLastError()!=ERROR_NO_MORE_FILES) result.incomplete=true;
std::map<DWORD,ProcessTimes> initial;
for(const auto &entry:result.entries)
{
if(stop.stop_requested()) return {};
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
if(handle.value)
if(const auto time=readProcessTimes(handle.value)) initial.emplace(entry.identity.pid,*time);
}
if(!initial.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(350));
const auto logicalCpus=std::max(1ul,static_cast<unsigned long>(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)));
std::array<wchar_t,32768> image;
for(auto &entry:result.entries)
{
if(stop.stop_requested()) return {};
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
if(!handle.value) continue;
const auto current=readProcessTimes(handle.value);
const auto before=initial.find(entry.identity.pid);
if(current && before!=initial.end() && current->started!=before->second.started) continue;
if(current)
{
entry.identity.started=current->started;
if(before!=initial.end() && current->busy>=before->second.busy)
{
const auto elapsed=std::chrono::duration<double>(current->measured-before->second.measured).count();
if(elapsed>0)
entry.cpu=std::clamp((current->busy-before->second.busy)*0.00001/(elapsed*logicalCpus),0.0,100.0);
}
}
DWORD count=image.size();
if(QueryFullProcessImageNameW(handle.value,0,image.data(),&count))
entry.image=std::wstring_view(image.data(),count);
PROCESS_MEMORY_COUNTERS memory{sizeof(memory)};
if(K32GetProcessMemoryInfo(handle.value,&memory,sizeof(memory))) entry.workingSet=memory.WorkingSetSize;
}
return result;
}
constexpr int processScope=430,processList=431,processDivider=432,processEnd=433,processRefresh=434,
processFilter=435,processSort=436,processReveal=437,processImage=438,processColumns=439,processStatus=443;
constexpr UINT_PTR processScanTimer=1;
enum class ProcessOrder { pid, cpu, memory, name, image };
struct ProcessDialog
{
std::vector<fs::path> files;
std::vector<ProcessEntry> entries;
std::future<ProcessScan> scan;
std::stop_source stop;
std::wstring failure;
fs::path reveal;
bool incomplete{};
};
const ProcessEntry *selectedProcess(HWND dialog,const ProcessDialog &state)
{
const auto row=SendDlgItemMessageW(dialog,processList,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendDlgItemMessageW(dialog,processList,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<state.entries.size()?&state.entries[index]:nullptr;
}
bool mayEndProcess(ProcessIdentity identity)
{
return identity.pid && identity.pid!=GetCurrentProcessId() && identity.started;
}
void updateSelectedProcess(HWND dialog,const ProcessDialog &state)
{
const auto *entry=selectedProcess(dialog,state);
const bool hasImage=entry && !entry->image.empty();
SetDlgItemTextW(dialog,processImage,hasImage?entry->image.c_str():entry?L"Unavailable":L"");
EnableWindow(GetDlgItem(dialog,processReveal),!state.scan.valid() && hasImage);
EnableWindow(GetDlgItem(dialog,processEnd),!state.scan.valid() && entry && mayEndProcess(entry->identity));
}
std::wstring processColumnsText(std::wstring_view pid,std::wstring_view cpu,std::wstring_view memory,
std::wstring_view name)
{
std::wostringstream fields;
fields<<std::right<<std::setw(10)<<pid<<L" "<<std::setw(7)<<cpu<<L" "<<std::setw(12)<<memory<<L" "<<name;
return fields.str();
}
int compareProcessNames(const std::wstring &left,const std::wstring &right)
{
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE);
}
void renderProcessList(HWND dialog,const ProcessDialog &state,std::optional<ProcessIdentity> preferred={})
{
const auto field=GetDlgItem(dialog,processFilter);
std::wstring query(GetWindowTextLengthW(field)+1,L'\0');
query.resize(GetWindowTextW(field,query.data(),static_cast<int>(query.size())));
const auto contains=[&](std::wstring_view value)
{
return query.empty() || (!value.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
value.data(),static_cast<int>(value.size()),query.c_str(),static_cast<int>(query.size()),nullptr,
nullptr,nullptr,0)>=0);
};
std::vector<size_t> rows;
for(size_t i=0;i<state.entries.size();++i)
{
const auto &entry=state.entries[i];
if(contains(entry.name) || contains(entry.image.native()) || contains(std::to_wstring(entry.identity.pid)))
rows.push_back(i);
}
const auto order=static_cast<ProcessOrder>(SendDlgItemMessageW(dialog,processSort,CB_GETCURSEL,0,0));
std::sort(rows.begin(),rows.end(),[&](size_t a,size_t b)
{
const auto &left=state.entries[a],&right=state.entries[b];
if(order==ProcessOrder::cpu && left.cpu!=right.cpu) return left.cpu>right.cpu;
if(order==ProcessOrder::memory && left.workingSet!=right.workingSet) return left.workingSet>right.workingSet;
if(order==ProcessOrder::name || order==ProcessOrder::image)
{
const auto names=order==ProcessOrder::name?compareProcessNames(left.name,right.name):
compareProcessNames(left.image.native(),right.image.native());
if(names!=CSTR_EQUAL) return names==CSTR_LESS_THAN;
}
return left.identity.pid<right.identity.pid;
});
const auto list=GetDlgItem(dialog,processList);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(const auto index:rows)
{
const auto &entry=state.entries[index];
wchar_t cpu[16]=L"—";
if(entry.cpu) swprintf_s(cpu,L"%.1f%%",*entry.cpu);
const auto text=processColumnsText(std::to_wstring(entry.identity.pid),cpu,
entry.workingSet?formatSize(*entry.workingSet):L"—",entry.name);
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(text.c_str()));
if(row<0) continue;
SendMessageW(list,LB_SETITEMDATA,row,index);
if(preferred==entry.identity) selected=row;
}
if(!rows.empty()) SendMessageW(list,LB_SETCURSEL,selected,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,TRUE);
updateSelectedProcess(dialog,state);
std::wstring status;
if(state.scan.valid()) status=state.files.empty()?L"Sampling processes…":L"Checking files for locking processes…";
else if(!state.failure.empty()) status=state.failure;
else if(state.entries.empty()) status=state.files.empty()?L"No processes found.":L"No locking processes found.";
else if(rows.empty()) status=L"No processes match the filter.";
else status=std::to_wstring(rows.size())+(query.empty()?L"":L" of "+std::to_wstring(state.entries.size()))+L" shown";
if(state.incomplete && !state.scan.valid() && state.failure.empty()) status+=L" Some items could not be checked.";
SetDlgItemTextW(dialog,processStatus,status.c_str());
}
void refreshProcesses(HWND dialog,ProcessDialog &state,std::shared_ptr<Handle> ended={})
{
if(state.scan.valid()) return;
const auto *entry=selectedProcess(dialog,state);
const auto selected=entry?std::optional(entry->identity):std::nullopt;
state.failure.clear();
try
{
std::packaged_task<ProcessScan()> task([files=state.files,stop=state.stop.get_token(),ended=std::move(ended)] {
if(ended) WaitForSingleObject(ended->value,2500);
return scanProcesses(files,stop);
});
auto future=task.get_future();
if(!SetTimer(dialog,processScanTimer,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(dialog,processScanTimer);
state.failure=L"Could not start the process scan.";
}
EnableWindow(GetDlgItem(dialog,processRefresh),!state.scan.valid());
renderProcessList(dialog,state,selected);
}
void endFileProcess(HWND dialog,ProcessDialog &state)
{
const auto *entry=selectedProcess(dialog,state);
if(state.scan.valid() || !entry || !mayEndProcess(entry->identity)) return;
const auto error=[&](const wchar_t *message)
{
showFilesNotice(dialog,message,L"End process",{.tone=FilesNoticeTone::warning});
};
const auto process=std::make_shared<Handle>();
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry->identity.pid);
const auto current=process->value?readProcessTimes(process->value):std::nullopt;
BOOL critical{};
if(!current || current->started!=entry->identity.started ||
!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->identity.pid)+
L")?\r\nUnsaved work in the process may be lost.";
if(showFilesNotice(dialog,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
return;
const auto alive=WaitForSingleObject(process->value,0);
if(alive!=WAIT_OBJECT_0 && (alive!=WAIT_TIMEOUT || !TerminateProcess(process->value,1)))
{
const auto reason=ks::lastError(L"Could not end the process");
error(reason.c_str());
return;
}
refreshProcesses(dialog,state,process);
}
INT_PTR CALLBACK processesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &state=*reinterpret_cast<ProcessDialog *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,processScope);
if(state.files.empty()) SetDlgItemTextW(dialog,processScope,L"This PC");
else
{
auto scope=L"Locks for "+state.files.front().native();
if(state.files.size()>1) scope+=L" (+"+std::to_wstring(state.files.size()-1)+L" more)";
SetDlgItemTextW(dialog,processScope,scope.c_str());
}
const auto filterField=GetDlgItem(dialog,processFilter);
SendMessageW(filterField,EM_SETLIMITTEXT,1024,0);
const auto sortField=GetDlgItem(dialog,processSort);
for(const auto name:{L"PID",L"CPU",L"Memory",L"Name",L"Executable"})
SendMessageW(sortField,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
SendMessageW(sortField,CB_SETCURSEL,1,0);
installFarCombo(sortField,filterField);
SetDlgItemTextW(dialog,processColumns,processColumnsText(L"PID",L"CPU",L"Working set",L"Process").c_str());
const auto list=GetDlgItem(dialog,processList);
const auto bounds=dialogControlBounds(dialog,processList);
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,dialog);
layoutDialogButtons(dialog,processDivider,{processReveal,processEnd,processRefresh,IDOK});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(filterField);
refreshProcesses(dialog,state);
return FALSE;
}
auto *data=reinterpret_cast<ProcessDialog *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!data) return FALSE;
auto &state=*data;
if(message==WM_TIMER && wp==processScanTimer)
{
if(!state.scan.valid() || state.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
return TRUE;
KillTimer(dialog,processScanTimer);
EnableWindow(GetDlgItem(dialog,processRefresh),TRUE);
const auto *entry=selectedProcess(dialog,state);
const auto selected=entry?std::optional(entry->identity):std::nullopt;
try
{
auto result=state.scan.get();
state.entries=std::move(result.entries);
state.incomplete=result.incomplete;
}
catch(const std::system_error &e) {state.failure=fileError(e);}
catch(const std::exception &) {state.failure=L"Could not read the process list.";}
renderProcessList(dialog,state,selected);
return TRUE;
}
if(message==WM_DRAWITEM && wp==processSort)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=GetDlgItem(dialog,processList))
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
if(message==WM_COMMAND)
{
const auto id=LOWORD(wp),notification=HIWORD(wp);
if((id==processFilter && notification==EN_CHANGE) || (id==processSort && notification==CBN_SELCHANGE))
{
const auto *entry=selectedProcess(dialog,state);
renderProcessList(dialog,state,entry?std::optional(entry->identity):std::nullopt);
return TRUE;
}
if(id==processList && notification==LBN_SELCHANGE)
{
updateSelectedProcess(dialog,state);
return TRUE;
}
if(id==processReveal || (id==processList && notification==LBN_DBLCLK))
{
const auto *entry=selectedProcess(dialog,state);
if(!state.scan.valid() && entry && !entry->image.empty())
{
state.reveal=entry->image;
FilesModalDialog::finish(dialog,processReveal);
}
return TRUE;
}
switch(id)
{
case processEnd: endFileProcess(dialog,state); return TRUE;
case processRefresh: refreshProcesses(dialog,state); return TRUE;
case IDOK:
case IDCANCEL: FilesModalDialog::finish(dialog,IDCANCEL); return TRUE;
}
}
if(message==WM_CLOSE) {FilesModalDialog::finish(dialog,IDCANCEL);return TRUE;}
const auto title=state.files.empty()?L" Processes ":L" Locking processes ";
return paintCopyDialog(dialog,message,wp,lp,title,false,{processDivider},false,GetDlgItem(dialog,processList));
}
void showProcesses(HWND owner,std::vector<fs::path> paths)
{
const auto source=active;
ProcessDialog state{std::move(paths)};
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,processesDialog,
reinterpret_cast<LPARAM>(&state));
state.stop.request_stop();
if(result!=processReveal) return;
const auto destination=state.files.empty()?source:1-source;
if(quickViewWindow && destination!=quickViewSource) toggleQuickView(owner);
revealLocalFile(panels[destination],state.reveal);
}
bool panelLockSearchAvailable(const Panel &panel)
{
return !terminalVisible && panelItemPropertiesAvailable(panel) && !panel.ftp && !panel.peer &&
!panel.archive && !windowsNetworkPath(panel.directory);
}
void showPanelLockProcesses(HWND owner,Panel &panel)
{
if(panelLockSearchAvailable(panel)) showProcesses(owner,selectedPanelPaths(panel));
}
-9444
View File
File diff suppressed because it is too large. Load diff
-18
View File
@@ -1,18 +0,0 @@
#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;
}
}
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff. Show more