Compare commits

..
28 Commits
Author SHA1 Message Date
agrynco 0addc663c2 Merge pull request 'Release KSwitcher v0.6.105 with document icons and the elevated LAN PowerShell fix' (#50) from codex/release-v0.6.105 into main 2026-11-16 17:52:02 +02:00
agrynco 9360991fab Record the package manifest for KSwitcher v0.6.105
Refs #8, #38
2026-11-16 17:50:53 +02:00
agrynco 01a97c9ca4 Separate the Files editor and viewer icons for v0.6.105
Publish the generated Windows ZIP as a Gitea release asset without adding a copy to Git.

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

Refs #8
2026-11-16 14:49:42 +02:00
agrynco 22b785e5ef Merge pull request 'Release KSwitcher v0.6.102 with command copy and LAN startup error handling' (#47) from codex/release-v0.6.102 into main 2026-11-16 14:20:22 +02:00
agrynco e6dd5108eb Package KSwitcher v0.6.102 2026-11-16 14:19:57 +02:00
agrynco 7bc5b9396b Fix command-line copy and prevent LAN startup dialogs
Refs #8
2026-11-16 14:18:13 +02:00
agrynco 23c49ce8bf Merge pull request 'Release KSwitcher v0.6.101 with panel Enter and compact Computers' (#46) from codex/release-v0.6.101 into main 2026-11-16 13:57:54 +02:00
agrynco a94c9dad14 Package KSwitcher v0.6.101 2026-11-16 13:57:39 +02:00
agrynco 553a2a0fa5 Release compact Computers and panel Enter fixes for v0.6.101
Refs #8
2026-11-16 13:57:39 +02:00
agrynco c01dfe8569 Merge pull request 'Release KSwitcher v0.6.100 with terminal Enter fix' (#45) from codex/release-v0.6.100 into main 2026-11-16 13:35:34 +02:00
agrynco 6b79f21a95 Package KSwitcher v0.6.100 2026-11-16 13:35:29 +02:00
agrynco 44b123b586 Fix Enter from the Files terminal output for v0.6.100
Refs #8
2026-11-16 13:31:06 +02:00
agrynco cb2f0a385b Merge pull request 'Release KSwitcher v0.6.99 with command line priority fix' (#44) from codex/release-v0.6.99 into main 2026-11-16 13:09:30 +02:00
agrynco 18c2b99dd5 Release KSwitcher v0.6.99 2026-11-16 13:09:20 +02:00
agrynco 2f7e97f13a Give the Files command line priority when submitting input 2026-11-16 13:05:12 +02:00
agrynco a82a99d21e Merge pull request 'Release KSwitcher v0.6.98 with Files shortcuts and FAR key bar' (#43) from codex/release-v0.6.98 into main 2026-11-16 11:45:02 +02:00
agrynco c9417e3d2c Release KSwitcher v0.6.98 2026-11-16 11:44:48 +02:00
agrynco 12e7b3e2fc Improve file opening, cursor redraw and the FAR-style key bar 2026-11-16 11:39:49 +02:00
agrynco d57b064d74 Merge pull request 'Release KSwitcher v0.6.97 with cursor highlight fix' (#42) from codex/release-v0.6.97 into main 2026-11-16 11:24:35 +02:00
agrynco 49ad7104fe Release KSwitcher v0.6.97 2026-11-16 11:24:24 +02:00
agrynco cc6615cb74 Clear the previous cursor highlight after pane selection changes 2026-11-16 11:20:20 +02:00
32 changed files with 1465 additions and 213 deletions

No files matched your search

+1
View File
@@ -4,5 +4,6 @@
/.vs/
/.idea/
/dist/
/Release/KSwitcher-win-x64.zip
/build-output.txt
*.user
+16 -2
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.96 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.105 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
@@ -149,10 +149,22 @@ 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_test(NAME files-terminal-enter
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
-TerminalOnly -Node "${KSWITCHER_NODE}")
set_tests_properties(files-terminal-enter PROPERTIES RUN_SERIAL TRUE TIMEOUT 90)
add_executable(KSwitcherFilesMarkdownLanFixture WIN32 tests/files_markdown_lan.cpp
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp)
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText)
@@ -187,6 +199,8 @@ else()
target_link_options(KSwitcherChatProfileTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests)
add_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout)
set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
target_link_libraries(KSwitcherHistoryHostTests PRIVATE kscore psapi)
set_target_properties(KSwitcherHistoryHostTests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/history-host-fixture-$<CONFIG>")
+35 -9
View File
@@ -32,18 +32,28 @@ Warning і початковий фокус на No.
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
панелі LAN, спочатку скопіюй його до локальної папки.
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
- У головному вікні клавіатурний фокус залишається в командному рядку.
Tab перемикає активну панель, клік вибирає рядок, а стрілки вгору й вниз,
Page Up і Page Down пересувають курсор у панелі навіть під час набору команди.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
текст із буфера обміну в позицію курсора або замінюють виділення.
Enter запускає введену команду або відкриває поточний елемент, якщо рядок
порожній. Escape очищає рядок.
Enter і Shift+Enter спочатку виконують введену команду. Коли рядок
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
Enter передає порожній рядок у термінал. Escape очищає рядок.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
Промпт і текст команди вирівняні по спільній базовій лінії.
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
що й клавіша F8.
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
а назви дій темні на бірюзових сегментах.
- У віддаленій панелі Enter запускає введену команду PowerShell на
спареному ПК в поточному каталозі цієї панелі. Вивід і код завершення
з’являються в терміналі Files як текст. Службовий прогрес PowerShell
@@ -76,11 +86,13 @@ Warning і початковий фокус на No.
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
зберігаються для наявних елементів, а підраховані через F3 розміри папок
скидаються. F2 також виконує цю дію.
- Ctrl+C копіює весь введений у командний рядок текст, навіть коли виділено
лише його частину.
- Ctrl+Insert копіює імена позначених файлів і папок активної панелі в порядку
відображення, по одному на рядок. Якщо позначок немає, копіюється ім’я під
курсором. Шляхи й рядок `..` пропускаються.
- Ctrl+C і Ctrl+Insert копіюють виділений текст із виводу термінала.
- За відсутності виділення у виводі Ctrl+C копіює весь введений у командний
рядок текст, навіть коли виділено лише його частину.
- Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок
порожній, копіюються імена позначених файлів і папок активної панелі в
порядку відображення, по одному на рядок. Якщо позначок немає, копіюється
ім’я під курсором. Шляхи й рядок `..` пропускаються.
- Ctrl+E підставляє останню команду. Повторне натискання
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
@@ -138,8 +150,10 @@ Warning і початковий фокус на No.
відкриває файл у програмі, призначеній Windows для цього типу, а Alt+F4
викликає зареєстровану дію Edit. Ці команди також є в меню Commands.
F10 або × закривають головне вікно Files. Вбудовані Viewer та Editor
відкриваються в окремих немодальних вікнах із власними кнопками на панелі
завдань Windows. При повторному відкритті Files пропонує перейти до вже
відкриваються в окремих немодальних вікнах. Редактор має іконку олівця,
переглядач — іконку ока. Ці іконки видно в заголовку, в Alt+Tab і в окремих
групах на панелі завдань Windows. F6 змінює іконку й групу поточного вікна.
При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
@@ -150,11 +164,18 @@ Warning і початковий фокус на No.
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
із підсвічуванням Markdown.
HTML усередині Markdown підтримує таблиці, текстове форматування, посилання,
відносні зображення й окремі стилі, зокрема `white-space: nowrap` у клітинках.
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
Вихідний текст приховано, доки Markdown і Mermaid готують перегляд.
Звичайний клік відкриває внутрішнє посилання в тому самому вікні,
Shift+клік відкриває окреме вікно. Назад і вперед працюють через стрілки
перегляду, бічні кнопки миші й Alt+←/→. Ctrl+W закриває перегляд.
Ctrl+F або кнопка пошуку відкриває пошук у відрендерованому документі.
Пошук без урахування регістру показує кількість збігів і підсвічує поточний.
Enter і F3 переходять до наступного збігу, а Shift+Enter і Shift+F3 — до
попереднього, циклічно. Escape спочатку закриває поле пошуку.
Коли локальний Markdown оновлюється на диску, відкритий перегляд
перерендерюється зі збереженням позиції прокрутки.
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
@@ -200,6 +221,11 @@ Warning і початковий фокус на No.
кодування. Нередаговані байти копіюються без перетворення.
- Команда Options у панелях, редакторі й переглядачі відкриває один діалог
KSwitcher Files Options. Розділи Viewer та Editor зберігають окремі профілі.
**Viewer → Markdown** задає максимальну ширину документа (0 — усе вікно),
гарнітуру та розмір основного тексту. Порожня гарнітура використовує системний
шрифт. Apply одразу оновлює відкриті перегляди Markdown.
Після повторного відкриття Options відновлюється останній розділ, зокрема
після Cancel. Пошуковий запит і чернетка змін не зберігаються.
З редактора або переглядача діалог відкриває відповідний розділ. Apply
застосовує зміни до відкритих вікон, Cancel відкидає незастосовану чернетку.
Доступні перенесення рядків, номери рядків, показ пробілів і
+2
View File
@@ -39,6 +39,8 @@ the local resident process running and log downloads enabled on the remote PC.
1. Install the v0.6.58 or newer on every participating PC. Input protocol v2 requires all participants to update; earlier one-pair builds cannot connect. Preserve local data; do not copy pairing identities between PCs.
2. Open **Settings → Computers → Manage computers…** and enable discovery on both PCs.
Only running LAN-enabled KSwitcher instances appear, not generic network devices.
The computer list and pairing controls are on the left, the monitor grid and
input sharing are on the right, and file, log and help actions are below.
3. Match the computer name and instance-ID prefix displayed on the other PC.
Select each other, generate one code, enter that same code on both, then click
Pair on both within two minutes. Spaces, hyphens and uppercase hex are accepted.
+4 -2
View File
@@ -921,8 +921,10 @@ CC BY-SA 4.0; attribution, pinned source revision and license are in `dictionari
## Latest compiled release
The [Release folder](Release/README.md) contains the latest portable Windows x64 ZIP and SHA-256 checksum.
Run `./package.ps1 -PublishRelease` after building and testing to refresh the tracked release archive.
Download the portable Windows x64 ZIP from [Gitea Releases](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases).
The [Release folder](Release/README.md) tracks the release notes, manifest and SHA-256 checksum.
Run `./package.ps1 -PublishRelease` after building and testing, then upload the generated ZIP,
manifest and checksum as release assets.
## Verification
Binary file not shown.
+54
View File
@@ -1,5 +1,59 @@
# Latest Windows release
## v0.6.105 — 2026-11-16
KSwitcher Files gives the Editor a pencil icon and the Viewer an eye icon. The two modes have separate taskbar groups, and **F6** switches the icon and group in the same window. On a PC running KSwitcher as administrator, LAN PowerShell commands such as `dir` now start with standard user rights. This fixes the `0xC0000142` startup failure on that path. This release replaces v0.6.104.
**Українською.** Редактор KSwitcher Files має іконку олівця, а переглядач — іконку ока. Режими мають окремі групи на панелі завдань Windows, і **F6** перемикає іконку й групу в тому самому вікні. Якщо KSwitcher на ПК-отримувачі запущено від адміністратора, команди PowerShell через LAN, зокрема `dir`, запускаються з правами звичайного користувача. Виправлено помилку запуску `0xC0000142` у цьому сценарії. Цей реліз замінює v0.6.104.
## v0.6.104 — 2026-11-16
**Ctrl+F** or the search icon opens search in the rendered KSwitcher Files Markdown preview. Search ignores case and highlights the current match. **Enter** or **F3** moves to the next match, and **Shift+Enter** or **Shift+F3** moves back. **Escape** closes the search first. This release includes the HTML, Markdown appearance, Options and terminal copy updates from v0.6.103.
**Українською.** **Ctrl+F** або піктограма пошуку відкриває пошук у відрендерованому Markdown у KSwitcher Files. Пошук ігнорує регістр і підсвічує поточний збіг. **Enter** або **F3** переходить до наступного збігу, а **Shift+Enter** або **Shift+F3** повертає до попереднього. **Escape** спочатку закриває пошук. Реліз включає підтримку HTML, налаштування вигляду Markdown, запам’ятовування розділу Options і копіювання з термінала з v0.6.103.
## v0.6.103 — 2026-11-16
The KSwitcher Files Markdown preview renders embedded HTML tables and inline styles such as `white-space: nowrap`. **Options → Viewer → Markdown** sets the preview width, font family and font size. Files Options reopens the last section. **Ctrl+C** and **Ctrl+Insert** copy selected terminal output. This release replaces v0.6.102.
**Українською.** Перегляд Markdown у KSwitcher Files відображає вбудовані HTML-таблиці й стилі, зокрема `white-space: nowrap`. У **Options → Viewer → Markdown** можна задати ширину перегляду, гарнітуру й розмір шрифту. Options відкриває останній відвіданий розділ. **Ctrl+C** і **Ctrl+Insert** копіюють виділений текст із виводу термінала. Цей реліз замінює v0.6.102.
## v0.6.102 — 2026-11-16
In KSwitcher Files, Ctrl+Insert copies the full command line when it contains text. With an empty command line, it copies names from the active pane. The LAN host returns Windows PowerShell startup errors without waiting for a system error dialog. Files explains DLL initialization failure `0xC0000142` and accepts another command. This release replaces v0.6.101.
**Українською.** У KSwitcher Files Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок порожній, копіюються імена з активної панелі. ПК, який приймає LAN-команду, повертає помилки запуску Windows PowerShell без очікування системного діалогу. Files пояснює помилку ініціалізації DLL `0xC0000142` і знову приймає команди. Цей реліз замінює v0.6.101.
## v0.6.101 — 2026-11-16
In KSwitcher Files, Enter opens the selected item when the command line is empty, including when focus is in the terminal output. The Computers window places pairing and the monitor grid side by side so the bottom actions fit at high display scaling. This release replaces v0.6.100.
**Українською.** У KSwitcher Files Enter відкриває вибраний елемент, коли командний рядок порожній, зокрема коли фокус у виводі термінала. У вікні Computers спарювання та схема моніторів розташовані поруч, тож нижні дії поміщаються і при високому масштабі. Цей реліз замінює v0.6.100.
## v0.6.100 — 2026-11-16
In KSwitcher Files, Enter and Shift+Enter submit the command line when focus is in the terminal output. The terminal scrolls to the latest output when a command is submitted. While a LAN command is still running, Files shows how to cancel it and keeps the next command in the input field. This release replaces v0.6.99.
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують введену команду, коли фокус у виводі термінала. Під час запуску команди термінал прокручується до останнього виводу. Поки виконується LAN-команда, Files показує, як її скасувати, і зберігає наступну команду в полі вводу. Цей реліз замінює v0.6.99.
## v0.6.99 — 2026-11-16
In KSwitcher Files, Enter and Shift+Enter run the command in the command line, including when the file panes are hidden. With visible panes and an empty command line, the keys act on the selected item. A command reveals the terminal output if it was hidden. This release replaces v0.6.98.
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують команду з командного рядка, зокрема коли файлові панелі приховані. Коли панелі видимі й рядок порожній, клавіші діють на вибраний елемент. Якщо вивід термінала приховано, команда відкриває його. Цей реліз замінює v0.6.98.
## v0.6.98 — 2026-11-16
In Files, Enter opens folders in the current pane, uses the Windows default action for local files, and runs BAT and CMD in the embedded terminal. Shift+Enter opens local folders in File Explorer and passes files, including BAT and CMD, to Windows. It preserves the draft command. Left and Right clear the previous cursor highlight when jumping to the first or last row. The FAR-style key bar uses gray key labels on black and dark action names on teal.
**Українською.** У Files Enter відкриває папки в поточній панелі, викликає стандартну дію Windows для локальних файлів, а BAT і CMD запускає у вбудованому терміналі. Shift+Enter відкриває локальні папки у Провіднику й передає файли, зокрема BAT і CMD, Windows. Чернетка команди зберігається. Стрілки вліво й вправо скидають старе підсвічування при переході до першого чи останнього рядка. Нижній рядок клавіш у стилі FAR має сірі позначення клавіш на чорному тлі й темні назви дій на бірюзовому.
## v0.6.97 — 2026-11-16
KSwitcher Files clears the highlight from the previous cursor row after a selection change and highlights the new row. It keeps the targeted repaint introduced in v0.6.96. This release replaces v0.6.96.
**Українською.** KSwitcher Files знімає підсвічування з попереднього рядка курсора після зміни вибору й виділяє новий рядок. Панель і далі перемальовує лише потрібні рядки. Цей реліз замінює v0.6.96.
## v0.6.96 — 2026-11-16
Clicking a file row in Files now redraws only the affected cursor rows, including when switching panes. The key bar adds **F8 Delete**, which opens the same confirmation as pressing F8.
+1 -1
View File
@@ -1 +1 @@
feec0c9bb0b45f1118524e5b358938c41d2d7fa065e0bbf739d5ca0dd7267b3e KSwitcher-win-x64.zip
41b5353f049d7c6da5e664dda316e1308c5e996cdbd5a7a9b51689c02dda8674 KSwitcher-win-x64.zip
+46 -46
View File
@@ -1,166 +1,166 @@
{
"files": [
{
"size": 2361856,
"path": "KSwitcher.exe",
"sha256": "89472489f12d46b44ebe2732b9cf3c330c2c981241b0ea18eea895322b404b27"
"size": 2362368,
"sha256": "87a61d636e941adc8b37385dd72fa0e15248368867adc301df5f3af894938e24"
},
{
"size": 2359808,
"path": "KSwitcher.Config.exe",
"sha256": "ad2836f34eed4bd69c53fec6cc657899ddf843edbc044fce367b7b2c7d46b43a"
"size": 2360320,
"sha256": "ea5640173dd0c0338d0b6843f737595b2c67793cceb1202e7e293ca42fe835b8"
},
{
"size": 3337216,
"path": "KSwitcher.Screenshot.exe",
"sha256": "71fada8b0e4248cb524bc70e3be4451a794c9a6db3fe218bbf4d0e700fd41293"
"size": 3337728,
"sha256": "c785ed267aeb3e1c1c27a8aa8fe296a98283553af3d67a9ee171fc873f4dd58c"
},
{
"size": 3736576,
"path": "KSwitcher.Files.exe",
"sha256": "6110e13aa7776a76e13d7b78a077d527ad01e38902be608b54180fd6c5d312f7"
"size": 3801088,
"sha256": "6cbb9cf16e251f618e543d0af3a014932123f455ed9a2c04f86c948a5852987e"
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"size": 527,
"path": "terminal/index.html",
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"size": 100786,
"path": "terminal/markdown-it.js",
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"size": 2212,
"path": "terminal/markdown.html",
"sha256": "27d3c6d39325d4995162911c352a8e20603513445683ceb0409e628949c39237"
"size": 3530,
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
},
{
"size": 6534,
"path": "terminal/markdown.js",
"sha256": "dbf9a062364dcc90b59fd98eb0adb0f153ed95accf26e28f7be9cce8c13ae324"
"size": 14660,
"sha256": "fe202fa3d3c362aff2ab9028b40bd2aee61240bf9bd4a44af55e45d1a4081cf0"
},
{
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"size": 5537838,
"path": "terminal/mermaid.js",
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"size": 4478,
"path": "terminal/terminal.js",
"sha256": "0f3edde02b30e7b0f76d0cc88daae5791d720a4b74cf8b34e7c0b4dbe0cf9c9d"
"size": 5033,
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a"
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"size": 7112,
"path": "terminal/xterm.css",
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"size": 488663,
"path": "terminal/xterm.js",
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"size": 4401,
"path": "LICENSE",
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
},
{
"size": 1096,
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
"size": 1075,
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86"
},
{
"size": 883,
"path": "files-text-license.txt",
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"size": 94357,
"path": "README.md",
"sha256": "fca41227e9b38bf061298d69806ea66fb00086ae03aec49665e4f68ed2c3f8e9"
"size": 94502,
"sha256": "b4b561d2bdf1ef80291c3abcadb625407b94279185fd33fd9dc113658ab9b486"
},
{
"size": 11418,
"path": "LAN-PREVIEW.md",
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada"
"size": 11577,
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
},
{
"size": 732485,
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
"size": 682867,
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21"
},
{
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
"size": 20138,
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5"
},
{
"size": 2265,
"path": "dictionaries/README.md",
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"size": 1109134,
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
"size": 1060364,
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b"
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"size": 993,
"path": "tools/README.txt",
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
},
{
"size": 134656,
"path": "tools/StayHere.exe",
"size": 134656,
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
],
"version": "0.6.96",
"version": "0.6.105",
"schema": 1
}
+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,96,0
PRODUCTVERSION 0,6,96,0
FILEVERSION 0,6,105,0
PRODUCTVERSION 0,6,105,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -20,7 +20,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.6.96"
VALUE "FileVersion", "0.6.105"
END
END
BLOCK "VarFileInfo"
+10
View File
@@ -1,11 +1,14 @@
#pragma code_page(65001)
#include <windows.h>
#include <commctrl.h>
#include "resource.h"
#define FAR_EDIT(id, mode, x, y, width, height) \
CONTROL "", id, "KSwitcher.Files.FarEdit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height
1 ICON "kswitcher-files.ico"
IDI_FILES_VIEWER ICON "kswitcher-files-viewer.ico"
IDI_FILES_EDITOR ICON "kswitcher-files-editor.ico"
1 RT_MANIFEST "app.manifest"
601 RCDATA "files-text-license.txt"
@@ -144,6 +147,13 @@ BEGIN
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
LTEXT "", 367, 345, 184, 45, 12
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12
EDITTEXT 376, 131, 68, 168, 14, ES_AUTOHSCROLL
PUSHBUTTON "Choose &font…", 377, 306, 68, 76, 14
LTEXT "Font &size (8–72 pt)", 378, 131, 99, 184, 12
EDITTEXT 379, 318, 96, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+2
View File
@@ -1,4 +1,6 @@
#pragma once
#define IDI_KSWITCHER 101
#define IDI_SCREENSHOT_QUESTION 102
#define IDI_FILES_VIEWER 103
#define IDI_FILES_EDITOR 104
#define IDC_SCREENSHOT_PENCIL 500
+18 -3
View File
@@ -7,13 +7,20 @@
<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; }
body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); }
nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; }
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
nav button:hover:not(:disabled) { text-decoration: underline; }
nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
#search { margin-inline-start: auto; display: flex; align-items: center; gap: .35em;
flex: 0 1 22em; min-width: 0; max-width: 100%; }
#search[hidden] { display: none; }
#search-query { box-sizing: border-box; flex: 1; min-width: 0; width: 0; font: inherit; }
#search-status { white-space: nowrap; font-size: .8em; }
::highlight(markdown-search-active) { background: #ffab45; color: #171717; }
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
a { color: LinkText; }
@@ -30,9 +37,17 @@ figure { margin: 1em 0; }
.task { list-style: none; }
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
</style>
<nav aria-label="Document history">
<nav aria-label="Markdown preview">
<button id="back" type="button" title="Back (Alt+Left)" aria-label="Back" disabled>←</button>
<button id="forward" type="button" title="Forward (Alt+Right)" aria-label="Forward" disabled>→</button>
<button id="search-open" type="button" title="Find (Ctrl+F)" aria-label="Find in document" aria-controls="search" aria-expanded="false">⌕</button>
<div id="search" role="search" hidden>
<input id="search-query" type="search" aria-label="Find in document" placeholder="Find in document" autocomplete="off">
<output id="search-status" for="search-query" aria-live="polite"></output>
<button id="search-previous" type="button" title="Previous match (Shift+Enter)" aria-label="Previous match" disabled>↑</button>
<button id="search-next" type="button" title="Next match (Enter)" aria-label="Next match" disabled>↓</button>
<button id="search-close" type="button" title="Close search (Esc)" aria-label="Close search">×</button>
</div>
</nav>
<main></main>
<script src="markdown-it.js"></script>
+179 -5
View File
@@ -4,9 +4,17 @@ 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 });
const searchOpen = document.querySelector('#search-open');
const search = document.querySelector('#search');
const searchQuery = document.querySelector('#search-query');
const searchStatus = document.querySelector('#search-status');
const searchPrevious = document.querySelector('#search-previous');
const searchNext = document.querySelector('#search-next');
const markdown = markdownit({ html: true, linkify: true });
let generation = 0;
let images = [];
let matches = [];
let activeMatch = -1;
mermaid.initialize({
startOnLoad: false,
@@ -42,13 +50,60 @@ markdown.renderer.rules.image = (tokens, i) => {
return '<img alt="' + escape(alt) + '" data-path="' + escape(token.attrGet('src')) + '">';
};
const htmlTags = new Set(`a abbr address article aside b blockquote br caption code col colgroup dd del
details div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hr i img input ins kbd li
mark ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
tr u ul var wbr`.split(/\s+/));
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
const tagAttributes = {
a: ['href'], col: ['span'], colgroup: ['span'], details: ['open'], img: ['alt', 'width', 'height'],
input: ['type', 'checked', 'disabled'], ol: ['start', 'reversed', 'type'], li: ['value'],
td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan', 'scope'], time: ['datetime']
};
const inlineStyles = ['white-space', 'text-align', 'vertical-align', 'color', 'background-color',
'font-weight', 'font-style', 'text-decoration-line', 'width', 'max-width'];
function relativeResource(path) {
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
}
function renderContent(text) {
// Parse in an inert template and allow only document markup before attaching it to the preview.
const template = document.createElement('template');
template.innerHTML = markdown.render(text);
for (const element of template.content.querySelectorAll('*')) {
const tag = element.localName;
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
(tag === 'input' && element.type !== 'checkbox')) {
element.remove();
continue;
}
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
const styles = element.hasAttribute('style')
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
for (const { name } of [...element.attributes]) {
if (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name)) element.removeAttribute(name);
}
for (const [name, value] of styles) {
if (value) element.style.setProperty(name, value);
}
if (relativeResource(imagePath)) element.dataset.path = imagePath;
if (tag === 'a' && element.hasAttribute('href')) {
const path = element.getAttribute('href').trim();
if (relativeResource(path) || /^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i.test(path)) element.setAttribute('href', path);
else element.removeAttribute('href');
}
}
content.replaceChildren(template.content);
}
function send(action, options = {}) {
bridge.postMessage(JSON.stringify({ action, ...options }));
}
function scrollToHeading(fragment) {
if (!fragment) { window.scrollTo(0, 0); return; }
try { document.getElementById(decodeURIComponent(fragment))?.scrollIntoView(); } catch {}
try { content.querySelector('#' + CSS.escape(decodeURIComponent(fragment)))?.scrollIntoView(); } catch {}
}
function restorePosition({ fragment, scroll }) {
@@ -64,15 +119,114 @@ function navigate(action) {
back.addEventListener('click', () => navigate('back'));
forward.addEventListener('click', () => navigate('forward'));
function updateSearch(reveal = true) {
matches = [];
activeMatch = -1;
const query = searchQuery.value.trim();
if (query) {
const pattern = query.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
const expression = new RegExp(pattern, 'giu');
const blockTags = 'article,aside,blockquote,caption,dd,div,dt,figcaption,footer,h1,h2,h3,h4,h5,h6,header,li,p,pre,section,summary,td,th,text';
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
let block = null;
let parts = [];
let text = '';
const searchBlock = () => {
let first = 0;
let last = 0;
for (const match of text.matchAll(expression)) {
const end = match.index + match[0].length;
while (parts[first].end <= match.index) ++first;
last = Math.max(last, first);
while (parts[last].end < end) ++last;
matches.push([parts[first].node, match.index - parts[first].start,
parts[last].node, end - parts[last].start]);
}
parts = [];
text = '';
};
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const element = node.parentElement;
if (!node.length || element.closest('style,svg title,svg desc,svg defs') ||
!element.checkVisibility({ visibilityProperty: true })) continue;
const nextBlock = element.closest(blockTags);
if (block !== nextBlock) searchBlock();
block = nextBlock;
const start = text.length;
text += node.data;
parts.push({ node, start, end: text.length });
}
searchBlock();
}
showSearchMatch(matches.length ? 0 : -1, reveal);
}
function showSearchMatch(index, reveal) {
activeMatch = index;
searchPrevious.disabled = searchNext.disabled = matches.length < 2;
searchStatus.value = !searchQuery.value.trim() ? '' : index < 0 ? 'No matches' : (index + 1) + ' / ' + matches.length;
CSS.highlights.delete('markdown-search-active');
if (index < 0) return;
const [start, from, end, to] = matches[index];
const range = new Range();
range.setStart(start, from);
range.setEnd(end, to);
CSS.highlights.set('markdown-search-active', new Highlight(range));
if (!reveal) return;
const rect = range.getBoundingClientRect();
const toolbarBottom = search.parentElement.getBoundingClientRect().bottom;
if (rect.top < toolbarBottom || rect.bottom > innerHeight) {
scrollBy(0, rect.top - Math.max(toolbarBottom, innerHeight / 2));
}
const scroller = start.parentElement.closest('pre, table');
if (scroller) {
const bounds = scroller.getBoundingClientRect();
if (rect.left < bounds.left || rect.right > bounds.right) {
scroller.scrollLeft += rect.left - bounds.left;
}
}
}
function openSearch() {
search.hidden = false;
searchOpen.setAttribute('aria-expanded', 'true');
searchQuery.focus({ preventScroll: true });
searchQuery.select();
}
function closeSearch() {
if (search.hidden) return false;
const hadFocus = search.contains(document.activeElement);
search.hidden = true;
searchOpen.setAttribute('aria-expanded', 'false');
searchQuery.value = '';
updateSearch();
if (hadFocus) searchOpen.focus({ preventScroll: true });
return true;
}
function stepSearch(direction) {
if (search.hidden) openSearch();
else if (matches.length) showSearchMatch((activeMatch + direction + matches.length) % matches.length, true);
}
searchOpen.addEventListener('click', openSearch);
document.querySelector('#search-close').addEventListener('click', closeSearch);
searchQuery.addEventListener('input', () => updateSearch());
searchPrevious.addEventListener('click', () => stepSearch(-1));
searchNext.addEventListener('click', () => stepSearch(1));
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
async function render({ text, fragment, scroll, title, keepPosition }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
else closeSearch();
document.documentElement.classList.remove('rendered');
document.title = title;
content.innerHTML = markdown.render(text);
renderContent(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, '-');
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
let id = base;
for (let n = 1; headings.has(id); ++n) id = base + '-' + n;
heading.id = id;
@@ -97,6 +251,7 @@ async function render({ text, fragment, scroll, title, keepPosition }) {
}
restorePosition({ fragment, scroll });
document.documentElement.classList.add('rendered');
if (!search.hidden) updateSearch(false);
send('rendered');
}
@@ -116,7 +271,16 @@ document.addEventListener('pointerup', event => {
});
document.addEventListener('keydown', event => {
if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
if (event.isComposing) return;
if (event.ctrlKey && !event.altKey && event.key.toLowerCase() === 'f') {
event.preventDefault();
openSearch();
} else if (event.key === 'F3' || (event.key === 'Enter' && event.target === searchQuery)) {
event.preventDefault();
stepSearch(event.shiftKey ? -1 : 1);
} else if (event.key === 'Escape' && closeSearch()) {
event.preventDefault();
} else if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
event.preventDefault();
send('cycle');
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
@@ -134,11 +298,21 @@ bridge.addEventListener('message', ({ data }) => {
const message = JSON.parse(data);
if (message.action === 'clear') {
++generation;
closeSearch();
document.documentElement.classList.remove('rendered');
content.replaceChildren();
}
if (message.action === 'render') void render(message).catch(() => send('failed'));
if (message.action === 'appearance') {
const style = document.documentElement.style;
style.setProperty('--markdown-width', message.width ? message.width + 'px' : 'none');
style.setProperty('--markdown-font-size', message.fontSize + 'pt');
style.setProperty('--markdown-font', message.font ? CSS.escape(message.font) + ', system-ui, sans-serif' : 'system-ui, sans-serif');
}
if (message.action === 'anchor') restorePosition(message);
if (message.action === 'find') openSearch();
if (message.action === 'find-next') stepSearch(message.previous ? -1 : 1);
if (message.action === 'escape' && !closeSearch()) send('close');
if (message.action === 'back' || message.action === 'forward') navigate(message.action);
if (message.action === 'history') {
back.disabled = !message.back;
+17 -2
View File
@@ -3,7 +3,7 @@ const terminal = new Terminal({
fontFamily: 'Consolas, monospace',
fontSize: 16,
cursorBlink: false,
stdinDisabled: true,
disableStdin: true,
theme: { background: '#181818', foreground: '#e8e8e8' },
});
const fit = new FitAddon.FitAddon();
@@ -20,6 +20,7 @@ terminal.parser.registerOscHandler(633, data => {
terminal.loadAddon(fit);
const host = document.getElementById('terminal');
terminal.open(host);
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true);
const screen = host.querySelector('.xterm-screen');
let traceEnabled = false;
@@ -51,6 +52,11 @@ function anchorOutput() {
trace(2);
}
terminal.attachCustomKeyEventHandler(event => {
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter');
event.preventDefault();
return false;
}
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) return true;
if (event.code === 'KeyO') bridge.postMessage('toggle');
else if (event.code === 'ArrowUp') bridge.postMessage('grow');
@@ -62,7 +68,7 @@ terminal.attachCustomKeyEventHandler(event => {
if (!event.repeat) bridge.postMessage('insert-name');
}
else if (event.key === 'Insert') {
if (!event.repeat) bridge.postMessage('copy-panel-names');
if (!event.repeat) bridge.postMessage('copy-command-line-or-panel-names');
}
else if (event.code === 'KeyR') {
if (!event.repeat) bridge.postMessage('refresh-panel');
@@ -78,6 +84,15 @@ terminal.onScroll(() => {
anchorOutput();
});
bridge.addEventListener('message', ({ data }) => {
if (data === 'clear-selection') {
terminal.clearSelection();
return;
}
if (data === 'scroll-bottom') {
terminal.scrollToBottom();
anchorOutput();
return;
}
if (data === 'trace:on' || data === 'trace:output') {
traceEnabled = true;
traceOutput = data === 'trace:output';
+155 -42
View File
@@ -341,6 +341,7 @@ void traceTerminal(const char *event,int a=0,int b=0,int c=0,int d=0,int e=0)
terminalTrace<<GetTickCount64()<<' '<<event<<' '<<a<<' '<<b<<' '<<c<<' '<<d<<' '<<e<<std::endl;
}
FilesTerminalView terminalView;
std::wstring terminalSelection;
COORD terminalSize{80,25};
bool terminalViewRequested{};
HWND terminalInput{},terminalOutput{},terminalPrompt{};
@@ -453,6 +454,7 @@ void showFileDetails(const Panel &panel);
void editOptions(HWND owner);
void showFolderShortcuts(Panel &panel,int digit,bool all=false);
void layout(HWND window,bool activeOnly=false);
void clearTerminalSelection();
DWORD preference(const wchar_t *name, DWORD fallback)
{
@@ -590,7 +592,7 @@ bool applyFont(HWND owner, LOGFONTW font, int points)
return true;
}
bool chooseDisplayFont(HWND owner,LOGFONTW &font,int &points)
bool chooseDisplayFont(HWND owner,LOGFONTW &font,int &points,int maximum=24)
{
CHOOSEFONTW dialog{};
dialog.lStructSize=sizeof(dialog);
@@ -599,7 +601,7 @@ bool chooseDisplayFont(HWND owner,LOGFONTW &font,int &points)
dialog.iPointSize=points;
dialog.Flags=CF_SCREENFONTS|CF_INITTOLOGFONTSTRUCT|CF_LIMITSIZE;
dialog.nSizeMin=8;
dialog.nSizeMax=24;
dialog.nSizeMax=maximum;
if(!ChooseFontW(&dialog)) return false;
points=dialog.iPointSize;
return true;
@@ -903,6 +905,7 @@ void layout(HWND window,bool activeOnly)
const auto region=CreateRectRgn(0,terminalTop-4,std::max(0,width-8),terminalBottom-4);
if(region && !SetWindowRgn(terminalOutput,region,FALSE)) DeleteObject(region);
}
if(!showOutput) clearTerminalSelection();
ShowWindow(terminalOutput,showOutput?SW_SHOWNA:SW_HIDE);
ShowWindow(status,terminalVisible?SW_HIDE:SW_SHOWNA);
terminalView.layout(terminalOutput,showOutput,terminalBottom-4);
@@ -935,6 +938,22 @@ void showTerminal(HWND owner,bool show)
void open(Panel &panel,const fs::path &directory,bool offerElevation);
void restoreCommandFocus();
void submitTerminalReturn(HWND owner,bool shift);
void invalidatePanelRow(HWND list,LRESULT row)
{
RECT bounds{};
if(row!=LB_ERR && SendMessageW(list,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR)
InvalidateRect(list,&bounds,FALSE);
}
void invalidatePanelCursorChange(HWND list,LRESULT previous)
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(current==previous) return;
invalidatePanelRow(list,previous);
invalidatePanelRow(list,current);
}
void activatePanel(int index)
{
@@ -945,10 +964,7 @@ void activatePanel(int index)
for(const auto &panel:panels)
{
InvalidateRect(panel.path,nullptr,FALSE);
const auto cursor=SendMessageW(panel.list,LB_GETCURSEL,0,0);
RECT row{};
if(cursor!=LB_ERR && SendMessageW(panel.list,LB_GETITEMRECT,cursor,reinterpret_cast<LPARAM>(&row))!=LB_ERR)
InvalidateRect(panel.list,&row,FALSE);
invalidatePanelRow(panel.list,SendMessageW(panel.list,LB_GETCURSEL,0,0));
}
layout(GetParent(panels[index].list),true);
}
@@ -960,12 +976,19 @@ std::wstring terminalInputText()
return value;
}
void copyTerminalInput(HWND owner)
void clearTerminalSelection()
{
const auto value=terminalInputText();
if(terminalSelection.empty()) return;
terminalSelection.clear();
terminalView.post(L"clear-selection");
}
void copyTerminalText(HWND owner)
{
const auto value=terminalSelection.empty()?terminalInputText():terminalSelection;
if(value.empty()) return;
try { ks::writeClipboard(owner,ks::textClip(value)); }
catch(const std::exception &) { setStatus(L"Could not copy the command line."); }
catch(const std::exception &) { setStatus(L"Could not copy terminal text."); }
}
LRESULT currentPanelRow(const Panel &panel)
@@ -1001,6 +1024,12 @@ void copyPanelNames(HWND owner)
catch(const std::exception &) { setStatus(L"Could not copy file names."); }
}
void copyCommandLineOrPanelNames(HWND owner)
{
if(!terminalSelection.empty() || GetWindowTextLengthW(terminalInput)) copyTerminalText(owner);
else copyPanelNames(owner);
}
void refreshPanel(Panel &panel)
{
panel.folderSizeStop.request_stop();
@@ -1087,10 +1116,13 @@ bool ensureTerminalView(HWND owner)
{
if(GetForegroundWindow()==owner) SetFocus(terminalInput);
}
else if(message.starts_with(L"selection:")) terminalSelection=message.substr(10);
else if(message==L"enter" || message==L"shift-enter")
submitTerminalReturn(owner,message==L"shift-enter");
else if(message==L"insert-path") insertCurrentPanelPath();
else if(message==L"insert-name") insertCurrentPanelPath(true);
else if(message==L"copy-command-line") SendMessageW(terminalInput,WM_COPY,0,0);
else if(message==L"copy-panel-names") copyPanelNames(owner);
else if(message==L"copy-command-line-or-panel-names") copyCommandLineOrPanelNames(owner);
else if(message==L"refresh-panel") refreshPanel(panels[active]);
else if(message==L"toggle") showTerminal(owner,!terminalVisible);
else if(!terminalVisible && (message==L"grow" || message==L"shrink"))
@@ -1172,7 +1204,9 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
const auto owner=GetParent(panel.list);
if(remoteCommandRunning)
{
setStatus(L"A remote command is running. Press Escape to cancel it.");
constexpr auto busy=L"A remote command is running. Clear the command line and press Escape to cancel it.";
setStatus(busy);
if(terminalVisible) appendRemoteOutput(ks::utf8(std::wstring(L"\r\n")+busy+L"\r\n"));
return false;
}
if(panel.peer)
@@ -1193,7 +1227,10 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
{
FilesConnection host(&peer);
const auto code=ks::lan::runRemoteCommand(host,directory,value,appendRemoteOutput,stop);
appendRemoteOutput("\r\n[Remote exit code "+std::to_string(code)+"]\r\n");
if(code==STATUS_DLL_INIT_FAILED)
appendRemoteOutput("\r\nRemote PowerShell could not start: DLL initialization failed (0xC0000142).\r\n");
else
appendRemoteOutput("\r\n[Remote exit code "+std::to_string(code)+"]\r\n");
}
catch(const std::system_error &error)
{
@@ -1229,11 +1266,30 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
return true;
}
void runCommandLine()
{
const auto value=terminalInputText();
if(!submitTerminalCommand(panels[active],value)) return;
terminalView.post(L"scroll-bottom");
if(value.find_first_not_of(L" \t\r\n")!=value.npos)
{
rememberCommand(value);
if(!terminalVisible && terminalRows==0)
{
terminalRows=5;
layout(GetParent(terminalInput));
}
}
terminalHistoryIndex=terminalHistory.size();
SetWindowTextW(terminalInput,L"");
}
LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN) clearTerminalSelection();
if(message==WM_COPY || (message==WM_CHAR && wp==3))
{
copyTerminalInput(GetParent(input));
copyTerminalText(GetParent(input));
return 0;
}
if(message==WM_CHAR && wp==VK_TAB && !terminalVisible) return 0;
@@ -1269,20 +1325,6 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
SendMessageW(input,EM_REPLACESEL,TRUE,reinterpret_cast<LPARAM>(L""));
return 0;
}
if(message==WM_CHAR && wp==VK_RETURN)
{
if(!terminalVisible && !GetWindowTextLengthW(input))
{
SendMessageW(panels[active].list,WM_KEYDOWN,VK_RETURN,lp);
return 0;
}
const auto value=terminalInputText();
if(!submitTerminalCommand(panels[active],value)) return 0;
if(value.find_first_not_of(L" \t\r\n")!=std::wstring::npos) rememberCommand(value);
terminalHistoryIndex=terminalHistory.size();
SetWindowTextW(input,L"");
return 0;
}
if(message==WM_KEYDOWN && !terminalVisible && wp==VK_TAB)
{
activatePanel(1-active);
@@ -2049,6 +2091,14 @@ void chooseDrive(int index,bool fromMenu)
RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW);
}
void openPanelPathWithSystem(const Panel &panel,const fs::path &path,const wchar_t *verb,
const wchar_t *failureMessage)
{
if (reinterpret_cast<INT_PTR>(ShellExecuteW(GetParent(panel.list), verb, path.c_str(), nullptr,
panel.directory.c_str(), SW_SHOWNORMAL)) <= 32)
setStatus(failureMessage);
}
void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb, const wchar_t *failureMessage)
{
if(panel.peer)
@@ -2078,9 +2128,21 @@ void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb
return;
}
if(!verb && isExtension(L".exe")) verb=L"open";
if (reinterpret_cast<INT_PTR>(ShellExecuteW(GetParent(panel.list), verb, file.c_str(), nullptr,
panel.directory.c_str(), SW_SHOWNORMAL)) <= 32)
setStatus(failureMessage);
openPanelPathWithSystem(panel,file,verb,failureMessage);
}
void openSelectedWithSystem(const Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row==LB_ERR) return;
if(panel.peer)
{
setStatus(L"Select a local item before opening it with Windows.");
return;
}
const bool folder=panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up";
openPanelPathWithSystem(panel,panel.rows[row],folder?L"explore":nullptr,
folder?L"Cannot open the selected folder in File Explorer.":L"Cannot open the selected file.");
}
#include "files_dialog_input.inl"
@@ -4418,6 +4480,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
if(message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK ||
(message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window))
{
if(message==WM_LBUTTONDOWN) clearTerminalSelection();
auto &panel=panels[index];
activatePanel(static_cast<int>(index));
const auto count=SendMessageW(window,LB_GETCOUNT,0,0);
@@ -4429,13 +4492,14 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
const bool rowHit=!HIWORD(hit) && row<count &&
SendMessageW(window,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR &&
PtInRect(&bounds,point);
if(rowHit)
const auto previous=SendMessageW(window,LB_GETCURSEL,0,0);
const auto target=rowHit?row:point.y>=0 && message==WM_LBUTTONDOWN?count-1:previous;
if(target!=previous)
{
if(row!=SendMessageW(window,LB_GETCURSEL,0,0))
SendMessageW(window,LB_SETCURSEL,row,0);
// The list box can draw synchronously before committing its new selection.
SendMessageW(window,LB_SETCURSEL,target,0);
invalidatePanelCursorChange(window,previous);
}
else if(point.y>=0 && message==WM_LBUTTONDOWN)
SendMessageW(window,LB_SETCURSEL,count-1,0);
showFileDetails(panel);
if(message==WM_LBUTTONDOWN) SetCapture(window);
if(message==WM_LBUTTONDBLCLK && rowHit) enter(panel);
@@ -4473,8 +4537,11 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
showFileDetails(panel);
return 0;
}
if (message == WM_KEYDOWN && (wp == VK_LEFT || wp == VK_RIGHT))
return scrollList(window, message, wp == VK_LEFT ? VK_HOME : VK_END, lp);
if(message==WM_KEYDOWN)
{
if(wp==VK_LEFT) wp=VK_HOME;
else if(wp==VK_RIGHT) wp=VK_END;
}
if(message==WM_SETFOCUS) activatePanel(static_cast<int>(index));
if(message==WM_CHAR && wp>=32 && wp!=127)
{
@@ -4515,7 +4582,11 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
return 0;
}
}
const bool movesCursor=message==WM_KEYDOWN &&
(wp==VK_UP || wp==VK_DOWN || wp==VK_PRIOR || wp==VK_NEXT || wp==VK_HOME || wp==VK_END);
const auto previous=movesCursor?SendMessageW(window,LB_GETCURSEL,0,0):LB_ERR;
auto result=scrollList(window, message, wp, lp);
if(movesCursor) invalidatePanelCursorChange(window,previous);
if(message==WM_LBUTTONUP && GetFocus()==window) restoreCommandFocus();
if(message==WM_PAINT && panels[index].wide)
{
@@ -4768,14 +4839,33 @@ bool handlePanelSearchKey(HWND window,MSG &message)
return message.wParam==VK_ESCAPE && !modified && !alt;
}
bool commandLineAvailable(HWND owner)
{
return !copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(owner) &&
!IsWindowVisible(menuBar) && !IsWindowVisible(picker);
}
void restoreCommandFocus()
{
if(GetFocus()!=terminalInput && !GetCapture() && !copyInProgress &&
!FilesModalDialog::activeFor(GetParent(terminalInput)) &&
!commandHistoryWindow && !IsWindowVisible(menuBar) && !IsWindowVisible(picker))
if(GetFocus()!=terminalInput && !GetCapture() && commandLineAvailable(GetParent(terminalInput)))
SetFocus(terminalInput);
}
void handleFilesReturn(bool shift)
{
closePanelSearch();
if(terminalVisible || GetWindowTextLengthW(terminalInput)) runCommandLine();
else if(shift) openSelectedWithSystem(panels[active]);
else enter(panels[active]);
}
void submitTerminalReturn(HWND owner,bool shift)
{
if(GetForegroundWindow()!=owner || !commandLineAvailable(owner)) return;
SetFocus(terminalInput);
handleFilesReturn(shift);
}
LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
{
if(message==filesPreferencesChanged)
@@ -5145,6 +5235,19 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
GetWindowTextW(item.hwndItem,label,64);
text=label;
}
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
{
const auto separator=text.find(L' ');
auto key=text.substr(0,separator);
if(key.starts_with(L'F') && key.size()>1) key.erase(0,1);
auto shortcut=item.rcItem, action=item.rcItem;
shortcut.right=std::min(shortcut.right,shortcut.left+static_cast<LONG>(key.size())*cellWidth+8);
action.left=shortcut.right;
paintText(item.hDC,shortcut,key.c_str(),RGB(184,184,184),RGB(0,0,0));
if(action.left<action.right)
paintText(item.hDC,action,text.c_str()+separator+1,colors[Selection],colors[Footer]);
return TRUE;
}
auto background=item.CtlType==ODT_BUTTON?Footer:item.hwndItem==picker?Dialog:PanelBlue;
auto foreground=colors[Text];
if(item.hwndItem==picker && commandPicker && item.itemID<commandActions.size() && commandActions[item.itemID]<0)
@@ -5175,10 +5278,10 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
const bool activePanelRow=panelRow && item.hwndItem==panels[active].list;
if(panelRow)
{
traceTerminal("panel-draw",item.CtlID-102,item.itemID);
const auto cursor=SendMessageW(item.hwndItem,LB_GETCURSEL,0,0);
if(activePanelRow && cursor!=LB_ERR &&
static_cast<UINT>(cursor)==item.itemID) background=PanelCursor;
traceTerminal("panel-draw",item.CtlID-102,item.itemID,background==PanelCursor);
}
else if(item.itemState&(ODS_SELECTED|ODS_FOCUS))
background=Selection;
@@ -5329,6 +5432,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
return TRUE;
}
case WM_COMMAND:
if(reinterpret_cast<HWND>(lp)==terminalInput && HIWORD(wp)==EN_CHANGE) clearTerminalSelection();
if(copyInProgress || commandHistoryWindow || FilesModalDialog::activeFor(window)) return 0;
if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive();
if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED)
@@ -5466,6 +5570,15 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST &&
GetFocus()==terminalInput)
message.hwnd=terminalInput;
if(message.message==WM_KEYDOWN && message.wParam==VK_RETURN &&
!(GetKeyState(VK_CONTROL)&0x8000) &&
!(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
!(GetKeyState(VK_RWIN)&0x8000) && commandLineAvailable(window) &&
(message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list))
{
if(!(message.lParam & (1LL<<30))) handleFilesReturn((GetKeyState(VK_SHIFT)&0x8000)!=0);
continue;
}
if(!copyInProgress && handlePanelSearchKey(window,message)) continue;
if(!copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(window) && !terminalVisible &&
message.message==WM_SYSKEYDOWN && (message.wParam==VK_F3 || message.wParam==VK_F4) &&
@@ -5553,7 +5666,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
if(message.wParam=='F') insertCurrentPanelPath();
else if(message.wParam=='R') refreshPanel(panels[active]);
else if(message.wParam==VK_RETURN) insertCurrentPanelPath(true);
else if(message.wParam==VK_INSERT) copyPanelNames(window);
else if(message.wParam==VK_INSERT) copyCommandLineOrPanelNames(window);
else SendMessageW(terminalInput,WM_COPY,0,0);
}
continue;
+104 -11
View File
@@ -19,6 +19,9 @@ constexpr int textTabWidth=357,textLineEnding=359,
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme};
constexpr int editingControls[]{354,355,358,textLineEnding};
constexpr int markdownSection=1,markdownWidth=374,markdownFamily=376,markdownChoose=377,markdownSize=379;
constexpr int markdownControls[]{373,markdownWidth,375,markdownFamily,markdownChoose,378,markdownSize};
constexpr wchar_t optionsLocationKey[]=L"OptionsLocation";
constexpr struct
{
int id;
@@ -102,7 +105,9 @@ struct OptionsDraft
int styleIndex=0;
bool styleSuggestionsLoaded{};
int page=PanelModes, section=PanelLayout;
HTREEITEM wideColumnsNode{};
DWORD location{};
int markdownError{};
HTREEITEM wideColumnsNode{},markdownNode{};
RECT initialClient{};
UINT initialDpi=96;
OptionsControl controls[8]{
@@ -150,7 +155,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
DWORD fields=0;
for(int i=0;i<4;++i) if(checked(205+i)) fields|=1u<<i;
const auto &base=draft.baseline;
const bool dirty=!valid || width!=base.width ||
const bool dirty=!valid || draft.markdownError || width!=base.width ||
checked(273)!=base.wide[0] || checked(274)!=base.wide[1] ||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
@@ -333,9 +338,31 @@ void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const k
refreshTextColor(dialog,profile);
}
void showMarkdownOptions(HWND dialog,const ks::files::MarkdownPreferences &settings)
{
// SetDlgItemText sends EN_CHANGE synchronously, so take a snapshot first.
const auto values=settings;
SetDlgItemInt(dialog,markdownWidth,values.width,FALSE);
SetDlgItemInt(dialog,markdownSize,values.fontSize,FALSE);
SetDlgItemTextW(dialog,markdownFamily,values.font.c_str());
}
int readMarkdownOptions(HWND dialog,ks::files::MarkdownPreferences &settings)
{
BOOL widthValid{}, sizeValid{};
const auto width=GetDlgItemInt(dialog,markdownWidth,&widthValid,FALSE);
const auto size=GetDlgItemInt(dialog,markdownSize,&sizeValid,FALSE);
if(!widthValid || width>999999) return markdownWidth;
if(!sizeValid || size<8 || size>72) return markdownSize;
wchar_t font[LF_FACESIZE]{};
GetDlgItemTextW(dialog,markdownFamily,font,std::size(font));
settings={width,size,font};
return 0;
}
bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
{
if(!textOptionsPage(draft.page)) return false;
if(!textOptionsPage(draft.page) || (draft.page==TextViewer && draft.section==markdownSection)) return false;
auto &profile=draft.text.profiles[draft.page==TextEditor];
const auto id=LOWORD(command);
const auto row=[&](int control){return SendDlgItemMessageW(dialog,control,CB_GETCURSEL,0,0);};
@@ -386,12 +413,14 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
{
draft.page=page;
draft.section=section;
const bool markdown=page==TextViewer && section==markdownSection;
const wchar_t *title=L"No matching settings";
if(page==allOptions) title=L"All settings";
else if(page>=0)
{
title=optionsTitles[page];
if(section>=0 && !textOptionsPage(page))
if(markdown) title=L"Markdown";
else if(section>=0 && !textOptionsPage(page))
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
(section==fileStyleSection?L"File type styles":colorNames[section]):
page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font";
@@ -430,9 +459,10 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
}
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
show(commandLineControls,page==CommandLine && section==0);
show(textControls,textOptionsPage(page));
show(markdownControls,markdown);
show(textControls,textOptionsPage(page) && !markdown);
show(editingControls,page==TextEditor);
if(textOptionsPage(page)) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
const bool fileTypes=page==PanelColors && section==fileStyleSection;
constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState};
show(fileStyleControls,fileTypes);
@@ -491,6 +521,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
const int previousPage=draft.page,previousSection=draft.section;
TreeView_DeleteAllItems(tree);
draft.wideColumnsNode=nullptr;
draft.markdownNode=nullptr;
const auto root=add(L"All settings",allOptions,-1,TVI_ROOT);
HTREEITEM first{},selected{};
for(int page=PanelModes;page<allOptions;++page)
@@ -500,11 +531,16 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
const auto addSection=[&](const wchar_t *label,int section,bool aliasMatches=false)
{
if(!wholeCategory && !aliasMatches && !matches(label)) return;
if(!category) category=add(optionsTitles[page],page,-1,root);
if(!category)
{
category=add(optionsTitles[page],page,-1,root);
if(page==previousPage && previousSection<0) selected=category;
}
const auto node=add(label,page,section,category);
if(!first) first=node;
if(page==previousPage && section==previousSection) selected=node;
if(page==PanelModes && section==WideColumns) draft.wideColumnsNode=node;
if(page==TextViewer && section==markdownSection) draft.markdownNode=node;
};
if(page==PanelModes)
{
@@ -535,6 +571,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
{return (page==TextEditor || check.id<354) && matches(check.name);}) ||
std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches);
addSection(page==TextEditor?L"Editing and appearance":L"Viewing and appearance",0,propertyMatches);
if(page==TextViewer) addSection(L"Markdown",markdownSection,
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size"));
}
else
{
@@ -569,6 +607,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
SendDlgItemMessageW(dialog,201,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,markdownWidth,EM_SETLIMITTEXT,6,0);
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
showMarkdownOptions(dialog,draft.text.markdown);
SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0);
for(const auto &option:frameOptions)
for(DWORD value=0;value<=option.maximum;++value)
@@ -626,7 +668,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
const auto &change=*reinterpret_cast<const NMTREEVIEWW*>(lp);
if(change.hdr.code==TVN_SELCHANGEDW && change.itemNew.hItem)
showOptionsPage(dialog,*draft,static_cast<int>(change.itemNew.lParam>>8),static_cast<int>(change.itemNew.lParam&255)-1);
{
const auto page=static_cast<int>(change.itemNew.lParam>>8);
if(page!=allOptions || !GetWindowTextLengthW(GetDlgItem(dialog,optionsSearch)))
draft->location=static_cast<DWORD>(change.itemNew.lParam);
showOptionsPage(dialog,*draft,page,static_cast<int>(change.itemNew.lParam&255)-1);
}
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
@@ -654,6 +701,27 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
showOptionsPage(dialog,*draft,Appearance,Font);
updateOptionsApply(dialog,*draft);
return TRUE;
case markdownWidth: case markdownSize: case markdownFamily:
if(HIWORD(wp)==EN_CHANGE)
{
draft->markdownError=readMarkdownOptions(dialog,draft->text.markdown);
updateOptionsApply(dialog,*draft);
}
return TRUE;
case markdownChoose:
{
LOGFONTW font{};
const auto &settings=draft->text.markdown;
wcsncpy_s(font.lfFaceName,settings.font.empty()?L"Segoe UI":settings.font.c_str(),_TRUNCATE);
auto size=static_cast<int>(settings.fontSize)*10;
font.lfHeight=-MulDiv(size,GetDpiForWindow(dialog),720);
if(chooseDisplayFont(dialog,font,size,72))
{
SetDlgItemTextW(dialog,markdownFamily,font.lfFaceName);
SetDlgItemInt(dialog,markdownSize,(size+5)/10,FALSE);
}
return TRUE;
}
case outerFramePadding: case innerFramePadding: case rowTextPadding:
if(HIWORD(wp)==CBN_SELCHANGE)
{
@@ -731,8 +799,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
draft->framePadding=defaultDialogFramePadding;
if(draft->page==allOptions || textOptionsPage(draft->page))
for(int page=TextViewer;page<=TextEditor;++page)
if(draft->page==allOptions || draft->page==page)
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
draft->text.profiles[page==TextEditor]=ks::files::TextPreferences{};
if(draft->page==allOptions || (draft->page==TextViewer && (draft->section<0 || draft->section==markdownSection)))
showMarkdownOptions(dialog,ks::files::MarkdownPreferences{});
showOptionsPage(dialog,*draft,draft->page,draft->section);
updateOptionsApply(dialog,*draft);
return TRUE;
@@ -759,6 +829,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
case optionsApply:
case IDOK:
{
if(draft->markdownError)
{
if(!draft->markdownNode) SetDlgItemTextW(dialog,optionsSearch,L"");
TreeView_SelectItem(GetDlgItem(dialog,optionsTree),draft->markdownNode);
showFilesNotice(dialog,L"Enter a width in pixels (0 for full window) and a font size from 8 to 72 pt.",L"Markdown");
SetFocus(GetDlgItem(dialog,draft->markdownError));
return TRUE;
}
BOOL valid{};
const auto width=GetDlgItemInt(dialog,201,&valid,FALSE);
if(!valid || width<6 || width>16)
@@ -780,6 +858,16 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto &base=draft->baseline;
const bool textChanged=draft->text!=base.text;
auto textSettings=ks::files::loadTextPreferences();
if(draft->text.markdown!=base.text.markdown)
{
if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown)
{
showFilesNotice(dialog,L"Markdown settings changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options");
return TRUE;
}
textSettings.markdown=draft->text.markdown;
}
for(size_t i=0;i<textSettings.profiles.size();++i)
{
if(draft->text.profiles[i]==base.text.profiles[i]) continue;
@@ -884,6 +972,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
SendMessageW(dialogOwner,filesPreferencesChanged,reinterpret_cast<WPARAM>(owner),0);
draft->baseline=OptionsBaseline{};
draft->text=draft->baseline.text;
showMarkdownOptions(dialog,draft->text.markdown);
populateTextSchemes(dialog,draft->text);
draft->font=displayFont;
draft->points=fontPoints;
@@ -919,12 +1008,16 @@ void runOptions(HWND owner,int page)
{
OptionsDraft draft;
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
draft.page=page;
draft.section=textOptionsPage(page)?0:PanelLayout;
const DWORD initial=static_cast<DWORD>((page<<8)|1);
const auto saved=preference(optionsLocationKey,initial);
draft.location=(saved>>8)<=allOptions?saved:initial;
draft.page=static_cast<int>(draft.location>>8);
draft.section=static_cast<int>(draft.location&255)-1;
std::copy(std::begin(colors),std::end(colors),draft.palette.begin());
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog,
reinterpret_cast<LPARAM>(&draft));
if(result==-1) setStatus(L"Could not open Files Options.");
else savePreference(optionsLocationKey,draft.location);
}
void editOptions(HWND owner)
+8
View File
@@ -44,10 +44,18 @@ struct NamedTextPalette
};
inline constexpr size_t maxTextPalettes = 48;
inline constexpr size_t maxTextPaletteName = 48;
struct MarkdownPreferences
{
unsigned width{960}, fontSize{12};
std::wstring font;
bool operator==(const MarkdownPreferences &) const = default;
};
struct TextSettings
{
TextPreferencesSet profiles;
std::vector<NamedTextPalette> schemes;
MarkdownPreferences markdown;
bool operator==(const TextSettings &) const = default;
};
TextSettings loadTextPreferences();
+95 -18
View File
@@ -8,6 +8,7 @@
#include "files_terminal_view.h"
#include "platform.h"
#include "lan_files.h"
#include "../resources/resource.h"
#include <commctrl.h>
#include <shellapi.h>
@@ -83,6 +84,15 @@ TextSettings loadTextPreferences()
const auto data = nlohmann::json::parse(readFile(combined, 64 * 1024));
for (size_t i = 0; i < profiles.size(); ++i)
if (data.contains(profileNames[i])) readTextProfile(profiles[i], data.at(profileNames[i]));
if (const auto markdown=data.find("markdown");markdown!=data.end() && markdown->is_object())
{
if (const auto width=markdown->find("width");width!=markdown->end() && width->is_number_unsigned() && *width<=999999)
settings.markdown.width=width->get<unsigned>();
if (const auto size=markdown->find("fontSize");size!=markdown->end() && size->is_number_unsigned() && *size>=8 && *size<=72)
settings.markdown.fontSize=size->get<unsigned>();
if (const auto family=markdown->find("font");family!=markdown->end() && family->is_string())
settings.markdown.font=wide(family->get<std::string>()).substr(0,LF_FACESIZE-1);
}
if (data.contains("schemes") && data.at("schemes").is_array())
for (const auto &entry : data.at("schemes"))
{
@@ -126,6 +136,8 @@ void saveTextPreferences(const TextSettings &settings)
auto &schemes = data["schemes"] = nlohmann::json::array();
for (const auto &scheme : settings.schemes)
schemes.push_back({{"name", utf8(scheme.name)}, {"colors", scheme.colors}});
data["markdown"]={{"width",settings.markdown.width},{"fontSize",settings.markdown.fontSize},
{"font",utf8(settings.markdown.font)}};
const auto json = data.dump(2);
atomicWrite(dataDirectory() / L"files-text.json", Bytes(json.begin(), json.end()));
}
@@ -187,7 +199,7 @@ enum Command : UINT
{
save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage,
undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, switchMode,
historyBack, historyForward,
historyBack, historyForward, findPrevious, previewEscape,
lexerStart = 1000,
};
@@ -731,6 +743,11 @@ public:
}
static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam);
~TextWindow()
{
if(smallIcon) DestroyIcon(smallIcon);
if(largeIcon) DestroyIcon(largeIcon);
}
HWND window{}, editor{};
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
@@ -742,6 +759,7 @@ private:
std::unique_ptr<TextDocument> document;
std::wstring filename;
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
HICON smallIcon{},largeIcon{};
TextPreferences prefs;
TextWindowFont filesFont;
TextLanguage automatic, language;
@@ -863,6 +881,7 @@ private:
void updatePreview();
void stopPreview(bool refresh=true,bool keepBrowser=false);
void renderPreview(bool keepPosition=false);
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
std::optional<FileStamp> previewFileStamp() const;
void refreshPreview();
void cancelPreviewImages();
@@ -872,6 +891,8 @@ private:
void showLocation(std::unique_ptr<RemoteTextFile> fetched);
void syncNavigation();
void updateTitle();
void updateIcons(UINT dpi);
void updateTaskbarGroup(bool closing=false);
void pollImages();
void focusContent();
void layout();
@@ -1134,7 +1155,9 @@ void TextWindow::reloadPreferences()
return;
}
pendingPreferences = false;
auto profile = loadTextPreferences().profiles[edit];
auto settings = loadTextPreferences();
applyMarkdownPreferences(settings.markdown);
auto &profile = settings.profiles[edit];
const auto font = search.style.readFont();
const bool fontChanged = font.tenthsOfPoint != filesFont.tenthsOfPoint ||
std::memcmp(&font.font, &filesFont.font, sizeof(LOGFONTW)) != 0;
@@ -1438,6 +1461,8 @@ void TextWindow::changeMode()
loadPage(std::min(page, document->pages() - 1));
send(SCI_GOTOPOS, std::min(caret, send(SCI_GETLENGTH)));
updateTitle();
updateIcons(GetDpiForWindow(window));
updateTaskbarGroup();
updatePreview();
layout();
focusContent();
@@ -1450,6 +1475,41 @@ void TextWindow::updateTitle()
SetWindowTextW(window,title.c_str());
}
void TextWindow::updateIcons(UINT dpi)
{
const auto instance=GetModuleHandleW(nullptr);
const auto resource=MAKEINTRESOURCEW(edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER);
const auto set=[&](HICON &current,WPARAM kind,int width,int height)
{
const auto icon=static_cast<HICON>(LoadImageW(instance,resource,IMAGE_ICON,
GetSystemMetricsForDpi(width,dpi),GetSystemMetricsForDpi(height,dpi),0));
if(!icon) return;
SendMessageW(window,WM_SETICON,kind,reinterpret_cast<LPARAM>(icon));
if(const auto previous=std::exchange(current,icon)) DestroyIcon(previous);
};
set(smallIcon,ICON_SMALL,SM_CXSMICON,SM_CYSMICON);
set(largeIcon,ICON_BIG,SM_CXICON,SM_CYICON);
}
void TextWindow::updateTaskbarGroup(bool closing)
{
auto icon=closing?std::wstring{}:executable()+L",-"+std::to_wstring(edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER);
auto identity=std::wstring(edit?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
IPropertyStore *properties{};
if(FAILED(SHGetPropertyStoreForWindow(window,IID_PPV_ARGS(&properties)))) return;
PROPVARIANT value{};
if(!closing)
{
value.vt=VT_LPWSTR;
value.pwszVal=icon.data();
}
properties->SetValue(PKEY_AppUserModel_RelaunchIconResource,value);
if(!closing) value.pwszVal=identity.data();
// Setting the group ID tells Explorer to refresh the taskbar button.
properties->SetValue(PKEY_AppUserModel_ID,value);
properties->Release();
}
bool TextWindow::canPreview() const
{
return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit;
@@ -1474,6 +1534,12 @@ void TextWindow::updatePreview()
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
if(!alt && ((ctrl && key=='F') || key==VK_F3))
{
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
PostMessageW(window,WM_COMMAND,key=='F'?findText:shift?findPrevious:findNext,0);
return true;
}
if(ctrl && !alt && key==VK_TAB)
{
PostMessageW(window,cycleWindow,0,0);
@@ -1485,7 +1551,7 @@ void TextWindow::updatePreview()
return true;
}
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:close,0);
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0);
return true;
}))
stopPreview();
@@ -1547,6 +1613,7 @@ std::optional<TextWindow::FileStamp> TextWindow::previewFileStamp() const
void TextWindow::renderPreview(bool keepPosition)
{
applyMarkdownPreferences(loadTextPreferences().markdown);
previewDeadline=GetTickCount64()+30000;
std::string text;
for(uint64_t index=0;index<document->pages();++index)
@@ -1560,6 +1627,13 @@ void TextWindow::renderPreview(bool keepPosition)
preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace)));
}
void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences)
{
if(!preview.initialized()) return;
preview.post(wide(nlohmann::json{{"action","appearance"},{"width",preferences.width},
{"fontSize",preferences.fontSize},{"font",utf8(preferences.font)}}.dump()));
}
void TextWindow::refreshPreview()
{
if(remote || !previewVisible || navigation.valid() || GetTickCount64()<nextFileCheck) return;
@@ -1918,8 +1992,20 @@ void TextWindow::command(UINT id)
reinterpret_cast<LPARAM>(&prompt)) == IDOK) go(prompt.page);
return;
}
case findText: openFind(); return;
case findNext: find((search.flags & FR_DOWN) != 0, search.flags); return;
case findText:
if(previewVisible) preview.post(L"{\"action\":\"find\"}");
else openFind();
return;
case findNext:
case findPrevious:
if(previewVisible)
preview.post(id==findNext?L"{\"action\":\"find-next\"}":L"{\"action\":\"find-next\",\"previous\":true}");
else if(id==findNext) find((search.flags & FR_DOWN) != 0, search.flags);
return;
case previewEscape:
if(previewVisible) preview.post(L"{\"action\":\"escape\"}");
else requestClose();
return;
case undo: if (edit) send(SCI_UNDO); return;
case redo: if (edit) send(SCI_REDO); return;
case cut: if (edit) send(SCI_CUT); return;
@@ -2104,6 +2190,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
});
}
else self->initializeDocument();
self->updateIcons(GetDpiForWindow(window));
self->updateTaskbarGroup();
self->layout();
return 0;
case WM_ERASEBKGND: return 1;
@@ -2115,6 +2203,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
SetWindowPos(window, nullptr, area->left, area->top, area->right - area->left,
area->bottom - area->top, SWP_NOZORDER | SWP_NOACTIVATE);
self->updateLineNumberMargin();
self->updateIcons(LOWORD(wparam));
self->layout();
return 0;
}
@@ -2190,6 +2279,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
return 0;
case WM_DESTROY:
if(self->cancelNavigation) *self->cancelNavigation=true;
self->updateTaskbarGroup(true);
self->stopPreview(false);
self->releaseMenu();
return 0;
@@ -2403,19 +2493,6 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,bounds.left,bounds.top,bounds.right-bounds.left,
bounds.bottom-bounds.top,nullptr,nullptr,instance,&state);
if(!window) return;
IPropertyStore *properties{};
if(SUCCEEDED(SHGetPropertyStoreForWindow(window,IID_PPV_ARGS(&properties))))
{
static unsigned sequence{};
auto identity=L"HrynCo.KSwitcher.Files.Text."+std::to_wstring(GetCurrentProcessId())+
L"."+std::to_wstring(++sequence);
PROPVARIANT value{};
value.vt=VT_LPWSTR;
value.pwszVal=identity.data();
properties->SetValue(PKEY_AppUserModel_ID,value);
properties->Commit();
properties->Release();
}
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
SendMessageW(window,WM_SETFOCUS,0,0);
}
+46 -3
View File
@@ -7,6 +7,7 @@
#include <bcrypt.h>
#include <wincrypt.h>
#include <sddl.h>
#include <winsafer.h>
#include <cstring>
#include <mutex>
#include <thread>
@@ -257,6 +258,40 @@ DWORD requestSystemHibernate()
return GetExitCodeProcess(process.value,&exitCode)?exitCode:GetLastError();
}
DWORD restrictElevatedCommandToken(HANDLE token,FileHandle &restricted)
{
// A synthetic LUA token made directly from an elevated token can fail to
// initialize KernelBase when the child starts without a console window.
SAFER_LEVEL_HANDLE level{};
if(!SaferCreateLevel(SAFER_SCOPEID_USER,SAFER_LEVELID_NORMALUSER,SAFER_LEVEL_OPEN,&level,nullptr))
return GetLastError();
const auto filtered=SaferComputeTokenFromLevel(level,token,&restricted.value,0,nullptr);
const auto filterError=GetLastError();
SaferCloseLevel(level);
if(!filtered) return filterError;
// Preserve DISABLE_MAX_PRIVILEGE without creating a second filtered token.
LUID changeNotify{};
if(!LookupPrivilegeValueW(nullptr,SE_CHANGE_NOTIFY_NAME,&changeNotify)) return GetLastError();
DWORD size{};
if(!GetTokenInformation(restricted.value,TokenPrivileges,nullptr,0,&size) &&
GetLastError()!=ERROR_INSUFFICIENT_BUFFER) return GetLastError();
std::vector<BYTE> storage(size);
const auto privileges=reinterpret_cast<TOKEN_PRIVILEGES *>(storage.data());
if(!GetTokenInformation(restricted.value,TokenPrivileges,privileges,size,&size)) return GetLastError();
DWORD removed{};
for(DWORD i=0;i<privileges->PrivilegeCount;++i)
{
const auto &luid=privileges->Privileges[i].Luid;
if(luid.LowPart!=changeNotify.LowPart || luid.HighPart!=changeNotify.HighPart)
privileges->Privileges[removed++]={luid,SE_PRIVILEGE_REMOVED};
}
if(!removed) return ERROR_SUCCESS;
privileges->PrivilegeCount=removed;
AdjustTokenPrivileges(restricted.value,FALSE,privileges,0,nullptr,nullptr);
return GetLastError();
}
struct RemoteCommand
{
FileHandle job,process,output;
@@ -294,9 +329,17 @@ struct RemoteCommand
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();
TOKEN_ADJUST_DEFAULT,&token.value)) return GetLastError();
TOKEN_ELEVATION elevation{};
DWORD elevationSize{};
if(!GetTokenInformation(token.value,TokenElevation,&elevation,sizeof(elevation),&elevationSize))
return GetLastError();
if(elevation.TokenIsElevated)
{
if(const auto error=restrictElevatedCommandToken(token.value,restricted)) return error;
}
else if(!CreateRestrictedToken(token.value,DISABLE_MAX_PRIVILEGE|LUA_TOKEN,0,nullptr,0,nullptr,0,nullptr,
&restricted.value)) return GetLastError();
PSID medium{};
if(!ConvertStringSidToSidW(L"S-1-16-8192",&medium)) return GetLastError();
TOKEN_MANDATORY_LABEL label{{medium,SE_GROUP_INTEGRITY}};
+2
View File
@@ -38,6 +38,8 @@ bool shouldElevateOnLaunch()
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
{
// Inherited by unattended children such as the LAN PowerShell process.
SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS);
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
int argc{};
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
+50 -41
View File
@@ -91,14 +91,8 @@ void refreshLan(HWND w,LanView &v)
for(const auto &peer:next["peers"])
{
auto id=peer.at("id").get<std::string>();ids.push_back(id);
std::wstring state=L"Not paired";
if(peer.at("paired").get<bool>()){
bool connected=next.value("inputReady",nlohmann::json::object()).contains(id);
state=connected?L"Pair saved — input connected":
!next.value("shareInput",false)?L"Pair saved — input disabled here":
!peer.value("online",false)?L"Pair saved — computer offline":L"Pair saved — input not connected";
}
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"] — "+state);
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"]"+
(peer.at("paired").get<bool>()?L" — Paired":L""));
}
// Presence/challenge refreshes must not repaint or reset the pairing list.
if(v.ids!=ids||v.rows!=rows)
@@ -131,11 +125,21 @@ void refreshLan(HWND w,LanView &v)
std::wstring peerName;
for(const auto &peer:v.snapshot["peers"])
if(peer.at("id")==v.snapshot.value("pendingPeer",std::string{}))peerName=wide(peer.at("name").get<std::string>());
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair there too. Pair is not saved yet.";
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair on the other PC.";
}
value(w,708,v.error.empty() ? pairingStatus : v.error);
value(w,705,pending ? L"Waiting..." : L"&Pair");
value(w,710,v.ids.empty() ? (enabled ? L"No KSwitcher found. Enable discovery on the other PC too. UDP 45883 must be allowed on your private network." : L"Discovery is disabled on this computer.") : L"Select the matching KSwitcher name and ID shown on the other computer.");
const wchar_t *peerStatus=L"Select the name and ID shown on the other PC.";
if(v.ids.empty()) peerStatus=enabled?L"No computers found. Enable discovery on both PCs and allow UDP 45883.":
L"Discovery is disabled on this computer.";
else if(paired)
{
const bool connected=v.snapshot.value("inputReady",nlohmann::json::object()).contains(selected);
peerStatus=connected?L"Pair saved — input connected":
!v.snapshot.value("shareInput",false)?L"Pair saved — input disabled here":
!online?L"Pair saved — computer offline":L"Pair saved — input not connected";
}
value(w,710,peerStatus);
EnableWindow(GetDlgItem(w,705),enabled&&online&&!pending&&!paired);
EnableWindow(GetDlgItem(w,706),pending);
EnableWindow(GetDlgItem(w,707),paired);
@@ -157,8 +161,7 @@ void refreshLan(HWND w,LanView &v)
EnableWindow(GetDlgItem(w,716),v.snapshot.value("shareInput",false));
auto gridState=positions.dump()+v.snapshot["peers"].dump()+selected+v.snapshot.value("controlPeer",std::string{})+v.snapshot.value("inputReady",nlohmann::json::object()).dump()+(v.snapshot.value("shareInput",false)?"1":"0");
if(gridState!=v.gridState){v.gridState=std::move(gridState);InvalidateRect(GetDlgItem(w,721),nullptr,FALSE);}
std::wstring detail=L"Drag paired monitors to empty cells. This PC stays fixed. Arrow keys also work.";
detail=L"Drag monitors to neighboring cells. Mouse crosses shared edges; empty cells block passage.";
const std::wstring detail=L"Drag monitors or use arrow keys. The pointer crosses shared edges.";
value(w,719,v.error.empty()?detail:v.error);
auto inputStatus=wide(v.snapshot.value("inputStatus",std::string("Input sharing disabled.")));
if(!v.snapshot.value("shareInput",false))
@@ -257,38 +260,44 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
}
void showLan(HWND parent,App &app)
{
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,740,908,0,false);
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,730,498,0,false);
windowLayoutState(w)->fixedClient=true;
SetWindowLongPtrW(w,GWLP_HWNDPARENT,(LONG_PTR)parent);
auto v=new LanView{parent,&app};SetWindowLongPtrW(w,GWLP_USERDATA,(LONG_PTR)v);
label(w,L"Changes here save automatically. No need to click Save in Settings.",18,16,700);
control(w,L"STATIC",L"",0,709,18,45,700,24);
button(w,L"&Enable discovery",701,18,78,210);
label(w,L"Only enabled KSwitcher instances announce themselves.",244,82,470);
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,18,120,700,96);
control(w,L"STATIC",L"",0,710,18,224,700,40);
label(w,L"Same pairing c&ode on both computers",18,273,700);
edit(w,703,18,301,470);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
button(w,L"&Generate code",704,504,300,214);
label(w,L"Generate once, enter that code on both PCs, select each other, then click Pair on both.",18,338,700);
button(w,L"&Pair",705,18,370,140);button(w,L"Cancel &pairing",706,174,370,160);button(w,L"&Forget pair",707,350,370,160);
control(w,L"STATIC",L"",0,708,18,412,700,40);
label(w,L"Arrange your computers",18,458,700);
label(w,L"Changes save automatically.",16,12,698);
control(w,L"STATIC",L"",0,709,16,35,698,22);
button(w,L"&Enable discovery",701,16,62,164);
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,16,98,332,70);
control(w,L"STATIC",L"",0,710,16,173,332,36);
label(w,L"Same pairing c&ode on both computers",16,211,332);
edit(w,703,16,234,189);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
button(w,L"&Generate code",704,213,234,135);
button(w,L"&Pair",705,16,268,76);
button(w,L"Cancel &pairing",706,100,268,125);
button(w,L"&Forget pair",707,233,268,115);
control(w,L"STATIC",L"Use one code on both PCs. Select each other and click Pair on both.",0,0,16,302,332,37);
control(w,L"STATIC",L"",0,708,16,344,332,53);
constexpr int right=366,rightWidth=348,gridTop=92,gridHeight=185;
label(w,L"Arrange your computers",right,65,rightWidth);
WNDCLASSW gridClass{};gridClass.lpfnWndProc=lanGridProc;gridClass.hInstance=app.instance;gridClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);gridClass.lpszClassName=L"KSwitcher.LAN.Layout";RegisterClassW(&gridClass);
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer above, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
scale(w,18),scale(w,486),scale(w,700),scale(w,180),w,reinterpret_cast<HMENU>(721),app.instance,v);
windowLayoutState(w)->controls.push_back({grid,{18,486,718,666}});
control(w,L"STATIC",L"",0,719,18,674,700,24);
button(w,L"Enable &input sharing",715,18,706,330);
button(w,L"&Stop input sharing",716,370,706,240);
control(w,L"STATIC",L"",0,718,18,744,700,30);
button(w,L"Send file…",726,18,774,144);
button(w,L"Incoming files…",730,174,774,160);
button(w,L"Download log…",727,346,774,164);
button(w,L"Previous log…",728,522,774,196);
control(w,L"BUTTON",L"Allow paired computers to download diagnostic logs",BS_AUTOCHECKBOX|WS_TABSTOP,729,18,808,700,24);
control(w,L"STATIC",L"",0,731,18,835,700,24);
button(w,L"Connection &help",722,18,864,300);
button(w,L"&Close",IDCANCEL,618,864,100);
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer in the list, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
scale(w,right),scale(w,gridTop),scale(w,rightWidth),scale(w,gridHeight),w,reinterpret_cast<HMENU>(721),app.instance,v);
windowLayoutState(w)->controls.push_back({grid,{right,gridTop,right+rightWidth,gridTop+gridHeight}});
control(w,L"STATIC",L"",0,719,right,283,rightWidth,37);
button(w,L"Enable &input sharing",715,right,323,172);
button(w,L"&Stop input sharing",716,546,323,168);
control(w,L"STATIC",L"",0,718,right,357,rightWidth,40);
button(w,L"Send file…",726,16,403,168);
button(w,L"Incoming files…",730,192,403,168);
button(w,L"Download log…",727,368,403,168);
button(w,L"Previous log…",728,544,403,170);
control(w,L"STATIC",L"",0,731,16,436,698,20);
checkbox(w,L"Allow paired computers to download diagnostic logs",729,16,464,418);
button(w,L"Connection &help",722,444,460,162);
button(w,L"&Close",IDCANCEL,614,460,100);
EnableWindow(parent,FALSE);showRequestedWindow(w);SetForegroundWindow(w);
SetTimer(w,1,1000,nullptr);
try {refreshLan(w,*v);} catch(const std::exception &e){v->error=wide(e.what());value(w,708,v->error);}
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.96";
inline constexpr wchar_t AppVersion[] = L"0.6.105";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+59 -2
View File
@@ -22,6 +22,56 @@ void require(bool ok, const char *message)
if (!ok) throw std::runtime_error(message);
++passed;
}
void lanWindowLayoutChecks(const std::filesystem::path &root)
{
const std::string peer(32,'b');
const nlohmann::json fixture={{"version",1},{"id",std::string(32,'a')},{"enabled",false},
{"trusted",{{peer,{{"name","Paired desktop"},{"key",std::string(64,'f')}}}}},
{"positions",{{peer,nlohmann::json::array({1,0})}}}};
const auto data=fixture.dump();
std::filesystem::create_directories(root);
ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(data.begin(),data.end())));
ks::App app(GetModuleHandleW(nullptr),true,root);
ks::showSettings(app);
SendMessageW(app.settingsWindow,WM_COMMAND,262,0);
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
require(lan!=nullptr,"Computers window opens");
const auto dpi=GetDpiForWindow(lan);
RECT room{0,0,MulDiv(750,dpi,96),MulDiv(510,dpi,96)};
AdjustWindowRectExForDpi(&room,GetWindowLongPtrW(lan,GWL_STYLE)&~(WS_HSCROLL|WS_VSCROLL),
FALSE,GetWindowLongPtrW(lan,GWL_EXSTYLE),dpi);
RECT frame{};GetWindowRect(lan,&frame);
SetWindowPos(lan,nullptr,0,0,std::min(frame.right-frame.left,room.right-room.left),
std::min(frame.bottom-frame.top,room.bottom-room.top),SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
require(!(GetWindowLongPtrW(lan,GWL_STYLE)&(WS_HSCROLL|WS_VSCROLL)),"Computers window fits without scrollbars");
RECT client{};GetClientRect(lan,&client);
std::vector<std::pair<int,RECT>> placed;
for(HWND child=GetWindow(lan,GW_CHILD);child;child=GetWindow(child,GW_HWNDNEXT))
{
RECT bounds{};GetWindowRect(child,&bounds);
MapWindowPoints(nullptr,lan,reinterpret_cast<POINT *>(&bounds),2);
require(bounds.left>=0&&bounds.top>=0&&bounds.right<=client.right&&bounds.bottom<=client.bottom,
"Computers control is fully visible");
const int id=GetDlgCtrlID(child);
for(const auto &[otherId,other]:placed)
{
RECT overlap{};
if(IntersectRect(&overlap,&bounds,&other))
throw std::runtime_error("Computers controls overlap: "+std::to_string(id)+" and "+std::to_string(otherId)+
" at "+std::to_string(overlap.left)+","+std::to_string(overlap.top));
}
placed.push_back({id,bounds});
}
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
auto dc=GetDC(lan);
auto screenshot=ks::screenshotClip(dc,client.right,client.bottom,{});
ReleaseDC(lan,dc);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-compact-layout.png",
ks::encodePng(ks::decodeImage(screenshot)));
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
std::cout<<"Computers layout verified at "<<dpi<<" DPI.\n";
}
void contextChecks()
{
ks::Settings scoped;
@@ -114,12 +164,19 @@ void contextChecks()
require(hook.update('A', true, MOD_ALT, true) == 0, "ordinary keys pass");
}
}
int main()
int main(int argc,char **argv)
{
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-chat-tests-" + std::to_wstring(GetCurrentProcessId()));
try
{
if(argc==2 && std::string_view(argv[1])=="--lan-layout")
{
lanWindowLayoutChecks(root);
std::filesystem::remove_all(root);
CoUninitialize();
return 0;
}
contextChecks();
{
ks::App app(GetModuleHandleW(nullptr), true, root);
@@ -451,7 +508,7 @@ int main()
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,262,0);
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"single saved pair selected automatically when opening LAN settings");
wchar_t pairState[512]{};SendDlgItemMessageW(lan,702,LB_GETTEXT,0,(LPARAM)pairState);
wchar_t pairState[512]{};GetDlgItemTextW(lan,710,pairState,std::size(pairState));
require(std::wstring(pairState).find(L"Pair saved — input disabled here")!=std::wstring::npos,"saved pairing does not imply an active input connection");
require(!IsWindowEnabled(GetDlgItem(lan,705))&&!IsWindowEnabled(GetDlgItem(lan,703))&&!IsWindowEnabled(GetDlgItem(lan,704)),"saved pair disables pairing and code controls");
SendDlgItemMessageW(lan,702,LB_SETCURSEL,-1,0);
+183 -2
View File
@@ -1,6 +1,9 @@
param(
[Parameter(Mandatory)][string]$Executable,
[Parameter(Mandatory)][string]$Fixture
[Parameter(Mandatory)][string]$Fixture,
[switch]$SystemOpenOnly,
[switch]$TerminalOnly,
[string]$Node='node'
)
$ErrorActionPreference = 'Stop'
Add-Type @"
@@ -113,6 +116,11 @@ function Send-Terminal([string]$Command) {
Press-Enter $inputBox
}
function Send-InteractiveTerminal([string]$Command, [string]$EnterKey = '{ENTER}') {
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, $Command)
$keys.SendKeys($EnterKey)
}
function Assert-Open($List, $Target, [bool]$DoubleClick) {
$report = "$Target.opened"
Remove-Item -LiteralPath $report -ErrorAction SilentlyContinue
@@ -133,6 +141,8 @@ $profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide
'ShowDetails', 'StatusFields', 'CommandHistory', 'WindowPlacement'
$process = $null
$trace = $null
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$webviewProfile=$env:WEBVIEW2_USER_DATA_FOLDER
try {
foreach ($name in $profileValues) {
if ($name -in $profile.GetValueNames()) {
@@ -149,7 +159,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 -or $TerminalOnly){$leftDir}else{$rightDir}) "Test document$extension"
[IO.File]::WriteAllText($document, 'Document fixture')
$association = $classes.CreateSubKey($extension)
$association.SetValue('', $progId)
@@ -169,6 +179,14 @@ try {
foreach ($name in 'LeftWide', 'RightWide', 'ShowDetails') { $profile.SetValue($name, 1) }
$profile.SetValue('StatusFields', 3)
if($TerminalOnly){
$listener=[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$listener.Start()
$port=$listener.LocalEndpoint.Port
$listener.Stop()
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=$port"
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $root 'webview'
}
$process = Start-Process -FilePath $testExe -ArgumentList '--terminal-output-trace' -PassThru
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
@@ -179,6 +197,159 @@ 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
}
$keys.SendKeys('+{ENTER}')
Wait-Until 'Shift+Enter invoking the default Windows file association' {
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
}
Wait-Until 'Files active for plain Enter' { [FilesActivationUi]::Activate($window) }
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
Remove-Item -LiteralPath "$document.opened"
$keys.SendKeys('{ENTER}')
Wait-Until 'plain Enter invoking the default Windows file association' {
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
}
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
Remove-Item -LiteralPath "$document.opened"
}
if($SystemOpenOnly -or $TerminalOnly){
$keys = New-Object -ComObject WScript.Shell
foreach($case in @(
@{Name='enter-panes'; Keys='{ENTER}'},
@{Name='shift-enter-panes'; Keys='+{ENTER}'},
@{Name='enter-terminal'; Keys='{ENTER}'; HidePanes=$true},
@{Name='shift-enter-terminal'; Keys='+{ENTER}'}
)) {
Wait-Until 'Files command line active' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
if($case.HidePanes){
$keys.SendKeys('^o')
Wait-Until 'file panes hidden' { ![FilesActivationUi]::IsWindowVisible($left) }
}
$marker=Join-Path $root "$($case.Name).txt"
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
Send-InteractiveTerminal $command $case.Keys
Wait-Until "$($case.Name) running the command" {
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
!(Read-Text $inputBox)
}
if(Test-Path -LiteralPath "$document.opened"){
throw "$($case.Name) did not give the command line priority."
}
}
Write-Output 'Verified command-line priority for Enter and Shift+Enter with panels visible and hidden.'
if(!$TerminalOnly){return}
foreach($name in 'zzzz-dir-first','zzzz-dir-second'){
[IO.File]::WriteAllText((Join-Path $leftDir $name),'dir marker')
Send-InteractiveTerminal 'dir'
Wait-Until "dir rendering $name in terminal output" {
!(Read-Text $inputBox) -and
(Select-String -LiteralPath $trace -SimpleMatch $name -Quiet -ErrorAction SilentlyContinue)
}
}
$keys.SendKeys('^o')
Wait-Until 'file panes visible again' { [FilesActivationUi]::IsWindowVisible($left) }
$listing=Join-Path $root 'dir-visible.txt'
Send-InteractiveTerminal "dir -Name | Set-Content -LiteralPath '$($listing.Replace("'","''"))'"
Wait-Until 'dir running after restoring the file panes' {
!(Read-Text $inputBox) -and (Test-Path -LiteralPath $listing) -and
([IO.File]::ReadAllLines($listing) -ccontains 'zzzz-dir-second')
}
Write-Output 'Verified repeated dir commands in the same terminal with file panes hidden and visible.'
$marker=Join-Path $root 'webview-enter.txt'
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$command)
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
Wait-Until 'the terminal WebView forwarding Enter to the command line' {
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
!(Read-Text $inputBox)
}
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
Select-Row $left '[Test folder]'
$outputSelection = 'terminal-output-copy-fixture'
Send-InteractiveTerminal "Write-Output '$outputSelection'"
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard = [Windows.Forms.Clipboard]::GetDataObject()
try {
$nativeDraft = "Get-Item -LiteralPath '$leftDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$nativeDraft)
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]0,[IntPtr]4)
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the full command line with a partial selection' {
[Windows.Forms.Clipboard]::GetText() -ceq $nativeDraft
}
$webviewDraft = "Get-Item -LiteralPath '$rightDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$webviewDraft)
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-copy'
if($LASTEXITCODE){throw 'Could not send Ctrl+Insert through the terminal WebView.'}
Wait-Until 'Ctrl+Insert copying the command line with focus in the terminal WebView' {
[Windows.Forms.Clipboard]::GetText() -ceq $webviewDraft
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-select-output'
if($LASTEXITCODE){throw 'Could not select the terminal output fixture.'}
Wait-Until 'focus returned to the command line after selecting terminal output' {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
foreach($key in '^c','^{INSERT}') {
[Windows.Forms.Clipboard]::SetText($webviewDraft)
$keys.SendKeys($key)
Wait-Until "$key copying only the selected terminal output with a command present" {
[Windows.Forms.Clipboard]::GetText() -ceq $outputSelection
}
if ((Read-Text $inputBox) -cne $webviewDraft) { throw 'Copying output changed the command line.' }
}
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the selected folder name when the command line is empty' {
[Windows.Forms.Clipboard]::GetText() -ceq 'Test folder'
}
} finally {
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
Write-Output 'Verified Ctrl+C and Ctrl+Insert copy the selected output, then fall back to the command line or panel.'
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
Wait-Until 'Enter from the terminal opening the selected folder in the pane' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -eq "$leftDir\Test folder"
}
Write-Output 'Verified Enter from the terminal opens the selected folder with an empty command line.'
return
}
Select-Row $left '..'
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr]::Zero, [IntPtr]::Zero)
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
@@ -343,7 +514,17 @@ try {
(Find-Row $right '[Size B]')
}
Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.'
} catch {
if ($inputBox -and $status) {
Write-Output "Command input length: $((Read-Text $inputBox).Length). Status: $(Read-Text $status)"
}
if ($trace -and (Test-Path -LiteralPath $trace)) {
Get-Content -LiteralPath $trace -Tail 25
}
throw
} finally {
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=$webviewFlags
$env:WEBVIEW2_USER_DATA_FOLDER=$webviewProfile
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
if (!$process.WaitForExit(4000)) { $process.Kill(); $process.WaitForExit() }
+115 -3
View File
@@ -1,6 +1,7 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$Screenshot,
[string]$SearchScreenshot,
[string]$Node = 'node',
[string]$LanFixture
)
@@ -10,6 +11,37 @@ using System;
using System.Text;
using System.Runtime.InteropServices;
public static class MarkdownUi {
[StructLayout(LayoutKind.Sequential)]
struct PropertyKey {
public Guid Format;
public uint Id;
}
[StructLayout(LayoutKind.Explicit, Size = 24)]
struct PropertyValue {
[FieldOffset(0)] public ushort Type;
[FieldOffset(8)] public IntPtr Text;
}
[ComImport, Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IPropertyStore {
void GetCount(out uint count);
void GetAt(uint index, out PropertyKey key);
void GetValue(ref PropertyKey key, out PropertyValue value);
}
[DllImport("shell32.dll", PreserveSig = false)]
static extern void SHGetPropertyStoreForWindow(IntPtr window, ref Guid iid, out IPropertyStore store);
[DllImport("ole32.dll")] static extern int PropVariantClear(ref PropertyValue value);
public static string TaskbarProperty(IntPtr window, uint property) {
var iid = typeof(IPropertyStore).GUID;
var key = new PropertyKey { Format = new Guid("9f4c2855-9f79-4b39-a8d0-e1d42de1d5f3"), Id = property };
SHGetPropertyStoreForWindow(window, ref iid, out var store);
try {
store.GetValue(ref key, out var value);
try { return value.Type == 31 ? Marshal.PtrToStringUni(value.Text) : null; }
finally { PropVariantClear(ref value); }
} finally { Marshal.ReleaseComObject(store); }
}
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
@@ -83,6 +115,22 @@ function Scintilla($Window) {
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
}
function Assert-TextWindowAppearance($Window, [string]$Mode) {
$identity = "HrynCo.KSwitcher.Files.$Mode"
$resource = if($Mode -eq 'Editor') { ',-104' } else { ',-103' }
[void](Wait-For "the $Mode taskbar group" { [MarkdownUi]::TaskbarProperty($Window,5) -ceq $identity })
$taskbarIcon = [MarkdownUi]::TaskbarProperty($Window,3)
if (!$taskbarIcon -or !$taskbarIcon.EndsWith($resource)) {
throw "$Mode taskbar icon was '$taskbarIcon'."
}
$small = [MarkdownUi]::Send($Window,0x7f,0,0)
$large = [MarkdownUi]::Send($Window,0x7f,1,0)
if (!$small.ToInt64() -or !$large.ToInt64() -or $small -eq $large) {
throw "$Mode must expose both a small title-bar icon and a large switcher icon."
}
@{ Small = $small; Large = $large }
}
function Append-Character($Control, [char]$Character) {
[void][MarkdownUi]::Send($Control,2318,0,0)
[void][MarkdownUi]::Send($Control,0x102,[int]$Character,0)
@@ -104,7 +152,7 @@ $docs = Join-Path $root 'docs'
$profileCaptured = $false
$profile = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$saved = @{}
$profileValues = 'LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
$profileValues = 'LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement','OptionsLocation'
$process = $null
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$data = $env:WEBVIEW2_USER_DATA_FOLDER
@@ -117,13 +165,25 @@ try {
| Header |
| ------ |
| Cell |
| <span id="nowrap-cell" style="white-space: nowrap; color: red; position: fixed" onclick="void 0">In Development</span> |
<table id="html-table">
<caption>Raw HTML table</caption>
<tr><th colspan="2">Priority</th></tr>
<tr><td><strong>Highest</strong></td><td>—</td></tr>
</table>
- [ ] Pending
- [x] Complete
## Збіг пошуку
Рядок для **збіг пошуку**.
![Relative image](images/tiny%20image.png)
![Missing image](images/missing.png)
[Child](child/Other.md#target-heading)
<img alt="HTML relative image" src="images/tiny%20image.png">
<a href="child/Other.md#target-heading">Child</a>
~~~mermaid
flowchart TD
@@ -160,7 +220,7 @@ const value = 42;
$profileCaptured = $true
$profile.SetValue('LeftPath',$docs)
$profile.SetValue('RightPath',$docs)
foreach ($name in 'LeftCursor','RightCursor','WindowPlacement') { $profile.DeleteValue($name,$false) }
foreach ($name in 'LeftCursor','RightCursor','WindowPlacement','OptionsLocation') { $profile.DeleteValue($name,$false) }
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$listener.Start()
@@ -175,10 +235,45 @@ const value = 42;
Open-File 'Preview.md' 0x72
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
if ([MarkdownUi]::IsWindowVisible((Scintilla $window))) {
throw 'F3 showed the source text while starting the Markdown preview.'
}
Browser 'render' $Screenshot
Post $window 0x111 3
Browser 'search-menu'
Browser 'search' $SearchScreenshot
Post $main 0x111 133
$options = Wait-For 'the shared Files Options dialog' { Find-Window '#32770' 'KSwitcher Files Options' }
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,270),0x0C,0,'Markdown')
[void](Wait-For 'the Markdown settings section' { [MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374)) })
foreach($field in @(@(374,'1200'),@(376,'Georgia'),@(379,'18'))){
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,$field[0]),0x0C,0,$field[1])
}
Post $options 0x111 1
[void](Wait-For 'Options to close after saving Markdown settings' { ![MarkdownUi]::IsWindowVisible($options) })
Browser 'appearance-width'
Post $main 0x111 133
$options = Wait-For 'reopened Files Options' { Find-Window '#32770' 'KSwitcher Files Options' }
if (![MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374))) {
throw 'Files Options did not restore its last section.'
}
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,374),0x0C,0,'0')
Post $options 0x111 2
[void](Wait-For 'Options to close on Cancel' { ![MarkdownUi]::IsWindowVisible($options) })
Browser 'appearance-width'
Post $main 0x111 133
$options = Wait-For 'Files Options after Cancel' { Find-Window '#32770' 'KSwitcher Files Options' }
if (![MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374))) {
throw 'Cancel did not preserve the last Options section.'
}
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,374),0x0C,0,'0')
Post $options 0x111 1
[void](Wait-For 'Options to close after saving full width' { ![MarkdownUi]::IsWindowVisible($options) })
Browser 'appearance-full'
Write-Output 'Verified live Markdown width and font settings, Cancel and reopening the last Options section.'
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Checking a task modified the read-only file.' }
[IO.File]::WriteAllText($original,($fixture.Replace('Перегляд Markdown','Зміна на диску')))
Browser 'Зміна на диску' '' 'Preview.md'
@@ -190,12 +285,17 @@ const value = 42;
Browser 'edit'
$editor = Wait-For 'F6 in WebView2 to open the editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
if ($editor -ne $window) { throw 'F6 changed windows.' }
$editorIcons = Assert-TextWindowAppearance $window 'Editor'
if ($editorIcons.Small -eq $viewerIcons.Small -or $editorIcons.Large -eq $viewerIcons.Large) {
throw 'F6 did not replace both viewer icons with editor icons.'
}
[MarkdownUi]::Activate($window)
Wait-Foreground $window
[MarkdownUi]::CycleWindow()
Wait-Foreground $main
[MarkdownUi]::CycleWindow()
Wait-Foreground $window
Write-Output 'Verified Ctrl+Tab between Files and the Markdown editor.'
$control = Scintilla $window
if ([MarkdownUi]::Send($control,2140,0,0).ToInt64()) { throw 'The editor is read-only.' }
Append-Character $control 'X'
@@ -207,6 +307,10 @@ const value = 42;
Post $control 0x100 0x75
Answer-Save 7
Browser 'Перегляд Markdown'
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
if ($viewerIcons.Small -eq $editorIcons.Small -or $viewerIcons.Large -eq $editorIcons.Large) {
throw 'F6 did not restore both viewer icons.'
}
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Discard changed the Markdown file.' }
Browser 'ctrl-follow'
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window -or (Find-Window 'KSwitcher.Files.Text' 'Other.md')) {
@@ -214,8 +318,10 @@ const value = 42;
}
Browser 'shift-follow'
$child = Wait-For 'the Shift+click Markdown window' { Find-Window 'KSwitcher.Files.Text' 'Other.md' $window }
[void](Assert-TextWindowAppearance $child 'Viewer')
Browser 'Linked Markdown' '' 'Other.md'
[MarkdownUi]::Activate($child)
Wait-Foreground $child
Browser 'cycle' '' 'Other.md'
Wait-Foreground $main
[MarkdownUi]::CycleWindow()
@@ -242,11 +348,14 @@ const value = 42;
Open-File 'Preview.md' 0x73
$window = Wait-For 'F4 to open the Markdown editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
[void](Assert-TextWindowAppearance $window 'Editor')
Write-Output 'Verified F3/F4 icons, separate taskbar groups and regrouping when the same window switches modes with F6.'
$control = Scintilla $window
Append-Character $control 'Y'
Post $control 0x100 0x75
Answer-Save 6
Browser 'Перегляд Markdown'
Browser 'appearance-full'
if (![IO.File]::ReadAllText($original).EndsWith('Y')) { throw 'F6 rendered before saving.' }
Post $window 0x10 0
[void](Wait-For 'the saved Markdown viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
@@ -313,11 +422,14 @@ const value = 42;
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'lan-webview'
$process = Start-Process -FilePath $lanExe -ArgumentList ('"{0}"' -f $original) -PassThru -WindowStyle Normal
$window = Wait-For 'the LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Loopback peer' }
[void](Assert-TextWindowAppearance $window 'Viewer')
Browser 'render'
Browser 'search'
Browser 'edit'
if ((Wait-For 'LAN F6 editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }) -ne $window) {
throw 'LAN F6 changed windows.'
}
[void](Assert-TextWindowAppearance $window 'Editor')
$control = Scintilla $window
Append-Character $control 'L'
Post $control 0x100 0x75
+117 -7
View File
@@ -3,6 +3,7 @@ import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
const [port, scenario, artifact, title] = process.argv.slice(2);
const terminalScenario = ['terminal-enter', 'terminal-copy', 'terminal-select-output'].includes(scenario);
let socket;
const pending = new Map();
let sequence = 0;
@@ -38,12 +39,21 @@ async function evaluate(expression) {
return reply.result.value;
}
async function pressKey(key, code, windowsVirtualKeyCode, modifiers = 0) {
const params = { key, code, windowsVirtualKeyCode, modifiers };
await command('Input.dispatchKeyEvent', { type: 'keyDown', ...params });
await command('Input.dispatchKeyEvent', { type: 'keyUp', ...params });
}
const target = await waitFor(async () => {
const response = await fetch('http://127.0.0.1:' + port + '/json/list').catch(() => null);
if (!response?.ok) return;
return (await response.json()).find(item => item.url === 'https://kswitcher-markdown.invalid/markdown.html' &&
const url = terminalScenario
? 'https://kswitcher-terminal.invalid/index.html'
: 'https://kswitcher-markdown.invalid/markdown.html';
return (await response.json()).find(item => item.url === url &&
(!title || item.title === title));
}, 'the Markdown page in WebView2');
}, 'the target WebView2 page');
socket = new WebSocket(target.webSocketDebuggerUrl);
socket.addEventListener('message', event => {
const reply = JSON.parse(event.data);
@@ -59,7 +69,26 @@ await new Promise((resolve, reject) => {
});
try {
if (scenario === 'render') {
if (scenario === 'terminal-select-output') {
const selection = await waitFor(() => evaluate(`(() => {
const marker = 'terminal-output-copy-fixture';
const buffer = terminal.buffer.active;
for (let row = buffer.viewportY; row < buffer.viewportY + terminal.rows; row++) {
if (buffer.getLine(row)?.translateToString(true) !== marker) continue;
terminal.select(0, row, marker.length);
document.querySelector('#terminal').dispatchEvent(new PointerEvent('pointerup', { bubbles:true }));
return terminal.getSelection();
}
})()`), 'the terminal output fixture');
assert.equal(selection, 'terminal-output-copy-fixture');
} else if (terminalScenario) {
await evaluate('document.querySelector(".xterm-helper-textarea").focus()');
const key = scenario === 'terminal-copy'
? { key:'Insert', code:'Insert', modifiers:2, windowsVirtualKeyCode:45 }
: { key:'Enter', code:'Enter', windowsVirtualKeyCode:13 };
await command('Input.dispatchKeyEvent', { type:'keyDown', ...key });
await command('Input.dispatchKeyEvent', { type:'keyUp', ...key });
} else if (scenario === 'render') {
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
!!document.querySelector('figure svg') &&
document.querySelector('img')?.naturalWidth === 1`), 'rendered Mermaid SVG and relative image');
@@ -69,6 +98,18 @@ try {
return style.borderTopWidth === '0px' && style.backgroundColor === 'rgba(0, 0, 0, 0)';
})`), true);
assert.equal(await evaluate(`document.querySelector('td').textContent`), 'Cell');
assert.deepEqual(await evaluate(`(() => {
const span = document.querySelector('td #nowrap-cell');
return span && [span.textContent, getComputedStyle(span).whiteSpace,
getComputedStyle(span).color, span.style.position, span.hasAttribute('onclick')];
})()`), ['In Development', 'nowrap', 'rgb(255, 0, 0)', '', false]);
assert.deepEqual(await evaluate(`(() => {
const table = document.querySelector('#html-table');
return table && [table.caption.textContent, table.querySelector('th').colSpan,
table.querySelector('td strong').textContent];
})()`), ['Raw HTML table', 2, 'Highest']);
await waitFor(() => evaluate(`document.querySelector('img[alt="HTML relative image"]')?.naturalWidth === 1`),
'the relative image in HTML');
assert.equal(await evaluate(`document.querySelector('figure svg').getBoundingClientRect().height > 0`), true);
assert.equal(await evaluate(`document.querySelector('figure svg').textContent.includes('Render target')`), true);
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
@@ -78,13 +119,82 @@ try {
.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]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => box.checked)`), [false, true]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [true, false]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [false, true]);
if (artifact) {
const { data } = await command('Page.captureScreenshot');
const { cssContentSize } = await command('Page.getLayoutMetrics');
const { data } = await command('Page.captureScreenshot', { captureBeyondViewport: true,
clip: { x:0, y:0, width:cssContentSize.width, height:Math.min(cssContentSize.height, 620), scale:1 } });
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} else if (scenario === 'search-menu' || scenario === 'search') {
const searchFocused = 'document.activeElement === document.getElementById("search-query")';
const searchClosed = 'document.getElementById("search").hidden';
if (scenario === 'search-menu') {
await waitFor(() => evaluate(searchFocused), 'the viewer menu opening rendered Markdown search');
await pressKey('Escape', 'Escape', 27);
await waitFor(() => evaluate(searchClosed), 'Escape closing only the search');
} else {
await pressKey('f', 'KeyF', 70, 2);
await waitFor(() => evaluate(searchFocused), 'Ctrl+F opening search and focusing the search field');
const status = 'document.getElementById("search-status").value';
const active = '[...(CSS.highlights.get("markdown-search-active") || [])][0]?.toString()';
const query = async text => {
await evaluate('document.getElementById("search-query").select()');
await command('Input.insertText', { text });
};
await query('ЗБІГ ПОШУКУ');
assert.equal(await evaluate(status), '1 / 2');
const toolbar = await evaluate(`({
queryWidth: document.getElementById('search-query').getBoundingClientRect().width,
closeRight: document.getElementById('search-close').getBoundingClientRect().right,
viewportWidth: document.documentElement.clientWidth
})`);
assert.ok(toolbar.queryWidth >= 100 && toolbar.closeRight <= toolbar.viewportWidth,
'The search controls must fit the viewer: ' + JSON.stringify(toolbar));
assert.equal(await evaluate(active), 'Збіг пошуку');
await pressKey('Enter', 'Enter', 13);
assert.equal(await evaluate(status), '2 / 2');
assert.equal(await evaluate(active), 'збіг пошуку');
await pressKey('F3', 'F3', 114);
assert.equal(await evaluate(status), '1 / 2');
await pressKey('Enter', 'Enter', 13, 8);
assert.equal(await evaluate(status), '2 / 2');
await pressKey('F3', 'F3', 114, 8);
assert.equal(await evaluate(status), '1 / 2');
await evaluate('document.getElementById("search-previous").click()');
assert.equal(await evaluate(status), '2 / 2');
await evaluate('document.getElementById("search-next").click()');
assert.equal(await evaluate(status), '1 / 2');
if (artifact) {
const { data } = await command('Page.captureScreenshot');
await writeFile(artifact, Buffer.from(data, 'base64'));
}
await query('для збіг пошуку');
assert.equal(await evaluate(status), '1 / 1');
assert.equal(await evaluate(active), 'для збіг пошуку');
await query('RENDER TARGET');
assert.equal(await evaluate(status), '1 / 1');
assert.equal(await evaluate(active), 'Render target');
await query('[no matches]');
assert.equal(await evaluate(status), 'No matches');
assert.equal(await evaluate(active), undefined);
await pressKey('Escape', 'Escape', 27);
assert.equal(await evaluate(searchClosed), true);
assert.equal(await evaluate('document.documentElement.classList.contains("rendered")'), true);
await evaluate('document.getElementById("search-open").click()');
assert.equal(await evaluate(searchFocused), true);
await evaluate('document.getElementById("search-close").click()');
assert.equal(await evaluate(searchClosed), true);
}
} else if (scenario === 'appearance-width' || scenario === 'appearance-full') {
const width = scenario === 'appearance-full' ? 'none' : '1200px';
await waitFor(() => evaluate(`(() => {
const text = getComputedStyle(document.querySelector('main'));
return getComputedStyle(document.body).maxWidth === ${JSON.stringify(width)} &&
text.fontSize === '24px' && text.fontFamily.startsWith('Georgia,');
})()`), 'the saved Markdown width, font family and font size');
} else if (scenario === 'edit') {
await command('Input.dispatchKeyEvent', { type: 'keyDown', key: 'F6', code: 'F6', windowsVirtualKeyCode: 117 });
} else if (['follow', 'shift-follow', 'ctrl-follow'].includes(scenario)) {
+104 -10
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 @"
@@ -104,6 +104,14 @@ function Click-PanelRow($Panel, $Row) {
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
@@ -223,16 +231,41 @@ $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 -ArgumentList '--terminal-trace' -PassThru -WindowStyle Normal
$paintTrace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
$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)
foreach($check in @(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1})) {
$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}
@@ -242,14 +275,17 @@ try {
Click-PanelRow $check.Panel $row
[void](Wait-Until { [SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32() -eq $row })
Start-Sleep -Milliseconds 150
$draws=@(Get-Content -LiteralPath $paintTrace | Select-Object -Skip $lineCount |
ForEach-Object { if($_ -match '^\d+ panel-draw ([01]) (\d+) '){ "$($Matches[1])/$($Matches[2])" } } |
Select-Object -Unique)
$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.'
}
}
Write-Output 'Verified file clicks repaint only cursor rows in the active pane and when changing panes.'
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)
@@ -301,10 +337,63 @@ try {
}
$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
@@ -730,12 +819,17 @@ try {
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(Test-Path -LiteralPath $paintTrace){Remove-Item -LiteralPath $paintTrace -Force}
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-*') {
+22
View File
@@ -211,11 +211,33 @@ int main()
require(console.find("PowerShell error")!=console.npos && console.find("CLIXML")==console.npos,
"remote PowerShell errors were not returned as text");
console.clear();
const auto restrictionsExit=runRemoteCommand(host,root,
L"$principal=[Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()); "
L"if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -or "
L"$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::PowerUser)) { exit 8 }; "
L"$privileges=& (Join-Path $env:SystemRoot 'System32\\whoami.exe') /priv /fo csv /nh; "
L"if ($LASTEXITCODE -or ($privileges | ConvertFrom-Csv -Header Name,Description,State | "
L"Where-Object { $_.Name -like 'Se*Privilege' -and $_.Name -ne 'SeChangeNotifyPrivilege' })) { exit 9 }; "
L"Write-Output 'LAN shell is restricted'",
[&](std::string_view part){console+=part;});
require(restrictionsExit==0 && console.find("LAN shell is restricted")!=console.npos,
"remote PowerShell must run with standard user rights and without extra token privileges");
console.clear();
const auto directoryExit=runRemoteCommand(host,root,
L"Write-Progress -Activity 'Hidden progress probe' -Status 'Working'; dir",
[&](std::string_view part){console+=part;});
require(directoryExit==0 && console.find("CLIXML")==console.npos &&
console.find("Hidden progress probe")==console.npos,"remote directory command included progress metadata");
for(const auto marker:{L"dir-first-marker.txt",L"dir-second-marker.txt"})
{
save(root/marker,"remote directory fixture");
FilesConnection separateCommand(one,client,key);
console.clear();
const auto code=runRemoteCommand(separateCommand,root,L"dir",
[&](std::string_view part){console+=part;});
require(code==0 && console.find(utf8(marker))!=console.npos,
"successive remote dir commands must list the current files and exit");
}
std::stop_source cancel;
try
{
+16
View File
@@ -21,3 +21,19 @@ for color, points in polygons:
im = im.resize((256,256),Image.Resampling.LANCZOS)
im.save(root / 'kswitcher.png')
im.save(root / 'kswitcher.ico', sizes=[(s,s) for s in (16,20,24,32,40,48,64,128,256)])
for mode, color in [('editor', '#4F46E5'), ('viewer', '#087C73')]:
image = Image.new('RGBA', (32*scale, 32*scale))
draw = ImageDraw.Draw(image)
draw.rounded_rectangle((scale, scale, 31*scale, 31*scale), radius=7*scale, fill=color)
if mode == 'editor':
draw.polygon([(x*scale, y*scale) for x, y in
[(7, 25), (8, 19), (20, 7), (23, 7), (26, 10), (26, 12), (14, 24)]], fill='white')
draw.line([(18*scale, 9*scale), (24*scale, 15*scale)], fill=color, width=2*scale)
else:
draw.polygon([(x*scale, y*scale) for x, y in
[(5, 16), (8, 12), (12, 9), (16, 8), (20, 9), (24, 12),
(27, 16), (24, 20), (20, 23), (16, 24), (12, 23), (8, 20)]], fill='white')
draw.ellipse((12*scale, 12*scale, 20*scale, 20*scale), fill=color)
image.resize((256, 256), Image.Resampling.LANCZOS).save(root / f'kswitcher-files-{mode}.ico',
sizes=[(s, s) for s in (16, 20, 24, 32, 40, 48, 64, 128, 256)])