Compare commits

...
Author SHA1 Message Date
agrynco 878ae8fce8 Release KSwitcher v0.6.98 2026-11-16 11:44:48 +02:00
agrynco edd9b2b3f9 Improve file opening, cursor redraw and the FAR-style key bar 2026-11-16 11:39:49 +02:00
agrynco 36b0002404 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 8ffafde12a Release KSwitcher v0.6.97 2026-11-16 11:24:24 +02:00
agrynco 2bd325d294 Clear the previous cursor highlight after pane selection changes 2026-11-16 11:20:20 +02:00
agrynco d4c4f9be76 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 af388be4a7 Release KSwitcher v0.6.96 2026-11-16 11:13:37 +02:00
agrynco 3efdd2ef06 Avoid file pane repaint on click and expose F8 Delete 2026-11-16 11:09:46 +02:00
agrynco 01b467e149 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 cf2dd6c419 Refresh v0.6.95 package and verify window cycling
Refs #38
2026-11-16 11:00:13 +02:00
agrynco 293c5fd47e Cycle Files editor and viewer windows with Ctrl+Tab
Refs #38
2026-11-16 10:56:47 +02:00
agrynco 1dd6d75596 Release KSwitcher v0.6.95
Refs #38
2026-11-16 10:54:13 +02:00
agrynco 1aa23636ea Improve Markdown preview, menu navigation and update shutdown
Refs #38
2026-11-16 10:49:22 +02:00
agrynco 886532f831 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 abaf73a050 Release KSwitcher v0.6.94
Refs #38
2026-11-16 10:18:44 +02:00
agrynco b16e50bee9 Render Markdown and Mermaid in KSwitcher Files
Refs #38
2026-11-16 10:13:42 +02:00
agrynco 3ed17fa6e8 Merge pull request 'Release KSwitcher v0.6.93' (#37)
Release KSwitcher v0.6.93
2026-11-16 01:26:42 +02:00
agrynco a1df56177d Release KSwitcher v0.6.93 2026-11-16 01:26:12 +02:00
agrynco 09db0e1051 Merge pull request 'Release KSwitcher v0.6.92' (#36)
Release KSwitcher v0.6.92
2026-11-16 01:19:49 +02:00
agrynco e1d8343c32 Release KSwitcher v0.6.92 2026-11-16 01:19:24 +02:00
agrynco 1ecd57a5e4 Merge pull request 'Release KSwitcher v0.6.91' (#35)
Release KSwitcher v0.6.91
2026-11-16 01:09:12 +02:00
agrynco 1ba169874a Release KSwitcher v0.6.91 2026-11-16 01:08:40 +02:00
agrynco 3037f9840e Merge pull request 'Release KSwitcher v0.6.90' (#34)
Release KSwitcher v0.6.90
2026-11-16 00:46:44 +02:00
agrynco 6b3a382f70 Release KSwitcher v0.6.90 2026-11-16 00:46:06 +02:00
agrynco ef4438359f Merge pull request 'Release KSwitcher v0.6.89' (#33)
Release KSwitcher v0.6.89
2026-11-16 00:31:10 +02:00
agrynco d2082f1593 Release KSwitcher v0.6.89 2026-11-16 00:30:48 +02:00
agrynco 57ccb2322d Merge pull request 'Release KSwitcher v0.6.88' (#32)
Release KSwitcher v0.6.88
2026-11-16 00:03:55 +02:00
agrynco 710d0cd591 Activate the Files test window before sending shortcuts 2026-11-16 00:03:42 +02:00
agrynco 8b53392b20 Release KSwitcher v0.6.88 2026-11-16 00:02:59 +02:00
agrynco 2824bef442 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 a8cf51002d Package KSwitcher v0.6.87 2026-11-15 23:49:54 +02:00
agrynco 0298e98bbe Fix remote PowerShell text output for v0.6.87 2026-11-15 23:48:53 +02:00
agrynco cc6a832c73 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 7873b1afda Package KSwitcher v0.6.86 2026-11-15 23:40:56 +02:00
agrynco 0f9e62abf2 Add approved LAN PowerShell commands and fix editor startup for v0.6.86 2026-11-15 23:39:59 +02:00
agrynco 3b4bc3f3b9 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 9649248dae Package KSwitcher v0.6.85 2026-11-15 23:10:08 +02:00
agrynco 47541dabc4 Add independent Files windows and LAN editing for v0.6.85 2026-11-15 23:09:00 +02:00
agrynco 59a07d91dc 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
40 changed files with 3922 additions and 411 deletions

No files matched your search

+29 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.84 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.98 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
@@ -47,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)
@@ -148,6 +149,33 @@ add_test(NAME files-activation-and-refresh
-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_executable(KSwitcherFilesMarkdownLanFixture WIN32 tests/files_markdown_lan.cpp
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp)
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)
+91 -2
View File
@@ -13,28 +13,81 @@ Far Manager є зразком для оформлення файлового м
Це діє і для вкладених діалогів. Під час файлової операції Cancel спершу
просить підтвердити переривання.
Спільне повідомлення Files підлаштовується під заголовок і кількість рядків.
Висота діалогу залежить від видимого вмісту. Приховані та порожні секції
не займають місця. Перед завершенням змін перевір коротке повідомлення й
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
Warning і початковий фокус на No.
## Скорочення
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
документ — у програмі, призначеній для його типу у Windows. EXE запускається
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
панелі LAN, спочатку скопіюй його до локальної папки.
- Shift+Enter відкриває поточний локальний елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
Введена в командному рядку команда зберігається.
- У головному вікні клавіатурний фокус залишається в командному рядку.
Tab перемикає активну панель, клік вибирає рядок, а стрілки вгору й вниз,
Page Up і Page Down пересувають курсор у панелі навіть під час набору команди.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
текст із буфера обміну в позицію курсора або замінюють виділення.
Enter запускає введену команду або відкриває поточний елемент, якщо рядок
порожній. Escape очищає рядок.
Промпт і текст команди вирівняні по спільній базовій лінії.
- **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+E підставляє останню команду. Повторне натискання
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
@@ -73,6 +126,10 @@ Far Manager є зразком для оформлення файлового м
а 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** у треї відкриває нове вікно.
@@ -87,8 +144,40 @@ Far Manager є зразком для оформлення файлового м
для читання. F4 відкриває спільне вікно в режимі редагування. Alt+F3
відкриває файл у програмі, призначеній Windows для цього типу, а Alt+F4
викликає зареєстровану дію Edit. Ці команди також є в меню Commands.
F10 або × закривають головне вікно Files. Файл із панелі LAN треба
спочатку скопіювати локально.
F10 або × закривають головне вікно Files. Вбудовані Viewer та Editor
відкриваються в окремих немодальних вікнах із власними кнопками на панелі
завдань Windows. При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
із підсвічуванням Markdown.
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
Вихідний текст приховано, доки Markdown і Mermaid готують перегляд.
Звичайний клік відкриває внутрішнє посилання в тому самому вікні,
Shift+клік відкриває окреме вікно. Назад і вперед працюють через стрілки
перегляду, бічні кнопки миші й Alt+←/→. Ctrl+W закриває перегляд.
Коли локальний Markdown оновлюється на диску, відкритий перегляд
перерендерюється зі збереженням позиції прокрутки.
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
8 МіБ, F3 відкриває текстовий перегляд.
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
junction не обходяться. Недоступний вміст позначається як частковий результат.
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
копії, Files відхиляє запис і залишає зміни в редакторі. Для F4 оновіть
KSwitcher також на віддаленому ПК. Alt+F3 і Alt+F4 потребують локальної копії.
- Вікно використовує той самий шрифт і розмір, що й файлові панелі,
синю палітру Far за замовчуванням,
рядок стану згори й підказки клавіш унизу. Інформація про файл
+2 -1
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
+85
View File
@@ -1,5 +1,90 @@
# Latest Windows release
## 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.
+1 -1
View File
@@ -1 +1 @@
134d6e543976c8db86b2a80b2cf0b7289eeff7bd2b11510fdafb3b32f2e79342 KSwitcher-win-x64.zip
56aa00696a0d285faf64474cb1f3b321c0681bb315807a7c70dceeb95e8469d0 KSwitcher-win-x64.zip
+95 -65
View File
@@ -1,136 +1,166 @@
{
"version": "0.6.98",
"schema": 1,
"files": [
{
"path": "KSwitcher.exe",
"size": 2342912,
"sha256": "cfe137724c1ecdef92de08de366917c9c5da998584e817444ee1d1ccf303299f"
"sha256": "222efeb00661165e15c60ce29865e36904895fee02972199a4aa22e40be24236",
"size": 2361856,
"path": "KSwitcher.exe"
},
{
"path": "KSwitcher.Config.exe",
"size": 2342912,
"sha256": "eb398e0fda3e999c4b3d137b3e8530acaa4ac792247ba4efec60a3f134d0f677"
"sha256": "8853a4bddd887fc4e35e4c3e1a3d3c3f863ac36ed509d4294516f09ae86b2c50",
"size": 2359808,
"path": "KSwitcher.Config.exe"
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3320832,
"sha256": "27d60882ff2ac7b5a689ad576a52f52c3400d497a86e7faf5649e63e27399cce"
"sha256": "27d77cd34fcb4aa6225bba12c87e76b7f410134f713754ace1b1b4cc34150979",
"size": 3337216,
"path": "KSwitcher.Screenshot.exe"
},
{
"path": "KSwitcher.Files.exe",
"size": 3618816,
"sha256": "ea5bc60f989d7f220c36196c93ac894647f4e74e9833c9abb32211e16b434149"
"sha256": "546dcfb34f4bcb7765152ab345ffca99b54b4f77445f7cd50379e07e75d4b048",
"size": 3738112,
"path": "KSwitcher.Files.exe"
},
{
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
"path": "WebView2Loader.dll"
},
{
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
"path": "terminal/addon-fit-LICENSE.txt"
},
{
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
"path": "terminal/addon-fit.js"
},
{
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
"path": "terminal/index.html"
},
{
"path": "terminal/terminal.js",
"size": 4167,
"sha256": "d60e6ff8948b6616695297695b05ef6e74b497a8e32e6031fc2e4fe2cca39ca7"
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt"
},
{
"path": "terminal/xterm-LICENSE.txt",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786,
"path": "terminal/markdown-it.js"
},
{
"sha256": "27d3c6d39325d4995162911c352a8e20603513445683ceb0409e628949c39237",
"size": 2212,
"path": "terminal/markdown.html"
},
{
"sha256": "dbf9a062364dcc90b59fd98eb0adb0f153ed95accf26e28f7be9cce8c13ae324",
"size": 6534,
"path": "terminal/markdown.js"
},
{
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt"
},
{
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838,
"path": "terminal/mermaid.js"
},
{
"sha256": "0f3edde02b30e7b0f76d0cc88daae5791d720a4b74cf8b34e7c0b4dbe0cf9c9d",
"size": 4478,
"path": "terminal/terminal.js"
},
{
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
"path": "terminal/xterm-LICENSE.txt"
},
{
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
"path": "terminal/xterm.css"
},
{
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
"path": "terminal/xterm.js"
},
{
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"path": "LICENSE"
},
{
"path": "json-LICENSE.txt",
"size": 1075,
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86"
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096,
"path": "json-LICENSE.txt"
},
{
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
"path": "files-text-license.txt"
},
{
"path": "README.md",
"size": 94223,
"sha256": "7b34f2af7341f57d7bac1b5b7e55a40595a6bc20f461f98c0c6320336d0deba7"
"sha256": "fca41227e9b38bf061298d69806ea66fb00086ae03aec49665e4f68ed2c3f8e9",
"size": 94357,
"path": "README.md"
},
{
"path": "LAN-PREVIEW.md",
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
"size": 11418,
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada"
"path": "LAN-PREVIEW.md"
},
{
"path": "dictionaries/en.txt",
"size": 682867,
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21"
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485,
"path": "dictionaries/en.txt"
},
{
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20138,
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5"
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
},
{
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
"path": "dictionaries/README.md"
},
{
"path": "dictionaries/ru.txt",
"size": 1060364,
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b"
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134,
"path": "dictionaries/ru.txt"
},
{
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
"path": "dictionaries/sources.json"
},
{
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
"path": "dictionaries/uk.txt"
},
{
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"path": "tools/README.txt"
},
{
"path": "tools/StayHere.exe",
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
"size": 134656,
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
"path": "tools/StayHere.exe"
},
{
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"path": "tools/StayHere-README.md"
}
],
"schema": 1,
"version": "0.6.84"
]
}
+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,84,0
PRODUCTVERSION 0,6,84,0
FILEVERSION 0,6,98,0
PRODUCTVERSION 0,6,98,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.84"
VALUE "FileVersion", "0.6.98"
END
END
BLOCK "VarFileInfo"
+8 -13
View File
@@ -47,24 +47,16 @@ BEGIN
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
END
607 DIALOGEX 0, 0, 300, 106
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
FONT 10, "Consolas"
BEGIN
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL | WS_TABSTOP, 18, 22, 264, 52
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 120, 80, 60, 17
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 85, 80, 60, 17
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 155, 80, 60, 17
AUTOCHECKBOX "&Remember for this session", 101, 18, 63, 264, 13, NOT WS_VISIBLE
END
609 DIALOGEX 0, 0, 185, 57
607 DIALOGEX 0, 0, 185, 57
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 100, 14, 16, 157, 13, SS_NOPREFIX
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
@@ -114,6 +106,9 @@ BEGIN
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
+41
View File
@@ -0,0 +1,41 @@
<!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: 960px; margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
nav { position: sticky; top: 0; display: flex; 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; }
: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="Document history">
<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>
</nav>
<main></main>
<script src="markdown-it.js"></script>
<script src="mermaid.js"></script>
<script src="markdown.js"></script>
</html>
+153
View File
@@ -0,0 +1,153 @@
'use strict';
const bridge = window.chrome.webview;
const content = document.querySelector('main');
const back = document.querySelector('#back');
const forward = document.querySelector('#forward');
const markdown = markdownit({ html: false, linkify: true });
let generation = 0;
let images = [];
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')) + '">';
};
function send(action, options = {}) {
bridge.postMessage(JSON.stringify({ action, ...options }));
}
function scrollToHeading(fragment) {
if (!fragment) { window.scrollTo(0, 0); return; }
try { document.getElementById(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'));
async function render({ text, fragment, scroll, title, keepPosition }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
document.documentElement.classList.remove('rendered');
document.title = title;
content.innerHTML = markdown.render(text);
const headings = new Set();
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
const base = 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');
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.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;
document.documentElement.classList.remove('rendered');
content.replaceChildren();
}
if (message.action === 'render') void render(message).catch(() => send('failed'));
if (message.action === 'anchor') restorePosition(message);
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');
+9
View File
@@ -58,6 +58,15 @@ terminal.attachCustomKeyEventHandler(event => {
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-panel-names');
}
else if (event.code === 'KeyR') {
if (!event.repeat) bridge.postMessage('refresh-panel');
}
else return true;
event.preventDefault();
return false;
+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 {
+26 -7
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"
@@ -2941,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;
@@ -3006,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));
@@ -3019,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);
}
+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;
+1 -1
View File
@@ -12,7 +12,7 @@ bool validHistoryKeys(const std::array<WORD,2> &keys)
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!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
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;
});
+15 -2
View File
@@ -64,6 +64,18 @@ public:
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_));
@@ -84,8 +96,9 @@ public:
static bool dismissOwned(HWND owner)
{
for(auto parent=GetWindow(activeFilesDialog,GW_OWNER);parent;parent=GetWindow(parent,GW_OWNER))
if(parent==owner) return PostMessageW(activeFilesDialog,WM_CLOSE,0,0)!=FALSE;
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;
}
+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;
}
}
+729 -158
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;
}
}
+32 -7
View File
@@ -1,4 +1,5 @@
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286;
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",
@@ -78,6 +79,9 @@ struct OptionsBaseline
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};
@@ -151,7 +155,10 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
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 || draft.text!=base.text;
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);
}
@@ -299,7 +306,8 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
[&](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",true)!=IDYES) return;
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;
}
@@ -420,7 +428,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
for(const auto &option:frameOptions)
SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0);
}
constexpr int commandLineControls[]{320,321,322,323};
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
show(commandLineControls,page==CommandLine && section==0);
show(textControls,textOptionsPage(page));
show(editingControls,page==TextEditor);
@@ -515,7 +523,9 @@ 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 if(page==CommandLine) addSection(L"Command history",0,matches(L"Previous command"));
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") ||
@@ -579,6 +589,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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;
@@ -692,7 +705,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);
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);
@@ -731,7 +750,7 @@ 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:
@@ -831,6 +850,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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);
@@ -876,6 +898,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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);
+62 -21
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,11 +52,20 @@ 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(bool output)
{
@@ -70,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);
@@ -85,6 +100,7 @@ public:
}
void close()
{
lifetime.reset();
if(controller) controller->Close();
web.Reset();
controller.Reset();
@@ -103,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*);
@@ -118,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)))
@@ -144,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;
});
@@ -161,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;
@@ -176,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();
+19 -3
View File
@@ -147,13 +147,21 @@ uint64_t TextDocument::pages() const
}
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,
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]);
@@ -224,8 +232,16 @@ std::string TextDocument::readPage(uint64_t page) const
std::string TextDocument::readOriginal(uint64_t page) const
{
const auto start = boundary(page);
return decode(read(source_, start, static_cast<size_t>(boundary(page + 1) - start)));
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
+2
View File
@@ -24,6 +24,7 @@ public:
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;
@@ -44,6 +45,7 @@ private:
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;
};
+920 -75
View File
File diff suppressed because it is too large. Load diff
+8 -1
View File
@@ -2,8 +2,11 @@
#include <windows.h>
#include <filesystem>
#include <string_view>
#include <vector>
namespace ks::lan { struct FilesPeer; }
namespace ks::files
{
inline constexpr int searchOptionsDivider = 104;
@@ -45,7 +48,11 @@ struct TextDialogs
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);
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
+277 -21
View File
@@ -5,7 +5,10 @@
#include <winioctl.h>
#include <atomic>
#include <bcrypt.h>
#include <wincrypt.h>
#include <sddl.h>
#include <cstring>
#include <mutex>
#include <thread>
#include "lan_files.h"
#include "lan_channel.h"
@@ -30,6 +33,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);
@@ -222,6 +236,148 @@ 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();
}
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) ||
!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");
@@ -271,6 +427,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{};
@@ -425,7 +584,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)
{
@@ -439,6 +601,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();
@@ -489,7 +671,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{};
@@ -499,6 +681,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;
@@ -517,7 +719,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")
@@ -698,6 +901,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>())
@@ -721,7 +930,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;
@@ -759,7 +968,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;
}
@@ -777,6 +992,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
@@ -792,29 +1027,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)
{
@@ -830,7 +1083,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);
@@ -849,6 +1102,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);
@@ -871,8 +1125,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();
}
+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.84";
inline constexpr wchar_t AppVersion[] = L"0.6.98";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+150 -2
View File
@@ -1,6 +1,7 @@
param(
[Parameter(Mandatory)][string]$Executable,
[Parameter(Mandatory)][string]$Fixture
[Parameter(Mandatory)][string]$Fixture,
[switch]$SystemOpenOnly
)
$ErrorActionPreference = 'Stop'
Add-Type @"
@@ -20,6 +21,9 @@ public static class FilesActivationUi {
[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);
@@ -36,6 +40,14 @@ public static class FilesActivationUi {
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)
@@ -138,7 +150,7 @@ try {
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 $rightDir "Test document$extension"
$document = Join-Path $(if($SystemOpenOnly){$leftDir}else{$rightDir}) "Test document$extension"
[IO.File]::WriteAllText($document, 'Document fixture')
$association = $classes.CreateSubKey($extension)
$association.SetValue('', $progId)
@@ -168,6 +180,54 @@ try {
$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
}
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'unsubmitted command')
$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'
}
if((Read-Text $inputBox) -cne 'unsubmitted command'){
throw 'Shift+Enter changed the draft command.'
}
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.'
return
}
Select-Row $left '..'
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr]::Zero, [IntPtr]::Zero)
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
@@ -179,6 +239,21 @@ try {
[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.'
@@ -244,6 +319,79 @@ try {
}
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.'
} finally {
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
+366
View File
@@ -0,0 +1,366 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$Screenshot,
[string]$Node = 'node',
[string]$LanFixture
)
$ErrorActionPreference = 'Stop'
Add-Type @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class MarkdownUi {
[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 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'
$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 |
- [ ] Pending
- [x] Complete
![Relative image](images/tiny%20image.png)
![Missing image](images/missing.png)
[Child](child/Other.md#target-heading)
~~~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') { $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' }
if ([MarkdownUi]::IsWindowVisible((Scintilla $window))) {
throw 'F3 showed the source text while starting the Markdown preview.'
}
Browser 'render' $Screenshot
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.' }
[MarkdownUi]::Activate($window)
Wait-Foreground $window
[MarkdownUi]::CycleWindow()
Wait-Foreground $main
[MarkdownUi]::CycleWindow()
Wait-Foreground $window
$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'
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 }
Browser 'Linked Markdown' '' 'Other.md'
[MarkdownUi]::Activate($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' }
$control = Scintilla $window
Append-Character $control 'Y'
Post $control 0x100 0x75
Answer-Save 6
Browser 'Перегляд Markdown'
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' }
Browser 'render'
Browser 'edit'
if ((Wait-For 'LAN F6 editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }) -ne $window) {
throw 'LAN F6 changed windows.'
}
$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
}
}
}
}
}
+116
View File
@@ -0,0 +1,116 @@
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);
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;
}
const target = await waitFor(async () => {
const response = await fetch('http://127.0.0.1:' + port + '/json/list').catch(() => null);
if (!response?.ok) return;
return (await response.json()).find(item => item.url === 'https://kswitcher-markdown.invalid/markdown.html' &&
(!title || item.title === title));
}, 'the Markdown page in WebView2');
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 === '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.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('input')].map(box => box.checked)`), [false, true]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => { box.click(); return box.checked; })`), [true, false]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => { box.click(); return box.checked; })`), [false, true]);
if (artifact) {
const { data } = await command('Page.captureScreenshot');
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} 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;
}
+279 -6
View File
@@ -1,4 +1,4 @@
param([Parameter(Mandatory)][string]$Executable)
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly)
$ErrorActionPreference='Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @"
@@ -10,6 +10,7 @@ public static class SearchArrowTest {
[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);
@@ -21,6 +22,33 @@ public static class SearchArrowTest {
[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 {
@@ -50,12 +78,12 @@ function Wait-Until($Block) {
}
throw "Timeout: $Block"
}
function Find-Window($Name, $ProcessId, [int]$ControlId=0) {
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 [SearchArrowTest]::IsWindowVisible($wnd) -and
if ($ownerProcess -eq $ProcessId -and $wnd -ne $Except -and [SearchArrowTest]::IsWindowVisible($wnd) -and
(!$ControlId -or [SearchArrowTest]::GetDlgItem($wnd,$ControlId) -ne [IntPtr]::Zero)) { return $wnd }
}
}
@@ -67,6 +95,23 @@ function Select-Row($Panel, $Name) {
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
@@ -86,6 +131,28 @@ function Read-Bounds($Window) {
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))
@@ -164,12 +231,94 @@ $scratch=Join-Path ([IO.Path]::GetDirectoryName((Resolve-Path -LiteralPath $Exec
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
$process = Start-Process -FilePath $copy -PassThru -WindowStyle Hidden
$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)
@@ -186,6 +335,71 @@ try {
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 }
@@ -217,6 +431,7 @@ try {
[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
@@ -269,7 +484,11 @@ try {
Post $selector 0x100 0x73
$popup=Wait-Until { Find-Window 'KSwitcher.Files.DropDown' $process.Id }
Assert-FarDropDown $popup $selector ($arrowBounds.Right-$arrowBounds.Left)
for ($row=0; $row -lt $kind; $row++) { Post $popup 0x100 0x28 }
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) })
@@ -432,10 +651,48 @@ try {
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)
@@ -443,6 +700,11 @@ try {
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
@@ -550,13 +812,24 @@ try {
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.HasExited) {
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-*') {
+124 -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,83 @@ 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 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");
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'
+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