Compare commits

..
Author SHA1 Message Date
agrynco 9360991fab Record the package manifest for KSwitcher v0.6.105
Refs #8, #38
2026-11-16 17:50:53 +02:00
agrynco 01a97c9ca4 Separate the Files editor and viewer icons for v0.6.105
Publish the generated Windows ZIP as a Gitea release asset without adding a copy to Git.

Refs #38
2026-11-16 17:50:10 +02:00
agrynco 0d68ee8078 Fix LAN PowerShell startup from an elevated resident
Refs #8
2026-11-16 17:50:10 +02:00
agrynco b04b66489c Merge pull request 'Release KSwitcher v0.6.104 with rendered Markdown search' (#49) from codex/release-v0.6.104 into main 2026-11-16 15:07:14 +02:00
agrynco b1a450f14b Package KSwitcher v0.6.104
Refs #38
2026-11-16 15:06:47 +02:00
agrynco de9fd29d5d Add search to the rendered Markdown viewer
Refs #38
2026-11-16 15:06:47 +02:00
agrynco 01fcd1ff9a Merge pull request 'Release KSwitcher v0.6.103 with Markdown appearance and terminal selection copy' (#48) from codex/release-v0.6.103 into main 2026-11-16 14:54:38 +02:00
agrynco b4fb0e8179 Package KSwitcher v0.6.103 2026-11-16 14:51:32 +02:00
agrynco 067373facd Render Markdown HTML and save viewer appearance in Files Options
Refs #38

Refs #8
2026-11-16 14:49:42 +02:00
agrynco 22b785e5ef Merge pull request 'Release KSwitcher v0.6.102 with command copy and LAN startup error handling' (#47) from codex/release-v0.6.102 into main 2026-11-16 14:20:22 +02:00
agrynco e6dd5108eb Package KSwitcher v0.6.102 2026-11-16 14:19:57 +02:00
agrynco 7bc5b9396b Fix command-line copy and prevent LAN startup dialogs
Refs #8
2026-11-16 14:18:13 +02:00
agrynco 23c49ce8bf Merge pull request 'Release KSwitcher v0.6.101 with panel Enter and compact Computers' (#46) from codex/release-v0.6.101 into main 2026-11-16 13:57:54 +02:00
agrynco a94c9dad14 Package KSwitcher v0.6.101 2026-11-16 13:57:39 +02:00
agrynco 553a2a0fa5 Release compact Computers and panel Enter fixes for v0.6.101
Refs #8
2026-11-16 13:57:39 +02:00
agrynco c01dfe8569 Merge pull request 'Release KSwitcher v0.6.100 with terminal Enter fix' (#45) from codex/release-v0.6.100 into main 2026-11-16 13:35:34 +02:00
agrynco 6b79f21a95 Package KSwitcher v0.6.100 2026-11-16 13:35:29 +02:00
agrynco 44b123b586 Fix Enter from the Files terminal output for v0.6.100
Refs #8
2026-11-16 13:31:06 +02:00
agrynco cb2f0a385b Merge pull request 'Release KSwitcher v0.6.99 with command line priority fix' (#44) from codex/release-v0.6.99 into main 2026-11-16 13:09:30 +02:00
agrynco 18c2b99dd5 Release KSwitcher v0.6.99 2026-11-16 13:09:20 +02:00
agrynco 2f7e97f13a Give the Files command line priority when submitting input 2026-11-16 13:05:12 +02:00
agrynco a82a99d21e Merge pull request 'Release KSwitcher v0.6.98 with Files shortcuts and FAR key bar' (#43) from codex/release-v0.6.98 into main 2026-11-16 11:45:02 +02:00
agrynco c9417e3d2c Release KSwitcher v0.6.98 2026-11-16 11:44:48 +02:00
agrynco 12e7b3e2fc Improve file opening, cursor redraw and the FAR-style key bar 2026-11-16 11:39:49 +02:00
agrynco d57b064d74 Merge pull request 'Release KSwitcher v0.6.97 with cursor highlight fix' (#42) from codex/release-v0.6.97 into main 2026-11-16 11:24:35 +02:00
agrynco 49ad7104fe Release KSwitcher v0.6.97 2026-11-16 11:24:24 +02:00
agrynco cc6615cb74 Clear the previous cursor highlight after pane selection changes 2026-11-16 11:20:20 +02:00
agrynco 66a69aa706 Merge pull request 'Release KSwitcher v0.6.96 with file pane and F8 fixes' (#41) from codex/release-v0.6.96 into main 2026-11-16 11:14:51 +02:00
agrynco 626fb685e5 Release KSwitcher v0.6.96 2026-11-16 11:13:37 +02:00
agrynco 8538c595e1 Avoid file pane repaint on click and expose F8 Delete 2026-11-16 11:09:46 +02:00
agrynco 7f54f12bf2 Merge pull request 'Release KSwitcher v0.6.95 with Markdown navigation and update fixes' (#40) from codex/release-v0.6.95 into main 2026-11-16 11:01:55 +02:00
agrynco e4ae9b6415 Refresh v0.6.95 package and verify window cycling
Refs #38
2026-11-16 11:00:13 +02:00
agrynco c789cdb1fe Cycle Files editor and viewer windows with Ctrl+Tab
Refs #38
2026-11-16 10:56:47 +02:00
agrynco dc645b9e46 Release KSwitcher v0.6.95
Refs #38
2026-11-16 10:54:13 +02:00
agrynco 19b3a24a71 Improve Markdown preview, menu navigation and update shutdown
Refs #38
2026-11-16 10:49:22 +02:00
agrynco 48ca436b7d Merge pull request 'Release KSwitcher v0.6.94 with Markdown preview' (#39) from codex/release-v0.6.94 into main 2026-11-16 10:21:49 +02:00
agrynco 6da3af0ae2 Release KSwitcher v0.6.94
Refs #38
2026-11-16 10:18:44 +02:00
agrynco 4eb41bac2b Render Markdown and Mermaid in KSwitcher Files
Refs #38
2026-11-16 10:13:42 +02:00
agrynco 2ea4f6f914 Merge pull request 'Release KSwitcher v0.6.93' (#37)
Release KSwitcher v0.6.93
2026-11-16 01:26:42 +02:00
agrynco 36f0b6ef8e Release KSwitcher v0.6.93 2026-11-16 01:26:12 +02:00
agrynco 3aafc1f937 Merge pull request 'Release KSwitcher v0.6.92' (#36)
Release KSwitcher v0.6.92
2026-11-16 01:19:49 +02:00
agrynco 6215675cb4 Release KSwitcher v0.6.92 2026-11-16 01:19:24 +02:00
agrynco 56c6257465 Merge pull request 'Release KSwitcher v0.6.91' (#35)
Release KSwitcher v0.6.91
2026-11-16 01:09:12 +02:00
agrynco 64b03a2168 Release KSwitcher v0.6.91 2026-11-16 01:08:40 +02:00
agrynco 36baeeb081 Merge pull request 'Release KSwitcher v0.6.90' (#34)
Release KSwitcher v0.6.90
2026-11-16 00:46:44 +02:00
agrynco 7698ea040d Release KSwitcher v0.6.90 2026-11-16 00:46:06 +02:00
agrynco 84d911ae9e Merge pull request 'Release KSwitcher v0.6.89' (#33)
Release KSwitcher v0.6.89
2026-11-16 00:31:10 +02:00
agrynco 8dedf30ece Release KSwitcher v0.6.89 2026-11-16 00:30:48 +02:00
agrynco f11bfff784 Merge pull request 'Release KSwitcher v0.6.88' (#32)
Release KSwitcher v0.6.88
2026-11-16 00:03:55 +02:00
agrynco 78aea46fb3 Activate the Files test window before sending shortcuts 2026-11-16 00:03:42 +02:00
agrynco 1549a89dc3 Release KSwitcher v0.6.88 2026-11-16 00:02:59 +02:00
agrynco 47382cdd86 Merge pull request 'Release KSwitcher v0.6.87 with clean LAN PowerShell output' (#31) from codex/release-v0.6.87 into main
Release KSwitcher v0.6.87
2026-11-15 23:50:24 +02:00
agrynco 49ae0ad157 Package KSwitcher v0.6.87 2026-11-15 23:49:54 +02:00
agrynco f8c05fd0ce Fix remote PowerShell text output for v0.6.87 2026-11-15 23:48:53 +02:00
agrynco d80fad6e48 Merge pull request 'Release KSwitcher v0.6.86 with LAN PowerShell' (#30) from codex/release-v0.6.86 into main
Release KSwitcher v0.6.86
2026-11-15 23:41:30 +02:00
agrynco a504adb22d Package KSwitcher v0.6.86 2026-11-15 23:40:56 +02:00
agrynco c3fa2af348 Add approved LAN PowerShell commands and fix editor startup for v0.6.86 2026-11-15 23:39:59 +02:00
agrynco cad264597d Merge pull request 'Release KSwitcher v0.6.85 with independent editor and LAN editing' (#29) from codex/release-v0.6.85 into main
Release KSwitcher v0.6.85
2026-11-15 23:10:40 +02:00
agrynco 97e5281c65 Package KSwitcher v0.6.85 2026-11-15 23:10:08 +02:00
agrynco 0af90b565d Add independent Files windows and LAN editing for v0.6.85 2026-11-15 23:09:00 +02:00
agrynco 6e3fc16c9f Merge pull request 'Release KSwitcher v0.6.84 with Files editor and folder creation' (#28) from codex/release-v0.6.84 into main
Release KSwitcher v0.6.84
2026-11-15 22:35:51 +02:00
agrynco 21ec9f30a6 Package KSwitcher v0.6.84 2026-11-15 22:35:01 +02:00
agrynco 4dd1a87a2a Add Files editor, viewer and Far dialogs for v0.6.84 2026-11-15 22:34:02 +02:00
agrynco 6cda28fcdd Merge pull request 'Release KSwitcher v0.6.83 with Files keyboard navigation' (#27) from codex/release-v0.6.83 into main 2026-11-15 10:33:10 +02:00
agrynco 0c4b6e390a Package KSwitcher v0.6.83 2026-11-15 10:32:46 +02:00
agrynco d0bd86513e Restore Files command focus after panel clicks 2026-11-15 10:32:35 +02:00
agrynco b5c803df87 Keep Files commands focused during pane navigation 2026-11-15 10:29:35 +02:00
agrynco 983e6f7b1a Merge pull request 'Release KSwitcher v0.6.82 with Files activation and refresh' (#26) from codex/files-activation-25 into main 2026-11-14 21:57:54 +02:00
agrynco 68edcc0bfb chore(release): package KSwitcher v0.6.82
Refs #25
2026-11-14 21:56:10 +02:00
agrynco b705c4e4a0 feat(files): open local files and refresh panels automatically
Refs #25
2026-11-14 21:53:00 +02:00
agrynco 31d582d29e Merge pull request 'Package KSwitcher 0.6.81' (#24) from codex/release-0681 into main 2026-11-14 16:34:11 +02:00
agrynco ad2fa2c92e chore(release): package kswitcher v0.6.81 2026-11-14 16:32:06 +02:00
agrynco 796d03f8a9 Merge pull request 'Show all folder shortcuts with Ctrl+8 and reuse the Files window' (#23) from codex/files-all-folder-shortcuts into main 2026-11-14 16:25:07 +02:00
agrynco be68b706f0 fix(files): use ctrl+8 and activate the open files window 2026-11-14 16:24:47 +02:00
agrynco 23a7c73331 feat(files): list all folder shortcuts with ctrl+f8
Reuse the folder shortcuts dialog and open the selected destination in the active panel.
2026-11-14 16:19:23 +02:00
agrynco 82fe8ce3a1 Merge pull request 'Show specific LAN peer lookup errors in Files' (#22) from codex/files-peer-errors into main 2026-11-14 16:14:28 +02:00
agrynco 00cd1262b4 chore(release): package kswitcher v0.6.80 2026-11-14 16:10:08 +02:00
agrynco 7bc734a9a8 fix(files): distinguish lan peer lookup failures 2026-11-14 16:07:54 +02:00
agrynco a19ccaf035 Merge pull request 'Synchronize Files with PowerShell and fix the LAN drive picker' (#21) from codex/files-polish-release into main 2026-11-14 16:01:54 +02:00
agrynco 60625103f8 chore(release): package kswitcher v0.6.79 2026-11-14 15:53:27 +02:00
agrynco aa02f2cacb fix(files): synchronize terminal navigation and polish lan picker 2026-11-14 15:52:14 +02:00
agrynco 6a1e39efa9 Merge pull request 'Synchronize KSwitcher Files settings across open windows' (#20) from codex/files-live-settings into main 2026-11-14 15:18:15 +02:00
agrynco 7242c3f775 test(settings): keep picker fixture within the monitor 2026-11-14 15:17:54 +02:00
agrynco a43f6441b4 chore(release): refresh verified windows package 2026-11-14 15:15:20 +02:00
agrynco 2f5ae373a1 fix(settings): preserve unset files shortcut in options 2026-11-14 15:14:16 +02:00
agrynco b978361180 chore(release): package kswitcher v0.6.78 with files 2026-11-14 15:11:26 +02:00
agrynco 93b8055085 fix(files): synchronize settings across windows
Reload shared preferences in open windows and apply only fields changed in Options.
2026-11-14 15:09:17 +02:00
agrynco 70ee338fc3 Merge pull request 'Add searchable command history to KSwitcher Files' (#19) from codex/files-command-history into main 2026-11-14 14:43:10 +02:00
agrynco 46b4b51cea feat(files): add searchable command history
Persist command recall and align keyboard, mouse, and dialog behavior.

Refs #18
2026-11-14 14:42:48 +02:00
agrynco 721c3f0f38 docs: record KSwitcher issue workflow 2026-11-14 12:56:47 +02:00
agrynco 47851d75ef Merge pull request 'Add folder shortcuts to KSwitcher Files' (#17) from codex/issue-15-folder-shortcuts into main
Fixes #15
2026-11-14 12:20:53 +02:00
agrynco ad01951956 Add folder shortcuts to KSwitcher Files
Share Far dialog fields, palette, frame layout, and configurable padding. Document shortcut behavior and the shared-code rule.

Refs #15
2026-11-14 12:19:13 +02:00
agrynco bf092d2764 Merge pull request 'Customize file type styles and preview Files options' (#16) from codex/files-type-styles into main
Fixes #14
2026-11-14 11:26:01 +02:00
73 changed files with 12406 additions and 724 deletions

No files matched your search

+1
View File
@@ -4,5 +4,6 @@
/.vs/
/.idea/
/dist/
/Release/KSwitcher-win-x64.zip
/build-output.txt
*.user
+32
View File
@@ -1,5 +1,11 @@
# 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.
@@ -34,8 +40,34 @@ Wiki: https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki
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.
+69 -2
View File
@@ -1,11 +1,13 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.77 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.105 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 resources/files.rc)
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
include(cmake/FilesTextLibraries.cmake)
set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files")
target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
find_program(KSWITCHER_POWERSHELL NAMES pwsh powershell REQUIRED)
@@ -14,6 +16,11 @@ add_custom_target(KSwitcherTerminalAssets
-Destination "$<TARGET_FILE_DIR:KSwitcherFiles>"
VERBATIM)
add_dependencies(KSwitcherFiles KSwitcherTerminalAssets)
add_custom_target(check-files-search-arrow
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_search_arrow.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>"
DEPENDS KSwitcherFiles
VERBATIM)
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid)
if(MSVC)
@@ -40,6 +47,7 @@ target_link_libraries(KSwitcherFiles PRIVATE kscore)
target_include_directories(kscore PUBLIC src PRIVATE vendor)
target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore)
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1")
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
target_link_libraries(KSwitcher PRIVATE kscore)
@@ -106,6 +114,21 @@ else()
target_link_options(KSwitcherOcrTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
enable_testing()
add_executable(KSwitcherFilesTextTests tests/files_text_document.cpp src/files_text_document.cpp)
target_include_directories(KSwitcherFilesTextTests PRIVATE src)
target_compile_definitions(KSwitcherFilesTextTests PRIVATE UNICODE _UNICODE NOMINMAX WIN32_LEAN_AND_MEAN)
target_link_libraries(KSwitcherFilesTextTests PRIVATE ole32)
if(NOT MSVC)
target_link_options(KSwitcherFilesTextTests PRIVATE -static)
endif()
add_test(NAME files-text-document COMMAND KSwitcherFilesTextTests)
add_executable(KSwitcherFilesModalTests tests/files_modal_dialog.cpp)
target_include_directories(KSwitcherFilesModalTests PRIVATE src)
target_link_libraries(KSwitcherFilesModalTests PRIVATE user32 comctl32)
if(NOT MSVC)
target_link_options(KSwitcherFilesModalTests PRIVATE -static)
endif()
add_test(NAME files-modal-dialog COMMAND KSwitcherFilesModalTests)
add_executable(KSwitcherLanTests tests/lan.cpp)
target_link_libraries(KSwitcherLanTests PRIVATE kscore)
if(MSVC)
@@ -117,6 +140,48 @@ add_test(NAME lan-pairing-regressions COMMAND KSwitcherLanTests)
add_executable(KSwitcherLanFilesTests tests/lan_files.cpp)
target_link_libraries(KSwitcherLanFilesTests PRIVATE kscore)
add_test(NAME lan-files-regressions COMMAND KSwitcherLanFilesTests)
add_executable(KSwitcherFilesActivationFixture tests/files_activation_fixture.cpp)
if(NOT MSVC)
target_link_options(KSwitcherFilesActivationFixture PRIVATE -municode -static)
endif()
add_test(NAME files-activation-and-refresh
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>")
set_tests_properties(files-activation-and-refresh PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
add_test(NAME files-system-open
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
-SystemOpenOnly)
set_tests_properties(files-system-open PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
find_program(KSWITCHER_NODE NAMES node)
if(KSWITCHER_NODE)
add_test(NAME files-terminal-enter
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
-TerminalOnly -Node "${KSWITCHER_NODE}")
set_tests_properties(files-terminal-enter PROPERTIES RUN_SERIAL TRUE TIMEOUT 90)
add_executable(KSwitcherFilesMarkdownLanFixture WIN32 tests/files_markdown_lan.cpp
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText)
add_dependencies(KSwitcherFilesMarkdownLanFixture KSwitcherTerminalAssets)
if(MSVC)
set_property(TARGET KSwitcherFilesMarkdownLanFixture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesMarkdownLanFixture PRIVATE /utf-8)
else()
target_link_options(KSwitcherFilesMarkdownLanFixture PRIVATE -municode -static)
endif()
add_test(NAME files-markdown-viewer
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_markdown.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Node "${KSWITCHER_NODE}"
-LanFixture "$<TARGET_FILE:KSwitcherFilesMarkdownLanFixture>")
set_tests_properties(files-markdown-viewer PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
endif()
add_executable(KSwitcherLanInputTests tests/lan_input.cpp)
target_link_libraries(KSwitcherLanInputTests PRIVATE kscore)
if(MSVC)
@@ -134,6 +199,8 @@ else()
target_link_options(KSwitcherChatProfileTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests)
add_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout)
set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
target_link_libraries(KSwitcherHistoryHostTests PRIVATE kscore psapi)
set_target_properties(KSwitcherHistoryHostTests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/history-host-fixture-$<CONFIG>")
+294 -7
View File
@@ -2,18 +2,256 @@
Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far.
Власні модальні діалоги панелей, редактора й переглядача використовують
`FilesModalDialog`. Escape і клік поза діалогом у клієнтській області Files
виконують Cancel, а фокус повертається до елемента, з якого відкрили діалог.
Кліки на робочому столі та в інших застосунках залишають діалог відкритим.
Заголовок і рамка вікна-власника доступні, а діалог рухається разом із
власником. Діалог центрується відносно власника та звужується разом із ним
до власної мінімальної ширини. Поки діалог відкритий, ширина власника
обмежена цією мінімальною шириною з відступами.
Це діє і для вкладених діалогів. Під час файлової операції Cancel спершу
просить підтвердити переривання.
Спільне повідомлення Files підлаштовується під заголовок і кількість рядків.
Висота діалогу залежить від видимого вмісту. Приховані та порожні секції
не займають місця. Перед завершенням змін перевір коротке повідомлення й
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
Warning і початковий фокус на No.
## Скорочення
- Короткий Alt перемикає головне меню Files при відпусканні. F9 також перемикає меню. Після закриття фокус повертається до активної панелі. Alt з літерою верхнього рівня спрацьовує одразу при натисканні літери. Alt+O відкриває Options, а відпускання Alt після комбінації не перемикає меню.
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
документ — у програмі, призначеній для його типу у Windows. EXE запускається
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
панелі LAN, спочатку скопіюй його до локальної папки.
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
- У головному вікні клавіатурний фокус залишається в командному рядку.
Tab перемикає активну панель, клік вибирає рядок, а стрілки вгору й вниз,
Page Up і Page Down пересувають курсор у панелі навіть під час набору команди.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
текст із буфера обміну в позицію курсора або замінюють виділення.
Enter і Shift+Enter спочатку виконують введену команду. Коли рядок
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
Enter передає порожній рядок у термінал. Escape очищає рядок.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
Промпт і текст команди вирівняні по спільній базовій лінії.
- **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.
- **F9 → Commands → Update remote KSwitcher** запускає штатне оновлення для
ПК активної LAN-панелі. Підтвердження з іменем ПК показується у Files
відправника. На цільовому ПК потрібен дозвіл **Options → Command line →
Command history → Allow paired PCs to update KSwitcher here**. Після
перевірки нового стабільного пакета оновлювач без запитань закриває
KSwitcher, Files, Config і редактори скриншотів цієї інсталяції.
Незбережені зміни у примусово закритих вікнах втрачаються.
Закриття процесів і результат записуються до `kswitcher.log`.
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
курсора командного рядка або замінює виділення. Подвійні лапки додаються
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
- 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 дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису. Brief і Wide доступні в меню Left/Right та Options.
## Налаштування Files
- Options у головному меню одразу відкриває стандартний діалог Windows. Ліворуч є пошук за назвою категорії чи параметра й дерево результатів. Вибір дочірнього вузла відкриває лише його редактор праворуч. Пошук за назвою окремої властивості відкриває вузол, що її містить. Перемикання вузлів зберігає незастосовані зміни.
### Переглядач і редактор
- F3 відкриває поточний локальний файл у вбудованому переглядачі лише
для читання. F4 відкриває спільне вікно в режимі редагування. Alt+F3
відкриває файл у програмі, призначеній Windows для цього типу, а Alt+F4
викликає зареєстровану дію Edit. Ці команди також є в меню Commands.
F10 або × закривають головне вікно Files. Вбудовані Viewer та Editor
відкриваються в окремих немодальних вікнах. Редактор має іконку олівця,
переглядач — іконку ока. Ці іконки видно в заголовку, в Alt+Tab і в окремих
групах на панелі завдань Windows. F6 змінює іконку й групу поточного вікна.
При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
із підсвічуванням Markdown.
HTML усередині Markdown підтримує таблиці, текстове форматування, посилання,
відносні зображення й окремі стилі, зокрема `white-space: nowrap` у клітинках.
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
Вихідний текст приховано, доки Markdown і Mermaid готують перегляд.
Звичайний клік відкриває внутрішнє посилання в тому самому вікні,
Shift+клік відкриває окреме вікно. Назад і вперед працюють через стрілки
перегляду, бічні кнопки миші й Alt+←/→. Ctrl+W закриває перегляд.
Ctrl+F або кнопка пошуку відкриває пошук у відрендерованому документі.
Пошук без урахування регістру показує кількість збігів і підсвічує поточний.
Enter і F3 переходять до наступного збігу, а Shift+Enter і Shift+F3 — до
попереднього, циклічно. Escape спочатку закриває поле пошуку.
Коли локальний Markdown оновлюється на диску, відкритий перегляд
перерендерюється зі збереженням позиції прокрутки.
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
8 МіБ, F3 відкриває текстовий перегляд.
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
junction не обходяться. Недоступний вміст позначається як частковий результат.
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
копії, Files відхиляє запис і залишає зміни в редакторі. Для F4 оновіть
KSwitcher також на віддаленому ПК. Alt+F3 і Alt+F4 потребують локальної копії.
- Вікно використовує той самий шрифт і розмір, що й файлові панелі,
синю палітру Far за замовчуванням,
рядок стану згори й підказки клавіш унизу. Інформація про файл
вирівняна праворуч. Режим (Edit або View) стоїть у дужках після імені,
далі йдуть кодування, синтаксис, позиція курсора й сторінка великого файла.
Номери рядків показані приглушеним кольором з невеликим відступом від тексту.
Меню редактора й переглядача використовують моноширинний шрифт і кольори
обраної схеми. У FAR (blue) написи верхнього меню чорні, поточний пункт
має чорне тло, а літери доступу жовті. F9 відкриває меню, Alt з літерою
доступу відкриває потрібний розділ. Редактор позначає незбережені зміни зірочкою.
Esc і F10 закривають незмінений файл одразу. Якщо вміст змінився,
діалог Far пропонує Save, Discard або Cancel.
- Syntax → Automatic визначає синтаксис за іменем, розширенням або
shebang. Відомі типи включають C#, C/C++, JavaScript/TypeScript,
HTML, XML, CSS, SQL, Python, PowerShell, Bash, JSON, YAML, TOML і Markdown.
У меню Syntax можна вибрати будь-який вбудований лексер Lexilla або Plain text.
Стан багаторядкової конструкції починається заново на межі сторінки.
- Ctrl+PgUp/PgDn перемикають сторінки, F5 переходить до заданої сторінки,
Ctrl+Shift+Home/End відкривають першу й останню. Ctrl+F шукає в поточній
сторінці, F3 повторює пошук. Ctrl+A виділяє поточну сторінку.
Історія Undo/Redo діє в межах відкритої сторінки.
- Початкова сторінка займає близько 1 МіБ файла. Для вставок і редагування
сторінка може вирости до 8 МіБ у UTF-8. Зміни інших сторінок тимчасово
зберігаються на диску. F2 або Ctrl+S потоково записують нову копію в
папку файла, тож збереження потребує вільного місця для цієї копії.
UTF-8 із BOM або без нього та UTF-16 LE/BE із BOM зберігають своє
кодування. Нередаговані байти копіюються без перетворення.
- Команда Options у панелях, редакторі й переглядачі відкриває один діалог
KSwitcher Files Options. Розділи Viewer та Editor зберігають окремі профілі.
**Viewer → Markdown** задає максимальну ширину документа (0 — усе вікно),
гарнітуру та розмір основного тексту. Порожня гарнітура використовує системний
шрифт. Apply одразу оновлює відкриті перегляди Markdown.
Після повторного відкриття Options відновлюється останній розділ, зокрема
після Cancel. Пошуковий запит і чернетка змін не зберігаються.
З редактора або переглядача діалог відкриває відповідний розділ. Apply
застосовує зміни до відкритих вікон, Cancel відкидає незастосовану чернетку.
Доступні перенесення рядків, номери рядків, показ пробілів і
кінців рядків, підсвічування поточного рядка, ширина табуляції від 1 до 16,
схеми FAR (blue), Dark і Light та власні кольори. Save scheme у розділі
Viewer або Editor додає поточну палітру до спільного списку схем. Apply
зберігає її та робить доступною в обох розділах. У редакторі також можна
ввімкнути вставлення пробілів замість табуляцій і автоматичні відступи,
а також вибрати символи кінця для нових рядків.
- Діалоги пошуку й переходу до сторінки використовують подвійні рамки та
кнопки Files. Search має компактний розмір, сіре тло, бірюзове поле та окремі кнопки
Find previous і Find next. Word і Selection підставляють у поле слово
під курсором або однорядкове виділення. Поле має висоту одного рядка
й вертикально центрований текст. Стрілка біля поля або Alt+Down
відкриває історію з групуванням за датами. Вибір запису підставляє
запит у поле. Editor і Viewer спільно зберігають до 100 останніх
різних запитів між запусками. Спільний шрифт панелей, меню й тексту змінюється в
Options → Appearance → Font. Редактор і переглядач отримують новий
шрифт після Apply.
### Параметри файлових панелей
- Options у головному меню спочатку прибирає смугу меню й одразу відкриває стандартний діалог Windows. Ліворуч є пошук за назвою категорії чи параметра й дерево результатів. Вибір дочірнього вузла відкриває лише його редактор праворуч. Пошук за назвою окремої властивості відкриває вузол, що її містить. Перемикання вузлів зберігає незастосовані зміни.
- File panel modes має вузли Panel layout, Wide panel columns і Status line columns. У Colors кожен колір має власний вузол. В Appearance шрифт редагується у вузлі Font. Діалог змінює розмір від розміру, який вміщує всі параметри. Ширина лівої навігації стала, дерево росте по висоті, а права область використовує додатковий простір. OK, Cancel та Apply лишаються внизу праворуч.
- Reset selected to defaults скидає вибраний рівень дерева. Корінь All settings скидає всі параметри, навіть коли пошук приховує частину дерева. У редакторах із кількома параметрами Reset property скидає лише вибрану властивість. Скидання змінює чернетку до Apply або OK. Стандартний Panel background — `#000080`.
- Apply доступна, коли чернетка відрізняється від застосованих налаштувань. Після Apply або повернення всіх значень до застосованих вона вимикається. Apply одразу зберігає зміни й перемальовує панелі за відкритим діалогом. OK робить те саме й закриває діалог. Cancel і Escape відкидають зміни після останнього Apply та повертають фокус до панелі.
- Apply доступна, коли чернетка відрізняється від застосованих налаштувань. Після Apply або повернення всіх значень до застосованих вона вимикається. Apply одразу зберігає зміни й перемальовує панелі за відкритим діалогом. OK робить те саме й закриває діалог. Cancel і Escape відкидають зміни після останнього Apply та повертають фокус до командного рядка.
- Colors → File type styles налаштовує текст, фон, підкреслення й закреслення для правил за розширенням і групи System and hidden. Розширення можна вибрати зі списку Windows або додати вручну з крапкою чи без неї. Вони зберігаються в KSwitcher, незалежно від асоціацій Windows. Курсор, позначки й результат передачі зберігають свої сигнальні кольори. Кольори правила можна перевизначити окремо для звичайного рядка, позначки Insert, курсора у фокусі та курсора без фокуса. Позначка має пріоритет над курсором, а підсвічування передачі має пріоритет над кольорами курсора. Без перевизначення стан зберігає звичайний вигляд панелі. Мініпанель унизу редактора одразу показує всі чотири стани на синтетичних рядках до Apply.
@@ -25,29 +263,75 @@ Far Manager є зразком для оформлення файлового м
## Панелі
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
у відкритих локальних папках. Фокус залишається там, де був, а курсор
лишається на поточному елементі, якщо той ще існує.
- Ctrl+8 відкриває список усіх ярликів папок. Кожен рядок показує групу
й назву або шлях. Enter відкриває папку в активній панелі, F4 редагує
ярлик, а Delete прибирає його зі списку.
- У Change drive повідомлення No paired computers з’являється після
успішної відповіді з порожнім списком. Збої локального запиту до
KSwitcher відображаються окремо.
- Якщо команда у вбудованому PowerShell змінює поточну папку,
панель, з якої надіслано команду, переходить до цієї папки.
- Коли список LAN-дисків змінює розмір меню Change drive, рамка й список
змінюють позицію разом. Рамка повністю перемальовується після зміни
розміру, а список має однаковий внутрішній відступ зліва і справа.
- Тайм-аут запиту дисків відображається як Connection timed out. Якщо
ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows.
- Застосовані налаштування Files одразу підхоплюють інші відкриті вікна.
Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
редагували набір стилів файлів, відкрий Options заново, щоб побачити свіжі правила.
- Типовий колір тексту для ZIP-архівів — світлий коралово-рожевий.
- Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК.
- Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно.
- F5, F6, F8 і Shift+Delete у віддалених панелях використовують спільні підтвердження, попередження й прогрес. F5/F6 працюють із файлами та деревами папок між локальними й віддаленими панелями, зокрема між двома різними ПК. Між шляхами одного віддаленого ПК вміст копіюється на ньому. F8 використовує кошик того ПК, на якому лежить файл.
- Після розриву з’єднання повтори F5 або F6 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення.
- F7, пункт Files → Make folder і кнопка F7 Mkdir відкривають модальний діалог Far. Стрілка біля імені та Alt+Down відкривають історію успішних введень. Link type має варіанти none, directory junction і symbolic link. Поле Target активне для посилань і приймає абсолютний шлях або шлях від поточної папки. У віддаленій панелі посилання створюється на віддаленому ПК, а symbolic link залежить від дозволів Windows на цьому ПК.
- Process multiple names дозволяє розділити імена комами або крапками з комою. Якщо такий символ є частиною імені, візьми ім’я в подвійні лапки. Діалог створює елементи у поточному каталозі, оновлює панель і ставить курсор на останній створений елемент. При помилці в середині списку вже створені елементи зберігаються.
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
- Бірюзовий курсор поточного рядка видно лише в активній панелі. Кожна панель зберігає свою позицію курсора.
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
## Спільні елементи діалогів
- Власні діалоги Files блокують дії панелей і командного рядка, залишаючи
системний заголовок і рамку головного вікна доступними. Клік у Files поза діалогом
діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває
підтвердження скасування.
- Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No.
- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання.
- Для власних діалогів використовуй подвійну рамку з одним заголовком у верхній лінії. Звичайний діалог має сіре тло, попередження — темно-червоне тло та білий текст.
- Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку.
- Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення.
- У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок.
- Модальні діалоги редактора й переглядача використовують той самий шрифт, що й діалоги операцій Files. Розміри полів і кнопок враховують метрики цього шрифту.
- Нижні секції з кнопками у Copy, Warning і вікні прогресу мають однакову висоту, прив’язану до висоти рядка шрифту. Використовуй `layoutDialogButtons` для такої секції та `centerDialogRow` для інших рядків між роздільниками. Межі секції визначають положення рядка.
- Поля вводу й випадаючі списки використовують бірюзове тло палітри менеджера. Текст і стрілку вирівнюй вертикально по центру. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус.
- Search і спільні нижні секції Far використовують компактні проміжки між рядками й кнопками, прив’язані до метрик моноширинного шрифту. У Search висота кнопки дорівнює висоті одного рядка.
- Нижні кнопки Far групуються по центру. Їхня ширина залежить від напису й дужок, а проміжок між ними становить приблизно половину символу.
- Прапорці Far у Search, Copy і попередженнях використовують спільний компонент. У фокусі короткий системний курсор блимає між дужками, а тло рядка зберігає колір діалогу.
- У Copy і Rename/Move помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
- Випадаючі списки й поля Far мають висоту одного рядка шрифту. Бірюзове поле прилягає до сірої ділянки завширшки один символ із темною, вертикально центрованою стрілкою. Make folder, Search і Copy використовують спільне малювання стрілки. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус.
- Розкриті списки й історія Far використовують спільний попап із бірюзовим тлом, світлою рамкою та чорним вибраним рядком. Попап прилягає до обох країв бірюзового поля, стрілка лишається праворуч за межами списку. Історія групується за датами. Довгі списки прокручуються, Enter вибирає рядок, Escape закриває список і повертає фокус до поля.
- Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів.
## Діалог Copy
@@ -67,6 +351,9 @@ Far Manager є зразком для оформлення файлового м
## Попередження про конфлікт
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
час останньої зміни окремо для вхідного файла та файла в папці призначення.
- Після розрахунку остаточної висоти центр Warning збігається з центром вікна прогресу.
- Remember choice стоїть по вертикальному центру власної секції. Кнопки Overwrite, Skip і Cancel стоять по центру нижньої секції.
- Tab проходить Remember choice, Overwrite, Skip і Cancel. Стрілки вліво та вправо циклічно перемикають три кнопки в порядку їх розташування.
@@ -75,7 +362,7 @@ Far Manager є зразком для оформлення файлового м
## Видалення
- F8 показує сіре підтвердження з дією Move. Shift+Delete і підтвердження непорожньої папки мають темно-червоне тло. Вікно прогресу видалення має сіре тло, як у Copy.
- Escape у початковому підтвердженні повертає фокус до панелі, з якої викликано видалення. Поточний рядок зберігається, а стрілки одразу працюють.
- Escape у початковому підтвердженні повертає фокус до командного рядка. Поточний рядок активної панелі зберігається, а стрілки одразу працюють.
- F8 переміщує підтверджені елементи в кошик Windows. Shift+Delete видаляє підтверджене дерево від вкладених елементів до батьківської папки. Прогрес і підсумок окремо показують успішні, пропущені й невдалі дії.
- Cancel і Esc у вікні прогресу відкривають спільне червоне підтвердження скасування. Yes зупиняє операцію, а No або Esc у підтвердженні повертає до прогресу. Початковий фокус стоїть на No.
+2
View File
@@ -39,6 +39,8 @@ the local resident process running and log downloads enabled on the remote PC.
1. Install the v0.6.58 or newer on every participating PC. Input protocol v2 requires all participants to update; earlier one-pair builds cannot connect. Preserve local data; do not copy pairing identities between PCs.
2. Open **Settings → Computers → Manage computers…** and enable discovery on both PCs.
Only running LAN-enabled KSwitcher instances appear, not generic network devices.
The computer list and pairing controls are on the left, the monitor grid and
input sharing are on the right, and file, log and help actions are below.
3. Match the computer name and instance-ID prefix displayed on the other PC.
Select each other, generate one code, enter that same code on both, then click
Pair on both within two minutes. Spaces, hyphens and uppercase hex are accepted.
+12 -3
View File
@@ -144,7 +144,8 @@ in the resident app. Screen capture and all screenshot editors run on demand in
process. Closing the last editor (or cancelling the only selection) exits that process. It does not
load resident settings, dictionaries, clipboard history or keyboard hooks. Editor windows have
stable numbered titles within that process. Keep all three executables together when copying or
updating the application. Close screenshot editors before installing an update.
updating the application. After verifying a new package, the updater closes Files, the text and
screenshot editors, Settings, and bundled StayHere for that installation. Save open work before approving an update.
If settings change in the tray while the configurator is open, a conflicting Save is rejected; reopen
the configurator to load the latest settings.
Updates from v0.3.x–v0.4.1 first install the compatible **v0.4.2 bridge** through
@@ -920,11 +921,19 @@ CC BY-SA 4.0; attribution, pinned source revision and license are in `dictionari
## Latest compiled release
The [Release folder](Release/README.md) contains the latest portable Windows x64 ZIP and SHA-256 checksum.
Run `./package.ps1 -PublishRelease` after building and testing to refresh the tracked release archive.
Download the portable Windows x64 ZIP from [Gitea Releases](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases).
The [Release folder](Release/README.md) tracks the release notes, manifest and SHA-256 checksum.
Run `./package.ps1 -PublishRelease` after building and testing, then upload the generated ZIP,
manifest and checksum as release assets.
## Verification
The Files build uses CMake 3.24 or later and Ninja, both included in the local
w64devkit toolchain. CMake downloads pinned Scintilla and Lexilla source
archives for the built-in viewer and editor on the first configure. The
[Scintilla and Lexilla license](resources/files-text-license.txt) is also
embedded in KSwitcher.Files.exe.
```powershell
.\build.ps1 -Test # Pure/native regression checks; does not touch the user's clipboard
.\build.ps1 -Ocr # Render a synthetic image, decode it with WIC and recognize it with Windows OCR
Binary file not shown.
+181
View File
@@ -1,5 +1,186 @@
# Latest Windows release
## 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
+1 -1
View File
@@ -1 +1 @@
51d95639527590b36453a5ef485532a7d2135950222fa197eb431a5309f1a45c KSwitcher-win-x64.zip
41b5353f049d7c6da5e664dda316e1308c5e996cdbd5a7a9b51689c02dda8674 KSwitcher-win-x64.zip
+97 -17
View File
@@ -1,20 +1,94 @@
{
"version": "0.6.77",
"files": [
{
"path": "KSwitcher.exe",
"size": 2249216,
"sha256": "f1c79d337d746efcda03946cc833b7b5588ef4e739f1dff7d3afa15d0465469f"
"size": 2362368,
"sha256": "87a61d636e941adc8b37385dd72fa0e15248368867adc301df5f3af894938e24"
},
{
"path": "KSwitcher.Config.exe",
"size": 2251776,
"sha256": "016edc389007e0d15ee365fff7115fc91a820b46080cb39a3fb362f3b463bae7"
"size": 2360320,
"sha256": "ea5640173dd0c0338d0b6843f737595b2c67793cceb1202e7e293ca42fe835b8"
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3247616,
"sha256": "c8ef070ad01acc410802c62e0df6a96cb299fe036fe8e99f0cf6a398b7324ec6"
"size": 3337728,
"sha256": "c785ed267aeb3e1c1c27a8aa8fe296a98283553af3d67a9ee171fc873f4dd58c"
},
{
"path": "KSwitcher.Files.exe",
"size": 3801088,
"sha256": "6cbb9cf16e251f618e543d0af3a014932123f455ed9a2c04f86c948a5852987e"
},
{
"path": "WebView2Loader.dll",
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"path": "terminal/addon-fit.js",
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"path": "terminal/index.html",
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"path": "terminal/markdown-it.js",
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"path": "terminal/markdown.html",
"size": 3530,
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
},
{
"path": "terminal/markdown.js",
"size": 14660,
"sha256": "fe202fa3d3c362aff2ab9028b40bd2aee61240bf9bd4a44af55e45d1a4081cf0"
},
{
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"path": "terminal/mermaid.js",
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"path": "terminal/terminal.js",
"size": 5033,
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a"
},
{
"path": "terminal/xterm-LICENSE.txt",
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"path": "terminal/xterm.css",
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"path": "terminal/xterm.js",
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"path": "LICENSE",
@@ -26,15 +100,20 @@
"size": 1075,
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86"
},
{
"path": "files-text-license.txt",
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"path": "README.md",
"size": 93885,
"sha256": "df6d40d0eb66ad7da8db1cffe6bd211de70dfee474cc228e041c821b3940718b"
"size": 94502,
"sha256": "b4b561d2bdf1ef80291c3abcadb625407b94279185fd33fd9dc113658ab9b486"
},
{
"path": "LAN-PREVIEW.md",
"size": 11418,
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada"
"size": 11577,
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
},
{
"path": "dictionaries/en.txt",
@@ -48,8 +127,8 @@
},
{
"path": "dictionaries/README.md",
"size": 2230,
"sha256": "2df17fe4e17d527c67ab57269b07dce59a49c1fb128c429a1408decbb47109ec"
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"path": "dictionaries/ru.txt",
@@ -58,13 +137,13 @@
},
{
"path": "dictionaries/sources.json",
"size": 1279,
"sha256": "d6e11a3aaba22a8a7eaba19f778d8a5bd66653ff306810e85a1b0e7fff3a6b86"
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"path": "dictionaries/uk.txt",
"size": 898248,
"sha256": "caeb097749d4afc84b68ad96b3d7dfb6a6569561cd32ccce0bee94a13b43ba86"
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"path": "tools/README.txt",
@@ -82,5 +161,6 @@
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
],
"version": "0.6.105",
"schema": 1
}
+13 -5
View File
@@ -47,14 +47,22 @@ try {
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'
$terminalIncludes = & "$root/tools/stage-files-terminal.ps1" -Destination (Split-Path $filesPath)
& "$root/tools/stage-files-terminal.ps1" -Destination build/release | Out-Null
& windres resources/files.rc -O coff -o build/files-res.o
if ($LASTEXITCODE) { throw 'File manager resource compilation failed' }
& $compiler @common "-I$terminalIncludes" -mwindows -municode -static -s src/files_main.cpp build/files-res.o build/lan_files.o build/lan_channel.o build/lan_pairing.o build/platform.o build/core.o '-Wl,--gc-sections' @libs -o $filesPath
$filesBuild = Join-Path $outDir 'files-cmake'
& cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel
if ($LASTEXITCODE) { throw 'File manager configuration failed' }
& cmake --build $filesBuild --target KSwitcherFiles --parallel 8
if ($LASTEXITCODE) { throw 'File manager build failed' }
Copy-Item -LiteralPath (Join-Path $filesBuild 'KSwitcher.Files.exe') -Destination $filesPath -Force
& strip $filesPath
if ($LASTEXITCODE) { throw 'File manager stripping failed' }
& "$root/tools/stage-files-terminal.ps1" -Destination (Split-Path $filesPath) | Out-Null
& "$root/tools/stage-files-terminal.ps1" -Destination build/release | Out-Null
Copy-Item -LiteralPath $filesPath -Destination build/release/KSwitcher.Files.exe -Force
if ($Test) {
& cmake --build $filesBuild --target KSwitcherFilesTextTests
if ($LASTEXITCODE) { throw 'Files text test build failed' }
& (Join-Path $filesBuild 'KSwitcherFilesTextTests.exe')
if ($LASTEXITCODE) { throw 'Files text tests failed' }
& $compiler @common -Werror tests/settings_merge.cpp build/sync.o build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
if ($LASTEXITCODE) { throw 'Settings merge test build failed' }
& .\build\KSwitcherSettingsMergeTests.exe
+26
View File
@@ -0,0 +1,26 @@
include(FetchContent)
FetchContent_Declare(scintilla
URL https://www.scintilla.org/scintilla569.zip
URL_HASH SHA256=fddc637afa6e3a9205a5ad67c777d711a921ed2797d792f3034010c1be1539d6
DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
FetchContent_Declare(lexilla
URL https://www.scintilla.org/lexilla555.zip
URL_HASH SHA256=713ada097b7da0594638e2c5723d8dea486653c23ec2e0c12631df7e5b7f0991
DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
FetchContent_MakeAvailable(scintilla lexilla)
file(GLOB scintilla_sources "${scintilla_SOURCE_DIR}/src/*.cxx" "${scintilla_SOURCE_DIR}/win32/*.cxx")
list(FILTER scintilla_sources EXCLUDE REGEX "/ScintillaDLL\\.cxx$")
file(GLOB lexilla_sources "${lexilla_SOURCE_DIR}/lexlib/*.cxx" "${lexilla_SOURCE_DIR}/lexers/*.cxx")
add_library(KSwitcherFilesText STATIC ${scintilla_sources} ${lexilla_sources}
"${lexilla_SOURCE_DIR}/src/Lexilla.cxx")
target_include_directories(KSwitcherFilesText
PUBLIC "${scintilla_SOURCE_DIR}/include" "${lexilla_SOURCE_DIR}/include"
PRIVATE "${scintilla_SOURCE_DIR}/src" "${lexilla_SOURCE_DIR}/lexlib")
target_compile_definitions(KSwitcherFilesText PRIVATE UNICODE _UNICODE NOMINMAX LEXILLA_NO_EXPORT)
target_link_libraries(KSwitcherFilesText PRIVATE imm32 ole32 oleaut32 msimg32)
target_link_libraries(KSwitcherFiles PRIVATE KSwitcherFilesText)
if(MSVC)
set_property(TARGET KSwitcherFilesText KSwitcherFiles PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesText PRIVATE /utf-8)
endif()
+2 -1
View File
@@ -11,6 +11,7 @@ Copy-Item -LiteralPath (Join-Path $root 'build\release\WebView2Loader.dll') -Des
Copy-Item -LiteralPath (Join-Path $root 'build\release\terminal') -Destination $destination -Recurse -Force
Copy-Item -LiteralPath (Join-Path $root 'LICENSE') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-text-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'LAN-PREVIEW.md') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'dictionaries') -Destination $destination -Recurse -Force
@@ -19,7 +20,7 @@ Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') -
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','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ }
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ }
$entries = foreach ($path in $files) {
foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) {
@{path=$file.FullName.Substring($destination.Length+1).Replace('\','/'); size=$file.Length; sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()}
+3 -3
View File
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,6,77,0
PRODUCTVERSION 0,6,77,0
FILEVERSION 0,6,105,0
PRODUCTVERSION 0,6,105,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -20,7 +20,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.6.77"
VALUE "FileVersion", "0.6.105"
END
END
BLOCK "VarFileInfo"
+20
View File
@@ -0,0 +1,20 @@
License for Lexilla, Scintilla, and SciTE
Copyright 1998-2021 by Neil Hodgson <[email protected]>
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation.
NEIL HODGSON DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL NEIL HODGSON BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
OR PERFORMANCE OF THIS SOFTWARE.
+172 -13
View File
@@ -1,8 +1,77 @@
#pragma code_page(65001)
#include <windows.h>
#include <commctrl.h>
#include "resource.h"
#define FAR_EDIT(id, mode, x, y, width, height) \
CONTROL "", id, "KSwitcher.Files.FarEdit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height
1 ICON "kswitcher-files.ico"
IDI_FILES_VIEWER ICON "kswitcher-files-viewer.ico"
IDI_FILES_EDITOR ICON "kswitcher-files-editor.ico"
1 RT_MANIFEST "app.manifest"
601 RCDATA "files-text-license.txt"
602 DIALOGEX 0, 0, 230, 85
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
FONT 10, "Consolas"
BEGIN
LTEXT "&Page number", 101, 18, 21, 194, 12
FAR_EDIT(100, ES_NUMBER, 18, 38, 194, 16)
CONTROL "&Go", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 53, 59, 60, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 117, 59, 60, 17
END
604 DIALOGEX 0, 0, 268, 101
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
CONTROL "&Search for", 109, "Static", SS_OWNERDRAW, 18, 17, 130, 12
FAR_EDIT(100, 0, 18, 30, 241, 14)
CONTROL "↓", 108, "Button", BS_OWNERDRAW | WS_TABSTOP, 259, 30, 11, 14
CONTROL "W&ord", 106, "Button", BS_OWNERDRAW | WS_TABSTOP, 160, 14, 49, 15
CONTROL "Se&lection", 107, "Button", BS_OWNERDRAW | WS_TABSTOP, 212, 14, 58, 15
CONTROL "", 104, "Static", NOT WS_VISIBLE, 18, 51, 1, 1
AUTOCHECKBOX "&Case sensitive", 101, 18, 52, 110, 12
AUTOCHECKBOX "&Whole words", 102, 18, 64, 110, 12
CONTROL "", 105, "Static", NOT WS_VISIBLE, 18, 81, 1, 1
CONTROL "Find pre&vious", 103, "Button", BS_OWNERDRAW | WS_TABSTOP, 33, 80, 83, 15
CONTROL "Find &next", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 121, 80, 76, 15
CONTROL "Canc&el", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 202, 80, 53, 15
END
603 DIALOGEX 0, 0, 230, 72
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
FONT 10, "Consolas"
BEGIN
LTEXT "Save changes to this file?", -1, 18, 23, 194, 12, SS_CENTER
CONTROL "&Save", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 17, 42, 60, 17
CONTROL "&Discard", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 42, 66, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
END
607 DIALOGEX 0, 0, 185, 57
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL, 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
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
@@ -30,6 +99,19 @@ BEGIN
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
@@ -48,23 +130,47 @@ BEGIN
AUTOCHECKBOX "&Underline", 297, 131, 166, 80, 12
AUTOCHECKBOX "Stri&kethrough", 298, 218, 166, 100, 12
CONTROL "Settings preview", 299, "Static", SS_OWNERDRAW | WS_BORDER, 131, 202, 253, 81
AUTOCHECKBOX "&Wrap lines", 350, 131, 28, 118, 12
AUTOCHECKBOX "&Line numbers", 351, 257, 28, 125, 12
AUTOCHECKBOX "Show &whitespace and line endings", 352, 131, 45, 118, 12
AUTOCHECKBOX "&Highlight current line", 353, 257, 45, 125, 12
AUTOCHECKBOX "Insert &spaces for tabs", 354, 131, 62, 118, 12
AUTOCHECKBOX "Auto &indent", 355, 257, 62, 125, 12
LTEXT "&Tab width", 356, 131, 84, 118, 10
COMBOBOX 357, 257, 81, 125, 100, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "Line &endings for new lines", 358, 131, 104, 118, 10
COMBOBOX 359, 257, 101, 125, 77, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "Color sc&heme", 362, 131, 125, 118, 10
COMBOBOX 363, 257, 122, 125, 67, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "Customize &color", 364, 131, 145, 118, 10
COMBOBOX 365, 257, 142, 125, 116, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
LTEXT "", 367, 345, 184, 45, 12
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12
EDITTEXT 376, 131, 68, 168, 14, ES_AUTOHSCROLL
PUSHBUTTON "Choose &font…", 377, 306, 68, 76, 14
LTEXT "Font &size (8–72 pt)", 378, 131, 99, 184, 12
EDITTEXT 379, 318, 96, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
END
102 DIALOGEX 0, 0, 350, 114
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
CONTROL "", 211, "Edit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP, 14, 29, 322, 18
LTEXT "Existing files:", 212, 14, 61, 122, 14, SS_CENTERIMAGE
COMBOBOX 213, 140, 61, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
CONTROL "Also ask on read-only files", 214, "Button", BS_OWNERDRAW | WS_TABSTOP, 14, 81, 322, 14
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 96, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 96, 86, 18
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
@@ -83,7 +189,7 @@ BEGIN
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 187, 106, 86, 18
END
104 DIALOGEX 0, 0, 360, 106
104 DIALOGEX 0, 0, 360, 139
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Warning"
FONT 10, "Consolas"
@@ -91,11 +197,16 @@ BEGIN
LTEXT "", 230, 12, 16, 336, 12
LTEXT "", 231, 12, 33, 336, 12, SS_PATHELLIPSIS
LTEXT "", 233, 12, 55, 1, 1
LTEXT "", 234, 12, 81, 1, 1
CONTROL "Remember choice", 232, "Button", BS_OWNERDRAW | WS_TABSTOP, 12, 57, 336, 18
CONTROL "&Overwrite", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 89, 110, 18
CONTROL "&Skip", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 158, 89, 68, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 232, 89, 86, 18
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
@@ -135,3 +246,51 @@ BEGIN
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
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+2
View File
@@ -1,4 +1,6 @@
#pragma once
#define IDI_KSWITCHER 101
#define IDI_SCREENSHOT_QUESTION 102
#define IDI_FILES_VIEWER 103
#define IDI_FILES_EDITOR 104
#define IDC_SCREENSHOT_PENCIL 500
+56
View File
@@ -0,0 +1,56 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'">
<title>Markdown preview</title>
<style>
:root { color-scheme: light dark; font: 16px/1.55 system-ui, sans-serif; }
:root:not(.rendered) body { visibility: hidden; }
body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); }
nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; }
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
nav button:hover:not(:disabled) { text-decoration: underline; }
nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
#search { margin-inline-start: auto; display: flex; align-items: center; gap: .35em;
flex: 0 1 22em; min-width: 0; max-width: 100%; }
#search[hidden] { display: none; }
#search-query { box-sizing: border-box; flex: 1; min-width: 0; width: 0; font: inherit; }
#search-status { white-space: nowrap; font-size: .8em; }
::highlight(markdown-search-active) { background: #ffab45; color: #171717; }
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
a { color: LinkText; }
pre, table, figure { overflow: auto; }
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
pre { padding: .75em; }
code { padding: .1em .25em; }
pre code { padding: 0; background: none; }
blockquote { margin-left: 0; padding-left: 1em; border-left: 3px solid GrayText; }
table { display: block; border-collapse: collapse; }
th, td { border: 1px solid GrayText; padding: .3em .65em; }
img, svg { max-width: 100%; height: auto; }
figure { margin: 1em 0; }
.task { list-style: none; }
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
</style>
<nav aria-label="Markdown preview">
<button id="back" type="button" title="Back (Alt+Left)" aria-label="Back" disabled>←</button>
<button id="forward" type="button" title="Forward (Alt+Right)" aria-label="Forward" disabled>→</button>
<button id="search-open" type="button" title="Find (Ctrl+F)" aria-label="Find in document" aria-controls="search" aria-expanded="false">⌕</button>
<div id="search" role="search" hidden>
<input id="search-query" type="search" aria-label="Find in document" placeholder="Find in document" autocomplete="off">
<output id="search-status" for="search-query" aria-live="polite"></output>
<button id="search-previous" type="button" title="Previous match (Shift+Enter)" aria-label="Previous match" disabled>↑</button>
<button id="search-next" type="button" title="Next match (Enter)" aria-label="Next match" disabled>↓</button>
<button id="search-close" type="button" title="Close search (Esc)" aria-label="Close search">×</button>
</div>
</nav>
<main></main>
<script src="markdown-it.js"></script>
<script src="mermaid.js"></script>
<script src="markdown.js"></script>
</html>
+327
View File
@@ -0,0 +1,327 @@
'use strict';
const bridge = window.chrome.webview;
const content = document.querySelector('main');
const back = document.querySelector('#back');
const forward = document.querySelector('#forward');
const searchOpen = document.querySelector('#search-open');
const search = document.querySelector('#search');
const searchQuery = document.querySelector('#search-query');
const searchStatus = document.querySelector('#search-status');
const searchPrevious = document.querySelector('#search-previous');
const searchNext = document.querySelector('#search-next');
const markdown = markdownit({ html: true, linkify: true });
let generation = 0;
let images = [];
let matches = [];
let activeMatch = -1;
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
for (let i = 2; i < tokens.length; ++i) {
const token = tokens[i];
if (token.type !== 'inline' || tokens[i - 1].type !== 'paragraph_open' ||
tokens[i - 2].type !== 'list_item_open') continue;
const text = token.children[0];
const marker = text?.type === 'text' && /^\[([ xX])\][ \t]+/.exec(text.content);
if (!marker) continue;
text.content = text.content.slice(marker[0].length);
const box = new text.constructor('task_checkbox', '', 0);
box.checked = marker[1] !== ' ';
box.content = token.content.slice(marker[0].length);
token.children.unshift(box);
tokens[i - 2].attrJoin('class', 'task');
}
});
markdown.renderer.rules.task_checkbox = (tokens, i) =>
'<input type="checkbox" aria-label="' + markdown.utils.escapeHtml(tokens[i].content) + '"' +
(tokens[i].checked ? ' checked' : '') + '>';
markdown.renderer.rules.image = (tokens, i) => {
const token = tokens[i];
const alt = markdown.renderer.renderInlineAsText(token.children, markdown.options, {});
const escape = markdown.utils.escapeHtml;
return '<img alt="' + escape(alt) + '" data-path="' + escape(token.attrGet('src')) + '">';
};
const htmlTags = new Set(`a abbr address article aside b blockquote br caption code col colgroup dd del
details div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hr i img input ins kbd li
mark ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
tr u ul var wbr`.split(/\s+/));
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
const tagAttributes = {
a: ['href'], col: ['span'], colgroup: ['span'], details: ['open'], img: ['alt', 'width', 'height'],
input: ['type', 'checked', 'disabled'], ol: ['start', 'reversed', 'type'], li: ['value'],
td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan', 'scope'], time: ['datetime']
};
const inlineStyles = ['white-space', 'text-align', 'vertical-align', 'color', 'background-color',
'font-weight', 'font-style', 'text-decoration-line', 'width', 'max-width'];
function relativeResource(path) {
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
}
function renderContent(text) {
// Parse in an inert template and allow only document markup before attaching it to the preview.
const template = document.createElement('template');
template.innerHTML = markdown.render(text);
for (const element of template.content.querySelectorAll('*')) {
const tag = element.localName;
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
(tag === 'input' && element.type !== 'checkbox')) {
element.remove();
continue;
}
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
const styles = element.hasAttribute('style')
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
for (const { name } of [...element.attributes]) {
if (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name)) element.removeAttribute(name);
}
for (const [name, value] of styles) {
if (value) element.style.setProperty(name, value);
}
if (relativeResource(imagePath)) element.dataset.path = imagePath;
if (tag === 'a' && element.hasAttribute('href')) {
const path = element.getAttribute('href').trim();
if (relativeResource(path) || /^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i.test(path)) element.setAttribute('href', path);
else element.removeAttribute('href');
}
}
content.replaceChildren(template.content);
}
function send(action, options = {}) {
bridge.postMessage(JSON.stringify({ action, ...options }));
}
function scrollToHeading(fragment) {
if (!fragment) { window.scrollTo(0, 0); return; }
try { content.querySelector('#' + CSS.escape(decodeURIComponent(fragment)))?.scrollIntoView(); } catch {}
}
function restorePosition({ fragment, scroll }) {
if (typeof scroll === 'number') window.scrollTo(0, scroll);
else scrollToHeading(fragment);
}
function navigate(action) {
const button = action === 'back' ? back : forward;
if (!button.disabled) send(action, { scroll: Math.round(window.scrollY) });
}
back.addEventListener('click', () => navigate('back'));
forward.addEventListener('click', () => navigate('forward'));
function updateSearch(reveal = true) {
matches = [];
activeMatch = -1;
const query = searchQuery.value.trim();
if (query) {
const pattern = query.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
const expression = new RegExp(pattern, 'giu');
const blockTags = 'article,aside,blockquote,caption,dd,div,dt,figcaption,footer,h1,h2,h3,h4,h5,h6,header,li,p,pre,section,summary,td,th,text';
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
let block = null;
let parts = [];
let text = '';
const searchBlock = () => {
let first = 0;
let last = 0;
for (const match of text.matchAll(expression)) {
const end = match.index + match[0].length;
while (parts[first].end <= match.index) ++first;
last = Math.max(last, first);
while (parts[last].end < end) ++last;
matches.push([parts[first].node, match.index - parts[first].start,
parts[last].node, end - parts[last].start]);
}
parts = [];
text = '';
};
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const element = node.parentElement;
if (!node.length || element.closest('style,svg title,svg desc,svg defs') ||
!element.checkVisibility({ visibilityProperty: true })) continue;
const nextBlock = element.closest(blockTags);
if (block !== nextBlock) searchBlock();
block = nextBlock;
const start = text.length;
text += node.data;
parts.push({ node, start, end: text.length });
}
searchBlock();
}
showSearchMatch(matches.length ? 0 : -1, reveal);
}
function showSearchMatch(index, reveal) {
activeMatch = index;
searchPrevious.disabled = searchNext.disabled = matches.length < 2;
searchStatus.value = !searchQuery.value.trim() ? '' : index < 0 ? 'No matches' : (index + 1) + ' / ' + matches.length;
CSS.highlights.delete('markdown-search-active');
if (index < 0) return;
const [start, from, end, to] = matches[index];
const range = new Range();
range.setStart(start, from);
range.setEnd(end, to);
CSS.highlights.set('markdown-search-active', new Highlight(range));
if (!reveal) return;
const rect = range.getBoundingClientRect();
const toolbarBottom = search.parentElement.getBoundingClientRect().bottom;
if (rect.top < toolbarBottom || rect.bottom > innerHeight) {
scrollBy(0, rect.top - Math.max(toolbarBottom, innerHeight / 2));
}
const scroller = start.parentElement.closest('pre, table');
if (scroller) {
const bounds = scroller.getBoundingClientRect();
if (rect.left < bounds.left || rect.right > bounds.right) {
scroller.scrollLeft += rect.left - bounds.left;
}
}
}
function openSearch() {
search.hidden = false;
searchOpen.setAttribute('aria-expanded', 'true');
searchQuery.focus({ preventScroll: true });
searchQuery.select();
}
function closeSearch() {
if (search.hidden) return false;
const hadFocus = search.contains(document.activeElement);
search.hidden = true;
searchOpen.setAttribute('aria-expanded', 'false');
searchQuery.value = '';
updateSearch();
if (hadFocus) searchOpen.focus({ preventScroll: true });
return true;
}
function stepSearch(direction) {
if (search.hidden) openSearch();
else if (matches.length) showSearchMatch((activeMatch + direction + matches.length) % matches.length, true);
}
searchOpen.addEventListener('click', openSearch);
document.querySelector('#search-close').addEventListener('click', closeSearch);
searchQuery.addEventListener('input', () => updateSearch());
searchPrevious.addEventListener('click', () => stepSearch(-1));
searchNext.addEventListener('click', () => stepSearch(1));
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
async function render({ text, fragment, scroll, title, keepPosition }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
else closeSearch();
document.documentElement.classList.remove('rendered');
document.title = title;
renderContent(text);
const headings = new Set();
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
let id = base;
for (let n = 1; headings.has(id); ++n) id = base + '-' + n;
heading.id = id;
headings.add(id);
}
images = Array.from(content.querySelectorAll('img[data-path]'));
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
for (const [index, block] of blocks.entries()) {
try {
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
if (current !== generation) return;
const figure = document.createElement('figure');
figure.innerHTML = svg;
block.parentElement.replaceWith(figure);
} catch {
if (current !== generation) return;
const caption = document.createElement('div');
caption.textContent = 'Invalid Mermaid diagram';
block.parentElement.before(caption);
}
}
restorePosition({ fragment, scroll });
document.documentElement.classList.add('rendered');
if (!search.hidden) updateSearch(false);
send('rendered');
}
content.addEventListener('click', event => {
const link = event.target.closest('a');
if (!link) return;
event.preventDefault();
const path = link.getAttribute('href');
if (!path || event.ctrlKey || event.metaKey || link.closest('svg')) return;
send('link', { path, newWindow: event.shiftKey, scroll: Math.round(window.scrollY) });
});
document.addEventListener('pointerup', event => {
if (event.button !== 3 && event.button !== 4) return;
event.preventDefault();
navigate(event.button === 3 ? 'back' : 'forward');
});
document.addEventListener('keydown', event => {
if (event.isComposing) return;
if (event.ctrlKey && !event.altKey && event.key.toLowerCase() === 'f') {
event.preventDefault();
openSearch();
} else if (event.key === 'F3' || (event.key === 'Enter' && event.target === searchQuery)) {
event.preventDefault();
stepSearch(event.shiftKey ? -1 : 1);
} else if (event.key === 'Escape' && closeSearch()) {
event.preventDefault();
} else if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
event.preventDefault();
send('cycle');
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
event.preventDefault();
navigate(['ArrowLeft', 'BrowserBack'].includes(event.key) ? 'back' : 'forward');
} else if (event.key === 'F6' || event.key === 'Escape' || event.key === 'F10' ||
(event.ctrlKey && event.key.toLowerCase() === 'w')) {
event.preventDefault();
send(event.key === 'F6' ? 'edit' : 'close');
}
});
bridge.addEventListener('message', ({ data }) => {
const message = JSON.parse(data);
if (message.action === 'clear') {
++generation;
closeSearch();
document.documentElement.classList.remove('rendered');
content.replaceChildren();
}
if (message.action === 'render') void render(message).catch(() => send('failed'));
if (message.action === 'appearance') {
const style = document.documentElement.style;
style.setProperty('--markdown-width', message.width ? message.width + 'px' : 'none');
style.setProperty('--markdown-font-size', message.fontSize + 'pt');
style.setProperty('--markdown-font', message.font ? CSS.escape(message.font) + ', system-ui, sans-serif' : 'system-ui, sans-serif');
}
if (message.action === 'anchor') restorePosition(message);
if (message.action === 'find') openSearch();
if (message.action === 'find-next') stepSearch(message.previous ? -1 : 1);
if (message.action === 'escape' && !closeSearch()) send('close');
if (message.action === 'back' || message.action === 'forward') navigate(message.action);
if (message.action === 'history') {
back.disabled = !message.back;
forward.disabled = !message.forward;
}
if (message.action === 'image' && message.generation === generation && images[message.index]) {
const image = images[message.index];
if (message.source) image.src = message.source;
else image.title = 'Image unavailable';
}
});
bridge.postMessage('ready');
+53 -4
View File
@@ -3,17 +3,30 @@ const terminal = new Terminal({
fontFamily: 'Consolas, monospace',
fontSize: 16,
cursorBlink: false,
stdinDisabled: true,
disableStdin: true,
theme: { background: '#181818', foreground: '#e8e8e8' },
});
const fit = new FitAddon.FitAddon();
terminal.parser.registerOscHandler(633, data => {
const prefix = 'ks-directory:';
if (!data.startsWith(prefix)) return false;
try {
bridge.postMessage('directory:' + decodeURIComponent(data.slice(prefix.length)));
} catch {
bridge.postMessage('directory:');
}
return true;
});
terminal.loadAddon(fit);
const host = document.getElementById('terminal');
terminal.open(host);
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true);
const screen = host.querySelector('.xterm-screen');
let traceEnabled = false;
let traceBudget = 4096;
let outputTraceBudget = 256;
let traceOutput = false;
let currentOffset = 0;
function trace(phase) {
if (!traceEnabled || traceBudget <= 0) return;
@@ -39,10 +52,27 @@ function anchorOutput() {
trace(2);
}
terminal.attachCustomKeyEventHandler(event => {
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.shiftKey) return true;
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter');
event.preventDefault();
return false;
}
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) return true;
if (event.code === 'KeyO') bridge.postMessage('toggle');
else if (event.code === 'ArrowUp') bridge.postMessage('grow');
else if (event.code === 'ArrowDown') bridge.postMessage('shrink');
else if (event.code === 'KeyF' || event.code === 'KeyC') {
if (!event.repeat) bridge.postMessage(event.code === 'KeyF' ? 'insert-path' : 'copy-command-line');
}
else if (event.key === 'Enter') {
if (!event.repeat) bridge.postMessage('insert-name');
}
else if (event.key === 'Insert') {
if (!event.repeat) bridge.postMessage('copy-command-line-or-panel-names');
}
else if (event.code === 'KeyR') {
if (!event.repeat) bridge.postMessage('refresh-panel');
}
else return true;
event.preventDefault();
return false;
@@ -54,8 +84,18 @@ terminal.onScroll(() => {
anchorOutput();
});
bridge.addEventListener('message', ({ data }) => {
if (data === 'trace:on') {
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;
}
@@ -73,7 +113,16 @@ bridge.addEventListener('message', ({ data }) => {
}
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);
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;
+62 -6
View File
@@ -4,6 +4,7 @@
[string]$InstallDirectory, [string]$WorkDirectory,
[int]$ParentProcessId, [string]$ReadyEvent,
[switch]$ShowProgress,
[switch]$Unattended, [string]$Journal,
[switch]$Library
)
$ErrorActionPreference = 'Stop'
@@ -408,12 +409,60 @@ function Undo-Files([string]$Target,[string]$Backup,[Collections.Generic.List[st
function Write-Result($Value) {
$Value | ConvertTo-Json -Compress | Set-Content -LiteralPath (Join-Path $WorkDirectory 'result.json') -Encoding UTF8
}
function Write-UpdateJournal([string]$Message) {
if (!$Journal) { return }
$label = if ($Unattended) { 'LAN update' } else { 'Update' }
[IO.File]::AppendAllText($Journal, "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ${label}: $Message`n",
[Text.UTF8Encoding]::new($false))
}
function Stop-UpdateCompanions([string]$Directory) {
if (!('KSwitcherUpdateProcessImage' -as [type])) {
Add-Type @'
using System;
using System.Runtime.InteropServices;
using System.Text;
public static class KSwitcherUpdateProcessImage {
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
[DllImport("kernel32.dll", CharSet=CharSet.Unicode)]
static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder image, ref int length);
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
public static string Read(int pid) {
var process = OpenProcess(0x1000, false, pid);
if (process == IntPtr.Zero) return null;
try {
var length = 32768;
var image = new StringBuilder(length);
return QueryFullProcessImageName(process, 0, image, ref length) ? image.ToString() : null;
} finally { CloseHandle(process); }
}
}
'@
}
$root = [IO.Path]::GetFullPath($Directory).TrimEnd('\')
$prefix = [regex]::Escape($root + '\')
$pattern = '^' + $prefix + '(?:\.kswitcher-update-[0-9a-f]{32}\\backup\\)?(?:KSwitcher(?:\.(?:Config|Screenshot|Files))?\.exe|tools\\StayHere\.exe)$'
foreach ($process in @(Get-Process 'KSwitcher','KSwitcher.Config','KSwitcher.Screenshot','KSwitcher.Files','StayHere' -ErrorAction SilentlyContinue)) {
$image = [KSwitcherUpdateProcessImage]::Read($process.Id)
if (!$image -and !$process.HasExited) {
Write-UpdateJournal "Could not identify $($process.ProcessName) (PID $($process.Id))."
}
if ($image -notmatch $pattern) { continue }
Write-UpdateJournal "Closing $($process.ProcessName) (PID $($process.Id))."
if (!$process.HasExited) {
try { $process.Kill() } catch { if (!$process.HasExited) { throw } }
if (!$process.WaitForExit(10000)) { throw "Could not close $($process.ProcessName) (PID $($process.Id))." }
}
Write-UpdateJournal "Closed $($process.ProcessName) (PID $($process.Id))."
}
}
if ($Library) { return }
$transaction = $null; $parentProcess = $null; $ready = $null; $started = $null
$changed = [Collections.Generic.List[string]]::new()
$parentExited = $false; $success = $false; $preserveBackup = $false; $child = $null; $uiFinished = $false
try {
if ($ShowProgress -or $Mode -eq 'Install') { Start-UpdateProgress }
if (!$Unattended -and ($ShowProgress -or $Mode -eq 'Install')) { Start-UpdateProgress }
$current = Get-StableVersion $CurrentVersion
if (!$current) { throw 'Invalid installed version.' }
if ($Mode -eq 'Install') {
@@ -426,9 +475,12 @@ try {
$metadata = Join-Path $WorkDirectory 'releases.json'
Receive-File 'https://gitea.hrynco.com/api/v1/repos/hrynco/hrynco-kswitcher/releases?limit=100' $metadata 2MB
$release = Select-Release (Get-Content -LiteralPath $metadata -Raw | ConvertFrom-Json) $current
if (!$release) { Write-Result @{state='current'}; exit 0 }
if (!$release) {
if ($Unattended) { Write-UpdateJournal "No newer stable release is available ($CurrentVersion)." }
Write-Result @{state='current'}; exit 0
}
if ($Mode -eq 'Check') { Write-Result @{state='available';version=$release.version}; exit 0 }
if ($ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' }
if (!$Unattended -and $ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' }
Assert-PlainDirectory $InstallDirectory
$transaction = Join-Path $InstallDirectory ('.kswitcher-update-'+[guid]::NewGuid().ToString('N'))
$stage = Join-Path $transaction 'stage'; $backup = Join-Path $transaction 'backup'
@@ -441,13 +493,15 @@ try {
Assert-Checksum $archive $checksum
Show-UpdateProgress 'Preparing installation' 'Validating and unpacking the release files'
Expand-Release $archive $stage (Get-StableVersion $release.version)
$screenshotPath = [IO.Path]::GetFullPath((Join-Path $InstallDirectory 'KSwitcher.Screenshot.exe'))
if (Get-Process 'KSwitcher.Screenshot' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $screenshotPath }) { throw 'Close screenshot editors before installing an update.' }
Write-UpdateJournal "Verified $($release.version). Closing KSwitcher (PID $ParentProcessId)."
Write-Result @{state='prepared';version=$release.version}
Show-UpdateProgress 'Closing KSwitcher' 'Waiting for the running application to exit safely'
$ready.Set() | Out-Null
if (!$parentProcess.WaitForExit(120000)) { throw 'KSwitcher did not exit; the installed files were not changed.' }
$parentExited = $true
Write-UpdateJournal "Closed KSwitcher (PID $ParentProcessId)."
Show-UpdateProgress 'Closing KSwitcher components' 'Closing Files, editors, Settings and StayHere'
Stop-UpdateCompanions $InstallDirectory
Show-UpdateProgress 'Installing update' 'Replacing application files; keeping your personal data'
Install-Files $stage $InstallDirectory $backup $changed
$startedName = 'Local\KSwitcher.Update.Started.'+[guid]::NewGuid().ToString('N')
@@ -456,6 +510,7 @@ try {
$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
}
@@ -474,7 +529,8 @@ try {
}
}
Write-Result @{state='error';error=$message}
if ($ready -and $ready.WaitOne(0)) {
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 {
+49 -8
View File
@@ -4,6 +4,7 @@
#include "../resources/resource.h"
#include "ocr.h"
#include "lan_clipboard_image.h"
#include "lan_files.h"
#include "configuration.h"
#include "diagnostics.h"
#include "paste_probe.h"
@@ -143,6 +144,28 @@ ULONG_PTR snippetReplayMarker()
}
constexpr int OpenFiles = 25, FilesHotkeyFirst = 0x4B10, FilesHotkeySecond = 0x4B11;
bool activateFilesWindow()
{
HWND files{};
EnumWindows([](HWND candidate, LPARAM context) -> BOOL
{
wchar_t name[32]{};
if(!IsWindowVisible(candidate) || !GetClassNameW(candidate,name,std::size(name)) ||
wcscmp(name,L"KSwitcher.Files"))
return TRUE;
*reinterpret_cast<HWND *>(context)=candidate;
return FALSE;
},reinterpret_cast<LPARAM>(&files));
if(!files) return false;
if(IsIconic(files)) ShowWindowAsync(files,SW_RESTORE);
if(!SetForegroundWindow(files))
{
FLASHWINFO flash{sizeof(flash),files,FLASHW_TRAY,3,0};
FlashWindowEx(&flash);
}
return true;
}
std::vector<std::pair<int, std::wstring>> shortcuts(const Settings &s)
{
std::vector<std::pair<int, std::wstring>> out{{Toggle, s.toggle},
@@ -2919,12 +2942,7 @@ void App::trayMenu()
void App::checkUpdate(bool interactive, bool install, const std::wstring &version)
{
if (updateRunning) return;
if (install && FindWindowW(L"KSwitcher.Config", nullptr))
{
report(L"Close the configurator before installing an update.");
return;
}
if (install && busy)
if (install && interactive && busy)
{
report(L"Wait for the current text operation to finish, then select Update again.");
return;
@@ -2984,6 +3002,22 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
switch (msg)
{
case LanUpdateRequestedMessage:
if (!lan::remoteUpdateAllowed()) return 0;
if (app->updateRunning)
{
if (!app->installingUpdate)
{
app->lanUpdatePending = true;
log(L"LAN update queued behind an update check.");
}
}
else
{
log(L"Starting unattended KSwitcher update requested over LAN.");
app->checkUpdate(false, true);
}
return 0;
case UpdateMessage:
{
std::unique_ptr<UpdateResult> result(reinterpret_cast<UpdateResult *>(lp));
@@ -2997,13 +3031,20 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
// The helper has verified and staged the package; it waits for process exit.
DestroyWindow(hwnd);
}
else if (std::exchange(app->lanUpdatePending, false) && lan::remoteUpdateAllowed() &&
result->state != L"current")
{
log(L"Starting queued unattended KSwitcher update.");
app->checkUpdate(false, true);
}
else if (result->state == L"available")
{
app->availableUpdate = result->version;
if (result->interactive)
{
auto prompt = L"Install KSwitcher " + result->version +
L"?\n\nThe program will close and restart. Settings, history and existing dictionaries are preserved.";
L"?\n\nKSwitcher will restart after closing Files, editors, Settings and StayHere from this installation. "
L"Save any unsaved work before continuing.";
if (MessageBoxW(hwnd, prompt.c_str(), L"KSwitcher Update", MB_YESNO | MB_ICONQUESTION) == IDYES)
app->checkUpdate(true, true, result->version);
}
@@ -3037,7 +3078,7 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case WM_HOTKEY:
if (app->filesHotkeyId && wp == static_cast<WPARAM>(app->filesHotkeyId))
{
app->dispatch(OpenFiles);
if(!activateFilesWindow()) app->dispatch(OpenFiles);
}
else if (wp != FilesHotkeyFirst && wp != FilesHotkeySecond) app->dispatch((int)wp);
return 0;
+1 -1
View File
@@ -155,7 +155,7 @@ class App
std::vector<SyncConflict> pendingSyncConflicts;
Bytes syncSnapshot;
std::wstring syncStatus = L"Not connected.";
bool updateRunning{}, installingUpdate{};
bool updateRunning{}, installingUpdate{}, lanUpdatePending{};
std::wstring availableUpdate, notifiedUpdate;
bool (*updateNotifier)(const std::wstring &){};
bool stop{};
+16 -5
View File
@@ -4,17 +4,25 @@
#include <cstring>
namespace ks
{
bool configurationPeer(HWND window, const wchar_t *filename)
namespace
{
std::filesystem::path processImage(HWND window)
{
DWORD pid{};
GetWindowThreadProcessId(window, &pid);
HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!process) return false;
if (!process) return {};
wchar_t path[32768]; DWORD count = std::size(path);
bool ok = QueryFullProcessImageNameW(process, 0, path, &count) != 0;
CloseHandle(process);
auto expected = std::filesystem::path(executable()).parent_path() / filename;
return ok && _wcsicmp(path, expected.c_str()) == 0;
return ok ? std::filesystem::path(path) : std::filesystem::path{};
}
}
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)
{
@@ -35,7 +43,10 @@ void launchConfiguration(App &app, bool snippets, bool logs)
LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &message)
{
const bool filesPeers = message.dwData == FilesLanPeers;
if (!configurationPeer(sender, filesPeers ? L"KSwitcher.Files.exe" : L"KSwitcher.Config.exe") || message.cbData > ConfigLimit ||
const bool knownSender = filesPeers
? isFilesPeerImage(processImage(sender), std::filesystem::path(executable()).parent_path())
: configurationPeer(sender, L"KSwitcher.Config.exe");
if (!knownSender || message.cbData > ConfigLimit ||
(message.cbData && !message.lpData)) return FALSE;
Bytes reply;
bool ok = false;
+104
View File
@@ -0,0 +1,104 @@
constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)};
auto commandHistoryKeys=defaultHistoryKeys;
constexpr size_t commandHistoryLimit=1000;
bool validHistoryKeys(const std::array<WORD,2> &keys)
{
if(keys[0]==keys[1]) return false;
return std::all_of(keys.begin(),keys.end(),[](WORD binding)
{
const auto key=LOBYTE(binding), modifiers=HIBYTE(binding);
const bool letter=key>='A' && key<='Z';
const bool function=key>=VK_F1 && key<=VK_F12;
if(!letter && !function) return false;
if(modifiers==HOTKEYF_CONTROL)
return (letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
return false;
});
}
std::array<WORD,2> optionHistoryKeys(HWND dialog)
{
return {static_cast<WORD>(SendDlgItemMessageW(dialog,321,HKM_GETHOTKEY,0,0)),
static_cast<WORD>(SendDlgItemMessageW(dialog,323,HKM_GETHOTKEY,0,0))};
}
void setOptionHistoryKeys(HWND dialog,const std::array<WORD,2> &keys)
{
SendDlgItemMessageW(dialog,321,HKM_SETHOTKEY,keys[0],0);
SendDlgItemMessageW(dialog,323,HKM_SETHOTKEY,keys[1],0);
}
void loadCommandHistoryKeys()
{
const std::array<WORD,2> keys{static_cast<WORD>(preference(L"PreviousCommandKey",defaultHistoryKeys[0])),
static_cast<WORD>(preference(L"CommandHistoryKey",defaultHistoryKeys[1]))};
commandHistoryKeys=validHistoryKeys(keys)?keys:defaultHistoryKeys;
}
void loadCommandHistory()
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)
!=ERROR_SUCCESS || bytes>16*1024*1024 || bytes%sizeof(wchar_t)) return;
std::wstring data(bytes/sizeof(wchar_t),L'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)
!=ERROR_SUCCESS) return;
size_t start{};
while(start<data.size())
{
const auto dateEnd=data.find(L'\0',start);
if(dateEnd==std::wstring::npos) break;
const auto commandEnd=data.find(L'\0',dateEnd+1);
if(commandEnd==std::wstring::npos) break;
terminalHistory.push_back({data.substr(start,dateEnd-start),data.substr(dateEnd+1,commandEnd-dateEnd-1)});
start=commandEnd+1;
}
terminalHistoryIndex=terminalHistory.size();
}
void rememberCommand(const std::wstring &command)
{
terminalHistory.push_back({ks::files::historyDate(),command});
if(terminalHistory.size()>commandHistoryLimit) terminalHistory.erase(terminalHistory.begin());
std::wstring data;
for(const auto &entry:terminalHistory)
{
data.append(entry.date).push_back(L'\0');
data.append(entry.command).push_back(L'\0');
}
if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",REG_BINARY,data.data(),
static_cast<DWORD>(data.size()*sizeof(wchar_t)))!=ERROR_SUCCESS)
setStatus(L"Could not save command history.");
refreshCommandHistory();
}
void recallCommand(size_t index)
{
terminalHistoryIndex=index;
SetWindowTextW(terminalInput,index<terminalHistory.size()?terminalHistory[index].command.c_str():L"");
SetFocus(terminalInput);
SendMessageW(terminalInput,EM_SETSEL,-2,-1);
}
void showCommandHistory(HWND owner);
bool handleCommandHistoryKey(HWND window,const MSG &message)
{
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
if((GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000)) return false;
const BYTE modifiers=((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0) |
((GetKeyState(VK_MENU)&0x8000)?HOTKEYF_ALT:0) | ((GetKeyState(VK_SHIFT)&0x8000)?HOTKEYF_SHIFT:0);
const auto binding=MAKEWORD(message.wParam,modifiers);
if(binding==commandHistoryKeys[0] && (message.hwnd==terminalInput ||
message.hwnd==panels[0].list || message.hwnd==panels[1].list))
{
if(terminalHistoryIndex) recallCommand(terminalHistoryIndex-1);
return true;
}
if(binding!=commandHistoryKeys[1]) return false;
if(!(message.lParam&(1LL<<30))) showCommandHistory(window);
return true;
}
+328
View File
@@ -0,0 +1,328 @@
constexpr int historyList=324;
constexpr int historySearch=325;
constexpr COLORREF historySearchSurface=RGB(132,177,177);
constexpr int historySearchLabel=326;
HWND commandHistoryWindow{};
std::wstring historyLower(std::wstring value)
{
if(!value.empty()) CharLowerBuffW(value.data(),static_cast<DWORD>(value.size()));
return value;
}
std::wstring_view commandTopicKeywords(const std::wstring &command)
{
const auto start=command.find_first_not_of(L" \t");
if(start==command.npos) return L"";
const auto end=command.find_first_of(L" \t",start);
auto tool=command.substr(start,end-start);
if(tool.ends_with(L".exe")) tool.resize(tool.size()-4);
const auto args=end==command.npos?L"":command.substr(end);
if(tool==L"ipconfig" && args.find(L"/flushdns")!=args.npos)
return L"network tools мережа dns flush clear cache очистити кеш";
if(tool==L"nslookup" || tool==L"resolve-dnsname")
return L"network tools мережа dns lookup запит";
if(tool==L"ping" || tool==L"tracert" || tool==L"ipconfig" || tool==L"test-netconnection" ||
tool==L"netstat" || tool==L"curl" || tool==L"invoke-webrequest")
return L"network tools мережа з’єднання connectivity address адреса";
if(tool==L"cls" || tool==L"clear" || tool==L"clear-host")
return L"terminal clear screen очистити екран консоль";
if(tool==L"git")
{
const auto first=args.find_first_not_of(L" \t");
const auto action=first==args.npos?L"":args.substr(first,args.find_first_of(L" \t",first)-first);
if(action==L"pull" || action==L"fetch" || action==L"update")
return L"git version control repository update fetch pull оновити репозиторій синхронізація";
return L"git version control repository репозиторій контроль версій";
}
return L"";
}
void populateCommandHistory(HWND dialog)
{
const auto search=GetDlgItem(dialog,historySearch);
std::wstring query(GetWindowTextLengthW(search)+1,L'\0');
query.resize(GetWindowTextW(search,query.data(),static_cast<int>(query.size())));
query=historyLower(std::move(query));
std::wistringstream stream(query);
std::vector<std::wstring> words;
for(std::wstring word;stream>>word;) words.push_back(word);
const auto list=GetDlgItem(dialog,historyList);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
const auto add=[&](const std::wstring &label,LPARAM index)
{
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row>=0) SendMessageW(list,LB_SETITEMDATA,row,index);
return row;
};
std::array<std::vector<size_t>,2> matches;
std::set<std::wstring_view> seen;
for(size_t index=terminalHistory.size();index-- > 0;)
{
const auto &entry=terminalHistory[index];
if(!seen.insert(entry.command).second) continue;
const auto command=historyLower(entry.command);
const auto containsAll=[&](const std::wstring &text)
{
return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;});
};
if(containsAll(command+L" "+entry.date))
{
matches[0].push_back(index);
continue;
}
const auto keywords=commandTopicKeywords(command);
if(!keywords.empty() && containsAll(command+L" "+entry.date+L" "+std::wstring(keywords)))
matches[1].push_back(index);
}
LRESULT selected=LB_ERR;
for(const auto &group:matches)
{
std::wstring lastDate;
bool first=true;
for(auto match=group.rbegin();match!=group.rend();++match)
{
const auto index=*match;
const auto &entry=terminalHistory[index];
const auto &date=entry.date;
if(first || date!=lastDate) add(date,-1);
first=false;
lastDate=date;
const auto row=add(entry.command,index);
if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row;
}
}
if(selected==LB_ERR) add(words.empty()?L"No commands yet":L"No matching commands",-2);
else SendMessageW(list,LB_SETCURSEL,selected,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,TRUE);
}
LRESULT CALLBACK historySearchKeys(HWND search,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR)
{
if(message==WM_GETDLGCODE)
{
const auto code=DefSubclassProc(search,message,key,flags);
if(key==VK_TAB || key==VK_ESCAPE) return code&~DLGC_WANTALLKEYS;
if(key==VK_RETURN) return code|DLGC_WANTMESSAGE;
return code|DLGC_WANTARROWS;
}
if(message==WM_KEYDOWN && key==VK_RETURN)
{
SendMessageW(GetParent(search),WM_COMMAND,IDOK,0);
return 0;
}
if(message==WM_KEYDOWN && (key==VK_UP || key==VK_DOWN))
{
const auto list=GetDlgItem(GetParent(search),historyList);
SetFocus(list);
SendMessageW(list,message,key,flags);
return 0;
}
return DefSubclassProc(search,message,key,flags);
}
int historyRowInset(UINT dpi)
{
return std::max(MulDiv(4,dpi,96),dialogFrameMetrics(dpi).inner)+dialogRowTextInset(cellWidth);
}
LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_GETDLGCODE && wp==VK_RETURN)
return DefSubclassProc(list,message,wp,lp)|DLGC_WANTMESSAGE;
if(message==WM_KEYDOWN && wp==VK_RETURN)
{
SendMessageW(GetParent(list),WM_COMMAND,IDOK,0);
return 0;
}
if(message==LB_GETTOPINDEX || message==WM_NCDESTROY)
return DefSubclassProc(list,message,wp,lp);
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
const auto result=scrollList(list,message,wp,lp);
if(top!=SendMessageW(list,LB_GETTOPINDEX,0,0))
InvalidateRect(GetParent(list),nullptr,FALSE);
return result;
}
void sizeCommandHistory(HWND dialog,HWND list)
{
const auto owner=GetWindow(dialog,GW_OWNER);
RECT ownerBounds{};
if(!GetWindowRect(owner,&ownerBounds) || IsIconic(owner)) return;
MONITORINFO monitor{sizeof(monitor)};
if(!GetMonitorInfoW(MonitorFromWindow(owner,MONITOR_DEFAULTTONEAREST),&monitor)) return;
RECT area{};
if(!IntersectRect(&area,&ownerBounds,&monitor.rcWork)) area=monitor.rcWork;
const auto dc=GetDC(list);
if(!dc) return;
const auto previous=SelectObject(dc,mono);
LONG longest{};
for(const auto &entry:terminalHistory)
{
SIZE size{};
if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast<int>(entry.command.size()),&size))
longest=std::max(longest,size.cx);
}
SelectObject(dc,previous);
ReleaseDC(list,dc);
const auto dpi=GetDpiForWindow(dialog);
const auto frame=dialogFrameMetrics(dpi);
const int inset=frame.content();
const int top=dialogListInset(frame,textHeight);
const int gap=MulDiv(4,dpi,96);
const int listTop=top+2*textHeight+2*gap;
const LONG desired=std::max<LONG>(MulDiv(320,dpi,96),
longest+2*cellWidth+2*historyRowInset(dpi)+GetSystemMetricsForDpi(SM_CXVSCROLL,dpi))+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-5),
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);
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);
}
+330
View File
@@ -0,0 +1,330 @@
HWND activeFilesDialog{};
HHOOK filesDialogMouseHook{};
bool filesMouseDown(UINT message)
{
return message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN ||
message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN;
}
bool handleFilesDialogClick(HWND dialog,HWND clicked,POINT point)
{
if(!clicked || clicked==dialog || IsChild(dialog,clicked) ||
GetAncestor(clicked,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER))
return false;
wchar_t windowClass[16]{};
if(GetClassNameW(clicked,windowClass,16) && std::wstring_view(windowClass)==L"#32768")
{
GUITHREADINFO thread{sizeof(thread)};
if(GetGUIThreadInfo(GetWindowThreadProcessId(dialog,nullptr),&thread) &&
(thread.hwndMenuOwner==dialog || IsChild(dialog,thread.hwndMenuOwner)))
return false;
}
// System pickers and dropdowns owned by this dialog handle their own input.
for(auto popup=GetAncestor(clicked,GA_ROOT);popup;popup=GetWindow(popup,GW_OWNER))
if(popup==dialog || IsChild(dialog,popup)) return false;
for(auto owner=GetWindow(dialog,GW_OWNER);owner;owner=GetWindow(owner,GW_OWNER))
{
if(clicked!=owner) continue;
RECT client{};
GetClientRect(owner,&client);
ScreenToClient(owner,&point);
if(!PtInRect(&client,point)) return false;
break;
}
if(const auto dropdown=static_cast<HWND>(GetPropW(dialog,ks::files::farDropDownProperty)))
return PostMessageW(dropdown,WM_CLOSE,0,0)!=FALSE;
return PostMessageW(dialog,WM_COMMAND,IDCANCEL,0)!=FALSE;
}
LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data)
{
const auto dialog=activeFilesDialog;
if(code==HC_ACTION && dialog && IsWindowVisible(dialog) && filesMouseDown(static_cast<UINT>(message)))
{
const auto point=reinterpret_cast<const MSLLHOOKSTRUCT*>(data)->pt;
if(handleFilesDialogClick(dialog,WindowFromPoint(point),point)) return 1;
}
return CallNextHookEx(nullptr,code,message,data);
}
class FilesModalDialog
{
public:
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument)
{
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
}
~FilesModalDialog() { close(); }
FilesModalDialog(const FilesModalDialog &)=delete;
FilesModalDialog &operator=(const FilesModalDialog &)=delete;
HWND window() const { return window_; }
static HWND activeFor(HWND owner)
{
const auto root=GetAncestor(owner,GA_ROOTOWNER);
for(auto dialog=activeFilesDialog;dialog;)
{
if(GetAncestor(dialog,GA_ROOTOWNER)==root) return dialog;
const auto *state=reinterpret_cast<const FilesModalDialog *>(GetPropW(dialog,stateProperty_));
dialog=state?state->previous_:nullptr;
}
return nullptr;
}
static void fitWidthToOwner(HWND dialog,int minimum,void (*layout)(HWND))
{
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
RECT bounds{};
if(!state || !GetWindowRect(dialog,&bounds)) return;
state->preferredWidth_=bounds.right-bounds.left;
state->minimumWidth_=minimum;
state->layout_=layout;
}
static void refreshLayout(HWND dialog)
{
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
if(!state || !state->entered_ || state->layout_) return;
state->captureLayout();
state->fitWidth(dialog,state->ownerBounds_);
}
static bool dismissOwned(HWND owner)
{
const auto dialog=activeFor(owner);
for(auto parent=GetWindow(dialog,GW_OWNER);parent;parent=GetWindow(parent,GW_OWNER))
if(parent==owner) return PostMessageW(dialog,WM_CLOSE,0,0)!=FALSE;
return false;
}
void show()
{
if(!window_ || entered_) return;
previous_=activeFilesDialog;
activeFilesDialog=window_;
entered_=true;
if(!filesDialogMouseHook)
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
if(GetWindowRect(owner_,&ownerBounds_))
{
if(!layout_) captureLayout();
SetWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this),reinterpret_cast<DWORD_PTR>(this));
if(ownerBounds_.right-ownerBounds_.left<minimumOwnerWidth() && !IsZoomed(owner_))
SetWindowPos(owner_,nullptr,0,0,minimumOwnerWidth(),ownerBounds_.bottom-ownerBounds_.top,
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
fitWidth(window_,ownerBounds_,true);
}
ShowWindow(window_,SW_SHOW);
SetActiveWindow(window_);
}
void close()
{
if(entered_ && IsWindow(owner_))
RemoveWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this));
if(window_ && IsWindow(window_)) DestroyWindow(window_);
window_=nullptr;
if(!entered_) return;
entered_=false;
activeFilesDialog=previous_;
if(!previous_ && filesDialogMouseHook)
{
UnhookWindowsHookEx(filesDialogMouseHook);
filesDialogMouseHook=nullptr;
}
if(IsWindow(owner_) && !IsIconic(GetAncestor(owner_,GA_ROOTOWNER)))
{
SetActiveWindow(owner_);
if(IsWindow(focus_) && IsWindowEnabled(focus_) && (focus_==owner_ || IsChild(owner_,focus_)))
SetFocus(focus_);
}
}
static bool handleMessage(HWND dialog,MSG &message)
{
if(message.hwnd==dialog || IsChild(dialog,message.hwnd))
{
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
{
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
return true;
}
return IsDialogMessageW(dialog,&message)!=FALSE;
}
if(!message.hwnd || GetAncestor(message.hwnd,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER))
return false;
const bool input=(message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) ||
(message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST) ||
message.message==WM_CONTEXTMENU;
if(input && (filesMouseDown(message.message) ||
(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)))
PostMessageW(dialog,WM_COMMAND,IDCANCEL,0);
return input;
}
static void finish(HWND dialog,INT_PTR answer)
{
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
if(!state) return;
state->result_=answer;
state->finished_=true;
ShowWindow(dialog,SW_HIDE);
}
static INT_PTR run(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
{
FilesModalDialog dialog(instance,resource,owner,procedure,argument);
if(!dialog.window()) return -1;
dialog.show();
MSG message{};
while(!dialog.finished_ && IsWindow(dialog.window()))
{
const auto status=GetMessageW(&message,nullptr,0,0);
if(status<=0)
{
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
break;
}
if(handleMessage(dialog.window(),message)) continue;
TranslateMessage(&message);
DispatchMessageW(&message);
}
return dialog.result_;
}
private:
static constexpr wchar_t stateProperty_[]=L"KSwitcher.Files.ModalDialog";
HWND window_{},owner_{},focus_{},previous_{};
RECT ownerBounds_{};
int preferredWidth_{},minimumWidth_{};
std::vector<std::pair<HWND,RECT>> controls_;
void (*layout_)(HWND){};
DLGPROC procedure_;
LPARAM argument_;
INT_PTR result_=IDCANCEL;
bool entered_{},finished_{};
void captureLayout()
{
RECT bounds{};
GetWindowRect(window_,&bounds);
preferredWidth_=bounds.right-bounds.left;
minimumWidth_=MulDiv(preferredWidth_,3,4);
controls_.clear();
if(GetWindowLongPtrW(window_,GWL_STYLE)&WS_THICKFRAME)
{
MINMAXINFO limits{};
SendMessageW(window_,WM_GETMINMAXINFO,0,reinterpret_cast<LPARAM>(&limits));
minimumWidth_=std::max<int>(minimumWidth_,limits.ptMinTrackSize.x);
return;
}
const auto dc=GetDC(window_);
if(!dc) return;
for(auto field=GetWindow(window_,GW_CHILD);field;field=GetWindow(field,GW_HWNDNEXT))
{
RECT rect{};
GetWindowRect(field,&rect);
MapWindowPoints(nullptr,window_,reinterpret_cast<POINT *>(&rect),2);
wchar_t type[16]{},label[128]{};
GetClassNameW(field,type,16);
RECT dropdown{};
if(lstrcmpiW(type,L"ComboBox")==0 &&
SendMessageW(field,CB_GETDROPPEDCONTROLRECT,0,reinterpret_cast<LPARAM>(&dropdown)))
rect.bottom=rect.top+dropdown.bottom-dropdown.top;
controls_.emplace_back(field,rect);
const auto fieldWidth=rect.right-rect.left;
if(!(GetWindowLongPtrW(field,GWL_STYLE)&WS_VISIBLE) || fieldWidth<=0) continue;
if(lstrcmpiW(type,L"Button")!=0 || !GetWindowTextW(field,label,128)) continue;
const auto font=reinterpret_cast<HFONT>(SendMessageW(field,WM_GETFONT,0,0));
const auto previous=font?SelectObject(dc,font):nullptr;
RECT text{};
DrawTextW(dc,label,-1,&text,DT_SINGLELINE|DT_CALCRECT);
TEXTMETRICW metrics{};
GetTextMetricsW(dc,&metrics);
if(previous) SelectObject(dc,previous);
const auto needed=std::min(fieldWidth,text.right+4*metrics.tmAveCharWidth);
minimumWidth_=std::max(minimumWidth_,static_cast<int>(
(preferredWidth_*needed+fieldWidth-1)/fieldWidth));
}
ReleaseDC(window_,dc);
}
int ownerMargin() const { return MulDiv(12,GetDpiForWindow(owner_),96); }
int minimumOwnerWidth() const { return minimumWidth_+2*ownerMargin(); }
void fitWidth(HWND window,const RECT &owner,bool initial=false)
{
RECT bounds{};
if(!GetWindowRect(window,&bounds)) return;
const int width=std::clamp(static_cast<int>(owner.right-owner.left)-2*ownerMargin(),
minimumWidth_,std::max(minimumWidth_,preferredWidth_));
const int height=bounds.bottom-bounds.top;
const int x=(owner.left+owner.right-width)/2;
const int y=(owner.top+owner.bottom-height)/2;
const bool resized=width!=bounds.right-bounds.left;
if(x!=bounds.left || y!=bounds.top || resized)
SetWindowPos(window,nullptr,x,y,width,height,SWP_NOZORDER|SWP_NOACTIVATE|
(resized?SWP_NOCOPYBITS:0));
if(layout_ && (initial || resized)) layout_(window);
else if(resized && preferredWidth_>0)
for(const auto &[field,rect]:controls_)
{
const auto left=MulDiv(rect.left,width,preferredWidth_);
const auto right=MulDiv(rect.right,width,preferredWidth_);
SetWindowPos(field,nullptr,left,rect.top,right-left,rect.bottom-rect.top,
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
}
if(initial || resized) RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
}
static LRESULT CALLBACK trackOwner(HWND owner,UINT message,WPARAM wp,LPARAM lp,UINT_PTR id,DWORD_PTR data)
{
auto &dialog=*reinterpret_cast<FilesModalDialog *>(data);
if(message==WM_WINDOWPOSCHANGING && !IsIconic(owner))
{
auto &position=*reinterpret_cast<WINDOWPOS *>(lp);
if(!(position.flags&SWP_NOSIZE) && position.cx>0)
position.cx=std::max(position.cx,dialog.minimumOwnerWidth());
}
if(message==WM_NCDESTROY) RemoveWindowSubclass(owner,trackOwner,id);
const auto result=DefSubclassProc(owner,message,wp,lp);
if(message==WM_GETMINMAXINFO)
{
auto &limits=*reinterpret_cast<MINMAXINFO *>(lp);
limits.ptMinTrackSize.x=std::max<LONG>(limits.ptMinTrackSize.x,dialog.minimumOwnerWidth());
return result;
}
if((message!=WM_MOVE && message!=WM_SIZE) || IsIconic(owner)) return result;
RECT ownerBounds{};
if(!GetWindowRect(owner,&ownerBounds)) return result;
if(EqualRect(&ownerBounds,&dialog.ownerBounds_)) return result;
dialog.ownerBounds_=ownerBounds;
dialog.fitWidth(dialog.window_,ownerBounds);
return result;
}
static INT_PTR CALLBACK dispatchDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
if(message==WM_INITDIALOG)
{
state=reinterpret_cast<FilesModalDialog *>(lp);
if(!SetPropW(dialog,stateProperty_,state)) return FALSE;
lp=state->argument_;
}
if(!state) return FALSE;
const auto handled=state->procedure_(dialog,message,wp,lp);
if(message==WM_NCDESTROY) RemovePropW(dialog,stateProperty_);
if(!handled && message==WM_CLOSE)
{
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
return TRUE;
}
return handled;
}
};
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <windows.h>
#include <algorithm>
namespace ks::files
{
inline void paintFarDropDownArrow(HDC dc, const RECT &bounds, HBRUSH surface, COLORREF ink, UINT dpi)
{
FillRect(dc, &bounds, surface);
// Center the drawn pixels. A font's arrow glyph can sit below the center of its line box.
const auto halfWidth = std::min((bounds.right - bounds.left - 1) / 2,
static_cast<LONG>(MulDiv(3, dpi, 96)));
const auto halfHeight = std::min((bounds.bottom - bounds.top - 1) / 2,
static_cast<LONG>(MulDiv(5, dpi, 96)));
if (halfWidth < 1 || halfHeight < 1) return;
const auto x = (bounds.left + bounds.right - 1) / 2;
const auto y = (bounds.top + bounds.bottom - 1) / 2;
const auto tip = y + halfHeight;
const auto head = std::min(halfWidth, halfHeight);
for (LONG row = y - halfHeight; row <= tip; ++row)
SetPixelV(dc, x, row, ink);
for (LONG offset = 1; offset <= head; ++offset)
{
SetPixelV(dc, x - offset, tip - offset, ink);
SetPixelV(dc, x + offset, tip - offset, ink);
}
}
inline void paintFarFieldArrow(HDC dc, const RECT &bounds, bool enabled, UINT dpi)
{
paintFarDropDownArrow(dc, bounds, static_cast<HBRUSH>(GetStockObject(LTGRAY_BRUSH)),
enabled ? RGB(0,0,0) : RGB(48,48,48), dpi);
}
}
+456
View File
@@ -0,0 +1,456 @@
struct FolderShortcut
{
fs::path path;
std::string peerId;
std::wstring peerName,title;
};
using FolderShortcuts=std::array<std::vector<FolderShortcut>,10>;
FolderShortcuts folderShortcuts;
constexpr wchar_t folderShortcutsKey[]=L"FolderShortcuts";
bool sameFolderShortcut(const FolderShortcut &left,const FolderShortcut &right)
{
return left.peerId==right.peerId &&
CompareStringOrdinal(left.path.c_str(),-1,right.path.c_str(),-1,TRUE)==CSTR_EQUAL;
}
bool saveFolderShortcuts(const FolderShortcuts &shortcuts)
{
try
{
auto groups=Json::array();
for(const auto &group:shortcuts)
{
auto rows=Json::array();
for(const auto &entry:group)
rows.push_back({{"path",ks::utf8(entry.path.native())},{"peer",entry.peerId},
{"name",ks::utf8(entry.peerName)},{"title",ks::utf8(entry.title)}});
groups.push_back(std::move(rows));
}
const auto data=groups.dump();
return data.size()<=1024*1024 &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
}
catch(const std::exception &){return false;}
}
void loadFolderShortcuts()
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>1024*1024) return;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
return;
try
{
const auto groups=Json::parse(data.begin(),data.begin()+bytes);
if(!groups.is_array() || groups.size()!=folderShortcuts.size()) return;
FolderShortcuts loaded;
for(size_t digit=0;digit<loaded.size();++digit)
{
if(!groups[digit].is_array()) return;
for(const auto &row:groups[digit])
{
FolderShortcut entry{filePath(row.at("path")),row.at("peer"),ks::wide(row.at("name")),ks::wide(row.value("title",""))};
if(!entry.path.is_absolute() || entry.path.native().find(L'\0')!=std::wstring::npos) continue;
loaded[digit].push_back(std::move(entry));
}
}
folderShortcuts=std::move(loaded);
}
catch(const std::exception &) {}
}
constexpr int shortcutTitle=314,shortcutPath=211;
struct FolderShortcutEdit
{
FolderShortcut entry;
int digit;
std::optional<size_t> index;
};
std::wstring shortcutField(HWND dialog,int id)
{
const auto field=GetDlgItem(dialog,id);
const auto length=GetWindowTextLengthW(field);
std::wstring result(static_cast<size_t>(length)+1,L'\0');
result.resize(GetWindowTextW(field,result.data(),length+1));
return result;
}
INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Folder shortcuts ",false,{315}))
return painted;
if(message==WM_INITDIALOG)
{
auto &edit=*reinterpret_cast<FolderShortcutEdit*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,316);
for(const auto id:{316,317,IDOK,IDCANCEL})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendDlgItemMessageW(dialog,shortcutTitle,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(dialog,shortcutPath,EM_SETLIMITTEXT,32767,0);
SetDlgItemTextW(dialog,shortcutTitle,edit.entry.title.c_str());
SetDlgItemTextW(dialog,shortcutPath,edit.entry.path.c_str());
if(!edit.entry.peerId.empty())
SetDlgItemTextW(dialog,317,(L"Path on "+edit.entry.peerName).c_str());
layoutDialogButtons(dialog,315,{IDOK,IDCANCEL});
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &edit=*reinterpret_cast<FolderShortcutEdit*>(GetWindowLongPtrW(dialog,DWLP_USER));
auto path=fs::path(shortcutField(dialog,shortcutPath)).lexically_normal();
if(path.has_relative_path() && !path.has_filename()) path=path.parent_path();
const auto root=path.root_name().native();
const bool lanDrive=root.size()==2 && root[1]==L':' &&
((root[0]>=L'A' && root[0]<=L'Z') || (root[0]>=L'a' && root[0]<=L'z'));
if(!path.is_absolute() || (!edit.entry.peerId.empty() && !lanDrive))
{
showFilesNotice(dialog,L"Enter an absolute folder path on the original computer.",L"Folder shortcuts");
SetFocus(GetDlgItem(dialog,shortcutPath));
return TRUE;
}
auto entry=edit.entry;
entry.path=std::move(path);
entry.title=shortcutField(dialog,shortcutTitle);
const auto &group=folderShortcuts[edit.digit];
for(size_t i=0;i<group.size();++i)
if((!edit.index || i!=*edit.index) && sameFolderShortcut(group[i],entry))
{
showFilesNotice(dialog,L"This folder is already assigned to this digit.",L"Folder shortcuts");
return TRUE;
}
auto updated=folderShortcuts;
if(edit.index) updated[edit.digit][*edit.index]=std::move(entry);
else updated[edit.digit].push_back(std::move(entry));
if(!saveFolderShortcuts(updated))
{
showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts");
return TRUE;
}
folderShortcuts=std::move(updated);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
{
return FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(110),owner,
folderShortcutEditDialog,reinterpret_cast<LPARAM>(&edit))==IDOK;
}
void addFolderShortcut(const Panel &panel,int digit)
{
if(panel.directory.empty()) return;
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
panel.peer?panel.peer->name:L""},digit,{}};
if(editFolderShortcut(GetParent(panel.list),edit))
setStatus(L"Folder added to Ctrl+"+std::to_wstring(digit)+L".");
SetFocus(panel.list);
}
void openFolderShortcut(Panel &panel,const FolderShortcut &entry)
{
if(entry.peerId.empty())
{
openOn(panel,entry.path,true,{});
return;
}
queryDrivePeers();
const auto peer=std::find_if(drivePeers.begin(),drivePeers.end(),
[&](const auto &candidate){return candidate.id==entry.peerId && !candidate.address.empty();});
if(peer==drivePeers.end())
{
setStatus(L"Paired computer unavailable: "+entry.peerName);
return;
}
openOn(panel,entry.path,false,*peer);
}
constexpr int shortcutList=310,quickRemove=313,quickEdit=318,quickInsert=319,quickMoveUp=320,quickMoveDown=321;
constexpr wchar_t quickFolderHints[]=L"Ins Del F4 Ctrl+Up Ctrl+Down";
struct FolderShortcutView
{
int digit;
std::optional<FolderShortcut> chosen;
std::vector<int> digits;
int rowHeight{};
Panel *panel{};
bool all{};
std::vector<std::pair<int,size_t>> entries;
};
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();
view.entries.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.all?L"Del F4":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.all)
{
for(int digit=0;digit<static_cast<int>(folderShortcuts.size());++digit)
for(size_t index=0;index<folderShortcuts[digit].size();++index)
{
view.entries.emplace_back(digit,index);
add(std::to_wstring(digit)+L" "+shortcutLabel(folderShortcuts[digit][index]));
}
}
else 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,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,width,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 scrollList(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);
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->all?L"Del F4":view->digit<0?L"Enter Esc":quickFolderHints);
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->all && 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;
}
int digit=view->digit;
size_t index=static_cast<size_t>(row);
if(view->all)
{
if(index>=view->entries.size() || action==quickInsert ||
action==quickMoveUp || action==quickMoveDown) return TRUE;
const auto &entry=view->entries[index];
digit=entry.first;
index=entry.second;
}
const auto &group=folderShortcuts[digit];
if(action==quickInsert)
{
const auto &panel=*view->panel;
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
panel.peer?panel.peer->name:L""},view->digit,{}};
if(!panel.directory.empty() && editFolderShortcut(dialog,edit))
layoutQuickFolders(dialog,*view,static_cast<int>(group.size())-1);
SetFocus(GetDlgItem(dialog,shortcutList));
return TRUE;
}
if(index>=group.size()) return TRUE;
if(action==quickMoveUp || action==quickMoveDown)
{
const auto target=row+(action==quickMoveUp?-1:1);
if(target<0 || static_cast<size_t>(target)>=group.size()) return TRUE;
auto updated=folderShortcuts;
std::swap(updated[view->digit][row],updated[view->digit][target]);
if(!saveFolderShortcuts(updated))
showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts");
else
{
folderShortcuts=std::move(updated);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
layoutQuickFolders(dialog,*view,static_cast<int>(target));
}
return TRUE;
}
if(action==quickEdit)
{
FolderShortcutEdit edit{group[index],digit,index};
if(editFolderShortcut(dialog,edit)) layoutQuickFolders(dialog,*view,static_cast<int>(row));
SetFocus(GetDlgItem(dialog,shortcutList));
return TRUE;
}
if(action==quickRemove)
{
auto updated=folderShortcuts;
updated[digit].erase(updated[digit].begin()+index);
if(!saveFolderShortcuts(updated))
{
showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts");
return TRUE;
}
folderShortcuts=std::move(updated);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
if(view->all?view->entries.size()==1: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,bool all)
{
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;
view.all=all;
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.");
}
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include <windows.h>
#include <string>
namespace ks::files
{
inline std::wstring historyDate()
{
SYSTEMTIME now{};
GetLocalTime(&now);
wchar_t date[24]{};
GetDateFormatEx(LOCALE_NAME_USER_DEFAULT,0,&now,L"dd.MM.yyyy",date,24,nullptr);
return date;
}
}
+24
View File
@@ -1,6 +1,30 @@
#pragma once
#include <windows.h>
#include <filesystem>
#include <string_view>
inline constexpr ULONG_PTR FilesLanPeers = 0x4b53010d;
inline constexpr ULONG_PTR FilesLanPeersReply = 0x4b53010e;
inline constexpr DWORD FilesLanPeersLimit = 64 * 1024;
namespace ks
{
inline bool isFilesPeerImage(const std::filesystem::path &image, const std::filesystem::path &install)
{
if (_wcsicmp(image.filename().c_str(), L"KSwitcher.Files.exe") != 0) return false;
const auto directory = image.parent_path();
if (_wcsicmp(directory.c_str(), install.c_str()) == 0) return true;
// Updating moves a still-running Files executable into the transaction backup.
// Windows then reports the moved path for its process image.
if (_wcsicmp(directory.filename().c_str(), L"backup") != 0) return false;
const auto transaction = directory.parent_path();
if (_wcsicmp(transaction.parent_path().c_str(), install.c_str()) != 0) return false;
constexpr std::wstring_view prefix = L".kswitcher-update-";
const auto name = transaction.filename().wstring();
if (name.size() != prefix.size() + 32 || _wcsnicmp(name.c_str(), prefix.data(), prefix.size()) != 0)
return false;
return std::wstring_view(name).substr(prefix.size()).find_first_not_of(L"0123456789abcdefABCDEF")
== std::wstring_view::npos;
}
}
+2464 -483
View File
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
#pragma once
namespace ks::files
{
template<class Index, class Selectable>
Index adjacentMenuRow(Index current, Index size, int direction, Selectable selectable)
{
auto row=current;
for(Index visited=0;visited<size;++visited)
{
row+=direction;
if(row<0) row=size-1;
if(row>=size) row=0;
if(selectable(row)) return row;
}
return current;
}
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <windows.h>
#include <string_view>
namespace ks::files
{
inline void paintMenuAccessKey(HDC dc, const RECT &clip, POINT origin, std::wstring_view title,
size_t access, COLORREF ink)
{
if (access >= title.size()) return;
SIZE prefix{};
GetTextExtentPoint32W(dc, title.data(), static_cast<int>(access), &prefix);
const auto background = SetBkMode(dc, TRANSPARENT);
const auto text = SetTextColor(dc, ink);
const auto alignment = SetTextAlign(dc, TA_LEFT | TA_TOP);
ExtTextOutW(dc, origin.x + prefix.cx, origin.y, ETO_CLIPPED, &clip, title.data() + access, 1, nullptr);
SetTextAlign(dc, alignment);
SetTextColor(dc, text);
SetBkMode(dc, background);
}
}
+556 -61
View File
@@ -1,7 +1,7 @@
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286;
constexpr int allOptions=3;
enum OptionsPage { PanelModes, PanelColors, Appearance };
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance"};
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372;
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions };
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",L"Viewer",L"Editor"};
constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background",
L"Menu selection",L"Command bar",L"File cursor"};
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
@@ -11,6 +11,40 @@ constexpr int wideColumnControls[]{275,276,201,202,204};
constexpr int statusColumnControls[]{277,203,205,206,207,208};
constexpr int colorOptionControls[]{279,280};
constexpr int appearanceControls[]{281,282};
enum AppearanceSection { Font, DialogFrame };
constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307;
constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding};
constexpr int textTabWidth=357,textLineEnding=359,
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368;
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme};
constexpr int editingControls[]{354,355,358,textLineEnding};
constexpr int markdownSection=1,markdownWidth=374,markdownFamily=376,markdownChoose=377,markdownSize=379;
constexpr int markdownControls[]{373,markdownWidth,375,markdownFamily,markdownChoose,378,markdownSize};
constexpr wchar_t optionsLocationKey[]=L"OptionsLocation";
constexpr struct
{
int id;
bool ks::files::TextPreferences::*value;
const wchar_t *name;
} textChecks[]{
{350,&ks::files::TextPreferences::wrap,L"Wrap lines"},
{351,&ks::files::TextPreferences::numbers,L"Line numbers"},
{352,&ks::files::TextPreferences::whitespace,L"Show whitespace and line endings"},
{353,&ks::files::TextPreferences::caretLine,L"Highlight current line"},
{354,&ks::files::TextPreferences::tabsAsSpaces,L"Insert spaces for tabs"},
{355,&ks::files::TextPreferences::autoIndent,L"Auto indent"}};
bool textOptionsPage(int page) { return page==TextViewer || page==TextEditor; }
constexpr struct
{
int id;
DWORD DialogFramePadding::*value;
DWORD maximum;
} frameOptions[]{
{outerFramePadding,&DialogFramePadding::outer,maxDialogFramePadding},
{innerFramePadding,&DialogFramePadding::inner,maxDialogFramePadding},
{rowTextPadding,&DialogFramePadding::rowText,maxDialogRowTextPadding}};
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight };
struct OptionsControl
@@ -40,17 +74,40 @@ void resetPanelProperty(HWND dialog,const PanelProperty &property)
else CheckDlgButton(dialog,property.control,property.defaultValue);
}
struct OptionsDraft
struct OptionsBaseline
{
LOGFONTW font=displayFont;
int points=fontPoints;
DialogFramePadding padding=dialogFramePadding;
std::array<COLORREF,ColorCount> palette=colors;
std::vector<FileStyle> styles=fileStyles;
std::array<WORD,2> keys=commandHistoryKeys;
bool remoteTerminal=ks::lan::remoteTerminalAllowed();
bool remoteHibernate=ks::lan::remoteHibernateAllowed();
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
std::array<bool,2> wide{panels[0].wide,panels[1].wide};
ks::files::TextSettings text=ks::files::loadTextPreferences();
};
struct OptionsDraft
{
OptionsBaseline baseline;
ks::files::TextSettings text=baseline.text;
HWND filesWindow{};
LOGFONTW font=displayFont;
int points=fontPoints;
DialogFramePadding framePadding=dialogFramePadding;
std::array<COLORREF,ColorCount> palette{};
std::array<COLORREF,16> custom{};
std::vector<FileStyle> styles=fileStyles;
int styleIndex=0;
bool styleSuggestionsLoaded{};
int page=PanelModes, section=PanelLayout;
HTREEITEM wideColumnsNode{};
DWORD location{};
int markdownError{};
HTREEITEM wideColumnsNode{},markdownNode{};
RECT initialClient{};
UINT initialDpi=96;
OptionsControl controls[8]{
@@ -68,15 +125,28 @@ struct OptionsDraft
bool optionsFontChanged(const OptionsDraft &draft)
{
auto pending=draft.font, applied=displayFont;
auto pending=draft.font, applied=draft.baseline.font;
// Height follows the selected point size and DPI. applyFont always uses natural width.
pending.lfHeight=applied.lfHeight=0;
pending.lfWidth=applied.lfWidth=0;
return draft.points!=fontPoints ||
return draft.points!=draft.baseline.points ||
memcmp(&pending,&applied,offsetof(LOGFONTW,lfFaceName))!=0 ||
_wcsicmp(pending.lfFaceName,applied.lfFaceName)!=0;
}
struct OptionsWriteLock
{
HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite");
DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED;
bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; }
~OptionsWriteLock()
{
if(acquired()) ReleaseMutex(mutex);
if(mutex) CloseHandle(mutex);
}
};
void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
{
BOOL valid{};
@@ -84,10 +154,16 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
DWORD fields=0;
for(int i=0;i<4;++i) if(checked(205+i)) fields|=1u<<i;
const bool dirty=!valid || width!=static_cast<UINT>(sizeWidth) ||
checked(273)!=panels[0].wide || checked(274)!=panels[1].wide ||
checked(202)!=alignExtensions || checked(204)!=alignFolders || checked(203)!=showDetails ||
fields!=statusFields || draft.palette!=colors || draft.styles!=fileStyles || optionsFontChanged(draft);
const auto &base=draft.baseline;
const bool dirty=!valid || draft.markdownError || width!=base.width ||
checked(273)!=base.wide[0] || checked(274)!=base.wide[1] ||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
draft.text!=base.text;
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
}
@@ -149,23 +225,205 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft)
SetWindowPos(GetDlgItem(dialog,control.id),nullptr,x,y,width,height,
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW);
}
groupDialogButtons(dialog,{IDOK,IDCANCEL,optionsApply},true);
if(draft.page==PanelColors && draft.section==fileStyleSection) layoutFileStyleFields(dialog,false);
layoutOptionsPreview(dialog);
// Paint the final layout together, including the areas vacated by moved controls.
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW);
}
void refreshTextColor(HWND dialog,const ks::files::TextPreferences &profile)
{
const auto index=SendDlgItemMessageW(dialog,textColor,CB_GETCURSEL,0,0);
if(index<0 || static_cast<size_t>(index)>=profile.colors.size()) return;
const auto color=profile.colors[index];
wchar_t hex[8]{};
swprintf_s(hex,L"#%02X%02X%02X",unsigned(GetRValue(color)),unsigned(GetGValue(color)),unsigned(GetBValue(color)));
SetDlgItemTextW(dialog,textColorValue,hex);
}
bool sameSchemeName(const std::wstring &left,const wchar_t *right)
{
return CompareStringOrdinal(left.c_str(),-1,right,-1,TRUE)==CSTR_EQUAL;
}
void populateTextSchemes(HWND dialog,const ks::files::TextSettings &settings)
{
SendDlgItemMessageW(dialog,textTheme,CB_RESETCONTENT,0,0);
const auto add=[&](const wchar_t *name)
{
SendDlgItemMessageW(dialog,textTheme,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
};
add(L"Custom");
for(const auto name:ks::files::textPaletteNames) add(name);
for(const auto &scheme:settings.schemes) add(scheme.name.c_str());
}
size_t currentTextScheme(const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
{
for(size_t index=0;index<std::size(ks::files::textPalettes);++index)
if(profile.scheme==ks::files::textPaletteNames[index] && profile.colors==ks::files::textPalettes[index])
return index+1;
for(size_t index=0;index<settings.schemes.size();++index)
{
const auto &scheme=settings.schemes[index];
if(profile.scheme==scheme.name && profile.colors==scheme.colors)
return std::size(ks::files::textPalettes)+index+1;
}
return 0;
}
INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
SendDlgItemMessageW(dialog,100,EM_SETLIMITTEXT,ks::files::maxTextPaletteName,0);
groupDialogButtons(dialog,{IDOK,IDCANCEL},true);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(LOWORD(wp)==IDCANCEL) { FilesModalDialog::finish(dialog,IDCANCEL); return TRUE; }
if(LOWORD(wp)!=IDOK) return FALSE;
wchar_t text[ks::files::maxTextPaletteName+1]{};
GetDlgItemTextW(dialog,100,text,static_cast<int>(std::size(text)));
std::wstring name=text;
const auto first=name.find_first_not_of(L" \t");
if(first==name.npos) { MessageBeep(MB_ICONWARNING); return TRUE; }
*reinterpret_cast<std::wstring *>(GetWindowLongPtrW(dialog,DWLP_USER))=
name.substr(first,name.find_last_not_of(L" \t")-first+1);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files::TextPreferences &profile)
{
std::wstring name;
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog,
reinterpret_cast<LPARAM>(&name))!=IDOK) return;
if(sameSchemeName(name,L"Custom") || std::any_of(std::begin(ks::files::textPaletteNames),
std::end(ks::files::textPaletteNames),[&](const wchar_t *preset){return sameSchemeName(name,preset);}))
{
showFilesNotice(dialog,L"Choose a different name for your color scheme.",L"Save color scheme");
return;
}
const auto existing=std::find_if(settings.schemes.begin(),settings.schemes.end(),
[&](const auto &scheme){return sameSchemeName(name,scheme.name.c_str());});
if(existing!=settings.schemes.end())
{
if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",
{.confirm=true,.tone=FilesNoticeTone::neutral})!=IDYES) return;
existing->colors=profile.colors;
profile.scheme=existing->name;
}
else
{
if(settings.schemes.size()>=ks::files::maxTextPalettes)
{
showFilesNotice(dialog,L"The color scheme list is full.",L"Save color scheme");
return;
}
settings.schemes.push_back({name,profile.colors});
profile.scheme=std::move(name);
}
populateTextSchemes(dialog,settings);
}
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
{
for(const auto &check:textChecks) CheckDlgButton(dialog,check.id,profile.*check.value?BST_CHECKED:BST_UNCHECKED);
SendDlgItemMessageW(dialog,textTabWidth,CB_SETCURSEL,profile.tabWidth-1,0);
SendDlgItemMessageW(dialog,textLineEnding,CB_SETCURSEL,profile.lineEnding,0);
SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,currentTextScheme(settings,profile),0);
refreshTextColor(dialog,profile);
}
void showMarkdownOptions(HWND dialog,const ks::files::MarkdownPreferences &settings)
{
// SetDlgItemText sends EN_CHANGE synchronously, so take a snapshot first.
const auto values=settings;
SetDlgItemInt(dialog,markdownWidth,values.width,FALSE);
SetDlgItemInt(dialog,markdownSize,values.fontSize,FALSE);
SetDlgItemTextW(dialog,markdownFamily,values.font.c_str());
}
int readMarkdownOptions(HWND dialog,ks::files::MarkdownPreferences &settings)
{
BOOL widthValid{}, sizeValid{};
const auto width=GetDlgItemInt(dialog,markdownWidth,&widthValid,FALSE);
const auto size=GetDlgItemInt(dialog,markdownSize,&sizeValid,FALSE);
if(!widthValid || width>999999) return markdownWidth;
if(!sizeValid || size<8 || size>72) return markdownSize;
wchar_t font[LF_FACESIZE]{};
GetDlgItemTextW(dialog,markdownFamily,font,std::size(font));
settings={width,size,font};
return 0;
}
bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
{
if(!textOptionsPage(draft.page) || (draft.page==TextViewer && draft.section==markdownSection)) return false;
auto &profile=draft.text.profiles[draft.page==TextEditor];
const auto id=LOWORD(command);
const auto row=[&](int control){return SendDlgItemMessageW(dialog,control,CB_GETCURSEL,0,0);};
if(const auto check=std::find_if(std::begin(textChecks),std::end(textChecks),
[id](const auto &entry){return entry.id==id;});check!=std::end(textChecks))
profile.*check->value=IsDlgButtonChecked(dialog,id)==BST_CHECKED;
else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,profile);
else if(id==textChangeColor)
{
const auto index=row(textColor);
if(index>=0 && static_cast<size_t>(index)<profile.colors.size())
choosePanelColor(dialog,profile.colors[index],draft.custom.data());
}
else if(HIWORD(command)==CBN_SELCHANGE)
{
const auto selected=row(id);
if(selected<0) return false;
switch(id)
{
case textColor: break;
case textTabWidth: profile.tabWidth=static_cast<int>(selected)+1; break;
case textLineEnding: profile.lineEnding=static_cast<int>(selected); break;
case textTheme:
if(selected==0) profile.scheme.clear();
else if(const auto scheme=static_cast<size_t>(selected-1);scheme<std::size(ks::files::textPalettes))
{
profile.scheme=ks::files::textPaletteNames[scheme];
profile.colors=ks::files::textPalettes[scheme];
}
else
{
const auto index=scheme-std::size(ks::files::textPalettes);
if(index>=draft.text.schemes.size()) return false;
profile.scheme=draft.text.schemes[index].name;
profile.colors=draft.text.schemes[index].colors;
}
break;
default: return false;
}
}
else return false;
showTextOptions(dialog,draft.text,profile);
updateOptionsApply(dialog,draft);
return true;
}
void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
{
draft.page=page;
draft.section=section;
const bool markdown=page==TextViewer && section==markdownSection;
const wchar_t *title=L"No matching settings";
if(page==allOptions) title=L"All settings";
else if(page>=0)
{
title=optionsTitles[page];
if(section>=0)
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?(section==fileStyleSection?L"File type styles":colorNames[section]):L"Font";
if(markdown) title=L"Markdown";
else if(section>=0 && !textOptionsPage(page))
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
(section==fileStyleSection?L"File type styles":colorNames[section]):
page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font";
}
SetDlgItemTextW(dialog,optionsTitle,title);
const auto show=[&](auto &controls,bool visible)
@@ -192,11 +450,24 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
show(panelLayoutControls,page==PanelModes && section==PanelLayout);
show(wideColumnControls,page==PanelModes && section==WideColumns);
show(statusColumnControls,page==PanelModes && section==StatusColumns);
show(appearanceControls,page==Appearance && section==Font);
show(dialogFrameControls,page==Appearance && section==DialogFrame);
if(page==Appearance && section==DialogFrame)
{
for(const auto &option:frameOptions)
SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0);
}
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
show(commandLineControls,page==CommandLine && section==0);
show(markdownControls,markdown);
show(textControls,textOptionsPage(page) && !markdown);
show(editingControls,page==TextEditor);
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
const bool fileTypes=page==PanelColors && section==fileStyleSection;
constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState};
show(fileStyleControls,fileTypes);
const auto preview=GetDlgItem(dialog,fileStylePreview);
ShowWindow(preview,page>=0 && page<allOptions && section>=0?SW_SHOW:SW_HIDE);
ShowWindow(preview,page>=0 && page<CommandLine && section>=0?SW_SHOW:SW_HIDE);
layoutOptionsPreview(dialog);
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
show(colorOptionControls,page==PanelColors && section>=0 && !fileTypes);
@@ -209,7 +480,6 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
}
updateFileStyleEditor(dialog,draft,true);
}
show(appearanceControls,page==Appearance && section>=0);
if(page==PanelColors && section>=0 && !fileTypes)
{
const auto color=draft.palette[section];
@@ -251,20 +521,26 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
const int previousPage=draft.page,previousSection=draft.section;
TreeView_DeleteAllItems(tree);
draft.wideColumnsNode=nullptr;
draft.markdownNode=nullptr;
const auto root=add(L"All settings",allOptions,-1,TVI_ROOT);
HTREEITEM first{},selected{};
for(int page=PanelModes;page<=Appearance;++page)
for(int page=PanelModes;page<allOptions;++page)
{
HTREEITEM category{};
const bool wholeCategory=matches(optionsTitles[page]) || (!query.empty() && matches(L"All settings"));
const auto addSection=[&](const wchar_t *label,int section,bool aliasMatches=false)
{
if(!wholeCategory && !aliasMatches && !matches(label)) return;
if(!category) category=add(optionsTitles[page],page,-1,root);
if(!category)
{
category=add(optionsTitles[page],page,-1,root);
if(page==previousPage && previousSection<0) selected=category;
}
const auto node=add(label,page,section,category);
if(!first) first=node;
if(page==previousPage && section==previousSection) selected=node;
if(page==PanelModes && section==WideColumns) draft.wideColumnsNode=node;
if(page==TextViewer && section==markdownSection) draft.markdownNode=node;
};
if(page==PanelModes)
{
@@ -283,7 +559,27 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
addSection(L"File type styles",fileStyleSection,extensionMatches || matches(L"System and hidden") ||
matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground"));
}
else addSection(L"Font",0,matches(L"Display font"));
else if(page==CommandLine) addSection(L"Command history",0,
matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here") ||
matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here"));
else if(textOptionsPage(page))
{
const bool propertyMatches=matches(L"Tab width") ||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Customize colors") ||
(page==TextEditor && matches(L"Line endings for new lines")) ||
std::any_of(std::begin(textChecks),std::end(textChecks),[&](const auto &check)
{return (page==TextEditor || check.id<354) && matches(check.name);}) ||
std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches);
addSection(page==TextEditor?L"Editing and appearance":L"Viewing and appearance",0,propertyMatches);
if(page==TextViewer) addSection(L"Markdown",markdownSection,
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size"));
}
else
{
addSection(L"Font",Font,matches(L"Display font"));
addSection(L"Dialog frame",DialogFrame,
matches(L"Outer padding") || matches(L"Inner padding") || matches(L"Row text padding"));
}
if(category) TreeView_Expand(tree,category,TVE_EXPAND);
}
TreeView_Expand(tree,root,TVE_EXPAND);
@@ -311,13 +607,33 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
SendDlgItemMessageW(dialog,201,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,markdownWidth,EM_SETLIMITTEXT,6,0);
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
showMarkdownOptions(dialog,draft.text.markdown);
SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0);
for(const auto &option:frameOptions)
for(DWORD value=0;value<=option.maximum;++value)
SendDlgItemMessageW(dialog,option.id,CB_ADDSTRING,0,
reinterpret_cast<LPARAM>(std::to_wstring(value).c_str()));
for(int width=1;width<=16;++width)
SendDlgItemMessageW(dialog,textTabWidth,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(std::to_wstring(width).c_str()));
for(const auto label:{L"Automatic",L"Windows (CRLF)",L"Unix (LF)",L"Classic Mac (CR)"})
SendDlgItemMessageW(dialog,textLineEnding,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
populateTextSchemes(dialog,draft.text);
for(const auto label:ks::files::textColorNames)
SendDlgItemMessageW(dialog,textColor,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
SendDlgItemMessageW(dialog,textColor,CB_SETCURSEL,0,0);
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,273,panels[0].wide);
CheckDlgButton(dialog,274,panels[1].wide);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
filterOptions(dialog,draft);
updateOptionsApply(dialog,draft);
return TRUE;
@@ -352,15 +668,21 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
const auto &change=*reinterpret_cast<const NMTREEVIEWW*>(lp);
if(change.hdr.code==TVN_SELCHANGEDW && change.itemNew.hItem)
showOptionsPage(dialog,*draft,static_cast<int>(change.itemNew.lParam>>8),static_cast<int>(change.itemNew.lParam&255)-1);
{
const auto page=static_cast<int>(change.itemNew.lParam>>8);
if(page!=allOptions || !GetWindowTextLengthW(GetDlgItem(dialog,optionsSearch)))
draft->location=static_cast<DWORD>(change.itemNew.lParam);
showOptionsPage(dialog,*draft,page,static_cast<int>(change.itemNew.lParam&255)-1);
}
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
EndDialog(dialog,IDCANCEL);
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(changeTextOption(dialog,*draft,wp)) return TRUE;
switch(LOWORD(wp))
{
case optionsSearch:
@@ -376,9 +698,40 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
case 282:
chooseDisplayFont(dialog,draft->font,draft->points);
showOptionsPage(dialog,*draft,Appearance,0);
showOptionsPage(dialog,*draft,Appearance,Font);
updateOptionsApply(dialog,*draft);
return TRUE;
case markdownWidth: case markdownSize: case markdownFamily:
if(HIWORD(wp)==EN_CHANGE)
{
draft->markdownError=readMarkdownOptions(dialog,draft->text.markdown);
updateOptionsApply(dialog,*draft);
}
return TRUE;
case markdownChoose:
{
LOGFONTW font{};
const auto &settings=draft->text.markdown;
wcsncpy_s(font.lfFaceName,settings.font.empty()?L"Segoe UI":settings.font.c_str(),_TRUNCATE);
auto size=static_cast<int>(settings.fontSize)*10;
font.lfHeight=-MulDiv(size,GetDpiForWindow(dialog),720);
if(chooseDisplayFont(dialog,font,size,72))
{
SetDlgItemTextW(dialog,markdownFamily,font.lfFaceName);
SetDlgItemInt(dialog,markdownSize,(size+5)/10,FALSE);
}
return TRUE;
}
case outerFramePadding: case innerFramePadding: case rowTextPadding:
if(HIWORD(wp)==CBN_SELCHANGE)
{
const auto value=SendMessageW(reinterpret_cast<HWND>(lp),CB_GETCURSEL,0,0);
if(value>=0)
for(const auto &option:frameOptions)
if(option.id==LOWORD(wp)) draft->framePadding.*option.value=static_cast<DWORD>(value);
updateOptionsApply(dialog,*draft);
}
return TRUE;
case fileStyleState:
if(HIWORD(wp)==CBN_SELCHANGE) updateFileStyleEditor(dialog,*draft,false);
return TRUE;
@@ -420,6 +773,13 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
return TRUE;
case optionsReset:
if(draft->page==allOptions || draft->page==CommandLine)
{
setOptionHistoryKeys(dialog,defaultHistoryKeys);
CheckDlgButton(dialog,optionsRemoteTerminal,BST_UNCHECKED);
CheckDlgButton(dialog,optionsRemoteHibernate,BST_UNCHECKED);
CheckDlgButton(dialog,optionsRemoteUpdate,BST_UNCHECKED);
}
if(draft->page==allOptions || draft->page==PanelModes)
for(const auto &property:panelProperties)
if(draft->section<0 || property.section==draft->section) resetPanelProperty(dialog,property);
@@ -430,11 +790,19 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(draft->page==allOptions || (draft->page==PanelColors &&
(draft->section<0 || draft->section==fileStyleSection)))
draft->styles=defaultFileStyles;
if(draft->page==allOptions || draft->page==Appearance)
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=DialogFrame))
{
draft->font=defaultFilesFont();
draft->points=defaultFontPoints;
}
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font))
draft->framePadding=defaultDialogFramePadding;
if(draft->page==allOptions || textOptionsPage(draft->page))
for(int page=TextViewer;page<=TextEditor;++page)
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
draft->text.profiles[page==TextEditor]=ks::files::TextPreferences{};
if(draft->page==allOptions || (draft->page==TextViewer && (draft->section<0 || draft->section==markdownSection)))
showMarkdownOptions(dialog,ks::files::MarkdownPreferences{});
showOptionsPage(dialog,*draft,draft->page,draft->section);
updateOptionsApply(dialog,*draft);
return TRUE;
@@ -452,72 +820,183 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
case 201:
case 202: case 203: case 204: case 205: case 206: case 207: case 208:
case 273: case 274:
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
updateOptionsApply(dialog,*draft);
return TRUE;
case 321: case 323:
updateOptionsApply(dialog,*draft);
return TRUE;
case optionsApply:
case IDOK:
{
if(draft->markdownError)
{
if(!draft->markdownNode) SetDlgItemTextW(dialog,optionsSearch,L"");
TreeView_SelectItem(GetDlgItem(dialog,optionsTree),draft->markdownNode);
showFilesNotice(dialog,L"Enter a width in pixels (0 for full window) and a font size from 8 to 72 pt.",L"Markdown");
SetFocus(GetDlgItem(dialog,draft->markdownError));
return TRUE;
}
BOOL valid{};
const auto width=GetDlgItemInt(dialog,201,&valid,FALSE);
if(!valid || width<6 || width>16)
{
SetDlgItemTextW(dialog,optionsSearch,L"");
TreeView_SelectItem(GetDlgItem(dialog,optionsTree),draft->wideColumnsNode);
MessageBoxW(dialog,L"Enter a width from 6 to 16 characters.",optionsTitles[PanelModes],MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Enter a width from 6 to 16 characters.",optionsTitles[PanelModes]);
SetFocus(GetDlgItem(dialog,201));
SendDlgItemMessageW(dialog,201,EM_SETSEL,0,-1);
return TRUE;
}
const auto owner=GetWindow(dialog,GW_OWNER);
const bool stylesChanged=draft->styles!=fileStyles;
const auto owner=draft->filesWindow;
const OptionsWriteLock writeLock;
if(!writeLock.acquired())
{
setStatus(L"Another window is saving Files settings. Try Apply again.");
return TRUE;
}
const auto &base=draft->baseline;
const bool textChanged=draft->text!=base.text;
auto textSettings=ks::files::loadTextPreferences();
if(draft->text.markdown!=base.text.markdown)
{
if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown)
{
showFilesNotice(dialog,L"Markdown settings changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options");
return TRUE;
}
textSettings.markdown=draft->text.markdown;
}
for(size_t i=0;i<textSettings.profiles.size();++i)
{
if(draft->text.profiles[i]==base.text.profiles[i]) continue;
if(textSettings.profiles[i]!=base.text.profiles[i] && textSettings.profiles[i]!=draft->text.profiles[i])
{
showFilesNotice(dialog,L"Text settings changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options");
return TRUE;
}
textSettings.profiles[i]=draft->text.profiles[i];
}
if(draft->text.schemes!=base.text.schemes)
{
if(textSettings.schemes!=base.text.schemes && textSettings.schemes!=draft->text.schemes)
{
showFilesNotice(dialog,L"Color schemes changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options");
return TRUE;
}
textSettings.schemes=draft->text.schemes;
}
auto keys=optionHistoryKeys(dialog);
loadCommandHistoryKeys();
for(size_t i=0;i<keys.size();++i)
if(keys[i]==base.keys[i]) keys[i]=commandHistoryKeys[i];
if(!validHistoryKeys(keys))
{
showFilesNotice(dialog,L"Choose distinct shortcuts using Ctrl or Alt that are free in Files.",L"Command history");
return TRUE;
}
const bool stylesChanged=draft->styles!=base.styles;
loadFileStyles();
if(stylesChanged && fileStyles!=base.styles && fileStyles!=draft->styles)
{
showFilesNotice(dialog,L"File type styles changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options");
return TRUE;
}
if(stylesChanged && !saveFileStyles(draft->styles))
{
MessageBoxW(dialog,L"Could not save the file type styles.",L"KSwitcher Files Options",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Could not save the file type styles.",L"KSwitcher Files Options");
return TRUE;
}
const bool fontChanged=optionsFontChanged(*draft);
if(fontChanged && !applyFont(owner,draft->font,draft->points))
{
if(stylesChanged) saveFileStyles(fileStyles);
MessageBoxW(dialog,L"Could not apply the selected font.",optionsTitles[Appearance],MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Could not apply the selected font.",optionsTitles[Appearance]);
return TRUE;
}
if(stylesChanged) fileStyles=draft->styles;
sizeWidth=static_cast<int>(width);
alignExtensions=IsDlgButtonChecked(dialog,202)==BST_CHECKED;
showDetails=IsDlgButtonChecked(dialog,203)==BST_CHECKED;
alignFolders=IsDlgButtonChecked(dialog,204)==BST_CHECKED;
statusFields=0;
for(int i=0;i<4;++i)
if(IsDlgButtonChecked(dialog,205+i)==BST_CHECKED) statusFields|=1u<<i;
savePreference(L"SizeWidth",sizeWidth);
savePreference(L"AlignExtensions",alignExtensions);
savePreference(L"ShowDetails",showDetails);
savePreference(L"AlignFolders",alignFolders);
savePreference(L"StatusFields",statusFields);
for(int i=0;i<ColorCount;++i)
if(colors[i]!=draft->palette[i])
if(textChanged)
{
try { ks::files::saveTextPreferences(textSettings); }
catch(const std::exception &error)
{
colors[i]=draft->palette[i];
savePreference(std::to_wstring(i).c_str(),colors[i]);
if(fontChanged) applyFont(owner,base.font,base.points);
if(stylesChanged) saveFileStyles(fileStyles);
const auto message=L"Could not save text settings. "+ks::wide(error.what());
showFilesNotice(dialog,message.c_str(),L"KSwitcher Files Options");
return TRUE;
}
refreshColors();
}
const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial)
{
if(value!=initial) savePreference(name,value);
};
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
const auto inputKeys=optionHistoryKeys(dialog);
saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]);
saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]);
saveChanged(ks::lan::remoteTerminalPreference,checked(optionsRemoteTerminal),base.remoteTerminal);
saveChanged(ks::lan::remoteHibernatePreference,checked(optionsRemoteHibernate),base.remoteHibernate);
saveChanged(ks::lan::remoteUpdatePreference,checked(optionsRemoteUpdate),base.remoteUpdate);
saveChanged(L"SizeWidth",width,base.width);
saveChanged(L"AlignExtensions",checked(202),base.extensions);
saveChanged(L"AlignFolders",checked(204),base.folders);
saveChanged(L"ShowDetails",checked(203),base.details);
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
const auto initialFields=fields;
for(int i=0;i<4;++i)
{
const DWORD bit=1u<<i;
if(checked(205+i)!=((base.fields&bit)!=0)) fields=checked(205+i)?fields|bit:fields&~bit;
}
saveChanged(L"StatusFields",fields,initialFields);
for(int i=0;i<ColorCount;++i)
saveChanged(std::to_wstring(i).c_str(),draft->palette[i],base.palette[i]);
saveChanged(dialogFrameOuterKey,draft->framePadding.outer,base.padding.outer);
saveChanged(dialogFrameInnerKey,draft->framePadding.inner,base.padding.inner);
saveChanged(dialogRowTextKey,draft->framePadding.rowText,base.padding.rowText);
if(fontChanged)
{
savePreference(L"FontPoints",fontPoints);
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",REG_BINARY,&displayFont,sizeof(displayFont));
draft->font=displayFont;
}
for(int i=0;i<2;++i)
{
const bool wide=IsDlgButtonChecked(dialog,273+i)==BST_CHECKED;
if(panels[i].wide!=wide) setMode(i,wide);
}
saveChanged(L"LeftWide",checked(273),base.wide[0]);
saveChanged(L"RightWide",checked(274),base.wide[1]);
loadFilesPreferences(owner);
notifyFilesPreferences(owner);
const auto dialogOwner=GetWindow(dialog,GW_OWNER);
if(dialogOwner!=owner)
SendMessageW(dialogOwner,filesPreferencesChanged,reinterpret_cast<WPARAM>(owner),0);
draft->baseline=OptionsBaseline{};
draft->text=draft->baseline.text;
showMarkdownOptions(dialog,draft->text.markdown);
populateTextSchemes(dialog,draft->text);
draft->font=displayFont;
draft->points=fontPoints;
draft->styles=fileStyles;
draft->palette=colors;
draft->framePadding=dialogFramePadding;
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,273,panels[0].wide);
CheckDlgButton(dialog,274,panels[1].wide);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
if(draft->page==PanelColors && draft->section==fileStyleSection)
updateFileStyleEditor(dialog,*draft,true);
showOptionsPage(dialog,*draft,draft->page,draft->section);
layout(owner);
showFileDetails(panels[active]);
RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW);
if(LOWORD(wp)==IDOK) EndDialog(dialog,IDOK);
if(LOWORD(wp)==IDOK) FilesModalDialog::finish(dialog,IDOK);
else updateOptionsApply(dialog,*draft);
return TRUE;
}
@@ -525,13 +1004,29 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return FALSE;
}
void runOptions(HWND owner,int page)
{
OptionsDraft draft;
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
const DWORD initial=static_cast<DWORD>((page<<8)|1);
const auto saved=preference(optionsLocationKey,initial);
draft.location=(saved>>8)<=allOptions?saved:initial;
draft.page=static_cast<int>(draft.location>>8);
draft.section=static_cast<int>(draft.location&255)-1;
std::copy(std::begin(colors),std::end(colors),draft.palette.begin());
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog,
reinterpret_cast<LPARAM>(&draft));
if(result==-1) setStatus(L"Could not open Files Options.");
else savePreference(optionsLocationKey,draft.location);
}
void editOptions(HWND owner)
{
const auto panel=panels[active].list;
OptionsDraft draft;
std::copy(std::begin(colors),std::end(colors),draft.palette.begin());
const auto result=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog,
reinterpret_cast<LPARAM>(&draft));
SetFocus(panel);
if(result==-1) setStatus(L"Could not open Files Options.");
runOptions(owner,PanelModes);
SetFocus(panels[active].list);
}
void editTextOptions(HWND owner,bool edit)
{
runOptions(owner,edit?TextEditor:TextViewer);
}
+31 -1
View File
@@ -80,7 +80,25 @@ void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDra
entry(L"examples",L"old",true,false);
};
if(draft.page==PanelColors && (draft.section==Dialog || draft.section==Selection))
if(draft.page==Appearance && draft.section==DialogFrame)
{
InflateRect(&bounds,-px(8),-px(8));
const auto framePadding=dialogFrameMetrics(dpi,draft.framePadding);
const auto surface=CreateSolidBrush(palette[Dialog]);
const auto ink=CreateSolidBrush(palette[Text]);
const auto frame=paintDialogFrame(dc,bounds,framePadding,surface,ink);
const auto titleFont=previewFont?previewFont:mono;
paintDialogFrameCaptions(dc,bounds,frame,L"Folder shortcuts",surface,palette[Text],titleFont);
DeleteObject(ink);
DeleteObject(surface);
auto content=bounds;
InflateRect(&content,-framePadding.content(),-dialogListInset(framePadding,metrics.tmHeight));
content.bottom=std::min(content.bottom,content.top+rowHeight);
if(content.bottom>content.top)
paintDialogListRow(dc,content,LR"(C:\Projects\Example\Documents\Archive)",titleFont,
palette[Text],palette[Selection],dialogRowTextInset(metrics.tmAveCharWidth,draft.framePadding));
}
else if(draft.page==PanelColors && (draft.section==Dialog || draft.section==Selection))
{
InflateRect(&bounds,-px(12),-px(10));
const auto maxWidth=px(340);
@@ -134,6 +152,18 @@ void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDra
else panel(bounds,draft.page==PanelModes || checked(273),
draft.page==PanelColors && draft.section==PanelCursor,L"C:\\Example");
if(draft.page==PanelColors && (draft.section==Text || draft.section==Dialog))
{
auto field=item.rcItem;
InflateRect(&field,-px(12),-px(10));
field.right=std::min(field.right,field.left+px(340));
field.top+=px(5)+4*rowHeight;
field.bottom=field.top+rowHeight+px(6);
fill(field,RGB(192,192,192));
InflateRect(&field,-px(4),-px(3));
row(field,L"C:\\Example",palette[Text],palette[Dialog]);
}
RestoreDC(dc,saved);
if(previewFont) DeleteObject(previewFont);
}
+2 -2
View File
@@ -127,7 +127,7 @@ bool addFileStyle(HWND dialog,OptionsDraft &draft)
const auto extension=fileStyleExtension(input);
if(extension.empty())
{
MessageBoxW(dialog,L"Enter a file extension such as .txt.",L"File type styles",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Enter a file extension such as .txt.",L"File type styles");
SetFocus(GetDlgItem(dialog,fileStyleSuggestion));
return false;
}
@@ -138,7 +138,7 @@ bool addFileStyle(HWND dialog,OptionsDraft &draft)
{
if(draft.styles.size()>=64)
{
MessageBoxW(dialog,L"The profile can contain up to 64 file type rules.",L"File type styles",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"The profile can contain up to 64 file type rules.",L"File type styles");
return false;
}
draft.styles.push_back({extension});
+1 -1
View File
@@ -15,7 +15,7 @@ struct FileStyle
const std::vector<FileStyle> defaultFileStyles{
{L"@system-hidden"},{L".exe",RGB(85,255,85)},{L".md",RGB(231,192,247)},
{L".7z",RGB(255,210,128)},{L".zip",RGB(255,210,128)},{L".rar",RGB(255,210,128)},
{L".7z",RGB(255,210,128)},{L".zip",RGB(255,155,170)},{L".rar",RGB(255,210,128)},
{L".tar",RGB(255,210,128)},{L".gz",RGB(255,210,128)},
{L".png",RGB(165,230,255)},{L".jpg",RGB(165,230,255)},{L".jpeg",RGB(165,230,255)},
{L".gif",RGB(165,230,255)},{L".webp",RGB(165,230,255)},{L".svg",RGB(165,230,255)},
+1 -1
View File
@@ -49,7 +49,7 @@ public:
startup.StartupInfo.cb=sizeof(startup);
startup.lpAttributeList=attributes;
PROCESS_INFORMATION info{};
wchar_t command[]=L"powershell.exe -NoLogo -NoProfile -NoExit -Command \"Remove-Module PSReadLine -ErrorAction SilentlyContinue; function global:prompt { ([string][char]27) + '[?25l' }; Clear-Host\"";
wchar_t command[]=L"powershell.exe -NoLogo -NoProfile -NoExit -Command \"Remove-Module PSReadLine -ErrorAction SilentlyContinue; function global:prompt { $location = Get-Location; $path = if ($location.Provider.Name -eq 'FileSystem') { [Uri]::EscapeDataString($location.ProviderPath) }; ([string][char]27) + ']633;ks-directory:' + $path + [char]7 + [char]27 + '[?25l' }; Clear-Host\"";
wchar_t system[MAX_PATH]{};
const auto length=GetSystemDirectoryW(system,MAX_PATH);
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
+66 -22
View File
@@ -8,8 +8,10 @@ __CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
__CRT_UUID_DECL(ICoreWebView2NewWindowRequestedEventHandler, 0xd4c185fe, 0xc81c, 0x4989, 0x97, 0xaf, 0x2d, 0x3f, 0xa7, 0xab, 0x56, 0x51)
__CRT_UUID_DECL(ICoreWebView2NavigationStartingEventHandler, 0x9adbe429, 0xf36d, 0x432b, 0x9d, 0xdc, 0xf8, 0x88, 0x1f, 0xbd, 0x76, 0xe3)
__CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa79, 0x41a8, 0x8e, 0x44, 0x65, 0x81, 0x1c, 0x76, 0xdc, 0xb2)
#endif
#include <wrl/client.h>
#include <filesystem>
#include <functional>
#include <memory>
#include <utility>
@@ -50,13 +52,25 @@ class FilesTerminalView
{
Microsoft::WRL::ComPtr<ICoreWebView2Controller> controller;
Microsoft::WRL::ComPtr<ICoreWebView2> web;
HMODULE loader{};
std::shared_ptr<int> lifetime;
RECT bounds{};
bool ready{};
bool visible{};
int viewportHeight{};
public:
~FilesTerminalView() { close(); }
void focus()
{
if(controller) controller->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
}
void post(const std::wstring &message)
{
if(ready) web->PostWebMessageAsString(message.c_str());
}
bool initialized() const { return ready; }
void enableTrace() { if(ready) web->PostWebMessageAsString(L"trace:on"); }
void enableTrace(bool output)
{
if(ready) web->PostWebMessageAsString(output?L"trace:output":L"trace:on");
}
void setFont(const LOGFONTW &font,int points)
{
if(!ready) return;
@@ -67,12 +81,16 @@ public:
}
void layout(HWND host,bool show,int fullHeight)
{
RECT area{};
GetClientRect(host,&area);
area.top=area.bottom-fullHeight;
layout(area,show);
}
void layout(RECT area,bool show)
{
bounds=area;
visible=show;
viewportHeight=fullHeight;
if(!controller) return;
RECT bounds{};
GetClientRect(host,&bounds);
bounds.top=bounds.bottom-viewportHeight;
RECT current{};
if(FAILED(controller->get_Bounds(&current)) || !EqualRect(&current,&bounds))
controller->put_Bounds(bounds);
@@ -82,6 +100,7 @@ public:
}
void close()
{
lifetime.reset();
if(controller) controller->Close();
web.Reset();
controller.Reset();
@@ -100,12 +119,13 @@ public:
}
return SUCCEEDED(web->PostWebMessageAsString(message.c_str()));
}
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed)
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed,
bool markdown=false,std::function<bool(UINT)> handleKey={})
{
wchar_t exe[MAX_PATH]{};
if(!GetModuleFileNameW(nullptr,exe,MAX_PATH)) return false;
const auto folder=std::filesystem::path(exe).parent_path();
loader=LoadLibraryExW((folder/L"WebView2Loader.dll").c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
static const auto loader=LoadLibraryExW((folder/L"WebView2Loader.dll").c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
if(!loader) return false;
using Create=HRESULT (STDAPICALLTYPE*)(PCWSTR,PCWSTR,ICoreWebView2EnvironmentOptions*,
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
@@ -115,23 +135,28 @@ public:
wchar_t local[MAX_PATH]{};
const auto length=GetEnvironmentVariableW(L"LOCALAPPDATA",local,MAX_PATH);
if(!length || length>=MAX_PATH) return false;
const auto profile=std::filesystem::path(local)/L"KSwitcher"/L"TerminalWebView";
const auto profile=std::filesystem::path(local)/L"KSwitcher"/(markdown?L"MarkdownWebView":L"TerminalWebView");
const auto origin=markdown?L"kswitcher-markdown.invalid":L"kswitcher-terminal.invalid";
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
const auto assets=folder/L"terminal";
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
lifetime=std::make_shared<int>(0);
const std::weak_ptr<int> alive=lifetime;
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
HRESULT,ICoreWebView2Environment*>([=,this](HRESULT hr,ICoreWebView2Environment *env)
{
if(!IsWindow(host)) return S_OK;
if(alive.expired()) return S_OK;
if(FAILED(hr) || !env) { failed(); return S_OK; }
auto completed=terminalCallback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler,
HRESULT,ICoreWebView2Controller*>([=,this](HRESULT result,ICoreWebView2Controller *view)
{
if(!IsWindow(host)) return S_OK;
if(alive.expired()) return S_OK;
if(FAILED(result) || !view) { failed(); return S_OK; }
controller=view;
view->get_CoreWebView2(&web);
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
L"kswitcher-terminal.invalid",assets.c_str(),COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY)))
origin,assets.c_str(),COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY)))
{ failed(); return S_OK; }
Microsoft::WRL::ComPtr<ICoreWebView2Settings> settings;
if(SUCCEEDED(web->get_Settings(&settings)))
@@ -141,14 +166,32 @@ public:
settings->put_AreHostObjectsAllowed(FALSE);
}
EventRegistrationToken token{};
auto navigation=terminalCallback<ICoreWebView2NavigationStartingEventHandler,
ICoreWebView2*,ICoreWebView2NavigationStartingEventArgs*>([](auto*,auto *args)
if(handleKey)
{
PWSTR uri{};
if(SUCCEEDED(args->get_Uri(&uri)))
auto accelerator=terminalCallback<ICoreWebView2AcceleratorKeyPressedEventHandler,
ICoreWebView2Controller*,ICoreWebView2AcceleratorKeyPressedEventArgs*>(
[alive,handleKey](auto*,auto *args)
{
COREWEBVIEW2_KEY_EVENT_KIND kind{};
UINT key{};
if(!alive.expired() && SUCCEEDED(args->get_KeyEventKind(&kind)) &&
(kind==COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN ||
kind==COREWEBVIEW2_KEY_EVENT_KIND_SYSTEM_KEY_DOWN) &&
SUCCEEDED(args->get_VirtualKey(&key)) && handleKey(key))
args->put_Handled(TRUE);
return S_OK;
});
if(FAILED(view->add_AcceleratorKeyPressed(accelerator.Get(),&token)))
{ failed(); return S_OK; }
}
auto navigation=terminalCallback<ICoreWebView2NavigationStartingEventHandler,
ICoreWebView2*,ICoreWebView2NavigationStartingEventArgs*>([uri](auto*,auto *args)
{
PWSTR address{};
if(SUCCEEDED(args->get_Uri(&address)))
{
args->put_Cancel(wcscmp(uri,L"https://kswitcher-terminal.invalid/index.html")!=0);
CoTaskMemFree(uri);
args->put_Cancel(uri!=address);
CoTaskMemFree(address);
}
return S_OK;
});
@@ -158,9 +201,10 @@ public:
auto messages=terminalCallback<ICoreWebView2WebMessageReceivedEventHandler,
ICoreWebView2*,ICoreWebView2WebMessageReceivedEventArgs*>([=,this](auto*,auto *args)
{
if(alive.expired()) return S_OK;
PWSTR source{}, value{};
if(SUCCEEDED(args->get_Source(&source)) &&
wcscmp(source,L"https://kswitcher-terminal.invalid/index.html")==0 &&
uri==source &&
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
{
if(wcscmp(value,L"ready")==0) ready=true;
@@ -173,9 +217,9 @@ public:
if(FAILED(web->add_NavigationStarting(navigation.Get(),&token)) ||
FAILED(web->add_NewWindowRequested(newWindow.Get(),&token)) ||
FAILED(web->add_WebMessageReceived(messages.Get(),&token)) ||
FAILED(web->Navigate(L"https://kswitcher-terminal.invalid/index.html")))
FAILED(web->Navigate(uri.c_str())))
failed();
layout(host,visible,viewportHeight);
layout(bounds,visible);
return S_OK;
});
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
+339
View File
@@ -0,0 +1,339 @@
#include "files_text_document.h"
#include <objbase.h>
#include <algorithm>
#include <stdexcept>
#include <system_error>
#include <utility>
#include <vector>
namespace ks::files
{
namespace
{
[[noreturn]] void fail(const char *operation)
{
throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), operation);
}
struct File
{
HANDLE handle = INVALID_HANDLE_VALUE;
~File() { if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); }
HANDLE release() { return std::exchange(handle, INVALID_HANDLE_VALUE); }
};
struct PendingSave
{
std::filesystem::path path;
~PendingSave() { if (!path.empty()) DeleteFileW(path.c_str()); }
};
HANDLE openSource(const std::filesystem::path &path, bool editable)
{
const auto sharing = FILE_SHARE_READ | FILE_SHARE_DELETE | (editable ? 0 : FILE_SHARE_WRITE);
const auto result = CreateFileW(path.c_str(), GENERIC_READ, sharing,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (result == INVALID_HANDLE_VALUE) fail("Open file");
return result;
}
uint64_t fileSize(HANDLE file)
{
LARGE_INTEGER size{};
if (!GetFileSizeEx(file, &size)) fail("Read file size");
return size.QuadPart;
}
void seek(HANDLE file, uint64_t offset)
{
LARGE_INTEGER position{};
position.QuadPart = static_cast<LONGLONG>(offset);
if (!SetFilePointerEx(file, position, nullptr, FILE_BEGIN)) fail("Seek");
}
std::string read(HANDLE file, uint64_t offset, size_t length)
{
if (!length) return {};
seek(file, offset);
std::string result(length, '\0');
DWORD count{};
if (!ReadFile(file, result.data(), static_cast<DWORD>(length), &count, nullptr)) fail("Read file");
if (count != length) throw std::runtime_error("The file ended unexpectedly.");
return result;
}
void write(HANDLE file, std::string_view bytes)
{
if (bytes.empty()) return;
DWORD written{};
if (!WriteFile(file, bytes.data(), static_cast<DWORD>(bytes.size()), &written, nullptr))
fail("Write file");
if (written != bytes.size()) throw std::runtime_error("The complete block could not be written.");
}
bool sameFile(HANDLE a, HANDLE b)
{
BY_HANDLE_FILE_INFORMATION first{}, second{};
if (!GetFileInformationByHandle(a, &first) || !GetFileInformationByHandle(b, &second))
fail("Check file identity");
return first.dwVolumeSerialNumber == second.dwVolumeSerialNumber &&
first.nFileIndexHigh == second.nFileIndexHigh && first.nFileIndexLow == second.nFileIndexLow;
}
std::filesystem::path temporaryPath(const std::filesystem::path &directory)
{
GUID id{};
wchar_t name[40]{};
if (FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id, name, 40))
throw std::runtime_error("Cannot create a temporary file name.");
return directory / (std::wstring(L".kswitcher-") + name + L".tmp");
}
std::filesystem::path createTemporary(const std::filesystem::path &directory, File &file, DWORD flags)
{
auto path = temporaryPath(directory);
file.handle = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_NEW, flags, nullptr);
if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file");
return path;
}
}
TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(std::move(path)), editable_(editable)
{
File source{openSource(path_, editable)};
if (editable)
{
std::wstring resolved(32768, L'\0');
const auto length = GetFinalPathNameByHandleW(source.handle, resolved.data(),
static_cast<DWORD>(resolved.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
if (length && length < resolved.size())
{
resolved.resize(length);
path_ = resolved;
}
}
size_ = fileSize(source.handle);
const auto prefix = read(source.handle, 0, static_cast<size_t>(std::min<uint64_t>(3, size_)));
if (prefix.starts_with("\xef\xbb\xbf")) bom_ = 3;
else if (prefix.starts_with("\xff\xfe") || prefix.starts_with("\xfe\xff"))
{
encoding_ = prefix.starts_with("\xff") ? Encoding::utf16le : Encoding::utf16be;
bom_ = 2;
if (size_ % 2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
}
source_ = source.release();
}
TextDocument::~TextDocument()
{
if (source_ != INVALID_HANDLE_VALUE) CloseHandle(source_);
if (spool_ != INVALID_HANDLE_VALUE) CloseHandle(spool_);
}
const wchar_t *TextDocument::encodingName() const
{
switch (encoding_)
{
case Encoding::utf16le: return L"UTF-16 LE";
case Encoding::utf16be: return L"UTF-16 BE";
default: return bom_ ? L"UTF-8 BOM" : L"UTF-8";
}
}
uint64_t TextDocument::pages() const
{
return std::max<uint64_t>(1, (size_ - bom_ + pageBytes - 1) / pageBytes);
}
uint64_t TextDocument::boundary(uint64_t page) const
{
if (!page) return bom_;
if (page >= pages()) return size_;
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
return boundary(page,source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_);
}
uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
{
if (!page) return bom_;
if (page >= pages()) return size_;
const auto offset = bom_ + page * pageBytes;
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
const auto sample = read(source, offset - unit,
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
const auto getUnit = [&](size_t i) -> unsigned {
const auto first = static_cast<unsigned char>(sample[i]);
if (unit == 1) return first;
const auto second = static_cast<unsigned char>(sample[i + 1]);
return encoding_ == Encoding::utf16le ? first | (second << 8) : (first << 8) | second;
};
if (getUnit(0) == '\n') return offset;
for (size_t i = unit; i + unit < sample.size(); i += unit)
if (getUnit(i) == '\n') return offset + i;
size_t i = unit;
if (unit == 1)
{
// Advance past at most one UTF-8 code point, even on malformed input.
while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i;
}
else if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit;
return offset + i - unit;
}
std::string TextDocument::decode(std::string bytes) const
{
if (encoding_ == Encoding::utf8 || bytes.empty()) return bytes;
std::wstring units;
units.resize(bytes.size() / 2);
for (size_t i = 0; i < units.size(); ++i)
{
const auto a = static_cast<unsigned char>(bytes[2 * i]);
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
units[i] = static_cast<wchar_t>(encoding_ == Encoding::utf16le ? a | (b << 8) : (a << 8) | b);
}
const auto length = static_cast<int>(units.size());
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
if (!required) fail("Decode UTF-16");
std::string result(required, '\0');
if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, result.data(), required, nullptr, nullptr))
fail("Decode UTF-16");
return result;
}
std::string TextDocument::encode(std::string_view utf8) const
{
if (encoding_ == Encoding::utf8 || utf8.empty()) return std::string(utf8);
const auto length = static_cast<int>(utf8.size());
const int required = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, nullptr, 0);
if (!required) fail("Encode UTF-16");
std::wstring units(required, L'\0');
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, units.data(), required))
fail("Encode UTF-16");
std::string bytes(units.size() * 2, '\0');
const int low = encoding_ == Encoding::utf16le ? 0 : 1;
for (size_t i = 0; i < units.size(); ++i)
{
bytes[2 * i + low] = static_cast<char>(units[i] & 0xff);
bytes[2 * i + 1 - low] = static_cast<char>(units[i] >> 8);
}
return bytes;
}
std::string TextDocument::readPage(uint64_t page) const
{
if (const auto it = changes_.find(page); it != changes_.end())
return read(spool_, it->second.offset, it->second.size);
return readOriginal(page);
}
std::string TextDocument::readOriginal(uint64_t page) const
{
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
const auto start = boundary(page,source);
return decode(read(source, start, static_cast<size_t>(boundary(page + 1,source) - start)));
}
void TextDocument::releaseReadHandle()
{
if(!editable_ && source_!=INVALID_HANDLE_VALUE)
CloseHandle(std::exchange(source_,INVALID_HANDLE_VALUE));
}
bool TextDocument::modifiedWith(uint64_t page, std::string_view current) const
{
const size_t changesOnPage = changes_.contains(page) ? 1 : 0;
return changes_.size() > changesOnPage || current != readOriginal(page);
}
void TextDocument::stage(uint64_t page, std::string_view utf8)
{
if (!editable_) throw std::logic_error("The file is open for viewing.");
if (utf8.size() > editLimit) throw std::runtime_error("The edit exceeds 8 MiB on this page.");
if (utf8 == readOriginal(page))
{
changes_.erase(page);
return;
}
if (spool_ == INVALID_HANDLE_VALUE)
{
wchar_t directory[32768]{};
const auto length = GetTempPathW(static_cast<DWORD>(std::size(directory)), directory);
if (!length || length >= std::size(directory)) fail("Locate temporary directory");
File file;
createTemporary(directory, file, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE);
spool_ = file.release();
}
seek(spool_, spoolSize_);
write(spool_, utf8);
changes_.insert_or_assign(page, Change{spoolSize_, utf8.size()});
spoolSize_ += utf8.size();
}
bool TextDocument::save()
{
if (!modified()) return true;
PendingSave pending;
File output;
pending.path = createTemporary(path_.parent_path(), output, FILE_ATTRIBUTE_NORMAL);
uint64_t written{};
const auto append = [&](std::string_view bytes) {
write(output.handle, bytes);
written += bytes.size();
};
const auto copyUntil = [&](uint64_t &offset, uint64_t end) {
while (offset < end)
{
const auto block = read(source_, offset, static_cast<size_t>(std::min(pageBytes, end - offset)));
append(block);
offset += block.size();
}
};
uint64_t offset{};
for (const auto &[page, change] : changes_)
{
copyUntil(offset, boundary(page));
append(encode(read(spool_, change.offset, change.size)));
offset = boundary(page + 1);
}
copyUntil(offset, size_);
if (!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
// A metadata-only handle survives the rename without blocking ReplaceFile's exclusive open.
File replacement{CreateFileW(pending.path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)};
if (replacement.handle == INVALID_HANDLE_VALUE) fail("Track replacement file");
File current{openSource(path_, true)};
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
const auto backup = temporaryPath(path_.parent_path());
if (!ReplaceFileW(path_.c_str(), pending.path.c_str(), backup.c_str(), 0, nullptr, nullptr))
{
const auto error = GetLastError();
if (GetFileAttributesW(backup.c_str()) != INVALID_FILE_ATTRIBUTES &&
!MoveFileExW(backup.c_str(), path_.c_str(), MOVEFILE_WRITE_THROUGH))
{
const auto location = backup.u8string();
throw std::runtime_error("Could not restore the original name after a save error. The original is at " +
std::string(location.begin(), location.end()));
}
SetLastError(error);
fail("Replace original file");
}
pending.path.clear();
const auto newSource = ReOpenFile(replacement.handle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, 0);
DeleteFileW(backup.c_str());
CloseHandle(source_);
source_ = newSource;
size_ = written;
changes_.clear();
if (spool_ != INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_, INVALID_HANDLE_VALUE));
spoolSize_ = 0;
return source_ != INVALID_HANDLE_VALUE;
}
}
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include <windows.h>
#include <cstdint>
#include <filesystem>
#include <map>
#include <string>
#include <string_view>
namespace ks::files
{
class TextDocument
{
public:
static constexpr uint64_t pageBytes = 1024 * 1024;
static constexpr size_t editLimit = 8 * pageBytes;
explicit TextDocument(std::filesystem::path path, bool editable = true);
~TextDocument();
TextDocument(const TextDocument &) = delete;
TextDocument &operator=(const TextDocument &) = delete;
uint64_t pages() const;
uint64_t size() const { return size_; }
uint64_t boundary(uint64_t page) const;
std::string readPage(uint64_t page) const;
void releaseReadHandle();
void stage(uint64_t page, std::string_view utf8);
bool modified() const { return !changes_.empty(); }
bool modifiedWith(uint64_t page, std::string_view current) const;
bool save();
const wchar_t *encodingName() const;
private:
enum class Encoding { utf8, utf16le, utf16be };
struct Change { uint64_t offset; size_t size; };
std::filesystem::path path_;
HANDLE source_ = INVALID_HANDLE_VALUE;
HANDLE spool_ = INVALID_HANDLE_VALUE;
uint64_t size_{}, spoolSize_{};
size_t bom_{};
Encoding encoding_ = Encoding::utf8;
bool editable_;
std::map<uint64_t, Change> changes_;
std::string decode(std::string bytes) const;
uint64_t boundary(uint64_t page,HANDLE source) const;
std::string readOriginal(uint64_t page) const;
std::string encode(std::string_view utf8) const;
};
}
+270
View File
@@ -0,0 +1,270 @@
#include "files_text_language.h"
#include "core.h"
#include <Sci_Position.h>
#include <ILexer.h>
#include <Lexilla.h>
#include <Scintilla.h>
#include <SciLexer.h>
#include <algorithm>
#include <cwctype>
namespace ks::files
{
namespace
{
constexpr char cpp[] = "alignas alignof asm auto bool break case catch char char8_t char16_t char32_t class concept const "
"consteval constexpr constinit const_cast continue co_await co_return co_yield decltype default delete do double "
"dynamic_cast else enum explicit export extern false float for friend goto if inline int long mutable namespace "
"new noexcept nullptr operator private protected public register reinterpret_cast requires return short signed "
"sizeof static static_assert static_cast struct switch template this thread_local throw true try typedef typeid "
"typename union unsigned using virtual void volatile wchar_t while import module";
constexpr char csharp[] = "abstract as async await base bool break byte case catch char checked class const continue "
"decimal default delegate do double else enum event explicit extern false file finally fixed float for foreach from "
"get global goto if implicit in init int interface internal is let lock long namespace new not null object operator "
"or out override partial private protected public readonly record ref required return sbyte sealed select set short "
"sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unmanaged unsafe "
"ushort using value var virtual void volatile when where while with yield";
constexpr char javascript[] = "abstract any as async await boolean break case catch class const continue debugger declare "
"default delete do else enum export extends false finally for from function get if implements import in infer "
"instanceof interface keyof let module namespace never new null number object of override private protected public "
"readonly return satisfies set static string super switch symbol this throw true try type typeof undefined unknown "
"using var void while with yield";
constexpr char java[] = "abstract assert boolean break byte case catch char class const continue default do double else "
"enum exports extends final finally float for if implements import instanceof int interface long module native new "
"non-sealed null open opens package permits private protected public record requires return sealed short static super "
"switch synchronized this throw throws transient true try var void volatile while yield false";
constexpr char sql[] = "add alter and any as asc begin between by case check column commit constraint create cross "
"database declare default delete desc distinct drop else end except exists fetch foreign from full function grant "
"group having in index inner insert intersect into is join left like limit merge not null offset on or order outer "
"over partition primary procedure references returning right rollback row select set table then top transaction "
"truncate union unique update using values view when where window with";
constexpr char python[] = "and as assert async await break class continue def del elif else except False finally for from "
"global if import in is lambda match case None nonlocal not or pass raise return True try while with yield";
constexpr char ps[] = "begin break catch class continue data define do dynamicparam else elseif end enum exit filter finally "
"for foreach from function if in param process return switch throw trap try until using var while workflow";
constexpr char shell[] = "alias bg break case cd continue declare do done echo elif else esac eval exec exit export "
"false fi for function if in local read readonly return select set shift source test then time trap true type "
"typeset ulimit umask unalias unset until wait while";
constexpr char rust[] = "as async await break const continue crate dyn else enum extern false fn for if impl in let loop "
"match mod move mut pub ref return self Self static struct super trait true type unsafe use where while";
constexpr char go[] = "break case chan const continue default defer else fallthrough for func go goto if import interface "
"map package range return select struct switch type var nil false true";
constexpr char lua[] = "and break do else elseif end false for function goto if in local nil not or repeat return then true until while";
constexpr char ruby[] = "BEGIN END alias and begin break case class def defined do else elsif end ensure false for if in "
"module next nil not or redo rescue retry return self super then true undef unless until when while yield";
constexpr char html[] = "a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption "
"cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer "
"form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark "
"menu meta meter nav noscript object ol optgroup option output p picture pre progress q rp rt ruby s samp script "
"search section select slot small source span strong style sub summary sup table tbody td template textarea tfoot "
"th thead time title tr track u ul var video wbr accept action alt aria-label async cellpadding charset checked cite "
"class content controls defer disabled for height href http-equiv id lang maxlength method multiple name placeholder "
"readonly rel required role rows scope selected src srcset style tabindex target type value width";
struct Mapping
{
std::wstring_view names;
const char *lexer;
const char *keywords = "";
};
constexpr Mapping languages[] = {
{L".c .h .cc .cpp .cxx .hh .hpp .hxx .inl .ipp .ixx .cppm .cu .cuh .m .mm .rc .idl .ino", "cpp", cpp},
{L".cs .csx .razor.cs", "cpp", csharp},
{L".js .jsx .mjs .cjs .ts .tsx .mts .cts .es", "cpp", javascript},
{L".java .pde", "cpp", java},
{L".kt .kts", "cpp", "abstract actual as break by catch class companion const constructor continue data do else enum "
"expect false finally for fun if import in init interface internal is lateinit null object open operator out "
"override package private protected public return sealed super suspend this throw true try typealias val var when while"},
{L".glsl .vert .frag .geom .hlsl .fx .metal", "cpp", cpp},
{L".html .htm .xhtml .shtml .vue .svelte .astro .cshtml .razor .aspx .jsp .php .phtml", "hypertext", html},
{L".xml .xsl .xslt .xsd .svg .resx .xaml .csproj .fsproj .vbproj .vcxproj .props .targets .config .nuspec "
L".wixproj .wxs .plist .rss .atom .gpx .kml .ui .iml .wsdl .manifest .slnx .axaml", "xml"},
{L".css .scss .sass .less", "css", "color background display position width height margin padding border font "
"grid flex content gap box-shadow transform animation opacity overflow text-align align-items justify-content"},
{L".sql .psql .ddl .dml .mysql", "sql", sql},
{L".py .pyw .pyi .rpy sconstruct sconscript", "python", python},
{L".json .jsonc .json5 .ipynb .webmanifest .geojson .topojson .code-workspace .sublime-settings .sublime-project",
"json", "false null true Infinity NaN"},
{L".yaml .yml .eyaml .clang-format .clang-tidy", "yaml", "true false null yes no on off"},
{L".toml pipfile uv.lock cargo.lock poetry.lock", "toml", "true false"},
{L".md .markdown .mdown .mkd .mdx readme", "markdown"},
{L".adoc .asciidoc", "asciidoc"},
{L".ini .cfg .conf .properties .url .inf .reg .editorconfig .gitconfig .gitattributes .gitmodules .npmrc .env", "props"},
{L".sh .bash .zsh .ksh .bats .bashrc .bash_profile .zshrc .profile configure gradlew mvnw", "bash", shell},
{L".ps1 .psm1 .psd1", "powershell", ps},
{L".bat .cmd", "batch", "call cd chdir cls copy del dir echo endlocal exit for goto if md mkdir move path pause popd "
"pushd rd rem ren rename set setlocal shift start title type"},
{L".cmake cmakelists.txt", "cmake", "add_executable add_library add_subdirectory cmake_minimum_required "
"configure_file else elseif endforeach endfunction endif endwhile file find_package foreach function if include "
"install list message option project set string target_compile_definitions target_include_directories "
"target_link_libraries unset while"},
{L".mk .mak makefile gnumakefile", "makefile"},
{L".rs", "rust", rust}, {L".go", "cpp", go}, {L".lua", "lua", lua}, {L".rb .rake .gemspec gemfile rakefile", "ruby", ruby},
{L".dart", "dart", "abstract as assert async await break case class const continue default do else enum extends "
"false final finally for if implements import in interface late mixin new null on override return sealed static "
"super switch this throw true try typedef var void while with yield"},
{L".swift", "cpp", "actor as associatedtype await break case catch class continue default defer deinit do else "
"enum extension false for func guard if import in init let nil private protocol public return self some "
"static struct super switch throw throws true try typealias var where while"},
{L".zig", "zig"}, {L".d .di", "d"}, {L".nim .nims .nimble", "nim"},
{L".fs .fsi .fsx", "fsharp"}, {L".ml .mli", "caml"}, {L".sml .sig", "SML"},
{L".vb .bas .frm .cls", "vb", "as byref byval class const dim each else elseif end enum for function if implements "
"imports inherits interface module new next nothing private property public return select shared sub then try while"},
{L".vbs", "vbscript"}, {L".pl .pm .t", "perl"}, {L".r .rprofile", "r"},
{L".jl", "julia"}, {L".matlab", "matlab"}, {L".oct", "octave"},
{L".tex .sty .ltx", "latex"}, {L".bib", "bib"}, {L".hs", "haskell"}, {L".lhs", "literatehaskell"},
{L".lisp .lsp .cl .el .scm .ss .rkt", "lisp"},
{L".s .asm .nasm .inc", "asm"}, {L".a68k", "a68k"},
{L".v .vh .sv .svh", "verilog"}, {L".vhd .vhdl", "vhdl"},
{L".f .for .f77", "f77"}, {L".f90 .f95 .f03 .f08", "fortran"},
{L".ada .adb .ads", "ada"}, {L".pas .pp .dpr", "pascal"}, {L".cob .cbl .cpy", "COBOL"},
{L".tcl .tk", "tcl"}, {L".coffee .litcoffee", "coffeescript"}, {L".au3", "au3"},
{L".st", "smalltalk"}, {L".erl .hrl", "erlang"},
{L".purs", "haskell"}, {L".diff .patch", "diff"}, {L".po .pot", "po"},
{L".iss", "inno"}, {L".nsi .nsh", "nsis"}, {L".idl3 .odl", "cpp", cpp},
{L".dmap", "DMAP"}, {L".dns .zone", "props"}, {L".ihex .hex", "ihex"}, {L".srec .s19 .s28 .s37", "srec"},
{L".edifact .edi", "edifact"}, {L".x12", "x12"}, {L".g4", "cpp", java},
{L".nix", "nix"}, {L".gd", "gdscript", python}, {L".il", "cil"}, {L".as", "cpp", javascript},
{L".frt .fth", "forth"}, {L".e .eif", "eiffel"}, {L".pov .povray", "pov"},
{L".rebol .reb", "rebol"}, {L".asn .asn1", "asn1"}, {L".asy", "asy"},
{L".raku .rakumod .rakutest .p6 .pm6", "raku"}, {L".bb", "blitzbasic"}, {L".bi", "freebasic"},
{L".t2t", "txt2tags"}, {L".troff .roff .man", "troff"},
{L".clw", "clarion"}, {L".spice .cir", "spice"},
};
bool containsWord(std::wstring_view words, std::wstring_view key)
{
if (key.empty()) return false;
for (size_t start = 0; start < words.size();)
{
const auto end = words.find(L' ', start);
if (words.substr(start, end == words.npos ? end : end - start) == key) return true;
if (end == words.npos) break;
start = end + 1;
}
return false;
}
}
TextLanguage detectLanguage(const std::filesystem::path &path, std::string_view firstPage)
{
auto filename = path.filename().wstring();
auto extension = path.extension().wstring();
for (auto *value : {&filename, &extension})
std::transform(value->begin(), value->end(), value->begin(), [](wchar_t ch) { return std::towlower(ch); });
for (const auto &language : languages)
if (containsWord(language.names, filename) || containsWord(language.names, extension))
return {language.lexer, language.keywords};
if (filename.starts_with(L".env.") || extension == L".env") return {"props"};
if (firstPage.starts_with("<?xml")) return {"xml"};
if (firstPage.starts_with("#!"))
{
const auto line = firstPage.substr(0, firstPage.find_first_of("\r\n"));
for (const auto &[needle, language] : {std::pair{"python", TextLanguage{"python", python}},
{"ruby", {"ruby", ruby}}, {"node", {"cpp", javascript}}, {"perl", {"perl"}},
{"pwsh", {"powershell", ps}}, {"lua", {"lua", lua}}, {"sh", {"bash", shell}}})
if (line.find(needle) != line.npos) return language;
}
return {};
}
std::wstring textLanguageLabel(const TextLanguage &language)
{
if (language.keywords == csharp) return L"C#";
if (language.keywords == javascript) return L"JavaScript / TypeScript";
if (language.keywords == java) return L"Java";
if (language.keywords == go) return L"Go";
if (language.lexer == "cpp") return L"C-family";
if (language.lexer == "hypertext") return L"HTML";
return language.lexer.empty() ? L"Plain text" : wide(language.lexer);
}
Scintilla::ILexer5 *createTextLexer(const TextLanguage &language)
{
if (language.lexer.empty()) return nullptr;
auto *lexer = CreateLexer(language.lexer.c_str());
if (!lexer) return nullptr;
const auto *keywords = language.keywords;
if (!*keywords)
for (const auto &mapping : languages)
if (language.lexer == mapping.lexer && *mapping.keywords)
{
keywords = mapping.keywords;
break;
}
if (*keywords) lexer->WordListSet(0, keywords);
if (language.lexer == "hypertext") lexer->WordListSet(1, javascript);
if (language.lexer == "json") lexer->PropertySet("lexer.json.allow.comments", "1");
if (language.lexer == "cpp" && (language.keywords == javascript || language.keywords == go))
{
lexer->PropertySet("lexer.cpp.backquoted.strings", language.keywords == javascript ? "2" : "1");
if (language.keywords == javascript) lexer->PropertySet("lexer.cpp.regex", "1");
}
if (language.lexer == "cpp" && language.keywords == csharp)
lexer->PropertySet("lexer.cpp.triplequoted.strings", "1");
return lexer;
}
TextColor syntaxColor(Scintilla::ILexer5 &lexer, std::string_view name, int style)
{
if (!style || (style >= STYLE_DEFAULT && style <= STYLE_LASTPREDEFINED)) return TextColor::text;
const auto *styleTags = lexer.TagsOfStyle(style);
const auto *styleName = lexer.NameOfStyle(style);
const std::string_view tags = styleTags ? styleTags : "";
const std::string_view token = styleName ? styleName : "";
const auto has = [&](std::string_view word) {
return tags.find(word) != tags.npos || token.find(word) != token.npos;
};
if (has("comment")) return TextColor::comment;
if (has("string") || has("character") || has("quoted") || has("regex")) return TextColor::string;
if (has("number") || has("numeric")) return TextColor::number;
if (has("keyword") || has("command") || has("tag") || has("heading") || has("header") ||
has("preprocessor") || has("keywordclass")) return TextColor::keyword;
if (has("operator") || has("attribute") || has("property") || has("variable") || has("label"))
return TextColor::symbol;
if (name == "markdown")
{
if (style >= SCE_MARKDOWN_HEADER1 && style <= SCE_MARKDOWN_HEADER6) return TextColor::keyword;
if (style >= SCE_MARKDOWN_CODE && style <= SCE_MARKDOWN_CODEBK) return TextColor::string;
return TextColor::symbol;
}
if (name == "diff")
{
if (style == SCE_DIFF_ADDED) return TextColor::string;
if (style == SCE_DIFF_DELETED) return TextColor::number;
if (style == SCE_DIFF_COMMENT) return TextColor::comment;
return TextColor::keyword;
}
if (name == "sql")
{
if (style >= SCE_SQL_COMMENT && style <= SCE_SQL_COMMENTDOC) return TextColor::comment;
if (style == SCE_SQL_NUMBER) return TextColor::number;
if (style == SCE_SQL_WORD || style == SCE_SQL_WORD2) return TextColor::keyword;
if (style == SCE_SQL_STRING || style == SCE_SQL_CHARACTER) return TextColor::string;
}
if (name == "json")
{
if (style == SCE_JSON_LINECOMMENT || style == SCE_JSON_BLOCKCOMMENT) return TextColor::comment;
if (style == SCE_JSON_STRING || style == SCE_JSON_STRINGEOL) return TextColor::string;
if (style == SCE_JSON_NUMBER) return TextColor::number;
if (style == SCE_JSON_KEYWORD || style == SCE_JSON_LDKEYWORD) return TextColor::keyword;
}
if (name == "css")
{
if (style == SCE_CSS_COMMENT) return TextColor::comment;
if (style == SCE_CSS_DOUBLESTRING || style == SCE_CSS_SINGLESTRING || style == SCE_CSS_VALUE)
return TextColor::string;
if (style == SCE_CSS_TAG || style == SCE_CSS_DIRECTIVE) return TextColor::keyword;
}
if (name == "yaml" || name == "toml")
{
// The two lexers assign the same IDs to these categories.
if (style == SCE_YAML_COMMENT) return TextColor::comment;
if (style == SCE_YAML_KEYWORD) return TextColor::keyword;
if (style == SCE_YAML_NUMBER) return TextColor::number;
}
if (token.empty()) return TextColor::symbol;
return TextColor::text;
}
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <filesystem>
#include <string>
#include <string_view>
namespace Scintilla { class ILexer5; }
namespace ks::files
{
enum class TextColor { background, text, chromebg, chrome, selection, comment, keyword, string, number, symbol,
menuText, menuHighlight, menuHighlightText, menuAccessKey, count };
struct TextLanguage
{
std::string lexer;
const char *keywords = "";
};
TextLanguage detectLanguage(const std::filesystem::path &path, std::string_view firstPage);
std::wstring textLanguageLabel(const TextLanguage &language);
Scintilla::ILexer5 *createTextLexer(const TextLanguage &language);
TextColor syntaxColor(Scintilla::ILexer5 &lexer, std::string_view name, int style);
}
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#include <windows.h>
#include <array>
#include <string>
#include <vector>
namespace ks::files
{
inline constexpr size_t documentColorCount = 10;
using TextPalette = std::array<COLORREF, 14>;
inline constexpr const wchar_t *textPaletteNames[] = {L"FAR (blue)", L"Dark", L"Light"};
inline constexpr TextPalette textPalettes[] = {
{RGB(0,0,128), RGB(215,230,255), RGB(0,128,128), RGB(255,255,255), RGB(0,115,115),
RGB(143,195,157), RGB(255,235,118), RGB(165,235,255), RGB(255,181,228), RGB(155,214,255),
RGB(0,0,0), RGB(0,0,0), RGB(255,255,255), RGB(255,255,0)},
{RGB(29,33,38), RGB(234,237,241), RGB(45,60,70), RGB(255,255,255), RGB(42,86,127),
RGB(155,185,150), RGB(145,201,255), RGB(241,186,143), RGB(208,170,255), RGB(152,226,218),
RGB(255,255,255), RGB(42,86,127), RGB(255,255,255), RGB(255,255,0)},
{RGB(255,255,255), RGB(28,35,46), RGB(221,231,237), RGB(25,38,54), RGB(74,104,146),
RGB(45,111,70), RGB(103,40,154), RGB(152,52,30), RGB(35,82,156), RGB(0,99,109),
RGB(0,0,0), RGB(189,207,223), RGB(0,0,0), RGB(111,77,0)},
};
inline constexpr const wchar_t *textColorNames[] = {L"Background", L"Text", L"Status background", L"Status text",
L"Selection", L"Comment", L"Keyword", L"String", L"Number", L"Symbol",
L"Top menu text", L"Selected menu background", L"Selected menu text", L"Menu access key"};
struct TextPreferences
{
bool wrap{}, numbers{true}, whitespace{}, tabsAsSpaces{}, autoIndent{true}, caretLine{true};
int tabWidth{4}, lineEnding{};
std::wstring scheme = textPaletteNames[0];
TextPalette colors = textPalettes[0];
bool operator==(const TextPreferences &) const = default;
};
// Index 0 is Viewer and index 1 is Editor.
using TextPreferencesSet = std::array<TextPreferences, 2>;
struct NamedTextPalette
{
std::wstring name;
TextPalette colors;
bool operator==(const NamedTextPalette &) const = default;
};
inline constexpr size_t maxTextPalettes = 48;
inline constexpr size_t maxTextPaletteName = 48;
struct MarkdownPreferences
{
unsigned width{960}, fontSize{12};
std::wstring font;
bool operator==(const MarkdownPreferences &) const = default;
};
struct TextSettings
{
TextPreferencesSet profiles;
std::vector<NamedTextPalette> schemes;
MarkdownPreferences markdown;
bool operator==(const TextSettings &) const = default;
};
TextSettings loadTextPreferences();
void saveTextPreferences(const TextSettings &settings);
}
File diff suppressed because it is too large. Load diff
+58
View File
@@ -0,0 +1,58 @@
#pragma once
#include <windows.h>
#include <filesystem>
#include <string_view>
#include <vector>
namespace ks::lan { struct FilesPeer; }
namespace ks::files
{
inline constexpr int searchOptionsDivider = 104;
inline constexpr int searchButtonsDivider = 105;
inline constexpr int searchHistoryButton = 108;
inline constexpr wchar_t farDropDownProperty[]=L"KSwitcher.Files.ActiveDropDown";
struct TextWindowFont
{
LOGFONTW font;
int tenthsOfPoint;
};
struct FarDropDownPalette
{
COLORREF surface, text, selection;
};
enum class FarHistoryKind { search, folder };
struct FarHistoryEntry { std::wstring date,text; };
std::vector<FarHistoryEntry> loadFarHistory(FarHistoryKind kind);
void rememberFarHistory(FarHistoryKind kind,std::wstring_view text);
int chooseFarDropDown(HWND anchor,const std::vector<FarHistoryEntry> &entries,int selected,
FarDropDownPalette palette,int rightInset=0);
void showFarHistory(HWND dialog,int fieldId,const std::vector<FarHistoryEntry> &history,
FarDropDownPalette palette);
void installFarHistoryKey(HWND field,int arrowId);
struct TextDialogs
{
INT_PTR (*confirmSave)(HWND);
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
void (*prepare)(HWND);
void (*options)(HWND, bool);
void (*message)(HWND, const wchar_t *);
TextWindowFont (*readFont)();
FarDropDownPalette (*dropDownPalette)();
INT_PTR (*run)(HINSTANCE,LPCWSTR,HWND,DLGPROC,LPARAM);
void (*finish)(HWND,INT_PTR);
bool (*dismissOwned)(HWND);
bool (*confirmExisting)(HWND);
};
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false);
void textWindowOwnerClosed();
bool cycleTextWindows(HWND current);
}
+12 -3
View File
@@ -295,15 +295,25 @@ struct LanService::Impl
{
std::lock_guard lock(mutex);
return !stopping && trusted.contains(peer)?trusted.at(peer).at("key").get<std::string>():std::string{};
},lan::FilesPort,lan::remoteTerminalAllowed,lan::hibernateFromPairedPC,[this]() -> DWORD
{
if(!lan::remoteUpdateAllowed()) return ERROR_ACCESS_DENIED;
if(!inputWindow) return ERROR_INVALID_WINDOW_HANDLE;
return PostMessageW(inputWindow,LanUpdateRequestedMessage,0,0)?ERROR_SUCCESS:GetLastError();
});
hub.datagrams([&](const auto &target,const auto &packet){
std::lock_guard lock(mutex);
if(shareInput&&trusted.contains(target)&&peers.contains(target))send(socket,peers.at(target).address,packet);
});
const bool filesListening=files.port()!=0;
if(!filesListening) diagnosticEvent(L"LAN Files could not listen on TCP 45885.");
bool filesListening=files.port()!=0;
while(!stopping)
{
files.poll();
if(filesListening!=(files.port()!=0))
{
filesListening=files.port()!=0;
nextHello=0;
}
auto now=GetTickCount64();bool clipboardActive=false;
std::vector<lan::InputEndpoint> endpoints;
{
@@ -341,7 +351,6 @@ struct LanService::Impl
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
hub.poll(endpoints,out,in,now);
files.poll();
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
for(auto &frame:in){
+1
View File
@@ -6,6 +6,7 @@ namespace ks
{
inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69;
inline constexpr UINT LanFilesChangedMessage=WM_APP+70;
inline constexpr UINT LanUpdateRequestedMessage=WM_APP+90;
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
// Discovery, pairing and optional encrypted input within the resident process.
class LanService
+374 -21
View File
@@ -2,8 +2,14 @@
#include <ws2tcpip.h>
#include <shellapi.h>
#include <shlobj.h>
#include <winioctl.h>
#include <atomic>
#include <bcrypt.h>
#include <wincrypt.h>
#include <sddl.h>
#include <winsafer.h>
#include <cstring>
#include <mutex>
#include <thread>
#include "lan_files.h"
#include "lan_channel.h"
@@ -28,6 +34,17 @@ void checkFileReply(const Json &reply)
if(error) throw std::system_error(static_cast<int>(error),std::system_category());
}
static bool filesPermissionEnabled(const wchar_t *name)
{
DWORD allowed{},size=sizeof(allowed);
return RegGetValueW(HKEY_CURRENT_USER,L"Software\\KSwitcher\\Files",name,
RRF_RT_REG_DWORD,nullptr,&allowed,&size)==ERROR_SUCCESS && allowed==1;
}
bool remoteTerminalAllowed() {return filesPermissionEnabled(remoteTerminalPreference);}
bool remoteHibernateAllowed() {return filesPermissionEnabled(remoteHibernatePreference);}
bool remoteUpdateAllowed() {return filesPermissionEnabled(remoteUpdatePreference);}
bool recycleFile(HWND owner,const fs::path &path)
{
const auto initialized=CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
@@ -52,6 +69,44 @@ bool recycleFile(HWND owner,const fs::path &path)
namespace
{
DWORD createJunction(const fs::path &name,const fs::path &target)
{
if(!target.is_absolute() || target.root_name().native().size()!=2) return ERROR_INVALID_NAME;
const auto print=target.lexically_normal().native();
const auto substitute=L"\\??\\"+print;
struct MountPointHeader
{
DWORD tag;
WORD dataLength,reserved,substituteOffset,substituteLength,printOffset,printLength;
};
const auto substituteBytes=substitute.size()*sizeof(wchar_t);
const auto printBytes=print.size()*sizeof(wchar_t);
const auto pathBytes=substituteBytes+printBytes+2*sizeof(wchar_t);
if(sizeof(MountPointHeader)+pathBytes>MAXIMUM_REPARSE_DATA_BUFFER_SIZE) return ERROR_FILENAME_EXCED_RANGE;
const MountPointHeader header{IO_REPARSE_TAG_MOUNT_POINT,static_cast<WORD>(8+pathBytes),0,0,
static_cast<WORD>(substituteBytes),static_cast<WORD>(substituteBytes+sizeof(wchar_t)),
static_cast<WORD>(printBytes)};
std::vector<char> buffer(sizeof(header)+pathBytes);
std::memcpy(buffer.data(),&header,sizeof(header));
std::memcpy(buffer.data()+sizeof(header),substitute.c_str(),substituteBytes);
std::memcpy(buffer.data()+sizeof(header)+header.printOffset,print.c_str(),printBytes);
if(!CreateDirectoryW(name.c_str(),nullptr)) return GetLastError();
const auto handle=CreateFileW(name.c_str(),GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr);
DWORD error=ERROR_SUCCESS;
if(handle==INVALID_HANDLE_VALUE) error=GetLastError();
else
{
DWORD returned{};
if(!DeviceIoControl(handle,FSCTL_SET_REPARSE_POINT,buffer.data(),static_cast<DWORD>(buffer.size()),
nullptr,0,&returned,nullptr)) error=GetLastError();
CloseHandle(handle);
}
if(error) RemoveDirectoryW(name.c_str());
return error;
}
constexpr size_t FrameLimit=256*1024;
constexpr DWORD SocketTimeout=5000;
@@ -182,6 +237,190 @@ struct FileHandle
~FileHandle(){close();}
};
DWORD requestSystemHibernate()
{
wchar_t system[MAX_PATH]{};
const auto length=GetSystemDirectoryW(system,MAX_PATH);
if(!length) return GetLastError();
if(length>=MAX_PATH) return ERROR_INSUFFICIENT_BUFFER;
const auto executable=fs::path(system)/L"shutdown.exe";
wchar_t command[]=L"shutdown.exe /h";
STARTUPINFOW startup{sizeof(startup)};
PROCESS_INFORMATION child{};
if(!CreateProcessW(executable.c_str(),command,nullptr,nullptr,FALSE,CREATE_NO_WINDOW,
nullptr,system,&startup,&child)) return GetLastError();
CloseHandle(child.hThread);
FileHandle process{child.hProcess};
const auto wait=WaitForSingleObject(process.value,3000);
if(wait==WAIT_TIMEOUT) return ERROR_TIMEOUT;
if(wait!=WAIT_OBJECT_0) return GetLastError();
DWORD exitCode{};
return GetExitCodeProcess(process.value,&exitCode)?exitCode:GetLastError();
}
DWORD restrictElevatedCommandToken(HANDLE token,FileHandle &restricted)
{
// A synthetic LUA token made directly from an elevated token can fail to
// initialize KernelBase when the child starts without a console window.
SAFER_LEVEL_HANDLE level{};
if(!SaferCreateLevel(SAFER_SCOPEID_USER,SAFER_LEVELID_NORMALUSER,SAFER_LEVEL_OPEN,&level,nullptr))
return GetLastError();
const auto filtered=SaferComputeTokenFromLevel(level,token,&restricted.value,0,nullptr);
const auto filterError=GetLastError();
SaferCloseLevel(level);
if(!filtered) return filterError;
// Preserve DISABLE_MAX_PRIVILEGE without creating a second filtered token.
LUID changeNotify{};
if(!LookupPrivilegeValueW(nullptr,SE_CHANGE_NOTIFY_NAME,&changeNotify)) return GetLastError();
DWORD size{};
if(!GetTokenInformation(restricted.value,TokenPrivileges,nullptr,0,&size) &&
GetLastError()!=ERROR_INSUFFICIENT_BUFFER) return GetLastError();
std::vector<BYTE> storage(size);
const auto privileges=reinterpret_cast<TOKEN_PRIVILEGES *>(storage.data());
if(!GetTokenInformation(restricted.value,TokenPrivileges,privileges,size,&size)) return GetLastError();
DWORD removed{};
for(DWORD i=0;i<privileges->PrivilegeCount;++i)
{
const auto &luid=privileges->Privileges[i].Luid;
if(luid.LowPart!=changeNotify.LowPart || luid.HighPart!=changeNotify.HighPart)
privileges->Privileges[removed++]={luid,SE_PRIVILEGE_REMOVED};
}
if(!removed) return ERROR_SUCCESS;
privileges->PrivilegeCount=removed;
AdjustTokenPrivileges(restricted.value,FALSE,privileges,0,nullptr,nullptr);
return GetLastError();
}
struct RemoteCommand
{
FileHandle job,process,output;
void stop()
{
job.close();
process.close();
output.close();
}
DWORD start(const fs::path &directory,const std::wstring &command)
{
if(process.value!=INVALID_HANDLE_VALUE) return ERROR_BUSY;
if(command.empty() || command.size()>12000 || command.find(L'\0')!=command.npos) return ERROR_INVALID_PARAMETER;
const auto script=L"$ProgressPreference='SilentlyContinue'; "
L"[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); "
L"$OutputEncoding=[Console]::OutputEncoding;\r\n"+command;
const auto data=reinterpret_cast<const BYTE *>(script.data());
const auto bytes=static_cast<DWORD>(script.size()*sizeof(wchar_t));
constexpr DWORD encoding=CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF;
DWORD length{};
if(!CryptBinaryToStringW(data,bytes,encoding,nullptr,&length)) return GetLastError();
std::wstring encoded(length,L'\0');
if(!CryptBinaryToStringW(data,bytes,encoding,encoded.data(),&length)) return GetLastError();
encoded.resize(length);
// Windows PowerShell serializes its error stream as CLIXML with -EncodedCommand.
// Decode the command inside a fixed text-mode expression instead.
auto arguments=L"powershell.exe -NoLogo -NoProfile -NonInteractive -OutputFormat Text -Command "
L"\"& ([ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('"+
encoded+L"'))))\"";
wchar_t system[MAX_PATH]{};
if(!GetSystemDirectoryW(system,MAX_PATH)) return GetLastError();
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
FileHandle token,restricted,read,write,input,processJob;
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|
TOKEN_ADJUST_DEFAULT,&token.value)) return GetLastError();
TOKEN_ELEVATION elevation{};
DWORD elevationSize{};
if(!GetTokenInformation(token.value,TokenElevation,&elevation,sizeof(elevation),&elevationSize))
return GetLastError();
if(elevation.TokenIsElevated)
{
if(const auto error=restrictElevatedCommandToken(token.value,restricted)) return error;
}
else if(!CreateRestrictedToken(token.value,DISABLE_MAX_PRIVILEGE|LUA_TOKEN,0,nullptr,0,nullptr,0,nullptr,
&restricted.value)) return GetLastError();
PSID medium{};
if(!ConvertStringSidToSidW(L"S-1-16-8192",&medium)) return GetLastError();
TOKEN_MANDATORY_LABEL label{{medium,SE_GROUP_INTEGRITY}};
const auto limited=SetTokenInformation(restricted.value,TokenIntegrityLevel,&label,
sizeof(label)+GetLengthSid(medium));
const auto tokenError=GetLastError();
LocalFree(medium);
if(!limited) return tokenError;
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
if(!CreatePipe(&read.value,&write.value,&inheritable,0) ||
!SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0)) return GetLastError();
input.value=CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,
OPEN_EXISTING,0,nullptr);
if(input.value==INVALID_HANDLE_VALUE) return GetLastError();
const auto createdJob=CreateJobObjectW(nullptr,nullptr);
if(!createdJob) return GetLastError();
processJob.value=createdJob;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(!SetInformationJobObject(processJob.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))
return GetLastError();
SIZE_T attributeBytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&attributeBytes);
std::vector<BYTE> storage(attributeBytes);
const auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&attributeBytes)) return GetLastError();
HANDLE inherited[]{input.value,write.value};
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput=input.value;
startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=write.value;
startup.lpAttributeList=attributes;
PROCESS_INFORMATION child{};
const auto started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inherited,sizeof(inherited),nullptr,nullptr) &&
CreateProcessAsUserW(restricted.value,shell.c_str(),arguments.data(),nullptr,nullptr,TRUE,
CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,nullptr,
directory.c_str(),&startup.StartupInfo,&child);
const auto processError=GetLastError();
DeleteProcThreadAttributeList(attributes);
if(!started) return processError;
FileHandle thread{child.hThread},childProcess{child.hProcess};
if(!AssignProcessToJobObject(processJob.value,childProcess.value) || ResumeThread(thread.value)==DWORD(-1))
{
const auto error=GetLastError();
TerminateProcess(childProcess.value,error);
return error;
}
job.value=std::exchange(processJob.value,INVALID_HANDLE_VALUE);
process.value=std::exchange(childProcess.value,INVALID_HANDLE_VALUE);
output.value=std::exchange(read.value,INVALID_HANDLE_VALUE);
return ERROR_SUCCESS;
}
Json poll()
{
if(process.value==INVALID_HANDLE_VALUE) return failure(ERROR_INVALID_HANDLE);
const auto wait=WaitForSingleObject(process.value,0);
if(wait==WAIT_FAILED) return failure();
DWORD available{};
if(!PeekNamedPipe(output.value,nullptr,0,nullptr,&available,nullptr) && GetLastError()!=ERROR_BROKEN_PIPE)
return failure();
Bytes bytes(std::min<DWORD>(available,FileChunk));
DWORD read{};
if(!bytes.empty() && !ReadFile(output.value,bytes.data(),static_cast<DWORD>(bytes.size()),&read,nullptr))
return failure();
bytes.resize(read);
const bool done=wait==WAIT_OBJECT_0 && bytes.empty();
DWORD exitCode{};
if(done)
{
if(!GetExitCodeProcess(process.value,&exitCode)) return failure();
stop();
}
return {{"error",0},{"data",Json::binary(std::move(bytes))},{"done",done},{"exitCode",exitCode}};
}
};
fs::path temporaryFile(const fs::path &target)
{
return target.parent_path()/wide(".kswitcher-"+randomHex(16)+".tmp");
@@ -231,6 +470,9 @@ std::string hashPrefix(HANDLE file,uint64_t size,const FileProgress &progress,ui
class FileOperations
{
FilesListener::TerminalPermission terminalPermission;
FilesListener::HostAction hibernate,update;
RemoteCommand terminal;
bool remote;
HANDLE search=INVALID_HANDLE_VALUE;
WIN32_FIND_DATAW entry{};
@@ -385,7 +627,10 @@ class FileOperations
return reply;
}
public:
explicit FileOperations(bool remote):remote(remote){}
explicit FileOperations(bool remote,FilesListener::TerminalPermission permission={},
FilesListener::HostAction hibernateAction={},FilesListener::HostAction updateAction={}):
terminalPermission(std::move(permission)),hibernate(std::move(hibernateAction)),
update(std::move(updateAction)),remote(remote){}
~FileOperations(){closeSearch();discard();}
Json call(const Json &request,const FileProgress &progress)
{
@@ -399,6 +644,26 @@ public:
Json perform(const Json &request,const FileProgress &progress)
{
const auto action=request.at("action").get<std::string>();
if(action=="hibernate" || action=="update")
{
if(request.size()!=1) return failure(ERROR_INVALID_PARAMETER);
const auto &hostAction=action=="hibernate"?hibernate:update;
if(!remote || !hostAction) return failure(ERROR_ACCESS_DENIED);
const auto error=hostAction();
return error?failure(error):ok();
}
if(action=="terminalRun" || action=="terminalPoll" || action=="terminalCancel")
{
if(!remote || !terminalPermission || !terminalPermission())
{
terminal.stop();
return failure(ERROR_ACCESS_DENIED);
}
if(action=="terminalCancel") {terminal.stop();return ok();}
if(action=="terminalPoll") return terminal.poll();
const auto error=terminal.start(path(request.at("path")),wide(request.at("command").get<std::string>()));
return error?failure(error):ok();
}
if(action=="drives")
{
auto reply=ok();
@@ -449,7 +714,7 @@ public:
discard(true);
return failure(error?error:ERROR_WRITE_FAULT);
}
if(action=="commit")
if(action=="commit" || action=="commitEdit")
{
if(output.value==INVALID_HANDLE_VALUE) return failure(ERROR_INVALID_HANDLE);
LARGE_INTEGER size{};
@@ -459,6 +724,26 @@ public:
const FILETIME time{static_cast<DWORD>(stamp),static_cast<DWORD>(stamp>>32)};
if(!SetFileTime(output.value,nullptr,nullptr,&time) || !FlushFileBuffers(output.value)) return failure();
output.close();
static std::mutex publicationMutex;
const std::lock_guard publication(publicationMutex);
if(action=="commitEdit")
{
WIN32_FILE_ATTRIBUTE_DATA existing{};
if(!GetFileAttributesExW(target.c_str(),GetFileExInfoStandard,&existing) ||
(existing.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_READONLY)) ||
fileSize(existing.nFileSizeHigh,existing.nFileSizeLow)!=request.at("expectedSize").get<uint64_t>() ||
fileSize(existing.ftLastWriteTime.dwHighDateTime,existing.ftLastWriteTime.dwLowDateTime)!=
request.at("expectedModified").get<uint64_t>())
{
discard(true);
return failure(ERROR_FILE_INVALID);
}
const auto attributes=FILE_ATTRIBUTE_ARCHIVE|
(existing.dwFileAttributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM|
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED));
if(!SetFileAttributesW(temporary.c_str(),attributes)) return failure();
return commit(target,true);
}
const auto reply=commit(target,request.at("replace").get<bool>());
if(reply.at("error")==ERROR_SUCCESS) SetFileAttributesW(target.c_str(),FILE_ATTRIBUTE_ARCHIVE);
return reply;
@@ -477,7 +762,8 @@ public:
{
WIN32_FILE_ATTRIBUTE_DATA data{};
if(!GetFileAttributesExW(name.c_str(),GetFileExInfoStandard,&data)) return failure();
return {{"error",0},{"attributes",data.dwFileAttributes},{"size",fileSize(data.nFileSizeHigh,data.nFileSizeLow)},
return {{"error",0},{"attributes",data.dwFileAttributes},{"editCommit",true},
{"size",fileSize(data.nFileSizeHigh,data.nFileSizeLow)},
{"modified",fileSize(data.ftLastWriteTime.dwHighDateTime,data.ftLastWriteTime.dwLowDateTime)}};
}
if(action=="canonical")
@@ -487,6 +773,20 @@ public:
return error?failure(error.value()):Json{{"error",0},{"path",utf8(canonical.native())}};
}
if(action=="mkdir") return CreateDirectoryW(name.c_str(),nullptr)?ok():failure();
if(action=="mkdir-link")
{
const auto target=path(request.at("target"));
if(target.empty()) return failure(ERROR_INVALID_NAME);
const auto kind=request.at("kind").get<std::string>();
if(kind=="junction")
{
const auto error=createJunction(name,target);
return error?failure(error):ok();
}
if(kind!="symlink") return failure(ERROR_INVALID_PARAMETER);
return CreateSymbolicLinkW(name.c_str(),target.c_str(),
SYMBOLIC_LINK_FLAG_DIRECTORY|SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)?ok():failure();
}
if(action=="rmdir") return RemoveDirectoryW(name.c_str())?ok():failure();
if(action=="recycle") return recycleFile(nullptr,name)?ok():failure(ERROR_ACCESS_DENIED);
if(action=="remove")
@@ -644,6 +944,12 @@ struct FilesConnection::Impl
}
};
DWORD hibernateFromPairedPC()
{
if(!remoteHibernateAllowed()) return ERROR_ACCESS_DENIED;
return requestSystemHibernate();
}
FilesConnection::FilesConnection(const FilesPeer *peer):impl(std::make_unique<Impl>(peer)){}
FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key):
impl(std::make_unique<Impl>())
@@ -667,7 +973,7 @@ Json FilesConnection::call(const Json &request,const FileProgress &progress)
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
bool replace,bool append,const FileProgress &progress)
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination)
{
auto openSource=fileRequest("openRead",from);
openSource["size"]=size;
@@ -705,7 +1011,13 @@ void streamFile(FilesConnection &source,FilesConnection &target,const std::strin
if(data.empty())
{
if(done!=size) throw std::system_error(ERROR_FILE_INVALID,std::system_category());
checkFileReply(target.call({{"action","commit"},{"replace",replace},{"modified",modified}}));
Json commit{{"action",expectedDestination?"commitEdit":"commit"},{"replace",replace},{"modified",modified}};
if(expectedDestination)
{
commit["expectedSize"]=expectedDestination->size;
commit["expectedModified"]=expectedDestination->modified;
}
checkFileReply(target.call(commit));
checkFileReply(source.call({{"action","closeRead"}}));
return;
}
@@ -723,6 +1035,26 @@ void streamFile(FilesConnection &source,FilesConnection &target,const std::strin
}
}
DWORD runRemoteCommand(FilesConnection &host,const fs::path &directory,std::wstring_view command,
const std::function<void(std::string_view)> &output,std::stop_token stop)
{
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
auto request=fileRequest("terminalRun",directory);
request["command"]=utf8(std::wstring(command));
checkFileReply(host.call(request));
while(!stop.stop_requested())
{
const auto reply=host.call({{"action","terminalPoll"}});
checkFileReply(reply);
const auto &bytes=reply.at("data").get_binary();
if(!bytes.empty()) output({reinterpret_cast<const char *>(bytes.data()),bytes.size()});
if(reply.at("done").get<bool>()) return reply.at("exitCode").get<DWORD>();
if(bytes.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(60));
}
checkFileReply(host.call({{"action","terminalCancel"}}));
throw std::system_error(ERROR_CANCELLED,std::system_category());
}
struct FilesListener::Impl
{
struct Client
@@ -738,29 +1070,47 @@ struct FilesListener::Impl
};
std::string local;
PairKey key;
TerminalPermission terminalPermission;
HostAction hibernate,update;
WinSocket listener;
std::vector<std::unique_ptr<Client>> clients;
uint16_t boundPort{};
Impl(std::string id,PairKey lookup,uint16_t port):local(std::move(id)),key(std::move(lookup))
uint16_t requestedPort{},boundPort{};
ULONGLONG nextBind{};
DWORD lastBindError{};
Impl(std::string id,PairKey lookup,uint16_t port,TerminalPermission permission,HostAction hibernateAction,
HostAction updateAction):
local(std::move(id)),key(std::move(lookup)),terminalPermission(std::move(permission)),
hibernate(std::move(hibernateAction)),update(std::move(updateAction)),requestedPort(port)
{
listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(listener.value==INVALID_SOCKET) return;
bindListener();
}
void bindListener()
{
nextBind=GetTickCount64()+1000;
WinSocket candidate{socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)};
BOOL exclusive=TRUE;
u_long mode=1;
sockaddr_in address{};
address.sin_family=AF_INET;
address.sin_port=htons(port);
if(setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
ioctlsocket(listener.value,FIONBIO,&mode) ||
bind(listener.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) ||
listen(listener.value,8))
address.sin_port=htons(requestedPort);
int length=sizeof(address);
if(candidate.value==INVALID_SOCKET ||
setsockopt(candidate.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
ioctlsocket(candidate.value,FIONBIO,&mode) ||
bind(candidate.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) ||
listen(candidate.value,8) ||
getsockname(candidate.value,reinterpret_cast<sockaddr*>(&address),&length))
{
closesocket(std::exchange(listener.value,INVALID_SOCKET));
const auto error=static_cast<DWORD>(WSAGetLastError());
if(requestedPort==FilesPort && lastBindError!=error)
log(L"LAN Files TCP 45885 unavailable; retrying. Windows error "+std::to_wstring(error));
lastBindError=error;
return;
}
int length=sizeof(address);
if(!getsockname(listener.value,reinterpret_cast<sockaddr*>(&address),&length))
boundPort=ntohs(address.sin_port);
listener.value=std::exchange(candidate.value,INVALID_SOCKET);
boundPort=ntohs(address.sin_port);
if(requestedPort==FilesPort) log(L"LAN Files listener ready on TCP 45885.");
lastBindError=0;
}
void serve(SOCKET socket)
{
@@ -776,7 +1126,7 @@ struct FilesListener::Impl
wire.authenticate(secret,peer,local,challenge,nonce,false);
if(wire.read().at("action")!="authenticate") return;
wire.write(ok());
FileOperations operations(true);
FileOperations operations(true,terminalPermission,hibernate,update);
for(;;)
{
const auto request=wire.read(true);
@@ -795,6 +1145,7 @@ struct FilesListener::Impl
void poll()
{
std::erase_if(clients,[](const auto &client){return client->done.load();});
if(listener.value==INVALID_SOCKET && GetTickCount64()>=nextBind) bindListener();
if(listener.value==INVALID_SOCKET || clients.size()>=16) return;
sockaddr_in address{};
int size=sizeof(address);
@@ -817,8 +1168,10 @@ struct FilesListener::Impl
}
};
FilesListener::FilesListener(std::string local,PairKey key,uint16_t port):
impl(std::make_unique<Impl>(std::move(local),std::move(key),port)){}
FilesListener::FilesListener(std::string local,PairKey key,uint16_t port,TerminalPermission terminalPermission,
HostAction hibernate,HostAction update):
impl(std::make_unique<Impl>(std::move(local),std::move(key),port,std::move(terminalPermission),
std::move(hibernate),std::move(update))){}
FilesListener::~FilesListener()=default;
uint16_t FilesListener::port()const{return impl->boundPort;}
void FilesListener::poll(){impl->poll();}
+16 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include "lan_pairing.h"
#include <functional>
#include <stop_token>
namespace ks::lan
{
@@ -13,6 +14,7 @@ struct FilesPeer
bool filesBrowse{};
};
using FileProgress = std::function<bool(uint64_t, uint64_t)>;
struct FileRevision { uint64_t size, modified; };
inline constexpr size_t FileChunk = 64 * 1024;
// One connection owns its enumeration, file handles and uncommitted upload.
@@ -29,7 +31,9 @@ public:
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
bool replace,bool append,const FileProgress &progress);
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr);
DWORD runRemoteCommand(FilesConnection &host,const std::filesystem::path &directory,std::wstring_view command,
const std::function<void(std::string_view)> &output,std::stop_token stop={});
class FilesListener
{
@@ -37,7 +41,10 @@ class FilesListener
std::unique_ptr<Impl> impl;
public:
using PairKey = std::function<std::string(const std::string &)>;
FilesListener(std::string local, PairKey key,uint16_t port=FilesPort);
using TerminalPermission = std::function<bool()>;
using HostAction = std::function<DWORD()>;
FilesListener(std::string local, PairKey key,uint16_t port=FilesPort,TerminalPermission terminalPermission={},
HostAction hibernate={},HostAction update={});
uint16_t port() const;
~FilesListener();
void poll();
@@ -47,4 +54,11 @@ Json fileRequest(std::string_view action, const std::filesystem::path &path);
std::filesystem::path filePath(const Json &path);
void checkFileReply(const Json &reply);
bool recycleFile(HWND owner, const std::filesystem::path &path);
inline constexpr wchar_t remoteTerminalPreference[]=L"AllowRemoteTerminal";
bool remoteTerminalAllowed();
inline constexpr wchar_t remoteHibernatePreference[]=L"AllowRemoteHibernate";
bool remoteHibernateAllowed();
DWORD hibernateFromPairedPC();
inline constexpr wchar_t remoteUpdatePreference[]=L"AllowRemoteUpdate";
bool remoteUpdateAllowed();
}
+2
View File
@@ -38,6 +38,8 @@ bool shouldElevateOnLaunch()
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
{
// Inherited by unattended children such as the LAN PowerShell process.
SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS);
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
int argc{};
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
+7 -1
View File
@@ -737,6 +737,7 @@ namespace
{
std::recursive_mutex logGate;
bool loggingEnabled = false;
std::wstring logFilename = L"kswitcher.log";
DiagnosticBuffer diagnosticBuffer;
}
size_t DiagnosticBuffer::expire(ULONGLONG now)
@@ -832,6 +833,11 @@ void diagnosticOperation(const std::string &json)
record["context"] = utf8(diagnosticBuffer.record(L"Operation complete", true, GetTickCount64()));
log(L"Operation " + wide(record.dump(-1, ' ', true, nlohmann::json::error_handler_t::replace)));
}
void setLogFilename(std::wstring filename)
{
std::lock_guard lock(logGate);
logFilename = std::move(filename);
}
void log(const std::wstring &message)
{
std::lock_guard lock(logGate);
@@ -839,7 +845,7 @@ void log(const std::wstring &message)
return;
try
{
auto path = dataDirectory() / L"kswitcher.log";
auto path = dataDirectory() / logFilename;
std::error_code ec;
auto size = std::filesystem::file_size(path, ec);
if (!ec && size > 256 * 1024)
+1
View File
@@ -94,6 +94,7 @@ class DiagnosticBuffer
void clear() { entries.clear(); }
};
void setLoggingEnabled(bool enabled);
void setLogFilename(std::wstring filename);
void expireDiagnostics(ULONGLONG now);
void diagnosticEvent(const std::wstring &message, bool problem = false);
void diagnosticOperation(const std::string &json);
+3 -1
View File
@@ -1514,7 +1514,9 @@ Settings collectSettings(HWND w, SettingsView *v)
s.undo = value(w, 213);
s.clipboard = value(w, 214);
s.screenshot = value(w, 215);
s.filesHotkey = value(w, 216);
auto filesHotkey = value(w, 216);
if (s.filesHotkey || !filesHotkey.empty())
s.filesHotkey = std::move(filesHotkey);
s.maxItems = integer(w, 240);
s.maxMiB = integer(w, 241);
s.maxImageMiB = integer(w, 242);
+50 -41
View File
@@ -91,14 +91,8 @@ void refreshLan(HWND w,LanView &v)
for(const auto &peer:next["peers"])
{
auto id=peer.at("id").get<std::string>();ids.push_back(id);
std::wstring state=L"Not paired";
if(peer.at("paired").get<bool>()){
bool connected=next.value("inputReady",nlohmann::json::object()).contains(id);
state=connected?L"Pair saved — input connected":
!next.value("shareInput",false)?L"Pair saved — input disabled here":
!peer.value("online",false)?L"Pair saved — computer offline":L"Pair saved — input not connected";
}
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"] — "+state);
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"]"+
(peer.at("paired").get<bool>()?L" — Paired":L""));
}
// Presence/challenge refreshes must not repaint or reset the pairing list.
if(v.ids!=ids||v.rows!=rows)
@@ -131,11 +125,21 @@ void refreshLan(HWND w,LanView &v)
std::wstring peerName;
for(const auto &peer:v.snapshot["peers"])
if(peer.at("id")==v.snapshot.value("pendingPeer",std::string{}))peerName=wide(peer.at("name").get<std::string>());
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair there too. Pair is not saved yet.";
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair on the other PC.";
}
value(w,708,v.error.empty() ? pairingStatus : v.error);
value(w,705,pending ? L"Waiting..." : L"&Pair");
value(w,710,v.ids.empty() ? (enabled ? L"No KSwitcher found. Enable discovery on the other PC too. UDP 45883 must be allowed on your private network." : L"Discovery is disabled on this computer.") : L"Select the matching KSwitcher name and ID shown on the other computer.");
const wchar_t *peerStatus=L"Select the name and ID shown on the other PC.";
if(v.ids.empty()) peerStatus=enabled?L"No computers found. Enable discovery on both PCs and allow UDP 45883.":
L"Discovery is disabled on this computer.";
else if(paired)
{
const bool connected=v.snapshot.value("inputReady",nlohmann::json::object()).contains(selected);
peerStatus=connected?L"Pair saved — input connected":
!v.snapshot.value("shareInput",false)?L"Pair saved — input disabled here":
!online?L"Pair saved — computer offline":L"Pair saved — input not connected";
}
value(w,710,peerStatus);
EnableWindow(GetDlgItem(w,705),enabled&&online&&!pending&&!paired);
EnableWindow(GetDlgItem(w,706),pending);
EnableWindow(GetDlgItem(w,707),paired);
@@ -157,8 +161,7 @@ void refreshLan(HWND w,LanView &v)
EnableWindow(GetDlgItem(w,716),v.snapshot.value("shareInput",false));
auto gridState=positions.dump()+v.snapshot["peers"].dump()+selected+v.snapshot.value("controlPeer",std::string{})+v.snapshot.value("inputReady",nlohmann::json::object()).dump()+(v.snapshot.value("shareInput",false)?"1":"0");
if(gridState!=v.gridState){v.gridState=std::move(gridState);InvalidateRect(GetDlgItem(w,721),nullptr,FALSE);}
std::wstring detail=L"Drag paired monitors to empty cells. This PC stays fixed. Arrow keys also work.";
detail=L"Drag monitors to neighboring cells. Mouse crosses shared edges; empty cells block passage.";
const std::wstring detail=L"Drag monitors or use arrow keys. The pointer crosses shared edges.";
value(w,719,v.error.empty()?detail:v.error);
auto inputStatus=wide(v.snapshot.value("inputStatus",std::string("Input sharing disabled.")));
if(!v.snapshot.value("shareInput",false))
@@ -257,38 +260,44 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
}
void showLan(HWND parent,App &app)
{
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,740,908,0,false);
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,730,498,0,false);
windowLayoutState(w)->fixedClient=true;
SetWindowLongPtrW(w,GWLP_HWNDPARENT,(LONG_PTR)parent);
auto v=new LanView{parent,&app};SetWindowLongPtrW(w,GWLP_USERDATA,(LONG_PTR)v);
label(w,L"Changes here save automatically. No need to click Save in Settings.",18,16,700);
control(w,L"STATIC",L"",0,709,18,45,700,24);
button(w,L"&Enable discovery",701,18,78,210);
label(w,L"Only enabled KSwitcher instances announce themselves.",244,82,470);
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,18,120,700,96);
control(w,L"STATIC",L"",0,710,18,224,700,40);
label(w,L"Same pairing c&ode on both computers",18,273,700);
edit(w,703,18,301,470);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
button(w,L"&Generate code",704,504,300,214);
label(w,L"Generate once, enter that code on both PCs, select each other, then click Pair on both.",18,338,700);
button(w,L"&Pair",705,18,370,140);button(w,L"Cancel &pairing",706,174,370,160);button(w,L"&Forget pair",707,350,370,160);
control(w,L"STATIC",L"",0,708,18,412,700,40);
label(w,L"Arrange your computers",18,458,700);
label(w,L"Changes save automatically.",16,12,698);
control(w,L"STATIC",L"",0,709,16,35,698,22);
button(w,L"&Enable discovery",701,16,62,164);
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,16,98,332,70);
control(w,L"STATIC",L"",0,710,16,173,332,36);
label(w,L"Same pairing c&ode on both computers",16,211,332);
edit(w,703,16,234,189);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
button(w,L"&Generate code",704,213,234,135);
button(w,L"&Pair",705,16,268,76);
button(w,L"Cancel &pairing",706,100,268,125);
button(w,L"&Forget pair",707,233,268,115);
control(w,L"STATIC",L"Use one code on both PCs. Select each other and click Pair on both.",0,0,16,302,332,37);
control(w,L"STATIC",L"",0,708,16,344,332,53);
constexpr int right=366,rightWidth=348,gridTop=92,gridHeight=185;
label(w,L"Arrange your computers",right,65,rightWidth);
WNDCLASSW gridClass{};gridClass.lpfnWndProc=lanGridProc;gridClass.hInstance=app.instance;gridClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);gridClass.lpszClassName=L"KSwitcher.LAN.Layout";RegisterClassW(&gridClass);
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer above, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
scale(w,18),scale(w,486),scale(w,700),scale(w,180),w,reinterpret_cast<HMENU>(721),app.instance,v);
windowLayoutState(w)->controls.push_back({grid,{18,486,718,666}});
control(w,L"STATIC",L"",0,719,18,674,700,24);
button(w,L"Enable &input sharing",715,18,706,330);
button(w,L"&Stop input sharing",716,370,706,240);
control(w,L"STATIC",L"",0,718,18,744,700,30);
button(w,L"Send file…",726,18,774,144);
button(w,L"Incoming files…",730,174,774,160);
button(w,L"Download log…",727,346,774,164);
button(w,L"Previous log…",728,522,774,196);
control(w,L"BUTTON",L"Allow paired computers to download diagnostic logs",BS_AUTOCHECKBOX|WS_TABSTOP,729,18,808,700,24);
control(w,L"STATIC",L"",0,731,18,835,700,24);
button(w,L"Connection &help",722,18,864,300);
button(w,L"&Close",IDCANCEL,618,864,100);
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer in the list, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
scale(w,right),scale(w,gridTop),scale(w,rightWidth),scale(w,gridHeight),w,reinterpret_cast<HMENU>(721),app.instance,v);
windowLayoutState(w)->controls.push_back({grid,{right,gridTop,right+rightWidth,gridTop+gridHeight}});
control(w,L"STATIC",L"",0,719,right,283,rightWidth,37);
button(w,L"Enable &input sharing",715,right,323,172);
button(w,L"&Stop input sharing",716,546,323,168);
control(w,L"STATIC",L"",0,718,right,357,rightWidth,40);
button(w,L"Send file…",726,16,403,168);
button(w,L"Incoming files…",730,192,403,168);
button(w,L"Download log…",727,368,403,168);
button(w,L"Previous log…",728,544,403,170);
control(w,L"STATIC",L"",0,731,16,436,698,20);
checkbox(w,L"Allow paired computers to download diagnostic logs",729,16,464,418);
button(w,L"Connection &help",722,444,460,162);
button(w,L"&Close",IDCANCEL,614,460,100);
EnableWindow(parent,FALSE);showRequestedWindow(w);SetForegroundWindow(w);
SetTimer(w,1,1000,nullptr);
try {refreshLan(w,*v);} catch(const std::exception &e){v->error=wide(e.what());value(w,708,v->error);}
+6 -1
View File
@@ -55,7 +55,12 @@ UpdateResult runUpdate(bool install, const std::wstring &expectedVersion, bool s
L" -CurrentVersion " + quoteArgument(AppVersion) + L" -WorkDirectory " + quoteArgument(work.wstring()) +
L" -InstallDirectory " + quoteArgument(std::filesystem::path(executable()).parent_path().wstring()) +
L" -ParentProcessId " + std::to_wstring(GetCurrentProcessId()) + L" -ReadyEvent " + quoteArgument(readyName);
if (install) command += L" -ExpectedVersion " + quoteArgument(expectedVersion);
if (install)
{
command += L" -Journal " + quoteArgument((dataDirectory() / L"kswitcher.log").wstring());
if (expectedVersion.empty()) command += L" -Unattended";
else command += L" -ExpectedVersion " + quoteArgument(expectedVersion);
}
if (showProgress) command += L" -ShowProgress";
STARTUPINFOW startup{sizeof(startup)};
PROCESS_INFORMATION process{};
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.77";
inline constexpr wchar_t AppVersion[] = L"0.6.105";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+66 -4
View File
@@ -22,6 +22,56 @@ void require(bool ok, const char *message)
if (!ok) throw std::runtime_error(message);
++passed;
}
void lanWindowLayoutChecks(const std::filesystem::path &root)
{
const std::string peer(32,'b');
const nlohmann::json fixture={{"version",1},{"id",std::string(32,'a')},{"enabled",false},
{"trusted",{{peer,{{"name","Paired desktop"},{"key",std::string(64,'f')}}}}},
{"positions",{{peer,nlohmann::json::array({1,0})}}}};
const auto data=fixture.dump();
std::filesystem::create_directories(root);
ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(data.begin(),data.end())));
ks::App app(GetModuleHandleW(nullptr),true,root);
ks::showSettings(app);
SendMessageW(app.settingsWindow,WM_COMMAND,262,0);
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
require(lan!=nullptr,"Computers window opens");
const auto dpi=GetDpiForWindow(lan);
RECT room{0,0,MulDiv(750,dpi,96),MulDiv(510,dpi,96)};
AdjustWindowRectExForDpi(&room,GetWindowLongPtrW(lan,GWL_STYLE)&~(WS_HSCROLL|WS_VSCROLL),
FALSE,GetWindowLongPtrW(lan,GWL_EXSTYLE),dpi);
RECT frame{};GetWindowRect(lan,&frame);
SetWindowPos(lan,nullptr,0,0,std::min(frame.right-frame.left,room.right-room.left),
std::min(frame.bottom-frame.top,room.bottom-room.top),SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
require(!(GetWindowLongPtrW(lan,GWL_STYLE)&(WS_HSCROLL|WS_VSCROLL)),"Computers window fits without scrollbars");
RECT client{};GetClientRect(lan,&client);
std::vector<std::pair<int,RECT>> placed;
for(HWND child=GetWindow(lan,GW_CHILD);child;child=GetWindow(child,GW_HWNDNEXT))
{
RECT bounds{};GetWindowRect(child,&bounds);
MapWindowPoints(nullptr,lan,reinterpret_cast<POINT *>(&bounds),2);
require(bounds.left>=0&&bounds.top>=0&&bounds.right<=client.right&&bounds.bottom<=client.bottom,
"Computers control is fully visible");
const int id=GetDlgCtrlID(child);
for(const auto &[otherId,other]:placed)
{
RECT overlap{};
if(IntersectRect(&overlap,&bounds,&other))
throw std::runtime_error("Computers controls overlap: "+std::to_string(id)+" and "+std::to_string(otherId)+
" at "+std::to_string(overlap.left)+","+std::to_string(overlap.top));
}
placed.push_back({id,bounds});
}
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
auto dc=GetDC(lan);
auto screenshot=ks::screenshotClip(dc,client.right,client.bottom,{});
ReleaseDC(lan,dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-compact-layout.png",
ks::encodePng(ks::decodeImage(screenshot)));
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
std::cout<<"Computers layout verified at "<<dpi<<" DPI.\n";
}
void contextChecks()
{
ks::Settings scoped;
@@ -114,12 +164,19 @@ void contextChecks()
require(hook.update('A', true, MOD_ALT, true) == 0, "ordinary keys pass");
}
}
int main()
int main(int argc,char **argv)
{
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-chat-tests-" + std::to_wstring(GetCurrentProcessId()));
try
{
if(argc==2 && std::string_view(argv[1])=="--lan-layout")
{
lanWindowLayoutChecks(root);
std::filesystem::remove_all(root);
CoUninitialize();
return 0;
}
contextChecks();
{
ks::App app(GetModuleHandleW(nullptr), true, root);
@@ -292,11 +349,16 @@ int main()
HWND picker = GetDlgItem(dialog, 728);
RECT dialogBounds{};
GetWindowRect(dialog, &dialogBounds);
MONITORINFO monitor{sizeof(monitor)};
require(GetMonitorInfoW(MonitorFromWindow(dialog, MONITOR_DEFAULTTONEAREST), &monitor),
"monitor work area available");
const auto targetX = std::clamp(dialogBounds.left + 32, monitor.rcWork.left, monitor.rcWork.right - 120);
const auto targetY = std::clamp(dialogBounds.top + 100, monitor.rcWork.top, monitor.rcWork.bottom - 48);
HWND target = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, L"EDIT", L"Picker fixture",
WS_POPUP | WS_VISIBLE, dialogBounds.left + 32, dialogBounds.top + 100, 120, 48,
WS_POPUP | WS_VISIBLE, targetX, targetY, 120, 48,
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
require(picker && target, "window picker and target available");
POINT drop{dialogBounds.left + 33, dialogBounds.top + 101};
POINT drop{targetX + 1, targetY + 1};
require(GetAncestor(WindowFromPoint(drop), GA_ROOT) == target, "fixture window is under the drop point");
ScreenToClient(picker, &drop);
SendMessageW(picker, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(8, 8));
@@ -446,7 +508,7 @@ int main()
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,262,0);
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"single saved pair selected automatically when opening LAN settings");
wchar_t pairState[512]{};SendDlgItemMessageW(lan,702,LB_GETTEXT,0,(LPARAM)pairState);
wchar_t pairState[512]{};GetDlgItemTextW(lan,710,pairState,std::size(pairState));
require(std::wstring(pairState).find(L"Pair saved — input disabled here")!=std::wstring::npos,"saved pairing does not imply an active input connection");
require(!IsWindowEnabled(GetDlgItem(lan,705))&&!IsWindowEnabled(GetDlgItem(lan,703))&&!IsWindowEnabled(GetDlgItem(lan,704)),"saved pair disables pairing and code controls");
SendDlgItemMessageW(lan,702,LB_SETCURSEL,-1,0);
+548
View File
@@ -0,0 +1,548 @@
param(
[Parameter(Mandatory)][string]$Executable,
[Parameter(Mandatory)][string]$Fixture,
[switch]$SystemOpenOnly,
[switch]$TerminalOnly,
[string]$Node='node'
)
$ErrorActionPreference = 'Stop'
Add-Type @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class FilesActivationUi {
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
struct GuiInfo {
public int Size, Flags;
public IntPtr Active, Focus, Capture, MenuOwner, MoveSize, Caret;
public Rect CaretRect;
}
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, IntPtr process);
[DllImport("user32.dll")] static extern bool GetGUIThreadInfo(uint thread, ref GuiInfo info);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] static extern IntPtr SendRect(IntPtr window, uint msg, IntPtr w, out Rect rect);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr Write(IntPtr window, uint msg, IntPtr w, string text);
[DllImport("shell32.dll")] public static extern void SHChangeNotify(int eventId, uint flags, IntPtr first, IntPtr second);
public static IntPtr Focus(IntPtr window) {
var info = new GuiInfo { Size = Marshal.SizeOf(typeof(GuiInfo)) };
if (!GetGUIThreadInfo(GetWindowThreadProcessId(window, IntPtr.Zero), ref info))
throw new InvalidOperationException("Could not read Files focus.");
return info.Focus;
}
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(0x12, 0, 0, UIntPtr.Zero);
keybd_event(0x12, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
public static void ClickRow(IntPtr list, int row, bool doubleClick) {
Rect rect;
if (SendRect(list, 0x198, new IntPtr(row), out rect).ToInt32() == -1)
throw new InvalidOperationException("Missing listbox row.");
var point = new IntPtr(((rect.Top + rect.Bottom) / 2 << 16) | (rect.Left + 6));
PostMessage(list, 0x201, new IntPtr(1), point);
PostMessage(list, 0x202, IntPtr.Zero, point);
if (doubleClick) {
PostMessage(list, 0x203, new IntPtr(1), point);
PostMessage(list, 0x202, IntPtr.Zero, point);
}
}
}
"@
function Wait-Until([string]$Description, [scriptblock]$Condition) {
$timer = [Diagnostics.Stopwatch]::StartNew()
while ($timer.Elapsed.TotalSeconds -lt 15) {
if (& $Condition) { return }
if ($process -and $process.HasExited) { throw "Files exited while waiting for $Description" }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for $Description"
}
function Read-Text($Control, $Message = 0x0D, $Parameter = 32768) {
$buffer = [Text.StringBuilder]::new(32768)
[void][FilesActivationUi]::Read($Control, $Message, [IntPtr]$Parameter, $buffer)
$buffer.ToString()
}
function Find-Row($List, [string]$Name) {
$count = [FilesActivationUi]::Send($List, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
for ($row = 0; $row -lt $count; $row++) {
if ((Read-Text $List 0x189 $row) -ceq $Name) { return $row }
}
-1
}
function Select-Row($List, [string]$Name, [switch]$DoubleClick) {
Wait-Until "row $Name" { (Find-Row $List $Name) -ge 0 }
$row = Find-Row $List $Name
[void][FilesActivationUi]::Send($List, 0x197, [IntPtr]$row, [IntPtr]::Zero)
[FilesActivationUi]::ClickRow($List, $row, $DoubleClick.IsPresent)
if (!$DoubleClick) {
Wait-Until "selection of $Name" {
[FilesActivationUi]::Focus($window) -eq $inputBox -and
[FilesActivationUi]::Send($List, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq (Find-Row $List $Name)
}
}
}
function Press-Enter($Control) {
[void][FilesActivationUi]::PostMessage($Control, 0x100, [IntPtr]13, [IntPtr]::Zero)
}
function Invoke-Row($List, [string]$Name, [bool]$DoubleClick) {
Select-Row $List $Name -DoubleClick:$DoubleClick
if (!$DoubleClick) { Press-Enter $inputBox }
}
function Send-Terminal([string]$Command) {
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, $Command)
Press-Enter $inputBox
}
function Send-InteractiveTerminal([string]$Command, [string]$EnterKey = '{ENTER}') {
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, $Command)
$keys.SendKeys($EnterKey)
}
function Assert-Open($List, $Target, [bool]$DoubleClick) {
$report = "$Target.opened"
Remove-Item -LiteralPath $report -ErrorAction SilentlyContinue
Invoke-Row $List ([IO.Path]::GetFileName($Target)) $DoubleClick
Wait-Until "launch of $Target (double click: $DoubleClick)" {
(Test-Path -LiteralPath $report) -and [IO.File]::ReadAllText($report) -eq 'opened'
}
}
$unique = [Guid]::NewGuid().ToString('N')
$root = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher test $unique"
$profile = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$classes = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\Classes')
$extension = ".ksfiles$unique"
$progId = "KSwitcher.Files.Test.$unique"
$saved = @{}
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
'ShowDetails', 'StatusFields', 'CommandHistory', 'WindowPlacement'
$process = $null
$trace = $null
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$webviewProfile=$env:WEBVIEW2_USER_DATA_FOLDER
try {
foreach ($name in $profileValues) {
if ($name -in $profile.GetValueNames()) {
$saved[$name] = @($profile.GetValue($name), $profile.GetValueKind($name))
}
}
$leftDir = Join-Path $root 'Left panel'
$rightDir = Join-Path $root 'Right panel'
$app = Join-Path $root 'Application'
New-Item -ItemType Directory -Path $leftDir, $rightDir, $app, "$leftDir\Test folder", "$rightDir\Test folder" | Out-Null
$source = Split-Path (Resolve-Path -LiteralPath $Executable)
$testExe = Join-Path $app 'KSwitcher.Files.exe'
Copy-Item -LiteralPath $Executable -Destination $testExe
Copy-Item -LiteralPath "$source\WebView2Loader.dll", "$source\terminal" -Destination $app -Recurse
$program = Join-Path $leftDir 'Test program.exe'
Copy-Item -LiteralPath $Fixture -Destination $program
$document = Join-Path $(if($SystemOpenOnly -or $TerminalOnly){$leftDir}else{$rightDir}) "Test document$extension"
[IO.File]::WriteAllText($document, 'Document fixture')
$association = $classes.CreateSubKey($extension)
$association.SetValue('', $progId)
$association.Dispose()
$handler = $classes.CreateSubKey("$progId\shell\open\command")
$handler.SetValue('', ('"{0}" "%1"' -f (Resolve-Path -LiteralPath $Fixture).Path))
$handler.Dispose()
[FilesActivationUi]::SHChangeNotify(0x08000000, 0, [IntPtr]::Zero, [IntPtr]::Zero)
$batch = Join-Path $leftDir "Test's script.BAT"
$cmd = Join-Path $rightDir 'Test script.CMD'
[IO.File]::WriteAllLines($batch, @('@echo off', 'echo BAT=%KS_TEST_STATE%'))
[IO.File]::WriteAllLines($cmd, @('@echo off', 'echo CMD=%KS_TEST_STATE%'))
$profile.SetValue('LeftPath', $leftDir)
$profile.SetValue('RightPath', $rightDir)
foreach ($name in 'LeftCursor', 'RightCursor') { $profile.DeleteValue($name, $false) }
foreach ($name in 'LeftWide', 'RightWide', 'ShowDetails') { $profile.SetValue($name, 1) }
$profile.SetValue('StatusFields', 3)
if($TerminalOnly){
$listener=[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$listener.Start()
$port=$listener.LocalEndpoint.Port
$listener.Stop()
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=$port"
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $root 'webview'
}
$process = Start-Process -FilePath $testExe -ArgumentList '--terminal-output-trace' -PassThru
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
$window = $process.MainWindowHandle
$left = [FilesActivationUi]::GetDlgItem($window, 102)
$right = [FilesActivationUi]::GetDlgItem($window, 103)
$status = [FilesActivationUi]::GetDlgItem($window, 144)
$output = [FilesActivationUi]::GetDlgItem($window, 145)
$inputBox = [FilesActivationUi]::FindWindowEx($window, [IntPtr]::Zero, 'Edit', $null)
if($SystemOpenOnly) {
$keys = New-Object -ComObject WScript.Shell
$explorer = New-Object -ComObject Shell.Application
$existingExplorerWindows = @($explorer.Windows() | ForEach-Object { $_.HWND })
Wait-Until 'Files ready for Shift+Enter' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$folderRow=Find-Row $left '[Test folder]'
if($folderRow -lt 0){throw 'The folder fixture is missing.'}
[void][FilesActivationUi]::Send($left,0x186,[IntPtr]$folderRow,[IntPtr]::Zero)
$keys.SendKeys('+{ENTER}')
$folderWindow = $null
Wait-Until 'Shift+Enter opening the selected folder in Explorer' {
$script:folderWindow = $explorer.Windows() | Where-Object {
$_.Document.Folder.Self.Path -eq "$leftDir\Test folder"
} | Select-Object -First 1
$null -ne $script:folderWindow
}
if($folderWindow.HWND -notin $existingExplorerWindows){$folderWindow.Quit()}
if((Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -ne $leftDir){
throw 'Shift+Enter changed the folder in the Files panel.'
}
Wait-Until 'Files active for the registered document test' { [FilesActivationUi]::Activate($window) }
$documentRow=Find-Row $left ([IO.Path]::GetFileName($document))
if($documentRow -lt 0){throw 'The document fixture is missing.'}
[void][FilesActivationUi]::Send($left,0x186,[IntPtr]$documentRow,[IntPtr]::Zero)
Wait-Until 'Files command line focused for document Shift+Enter' {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
$keys.SendKeys('+{ENTER}')
Wait-Until 'Shift+Enter invoking the default Windows file association' {
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
}
Wait-Until 'Files active for plain Enter' { [FilesActivationUi]::Activate($window) }
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
Remove-Item -LiteralPath "$document.opened"
$keys.SendKeys('{ENTER}')
Wait-Until 'plain Enter invoking the default Windows file association' {
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
}
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
Remove-Item -LiteralPath "$document.opened"
}
if($SystemOpenOnly -or $TerminalOnly){
$keys = New-Object -ComObject WScript.Shell
foreach($case in @(
@{Name='enter-panes'; Keys='{ENTER}'},
@{Name='shift-enter-panes'; Keys='+{ENTER}'},
@{Name='enter-terminal'; Keys='{ENTER}'; HidePanes=$true},
@{Name='shift-enter-terminal'; Keys='+{ENTER}'}
)) {
Wait-Until 'Files command line active' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
if($case.HidePanes){
$keys.SendKeys('^o')
Wait-Until 'file panes hidden' { ![FilesActivationUi]::IsWindowVisible($left) }
}
$marker=Join-Path $root "$($case.Name).txt"
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
Send-InteractiveTerminal $command $case.Keys
Wait-Until "$($case.Name) running the command" {
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
!(Read-Text $inputBox)
}
if(Test-Path -LiteralPath "$document.opened"){
throw "$($case.Name) did not give the command line priority."
}
}
Write-Output 'Verified command-line priority for Enter and Shift+Enter with panels visible and hidden.'
if(!$TerminalOnly){return}
foreach($name in 'zzzz-dir-first','zzzz-dir-second'){
[IO.File]::WriteAllText((Join-Path $leftDir $name),'dir marker')
Send-InteractiveTerminal 'dir'
Wait-Until "dir rendering $name in terminal output" {
!(Read-Text $inputBox) -and
(Select-String -LiteralPath $trace -SimpleMatch $name -Quiet -ErrorAction SilentlyContinue)
}
}
$keys.SendKeys('^o')
Wait-Until 'file panes visible again' { [FilesActivationUi]::IsWindowVisible($left) }
$listing=Join-Path $root 'dir-visible.txt'
Send-InteractiveTerminal "dir -Name | Set-Content -LiteralPath '$($listing.Replace("'","''"))'"
Wait-Until 'dir running after restoring the file panes' {
!(Read-Text $inputBox) -and (Test-Path -LiteralPath $listing) -and
([IO.File]::ReadAllLines($listing) -ccontains 'zzzz-dir-second')
}
Write-Output 'Verified repeated dir commands in the same terminal with file panes hidden and visible.'
$marker=Join-Path $root 'webview-enter.txt'
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$command)
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
Wait-Until 'the terminal WebView forwarding Enter to the command line' {
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
!(Read-Text $inputBox)
}
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
Select-Row $left '[Test folder]'
$outputSelection = 'terminal-output-copy-fixture'
Send-InteractiveTerminal "Write-Output '$outputSelection'"
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard = [Windows.Forms.Clipboard]::GetDataObject()
try {
$nativeDraft = "Get-Item -LiteralPath '$leftDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$nativeDraft)
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]0,[IntPtr]4)
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the full command line with a partial selection' {
[Windows.Forms.Clipboard]::GetText() -ceq $nativeDraft
}
$webviewDraft = "Get-Item -LiteralPath '$rightDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$webviewDraft)
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-copy'
if($LASTEXITCODE){throw 'Could not send Ctrl+Insert through the terminal WebView.'}
Wait-Until 'Ctrl+Insert copying the command line with focus in the terminal WebView' {
[Windows.Forms.Clipboard]::GetText() -ceq $webviewDraft
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-select-output'
if($LASTEXITCODE){throw 'Could not select the terminal output fixture.'}
Wait-Until 'focus returned to the command line after selecting terminal output' {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
foreach($key in '^c','^{INSERT}') {
[Windows.Forms.Clipboard]::SetText($webviewDraft)
$keys.SendKeys($key)
Wait-Until "$key copying only the selected terminal output with a command present" {
[Windows.Forms.Clipboard]::GetText() -ceq $outputSelection
}
if ((Read-Text $inputBox) -cne $webviewDraft) { throw 'Copying output changed the command line.' }
}
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the selected folder name when the command line is empty' {
[Windows.Forms.Clipboard]::GetText() -ceq 'Test folder'
}
} finally {
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
Write-Output 'Verified Ctrl+C and Ctrl+Insert copy the selected output, then fall back to the command line or panel.'
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
Wait-Until 'Enter from the terminal opening the selected folder in the pane' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -eq "$leftDir\Test folder"
}
Write-Output 'Verified Enter from the terminal opens the selected folder with an empty command line.'
return
}
Select-Row $left '..'
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr]::Zero, [IntPtr]::Zero)
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]9, [IntPtr]::Zero)
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]40, [IntPtr]::Zero)
Wait-Until 'Tab and Down navigating the right pane with command-line focus' {
[FilesActivationUi]::Focus($window) -eq $inputBox -and
[FilesActivationUi]::Send($right, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq 1 -and
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq (Find-Row $left '..')
}
if ((Read-Text $inputBox) -cne 'draft command') { throw 'Pane navigation changed the command line.' }
$shell = New-Object -ComObject WScript.Shell
$fileName = [IO.Path]::GetFileName($document)
foreach ($name in $fileName, 'Test folder') {
$label = if ($name -eq $fileName) { $name } else { "[$name]" }
Select-Row $right $label
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
[void][FilesActivationUi]::Send($inputBox, 0xB1, [IntPtr]6, [IntPtr]13)
Wait-Until 'Files activation for Ctrl+Enter' {
[FilesActivationUi]::Activate($window) -and
[FilesActivationUi]::Focus($window) -eq $inputBox
}
$shell.SendKeys('^{ENTER}')
$expected = 'draft "{0}"' -f $name
Wait-Until "Ctrl+Enter inserting $name" { (Read-Text $inputBox) -ceq $expected }
}
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, '')
Write-Output 'Tab and Down navigated the panes while preserving command-line focus and text.'
foreach ($double in $false, $true) {
Assert-Open $left $program $double
Assert-Open $right $document $double
}
Invoke-Row $left '[Test folder]' $false
Wait-Until 'folder navigation by Enter' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 142))) -eq "$leftDir\Test folder"
}
Invoke-Row $left '..' $false
Invoke-Row $right '[Test folder]' $true
Wait-Until 'folder navigation by double click' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 143))) -eq "$rightDir\Test folder"
}
Invoke-Row $right '..' $false
Write-Output 'Enter and double-click opened folders, the registered document, and the standalone EXE.'
$sessionValue = $unique.Substring(0, 8)
Send-Terminal ('$global:ksSession = "{0}"; $env:KS_TEST_STATE = $ksSession; "READY=" + $ksSession' -f $sessionValue)
Wait-Until 'initialized terminal session and rendered test marker' {
(Get-Content -LiteralPath $trace -ErrorAction SilentlyContinue) -contains "READY=$sessionValue"
}
Invoke-Row $left ([IO.Path]::GetFileName($batch)) $false
Wait-Until 'visible BAT output with the existing session environment' {
[FilesActivationUi]::IsWindowVisible($output) -and
(Get-Content -LiteralPath $trace) -contains "BAT=$sessionValue"
}
Invoke-Row $right ([IO.Path]::GetFileName($cmd)) $true
Wait-Until 'visible CMD output with the existing session environment' {
[FilesActivationUi]::IsWindowVisible($output) -and
(Get-Content -LiteralPath $trace) -contains "CMD=$sessionValue"
}
Send-Terminal '"AFTER=" + $global:ksSession'
Wait-Until 'unchanged PowerShell session state' {
(Get-Content -LiteralPath $trace) -contains "AFTER=$sessionValue"
}
Assert-Open $left $program $false
Write-Output 'BAT and CMD ran in the existing terminal and rendered their output.'
$external = 'External change.txt'
Select-Row $left ([IO.Path]::GetFileName($program))
foreach ($dir in $leftDir, $rightDir) { [IO.File]::WriteAllText((Join-Path $dir $external), 'one') }
Wait-Until 'external creation in both panels' {
(Find-Row $left $external) -ge 0 -and (Find-Row $right $external) -ge 0
}
if ([FilesActivationUi]::Focus($window) -ne $inputBox -or
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne
(Find-Row $left ([IO.Path]::GetFileName($program)))) { throw 'Creation moved focus or selection.' }
foreach ($panel in @(@{ List = $left; Dir = $leftDir }, @{ List = $right; Dir = $rightDir })) {
Select-Row $panel.List $external
Wait-Until 'initial file size' { (Read-Text $status) -match ' 3 B$' }
[IO.File]::AppendAllText((Join-Path $panel.Dir $external), 'two!')
Wait-Until 'updated file size' { (Read-Text $status) -match ' 7 B$' }
if ([FilesActivationUi]::Focus($window) -ne $inputBox) { throw 'Modification moved focus.' }
}
foreach ($dir in $leftDir, $rightDir) { [IO.File]::Delete((Join-Path $dir $external)) }
Wait-Until 'external deletion in both panels' {
(Find-Row $left $external) -eq -1 -and (Find-Row $right $external) -eq -1
}
if ([FilesActivationUi]::Focus($window) -ne $inputBox) { throw 'Deletion moved focus.' }
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard=[Windows.Forms.Clipboard]::GetDataObject()
$programName=[IO.Path]::GetFileName($program)
$expectedNames="Test folder`r`n$programName"
try {
Select-Row $left '[Test folder]'
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
Select-Row $left $programName
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
Wait-Until 'Files activation for Ctrl+Insert' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
[Windows.Forms.Clipboard]::GetText() -ceq $expectedNames
}
Select-Row $right $fileName
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
[Windows.Forms.Clipboard]::GetText() -ceq $fileName
}
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
} finally {
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
$sizeA=Join-Path $rightDir 'Size A'
$sizeB=Join-Path $rightDir 'Size B'
$sizeC=Join-Path $rightDir 'Size C'
New-Item -ItemType Directory -Path "$sizeA\nested", $sizeB, $sizeC | Out-Null
[IO.File]::WriteAllBytes("$sizeA\file.bin",[byte[]]::new(4))
[IO.File]::WriteAllBytes("$sizeA\nested\file.bin",[byte[]]::new(7))
[IO.File]::WriteAllBytes("$sizeB\file.bin",[byte[]]::new(23))
[IO.File]::WriteAllBytes("$sizeC\file.bin",[byte[]]::new(31))
Select-Row $right '[Size A]'
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
Wait-Until 'F3 recursive size for the current folder' { (Read-Text $status) -ceq 'Size A 11 B' }
foreach($name in 'Size A','Size B'){
Select-Row $right "[$name]"
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
}
Select-Row $right '[Size C]'
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
Wait-Until 'completion of the marked size batch' { (Read-Text $status) -ceq 'Size C Folder' }
Select-Row $right '[Size B]'
Wait-Until 'F3 size for a marked folder' { (Read-Text $status) -ceq 'Size B 23 B' }
Select-Row $right '[Size C]'
if ((Read-Text $status) -cne 'Size C Folder') { throw 'F3 measured the unmarked cursor folder.' }
Select-Row $right $fileName
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
$viewerTitle='Viewer '+[char]0x2014+" $document"
Wait-Until 'F3 opening a file when folders are marked' {
[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle) -ne [IntPtr]::Zero
}
$viewer=[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle)
[void][FilesActivationUi]::PostMessage($viewer,0x10,[IntPtr]::Zero,[IntPtr]::Zero)
Write-Output 'F3 measured the current folder recursively and measured marked folders without measuring the unmarked cursor folder.'
Select-Row $right '[Size B]'
Wait-Until 'Files activation for Ctrl+R' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$shell.SendKeys('^r')
Wait-Until 'Ctrl+R clearing the measured size and retaining the current folder' {
(Read-Text $status) -ceq 'Size B Folder' -and
[FilesActivationUi]::Send($right,0x188,[IntPtr]::Zero,[IntPtr]::Zero).ToInt32() -eq
(Find-Row $right '[Size B]')
}
Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.'
} catch {
if ($inputBox -and $status) {
Write-Output "Command input length: $((Read-Text $inputBox).Length). Status: $(Read-Text $status)"
}
if ($trace -and (Test-Path -LiteralPath $trace)) {
Get-Content -LiteralPath $trace -Tail 25
}
throw
} finally {
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=$webviewFlags
$env:WEBVIEW2_USER_DATA_FOLDER=$webviewProfile
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
if (!$process.WaitForExit(4000)) { $process.Kill(); $process.WaitForExit() }
}
foreach ($name in $profileValues) {
if ($saved.ContainsKey($name)) { $profile.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $profile.DeleteValue($name, $false) }
}
$profile.Dispose()
$classes.DeleteSubKeyTree($extension, $false)
$classes.DeleteSubKeyTree($progId, $false)
$classes.Dispose()
[FilesActivationUi]::SHChangeNotify(0x08000000, 0, [IntPtr]::Zero, [IntPtr]::Zero)
if ($trace) { Remove-Item -LiteralPath $trace -ErrorAction SilentlyContinue }
$resolvedRoot = Resolve-Path -LiteralPath $root -ErrorAction SilentlyContinue
$tempPrefix = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\'
if ($resolvedRoot -and $resolvedRoot.Path.StartsWith($tempPrefix, [StringComparison]::OrdinalIgnoreCase)) {
Remove-Item -LiteralPath $resolvedRoot.Path -Recurse -Force -ErrorAction SilentlyContinue
}
}
+19
View File
@@ -0,0 +1,19 @@
#include <windows.h>
#include <filesystem>
#include <fstream>
int wmain(int argc,wchar_t **argv)
{
// A launch through the embedded terminal would inherit its console.
DWORD consoleProcesses[1]{};
if(GetConsoleProcessList(consoleProcesses,1)>1) return 1;
wchar_t executable[32768]{};
const auto length=GetModuleFileNameW(nullptr,executable,static_cast<DWORD>(std::size(executable)));
if(!length || length>=std::size(executable)) return 1;
const std::filesystem::path target=argc==2?argv[1]:executable;
auto report=target;
report+=L".opened";
std::ofstream result(report,std::ios::binary);
result<<"opened";
return result?0:1;
}
+478
View File
@@ -0,0 +1,478 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$Screenshot,
[string]$SearchScreenshot,
[string]$Node = 'node',
[string]$LanFixture
)
$ErrorActionPreference = 'Stop'
Add-Type @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class MarkdownUi {
[StructLayout(LayoutKind.Sequential)]
struct PropertyKey {
public Guid Format;
public uint Id;
}
[StructLayout(LayoutKind.Explicit, Size = 24)]
struct PropertyValue {
[FieldOffset(0)] public ushort Type;
[FieldOffset(8)] public IntPtr Text;
}
[ComImport, Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IPropertyStore {
void GetCount(out uint count);
void GetAt(uint index, out PropertyKey key);
void GetValue(ref PropertyKey key, out PropertyValue value);
}
[DllImport("shell32.dll", PreserveSig = false)]
static extern void SHGetPropertyStoreForWindow(IntPtr window, ref Guid iid, out IPropertyStore store);
[DllImport("ole32.dll")] static extern int PropVariantClear(ref PropertyValue value);
public static string TaskbarProperty(IntPtr window, uint property) {
var iid = typeof(IPropertyStore).GUID;
var key = new PropertyKey { Format = new Guid("9f4c2855-9f79-4b39-a8d0-e1d42de1d5f3"), Id = property };
SHGetPropertyStoreForWindow(window, ref iid, out var store);
try {
store.GetValue(ref key, out var value);
try { return value.Type == 31 ? Marshal.PtrToStringUni(value.Text) : null; }
finally { PropVariantClear(ref value); }
} finally { Marshal.ReleaseComObject(store); }
}
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
public static void Activate(IntPtr window) {
if (GetForegroundWindow() == window) return;
keybd_event(0x12,0,0,UIntPtr.Zero);
keybd_event(0x12,0,2,UIntPtr.Zero);
SetForegroundWindow(window);
}
public static void CycleWindow() {
keybd_event(0x11,0,0,UIntPtr.Zero);
keybd_event(0x09,0,0,UIntPtr.Zero);
keybd_event(0x09,0,2,UIntPtr.Zero);
keybd_event(0x11,0,2,UIntPtr.Zero);
}
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr window, StringBuilder title, int capacity);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SendText(IntPtr window, uint msg, IntPtr w, string l);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
}
"@
function Wait-For([string]$Name, [scriptblock]$Check) {
for ($i=0; $i -lt 150; $i++) {
$value = & $Check
if ($value) { return $value }
Start-Sleep -Milliseconds 100
}
throw "Timed out waiting for $Name"
}
function Find-Window([string]$Class, [string]$Title = '', [IntPtr]$Except = 0) {
$window = [IntPtr]::Zero
while (($window = [MarkdownUi]::FindWindowEx(0,$window,$Class,[NullString]::Value)) -ne [IntPtr]::Zero) {
[uint32]$pidFound = 0
[void][MarkdownUi]::GetWindowThreadProcessId($window,[ref]$pidFound)
if ($pidFound -ne $process.Id -or $window -eq $Except -or ![MarkdownUi]::IsWindowVisible($window)) { continue }
$buffer = [Text.StringBuilder]::new(2048)
[void][MarkdownUi]::GetWindowText($window,$buffer,$buffer.Capacity)
if ($buffer.ToString() -like "*$Title*") { return $window }
}
}
function Post($Window, $Message, $Key) {
if (![MarkdownUi]::PostMessage($Window,$Message,$Key,0)) { throw 'Could not drive the Files window.' }
}
function Open-File($File, $Key) {
$row = [MarkdownUi]::SendText($panel,0x1A2,-1,$File)
if ($row.ToInt64() -lt 0) { throw "Missing row $File" }
[void][MarkdownUi]::Send($panel,0x186,$row,0)
Post $panel 0x100 $Key
}
function Browser($Scenario, $Image = '', $Title = '') {
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port $Scenario $Image $Title
if ($LASTEXITCODE) { throw "WebView2 verification failed for $Scenario" }
}
function Wait-Foreground($Window) {
$buffer = [Text.StringBuilder]::new(2048)
[void][MarkdownUi]::GetWindowText($Window,$buffer,$buffer.Capacity)
[void](Wait-For "foreground window $buffer" { [MarkdownUi]::GetForegroundWindow() -eq $Window })
}
function Scintilla($Window) {
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
}
function Assert-TextWindowAppearance($Window, [string]$Mode) {
$identity = "HrynCo.KSwitcher.Files.$Mode"
$resource = if($Mode -eq 'Editor') { ',-104' } else { ',-103' }
[void](Wait-For "the $Mode taskbar group" { [MarkdownUi]::TaskbarProperty($Window,5) -ceq $identity })
$taskbarIcon = [MarkdownUi]::TaskbarProperty($Window,3)
if (!$taskbarIcon -or !$taskbarIcon.EndsWith($resource)) {
throw "$Mode taskbar icon was '$taskbarIcon'."
}
$small = [MarkdownUi]::Send($Window,0x7f,0,0)
$large = [MarkdownUi]::Send($Window,0x7f,1,0)
if (!$small.ToInt64() -or !$large.ToInt64() -or $small -eq $large) {
throw "$Mode must expose both a small title-bar icon and a large switcher icon."
}
@{ Small = $small; Large = $large }
}
function Append-Character($Control, [char]$Character) {
[void][MarkdownUi]::Send($Control,2318,0,0)
[void][MarkdownUi]::Send($Control,0x102,[int]$Character,0)
}
function Answer-Save($Button) {
$dialog = Wait-For 'the save confirmation' {
$candidate = Find-Window '#32770'
if ($candidate -and [MarkdownUi]::GetDlgItem($candidate,7) -ne [IntPtr]::Zero) { $candidate }
}
Post $dialog 0x111 $Button
[void](Wait-For 'the save confirmation to close' { ![MarkdownUi]::IsWindowVisible($dialog) })
}
$source = Split-Path (Resolve-Path -LiteralPath $Executable)
$root = Join-Path ([IO.Path]::GetTempPath()) ('ks-markdown-test-' + [Guid]::NewGuid().ToString('N'))
$app = Join-Path $root 'app'
$docs = Join-Path $root 'docs'
$profileCaptured = $false
$profile = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$saved = @{}
$profileValues = 'LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement','OptionsLocation'
$process = $null
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$data = $env:WEBVIEW2_USER_DATA_FOLDER
try {
New-Item -ItemType Directory -Path $app,$docs,"$docs\child","$docs\images" | Out-Null
Copy-Item -LiteralPath $Executable,"$source\WebView2Loader.dll","$source\terminal" -Destination $app -Recurse
$fixture = @'
# Перегляд Markdown
| Header |
| ------ |
| Cell |
| <span id="nowrap-cell" style="white-space: nowrap; color: red; position: fixed" onclick="void 0">In Development</span> |
<table id="html-table">
<caption>Raw HTML table</caption>
<tr><th colspan="2">Priority</th></tr>
<tr><td><strong>Highest</strong></td><td>—</td></tr>
</table>
- [ ] Pending
- [x] Complete
## Збіг пошуку
Рядок для **збіг пошуку**.
![Relative image](images/tiny%20image.png)
![Missing image](images/missing.png)
<img alt="HTML relative image" src="images/tiny%20image.png">
<a href="child/Other.md#target-heading">Child</a>
~~~mermaid
flowchart TD
A[Render target] --> B[Result]
~~~
~~~mermaid
this is not a diagram
~~~
~~~js
const value = 42;
~~~
<iframe src="https://example.invalid">Raw HTML</iframe>
'@
$original = Join-Path $docs 'Preview.md'
[IO.File]::WriteAllText($original,$fixture)
$childText = '# Linked Markdown' + "`n`n" + (("Filler paragraph.`n`n") * 60) + '## Target heading'
[IO.File]::WriteAllText("$docs\child\Other.md",$childText)
[IO.File]::WriteAllText("$docs\Plain.txt",'Plain text')
$largeFile = [IO.File]::Create("$docs\Large.md")
try {
$line = [Text.Encoding]::UTF8.GetBytes(("# Large Markdown file`n" * 1024))
while ($largeFile.Length -le 8MB) { $largeFile.Write($line,0,$line.Length) }
} finally { $largeFile.Dispose() }
[IO.File]::WriteAllBytes("$docs\images\tiny image.png",[Convert]::FromBase64String(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jBo0AAAAASUVORK5CYII='))
foreach ($name in $profileValues) {
if ($name -in $profile.GetValueNames()) {
$saved[$name] = @($profile.GetValue($name),$profile.GetValueKind($name))
}
}
$profileCaptured = $true
$profile.SetValue('LeftPath',$docs)
$profile.SetValue('RightPath',$docs)
foreach ($name in 'LeftCursor','RightCursor','WindowPlacement','OptionsLocation') { $profile.DeleteValue($name,$false) }
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$listener.Start()
$port = $listener.LocalEndpoint.Port
$listener.Stop()
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = "--remote-debugging-port=$port --disable-background-networking"
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'webview'
$process = Start-Process -FilePath (Join-Path $app (Split-Path -Leaf $Executable)) -PassThru -WindowStyle Normal
$main = Wait-For 'Files' { Find-Window 'KSwitcher.Files' }
[MarkdownUi]::Activate($main)
$panel = [MarkdownUi]::GetDlgItem($main,102)
Open-File 'Preview.md' 0x72
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
if ([MarkdownUi]::IsWindowVisible((Scintilla $window))) {
throw 'F3 showed the source text while starting the Markdown preview.'
}
Browser 'render' $Screenshot
Post $window 0x111 3
Browser 'search-menu'
Browser 'search' $SearchScreenshot
Post $main 0x111 133
$options = Wait-For 'the shared Files Options dialog' { Find-Window '#32770' 'KSwitcher Files Options' }
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,270),0x0C,0,'Markdown')
[void](Wait-For 'the Markdown settings section' { [MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374)) })
foreach($field in @(@(374,'1200'),@(376,'Georgia'),@(379,'18'))){
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,$field[0]),0x0C,0,$field[1])
}
Post $options 0x111 1
[void](Wait-For 'Options to close after saving Markdown settings' { ![MarkdownUi]::IsWindowVisible($options) })
Browser 'appearance-width'
Post $main 0x111 133
$options = Wait-For 'reopened Files Options' { Find-Window '#32770' 'KSwitcher Files Options' }
if (![MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374))) {
throw 'Files Options did not restore its last section.'
}
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,374),0x0C,0,'0')
Post $options 0x111 2
[void](Wait-For 'Options to close on Cancel' { ![MarkdownUi]::IsWindowVisible($options) })
Browser 'appearance-width'
Post $main 0x111 133
$options = Wait-For 'Files Options after Cancel' { Find-Window '#32770' 'KSwitcher Files Options' }
if (![MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374))) {
throw 'Cancel did not preserve the last Options section.'
}
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,374),0x0C,0,'0')
Post $options 0x111 1
[void](Wait-For 'Options to close after saving full width' { ![MarkdownUi]::IsWindowVisible($options) })
Browser 'appearance-full'
Write-Output 'Verified live Markdown width and font settings, Cancel and reopening the last Options section.'
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Checking a task modified the read-only file.' }
[IO.File]::WriteAllText($original,($fixture.Replace('Перегляд Markdown','Зміна на диску')))
Browser 'Зміна на диску' '' 'Preview.md'
$replacement = Join-Path $docs 'Preview-replacement.md'
[IO.File]::WriteAllText($replacement,$fixture)
[IO.File]::Move($replacement,$original,$true)
Browser 'Перегляд Markdown' '' 'Preview.md'
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window) { throw 'Reload changed windows.' }
Browser 'edit'
$editor = Wait-For 'F6 in WebView2 to open the editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
if ($editor -ne $window) { throw 'F6 changed windows.' }
$editorIcons = Assert-TextWindowAppearance $window 'Editor'
if ($editorIcons.Small -eq $viewerIcons.Small -or $editorIcons.Large -eq $viewerIcons.Large) {
throw 'F6 did not replace both viewer icons with editor icons.'
}
[MarkdownUi]::Activate($window)
Wait-Foreground $window
[MarkdownUi]::CycleWindow()
Wait-Foreground $main
[MarkdownUi]::CycleWindow()
Wait-Foreground $window
Write-Output 'Verified Ctrl+Tab between Files and the Markdown editor.'
$control = Scintilla $window
if ([MarkdownUi]::Send($control,2140,0,0).ToInt64()) { throw 'The editor is read-only.' }
Append-Character $control 'X'
Post $control 0x100 0x75
Answer-Save 2
if ((Find-Window 'KSwitcher.Files.Text' 'Editor') -ne $window -or ![MarkdownUi]::Send($control,2159,0,0).ToInt64()) {
throw 'Cancel lost unsaved changes.'
}
Post $control 0x100 0x75
Answer-Save 7
Browser 'Перегляд Markdown'
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
if ($viewerIcons.Small -eq $editorIcons.Small -or $viewerIcons.Large -eq $editorIcons.Large) {
throw 'F6 did not restore both viewer icons.'
}
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Discard changed the Markdown file.' }
Browser 'ctrl-follow'
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window -or (Find-Window 'KSwitcher.Files.Text' 'Other.md')) {
throw 'Ctrl+click navigated without tabs.'
}
Browser 'shift-follow'
$child = Wait-For 'the Shift+click Markdown window' { Find-Window 'KSwitcher.Files.Text' 'Other.md' $window }
[void](Assert-TextWindowAppearance $child 'Viewer')
Browser 'Linked Markdown' '' 'Other.md'
[MarkdownUi]::Activate($child)
Wait-Foreground $child
Browser 'cycle' '' 'Other.md'
Wait-Foreground $main
[MarkdownUi]::CycleWindow()
Wait-Foreground $window
Browser 'cycle' '' 'Preview.md'
Wait-Foreground $child
Browser 'close' '' 'Other.md'
[void](Wait-For 'Ctrl+W to close the Shift+click window' { ![MarkdownUi]::IsWindowVisible($child) })
Browser 'follow'
if ((Wait-For 'the in-place Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
throw 'A normal click did not stay in the same window.'
}
Browser 'Linked Markdown' '' 'Other.md'
Browser 'mouse-back' '' 'Other.md'
Browser 'Перегляд Markdown' '' 'Preview.md'
Browser 'mouse-forward' '' 'Preview.md'
Browser 'Linked Markdown' '' 'Other.md'
Browser 'back' '' 'Other.md'
Browser 'Перегляд Markdown' '' 'Preview.md'
Browser 'forward' '' 'Preview.md'
Browser 'Linked Markdown' '' 'Other.md'
Browser 'close' '' 'Other.md'
[void](Wait-For 'the Markdown viewers to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Preview.md' 0x73
$window = Wait-For 'F4 to open the Markdown editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
[void](Assert-TextWindowAppearance $window 'Editor')
Write-Output 'Verified F3/F4 icons, separate taskbar groups and regrouping when the same window switches modes with F6.'
$control = Scintilla $window
Append-Character $control 'Y'
Post $control 0x100 0x75
Answer-Save 6
Browser 'Перегляд Markdown'
Browser 'appearance-full'
if (![IO.File]::ReadAllText($original).EndsWith('Y')) { throw 'F6 rendered before saving.' }
Post $window 0x10 0
[void](Wait-For 'the saved Markdown viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Preview.md' 0x73
$window = Wait-For 'the editor before a save conflict' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
$control = Scintilla $window
Append-Character $control 'Z'
[IO.File]::Move($original,"$docs\replaced.md")
[IO.File]::WriteAllText($original,'An external replacement')
Post $control 0x100 0x75
Answer-Save 6
$errorDialog = Wait-For 'a save conflict error' {
$candidate = Find-Window '#32770'
if ($candidate -and [MarkdownUi]::GetDlgItem($candidate,1) -ne [IntPtr]::Zero) { $candidate }
}
Post $errorDialog 0x111 1
if ((Find-Window 'KSwitcher.Files.Text' 'Editor') -ne $window -or
[MarkdownUi]::Send($control,2140,0,0).ToInt64() -or
[IO.File]::ReadAllText($original) -cne 'An external replacement') {
throw 'The failed save left editing mode or overwrote an externally replaced file.'
}
Post $control 0x100 0x75
Answer-Save 7
Post $window 0x10 0
[void](Wait-For 'the conflict fixture to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Plain.txt' 0x72
$window = Wait-For 'plain-text viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
$control = Scintilla $window
[void](Wait-For 'plain-text read-only view' { [MarkdownUi]::Send($control,2140,0,0).ToInt64() })
Post $control 0x100 0x75
[void](Wait-For 'F6 plain-text editor' { !( [MarkdownUi]::Send($control,2140,0,0).ToInt64() ) })
Post $control 0x100 0x75
[void](Wait-For 'F6 plain-text viewer' { [MarkdownUi]::Send($control,2140,0,0).ToInt64() })
Post $window 0x10 0
[void](Wait-For 'plain-text viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Large.md' 0x72
$window = Wait-For 'large Markdown text fallback' { Find-Window 'KSwitcher.Files.Text' 'Large.md' }
$control = Scintilla $window
if (![MarkdownUi]::IsWindowVisible($control) -or ![MarkdownUi]::Send($control,2140,0,0).ToInt64()) {
throw 'Large Markdown did not open in the text viewer.'
}
Post $window 0x10 0
[void](Wait-For 'large-file viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
$previewPage = Join-Path $app 'terminal\markdown.html'
[IO.File]::Move($previewPage,"$previewPage.disabled")
try {
Open-File 'Preview.md' 0x72
$window = Wait-For 'text fallback without preview assets' { Find-Window 'KSwitcher.Files.Text' 'Preview.md' }
$control = Scintilla $window
if (![MarkdownUi]::IsWindowVisible($control) -or ![MarkdownUi]::Send($control,2140,0,0).ToInt64()) {
throw 'Markdown did not open in the text viewer when preview assets were missing.'
}
} finally { [IO.File]::Move("$previewPage.disabled",$previewPage) }
Write-Output 'Verified Markdown rendering, Mermaid, task checkboxes, local relative resources, F3/F4, F6 Save/Discard/Cancel/save failure and text fallback.'
if ($LanFixture) {
Post $window 0x10 0
Post $main 0x10 0
if (!$process.WaitForExit(5000)) { throw 'Files did not close before the LAN check.' }
[IO.File]::WriteAllText($original,$fixture)
$lanExe = Join-Path $app 'KSwitcherFilesMarkdownLanFixture.exe'
Copy-Item -LiteralPath $LanFixture -Destination $lanExe
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'lan-webview'
$process = Start-Process -FilePath $lanExe -ArgumentList ('"{0}"' -f $original) -PassThru -WindowStyle Normal
$window = Wait-For 'the LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Loopback peer' }
[void](Assert-TextWindowAppearance $window 'Viewer')
Browser 'render'
Browser 'search'
Browser 'edit'
if ((Wait-For 'LAN F6 editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }) -ne $window) {
throw 'LAN F6 changed windows.'
}
[void](Assert-TextWindowAppearance $window 'Editor')
$control = Scintilla $window
Append-Character $control 'L'
Post $control 0x100 0x75
Browser 'Перегляд Markdown'
if (![IO.File]::ReadAllText($original).EndsWith('L')) { throw 'F6 rendered before uploading the LAN edit.' }
Browser 'follow'
if ((Wait-For 'the in-place LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
throw 'A LAN link did not stay in the same window.'
}
Browser 'Linked Markdown' '' 'Other.md'
Browser 'back' '' 'Other.md'
Browser 'Перегляд Markdown' '' 'Preview.md'
Browser 'forward' '' 'Preview.md'
Browser 'Linked Markdown' '' 'Other.md'
Browser 'close' '' 'Other.md'
if (!$process.WaitForExit(5000) -or $process.ExitCode) { throw 'The LAN fixture did not close normally.' }
Write-Output 'Verified Markdown, Mermaid, relative links/images and F6 saving through an authenticated loopback LAN connection.'
}
} finally {
if ($process -and !$process.HasExited) {
Stop-Process -Id $process.Id
[void]$process.WaitForExit(5000)
}
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags
$env:WEBVIEW2_USER_DATA_FOLDER = $data
if ($profileCaptured) {
foreach ($name in $profileValues) {
if ($saved.ContainsKey($name)) { $profile.SetValue($name,$saved[$name][0],$saved[$name][1]) }
else { $profile.DeleteValue($name,$false) }
}
}
$profile.Dispose()
if (Test-Path -LiteralPath $root) {
$resolved = (Resolve-Path -LiteralPath $root).Path
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-markdown-test-*') {
for ($attempt=0; $attempt -lt 40 -and (Test-Path -LiteralPath $resolved); ++$attempt) {
try { Remove-Item -LiteralPath $resolved -Recurse -Force }
catch {
if ($attempt -eq 39) { throw }
Start-Sleep -Milliseconds 250
}
}
}
}
}
+226
View File
@@ -0,0 +1,226 @@
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
const [port, scenario, artifact, title] = process.argv.slice(2);
const terminalScenario = ['terminal-enter', 'terminal-copy', 'terminal-select-output'].includes(scenario);
let socket;
const pending = new Map();
let sequence = 0;
async function waitFor(callback, label) {
for (let i = 0; i < 150; ++i) {
const result = await callback();
if (result) return result;
await delay(100);
}
throw new Error('Timed out waiting for ' + label);
}
function command(method, params = {}) {
const id = ++sequence;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error('DevTools timed out on ' + method));
}, 5000);
pending.set(id, reply => {
clearTimeout(timer);
if (reply.error) reject(new Error(reply.error.message));
else resolve(reply.result);
});
socket.send(JSON.stringify({ id, method, params }));
});
}
async function evaluate(expression) {
const reply = await command('Runtime.evaluate', { expression, returnByValue: true });
if (reply.exceptionDetails) throw new Error(reply.exceptionDetails.exception.description);
return reply.result.value;
}
async function pressKey(key, code, windowsVirtualKeyCode, modifiers = 0) {
const params = { key, code, windowsVirtualKeyCode, modifiers };
await command('Input.dispatchKeyEvent', { type: 'keyDown', ...params });
await command('Input.dispatchKeyEvent', { type: 'keyUp', ...params });
}
const target = await waitFor(async () => {
const response = await fetch('http://127.0.0.1:' + port + '/json/list').catch(() => null);
if (!response?.ok) return;
const url = terminalScenario
? 'https://kswitcher-terminal.invalid/index.html'
: 'https://kswitcher-markdown.invalid/markdown.html';
return (await response.json()).find(item => item.url === url &&
(!title || item.title === title));
}, 'the target WebView2 page');
socket = new WebSocket(target.webSocketDebuggerUrl);
socket.addEventListener('message', event => {
const reply = JSON.parse(event.data);
const callback = pending.get(reply.id);
if (callback) {
pending.delete(reply.id);
callback(reply);
}
});
await new Promise((resolve, reject) => {
socket.addEventListener('open', resolve, { once: true });
socket.addEventListener('error', reject, { once: true });
});
try {
if (scenario === 'terminal-select-output') {
const selection = await waitFor(() => evaluate(`(() => {
const marker = 'terminal-output-copy-fixture';
const buffer = terminal.buffer.active;
for (let row = buffer.viewportY; row < buffer.viewportY + terminal.rows; row++) {
if (buffer.getLine(row)?.translateToString(true) !== marker) continue;
terminal.select(0, row, marker.length);
document.querySelector('#terminal').dispatchEvent(new PointerEvent('pointerup', { bubbles:true }));
return terminal.getSelection();
}
})()`), 'the terminal output fixture');
assert.equal(selection, 'terminal-output-copy-fixture');
} else if (terminalScenario) {
await evaluate('document.querySelector(".xterm-helper-textarea").focus()');
const key = scenario === 'terminal-copy'
? { key:'Insert', code:'Insert', modifiers:2, windowsVirtualKeyCode:45 }
: { key:'Enter', code:'Enter', windowsVirtualKeyCode:13 };
await command('Input.dispatchKeyEvent', { type:'keyDown', ...key });
await command('Input.dispatchKeyEvent', { type:'keyUp', ...key });
} else if (scenario === 'render') {
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
!!document.querySelector('figure svg') &&
document.querySelector('img')?.naturalWidth === 1`), 'rendered Mermaid SVG and relative image');
assert.equal(await evaluate(`document.querySelector('h1').textContent`), 'Перегляд Markdown');
assert.equal(await evaluate(`[...document.querySelectorAll('nav button')].every(button => {
const style = getComputedStyle(button);
return style.borderTopWidth === '0px' && style.backgroundColor === 'rgba(0, 0, 0, 0)';
})`), true);
assert.equal(await evaluate(`document.querySelector('td').textContent`), 'Cell');
assert.deepEqual(await evaluate(`(() => {
const span = document.querySelector('td #nowrap-cell');
return span && [span.textContent, getComputedStyle(span).whiteSpace,
getComputedStyle(span).color, span.style.position, span.hasAttribute('onclick')];
})()`), ['In Development', 'nowrap', 'rgb(255, 0, 0)', '', false]);
assert.deepEqual(await evaluate(`(() => {
const table = document.querySelector('#html-table');
return table && [table.caption.textContent, table.querySelector('th').colSpan,
table.querySelector('td strong').textContent];
})()`), ['Raw HTML table', 2, 'Highest']);
await waitFor(() => evaluate(`document.querySelector('img[alt="HTML relative image"]')?.naturalWidth === 1`),
'the relative image in HTML');
assert.equal(await evaluate(`document.querySelector('figure svg').getBoundingClientRect().height > 0`), true);
assert.equal(await evaluate(`document.querySelector('figure svg').textContent.includes('Render target')`), true);
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
document.querySelector('main').textContent.includes('Invalid Mermaid diagram')`), true);
assert.equal(await evaluate(`!!document.querySelector('pre code.language-js') && !document.querySelector('iframe')`), true);
assert.equal(await evaluate(`performance.getEntriesByType('resource')
.every(entry => entry.name.startsWith(location.origin + '/') || entry.name.startsWith('data:'))`), true);
await waitFor(() => evaluate(`document.querySelector('img[alt="Missing image"]')?.title === 'Image unavailable'`),
'missing image feedback');
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => box.checked)`), [false, true]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [true, false]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [false, true]);
if (artifact) {
const { cssContentSize } = await command('Page.getLayoutMetrics');
const { data } = await command('Page.captureScreenshot', { captureBeyondViewport: true,
clip: { x:0, y:0, width:cssContentSize.width, height:Math.min(cssContentSize.height, 620), scale:1 } });
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} else if (scenario === 'search-menu' || scenario === 'search') {
const searchFocused = 'document.activeElement === document.getElementById("search-query")';
const searchClosed = 'document.getElementById("search").hidden';
if (scenario === 'search-menu') {
await waitFor(() => evaluate(searchFocused), 'the viewer menu opening rendered Markdown search');
await pressKey('Escape', 'Escape', 27);
await waitFor(() => evaluate(searchClosed), 'Escape closing only the search');
} else {
await pressKey('f', 'KeyF', 70, 2);
await waitFor(() => evaluate(searchFocused), 'Ctrl+F opening search and focusing the search field');
const status = 'document.getElementById("search-status").value';
const active = '[...(CSS.highlights.get("markdown-search-active") || [])][0]?.toString()';
const query = async text => {
await evaluate('document.getElementById("search-query").select()');
await command('Input.insertText', { text });
};
await query('ЗБІГ ПОШУКУ');
assert.equal(await evaluate(status), '1 / 2');
const toolbar = await evaluate(`({
queryWidth: document.getElementById('search-query').getBoundingClientRect().width,
closeRight: document.getElementById('search-close').getBoundingClientRect().right,
viewportWidth: document.documentElement.clientWidth
})`);
assert.ok(toolbar.queryWidth >= 100 && toolbar.closeRight <= toolbar.viewportWidth,
'The search controls must fit the viewer: ' + JSON.stringify(toolbar));
assert.equal(await evaluate(active), 'Збіг пошуку');
await pressKey('Enter', 'Enter', 13);
assert.equal(await evaluate(status), '2 / 2');
assert.equal(await evaluate(active), 'збіг пошуку');
await pressKey('F3', 'F3', 114);
assert.equal(await evaluate(status), '1 / 2');
await pressKey('Enter', 'Enter', 13, 8);
assert.equal(await evaluate(status), '2 / 2');
await pressKey('F3', 'F3', 114, 8);
assert.equal(await evaluate(status), '1 / 2');
await evaluate('document.getElementById("search-previous").click()');
assert.equal(await evaluate(status), '2 / 2');
await evaluate('document.getElementById("search-next").click()');
assert.equal(await evaluate(status), '1 / 2');
if (artifact) {
const { data } = await command('Page.captureScreenshot');
await writeFile(artifact, Buffer.from(data, 'base64'));
}
await query('для збіг пошуку');
assert.equal(await evaluate(status), '1 / 1');
assert.equal(await evaluate(active), 'для збіг пошуку');
await query('RENDER TARGET');
assert.equal(await evaluate(status), '1 / 1');
assert.equal(await evaluate(active), 'Render target');
await query('[no matches]');
assert.equal(await evaluate(status), 'No matches');
assert.equal(await evaluate(active), undefined);
await pressKey('Escape', 'Escape', 27);
assert.equal(await evaluate(searchClosed), true);
assert.equal(await evaluate('document.documentElement.classList.contains("rendered")'), true);
await evaluate('document.getElementById("search-open").click()');
assert.equal(await evaluate(searchFocused), true);
await evaluate('document.getElementById("search-close").click()');
assert.equal(await evaluate(searchClosed), true);
}
} else if (scenario === 'appearance-width' || scenario === 'appearance-full') {
const width = scenario === 'appearance-full' ? 'none' : '1200px';
await waitFor(() => evaluate(`(() => {
const text = getComputedStyle(document.querySelector('main'));
return getComputedStyle(document.body).maxWidth === ${JSON.stringify(width)} &&
text.fontSize === '24px' && text.fontFamily.startsWith('Georgia,');
})()`), 'the saved Markdown width, font family and font size');
} else if (scenario === 'edit') {
await command('Input.dispatchKeyEvent', { type: 'keyDown', key: 'F6', code: 'F6', windowsVirtualKeyCode: 117 });
} else if (['follow', 'shift-follow', 'ctrl-follow'].includes(scenario)) {
await evaluate(`document.querySelector('a[href^="child/"]').dispatchEvent(new MouseEvent('click', {
bubbles: true, cancelable: true, shiftKey: ${scenario === 'shift-follow'}, ctrlKey: ${scenario === 'ctrl-follow'}
}))`);
} else if (scenario === 'mouse-back' || scenario === 'mouse-forward') {
const button = scenario === 'mouse-back' ? 'back' : 'forward';
await waitFor(() => evaluate(`!document.getElementById('${button}').disabled`), button);
await command('Input.dispatchMouseEvent', {type:'mousePressed', x:15, y:80, button, buttons:button === 'back' ? 8 : 16});
await command('Input.dispatchMouseEvent', {type:'mouseReleased', x:15, y:80, button, buttons:0});
} else if (scenario === 'back' || scenario === 'forward') {
await waitFor(() => evaluate(`!document.getElementById('${scenario}').disabled`), scenario);
await evaluate(`document.getElementById('${scenario}').click()`);
} else if (scenario === 'cycle') {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers:2, windowsVirtualKeyCode:9});
} else if (scenario === 'close') {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'w', code:'KeyW', modifiers:2, windowsVirtualKeyCode:87});
} else {
await waitFor(() => evaluate('document.documentElement?.classList.contains("rendered") && ' +
'document.querySelector("h1")?.textContent === ' + JSON.stringify(scenario)), scenario);
if (scenario === 'Linked Markdown') {
await waitFor(() => evaluate('scrollY > 0 && document.getElementById("target-heading").getBoundingClientRect().top < innerHeight'),
'the relative heading fragment to scroll into view');
}
}
} finally {
socket.close();
}
+80
View File
@@ -0,0 +1,80 @@
#include <winsock2.h>
#include "files_text_window.h"
#include "lan_files.h"
#include "platform.h"
#include <shellapi.h>
#include <thread>
int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
{
int count{};
auto args=CommandLineToArgvW(GetCommandLineW(),&count);
if(!args || count!=2)
{
if(args) LocalFree(args);
return 1;
}
const std::filesystem::path document=args[1];
LocalFree(args);
if(FAILED(CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED))) return 1;
WSADATA network{};
if(WSAStartup(MAKEWORD(2,2),&network))
{
CoUninitialize();
return 1;
}
int result=0;
try
{
using namespace ks;
using namespace ks::lan;
const auto serverId=randomHex(16), clientId=randomHex(16), key=randomHex(32);
FilesListener listener(serverId,[&](const auto &id){return id==clientId?key:std::string{};},0);
if(!listener.port()) throw std::runtime_error("Could not bind the LAN test listener.");
const auto pairing=Json{{"enabled",true},{"id",clientId},
{"trusted",{{serverId,{{"key",key}}}}}}.dump();
atomicWrite(dataDirectory()/L"lan-pairing.bin",protect(Bytes(pairing.begin(),pairing.end())));
const FilesPeer peer{serverId,"127.0.0.1",L"Loopback peer",listener.port()};
std::jthread server([&](std::stop_token stop) {
while(!stop.stop_requested()) { listener.poll(); Sleep(5); }
});
WNDCLASSW type{};
type.hInstance=instance;
type.lpszClassName=L"KSwitcher.Files.MarkdownFixture";
type.lpfnWndProc=[](HWND window,UINT message,WPARAM wparam,LPARAM lparam)->LRESULT {
if(message==WM_DESTROY) { files::textWindowOwnerClosed(); return 0; }
return DefWindowProcW(window,message,wparam,lparam);
};
if(!RegisterClassW(&type)) throw std::runtime_error("Could not register the LAN fixture.");
const auto owner=CreateWindowW(type.lpszClassName,L"LAN Markdown fixture",WS_OVERLAPPEDWINDOW,
20,20,960,720,nullptr,nullptr,instance,nullptr);
if(!owner) throw std::runtime_error("Could not open the LAN fixture.");
files::TextDialogs dialogs{};
dialogs.readFont=[] {
files::TextWindowFont font{};
wcscpy_s(font.font.lfFaceName,L"Consolas");
font.tenthsOfPoint=100;
return font;
};
dialogs.confirmExisting=[](HWND){return true;};
dialogs.confirmSave=[](HWND)->INT_PTR {return IDYES;};
dialogs.message=[](HWND,const wchar_t *message){log(message);};
dialogs.dismissOwned=[](HWND){return false;};
files::openTextWindow(owner,document,false,dialogs,&peer);
DestroyWindow(owner);
MSG message{};
while(GetMessageW(&message,nullptr,0,0)>0)
{
TranslateMessage(&message);
DispatchMessageW(&message);
}
}
catch(const std::exception &error)
{
ks::log(L"LAN Markdown fixture: "+ks::wide(error.what()));
result=1;
}
WSACleanup();
CoUninitialize();
return result;
}
+60
View File
@@ -0,0 +1,60 @@
#include <windows.h>
#include <commctrl.h>
#include <algorithm>
#include <iostream>
#include <string_view>
#include <utility>
#include <vector>
#include "files_text_window.h"
namespace
{
#include "files_dialog_input.inl"
bool cancelled(HWND dialog)
{
MSG message{};
return PeekMessageW(&message,dialog,WM_COMMAND,WM_COMMAND,PM_REMOVE) &&
LOWORD(message.wParam)==IDCANCEL;
}
}
int main()
{
const auto instance=GetModuleHandleW(nullptr);
const auto owner=CreateWindowW(L"STATIC",L"Files",WS_OVERLAPPEDWINDOW,
0,0,300,200,nullptr,nullptr,instance,nullptr);
const auto dialog=CreateWindowW(L"STATIC",L"Search",WS_POPUP,
0,0,200,100,owner,nullptr,instance,nullptr);
const auto external=CreateWindowW(L"STATIC",L"Other",WS_OVERLAPPEDWINDOW,
0,0,300,200,nullptr,nullptr,instance,nullptr);
if(!owner || !dialog || !external)
{
std::cerr << "Could not create modal test windows.\n";
return 1;
}
POINT client{10,10},frame{10,-1};
ClientToScreen(owner,&client);
ClientToScreen(owner,&frame);
if(handleFilesDialogClick(dialog,external,client) ||
handleFilesDialogClick(dialog,GetDesktopWindow(),client) ||
handleFilesDialogClick(dialog,nullptr,client) || cancelled(dialog))
{
std::cerr << "A click outside Files cancelled the dialog.\n";
return 1;
}
if(handleFilesDialogClick(dialog,owner,frame) || cancelled(dialog))
{
std::cerr << "A click on the owner's frame cancelled the dialog.\n";
return 1;
}
if(!handleFilesDialogClick(dialog,owner,client) || !cancelled(dialog))
{
std::cerr << "A click in the Files client area did not cancel the dialog.\n";
return 1;
}
DestroyWindow(owner);
DestroyWindow(external);
std::cout << "Verified Files modal handling of external, frame, and client-area clicks.\n";
}
+838
View File
@@ -0,0 +1,838 @@
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly)
$ErrorActionPreference='Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Text;
public static class SearchArrowTest {
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string name, string title);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr hwnd, int id);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr hwnd, uint message, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr SendRect(IntPtr hwnd, uint message, IntPtr w, out Rect rect);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SendText(IntPtr hwnd, uint message, IntPtr w, string l);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr GetText(IntPtr hwnd, uint message, IntPtr w, StringBuilder l);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hwnd, uint message, IntPtr w, IntPtr l);
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags);
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out Rect rect);
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hwnd,uint command);
[DllImport("user32.dll",EntryPoint="GetWindowLongPtrW")] public static extern IntPtr GetWindowStyle(IntPtr hwnd,int index);
[StructLayout(LayoutKind.Sequential)]
struct PropertyKey { public Guid Format; public uint Id; }
[StructLayout(LayoutKind.Explicit, Size=24)]
struct PropertyValue {
[FieldOffset(0)] public ushort Type;
[FieldOffset(8)] public IntPtr String;
}
[ComImport, Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface WindowProperties {
[PreserveSig] int GetCount(out uint count);
[PreserveSig] int GetAt(uint index, out PropertyKey key);
[PreserveSig] int GetValue(ref PropertyKey key, out PropertyValue value);
}
[DllImport("shell32.dll")] static extern int SHGetPropertyStoreForWindow(IntPtr hwnd, ref Guid iid, out WindowProperties properties);
[DllImport("ole32.dll")] static extern int PropVariantClear(ref PropertyValue value);
public static string TaskbarIdentity(IntPtr window) {
var iid = typeof(WindowProperties).GUID;
if (SHGetPropertyStoreForWindow(window, ref iid, out var properties) < 0) return null;
try {
var key = new PropertyKey { Format = new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), Id = 5 };
if (properties.GetValue(ref key, out var value) < 0) return null;
try { return value.Type == 31 ? Marshal.PtrToStringUni(value.String) : null; }
finally { PropVariantClear(ref value); }
} finally { Marshal.ReleaseComObject(properties); }
}
[DllImport("user32.dll")] public static extern bool IsWindowEnabled(IntPtr hwnd);
[StructLayout(LayoutKind.Sequential)]
struct GuiThreadInfo {
public int Size, Flags;
public IntPtr Active, Focus, Capture, MenuOwner, MoveSize, Caret;
public Rect CaretBounds;
}
[DllImport("user32.dll")] static extern bool GetGUIThreadInfo(uint thread, ref GuiThreadInfo info);
public static IntPtr FocusedControl(IntPtr window) {
var info = new GuiThreadInfo { Size = Marshal.SizeOf<GuiThreadInfo>() };
return GetGUIThreadInfo(GetWindowThreadProcessId(window, out _), ref info) ? info.Focus : IntPtr.Zero;
}
public static bool HasCheckboxCaret(IntPtr checkbox) {
var info = new GuiThreadInfo { Size = Marshal.SizeOf<GuiThreadInfo>() };
return GetGUIThreadInfo(GetWindowThreadProcessId(checkbox, out _), ref info) &&
info.Caret == checkbox && info.CaretBounds.Left > 0 &&
info.CaretBounds.Right > info.CaretBounds.Left &&
info.CaretBounds.Bottom - info.CaretBounds.Top < info.CaretBounds.Right - info.CaretBounds.Left;
}
}
"@
function Wait-Until($Block) {
for ($i=0; $i -lt 120; $i++) {
$value = & $Block
if ($value) { return $value }
Start-Sleep -Milliseconds 100
}
throw "Timeout: $Block"
}
function Find-Window($Name, $ProcessId, [int]$ControlId=0, [IntPtr]$Except=[IntPtr]::Zero) {
$wnd = [IntPtr]::Zero
while (($wnd = [SearchArrowTest]::FindWindowEx(0, $wnd, $Name, [System.Management.Automation.Language.NullString]::Value)) -ne [IntPtr]::Zero) {
[uint32]$ownerProcess = 0
[void][SearchArrowTest]::GetWindowThreadProcessId($wnd, [ref]$ownerProcess)
if ($ownerProcess -eq $ProcessId -and $wnd -ne $Except -and [SearchArrowTest]::IsWindowVisible($wnd) -and
(!$ControlId -or [SearchArrowTest]::GetDlgItem($wnd,$ControlId) -ne [IntPtr]::Zero)) { return $wnd }
}
}
function Select-Row($Panel, $Name) {
$row = [SearchArrowTest]::SendText($Panel, 0x1A2, -1, $Name)
if ($row.ToInt64() -lt 0) { throw "Missing row $Name" }
[void][SearchArrowTest]::Send($Panel, 0x186, $row, 0)
}
function Post($Window, $Message, $W, $L = 0) {
if (![SearchArrowTest]::PostMessage($Window, $Message, $W, $L)) { throw "Post failed" }
}
function Click-PanelRow($Panel, $Row) {
$bounds=[SearchArrowTest+Rect]::new()
if([SearchArrowTest]::SendRect($Panel,0x198,$Row,[ref]$bounds).ToInt64() -eq -1){
throw "Missing file panel row $Row"
}
$point=([int](($bounds.Top+$bounds.Bottom)/2) -shl 16) -bor 6
Post $Panel 0x201 1 $point
Post $Panel 0x202 0 $point
}
function Read-PanelHighlights($Trace, $Start) {
$highlight=@{}
Get-Content -LiteralPath $Trace | Select-Object -Skip $Start |
ForEach-Object { if($_ -match '^\d+ panel-draw ([01]) (\d+) ([01]) '){
$highlight["$($Matches[1])/$($Matches[2])"]=$Matches[3]
} }
return $highlight
}
function Assert-FarCheckbox($Dialog, [int]$Id, $NextControl) {
$checkbox=[SearchArrowTest]::GetDlgItem($Dialog,$Id)
Post $Dialog 0x28 $checkbox 1
[void](Wait-Until { [SearchArrowTest]::HasCheckboxCaret($checkbox) })
$checked=[SearchArrowTest]::Send($checkbox,0xF0,0,0)
[void][SearchArrowTest]::Send($checkbox,0xF5,0,0)
if ([SearchArrowTest]::Send($checkbox,0xF0,0,0) -eq $checked) { throw 'The Far checkbox did not toggle.' }
[void][SearchArrowTest]::Send($checkbox,0xF5,0,0)
Post $Dialog 0x28 $NextControl 1
[void](Wait-Until {
[SearchArrowTest]::FocusedControl($Dialog) -eq $NextControl -and
![SearchArrowTest]::HasCheckboxCaret($checkbox)
})
}
function Read-Bounds($Window) {
$bounds=[SearchArrowTest+Rect]::new()
if (![SearchArrowTest]::GetWindowRect($Window,[ref]$bounds)) { throw 'Missing window bounds' }
$bounds
}
function Assert-CompactNotice($Dialog, [int]$DefaultButton) {
$text=[SearchArrowTest]::GetDlgItem($Dialog,100)
if (([SearchArrowTest]::GetWindowStyle($text,-16).ToInt64() -band 0x00200000) -ne 0) {
throw 'A short Files notice has a vertical scrollbar.'
}
$lines=[SearchArrowTest]::Send($text,0xBA,0,0).ToInt32()
$body=Read-Bounds $text
$button=[SearchArrowTest]::GetDlgItem($Dialog,$DefaultButton)
$footer=Read-Bounds $button
$lineHeight=($body.Bottom-$body.Top)/$lines
$frame=Read-Bounds $Dialog
if (($body.Top-$frame.Top) -gt 2*$lineHeight -or
($frame.Bottom-$footer.Bottom) -gt $lineHeight) {
throw 'A short Files notice has excess space between its content and frame.'
}
if (($footer.Top-$body.Bottom) -gt $lineHeight -or $footer.Top -le $body.Bottom) {
throw 'A short Files notice has incorrect spacing between the text and the buttons.'
}
if ([SearchArrowTest]::FocusedControl($Dialog) -ne $button) {
throw 'A Files notice has the wrong starting focus.'
}
}
function Assert-FarFieldHeight($Dialog, [int[]]$Ids) {
$heights=@(foreach ($id in $Ids) {
$bounds=Read-Bounds ([SearchArrowTest]::GetDlgItem($Dialog,$id))
$bounds.Bottom-$bounds.Top
})
if (@($heights | Select-Object -Unique).Count -ne 1) {
throw "Far field heights differ: $heights."
}
}
function Assert-FarDropDown($Popup, $Anchor, [int]$ArrowWidth=0) {
$bounds=Read-Bounds $Popup
$anchorBounds=Read-Bounds $Anchor
if ($bounds.Left -ne $anchorBounds.Left -or $bounds.Top -ne $anchorBounds.Bottom -or
$bounds.Right -ne $anchorBounds.Right-$ArrowWidth) {
throw 'The Far list is not aligned with the field edges.'
}
$bitmap=[Drawing.Bitmap]::new($bounds.Right-$bounds.Left,$bounds.Bottom-$bounds.Top)
try {
$graphics=[Drawing.Graphics]::FromImage($bitmap)
try {
$dc=$graphics.GetHdc()
try {
if (![SearchArrowTest]::PrintWindow($Popup,$dc,0)) { throw 'Could not render Far list.' }
} finally { $graphics.ReleaseHdc($dc) }
} finally { $graphics.Dispose() }
$background=$bitmap.GetPixel(2,2)
if ($background.G -lt 85 -or $background.B -lt 85 -or $background.R -ge $background.G) {
throw "The Far list background is not teal: $background."
}
$frame=$false
$selection=$false
for ($y=3; $y -lt $bitmap.Height-3; $y++) {
$pixel=$bitmap.GetPixel([int]($bitmap.Width/3),$y)
if ($y -lt 16 -and $pixel.R -gt 220 -and $pixel.G -gt 220 -and $pixel.B -gt 220) { $frame=$true }
if ($pixel.R -lt 16 -and $pixel.G -lt 16 -and $pixel.B -lt 16) { $selection=$true }
}
if (!$frame -or !$selection) { throw 'The Far list is missing its light frame or black selected row.' }
} finally { $bitmap.Dispose() }
}
function Resize-Window($Window, $Bounds, [int]$Width, [switch]$Clamped) {
if (![SearchArrowTest]::SetWindowPos($Window,0,$Bounds.Left,$Bounds.Top,$Width,
($Bounds.Bottom-$Bounds.Top),0x14)) { throw 'Could not resize the owner window.' }
if (!$Clamped) {
[void](Wait-Until {
$current=Read-Bounds $Window
$current.Right-$current.Left -eq $Width
})
}
}
function Assert-MovesWithOwner($Owner, $Dialog) {
$ownerBefore=Read-Bounds $Owner
$dialogBefore=Read-Bounds $Dialog
$dx=17
$dy=23
if (![SearchArrowTest]::SetWindowPos($Owner,0,($ownerBefore.Left+$dx),($ownerBefore.Top+$dy),0,0,0x15)) {
throw 'Could not move the dialog owner.'
}
try {
for ($i=0; $i -lt 20; $i++) {
$ownerAfter=Read-Bounds $Owner
$dialogAfter=Read-Bounds $Dialog
$ownerDeltaX=$ownerAfter.Left-$ownerBefore.Left
$ownerDeltaY=$ownerAfter.Top-$ownerBefore.Top
$dialogDeltaX=$dialogAfter.Left-$dialogBefore.Left
$dialogDeltaY=$dialogAfter.Top-$dialogBefore.Top
if ($ownerDeltaX -eq $dx -and $ownerDeltaY -eq $dy -and
$dialogDeltaX -eq $dx -and $dialogDeltaY -eq $dy) { return }
Start-Sleep -Milliseconds 100
}
throw "Expected movement ($dx, $dy). Owner moved ($ownerDeltaX, $ownerDeltaY), dialog moved ($dialogDeltaX, $dialogDeltaY)."
} finally {
[void][SearchArrowTest]::SetWindowPos($Owner,0,$ownerBefore.Left,$ownerBefore.Top,0,0,0x15)
}
}
$scratch=Join-Path ([IO.Path]::GetDirectoryName((Resolve-Path -LiteralPath $Executable).Path)) ('search-arrow-test-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $scratch | Out-Null
$fixture = Join-Path $scratch ('files-editor-ui-' + [Guid]::NewGuid().ToString('N') + '.cs')
[IO.File]::WriteAllText($fixture, "public class Test {`r`n}`r`n")
foreach($name in 'A.txt','B.txt','C.txt','D.txt'){
[IO.File]::WriteAllText((Join-Path $scratch $name),'Cursor test fixture')
}
$rightFixture=Join-Path $scratch 'Right fixture'
New-Item -ItemType Directory -Path $rightFixture | Out-Null
foreach($name in 'A.txt','B.txt','C.txt','D.txt'){
[IO.File]::WriteAllText((Join-Path $rightFixture $name),'Cursor test fixture')
}
$copy=Join-Path $scratch 'KSwitcher.Files.search-arrow-test.exe'
Copy-Item -LiteralPath $Executable -Destination $copy
$profile=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
$saved=@{}
foreach($name in $keysToRestore){
if($name -in $profile.GetValueNames()){
$saved[$name]=@($profile.GetValue($name),$profile.GetValueKind($name))
}
}
$process=$null
$paintTrace=$null
try {
$profile.SetValue('LeftPath',$scratch)
$profile.SetValue('RightPath',$rightFixture)
$profile.DeleteValue('LeftCursor',$false)
$profile.DeleteValue('RightCursor',$false)
$process=Start-Process -FilePath $copy -ArgumentList '--terminal-trace' -PassThru -WindowStyle Normal
$paintTrace=Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
$previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
$main = Wait-Until { Find-Window 'KSwitcher.Files' $process.Id }
$leftPanel=[SearchArrowTest]::GetDlgItem($main,102)
$rightPanel=[SearchArrowTest]::GetDlgItem($main,103)
$clicks=if(!$KeyboardCursorOnly){
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
}
foreach($check in $clicks) {
$before=[SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32()
$top=[SearchArrowTest]::Send($check.Panel,0x18E,0,0).ToInt32()
$row=if($before -eq $top){$top+1}else{$top}
[void](Wait-Until { Test-Path -LiteralPath $paintTrace })
Start-Sleep -Milliseconds 150
$lineCount=@(Get-Content -LiteralPath $paintTrace).Count
Click-PanelRow $check.Panel $row
[void](Wait-Until { [SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32() -eq $row })
Start-Sleep -Milliseconds 150
$highlight=Read-PanelHighlights $paintTrace $lineCount
$draws=@($highlight.Keys)
if("$($check.Index)/$row" -notin $draws -or $draws.Count -gt 3){
throw "Clicking a row repainted unrelated file rows. Drawn rows: $draws"
}
if($highlight["$($check.Index)/$row"] -ne '1' -or
($before -ge $top -and $highlight["$($check.Index)/$before"] -ne '0')){
throw 'The new row must be painted active and the previous visible row must lose its highlight.'
}
}
if($clicks){Write-Output 'Verified file clicks repaint only cursor rows in the active pane and when changing panes.'}
Post $main 0x111 132
$commandMenu=Wait-Until {
$list=[SearchArrowTest]::GetDlgItem($main,121)
if ([SearchArrowTest]::IsWindowVisible($list)) { $list }
}
$count=[SearchArrowTest]::Send($commandMenu,0x18B,0,0).ToInt32()
$rows=@(for ($i=0; $i -lt $count; $i++) {
$label=[Text.StringBuilder]::new(128)
[void][SearchArrowTest]::GetText($commandMenu,0x189,$i,$label)
$label.ToString()
})
if (($rows -join '|') -cne "Refresh panel`tCtrl+R|Folder shortcuts||View`tF3|Edit`tF4|View externally`tAlt+F3|Edit externally`tAlt+F4") {
throw 'Commands did not group local actions or showed a LAN-only section.'
}
Post $commandMenu 0x100 38
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq ($count-1) })
Post $commandMenu 0x100 40
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 0 })
Post $commandMenu 0x100 40
Post $commandMenu 0x100 40
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 3 })
Post $commandMenu 0x100 38
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 1 })
$rowHeight=[SearchArrowTest]::Send($commandMenu,0x1A1,0,0).ToInt32()
$separatorPoint=((2*$rowHeight+1) -shl 16) -bor 4
[void][SearchArrowTest]::Send($commandMenu,0x201,1,$separatorPoint)
[void][SearchArrowTest]::Send($commandMenu,0x202,0,$separatorPoint)
if ([SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -ne 1) {
throw 'A click selected the Commands separator.'
}
Post $commandMenu 0x100 27
[void](Wait-Until { ![SearchArrowTest]::IsWindowVisible($commandMenu) })
Write-Output 'Verified Commands grouping, arrow navigation, and inert separators.'
$panel = Wait-Until { $handle = [SearchArrowTest]::GetDlgItem($main,102); if ($handle -ne [IntPtr]::Zero) { $handle } }
$pathControl = [SearchArrowTest]::GetDlgItem($main,142)
$pathText = [Text.StringBuilder]::new(1024)
[void][SearchArrowTest]::GetText($pathControl,0xD,$pathText.Capacity,$pathText)
$path=$pathText.ToString()
if ([IO.Path]::GetPathRoot($path) -ne [IO.Path]::GetPathRoot($scratch)) {
throw 'Select a local left-panel folder on the test executable drive before running this interactive test.'
}
foreach ($component in $path.Substring(3).Split('\',[System.StringSplitOptions]::RemoveEmptyEntries)) {
Select-Row $panel '..'
[void][SearchArrowTest]::Send($panel,0x100,13,0)
}
foreach ($component in $scratch.Substring(3).Split('\')) {
Select-Row $panel "[$component]"
[void][SearchArrowTest]::Send($panel,0x100,13,0)
}
$fixtureRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,([IO.Path]::GetFileName($fixture))).ToInt32()
Click-PanelRow $panel $fixtureRow
[void](Wait-Until { [SearchArrowTest]::Send($panel,0x188,0,0).ToInt32() -eq $fixtureRow })
$inputBox=[SearchArrowTest]::FindWindowEx($main,0,'Edit',[NullString]::Value)
[void](Wait-Until { [SearchArrowTest]::FocusedControl($main) -eq $inputBox })
[void][SearchArrowTest]::SendText($inputBox,0xC,0,'')
$last=[SearchArrowTest]::Send($panel,0x18B,0,0).ToInt32()-1
$keys=@(
@{Name='Left'; Code=37; Row=0}
@{Name='Right'; Code=39; Row=$last}
@{Name='Left'; Code=37; Row=0}
@{Name='Down'; Code=40; Row=1}
@{Name='Up'; Code=38; Row=0}
@{Name='End'; Code=35; Row=$last}
@{Name='Home'; Code=36; Row=0}
@{Name='Page Down'; Code=34; Row=$last}
@{Name='Page Up'; Code=33; Row=0}
)
foreach($key in $keys){
$previous=[SearchArrowTest]::Send($panel,0x188,0,0).ToInt32()
Start-Sleep -Milliseconds 100
$lineCount=@(Get-Content -LiteralPath $paintTrace).Count
Post $inputBox 0x100 $key.Code
try {
[void](Wait-Until { [SearchArrowTest]::Send($panel,0x188,0,0).ToInt32() -eq $key.Row })
} catch {
$actual=[SearchArrowTest]::Send($panel,0x188,0,0).ToInt32()
throw "$($key.Name) selected row $actual, expected row $($key.Row)."
}
Start-Sleep -Milliseconds 150
$highlight=Read-PanelHighlights $paintTrace $lineCount
if($highlight["0/$($key.Row)"] -ne '1' -or $highlight["0/$previous"] -ne '0'){
throw "$($key.Name) left the previous row highlighted or did not paint the new row active."
}
}
Write-Output 'Verified cursor highlighting after arrows, Home, End, Page Up and Page Down from the command line.'
if($KeyboardCursorOnly){return}
Click-PanelRow $panel $fixtureRow
$deleteButton=[SearchArrowTest]::GetDlgItem($main,117)
$deleteLabel=[Text.StringBuilder]::new(64)
[void][SearchArrowTest]::GetText($deleteButton,0xD,$deleteLabel.Capacity,$deleteLabel)
if($deleteLabel.ToString() -cne 'F8 Delete'){throw 'The F8 Delete key bar button is missing.'}
$bounds=Read-Bounds $deleteButton
$windowBounds=Read-Bounds $main
$bitmap=[Drawing.Bitmap]::new($windowBounds.Right-$windowBounds.Left,$windowBounds.Bottom-$windowBounds.Top)
try {
$graphics=[Drawing.Graphics]::FromImage($bitmap)
try {
$dc=$graphics.GetHdc()
try { if(![SearchArrowTest]::PrintWindow($main,$dc,0)){throw 'Could not render the Files window.'} }
finally { $graphics.ReleaseHdc($dc) }
} finally {$graphics.Dispose()}
$y=$bounds.Top-$windowBounds.Top+1
$cap=$bitmap.GetPixel(($bounds.Left-$windowBounds.Left+1),$y)
$action=$bitmap.GetPixel(($bounds.Right-$windowBounds.Left-2),$y)
if($cap.ToArgb() -ne [Drawing.Color]::Black.ToArgb() -or $action.ToArgb() -eq $cap.ToArgb()){
throw 'The key bar no longer separates its dark key cap from the action segment.'
}
} finally {$bitmap.Dispose()}
Post $deleteButton 0xF5 0
$deleteDialog=Wait-Until { Find-Window '#32770' $process.Id 6 }
Post $deleteDialog 0x111 2
[void](Wait-Until { ![SearchArrowTest]::IsWindow($deleteDialog) })
if(!(Test-Path -LiteralPath $fixture)){throw 'Canceling F8 Delete removed the fixture.'}
Write-Output 'Verified F8 Delete on the key bar opens the normal confirmation.'
$newFolder='F7 тестова папка'
Post $panel 0x100 0x76
$makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 }
$nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361)
Assert-FarFieldHeight $makeDialog @(361,363,365,367)
$nameBounds=Read-Bounds $nameField
$arrowBounds=Read-Bounds ([SearchArrowTest]::GetDlgItem($makeDialog,363))
if ($nameBounds.Right -ne $arrowBounds.Left) { throw 'F7 history arrow does not touch the field.' }
$okButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($makeDialog,1))
$cancelButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($makeDialog,2))
$okWidth=$okButton.Right-$okButton.Left
$gap=$cancelButton.Left-$okButton.Right
if ($gap -lt 0 -or $gap -gt $okWidth/7 -or $cancelButton.Right-$cancelButton.Left -le $okWidth) {
throw 'Make folder buttons are not grouped at their caption widths.'
}
[void][SearchArrowTest]::SendText($nameField,0xC,0,$newFolder)
Post $makeDialog 0x111 1
[void](Wait-Until { ![SearchArrowTest]::IsWindow($makeDialog) })
if (!(Test-Path -LiteralPath (Join-Path $scratch $newFolder) -PathType Container)) {
throw 'F7 did not create the folder in the active panel.'
}
$newRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,"[$newFolder]")
if ($newRow.ToInt64() -lt 0 -or [SearchArrowTest]::Send($panel,0x188,0,0) -ne $newRow) {
throw 'F7 did not select the new folder.'
}
Post $main 0x111 115
$makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 }
$nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361)
[void][SearchArrowTest]::SendText($nameField,0xC,0,$newFolder)
Post $makeDialog 0x111 1
$folderError=Wait-Until { Find-Window '#32770' $process.Id 100 }
Assert-CompactNotice $folderError 1
Post $folderError 0x111 1
[void](Wait-Until {
![SearchArrowTest]::IsWindow($folderError) -and
[SearchArrowTest]::FocusedControl($makeDialog) -eq $nameField
})
[void][SearchArrowTest]::SendText($nameField,0xC,0,'Canceled folder')
Post $nameField 0x100 27
[void](Wait-Until { ![SearchArrowTest]::IsWindow($makeDialog) })
if (Test-Path -LiteralPath (Join-Path $scratch 'Canceled folder')) { throw 'Canceled F7 created a folder.' }
Write-Output 'Verified F7 folder creation, selection, duplicate error, and cancellation.'
Post $panel 0x100 0x76
$makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 }
$nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361)
if (![SearchArrowTest]::IsWindowEnabled([SearchArrowTest]::GetDlgItem($makeDialog,363))) {
throw 'F7 did not persist the folder name in history.'
}
Post $makeDialog 0x111 363
$popup=Wait-Until { Find-Window 'KSwitcher.Files.DropDown' $process.Id }
Assert-FarDropDown $popup $nameField
Post $popup 0x100 13
[void](Wait-Until { ![SearchArrowTest]::IsWindow($popup) })
$chosen=[Text.StringBuilder]::new(256)
[void][SearchArrowTest]::GetText($nameField,0xD,$chosen.Capacity,$chosen)
if ($chosen.ToString() -ne $newFolder) { throw 'The history list did not fill in the selected name.' }
Post $makeDialog 0x111 363
$popup=Wait-Until { Find-Window 'KSwitcher.Files.DropDown' $process.Id }
Post $popup 0x100 27
[void](Wait-Until {
![SearchArrowTest]::IsWindow($popup) -and [SearchArrowTest]::FocusedControl($makeDialog) -eq $nameField
})
$targetField=[SearchArrowTest]::GetDlgItem($makeDialog,367)
if ([SearchArrowTest]::IsWindowEnabled($targetField)) { throw 'Target is enabled with link type none.' }
$multiple=[SearchArrowTest]::GetDlgItem($makeDialog,368)
[void][SearchArrowTest]::Send($multiple,0xF1,1,0)
[void][SearchArrowTest]::SendText($nameField,0xC,0,'Alpha;"Beta, Gamma", Delta')
Post $makeDialog 0x111 1
[void](Wait-Until { ![SearchArrowTest]::IsWindow($makeDialog) })
foreach ($name in 'Alpha','Beta, Gamma','Delta') {
if (!(Test-Path -LiteralPath (Join-Path $scratch $name) -PathType Container)) {
throw "F7 did not create '$name' in the batch."
}
}
[IO.File]::WriteAllText((Join-Path $scratch 'Alpha\link-target.txt'),'F7 link target')
foreach ($kind in 1,2) {
Post $panel 0x100 0x76
$makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 }
$nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361)
$selector=[SearchArrowTest]::GetDlgItem($makeDialog,365)
$targetField=[SearchArrowTest]::GetDlgItem($makeDialog,367)
Post $selector 0x100 0x73
$popup=Wait-Until { Find-Window 'KSwitcher.Files.DropDown' $process.Id }
Assert-FarDropDown $popup $selector ($arrowBounds.Right-$arrowBounds.Left)
Post $popup 0x100 0x26
if ($kind -eq 1) {
Post $popup 0x100 0x28
Post $popup 0x100 0x28
}
Post $popup 0x100 13
[void](Wait-Until { ![SearchArrowTest]::IsWindow($popup) })
[void](Wait-Until { [SearchArrowTest]::IsWindowEnabled($targetField) })
$linkName="Folder link $kind"
[void][SearchArrowTest]::SendText($nameField,0xC,0,$linkName)
[void][SearchArrowTest]::SendText($targetField,0xC,0,'Alpha')
Post $makeDialog 0x111 1
$linkPath=Join-Path $scratch $linkName
$outcome=Wait-Until {
if (![SearchArrowTest]::IsWindow($makeDialog)) { 'created' }
elseif (Find-Window '#32770' $process.Id 100) { 'error' }
}
if ($outcome -eq 'error' -and $kind -eq 2) {
# The test host can deny symlink creation by policy. Confirm the same result with Windows.
$probe=Join-Path $scratch 'Symbolic link privilege probe'
try {
[void][IO.Directory]::CreateSymbolicLink($probe,(Join-Path $scratch 'Alpha'))
throw 'Windows can create symbolic links, but F7 reported an error.'
} catch {
if ($_.Exception.InnerException -isnot [IO.IOException] -and
$_.Exception.InnerException -isnot [UnauthorizedAccessException]) { throw }
}
$alert=Find-Window '#32770' $process.Id 100
Post $alert 0x111 1
[void](Wait-Until { ![SearchArrowTest]::IsWindow($alert) })
Post $makeDialog 0x111 2
[void](Wait-Until { ![SearchArrowTest]::IsWindow($makeDialog) })
Write-Output 'Windows denied directory symbolic link creation and F7 reported the error.'
continue
}
if ($outcome -ne 'created') { throw "F7 failed to create link type $kind." }
$link=Get-Item -LiteralPath $linkPath
$expected=if ($kind -eq 1) { 'Junction' } else { 'SymbolicLink' }
if ($link.LinkType -ne $expected -or
!(Test-Path -LiteralPath (Join-Path $linkPath 'link-target.txt') -PathType Leaf)) {
throw "F7 did not create a $expected pointing to Alpha."
}
}
Write-Output 'Verified F7 history, quoted batch names, and directory link handling.'
Select-Row $panel ([IO.Path]::GetFileName($fixture))
Post $panel 0x100 0x74
$copyDialog=Wait-Until {
$dialog=Find-Window '#32770' $process.Id
if ($dialog -and [SearchArrowTest]::GetDlgItem($dialog,211) -ne [IntPtr]::Zero) { $dialog }
}
if (![SearchArrowTest]::IsWindowEnabled($main)) { throw 'Copy disabled the Files frame.' }
Assert-FarFieldHeight $copyDialog @(211,213)
Assert-MovesWithOwner $main $copyDialog
$mainBounds=Read-Bounds $main
$copyBounds=Read-Bounds $copyDialog
$copyPreferred=$copyBounds.Right-$copyBounds.Left
try {
Resize-Window $main $mainBounds ([Math]::Max(540,[int]($copyPreferred*0.65))) -Clamped
[void](Wait-Until {
$current=Read-Bounds $copyDialog
$current.Right-$current.Left -lt $copyPreferred
})
} finally {
Resize-Window $main $mainBounds ($mainBounds.Right-$mainBounds.Left)
}
[void](Wait-Until {
$current=Read-Bounds $copyDialog
$current.Right-$current.Left -eq $copyPreferred
})
$destination=[SearchArrowTest]::GetDlgItem($copyDialog,211)
Assert-FarCheckbox $copyDialog 214 $destination
if ([SearchArrowTest]::GetDlgItem($copyDialog,328) -ne [IntPtr]::Zero) { throw 'Copy has an inline error row.' }
$compact=Read-Bounds $copyDialog
[void][SearchArrowTest]::SendText($destination,0xC,0,'')
Post $copyDialog 0x111 1
$alert=Wait-Until { Find-Window '#32770' $process.Id 100 }
$alertBounds=Read-Bounds $alert
$alertText=Read-Bounds ([SearchArrowTest]::GetDlgItem($alert,100))
$alertButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($alert,1))
if ($alertText.Bottom-$alertText.Top -gt 2*($alertButton.Bottom-$alertButton.Top) -or
$alertButton.Top-$alertText.Bottom -gt $alertButton.Bottom-$alertButton.Top) {
throw 'The short error alert has excess space around the message.'
}
$bitmap=[Drawing.Bitmap]::new($alertBounds.Right-$alertBounds.Left,$alertBounds.Bottom-$alertBounds.Top)
try {
$graphics=[Drawing.Graphics]::FromImage($bitmap)
try {
$dc=$graphics.GetHdc()
try {
if (![SearchArrowTest]::PrintWindow($alert,$dc,0)) { throw 'Could not render the path alert.' }
} finally { $graphics.ReleaseHdc($dc) }
} finally { $graphics.Dispose() }
$background=$bitmap.GetPixel(4,4)
if ($background.R -lt 100 -or $background.G -gt 20 -or $background.B -gt 20) {
throw "Path alert did not use the red warning surface. Got $background."
}
} finally { $bitmap.Dispose() }
Post $alert 0x111 1
[void](Wait-Until {
![SearchArrowTest]::IsWindow($alert) -and [SearchArrowTest]::FocusedControl($copyDialog) -eq $destination
})
$current=Read-Bounds $copyDialog
if ($current.Bottom-$current.Top -ne $compact.Bottom-$compact.Top) { throw 'The error resized Copy vertically.' }
Write-Output 'Verified the red path alert and focus restoration to Copy.'
Post $panel 0x201 1
[void](Wait-Until { ![SearchArrowTest]::IsWindow($copyDialog) })
function Open-Search {
Post $editor 0x111 3
Wait-Until {
$dialog=Find-Window '#32770' $process.Id
if ($dialog -and [SearchArrowTest]::GetDlgItem($dialog,108) -ne [IntPtr]::Zero) { $dialog }
}
}
function Assert-Arrow($Dialog, [bool]$Enabled) {
$arrow=[SearchArrowTest]::GetDlgItem($Dialog,108)
$arrowBounds=[SearchArrowTest+Rect]::new()
$dialogBounds=[SearchArrowTest+Rect]::new()
if (![SearchArrowTest]::GetWindowRect($arrow,[ref]$arrowBounds) -or
![SearchArrowTest]::GetWindowRect($Dialog,[ref]$dialogBounds)) { throw 'Missing Search bounds' }
if ([SearchArrowTest]::IsWindowEnabled($arrow) -ne $Enabled) { throw 'Unexpected history button state' }
$bitmap=[Drawing.Bitmap]::new($dialogBounds.Right-$dialogBounds.Left,$dialogBounds.Bottom-$dialogBounds.Top)
try {
$graphics=[Drawing.Graphics]::FromImage($bitmap)
try {
$dc=$graphics.GetHdc()
try {
if (![SearchArrowTest]::PrintWindow($Dialog,$dc,0)) { throw 'Could not render the Search dialog' }
} finally { $graphics.ReleaseHdc($dc) }
} finally { $graphics.Dispose() }
$x=$arrowBounds.Left-$dialogBounds.Left
$y=$arrowBounds.Top-$dialogBounds.Top
$width=$arrowBounds.Right-$arrowBounds.Left
$height=$arrowBounds.Bottom-$arrowBounds.Top
$field=Read-Bounds ([SearchArrowTest]::GetDlgItem($Dialog,100))
$inset=$field.Left-$dialogBounds.Left
foreach ($dividerId in 104,105) {
$divider=Read-Bounds ([SearchArrowTest]::GetDlgItem($Dialog,$dividerId))
$line=$divider.Top-$dialogBounds.Top
for ($column=$inset; $column -lt $bitmap.Width-$inset; $column++) {
$pixel=$bitmap.GetPixel($column,$line)
if ($pixel.R -ne 0 -or $pixel.G -ne 0 -or $pixel.B -ne 0) {
throw "Search divider $dividerId is broken at pixel $column."
}
}
}
$background=$bitmap.GetPixel($x+2,$y+2)
if ([Math]::Abs($background.R-$background.G) -gt 1 -or
[Math]::Abs($background.G-$background.B) -gt 1 -or $background.R -lt 175) {
throw "Expected a light gray arrow slot, got $background."
}
$ink=@(for ($row=1; $row -lt $height-1; $row++) {
for ($column=1; $column -lt $width-1; $column++) {
$pixel=$bitmap.GetPixel($x+$column,$y+$row)
if ($background.R-[Math]::Max($pixel.R,[Math]::Max($pixel.G,$pixel.B)) -ge 100) { $row; break }
}
})
if ($ink.Count -lt [Math]::Max(5,$height/3)) { throw 'The arrow is missing or has insufficient contrast.' }
if ([Math]::Abs($ink[0]+$ink[-1]-($height-1)) -gt 2) {
throw "The arrow is vertically off center. Ink spans rows $($ink[0])–$($ink[-1]) in a $height-pixel slot."
}
} finally { $bitmap.Dispose() }
}
Post $panel 0x100 0x73
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
$firstControl=[SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[System.Management.Automation.Language.NullString]::Value)
if ($firstControl -eq [IntPtr]::Zero -or
[SearchArrowTest]::Send($firstControl,2482,32,0).ToInt64() -eq 0xFFFFFF) {
throw 'The editor is visible with the default white Scintilla background.'
}
$originalFocus=Wait-Until {
$focus=[SearchArrowTest]::FocusedControl($editor)
if ($focus -ne [IntPtr]::Zero) { $focus }
}
if (![SearchArrowTest]::IsWindowEnabled($main) -or [SearchArrowTest]::GetWindow($editor,4) -ne [IntPtr]::Zero -or
([SearchArrowTest]::GetWindowStyle($editor,-20).ToInt64() -band 0x40000) -eq 0) {
throw 'The editor is not an independent taskbar window.'
}
Post $panel 0x100 0x73
$existing=Wait-Until { Find-Window '#32770' $process.Id 100 }
$notice=[Text.StringBuilder]::new(256)
[void][SearchArrowTest]::GetText([SearchArrowTest]::GetDlgItem($existing,100),0xD,$notice.Capacity,$notice)
if (!$notice.ToString().Contains('already open')) { throw 'Reopening did not offer to switch to the editor.' }
Assert-CompactNotice $existing 7
Post $existing 0x111 6
[void](Wait-Until { ![SearchArrowTest]::IsWindow($existing) })
if (Find-Window 'KSwitcher.Files.Text' $process.Id 0 $editor) { throw 'Duplicate editor opened.' }
$otherFile=Join-Path $scratch 'other-editor.cs'
[IO.File]::WriteAllText($otherFile,'class Other { }')
[void](Wait-Until {
[SearchArrowTest]::SendText($panel,0x1A2,-1,'other-editor.cs').ToInt64() -ge 0
})
Select-Row $panel 'other-editor.cs'
Post $panel 0x100 0x73
$otherEditor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id 0 $editor }
if ([SearchArrowTest]::GetWindow($otherEditor,4) -ne [IntPtr]::Zero) { throw 'The second editor is owned.' }
$editorIdentity=[SearchArrowTest]::TaskbarIdentity($editor)
$otherIdentity=[SearchArrowTest]::TaskbarIdentity($otherEditor)
if (!$editorIdentity -or !$otherIdentity -or $editorIdentity -eq $otherIdentity) {
throw 'Editor windows do not have distinct Windows taskbar identities.'
}
Post $otherEditor 0x10 0
[void](Wait-Until { ![SearchArrowTest]::IsWindow($otherEditor) })
Select-Row $panel ([IO.Path]::GetFileName($fixture))
Post $editor 7 0
[void](Wait-Until { [SearchArrowTest]::FocusedControl($editor) -eq $originalFocus })
Write-Output 'Verified independent editor taskbar styling and the already-open prompt.'
foreach ($action in 'Escape','outside click','owner close') {
$dialog=Open-Search
$field=[SearchArrowTest]::GetDlgItem($dialog,100)
[void](Wait-Until { [SearchArrowTest]::FocusedControl($dialog) -eq $field })
if (![SearchArrowTest]::IsWindowEnabled($editor)) { throw 'Search disabled the editor frame.' }
switch ($action) {
'Escape' {
Post $main 0x111 115
$managerPrompt=Wait-Until { Find-Window '#32770' $process.Id 361 }
Post $managerPrompt 0x111 2
[void](Wait-Until { ![SearchArrowTest]::IsWindow($managerPrompt) })
if (![SearchArrowTest]::IsWindow($dialog)) { throw 'The manager dismissed the editor Search dialog.' }
Assert-MovesWithOwner $editor $dialog
$ownerBounds=Read-Bounds $editor
$dialogBounds=Read-Bounds $dialog
$originalWidth=$ownerBounds.Right-$ownerBounds.Left
$preferred=$dialogBounds.Right-$dialogBounds.Left
try {
Resize-Window $editor $ownerBounds ([int]($preferred*0.92))
$reduced=Wait-Until {
$current=Read-Bounds $dialog
$width=$current.Right-$current.Left
if ($width -lt $preferred) { $width }
}
Assert-Arrow $dialog $false
Resize-Window $editor $ownerBounds ([int]($preferred*0.30)) -Clamped
$minimum=Wait-Until {
$current=Read-Bounds $dialog
if ($current.Right-$current.Left -lt $reduced) { $current }
}
$floor=$minimum.Right-$minimum.Left
Resize-Window $editor $ownerBounds ([int]($preferred*0.25)) -Clamped
$stillMinimum=Read-Bounds $dialog
$narrowOwner=Read-Bounds $editor
if ($floor -ne ($stillMinimum.Right-$stillMinimum.Left) -or
$stillMinimum.Left -lt $narrowOwner.Left -or $stillMinimum.Right -gt $narrowOwner.Right) {
throw 'The editor shrank below the minimum width needed to contain Search.'
}
$previous=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,103))
$next=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,1))
if ($previous.Bottom -gt $next.Top) { throw 'The narrow Search actions are not on separate rows.' }
Assert-Arrow $dialog $false
} finally {
Resize-Window $editor $ownerBounds $originalWidth
}
[void](Wait-Until {
$restored=Read-Bounds $dialog
$restored.Right-$restored.Left -eq $preferred
})
Post $field 0x100 27
}
'outside click' { Post $editor 0x201 1 }
'owner close' { Post $editor 0x10 0 }
}
[void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) })
if (![SearchArrowTest]::IsWindow($editor)) { throw "$action closed the editor." }
[void](Wait-Until { [SearchArrowTest]::FocusedControl($editor) -eq $originalFocus })
}
Write-Output 'Verified Search focus and dismissal by Escape, outside click, and editor close.'
Write-Output 'Verified that Search narrows to its own minimum and regains its width as the editor grows.'
$dialog=Open-Search
Assert-FarCheckbox $dialog 101 ([SearchArrowTest]::GetDlgItem($dialog,100))
$previousButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,103))
$nextButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,1))
if ($nextButton.Left-$previousButton.Right -ne $gap) { throw 'Search and F7 use different button gaps.' }
Assert-Arrow $dialog $false
[void][SearchArrowTest]::SendText([SearchArrowTest]::GetDlgItem($dialog,100),0xC,0,'public')
Post $dialog 0x111 1
[void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) })
$dialog=Open-Search
Assert-Arrow $dialog $true
Write-Output 'Verified continuous Search dividers and history arrow contrast and centering.'
Post ([SearchArrowTest]::GetDlgItem($dialog,100)) 0x100 27
[void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) })
Post $editor 0x10 0
[void](Wait-Until { ![SearchArrowTest]::IsWindow($editor) })
Post $panel 0x100 0x73
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
$editControl=Wait-Until {
$control=[SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[System.Management.Automation.Language.NullString]::Value)
if ($control -ne [IntPtr]::Zero) { $control }
}
$initialText=[IO.File]::ReadAllText($fixture)
Post $editControl 0x102 88
[void](Wait-Until { [SearchArrowTest]::Send($editControl,2159,0,0) -ne [IntPtr]::Zero })
function Open-SavePrompt {
Post $editor 0x10 0
Wait-Until {
$dialog=Find-Window '#32770' $process.Id
if ($dialog -and [SearchArrowTest]::GetDlgItem($dialog,7) -ne [IntPtr]::Zero) { $dialog }
}
}
$dialog=Open-SavePrompt
$saveButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,6))
$discardButton=Read-Bounds ([SearchArrowTest]::GetDlgItem($dialog,7))
if ($discardButton.Left-$saveButton.Right -ne $gap) { throw 'Save and F7 use different button gaps.' }
Post $editor 0x201 1
[void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) })
if (![SearchArrowTest]::IsWindow($editor) -or
[SearchArrowTest]::Send($editControl,2159,0,0) -eq [IntPtr]::Zero) {
throw 'Dismissing the save prompt did not preserve the edited document.'
}
$dialog=Open-SavePrompt
Post $dialog 0x111 7
[void](Wait-Until { ![SearchArrowTest]::IsWindow($editor) })
if ([IO.File]::ReadAllText($fixture) -ne $initialText) { throw 'Discard wrote to the file.' }
Write-Output 'Verified that dismissing the save prompt preserves edits, and Discard leaves the file untouched.'
Post $panel 0x100 0x72
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
$dialog=Open-Search
Assert-Arrow $dialog $true
Assert-MovesWithOwner $editor $dialog
Post $editor 0x201 1
[void](Wait-Until { ![SearchArrowTest]::IsWindow($dialog) })
if (![SearchArrowTest]::IsWindow($editor)) { throw 'Outside click closed the viewer.' }
Write-Output 'Verified outside-click cancellation in Copy and Viewer Search.'
Write-Output 'Verified that Copy and Search move and resize with their owners.'
Post $main 0x10 0
[void](Wait-Until { ![SearchArrowTest]::IsWindow($main) })
if (![SearchArrowTest]::IsWindow($editor)) { throw 'Closing the manager also closed the viewer.' }
Post $editor 0x10 0
if (!$process.WaitForExit(5000)) { throw 'Files did not exit after its last window closed.' }
}
finally {
if ($process -and !$process.HasExited) {
Stop-Process -Id $process.Id
[void]$process.WaitForExit(5000)
}
if ($previousDpi) { [void][SearchArrowTest]::SetThreadDpiAwarenessContext($previousDpi) }
if($paintTrace -and (Test-Path -LiteralPath $paintTrace)){Remove-Item -LiteralPath $paintTrace -Force}
foreach($name in $keysToRestore){
if($saved.ContainsKey($name)){$profile.SetValue($name,$saved[$name][0],$saved[$name][1])}
else{$profile.DeleteValue($name,$false)}
}
$profile.Dispose()
$resolved=(Resolve-Path -LiteralPath $scratch).Path
$root=(Resolve-Path -LiteralPath (Split-Path -Parent $scratch)).Path
if ([IO.Path]::GetDirectoryName($resolved) -eq $root -and (Split-Path -Leaf $resolved) -like 'search-arrow-test-*') {
Remove-Item -LiteralPath $resolved -Recurse -Force
}
}
+162
View File
@@ -0,0 +1,162 @@
#include "files_text_document.h"
#include <objbase.h>
#include <winioctl.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
namespace fs = std::filesystem;
using ks::files::TextDocument;
namespace
{
void check(bool condition, const char *message)
{
if (!condition) throw std::runtime_error(message);
}
struct Fixture
{
fs::path directory;
Fixture()
{
GUID id{};
wchar_t name[40]{};
check(SUCCEEDED(CoCreateGuid(&id)) && StringFromGUID2(id, name, 40), "Create fixture ID");
directory = fs::temp_directory_path() / (std::wstring(L"ks-files-text-") + name);
fs::create_directory(directory);
}
~Fixture()
{
std::error_code error;
fs::remove_all(directory, error);
}
};
void writeFile(const fs::path &path, const std::string &bytes)
{
std::ofstream output(path, std::ios::binary);
output.write(bytes.data(), bytes.size());
check(static_cast<bool>(output), "Write fixture");
}
std::string readFile(const fs::path &path)
{
std::ifstream input(path, std::ios::binary);
check(static_cast<bool>(input), "Read fixture");
return {std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
}
void editsAcrossPages(const fs::path &file)
{
const std::string first = std::string(TextDocument::pageBytes - 2, 'a') + "\r\n";
const std::string middle = std::string(TextDocument::pageBytes - 2, 'b') + "\r\n";
const std::string last = "last\r\n";
const std::string bom = "\xef\xbb\xbf";
writeFile(file, bom + first + middle + last);
TextDocument document(file);
check(document.pages() == 3, "Expected three pages");
check(document.readPage(1) == middle, "Read middle page");
document.stage(2, "last changed\r\n");
check(!document.modifiedWith(2, last), "Restoring the only modified page leaves no changes");
check(document.modifiedWith(0, first), "An original page must not hide changes to other pages");
document.stage(0, "first changed\n");
check(document.readPage(2) == "last changed\r\n", "Read staged page");
check(document.save(), "Replace and reopen");
check(!document.modified(), "Save clears staged page edits");
check(readFile(file) == bom + "first changed\n" + middle + "last changed\r\n",
"Save must preserve untouched bytes and the BOM");
document.stage(0, "saved again\n");
check(document.save(), "Save again through the same document");
}
void unicodeBoundaries(const fs::path &file)
{
const auto chunk = TextDocument::pageBytes;
const std::string emoji = "\xf0\x9f\x98\x80";
writeFile(file, std::string(chunk - 1, 'a') + emoji + "tail");
{
TextDocument document(file, false);
check(document.boundary(1) == chunk + 3, "UTF-8 split within a code point");
check(document.readPage(0).ends_with(emoji) && document.readPage(1) == "tail", "Read split UTF-8");
}
for (const bool little : {true, false})
{
const std::string bom = little ? "\xff\xfe" : "\xfe\xff";
const std::string letter(little ? "a\0" : "\0a", 2);
const std::string pair(little ? "\x3d\xd8\x00\xde" : "\xd8\x3d\xde\x00", 4);
std::string first;
for (size_t n = 0; n < chunk / 2 - 1; ++n) first += letter;
first += pair;
writeFile(file, bom + first + letter);
TextDocument document(file);
check(document.readPage(0).ends_with(emoji) && document.readPage(1) == "a", "Read split UTF-16");
document.stage(1, emoji);
check(document.save() && readFile(file) == bom + first + pair, "Preserve UTF-16 byte order");
}
}
void rejectExternalReplacement(const fs::path &file)
{
writeFile(file, "original");
TextDocument document(file);
document.stage(0, "editor changes");
auto later = file;
later += L".later";
auto original = file;
original += L".original";
writeFile(later, "external changes");
check(MoveFileExW(file.c_str(), original.c_str(), 0) && MoveFileExW(later.c_str(), file.c_str(), 0),
"Replace file externally");
bool rejected{};
try { document.save(); }
catch (const std::exception &) { rejected = true; }
check(rejected && document.modified() && readFile(file) == "external changes",
"Preserve external file and staged changes after conflict");
}
void sparseFile(const fs::path &file)
{
constexpr uint64_t offset = 5ULL << 30;
const auto handle = CreateFileW(file.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
check(handle != INVALID_HANDLE_VALUE, "Create sparse fixture");
DWORD count{};
if (!DeviceIoControl(handle, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &count, nullptr))
{
CloseHandle(handle);
std::cout << "Sparse fixture skipped on this file system.\n";
return;
}
LARGE_INTEGER position{};
position.QuadPart = offset;
const bool written = SetFilePointerEx(handle, position, nullptr, FILE_BEGIN) &&
WriteFile(handle, "last", 4, &count, nullptr) && count == 4;
CloseHandle(handle);
check(written, "Write beyond the 32-bit range");
TextDocument document(file);
const auto index = document.pages() - 1;
check(document.size() == offset + 4 && document.boundary(index) == offset, "Use 64-bit offsets");
check(document.readPage(index) == "last", "Read past 4 GiB");
document.stage(index, "edited");
check(document.readPage(index) == "edited", "Stage an edit past 4 GiB");
}
}
int main()
{
try
{
const Fixture fixture;
editsAcrossPages(fixture.directory / L"pages.txt");
unicodeBoundaries(fixture.directory / L"unicode.txt");
rejectExternalReplacement(fixture.directory / L"external.txt");
sparseFile(fixture.directory / L"5gib.log");
std::cout << "Files text document regressions passed.\n";
}
catch (const std::exception &error)
{
std::cerr << error.what() << '\n';
return 1;
}
}
+146 -1
View File
@@ -1,7 +1,9 @@
#include <winsock2.h>
#include <sddl.h>
#include "lan_files.h"
#include "files_lan_ipc.h"
#include <bit>
#include <atomic>
#include <fstream>
#include <iostream>
#include <thread>
@@ -17,6 +19,23 @@ void require(bool condition,const char *message)
if(!condition) throw std::runtime_error(message);
}
void verifyFilesPeerImage()
{
const fs::path install = LR"(C:\Tools\KSwitcher)";
const auto transaction = install / L".kswitcher-update-0123456789abcdef0123456789abcdef";
constexpr auto files = L"KSwitcher.Files.exe";
require(isFilesPeerImage(install / files, install), "installed Files can request LAN peers");
require(isFilesPeerImage(transaction / L"backup" / files, install),
"Files open during an update can still request LAN peers");
require(!isFilesPeerImage(transaction / L"stage" / files, install), "staged Files image is rejected");
require(!isFilesPeerImage(transaction / L"backup" / L"KSwitcher.Config.exe", install),
"another executable in the backup is rejected");
require(!isFilesPeerImage(install / L".kswitcher-update-invalid" / L"backup" / files, install),
"malformed transaction directory is rejected");
require(!isFilesPeerImage(install.parent_path() / transaction.filename() / L"backup" / files, install),
"backup outside the active installation is rejected");
}
void save(const fs::path &path,const std::string &text)
{
std::ofstream file(path,std::ios::binary|std::ios::trunc);
@@ -110,10 +129,37 @@ int main()
int result=0;
try
{
verifyFilesPeerImage();
fs::create_directory(root);
const auto client=randomHex(16),first=randomHex(16),second=randomHex(16),key=randomHex(32);
auto lookup=[&](const std::string &id){return id==client?key:std::string{};};
FilesListener a(first,lookup,0),b(second,lookup,0);
{
auto previous=std::make_unique<FilesListener>(first,lookup,0);
const auto port=previous->port();
require(port!=0,"old listener bound before restart");
FilesListener restarting(first,lookup,port);
require(restarting.port()==0,"new listener must not take over an occupied port");
previous.reset();
const auto deadline=GetTickCount64()+4000;
while(!restarting.port() && GetTickCount64()<deadline)
{
restarting.poll();
Sleep(20);
}
require(restarting.port()==port,"listener automatically recovers after its port becomes available");
std::jthread pollingRestarted([&](std::stop_token stop)
{
while(!stop.stop_requested()){restarting.poll();Sleep(5);}
});
FilesConnection recovered(FilesPeer{first,"127.0.0.1",L"Recovered",port},client,key);
checkFileReply(recovered.call({{"action","drives"}}));
}
std::atomic<bool> allowTerminal{};
std::atomic<unsigned> hibernateRequests{};
std::atomic<unsigned> updateRequests{};
FilesListener a(first,lookup,0,[&]{return allowTerminal.load();}),
b(second,lookup,0,{},[&]{++hibernateRequests;return ERROR_SUCCESS;},
[&]{++updateRequests;return ERROR_SUCCESS;});
require(a.port() && b.port() && a.port()!=b.port(),"test listeners unavailable");
std::jthread polling([&](std::stop_token stop)
{
@@ -131,6 +177,105 @@ int main()
}
catch(const std::system_error &){}
FilesConnection host(one,client,key);
{
const Json hibernate={{"action","hibernate"}};
FilesConnection target(two,client,key);
FilesConnection local;
require(local.call(hibernate).at("error")==ERROR_ACCESS_DENIED,
"local file operations cannot dispatch the LAN power action");
require(host.call(hibernate).at("error")==ERROR_ACCESS_DENIED && hibernateRequests==0,
"hibernate requires a separately enabled handler on the target");
require(target.call({{"action","hibernate"},{"command","anything"}}).at("error")
==ERROR_INVALID_PARAMETER && hibernateRequests==0,"hibernate accepts no extra parameters");
require(target.call(hibernate).at("error")==ERROR_SUCCESS && hibernateRequests==1,
"hibernate dispatches only to the addressed paired PC");
const Json update={{"action","update"}};
require(host.call(update).at("error")==ERROR_ACCESS_DENIED && updateRequests==0,
"update requires a separate handler on the target");
require(target.call({{"action","update"},{"url","https://example.invalid"}}).at("error")
==ERROR_INVALID_PARAMETER && updateRequests==0,"update cannot supply an external package");
require(target.call(update).at("error")==ERROR_SUCCESS && updateRequests==1 && hibernateRequests==1,
"update dispatches to the addressed paired PC without invoking hibernate");
}
auto deniedCommand=fileRequest("terminalRun",root);
deniedCommand["command"]="Write-Output denied";
require(host.call(deniedCommand).at("error")==ERROR_ACCESS_DENIED,"remote command allowed without consent");
allowTerminal=true;
std::string console;
const auto exit=runRemoteCommand(host,root,
L"[Console]::Out.WriteLine((Get-Location).ProviderPath); "
L"[Console]::Error.WriteLine('Тест stderr'); Write-Error 'PowerShell error'; exit 7",
[&](std::string_view part){console+=part;});
require(exit==7 && console.find(utf8(root.native()))!=console.npos &&
console.find(utf8(L"Тест stderr"))!=console.npos,"remote command output or exit code differs");
require(console.find("PowerShell error")!=console.npos && console.find("CLIXML")==console.npos,
"remote PowerShell errors were not returned as text");
console.clear();
const auto restrictionsExit=runRemoteCommand(host,root,
L"$principal=[Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()); "
L"if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -or "
L"$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::PowerUser)) { exit 8 }; "
L"$privileges=& (Join-Path $env:SystemRoot 'System32\\whoami.exe') /priv /fo csv /nh; "
L"if ($LASTEXITCODE -or ($privileges | ConvertFrom-Csv -Header Name,Description,State | "
L"Where-Object { $_.Name -like 'Se*Privilege' -and $_.Name -ne 'SeChangeNotifyPrivilege' })) { exit 9 }; "
L"Write-Output 'LAN shell is restricted'",
[&](std::string_view part){console+=part;});
require(restrictionsExit==0 && console.find("LAN shell is restricted")!=console.npos,
"remote PowerShell must run with standard user rights and without extra token privileges");
console.clear();
const auto directoryExit=runRemoteCommand(host,root,
L"Write-Progress -Activity 'Hidden progress probe' -Status 'Working'; dir",
[&](std::string_view part){console+=part;});
require(directoryExit==0 && console.find("CLIXML")==console.npos &&
console.find("Hidden progress probe")==console.npos,"remote directory command included progress metadata");
for(const auto marker:{L"dir-first-marker.txt",L"dir-second-marker.txt"})
{
save(root/marker,"remote directory fixture");
FilesConnection separateCommand(one,client,key);
console.clear();
const auto code=runRemoteCommand(separateCommand,root,L"dir",
[&](std::string_view part){console+=part;});
require(code==0 && console.find(utf8(marker))!=console.npos,
"successive remote dir commands must list the current files and exit");
}
std::stop_source cancel;
try
{
runRemoteCommand(host,root,L"[Console]::Out.WriteLine('Ready'); Start-Sleep -Seconds 30",
[&](std::string_view){cancel.request_stop();},cancel.get_token());
require(false,"remote command cancellation did not stop execution");
}
catch(const std::system_error &error)
{
require(error.code().value()==ERROR_CANCELLED,"remote terminal returned the wrong cancellation error");
}
allowTerminal=false;
require(host.call(deniedCommand).at("error")==ERROR_ACCESS_DENIED,"remote command allowed after revocation");
std::cout<<"Verified remote PowerShell consent, working directory, streamed output, exit code and cancellation.\n";
const auto edited=root/L"edited.txt", serverFile=root/L"server.txt", snapshot=root/L"snapshot.txt";
save(serverFile,"original remote content");
const auto initial=host.call(fileRequest("stat",serverFile));
checkFileReply(initial);
const FileRevision base{initial.at("size"),initial.at("modified")};
FilesConnection local;
streamFile(host,local,one.id,serverFile,snapshot,base.size,base.modified,false,false,{});
require(load(snapshot)=="original remote content","remote editor snapshot is incorrect");
save(edited,"editor writeback");
const auto changed=local.call(fileRequest("stat",edited));
checkFileReply(changed);
streamFile(local,host,"editor",edited,serverFile,changed.at("size"),changed.at("modified"),true,false,{},&base);
require(load(serverFile)=="editor writeback","remote edit did not replace the original");
save(serverFile,"an external replacement of the remote file");
try
{
streamFile(local,host,"editor",edited,serverFile,changed.at("size"),changed.at("modified"),true,false,{},&base);
require(false,"stale editor upload succeeded");
}
catch(const std::system_error &error)
{
require(error.code().value()==ERROR_FILE_INVALID,"stale editor returned the wrong error");
}
require(load(serverFile)=="an external replacement of the remote file","stale upload overwrote external edits");
const auto drives=host.call({{"action","drives"}});
checkFileReply(drives);
require(drives.at("drives").size()==static_cast<size_t>(std::popcount(GetLogicalDrives())),"drive mask differs");
+39
View File
@@ -7,6 +7,45 @@ function Reject([scriptblock]$Action,[string]$Name) { $rejected=$false; try { &
$root=Join-Path ([IO.Path]::GetTempPath()) ('KSwitcher-update-tests-'+[guid]::NewGuid().ToString('N'))
[IO.Directory]::CreateDirectory($root) | Out-Null
try {
$companionRoot=Join-Path $root 'companion-install'
$otherRoot=Join-Path $root 'other-install'
[IO.Directory]::CreateDirectory($companionRoot) | Out-Null
[IO.Directory]::CreateDirectory($otherRoot) | Out-Null
[IO.Directory]::CreateDirectory((Join-Path $companionRoot 'tools')) | Out-Null
[IO.Directory]::CreateDirectory((Join-Path $otherRoot 'tools')) | Out-Null
$companions=@()
$Journal=Join-Path $root 'update.log'
try {
foreach ($fixture in @(
@{Root=$companionRoot; Name='KSwitcher.Files.exe'},
@{Root=$companionRoot; Name='KSwitcher.Screenshot.exe'},
@{Root=$companionRoot; Name='KSwitcher.Config.exe'},
@{Root=$companionRoot; Name='KSwitcher.exe'},
@{Root=$otherRoot; Name='KSwitcher.Files.exe'},
@{Root=$companionRoot; Name='tools/StayHere.exe'},
@{Root=$otherRoot; Name='tools/StayHere.exe'})) {
$path=Join-Path $fixture.Root $fixture.Name
Copy-Item -LiteralPath (Join-Path ([Environment]::SystemDirectory) 'ping.exe') -Destination $path
$companions+=Start-Process -FilePath $path -ArgumentList '-t','127.0.0.1' -WindowStyle Hidden -PassThru
}
$oldFiles=Join-Path $companionRoot 'KSwitcher.Files.exe'
$backup=Join-Path $companionRoot '.kswitcher-update-0123456789abcdef0123456789abcdef/backup'
[IO.Directory]::CreateDirectory($backup) | Out-Null
Move-Item -LiteralPath $oldFiles -Destination $backup
Copy-Item -LiteralPath (Join-Path $backup 'KSwitcher.Files.exe') -Destination $oldFiles
$companions+=Start-Process -FilePath $oldFiles -ArgumentList '-t','127.0.0.1' -WindowStyle Hidden -PassThru
Stop-UpdateCompanions $companionRoot
Assert (@($companions[0,1,2,3,5,7] | Where-Object HasExited).Count -eq 6) 'update closes resident helpers, both Files processes and bundled StayHere in its installation'
Assert (!$companions[4].HasExited -and !$companions[6].HasExited) 'update leaves Files and StayHere from another installation running'
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'Update: Closing (KSwitcher|StayHere)' }).Count -eq 6) 'update journals every companion closure'
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'Update: Closed (KSwitcher|StayHere)' }).Count -eq 6) 'update confirms each companion exited'
} finally {
foreach ($companion in $companions) {
if (!$companion.HasExited) { $companion.Kill(); $companion.WaitForExit() }
$companion.Dispose()
}
$Journal=$null
}
$binaryInfo = [Diagnostics.FileVersionInfo]::GetVersionInfo((Resolve-Path -LiteralPath $Executable).Path)
$binaryVersion = Get-StableVersion $binaryInfo.FileVersion
Assert ($null -ne $binaryVersion) 'executable has a stable version'
+16
View File
@@ -21,3 +21,19 @@ for color, points in polygons:
im = im.resize((256,256),Image.Resampling.LANCZOS)
im.save(root / 'kswitcher.png')
im.save(root / 'kswitcher.ico', sizes=[(s,s) for s in (16,20,24,32,40,48,64,128,256)])
for mode, color in [('editor', '#4F46E5'), ('viewer', '#087C73')]:
image = Image.new('RGBA', (32*scale, 32*scale))
draw = ImageDraw.Draw(image)
draw.rounded_rectangle((scale, scale, 31*scale, 31*scale), radius=7*scale, fill=color)
if mode == 'editor':
draw.polygon([(x*scale, y*scale) for x, y in
[(7, 25), (8, 19), (20, 7), (23, 7), (26, 10), (26, 12), (14, 24)]], fill='white')
draw.line([(18*scale, 9*scale), (24*scale, 15*scale)], fill=color, width=2*scale)
else:
draw.polygon([(x*scale, y*scale) for x, y in
[(5, 16), (8, 12), (12, 9), (16, 8), (20, 9), (24, 12),
(27, 16), (24, 20), (20, 23), (16, 24), (12, 23), (8, 20)]], fill='white')
draw.ellipse((12*scale, 12*scale, 20*scale, 20*scale), fill=color)
image.resize((256, 256), Image.Resampling.LANCZOS).save(root / f'kswitcher-files-{mode}.ico',
sizes=[(s, s) for s in (16, 20, 24, 32, 40, 48, 64, 128, 256)])
+3 -1
View File
@@ -10,7 +10,9 @@ if (!(Test-Path "$deps/sdk/build/native/include/WebView2.h")) {
$assets = New-Item -ItemType Directory -Force (Join-Path $Destination 'terminal')
foreach ($package in @(
@{ Name='xterm'; Spec='@xterm/[email protected]'; Archive='xterm-xterm-6.0.0.tgz'; Files=@{'lib/xterm.js'='xterm.js'; 'css/xterm.css'='xterm.css'; 'LICENSE'='xterm-LICENSE.txt'} },
@{ Name='fit'; Spec='@xterm/[email protected]'; Archive='xterm-addon-fit-0.11.0.tgz'; Files=@{'lib/addon-fit.js'='addon-fit.js'; 'LICENSE'='addon-fit-LICENSE.txt'} }
@{ Name='fit'; Spec='@xterm/[email protected]'; Archive='xterm-addon-fit-0.11.0.tgz'; Files=@{'lib/addon-fit.js'='addon-fit.js'; 'LICENSE'='addon-fit-LICENSE.txt'} },
@{ Name='markdown-it'; Spec='[email protected]'; Archive='markdown-it-15.0.3.tgz'; Files=@{'dist/browser/markdown-it.umd.min.js'='markdown-it.js'; 'LICENSE'='markdown-it-LICENSE.txt'} },
@{ Name='mermaid'; Spec='[email protected]'; Archive='mermaid-12.3.0.tgz'; Files=@{'dist/mermaid.min.js'='mermaid.js'; 'LICENSE'='mermaid-LICENSE.txt'} }
)) {
if (!(Test-Path "$deps/$($package.Archive)")) {
& npm.cmd pack $package.Spec --pack-destination $deps.FullName --silent | Out-Host