Compare commits

..
10 Commits
Author SHA1 Message Date
agrynco bdd058f493 Release KSwitcher v0.6.123 (#69)
Ship the offline tray state and discovery-driven LAN input reconnection. Include the verified Windows x64 package manifest and checksum.
2026-11-20 20:40:01 +02:00
agrynco e7624b620e Release KSwitcher v0.6.122 (#68)
Ship LAN input reconnection and a tray connection indicator. Include the verified Windows x64 package manifest and checksum.
2026-11-20 18:44:21 +02:00
agrynco 367a5fd9f7 Release KSwitcher v0.6.121 (#67)
Ship the Files Markdown startup retry and apply word-boundary checks to all snippet triggers.
2026-11-20 16:40:10 +02:00
agrynco 4095c889c1 Release KSwitcher v0.6.120 (#66) 2026-11-20 00:42:13 +02:00
agrynco d8c329c265 Prepare KSwitcher v0.6.120
Keep image clipboard backups in a short-lived helper to reduce layout conversion latency while preserving newer copies.
2026-11-20 00:40:46 +02:00
agrynco debd2b9cd9 Release KSwitcher v0.6.119 (#65) 2026-11-18 13:08:23 +02:00
agrynco 90c93fba8c Prepare KSwitcher v0.6.119
Run local Files commands and resolve completion paths from the active pane.
2026-11-18 13:06:48 +02:00
agrynco a09d5e72d1 Release KSwitcher v0.6.118 (#64) 2026-11-18 02:19:11 +02:00
agrynco c0bca1b4a2 Record KSwitcher v0.6.118 package checksums 2026-11-18 02:18:30 +02:00
agrynco d5ee6ee024 Prepare KSwitcher v0.6.118 2026-11-18 02:17:34 +02:00
43 changed files with 2924 additions and 467 deletions

No files matched your search

+8 -2
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.117 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.123 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
@@ -10,7 +10,8 @@ add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico")
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-compare.ico")
include(cmake/FilesTextLibraries.cmake)
set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files")
target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
@@ -160,6 +161,11 @@ add_test(NAME files-system-open
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
-SystemOpenOnly)
set_tests_properties(files-system-open PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
add_test(NAME files-comparison-splitter
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
find_program(KSWITCHER_NODE NAMES node)
if(KSWITCHER_NODE)
add_test(NAME files-terminal-enter
+55 -7
View File
@@ -57,6 +57,36 @@ Warning і початковий фокус на No.
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
- **F9 → Commands → Compare files** порівнює два позначені текстові файли
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
рядків і підсвічуванням вставок, видалень і замін. У замінених рядках
виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8)
переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків.
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
Текст файлів і порожня область під ним мають білий фон, рядки
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
Центральний розділювач можна перетягнути мишею. Під час зміни розміру
вікна пропорція колонок зберігається.
Ctrl+колесо змінює масштаб тексту в поточному вікні.
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
на панелі завдань. У **Options → File comparison → Font and colors**
можна окремо налаштувати шрифт, тло, текст і кольори змін.
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
і меню Commands показує поточне призначення.
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
Вставлені й видалені порожні рядки враховуються завжди.
Кнопка розгортання в системному заголовку збільшує вікно порівняння
до робочої області екрана. Повторне натискання відновлює попередній розмір.
Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM,
до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються
як рівнозначні.
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
@@ -86,6 +116,7 @@ Warning і початковий фокус на No.
керують панеллю, коли список підказок закритий.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Ctrl+← і Ctrl+→ зміщують розділювач видимих панелей на ширину одного символу.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
@@ -98,14 +129,19 @@ Warning і початковий фокус на No.
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
Локальна команда запускається в папці активної панелі, яку показано
перед командним рядком. Після перемикання панелі або переходу до іншої
папки наступна команда використовує нову папку навіть у вже відкритому
PowerShell. Якщо команда змінює папку (наприклад, через `cd`), панель
переходить до неї, якщо користувач за цей час не змінив її розташування.
Під час запуску термінала область виводу має темне тло, поки WebView2
готує сторінку.
Промпт і текст команди вирівняні по спільній базовій лінії.
- Під час набору локальної команди над полем з’являються підказки PowerShell.
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
та шляхи відносно робочої папки термінала або активної панелі до запуску
термінала. Після `cd ` список пропонує папки,
та шляхи відносно робочої папки активної панелі.
Після `cd ` список пропонує папки,
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
Enter вставляє виділену, а клік вставляє підказку під вказівником.
@@ -186,6 +222,10 @@ Warning і початковий фокус на No.
Якщо надійшов новіший запит, результат попереднього
сканування пропускається. Після підтвердження UAC очікування списку
від підвищеного процесу теж відбувається у фоні.
- Якщо Windows відмовляє у правах для F5, F6, F7 або F8 на локальних
дисках, Files пропонує повторити операцію з правами адміністратора.
Після підтвердження UAC допоміжний процес обробляє захищені елементи
поточної операції. Відмова в діалозі або в UAC зупиняє операцію.
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
зберігаються для наявних елементів, а підраховані через F3 розміри папок
скидаються. F2 також виконує цю дію.
@@ -271,9 +311,10 @@ Warning і початковий фокус на No.
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
рядків. Скасування параметрів залишає текст у редакторі.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
із підсвічуванням Markdown.
інтерактивними чекбоксами списків і діаграмами Mermaid. Клік по чекбоксу
одразу записує позначку у вихідний Markdown. У разі помилки збереження
попередній стан відновлюється. Підписи з'єднань малюються поверх стрілок.
F4 відкриває текст із підсвічуванням Markdown.
HTML усередині Markdown підтримує таблиці, текстове форматування, посилання,
відносні зображення й окремі стилі, зокрема `white-space: nowrap` у клітинках.
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
@@ -290,8 +331,10 @@ Warning і початковий фокус на No.
перерендерюється зі збереженням позиції прокрутки.
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
8 МіБ, F3 відкриває текстовий перегляд.
кліку. Mermaid працює офлайн і завантажується лише для документів із
діаграмами Mermaid. Якщо WebView2 не завершує запуск, Files один раз
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
позначених папок в інших рядках рахує позначені папки. Без позначок
@@ -305,6 +348,11 @@ Warning і початковий фокус на No.
Esc скасовує поточний підрахунок і чергу активної панелі, залишаючи
вже обчислені розміри та поточний каталог.
Перехід до іншого каталогу чи джерела панелі скасовує підрахунок.
- Під списком кожної панелі з позначками показано кількість позначених
елементів і їхній сумарний розмір. Файли враховуються одразу, папки — у
міру завершення підрахунку через F3. Позначка ≥ означає, що сума
неповна, а число біля «to measure» показує, скільки позначених папок
ще без розміру.
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
+14 -2
View File
@@ -59,6 +59,12 @@ the local resident process running and log downloads enabled on the remote PC.
into the source computer restores its cursor at the corresponding edge. Empty
cells, diagonal-only neighbors and offline PCs do not transfer control.
When input sharing is enabled, the tray icon shows a steady gray dot if all
paired PCs are offline, a pulsing amber dot while a discovered PC is connecting,
a green dot when all online paired PCs are connected, and a red dot if the LAN
worker stops. Hover over the icon to see the connection status and the connected
count when only some paired PCs are connected.
The source cursor is parked and hidden beneath a tiny no-activation window. A
small banner identifies remote control; no full-screen layered bitmap is retained.
The destination uses its own keyboard layout and runs its own hotkeys/snippets.
@@ -105,8 +111,14 @@ VLANs, public IPv4 and IPv6-only networks are not supported by discovery yet.
A second LAN-enabled KSwitcher cannot use the same ports on one computer.
Input first tries TCP in the usual direction, then reverse TCP after 1.5 seconds.
If TCP has not authenticated after 5 seconds, the lower-ID peer negotiates an
encrypted UDP input session on the existing discovery socket (UDP 45883).
LAN discovery authenticates paired PCs before starting new input connections.
Discovery remains active while all paired PCs are offline and wakes input sharing
when one reappears. An authenticated input connection survives missed discovery
announcements. Once discovery has expired and the channel closes, further input
attempts wait for fresh discovery.
After at least 5 seconds, the lower-ID peer starts encrypted UDP fallback on the
discovery socket (UDP 45883) once its current TCP connection attempt has failed
or reached its 10-second deadline.
UDP uses fresh session challenges, authenticated encryption, ordered event
numbers, acknowledgements and bounded retries; duplicated packets do not repeat
key presses. Two seconds without authenticated traffic or acknowledgement
+7 -5
View File
@@ -473,14 +473,16 @@ expand the snippet.
Type `;` at the start of a trigger to open suggestions near the caret, or
type the first three characters of another trigger. The list filters as you
type and fits the widest matching trigger. Use **↑ / ↓** and **Tab** or click
an entry. **Esc** dismisses the list. Full triggers still expand
automatically. See the [snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
an entry. **Esc** dismisses the list. Full triggers expand automatically at the
start of a word, including when typed in another keyboard layout. See the
[snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
**Українською.** Введіть `;` на початку тригера або три перші символи іншого
тригера, щоб відкрити підказки біля курсора. Список фільтрується під час набору
й підлаштовує ширину під найдовший збіг. Для вибору натисніть **↑ / ↓** і
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери й далі
спрацьовують автоматично. Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери спрацьовують
автоматично на межі перед словом, зокрема під час набору в іншій розкладці.
Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
З v0.6.70 підказки відкриваються біля текстового курсора. Якщо редактор не
надає його позицію, введіть повний тригер для розгортання сніпета.
@@ -1027,7 +1029,7 @@ History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc**
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels.
History reuses separate helper processes for OCR and thumbnails so recognition can run alongside previews.
Idle helpers exit after 30 seconds, and closing the history host stops its helpers. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
Idle history helpers exit after 30 seconds, and closing the history host stops its helpers. During text conversion, a short-lived instance of **KSwitcher.Screenshot.exe** holds the image clipboard backup in memory and restores it only if the clipboard sequence still matches. Selection reads avoid loading image formats. Keep the executables from the same ZIP together. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
A live development-build test measured **4.37 MiB before history and 4.35 MiB after two open/Esc cycles**, compared with an earlier roughly 8–9 MiB plateau. A same-image clipboard-backup benchmark retained **12.78 MiB before versus 0.05 MiB after**. These measure private working set, not a guaranteed total footprint. Include all helpers when measuring active use: combined memory can be higher while history is open. No forced working-set trimming is used. Existing screenshots and shortcuts remain applicable. The v0.6.38 approach of retaining a hidden history window/RichEdit control is superseded by process termination.
+63 -1
View File
@@ -1,5 +1,67 @@
# Latest Windows release
## v0.6.123 — 2026-11-20
- The tray shows a steady gray dot when all paired PCs are offline. The amber dot pulses while a discovered PC is connecting. Green means every online paired PC is connected.
- LAN discovery stays active. Once discovery has expired and the last input channel closes, KSwitcher pauses mouse and keyboard connection attempts until a paired PC reappears.
**Українською.**
- Коли всі спаровані ПК офлайн, у треї видно статичну сіру крапку. Жовта крапка пульсує під час підключення до знайденого ПК. Зелена означає, що всі доступні спаровані ПК під’єднані.
- Пошук у LAN продовжує працювати. Коли строк дії підтвердження присутності спливає й останній канал вводу закривається, KSwitcher призупиняє спроби підключення миші та клавіатури до появи спарованого ПК.
## v0.6.122 — 2026-11-20
- LAN mouse and keyboard sharing lets a TCP attempt finish or time out before starting the encrypted UDP fallback.
- The tray icon pulses amber while reconnecting, shows green when all paired PCs are connected, and shows red if the LAN service stops. Hover to see connection status and how many PCs are connected. Diagnostic logs distinguish a declined cursor handoff from returned control.
**Українською.**
- Під час передавання миші та клавіатури KSwitcher чекає завершення TCP-спроби або її тайм-ауту, перш ніж запустити резервне з’єднання через зашифрований UDP.
- Іконка в треї пульсує жовтим під час перепідключення, показує зелену крапку, коли всі спаровані ПК під’єднані, і червону, якщо LAN-модуль зупинився. Наведіть курсор, щоб побачити стан і кількість підключених ПК. У діагностичному журналі видно, коли другий ПК відхилив перехід курсора або повернув керування.
## v0.6.121 — 2026-11-20
KSwitcher Files retries WebView2 startup once when a Markdown preview fails to initialize. If the retry succeeds, the same window displays the formatted document. The Markdown viewer loads the bundled Mermaid library only for documents with Mermaid diagrams.
Snippet expansion now requires a word boundary before the trigger, even after a pause. The same rule applies across keyboard layouts and in Far Manager.
**Українською.**
Якщо перегляд Markdown не запускається, KSwitcher Files один раз повторює запуск WebView2. Після успішної спроби форматований документ з’являється в тому самому вікні. Бібліотека Mermaid завантажується лише для документів із діаграмами Mermaid.
KSwitcher розгортає сніпети, коли тригер відокремлено від попереднього слова. Перевірка діє після паузи, у різних розкладках і у Far Manager.
## v0.6.120 — 2026-11-20
Layout conversion starts faster when the Windows clipboard contains an image. KSwitcher keeps the image and accompanying formats in memory for the duration of the operation. It restores them after conversion if the clipboard still belongs to the operation. A newer copy takes precedence.
**Українською.**
Перетворення розкладки починається швидше, коли в буфері обміну Windows є зображення. KSwitcher тримає зображення й супровідні формати в пам’яті до завершення операції. Копія відновлюється, якщо буфер усе ще належить операції. Новіше копіювання має пріоритет.
## v0.6.119 — 2026-11-18
KSwitcher Files runs local commands in the folder shown at the command prompt. After switching panes or opening a different folder, commands such as `git clone` and relative path suggestions use that folder in the same PowerShell session.
**Українською.**
KSwitcher Files запускає локальні команди в папці, показаній перед командним рядком. Після перемикання панелі або переходу до іншої папки команди на кшталт `git clone` і підказки відносних шляхів використовують цю папку в тій самій сесії PowerShell.
## v0.6.118 — 2026-11-18
- **Shift+F11** opens a side-by-side comparison of two selected text files from local, LAN or FTP panes. The comparison has its own taskbar button, a movable divider, a native toolbar, **F7/F8** change navigation, and **Ctrl+wheel** text zoom. The shortcut, font and colors are configurable in **Options → File comparison**.
- The footer of each file pane shows the number and combined size of marked items, including folders measured by **F3**. **Ctrl+Left/Right** resize the file panes.
- When Windows denies access during a supported local **F5–F8** operation, Files offers to retry with administrator rights through UAC.
- Markdown task checkboxes save their state to the source file. Mermaid flowchart labels appear above the connecting lines.
**Українською.**
- **Shift+F11** відкриває двостороннє порівняння двох вибраних текстових файлів із локальних, LAN- або FTP-панелей. Вікно має власну кнопку на панелі завдань, рухомий розділювач і системний тулбар. **F7/F8** переходять між змінами, **Ctrl+колесо** змінює масштаб тексту. Комбінація, шрифт і кольори налаштовуються в **Options → File comparison**.
- Унизу кожної панелі видно кількість і сумарний розмір позначених елементів, зокрема папок, виміряних через **F3**. **Ctrl+←/→** змінюють ширину панелей.
- Якщо Windows відмовляє в доступі під час підтримуваної локальної операції **F5–F8**, Files пропонує повторити її з правами адміністратора через UAC.
- Чекбокси Markdown зберігають стан у вихідному файлі. Підписи з’єднань у блок-схемах Mermaid відображаються поверх ліній.
## v0.6.117 — 2026-11-18
- KSwitcher Files supports saved FTP connections in both panes. Browse UTF-8 file names, open or edit remote files with **F3/F4**, save with **F2**, copy between a local and FTP pane with **F5**, rename with **F6**, and permanently delete with **F8**.
@@ -512,6 +574,6 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
Choose **Update** in the tray menu. For v0.3.x–v0.4.1, install the [v0.4.2 bridge](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2) manually first. Close KSwitcher and its editors, extract the bridge ZIP into the installation folder while keeping personal data, dictionaries, and tools, then start v0.4.2 and choose **Update**. v0.2.3 and earlier require manual installation.
For a manual upgrade, exit KSwitcher and its configurator and screenshot editors, then extract the entire **KSwitcher-win-x64.zip** into its installation folder. Verify it with **SHA256SUMS.txt**. Keep personal data, customized dictionaries and tools. Keep the three KSwitcher executables together.
For a manual upgrade, save your work and exit KSwitcher, Settings, Files, screenshot editors and bundled StayHere. Verify **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**, then extract the entire ZIP into the installation folder. Keep personal data, customized dictionaries and tools.
See the [English Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home) or [Українська Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk).
+1 -1
View File
@@ -1 +1 @@
b11409bce6fcc98484107e6c56c13d3830b5c1c6d58515ab7f395ede30dc6d5b KSwitcher-win-x64.zip
868941978ca231f3df01917277d8ec5b8de970c81f6b83b5fa9e64b18b71ab9a KSwitcher-win-x64.zip
+76 -76
View File
@@ -1,166 +1,166 @@
{
"version": "0.6.117",
"schema": 1,
"version": "0.6.123",
"files": [
{
"size": 2479104,
"path": "KSwitcher.exe",
"sha256": "4ea5e71940d5cd1cbd062c6eead6a57d6c9a7b8a3884f2d8707267872643a55f"
"size": 5892884,
"sha256": "043c10eb6752656fc2aa6c1f8d329d4fe243347a5275088e5dc4385638acd870",
"path": "KSwitcher.exe"
},
{
"size": 2458112,
"path": "KSwitcher.Config.exe",
"sha256": "3576d94c26dbed409dc12a13fb570d3dac5d35f8df1cf79761758a1e308e6b89"
"size": 5948997,
"sha256": "ac6368858b86d4e9a4a2c1cf4cd90c39b58d699909c417f73d9f882c54dd96a0",
"path": "KSwitcher.Config.exe"
},
{
"size": 3060224,
"path": "KSwitcher.Screenshot.exe",
"sha256": "738a6c42f56bd44d3cd871d53d51aa9580c3a20825c5407d2bb36ce512fe2103"
"size": 5763947,
"sha256": "d2f435c645419a155e6feac7761d9894f7bd2099cd695a93650847c869c50ffb",
"path": "KSwitcher.Screenshot.exe"
},
{
"size": 4286976,
"path": "KSwitcher.Files.exe",
"sha256": "f1231f85448b57771e6ce1f8e416282af8d9112f093bd05cb26881c79ccd5cc5"
"size": 9395313,
"sha256": "43512aa25c8b9854cb3134b9480e24049eab77a0008af55cede06369dc6a0964",
"path": "KSwitcher.Files.exe"
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"path": "WebView2Loader.dll"
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"path": "terminal/addon-fit-LICENSE.txt"
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"path": "terminal/addon-fit.js"
},
{
"size": 527,
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"path": "terminal/index.html"
},
{
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"path": "terminal/markdown-it-LICENSE.txt"
},
{
"size": 100786,
"path": "terminal/markdown-it.js",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"path": "terminal/markdown-it.js"
},
{
"size": 3530,
"path": "terminal/markdown.html",
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
"size": 3599,
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
"path": "terminal/markdown.html"
},
{
"size": 15014,
"path": "terminal/markdown.js",
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763"
"size": 17575,
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
"path": "terminal/markdown.js"
},
{
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"path": "terminal/mermaid-LICENSE.txt"
},
{
"size": 5537838,
"path": "terminal/mermaid.js",
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"path": "terminal/mermaid.js"
},
{
"size": 5065,
"path": "terminal/terminal.js",
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"path": "terminal/terminal.js"
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"path": "terminal/xterm-LICENSE.txt"
},
{
"size": 7112,
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"path": "terminal/xterm.css"
},
{
"size": 488663,
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"path": "terminal/xterm.js"
},
{
"size": 4401,
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"path": "LICENSE"
},
{
"size": 1096,
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"path": "json-LICENSE.txt"
},
{
"size": 883,
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"path": "files-text-license.txt"
},
{
"size": 95317,
"path": "README.md",
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8"
"size": 95524,
"sha256": "23d203a1fe73d1adc5e51d088420848cfabf03929401b78c4dbb249d0b5bdbf6",
"path": "README.md"
},
{
"size": 11577,
"path": "LAN-PREVIEW.md",
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
"size": 12353,
"sha256": "3ab51025826e8aa2f7c07b70b920b556409b002029b4bb92cb34c5b32dac6e54",
"path": "LAN-PREVIEW.md"
},
{
"size": 732485,
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"path": "dictionaries/en.txt"
},
{
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
},
{
"size": 2265,
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"path": "dictionaries/README.md"
},
{
"size": 1109134,
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"path": "dictionaries/ru.txt"
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"path": "dictionaries/sources.json"
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"path": "dictionaries/uk.txt"
},
{
"size": 993,
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"path": "tools/README.txt"
},
{
"size": 133120,
"path": "tools/StayHere.exe",
"sha256": "ebe97d3b7f267632b90463358bcc2518cad12f43c1eb568d2749a08f88a4bd97"
"size": 540583,
"sha256": "bb595202cc4749f3c0fe47adc92d4b02a174abeb5765e493673de9f5e070251c",
"path": "tools/StayHere.exe"
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"path": "tools/StayHere-README.md"
}
],
"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,117,0
PRODUCTVERSION 0,6,117,0
FILEVERSION 0,6,123,0
PRODUCTVERSION 0,6,123,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.117"
VALUE "FileVersion", "0.6.123"
END
END
BLOCK "VarFileInfo"
+31
View File
@@ -9,6 +9,7 @@
1 ICON "kswitcher-files.ico"
IDI_FILES_VIEWER ICON "kswitcher-files-viewer.ico"
IDI_FILES_EDITOR ICON "kswitcher-files-editor.ico"
IDI_FILES_COMPARE ICON "kswitcher-files-compare.ico"
1 RT_MANIFEST "app.manifest"
601 RCDATA "files-text-license.txt"
@@ -203,6 +204,14 @@ BEGIN
PUSHBUTTON "Choose &font…", 377, 306, 68, 76, 14
LTEXT "Font &size (8–72 pt)", 378, 131, 99, 184, 12
EDITTEXT 379, 318, 96, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
LTEXT "", 408, 131, 30, 254, 14
PUSHBUTTON "Change &font…", 409, 131, 49, 82, 15
LTEXT "Comparison &color", 410, 131, 79, 117, 12
COMBOBOX 411, 250, 76, 132, 126, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
PUSHBUTTON "Change color…", 412, 250, 97, 82, 15
LTEXT "", 413, 338, 100, 45, 12
LTEXT "Compare files &shortcut", 414, 131, 130, 117, 12
CONTROL "", 415, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 250, 127, 132, 15
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
@@ -376,3 +385,25 @@ BEGIN
CONTROL "&Rename", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 51, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 51, 86, 18
END
114 DIALOGEX 0, 0, 510, 252
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_CLIPCHILDREN
EXSTYLE WS_EX_APPWINDOW
CAPTION "Compare files"
FONT 9, "Segoe UI"
BEGIN
LTEXT "", 400, 4, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 401, 259, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 45, 510, 207
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
LTEXT "", 403, 216, 12, 98, 14
END
115 DIALOGEX 0, 0, 290, 58
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Compare files"
FONT 10, "Consolas"
BEGIN
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
END
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+1
View File
@@ -3,4 +3,5 @@
#define IDI_SCREENSHOT_QUESTION 102
#define IDI_FILES_VIEWER 103
#define IDI_FILES_EDITOR 104
#define IDI_FILES_COMPARE 105
#define IDC_SCREENSHOT_PENCIL 500
+1 -1
View File
@@ -34,6 +34,7 @@ table { display: block; border-collapse: collapse; }
th, td { border: 1px solid GrayText; padding: .3em .65em; }
img, svg { max-width: 100%; height: auto; }
figure { margin: 1em 0; }
figure svg .edgeLabel rect { fill: Canvas !important; opacity: 1 !important; stroke: none !important; }
.task { list-style: none; }
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
</style>
@@ -51,6 +52,5 @@ figure { margin: 1em 0; }
</nav>
<main></main>
<script src="markdown-it.js"></script>
<script src="mermaid.js"></script>
<script src="markdown.js"></script>
</html>
+67 -15
View File
@@ -15,16 +15,34 @@ let generation = 0;
let images = [];
let matches = [];
let activeMatch = -1;
let taskMarkers = new WeakMap();
let pendingTask;
let previewRevision = 0;
let mermaidReady;
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
function loadMermaid() {
mermaidReady ??= new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'mermaid.js';
script.onload = resolve;
script.onerror = () => reject(new Error('Could not load Mermaid'));
document.head.append(script);
}).then(() => {
const renderer = window.mermaid;
renderer.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
return renderer;
});
return mermaidReady;
}
markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
markdown.core.ruler.after('inline', 'task_lists', ({ tokens, src, env }) => {
const lines = src.split('\n');
for (let i = 2; i < tokens.length; ++i) {
const token = tokens[i];
if (token.type !== 'inline' || tokens[i - 1].type !== 'paragraph_open' ||
@@ -36,13 +54,16 @@ markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
const box = new text.constructor('task_checkbox', '', 0);
box.checked = marker[1] !== ' ';
box.content = token.content.slice(marker[0].length);
const line = tokens[i - 1].map?.[0];
const sourceMarker = /^[ \t]*(?:>[ \t]*)*(?:[-+*]|\d{1,9}[.)])[ \t]+\[([ xX])\][ \t]+/.exec(lines[line]);
if (sourceMarker) box.source = env.taskKey + ':' + line + ':' + (sourceMarker[0].lastIndexOf('[') + 1);
token.children.unshift(box);
tokens[i - 2].attrJoin('class', 'task');
}
});
markdown.renderer.rules.task_checkbox = (tokens, i) =>
'<input type="checkbox" aria-label="' + markdown.utils.escapeHtml(tokens[i].content) + '"' +
(tokens[i].checked ? ' checked' : '') + '>';
(tokens[i].checked ? ' checked' : '') + (tokens[i].source ? ' data-task="' + tokens[i].source + '"' : '') + '>';
markdown.renderer.rules.image = (tokens, i) => {
const token = tokens[i];
const alt = markdown.renderer.renderInlineAsText(token.children, markdown.options, {});
@@ -67,10 +88,13 @@ function relativeResource(path) {
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
}
function renderContent(text) {
function renderContent(text, canSave) {
// Parse in an inert template and allow only document markup before attaching it to the preview.
const template = document.createElement('template');
template.innerHTML = markdown.render(text);
const taskKey = [...crypto.getRandomValues(new Uint32Array(4))].join('-');
taskMarkers = new WeakMap();
pendingTask = undefined;
template.innerHTML = markdown.render(text, { taskKey });
for (const element of template.content.querySelectorAll('*')) {
const tag = element.localName;
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
@@ -79,6 +103,12 @@ function renderContent(text) {
continue;
}
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
const task = tag === 'input' && element.getAttribute('data-task');
if (task && task.startsWith(taskKey + ':')) {
const [, line, column] = task.split(':');
taskMarkers.set(element, { line: Number(line), column: Number(column) });
element.disabled = !canSave;
}
const styles = element.hasAttribute('style')
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
for (const { name } of [...element.attributes]) {
@@ -217,13 +247,14 @@ 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 }) {
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
else closeSearch();
document.documentElement.classList.remove('rendered');
document.title = title;
renderContent(text);
previewRevision = revision;
renderContent(text, canSave);
const headings = new Set();
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
@@ -237,15 +268,21 @@ async function render({ text, fragment, scroll, title, keepPosition }) {
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
for (const [index, block] of blocks.entries()) {
try {
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
const renderer = await loadMermaid();
if (current !== generation) return;
const { svg } = await renderer.render('diagram-' + current + '-' + index, block.textContent);
if (current !== generation) return;
const figure = document.createElement('figure');
figure.innerHTML = svg;
const paths = figure.querySelector('g.edgePaths');
const labels = figure.querySelector('g.edgeLabels');
if (paths && labels && paths.parentNode === labels.parentNode) paths.after(labels);
block.parentElement.replaceWith(figure);
} catch {
} catch (error) {
if (current !== generation) return;
const caption = document.createElement('div');
caption.textContent = 'Invalid Mermaid diagram';
caption.title = error instanceof Error ? error.message : String(error);
block.parentElement.before(caption);
}
}
@@ -255,6 +292,17 @@ async function render({ text, fragment, scroll, title, keepPosition }) {
send('rendered');
}
content.addEventListener('change', ({ target }) => {
const marker = taskMarkers.get(target);
if (!marker) return;
if (pendingTask) {
target.checked = !target.checked;
return;
}
pendingTask = { target, checked: target.checked };
send('save-task', { ...marker, revision: previewRevision, checked: target.checked });
});
content.addEventListener('click', event => {
const link = event.target.closest('a');
if (!link) return;
@@ -303,6 +351,10 @@ bridge.addEventListener('message', ({ data }) => {
content.replaceChildren();
}
if (message.action === 'render') void render(message).catch(() => send('failed'));
if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) {
if (!message.saved) pendingTask.target.checked = !pendingTask.checked;
pendingTask = undefined;
}
if (message.action === 'appearance') {
const style = document.documentElement.style;
style.setProperty('--markdown-width', message.width ? message.width + 'px' : 'none');
+183 -29
View File
@@ -200,6 +200,14 @@ std::vector<std::wstring> buildSnippetVariants(const std::wstring &trigger, cons
}
return variants;
}
bool snippetWordCharacter(wchar_t character)
{
WORD type{};
if (character == L'_' ||
(GetStringTypeW(CT_CTYPE1, &character, 1, &type) && (type & (C1_ALPHA | C1_DIGIT))))
return true;
return GetStringTypeW(CT_CTYPE3, &character, 1, &type) && (type & (C3_NONSPACING | C3_VOWELMARK));
}
size_t caretSteps(std::wstring text)
{
size_t n = 0;
@@ -535,12 +543,16 @@ class Transaction
farSelectedSteps = 0;
return valid() && chord(VK_LEFT);
}
while (farSelectedSteps && valid())
return narrowFarSelection(0);
}
bool narrowFarSelection(size_t count)
{
while (farSelectedSteps > count && valid())
{
if (!chord(VK_RIGHT, MOD_ALT | MOD_SHIFT)) return false;
--farSelectedSteps;
}
return !farSelectedSteps && valid();
return farSelectedSteps == count && valid();
}
std::optional<std::wstring> readFarSnippet(size_t count)
{
@@ -549,6 +561,21 @@ class Transaction
if (!finishSelection(false) || observed.empty()) return {};
return observed;
}
std::optional<bool> farSnippetWordBoundary(std::wstring_view trigger)
{
// Select to the beginning of Far's input line in one operation, then
// use the copied prefix to find the preceding character and restore the range.
if (!valid() || !chord(VK_HOME, MOD_ALT | MOD_SHIFT)) return {};
const auto context = copy();
if (!valid() || !context.ends_with(trigger)) return {};
if (context == trigger) return true;
const auto triggerSteps = farSelectedSteps;
farSelectedSteps = caretSteps(context);
if (snippetWordCharacter(context[context.size() - trigger.size() - 1]))
return false;
if (!narrowFarSelection(triggerSteps) || copy() != trigger || !valid()) return {};
return true;
}
std::wstring copyRange(size_t count, const std::wstring &wordCandidate,
const std::function<bool(const std::wstring &)> &matches,
const std::function<bool(const std::wstring &)> &suffixMatches = {})
@@ -862,30 +889,132 @@ void App::report(const std::wstring &text)
}
constexpr UINT_PTR TrayRetryTimer = 20;
constexpr UINT TrayRetryIntervalMs = 1000;
constexpr UINT_PTR TrayInputTimer = 22;
constexpr UINT TrayInputPulseMs = 450;
void App::addTray()
namespace
{
HICON trayInputIcon(HICON base, int width, int height, uint32_t color)
{
if (!base || width < 8 || height < 8) return nullptr;
BITMAPINFO bitmapInfo{};
bitmapInfo.bmiHeader = {sizeof(BITMAPINFOHEADER), width, -height, 1, 32, BI_RGB};
void *bits{};
HBITMAP bitmap = CreateDIBSection(nullptr, &bitmapInfo, DIB_RGB_COLORS, &bits, nullptr, 0);
if (!bitmap) return nullptr;
HDC dc = CreateCompatibleDC(nullptr);
HICON icon{};
if (dc)
{
auto previous = SelectObject(dc, bitmap);
auto pixels = static_cast<uint32_t *>(bits);
std::fill_n(pixels, size_t(width) * height, 0);
if (DrawIconEx(dc, 0, 0, base, width, height, 0, nullptr, DI_NORMAL))
{
GdiFlush();
const int radius = std::max(3, MulDiv(std::min(width, height), 3, 16));
const int cx = width - 1 - radius, cy = height - 1 - radius;
for (int y = -radius; y <= radius; ++y)
for (int x = -radius; x <= radius; ++x)
{
const int distance = x * x + y * y;
if (distance <= radius * radius)
pixels[(cy + y) * width + cx + x] = distance <= (radius - 1) * (radius - 1)
? color : 0xff242424;
}
// The 32-bit DIB supplies the transparency. The fallback mask is initialized as well.
std::vector<unsigned char> maskBits(size_t((width + 15) / 16) * 2 * height);
if (auto mask = CreateBitmap(width, height, 1, 1, maskBits.data()))
{
ICONINFO info{TRUE, 0, 0, mask, bitmap};
icon = CreateIconIndirect(&info);
DeleteObject(mask);
}
}
SelectObject(dc, previous);
DeleteDC(dc);
}
DeleteObject(bitmap);
return icon;
}
}
bool App::updateTray(DWORD action, bool notifyFile)
{
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = window;
icon.uID = 1;
icon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP;
icon.uFlags = NIF_ICON | NIF_TIP | NIF_SHOWTIP;
if (action == NIM_ADD) icon.uFlags |= NIF_MESSAGE;
icon.uCallbackMessage = TrayMessage;
icon.hIcon = (HICON)LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED);
auto tip = incomingLanFileCount ? L"KSwitcher — files ready to save: " + std::to_wstring(incomingLanFileCount)
: localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
const int width = GetSystemMetrics(SM_CXSMICON), height = GetSystemMetrics(SM_CYSMICON);
icon.hIcon = (HICON)LoadImageW(instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON, width, height, LR_SHARED);
HICON badge{};
auto tip = localBuildTitle(L"KSwitcher");
if (trayInput.paired)
{
const bool reconnecting = trayInput.reconnecting();
const uint32_t color = trayInput.stopped ? 0xfff16b66 : !trayInput.online ? 0xffa0a4ab :
!reconnecting ? 0xff45d58c : trayInputPulse ? 0xffffc457 : 0xffac7830;
badge = trayInputIcon(icon.hIcon, width, height, color);
if (badge) icon.hIcon = badge;
tip += L" — Mouse & keyboard: ";
if (trayInput.stopped) tip += L"connection stopped";
else if (!trayInput.online) tip += L"all paired PCs offline. Waiting for LAN discovery.";
else
{
tip += reconnecting ? L"reconnecting" : L"connected";
if (trayInput.connected < trayInput.paired)
tip += L" (" + std::to_wstring(trayInput.connected) + L"/" +
std::to_wstring(trayInput.paired) + L" PCs connected)";
}
}
else if (!incomingLanFileCount)
tip = localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
if (incomingLanFileCount)
tip += L"\nFiles ready to save: " + std::to_wstring(incomingLanFileCount);
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
if (Shell_NotifyIconW(NIM_ADD, &icon))
if (notifyFile)
{
icon.uFlags |= NIF_INFO;
wcscpy_s(icon.szInfoTitle, L"Incoming file ready to save");
wcscpy_s(icon.szInfo, L"Open Settings → Computers → Manage computers → Incoming files.");
icon.dwInfoFlags = NIIF_INFO;
}
const bool updated = Shell_NotifyIconW(action, &icon) != FALSE;
if (badge) DestroyIcon(badge);
return updated;
}
void App::refreshTrayInput()
{
const auto state = lanService ? lanService->inputConnections() : LanInputConnections{};
if (state == trayInput) return;
trayInput = state;
trayInputPulse = true;
if (state.reconnecting())
SetTimer(window, TrayInputTimer, TrayInputPulseMs, nullptr);
else
KillTimer(window, TrayInputTimer);
updateTray(NIM_MODIFY);
}
void App::addTray()
{
if (updateTray(NIM_ADD))
{
KillTimer(window, TrayRetryTimer);
trayRetryPending = false;
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = window;
icon.uID = 1;
icon.uVersion = NOTIFYICON_VERSION_4;
Shell_NotifyIconW(NIM_SETVERSION, &icon);
}
else if (!trayRetryPending)
{
trayRetryPending = SetTimer(window, TrayRetryTimer, TrayRetryIntervalMs, nullptr) != 0;
}
icon.uVersion = NOTIFYICON_VERSION_4;
Shell_NotifyIconW(NIM_SETVERSION, &icon);
}
bool App::registerHotkeys(const Settings &s, bool rollback)
{
@@ -926,6 +1055,7 @@ Bytes App::lanCommand(const Bytes &command)
if (lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
else KillTimer(window, 7);
if (lanService->takeInputChange()) resetLanInput();
refreshTrayInput();
return reply;
}
void App::applySettings(const Settings &requested)
@@ -1231,7 +1361,16 @@ void App::matchSnippets(HWND fg, bool expandExact)
trigger = sn.trigger;
}
if (expandExact && std::any_of(variants.begin(), variants.end(), [&](const auto &trigger) {
return keys.ends_with(trigger);
if (!keys.ends_with(trigger)) return false;
// A fresh key run can start inside existing text. The editor
// verifies the boundary before expansion even when this check passes.
if (keys.size() == trigger.size()) return true;
const auto layout = std::find_if(layouts.begin(), layouts.end(), [&](const auto &candidate) {
return candidate.handle == run.layout && candidate.convertible;
});
const auto previous = keys[keys.size() - trigger.size() - 1];
return layout == layouts.end() ||
!snippetWordCharacter(layout->at(physicalLayout().code(previous)));
}))
{
queueSnippet(fg, i, sn.trigger.size());
@@ -2207,6 +2346,7 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
{"command", transformCommandName(command)}, {"source", layout(text.empty() ? hint : detect(text, layouts, hint))}, {"target", layout(to)},
{"outcome", utf8(reason)}, {"verification", utf8(verification)},
{"problem", reason != L"Paste verified" && reason != L"layout-only" &&
reason != L"snippet-inside-word" &&
!(command == 0 && reason == L"paste-sent-unverified")},
{"elapsedMs", GetTickCount64() - start}, {"verificationMs", verificationMs},
{"foregroundSame", GetForegroundWindow() == target},
@@ -2489,11 +2629,13 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
}
bool sent = false;
const bool requireReadback = tx.recoveredSelection() || snippet >= 0;
const bool verifySelection = snippet >= 0 || (requireReadback && result != text);
auto probeStarted = GetTickCount64();
PasteProbe probe(!farSnippet && ((config.writeLog && manual) || requireReadback) && result != text, text, target);
PasteProbe probe(!farSnippet && (verifySelection || (config.writeLog && manual && result != text)),
text, target, snippet >= 0);
verificationMs = GetTickCount64() - probeStarted;
diagnosticEvent(L"Paste probe prepared: elapsedMs=" + std::to_wstring(verificationMs) + L" status=" + probe.status);
if (requireReadback && !farSnippet && result != text && probe.status != L"ready")
if (!farSnippet && verifySelection && probe.status != L"ready")
{
verification = probe.status;
reason = snippet >= 0 ? L"snippet-verification-unavailable" : L"recovered-selection-unavailable";
@@ -2502,6 +2644,19 @@ void App::transform(int command, int snippet, size_t snippetLength, HWND snippet
run.reset();
return;
}
if (snippet >= 0)
{
std::optional<bool> boundary;
if (farSnippet)
boundary = tx.farSnippetWordBoundary(text);
else if (const auto &preceding = probe.precedingCharacter)
boundary = preceding->empty() || !snippetWordCharacter(preceding->back());
if (!boundary.value_or(false))
{
reason = boundary ? L"snippet-inside-word" : L"snippet-word-boundary-unavailable";
return;
}
}
diagnosticEvent(L"Conversion source=" + std::to_wstring(hint) + L" target=" + std::to_wstring(to) +
L" changed=" + std::to_wstring(result != text));
if (result != text)
@@ -3201,23 +3356,12 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case LanFilesChangedMessage:
{
app->incomingLanFileCount = wp;
NOTIFYICONDATAW icon{sizeof(icon)};
icon.hWnd = hwnd;
icon.uID = 1;
icon.uFlags = NIF_TIP | NIF_SHOWTIP;
auto tip = wp ? L"KSwitcher — files ready to save: " + std::to_wstring(wp)
: localBuildTitle(L"KSwitcher — keyboard layouts & clipboard");
wcsncpy_s(icon.szTip, tip.c_str(), _TRUNCATE);
if (lp)
{
icon.uFlags |= NIF_INFO;
wcscpy_s(icon.szInfoTitle, L"Incoming file ready to save");
wcscpy_s(icon.szInfo, L"Open Settings → Computers → Manage computers → Incoming files.");
icon.dwInfoFlags = NIIF_INFO;
}
if (Shell_NotifyIconW(NIM_MODIFY, &icon) && lp) app->incomingFileBalloon = true;
if (app->updateTray(NIM_MODIFY, lp != 0) && lp) app->incomingFileBalloon = true;
return 0;
}
case LanInputStatusMessage:
app->refreshTrayInput();
return 0;
case CheckAutostartMessage:
app->checkAutostartPath();
return 0;
@@ -3260,6 +3404,15 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
if (app->trayRetryPending) app->addTray();
return 0;
}
if (wp == TrayInputTimer)
{
if (app->trayInput.reconnecting())
{
app->trayInputPulse = !app->trayInputPulse;
app->updateTray(NIM_MODIFY);
}
return 0;
}
if (wp == MouseClickTimer) { app->flushMouseClicks(); return 0; }
if (wp >= FirstMouseVolumeTimer && wp < FirstMouseVolumeTimer + std::size(MouseButtonNames))
{
@@ -3453,6 +3606,7 @@ int App::execute()
try { lanService = std::make_unique<LanService>(data,window); }
catch (const std::exception &e) { report(L"LAN module: " + wide(e.what())); }
if (lanService && lanService->inputEnabled()) SetTimer(window, 7, 10, nullptr);
refreshTrayInput();
SetTimer(window, 1, 60000, nullptr);
if (!smoke) SetTimer(window, 6, 1000, nullptr);
if (!smoke) SetTimer(window, 8, 250, nullptr);
+4
View File
@@ -161,6 +161,10 @@ class App
bool stop{};
UINT taskbarCreated{};
bool trayRetryPending{};
LanInputConnections trayInput;
bool trayInputPulse{};
bool updateTray(DWORD action, bool notifyFile = false);
void refreshTrayInput();
uint64_t transformAttempt{}, previousAttemptVersion{};
size_t incomingLanFileCount{};
bool incomingFileBalloon{};
+868
View File
@@ -0,0 +1,868 @@
constexpr uint64_t compareFileLimit=2*ks::files::TextDocument::pageBytes;
enum ComparisonColor { CompareBackground, CompareText, CompareInsert, CompareDelete, CompareReplace,
CompareInline, ComparePadding, CompareDivider, CompareChangedText, CompareColorCount };
constexpr const wchar_t *comparisonColorNames[]{L"Background",L"Text",L"Insertion",L"Deletion",L"Replacement",
L"Changed fragment",L"Alignment padding",L"Divider",L"Text on changed lines"};
constexpr wchar_t comparisonAppearanceKey[]=L"ComparisonAppearance";
constexpr wchar_t comparisonShortcutKey[]=L"ComparisonShortcut";
constexpr WORD defaultComparisonShortcut=MAKEWORD(VK_F11,HOTKEYF_SHIFT);
WORD comparisonShortcut=defaultComparisonShortcut;
constexpr int comparisonSplitScale=10000;
bool validComparisonShortcut(WORD shortcut)
{
const auto key=LOBYTE(shortcut),modifiers=HIBYTE(shortcut);
return key>=VK_F1 && key<=VK_F12 &&
(modifiers==(HOTKEYF_CONTROL|HOTKEYF_SHIFT) ||
(modifiers==HOTKEYF_SHIFT && key!=VK_F4 && key!=VK_F8));
}
void loadComparisonShortcut()
{
const auto shortcut=static_cast<WORD>(preference(comparisonShortcutKey,defaultComparisonShortcut));
comparisonShortcut=validComparisonShortcut(shortcut)?shortcut:defaultComparisonShortcut;
}
std::wstring comparisonShortcutLabel()
{
return std::wstring(HIBYTE(comparisonShortcut)&HOTKEYF_CONTROL?L"Ctrl+Shift+F":L"Shift+F")+
std::to_wstring(LOBYTE(comparisonShortcut)-VK_F1+1);
}
struct ComparisonAppearance
{
LOGFONTW font=defaultFilesFont();
int points=defaultFontPoints;
std::array<COLORREF,CompareColorCount> palette{RGB(255,255,255),RGB(24,24,24),RGB(177,226,184),
RGB(249,194,194),RGB(251,224,154),RGB(245,170,90),RGB(230,230,230),RGB(160,160,160),RGB(24,24,24)};
bool operator==(const ComparisonAppearance &other) const
{
return points==other.points && palette==other.palette && !memcmp(&font,&other.font,sizeof(font));
}
};
ComparisonAppearance readComparisonAppearance()
{
ComparisonAppearance appearance;
DWORD bytes=sizeof(appearance);
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,comparisonAppearanceKey,RRF_RT_REG_BINARY,nullptr,
&appearance,&bytes)!=ERROR_SUCCESS || bytes!=sizeof(appearance) ||
appearance.points<80 || appearance.points>240 ||
std::any_of(appearance.palette.begin(),appearance.palette.end(),[](auto color){return color>0xffffff;}))
return {};
appearance.font.lfFaceName[LF_FACESIZE-1]=0;
return appearance;
}
bool saveComparisonAppearance(const ComparisonAppearance &appearance)
{
return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,comparisonAppearanceKey,REG_BINARY,
&appearance,sizeof(appearance))==ERROR_SUCCESS;
}
struct CompareFile
{
fs::path path;
std::wstring label;
std::optional<FilesPeer> peer;
std::optional<FtpProfile> ftp;
};
struct CompareRow
{
int left=-1,right=-1;
bool changed{};
size_t commonStart{},commonEnd{};
bool whitespaceOnly{};
bool hasChange(bool showWhitespace) const {return changed && (showWhitespace || !whitespaceOnly);}
};
struct FileComparison
{
static constexpr std::array controls{400,401,402,403,407};
CompareFile files[2];
std::vector<std::wstring> lines[2];
std::vector<CompareRow> rows;
std::vector<int> changes,allChanges;
bool showWhitespace{};
RECT initialClient{};
std::array<RECT,controls.size()> initialControls{};
SIZE minimumWindow{};
ComparisonAppearance appearance;
HFONT font{};
HBRUSH background{};
int characterWidth=1;
int split=comparisonSplitScale/2;
std::optional<int> splitDragOffset;
int zoom{},wheelRemainder{};
~FileComparison()
{
if(font) DeleteObject(font);
if(background) DeleteObject(background);
}
};
std::map<HWND,std::unique_ptr<FileComparison>> comparisonWindows;
LONG comparisonSplitX(const FileComparison &comparison,LONG width)
{
return MulDiv(width,comparison.split,comparisonSplitScale);
}
void layoutComparisonHeaders(HWND dialog,const FileComparison &comparison)
{
const auto list=GetDlgItem(dialog,402);
RECT bounds{};
GetClientRect(list,&bounds);
MapWindowPoints(list,dialog,reinterpret_cast<POINT*>(&bounds),2);
const auto middle=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const auto inset=comparison.initialControls[0].left;
for(int side=0;side<2;++side)
{
const auto &initial=comparison.initialControls[side];
const auto left=(side?middle:bounds.left)+inset;
const auto right=(side?bounds.right:middle)-inset;
SetWindowPos(GetDlgItem(dialog,400+side),nullptr,left,initial.top,std::max(0L,right-left),
initial.bottom-initial.top,SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
}
}
void applyComparisonFont(HWND dialog,FileComparison &comparison)
{
auto font=comparison.appearance.font;
const auto dpi=GetDpiForWindow(dialog);
const auto points=std::clamp(comparison.appearance.points+comparison.zoom,80,240);
comparison.zoom=points-comparison.appearance.points;
font.lfHeight=-MulDiv(points,dpi,720);
font.lfWidth=0;
if(const auto next=CreateFontIndirectW(&font))
{
if(comparison.font) DeleteObject(comparison.font);
comparison.font=next;
}
const auto list=GetDlgItem(dialog,402);
if(const auto dc=GetDC(list))
{
const auto previous=SelectObject(dc,comparison.font?comparison.font:mono);
TEXTMETRICW metrics{};
if(GetTextMetricsW(dc,&metrics))
{
comparison.characterWidth=std::max(1L,metrics.tmAveCharWidth);
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
SendMessageW(list,LB_SETITEMHEIGHT,0,metrics.tmHeight+MulDiv(6,dpi,96));
SendMessageW(list,LB_SETTOPINDEX,top,0);
}
SelectObject(dc,previous);
ReleaseDC(list,dc);
}
InvalidateRect(list,nullptr,TRUE);
}
void applyComparisonAppearance(HWND dialog,FileComparison &comparison)
{
comparison.appearance=readComparisonAppearance();
if(const auto next=CreateSolidBrush(comparison.appearance.palette[CompareBackground]))
{
if(comparison.background) DeleteObject(comparison.background);
comparison.background=next;
}
applyComparisonFont(dialog,comparison);
}
bool zoomComparison(HWND dialog,FileComparison &comparison,WPARAM wheel)
{
if(!(GET_KEYSTATE_WPARAM(wheel)&MK_CONTROL)) return false;
comparison.wheelRemainder+=GET_WHEEL_DELTA_WPARAM(wheel);
const auto steps=comparison.wheelRemainder/WHEEL_DELTA;
comparison.wheelRemainder%=WHEEL_DELTA;
const auto base=comparison.appearance.points;
const auto zoom=std::clamp(base+comparison.zoom+10*steps,80,240)-base;
if(zoom!=comparison.zoom)
{
comparison.zoom=zoom;
applyComparisonFont(dialog,comparison);
layoutComparisonHeaders(dialog,comparison);
}
return true;
}
bool handleComparisonMessage(MSG &message)
{
if(!message.hwnd) return false;
const auto window=GetAncestor(message.hwnd,GA_ROOT);
if(!comparisonWindows.contains(window)) return false;
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
{
SendMessageW(window,WM_CLOSE,0,0);
return true;
}
if(!IsDialogMessageW(window,&message))
{
TranslateMessage(&message);
DispatchMessageW(&message);
}
return true;
}
std::vector<std::wstring> readComparisonLines(const CompareFile &input,const std::atomic_bool &canceled)
{
struct TemporaryDirectory
{
fs::path path;
~TemporaryDirectory()
{
if(path.empty()) return;
std::error_code ignored;
fs::remove_all(path,ignored);
}
} temporary;
auto path=input.path;
if(input.ftp || input.peer)
{
const auto directory=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
requireFileOperation(fs::create_directory(directory),ERROR_ALREADY_EXISTS);
temporary.path=directory;
path=directory/L"file";
CopyHost source(input.peer?&*input.peer:nullptr,input.ftp);
const auto info=source.stat(input.path,canceled);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_NOT_SUPPORTED);
requireFileOperation(info->size<=compareFileLimit,ERROR_FILE_TOO_LARGE);
FilesConnection local;
const auto progress=[&](uint64_t,uint64_t){return !canceled;};
if(source.ftp) downloadFtpFile(*source.ftp,local,input.path,path,*info,false,progress);
else ks::lan::streamFile(*source.files,local,input.peer->id,input.path,path,info->size,
info->modified,false,false,progress);
}
ks::files::TextDocument document(path,false);
requireFileOperation(document.size()<=compareFileLimit,ERROR_FILE_TOO_LARGE);
std::string text;
for(uint64_t page=0;page<document.pages() && !canceled;++page) text+=document.readPage(page);
requireFileOperation(!canceled,ERROR_CANCELLED);
if(std::any_of(text.begin(),text.end(),[](unsigned char ch){
return ch<32 && ch!='\t' && ch!='\r' && ch!='\n' && ch!='\f';
})) throw std::runtime_error("Select two text files.");
if(text.empty()) return {};
const auto bytes=static_cast<int>(text.size());
const auto count=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,nullptr,0);
if(!count) throw std::runtime_error("Compare files supports UTF-8 and UTF-16 text.");
std::wstring decoded(count,L'\0');
checkFileOperation(MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,decoded.data(),count)!=0);
std::vector<std::wstring> lines;
size_t start=0;
while(true)
{
requireFileOperation(!canceled,ERROR_CANCELLED);
if(lines.size()==100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
const auto end=decoded.find_first_of(L"\r\n",start);
lines.push_back(decoded.substr(start,end==decoded.npos?end:end-start));
if(end==decoded.npos) break;
start=end+((decoded[end]==L'\r' && end+1<decoded.size() && decoded[end+1]==L'\n')?2:1);
}
return lines;
}
std::wstring_view comparisonContent(std::wstring_view line)
{
const auto start=line.find_first_not_of(L" \t");
if(start==line.npos) return {};
return line.substr(start,line.find_last_not_of(L" \t")-start+1);
}
void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
{
const auto &left=result.lines[0],&right=result.lines[1];
std::map<std::wstring_view,unsigned> ids;
std::map<unsigned,unsigned> blankIds;
unsigned nextId=1;
const auto encode=[&](const auto &lines)
{
std::vector<unsigned> values;
values.reserve(lines.size());
unsigned previousContent=0;
for(const auto &line:lines)
{
requireFileOperation(!canceled,ERROR_CANCELLED);
const auto content=comparisonContent(line);
// Blank lines can anchor alignment alongside the preceding content.
if(content.empty())
{
const auto [entry,inserted]=blankIds.try_emplace(previousContent,nextId);
nextId+=inserted;
values.push_back(entry->second);
}
else
{
const auto [entry,inserted]=ids.try_emplace(content,nextId);
nextId+=inserted;
previousContent=entry->second;
values.push_back(previousContent);
}
}
return values;
};
const auto a=encode(left),b=encode(right);
size_t prefix=0, suffix=0;
while(prefix<a.size() && prefix<b.size() && a[prefix]==b[prefix]) ++prefix;
while(suffix<a.size()-prefix && suffix<b.size()-prefix &&
a[a.size()-1-suffix]==b[b.size()-1-suffix]) ++suffix;
const auto n=static_cast<int>(a.size()-prefix-suffix),m=static_cast<int>(b.size()-prefix-suffix);
const auto append=[&](int x,int y)
{
CompareRow row{x,y,x<0 || y<0 || left[x]!=right[y]};
if(row.changed && (result.rows.empty() || !result.rows.back().changed))
result.allChanges.push_back(static_cast<int>(result.rows.size()));
if(row.changed && x>=0 && y>=0)
{
const auto &l=left[x],&r=right[y];
row.whitespaceOnly=comparisonContent(l)==comparisonContent(r);
const size_t length=std::min(l.size(),r.size());
while(row.commonStart<length && l[row.commonStart]==r[row.commonStart]) ++row.commonStart;
if(row.commonStart && l[row.commonStart-1]>=0xd800 && l[row.commonStart-1]<=0xdbff)
--row.commonStart;
while(row.commonEnd<length-row.commonStart &&
l[l.size()-1-row.commonEnd]==r[r.size()-1-row.commonEnd]) ++row.commonEnd;
if(row.commonEnd && l[l.size()-row.commonEnd]>=0xdc00 && l[l.size()-row.commonEnd]<=0xdfff)
--row.commonEnd;
}
if(row.hasChange(false) && (result.rows.empty() || !result.rows.back().hasChange(false)))
result.changes.push_back(static_cast<int>(result.rows.size()));
result.rows.push_back(row);
};
const auto change=[&](size_t x,size_t y,size_t countLeft,size_t countRight)
{
// Prefer pairing structurally similar lines, leaving unmatched lines on their own side.
const auto score=[](std::wstring_view l,std::wstring_view r)
{
if(l.empty() || r.empty()) return l.empty() && r.empty()?1u:0u;
const auto cap=std::min({l.size(),r.size(),size_t{64}});
size_t start=0,end=0;
while(start<cap && l[start]==r[start]) ++start;
while(end<cap-start && l[l.size()-1-end]==r[r.size()-1-end]) ++end;
return 1u+static_cast<unsigned>(4*(start+end));
};
if(!countLeft || !countRight || countLeft>160'000/countRight)
{
for(size_t i=0;i<std::max(countLeft,countRight);++i)
append(i<countLeft?static_cast<int>(x+i):-1,i<countRight?static_cast<int>(y+i):-1);
return;
}
const auto stride=countRight+1;
std::vector<std::wstring_view> l,r;
for(size_t i=0;i<countLeft;++i) l.push_back(comparisonContent(left[x+i]));
for(size_t j=0;j<countRight;++j) r.push_back(comparisonContent(right[y+j]));
std::vector<unsigned> best((countLeft+1)*stride);
for(size_t i=countLeft;i-->0;)
for(size_t j=countRight;j-->0;)
best[i*stride+j]=std::max({best[(i+1)*stride+j],best[i*stride+j+1],
best[(i+1)*stride+j+1]+score(l[i],r[j])});
size_t i=0,j=0;
while(i<countLeft && j<countRight)
{
const auto pairScore=score(l[i],r[j]);
if(pairScore && best[i*stride+j]==best[(i+1)*stride+j+1]+pairScore)
{
append(static_cast<int>(x+i),static_cast<int>(y+j));
++i;
++j;
}
else if(best[(i+1)*stride+j]>=best[i*stride+j+1]) append(static_cast<int>(x+i++),-1);
else append(-1,static_cast<int>(y+j++));
}
while(i<countLeft) append(static_cast<int>(x+i++),-1);
while(j<countRight) append(-1,static_cast<int>(y+j++));
};
for(size_t i=0;i<prefix;++i) append(static_cast<int>(i),static_cast<int>(i));
if(n && m)
{
// Myers alignment. Each pass records the farthest left index per edit diagonal.
std::vector<std::vector<int>> trace;
const auto previousDiagonal=[](const std::vector<int> &prior,int d,int k)
{
if(k==-d || (k!=d && prior[(d+k-2)/2]<prior[(d+k)/2])) return k+1;
return k-1;
};
bool complete=false;
for(int d=0;!complete;++d)
{
requireFileOperation(!canceled,ERROR_CANCELLED);
if(d>2'500) throw std::runtime_error("Too many differing lines to align in this comparison.");
std::vector<int> level;
level.reserve(d+1);
for(int k=-d;k<=d;k+=2)
{
int x=0;
if(d)
{
const auto &prior=trace.back();
const auto previous=previousDiagonal(prior,d,k);
x=prior[(d-1+previous)/2]+(previous<k);
}
int y=x-k;
while(x<n && y<m && a[prefix+x]==b[prefix+y]) {++x;++y;}
level.push_back(x);
if(x>=n && y>=m) {complete=true;break;}
}
trace.push_back(std::move(level));
}
std::vector<std::pair<int,int>> matches;
int x=n,y=m;
for(int d=static_cast<int>(trace.size())-1;d>0;--d)
{
const auto &prior=trace[d-1];
const auto previous=previousDiagonal(prior,d,x-y);
const int startX=prior[(d-1+previous)/2],startY=startX-previous;
while(x>startX && y>startY) {--x;--y;matches.emplace_back(x,y);}
x=startX;
y=startY;
}
while(x>0 && y>0) {--x;--y;matches.emplace_back(x,y);}
int fromLeft=0,fromRight=0;
for(auto it=matches.rbegin();it!=matches.rend();++it)
{
const auto [leftLine,rightLine]=*it;
change(prefix+fromLeft,prefix+fromRight,leftLine-fromLeft,rightLine-fromRight);
append(static_cast<int>(prefix+leftLine),static_cast<int>(prefix+rightLine));
fromLeft=leftLine+1;
fromRight=rightLine+1;
}
change(prefix+fromLeft,prefix+fromRight,n-fromLeft,m-fromRight);
}
else change(prefix,prefix,n,m);
for(size_t i=0;i<suffix;++i)
append(static_cast<int>(a.size()-suffix+i),static_cast<int>(b.size()-suffix+i));
}
void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &item)
{
const auto dc=item.hDC;
const auto bounds=item.rcItem;
const auto fill=[&](const RECT &area,COLORREF color)
{
SetDCBrushColor(dc,color);
FillRect(dc,&area,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
};
const auto &palette=comparison.appearance.palette;
const auto cell=comparison.characterWidth;
fill(bounds,palette[CompareBackground]);
if(item.itemID>=comparison.rows.size()) return;
const auto &row=comparison.rows[item.itemID];
const bool changed=row.hasChange(comparison.showWhitespace);
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const LONG gutter=std::max(4,cell);
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
if(changed) fill(link,highlight);
else
{
const RECT divider{center,bounds.top,center+1,bounds.bottom};
fill(divider,palette[CompareDivider]);
}
if(changed)
{
const LONG middle=(bounds.top+bounds.bottom)/2;
const LONG start=row.left<0?bounds.top:middle,end=row.right<0?bounds.top:middle;
SetDCPenColor(dc,palette[CompareChangedText]);
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
MoveToEx(dc,link.left,start,nullptr);
LineTo(dc,link.right,end);
SelectObject(dc,pen);
}
SelectObject(dc,comparison.font?comparison.font:mono);
SetBkMode(dc,TRANSPARENT);
const auto ink=palette[changed?CompareChangedText:CompareText];
SetTextColor(dc,ink);
const auto drawSide=[&](int side,int number,RECT area)
{
if(number<0)
{
fill(area,palette[ComparePadding]);
return;
}
if(changed) fill(area,highlight);
const auto numberText=std::to_wstring(number+1);
RECT numberArea=area;
numberArea.right=std::min(area.right,area.left+7*cell);
DrawTextW(dc,numberText.c_str(),-1,&numberArea,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
area.left=std::min(area.right,numberArea.right+cell);
const auto &line=comparison.lines[side][number];
const auto paneWidth=area.right-area.left;
if(paneWidth<=0) return;
const auto limit=static_cast<size_t>(paneWidth/cell+2)*4;
auto visible=std::wstring_view(line).substr(0,limit);
const bool clipped=visible.size()<line.size();
if(clipped && visible.back()>=0xd800 && visible.back()<=0xdbff)
visible.remove_suffix(1);
if(changed && row.left>=0 && row.right>=0)
{
const auto width=[&](size_t chars)->LONG
{
if(chars>visible.size()) return paneWidth;
RECT measured{};
if(chars) DrawTextW(dc,visible.data(),static_cast<int>(chars),&measured,
DT_CALCRECT|DT_SINGLELINE|DT_EXPANDTABS|DT_NOPREFIX);
return std::min(paneWidth,measured.right);
};
const auto start=std::min(area.right,area.left+width(row.commonStart));
const auto end=std::min(area.right,area.left+width(line.size()-row.commonEnd));
const RECT changed{start,area.top,std::min(area.right,std::max(start+2,end)),area.bottom};
fill(changed,palette[CompareInline]);
}
constexpr UINT flags=DT_SINGLELINE|DT_VCENTER|DT_EXPANDTABS|DT_NOPREFIX|DT_END_ELLIPSIS;
if(clipped)
{
auto text=std::wstring(visible)+L"…";
DrawTextW(dc,text.c_str(),static_cast<int>(text.size()),&area,flags);
}
else if(!visible.empty()) DrawTextW(dc,visible.data(),static_cast<int>(visible.size()),&area,flags);
};
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
if(item.itemState&ODS_SELECTED)
{
SetDCBrushColor(dc,ink);
FrameRect(dc,&bounds,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
}
LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_KEYDOWN && (wp==VK_F7 || wp==VK_F8))
{
SendMessageW(GetParent(control),WM_COMMAND,wp==VK_F7?404:405,0);
return 0;
}
if(GetDlgCtrlID(control)!=402) return DefSubclassProc(control,message,wp,lp);
const auto dialog=GetParent(control);
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!comparison) return DefSubclassProc(control,message,wp,lp);
if(message==WM_MOUSEWHEEL && zoomComparison(dialog,*comparison,wp)) return 0;
if(message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)
{
RECT client{};
GetClientRect(control,&client);
const auto middle=comparisonSplitX(*comparison,client.right);
POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
if(message==WM_SETCURSOR)
{
if(LOWORD(lp)!=HTCLIENT) return DefSubclassProc(control,message,wp,lp);
GetCursorPos(&point);
ScreenToClient(control,&point);
}
const auto grip=MulDiv(5,GetDpiForWindow(control),96);
if(comparison->splitDragOffset || std::abs(point.x-middle)<=grip)
{
SetCursor(LoadCursorW(nullptr,IDC_SIZEWE));
if(message!=WM_SETCURSOR)
{
comparison->splitDragOffset=point.x-middle;
SetCapture(control);
if(GetCapture()!=control) comparison->splitDragOffset.reset();
}
return TRUE;
}
}
if(comparison->splitDragOffset && (message==WM_MOUSEMOVE || message==WM_LBUTTONUP))
{
RECT client{};
GetClientRect(control,&client);
if(client.right>0)
{
constexpr int minimumShare=1500;
const auto position=GET_X_LPARAM(lp)-*comparison->splitDragOffset;
const auto split=std::clamp(MulDiv(position,comparisonSplitScale,client.right),
minimumShare,comparisonSplitScale-minimumShare);
if(split!=comparison->split)
{
comparison->split=split;
layoutComparisonHeaders(dialog,*comparison);
InvalidateRect(control,nullptr,FALSE);
}
}
if(message==WM_LBUTTONUP) ReleaseCapture();
return 0;
}
if(message==WM_CAPTURECHANGED) comparison->splitDragOffset.reset();
const auto result=DefSubclassProc(control,message,wp,lp);
if(message==WM_PAINT)
{
RECT client{},last{};
GetClientRect(control,&client);
const auto count=SendMessageW(control,LB_GETCOUNT,0,0);
if(count>0 && SendMessageW(control,LB_GETITEMRECT,count-1,reinterpret_cast<LPARAM>(&last))==LB_ERR)
return result;
const auto middle=comparisonSplitX(*comparison,client.right);
const RECT blank{client.left,std::max(client.top,last.bottom),client.right,client.bottom};
if(blank.top<blank.bottom)
{
const auto dc=GetDC(control);
if(dc)
{
// The list box repaints its rows but can leave earlier divider marks below them.
FillRect(dc,&blank,comparison->background?comparison->background:
static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
const RECT divider{middle,blank.top,middle+1,blank.bottom};
SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]);
FillRect(dc,&divider,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
ReleaseDC(control,dc);
}
}
}
return result;
}
void layoutComparison(HWND dialog)
{
const auto *comparison=reinterpret_cast<const FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!comparison || comparison->initialClient.right<=0) return;
RECT client{};
GetClientRect(dialog,&client);
for(size_t i=0;i<FileComparison::controls.size();++i)
{
const auto id=FileComparison::controls[i];
if(id==400 || id==401) continue;
auto bounds=comparison->initialControls[i];
if(id==402) bounds={0,bounds.top,client.right,client.bottom};
SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,bounds.top,
bounds.right-bounds.left,std::max(0L,bounds.bottom-bounds.top),
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
}
layoutComparisonHeaders(dialog,*comparison);
InvalidateRect(dialog,nullptr,FALSE);
}
void updateComparisonSummary(HWND dialog,const FileComparison &comparison)
{
const auto blocks=(comparison.showWhitespace?comparison.allChanges:comparison.changes).size();
const auto summary=blocks==0?L"Text is identical":blocks==1?L"1 change block":
std::to_wstring(blocks)+L" change blocks";
SetDlgItemTextW(dialog,403,summary.c_str());
const auto toolbar=GetDlgItem(dialog,407);
for(const auto id:{404,405}) SendMessageW(toolbar,TB_ENABLEBUTTON,id,MAKELONG(blocks!=0,0));
}
void initializeComparisonToolbar(HWND toolbar)
{
SendMessageW(toolbar,TB_BUTTONSTRUCTSIZE,sizeof(TBBUTTON),0);
SendMessageW(toolbar,TB_SETEXTENDEDSTYLE,0,TBSTYLE_EX_MIXEDBUTTONS);
SendMessageW(toolbar,TB_SETMAXTEXTROWS,1,0);
const auto first=SendMessageW(toolbar,TB_LOADIMAGES,IDB_HIST_SMALL_COLOR,reinterpret_cast<LPARAM>(HINST_COMMCTRL));
const auto icon=[&](int index){return first<0?I_IMAGENONE:static_cast<int>(first)+index;};
constexpr BYTE text=BTNS_AUTOSIZE|BTNS_SHOWTEXT;
const auto separator=MulDiv(8,GetDpiForWindow(toolbar),96);
const TBBUTTON buttons[]{
{icon(HIST_BACK),404,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Previous")},
{icon(HIST_FORWARD),405,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Next")},
{separator,0,0,BTNS_SEP,{},0,0},
{I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Show whitespace changes")}
};
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
}
INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
const auto list=GetDlgItem(dialog,402);
const auto toolbar=GetDlgItem(dialog,407);
if(message==WM_INITDIALOG)
{
comparison=reinterpret_cast<FileComparison*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
GetClientRect(dialog,&comparison->initialClient);
for(size_t i=0;i<FileComparison::controls.size();++i)
comparison->initialControls[i]=dialogControlBounds(dialog,FileComparison::controls[i]);
RECT window{};
GetWindowRect(dialog,&window);
comparison->minimumWindow={MulDiv(window.right-window.left,3,4),(window.bottom-window.top)/2};
const auto resource=MAKEINTRESOURCEW(IDI_FILES_COMPARE);
const auto dpi=GetDpiForWindow(dialog);
const auto small=LoadImageW(GetModuleHandleW(nullptr),resource,IMAGE_ICON,
GetSystemMetricsForDpi(SM_CXSMICON,dpi),GetSystemMetricsForDpi(SM_CYSMICON,dpi),LR_SHARED);
const auto large=LoadIconW(GetModuleHandleW(nullptr),resource);
SendMessageW(dialog,WM_SETICON,ICON_SMALL,reinterpret_cast<LPARAM>(small));
SendMessageW(dialog,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(large));
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,L"HrynCo.KSwitcher.Files.Compare");
for(int side=0;side<2;++side) SetDlgItemTextW(dialog,400+side,comparison->files[side].label.c_str());
initializeComparisonToolbar(toolbar);
updateComparisonSummary(dialog,*comparison);
SetWindowSubclass(list,comparisonKeys,1,0);
SetWindowSubclass(toolbar,comparisonKeys,1,0);
applyComparisonAppearance(dialog,*comparison);
SendMessageW(list,LB_SETCOUNT,comparison->rows.size(),0);
layoutComparisonHeaders(dialog,*comparison);
if(!comparison->changes.empty()) SendMessageW(list,LB_SETCURSEL,comparison->changes.front(),0);
return TRUE;
}
if(message==filesPreferencesChanged && comparison)
{
applyComparisonAppearance(dialog,*comparison);
layoutComparisonHeaders(dialog,*comparison);
return TRUE;
}
if(message==WM_CLOSE)
{
DestroyWindow(dialog);
return TRUE;
}
if(message==WM_MOUSEWHEEL && comparison && zoomComparison(dialog,*comparison,wp)) return TRUE;
if(message==WM_NCDESTROY)
{
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,nullptr);
comparisonWindows.erase(dialog);
return FALSE;
}
if(message==WM_GETMINMAXINFO && comparison && comparison->minimumWindow.cx)
{
auto &size=reinterpret_cast<MINMAXINFO*>(lp)->ptMinTrackSize;
size.x=comparison->minimumWindow.cx;
size.y=comparison->minimumWindow.cy;
return TRUE;
}
if(message==WM_SIZE && wp!=SIZE_MINIMIZED)
{
layoutComparison(dialog);
return TRUE;
}
if(message==WM_DRAWITEM && wp==402 && comparison)
{
drawComparisonRow(*comparison,*reinterpret_cast<const DRAWITEMSTRUCT*>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX)
return reinterpret_cast<INT_PTR>(comparison && comparison->background?comparison->background:
GetStockObject(WHITE_BRUSH));
if(message==WM_COMMAND && comparison)
{
const auto id=LOWORD(wp);
if(id==IDCANCEL) {DestroyWindow(dialog);return TRUE;}
if(id==406 && HIWORD(wp)==BN_CLICKED)
{
comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0;
updateComparisonSummary(dialog,*comparison);
InvalidateRect(list,nullptr,FALSE);
return TRUE;
}
const auto &changes=comparison->showWhitespace?comparison->allChanges:comparison->changes;
if((id==404 || id==405) && !changes.empty())
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(id==404)
{
const auto previous=std::lower_bound(changes.begin(),changes.end(),current);
if(previous!=changes.begin()) SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
}
else
{
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
if(next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
}
return TRUE;
}
if(id==402 && HIWORD(wp)==LBN_DBLCLK)
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(current>=0 && static_cast<size_t>(current)<comparison->rows.size())
{
const auto &row=comparison->rows[current];
const auto side=[&](int file,int line)
{
return line<0?std::wstring(L"—"):comparison->lines[file][line];
};
const auto detail=L"Left\n"+side(0,row.left)+L"\n\nRight\n"+side(1,row.right);
showFilesNotice(dialog,detail.c_str(),L"Line details");
}
return TRUE;
}
}
return FALSE;
}
INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDCANCEL)
{
*reinterpret_cast<std::atomic_bool*>(GetWindowLongPtrW(dialog,DWLP_USER))=true;
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
return TRUE;
}
return paintTextDialog(dialog,message,wp,lp,L" Compare files ");
}
void compareSelectedFiles(HWND owner)
{
auto &current=panels[active],&other=panels[1-active];
const auto selected=selectedPanelPaths(current);
const auto opposite=selectedPanelPaths(other);
auto state=std::make_unique<FileComparison>();
auto &comparison=*state;
const auto pick=[](const Panel &panel,const fs::path &path,CompareFile &file)
{
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
if(ftpProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder")
return false;
const auto directory=path.parent_path();
const auto tail=(directory.filename()/path.filename()).native();
const auto location=panelLocation(panel);
const auto label=tail+L" · "+location;
file={path,label,panel.peer,panel.ftp};
return true;
};
bool valid=false;
if(selected.size()==2)
valid=pick(current,selected[0],comparison.files[0]) && pick(current,selected[1],comparison.files[1]);
else if(selected.size()==1 && opposite.size()==1)
valid=pick(current,selected.front(),comparison.files[active]) &&
pick(other,opposite.front(),comparison.files[1-active]);
if(!valid)
{
showFilesNotice(owner,L"Mark two text files in the active panel or select one text file in each panel.",
L"Compare files");
return;
}
std::atomic_bool canceled{};
try
{
{
FileOperationUi worker;
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
comparisonProgressDialog,reinterpret_cast<LPARAM>(&canceled),false);
if(!progress.window()) throw std::runtime_error("Could not open the progress dialog.");
progress.show();
worker.run(progress.window(),canceled,[&]
{
for(int side=0;side<2;++side)
comparison.lines[side]=readComparisonLines(comparison.files[side],canceled);
alignComparison(comparison,canceled);
});
}
if(!canceled)
{
const auto window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(114),nullptr,
comparisonDialog,reinterpret_cast<LPARAM>(&comparison));
if(!window) throw std::runtime_error("Could not open the comparison window.");
comparisonWindows.emplace(window,std::move(state));
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
SetFocus(GetDlgItem(window,402));
}
}
catch(const std::system_error &error)
{
if(canceled || error.code().value()==ERROR_CANCELLED) return;
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":
fileError(error);
showFileOperationError(owner,L"Comparison failed",detail);
}
catch(const std::exception &error)
{
if(!canceled) showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
}
}
+34 -16
View File
@@ -52,8 +52,10 @@ LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data)
class FilesModalDialog
{
public:
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument)
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument,
bool watchOutsideClicks=true)
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
watchOutsideClicks_(watchOutsideClicks)
{
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
}
@@ -108,8 +110,7 @@ public:
previous_=activeFilesDialog;
activeFilesDialog=window_;
entered_=true;
if(!filesDialogMouseHook)
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
refreshMouseHook();
if(GetWindowRect(owner_,&ownerBounds_))
{
if(!layout_) captureLayout();
@@ -132,11 +133,7 @@ public:
if(!entered_) return;
entered_=false;
activeFilesDialog=previous_;
if(!previous_ && filesDialogMouseHook)
{
UnhookWindowsHookEx(filesDialogMouseHook);
filesDialogMouseHook=nullptr;
}
refreshMouseHook();
if(IsWindow(owner_) && !IsIconic(GetAncestor(owner_,GA_ROOTOWNER)))
{
SetActiveWindow(owner_);
@@ -179,10 +176,15 @@ public:
static INT_PTR run(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
{
FilesModalDialog dialog(instance,resource,owner,procedure,argument);
if(!dialog.window()) return -1;
dialog.show();
return dialog.runModal();
}
INT_PTR runModal()
{
if(!window_) return -1;
show();
MSG message{};
while(!dialog.finished_ && IsWindow(dialog.window()))
while(!finished_ && IsWindow(window_))
{
const auto status=GetMessageW(&message,nullptr,0,0);
if(status<=0)
@@ -190,11 +192,11 @@ public:
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
break;
}
if(handleMessage(dialog.window(),message)) continue;
if(handleMessage(window_,message)) continue;
TranslateMessage(&message);
DispatchMessageW(&message);
}
return dialog.result_;
return result_;
}
private:
@@ -207,7 +209,23 @@ private:
DLGPROC procedure_;
LPARAM argument_;
INT_PTR result_=IDCANCEL;
bool entered_{},finished_{};
bool entered_{},finished_{},watchOutsideClicks_;
static void refreshMouseHook()
{
const auto *active=activeFilesDialog?
reinterpret_cast<const FilesModalDialog*>(GetPropW(activeFilesDialog,stateProperty_)):nullptr;
if(active && active->watchOutsideClicks_)
{
if(!filesDialogMouseHook)
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
}
else if(filesDialogMouseHook)
{
UnhookWindowsHookEx(filesDialogMouseHook);
filesDialogMouseHook=nullptr;
}
}
void captureLayout()
{
@@ -260,7 +278,7 @@ private:
void fitWidth(HWND window,const RECT &owner,bool initial=false)
{
RECT bounds{};
if(!GetWindowRect(window,&bounds)) return;
if(IsZoomed(window) || !GetWindowRect(window,&bounds)) return;
const int width=std::clamp(static_cast<int>(owner.right-owner.left)-2*ownerMargin(),
minimumWidth_,std::max(minimumWidth_,preferredWidth_));
const int height=bounds.bottom-bounds.top;
+202
View File
@@ -0,0 +1,202 @@
constexpr wchar_t operationPipePrefix[]=L"\\\\.\\pipe\\KSwitcher.Files.Operation.";
constexpr DWORD operationMessageLimit=256*1024;
void writeElevationMessage(HANDLE pipe,const Json &message)
{
const auto bytes=message.dump();
requireFileOperation(bytes.size()<=operationMessageLimit,ERROR_BUFFER_OVERFLOW);
DWORD written{};
checkFileOperation(WriteFile(pipe,bytes.data(),static_cast<DWORD>(bytes.size()),&written,nullptr));
requireFileOperation(written==bytes.size(),ERROR_WRITE_FAULT);
}
Json readElevationMessage(HANDLE pipe)
{
std::array<char,operationMessageLimit> bytes;
DWORD read{};
checkFileOperation(ReadFile(pipe,bytes.data(),operationMessageLimit,&read,nullptr));
return Json::parse(bytes.data(),bytes.data()+read);
}
bool localElevationPath(const fs::path &path)
{
const auto root=path.root_name().native();
return path.is_absolute() && root.size()==2 && root[1]==L':' &&
path.native().find(L'\0')==std::wstring::npos && path.has_relative_path() &&
GetDriveTypeW(path.root_path().c_str())!=DRIVE_REMOTE;
}
bool allowedElevationRequest(const Json &request)
{
const auto action=request.at("action").get<std::string>();
if(action!="copy" && action!="move" && action!="mkdir" && action!="mkdir-link" &&
action!="remove" && action!="recycle" && action!="rmdir" && action!="stat" &&
action!="canonical" && action!="list") return false;
if(!localElevationPath(filePath(request.at("path")))) return false;
if(action=="copy" || action=="move" || action=="mkdir-link")
return localElevationPath(filePath(request.at("target")));
return true;
}
DWORD serveElevatedFileOperations(const std::wstring &parent,const std::wstring &pipeName)
{
try
{
if(!IsUserAnAdmin() || !pipeName.starts_with(operationPipePrefix)) return ERROR_ACCESS_DENIED;
DWORD expected{};
for(const auto ch:parent)
{
if(ch<L'0' || ch>L'9' || expected>(MAXDWORD-(ch-L'0'))/10) return ERROR_INVALID_PARAMETER;
expected=expected*10+(ch-L'0');
}
Handle pipe{CreateFileW(pipeName.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr)};
checkFileOperation(pipe.value!=INVALID_HANDLE_VALUE);
ULONG server{};
checkFileOperation(GetNamedPipeServerProcessId(pipe.value,&server));
requireFileOperation(server==expected,ERROR_ACCESS_DENIED);
DWORD mode=PIPE_READMODE_MESSAGE;
checkFileOperation(SetNamedPipeHandleState(pipe.value,&mode,nullptr,nullptr));
FilesConnection listing;
bool more=false;
while(true)
{
const auto request=readElevationMessage(pipe.value);
Json reply;
try
{
const auto action=request.at("action").get<std::string>();
if(action=="listNext" || action=="list")
{
requireFileOperation(action=="listNext"?more:allowedElevationRequest(request),ERROR_ACCESS_DENIED);
more=false;
reply=listing.call(request);
more=reply.value("more",false);
}
else
{
requireFileOperation(allowedElevationRequest(request),ERROR_ACCESS_DENIED);
FilesConnection local;
ULONGLONG lastUpdate{};
reply=local.call(request,[&](uint64_t done,uint64_t total)
{
const auto now=GetTickCount64();
if(lastUpdate && now-lastUpdate<100 && done!=total) return true;
lastUpdate=now;
writeElevationMessage(pipe.value,{{"progress",{done,total}}});
return readElevationMessage(pipe.value).at("continue").get<bool>();
});
}
}
catch(const std::system_error &error) {reply={{"error",error.code().value()}};}
catch(const std::exception &) {reply={{"error",ERROR_INVALID_DATA}};}
writeElevationMessage(pipe.value,reply);
}
}
catch(const std::system_error &error)
{
const auto code=error.code().value();
return code==ERROR_BROKEN_PIPE || code==ERROR_NO_DATA?ERROR_SUCCESS:static_cast<DWORD>(code);
}
catch(const std::exception &) {return ERROR_INVALID_DATA;}
}
class FileOperationElevation
{
HWND owner_;
FileOperationUi *ui_;
std::atomic_bool &canceled_;
ElevatedHelper helper_;
bool connected_{};
DWORD connect()
{
const auto deadline=GetTickCount64()+10000;
while(!canceled_ && GetTickCount64()<deadline)
{
if(ConnectNamedPipe(helper_.pipe.value,nullptr) || GetLastError()==ERROR_PIPE_CONNECTED)
{
ULONG client{};
if(!GetNamedPipeClientProcessId(helper_.pipe.value,&client)) return GetLastError();
if(client!=GetProcessId(helper_.process.value)) return ERROR_ACCESS_DENIED;
DWORD mode=PIPE_READMODE_MESSAGE;
if(!SetNamedPipeHandleState(helper_.pipe.value,&mode,nullptr,nullptr)) return GetLastError();
connected_=true;
return ERROR_SUCCESS;
}
if(WaitForSingleObject(helper_.process.value,20)==WAIT_OBJECT_0)
{
DWORD result{};
if(!GetExitCodeProcess(helper_.process.value,&result)) return GetLastError();
return result?result:ERROR_PIPE_NOT_CONNECTED;
}
}
return canceled_?ERROR_CANCELLED:ERROR_TIMEOUT;
}
DWORD requestConsent(const Json &request)
{
if(canceled_) return ERROR_CANCELLED;
auto paths=filePath(request.at("path")).wstring();
if(request.contains("target")) paths+=L"\r\n"+filePath(request.at("target")).wstring();
const auto question=L"Windows denied access to the following path:\r\n"+paths+
L"\r\n\r\nRetry with administrator rights for the current operation?";
if(showFilesNotice(owner_,question.c_str(),L"Access denied",{.confirm=true})!=IDYES)
return ERROR_CANCELLED;
const auto error=launchElevatedHelper(owner_,operationPipePrefix,L"--elevated-file-operation",
std::to_wstring(GetCurrentProcessId()),helper_);
SetForegroundWindow(owner_);
return error;
}
Json send(const Json &request,const ks::lan::FileProgress &progress={})
{
if(canceled_) return {{"error",ERROR_CANCELLED}};
writeElevationMessage(helper_.pipe.value,request);
for(;;)
{
auto message=readElevationMessage(helper_.pipe.value);
if(!message.contains("progress")) return message;
const auto &value=message.at("progress");
writeElevationMessage(helper_.pipe.value,{{"continue",!canceled_ &&
(!progress || progress(value.at(0).get<uint64_t>(),value.at(1).get<uint64_t>()))}});
}
}
public:
FileOperationElevation(HWND owner,std::atomic_bool &canceled,FileOperationUi *ui=nullptr):
owner_(owner),ui_(ui),canceled_(canceled){}
Json retry(const Json &request,Json reply,const ks::lan::FileProgress &progress={})
{
const auto failure=reply.at("error").get<DWORD>();
if((failure!=ERROR_ACCESS_DENIED && failure!=ERROR_PRIVILEGE_NOT_HELD && failure!=ERROR_ELEVATION_REQUIRED) ||
IsUserAnAdmin() || !allowedElevationRequest(request))
return reply;
if(!connected_)
{
auto error=ui_?ui_->invoke([&]{return requestConsent(request);}):requestConsent(request);
if(error==ERROR_SUCCESS) error=connect();
if(error==ERROR_CANCELLED) canceled_=true;
if(error!=ERROR_SUCCESS) return {{"error",error}};
}
return send(request,progress);
}
Json call(FilesConnection &local,const Json &request,const ks::lan::FileProgress &progress={})
{
return retry(request,local.call(request,progress),progress);
}
void list(FilesConnection &local,const fs::path &path,const FileVisitor &visit)
{
const auto request=fileRequest("list",path);
auto reply=local.call(request);
const bool elevated=reply.at("error")==ERROR_ACCESS_DENIED;
if(elevated) reply=retry(request,std::move(reply));
listFilePages(std::move(reply),path,visit,[&]{
const Json next{{"action","listNext"}};
return elevated?send(next):local.call(next);
});
}
};
+23 -7
View File
@@ -30,13 +30,20 @@ struct CopyHost
{
std::optional<FilesConnection> files;
std::optional<FtpSession> ftp;
FileOperationElevation *elevation{};
fs::path listedDirectory;
FileEntries listedEntries;
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile)
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile,FileOperationElevation *admin=nullptr)
{
if(profile) ftp.emplace(*profile);
else files.emplace(peer);
if(!peer && !profile) elevation=admin;
}
Json request(const Json &message,const ks::lan::FileProgress &progress={})
{
return elevation?elevation->call(*files,message,progress):files->call(message,progress);
}
const FileEntries &ftpListing(const fs::path &path,const std::atomic_bool &canceled)
@@ -51,19 +58,28 @@ struct CopyHost
std::optional<FileInfo> stat(const fs::path &path,const std::atomic_bool &canceled)
{
return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(*files,path);
return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path)));
}
FileEntries children(const fs::path &path,const std::atomic_bool &canceled)
{
return ftp?ftpListing(path,canceled):childrenOf(*files,path);
if(ftp) return ftpListing(path,canceled);
if(!elevation) return childrenOf(*files,path);
FileEntries entries;
elevation->list(*files,path,[&](const fs::path &child,const FileInfo &info)
{
if(canceled) return false;
entries.emplace_back(child,info);
return true;
});
return entries;
}
void makeDirectory(const fs::path &path)
{
if(!ftp)
{
checkFileReply(files->call(fileRequest("mkdir",path)));
checkFileReply(request(fileRequest("mkdir",path)));
return;
}
ftp->setDirectory(path.parent_path());
@@ -81,9 +97,9 @@ struct CopyHost
FtpRemoveDirectoryA(ftp->handle(),name.c_str()):FtpDeleteFileA(ftp->handle(),name.c_str()));
return;
}
auto request=fileRequest(permanent?"remove":"recycle",path);
request["readOnly"]=readOnly;
checkFileReply(files->call(request));
auto message=fileRequest(permanent?"remove":"recycle",path);
message["readOnly"]=readOnly;
checkFileReply(request(message));
}
};
+239 -66
View File
@@ -36,6 +36,7 @@
#include "lan_files.h"
#include "lan_wake.h"
#include "platform.h"
#include "../resources/resource.h"
namespace
{
@@ -52,27 +53,35 @@ FileInfo fileInfo(const Json &row)
{
return {row.at("attributes"),row.at("size"),row.at("modified")};
}
std::optional<FileInfo> statFile(FilesConnection &host,const fs::path &path)
std::optional<FileInfo> statFile(const Json &reply)
{
const auto reply=host.call(fileRequest("stat",path));
const auto error=reply.at("error").get<DWORD>();
if(error==ERROR_FILE_NOT_FOUND || error==ERROR_PATH_NOT_FOUND) return {};
checkFileReply(reply);
return fileInfo(reply);
}
std::optional<FileInfo> statFile(FilesConnection &host,const fs::path &path)
{
return statFile(host.call(fileRequest("stat",path)));
}
using FileVisitor=std::function<bool(const fs::path &,const FileInfo &)>;
bool listFiles(FilesConnection &host,const fs::path &directory,const FileVisitor &visit)
template<class NextPage>
bool listFilePages(Json page,const fs::path &directory,const FileVisitor &visit,NextPage next)
{
auto page=host.call(fileRequest("list",directory));
for(;;)
{
checkFileReply(page);
for(const auto &row:page.at("entries"))
if(!visit(directory/filePath(row.at("name")),fileInfo(row))) return false;
if(!page.at("more").get<bool>()) return true;
page=host.call({{"action","listNext"}});
page=next();
}
}
bool listFiles(FilesConnection &host,const fs::path &directory,const FileVisitor &visit)
{
return listFilePages(host.call(fileRequest("list",directory)),directory,visit,
[&]{return host.call({{"action","listNext"}});});
}
std::wstring fileError(const std::system_error &error)
{
wchar_t *message{};
@@ -182,23 +191,24 @@ DWORD listElevatedFolder(const fs::path &directory, const std::wstring &pipeName
return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error;
}
struct ElevatedFolderListing
struct ElevatedHelper
{
Handle pipe{}, process{};
};
DWORD launchElevatedFolder(HWND owner,const fs::path &directory,ElevatedFolderListing &session)
DWORD launchElevatedHelper(HWND owner,std::wstring_view prefix,const std::wstring &command,
const std::wstring &arguments,ElevatedHelper &session)
{
GUID id{};
wchar_t token[40]{}, executable[32768]{};
auto length=GetModuleFileNameW(nullptr,executable,static_cast<DWORD>(std::size(executable)));
if(!length || length>=std::size(executable) || FAILED(CoCreateGuid(&id)) ||
!StringFromGUID2(id,token,static_cast<int>(std::size(token)))) return ERROR_GEN_FAILURE;
auto name=std::wstring(folderPipePrefix)+token;
auto name=std::wstring(prefix)+token;
session.pipe.value=CreateNamedPipeW(name.c_str(),PIPE_ACCESS_DUPLEX|FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_NOWAIT|PIPE_REJECT_REMOTE_CLIENTS,1,0,4096,0,nullptr);
if(session.pipe.value==INVALID_HANDLE_VALUE) return GetLastError();
auto parameters=L"--list-folder \""+(directory/L".").wstring()+L"\" \""+name+L"\"";
auto parameters=command+L" "+arguments+L" \""+name+L"\"";
SHELLEXECUTEINFOW launch{};
launch.cbSize=sizeof(launch);
launch.fMask=SEE_MASK_NOCLOSEPROCESS|SEE_MASK_NOASYNC;
@@ -212,8 +222,13 @@ DWORD launchElevatedFolder(HWND owner,const fs::path &directory,ElevatedFolderLi
return ERROR_SUCCESS;
}
DWORD launchElevatedFolder(HWND owner,const fs::path &directory,ElevatedHelper &session)
{
return launchElevatedHelper(owner,folderPipePrefix,L"--list-folder",
L"\""+(directory/L".").wstring()+L"\"",session);
}
DWORD readElevatedFolder(const ElevatedFolderListing &session,const fs::path &directory,
DWORD readElevatedFolder(const ElevatedHelper &session,const fs::path &directory,
std::vector<fs::path> &folders,std::vector<fs::path> &files,
std::map<fs::path,FolderEntryMetadata> &metadata,
std::atomic_size_t &entriesRead,std::stop_token stop)
@@ -358,7 +373,7 @@ struct Panel
std::optional<FilesPeer> peer;
bool offerElevation{};
uint64_t statusRevision{};
std::shared_ptr<ElevatedFolderListing> elevated;
std::shared_ptr<ElevatedHelper> elevated;
std::optional<FtpProfile> ftp;
};
struct ScanResult
@@ -382,6 +397,7 @@ struct Panel
std::vector<std::wstring> sizes;
std::vector<bool> dimmed;
std::vector<bool> marked;
HWND selectionSummary{};
FolderSizes folderSizes;
std::shared_ptr<FolderSizeJob> folderSizeJob;
std::set<fs::path> folderSizeWaiting;
@@ -425,7 +441,12 @@ HWND terminalInput{},terminalOutput{},terminalPrompt{};
constexpr UINT_PTR terminalTimer=2;
constexpr UINT_PTR directoryWatchTimer=4;
bool terminalVisible{};
std::deque<int> terminalCommandPanels;
struct TerminalCommandContext
{
int panel=-1;
fs::path directory;
};
std::deque<TerminalCommandContext> terminalCommands;
std::wstring terminalDirectory;
int terminalRows{};
struct CommandEntry { std::wstring date, command; };
@@ -533,6 +554,7 @@ struct FilesNoticeOptions
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
void openMenu(HWND window, int index);
void showFileDetails(const Panel &panel);
void updateSelectionSummary(const Panel &panel);
void editOptions(HWND owner);
void showFolderShortcuts(Panel &panel,int digit);
void layout(HWND window,bool activeOnly=false);
@@ -678,6 +700,7 @@ bool applyFont(HWND owner, LOGFONTW font, int points)
for(auto &panel:panels)
{
if(panel.path) SendMessageW(panel.path,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
if(panel.selectionSummary) SendMessageW(panel.selectionSummary,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
if(panel.list) SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight);
}
if(picker) SendMessageW(picker,LB_SETITEMHEIGHT,0,textHeight);
@@ -1043,20 +1066,44 @@ void swapPanels(HWND window)
// Move the controls with their contents to retain the cursor and scroll position.
std::swap(panels[0],panels[1]);
active=1-active;
for(auto &panel:terminalCommandPanels)
if(panel>=0) panel=1-panel;
for(auto &command:terminalCommands)
if(command.panel>=0) command.panel=1-command.panel;
for(int i=0;i<2;++i)
{
const auto &panel=panels[i];
SetWindowLongPtrW(panel.list,GWLP_ID,102+i);
SetWindowLongPtrW(panel.heading,GWLP_ID,140+i);
SetWindowLongPtrW(panel.path,GWLP_ID,142+i);
SetWindowLongPtrW(panel.selectionSummary,GWLP_ID,154+i);
savePreference(panelModeKeys[i],panel.wide);
}
notifyFilesPreferences(window);
layout(window);
}
bool hasSelectionSummary()
{
return GetWindowTextLengthW(panels[0].selectionSummary) || GetWindowTextLengthW(panels[1].selectionSummary);
}
int clampPanelDivider(int position,int width)
{
return std::clamp(position,120,std::max(120,width-120));
}
int panelDivider(int width)
{
return clampPanelDivider(split?split:width/2,width);
}
void setPanelDivider(HWND window,int width,int position)
{
const auto next=clampPanelDivider(position,width);
if(next==panelDivider(width)) return;
split=next;
layout(window);
}
void layout(HWND window,bool activeOnly)
{
RECT rect{};
@@ -1064,13 +1111,14 @@ void layout(HWND window,bool activeOnly)
int width = rect.right, height = rect.bottom;
const int inputTop=height-2*textHeight;
const int terminalBottom=std::max(4,inputTop);
const int detailsHeight=terminalVisible?0:textHeight+12;
const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0;
const int detailsHeight=terminalVisible?0:textHeight+12+summaryHeight;
const int terminalTop=terminalVisible?4:std::max(4,terminalBottom-
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/textHeight-4))*textHeight);
const int panelBottom=terminalTop-detailsHeight;
const bool showOutput=terminalTop<terminalBottom;
traceTerminal("layout",terminalRows,terminalTop,terminalBottom,showOutput,terminalVisible);
int middle = std::clamp(split ? split : width / 2, 120, std::max(120, width - 120));
const int middle=panelDivider(width);
auto place=[](HWND control, int x, int y, int width, int height)
{
if(control) SetWindowPos(control,nullptr,x,y,width,height,
@@ -1089,6 +1137,8 @@ void layout(HWND window,bool activeOnly)
ShowWindow(panels[i].heading,!terminalVisible && panels[i].wide?SW_SHOWNA:SW_HIDE);
place(panels[i].list, x + 5, textHeight+10+headingHeight,listWidth,
std::max(0, panelBottom-textHeight-10-headingHeight));
place(panels[i].selectionSummary,x+8,panelBottom+4,std::max(0,end-x-16),summaryHeight);
ShowWindow(panels[i].selectionSummary,summaryHeight?SW_SHOWNA:SW_HIDE);
}
place(menuBar,0,0,width,textHeight+4);
const int menuEdges[]{0,7,15,27,38,46};
@@ -1097,7 +1147,7 @@ void layout(HWND window,bool activeOnly)
}
const int detailsLeft=active?middle+2:0;
const int detailsRight=active?width:middle-2;
place(status,detailsLeft+8,panelBottom+4,std::max(0,detailsRight-detailsLeft-16),textHeight);
place(status,detailsLeft+8,panelBottom+4+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
const auto &current=panels[active];
const auto prompt=panelLocation(current)+L">";
SetWindowTextW(terminalPrompt,prompt.c_str());
@@ -1114,7 +1164,7 @@ void layout(HWND window,bool activeOnly)
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),textHeight);
if(activeOnly)
{
const RECT details{0,panelBottom+4,width,panelBottom+4+textHeight};
const RECT details{0,panelBottom+4+summaryHeight,width,panelBottom+4+summaryHeight+textHeight};
const RECT commandLine{0,inputTop,width,inputTop+textHeight};
if(!terminalVisible) RedrawWindow(window,&details,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
RedrawWindow(window,&commandLine,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
@@ -1301,7 +1351,7 @@ std::optional<CompletionQuery> currentCompletionQuery()
if(!first || first!=last) return {};
std::wstring directory;
if(!panels[active].peer && !panels[active].ftp)
directory=terminal.alive() && !terminalDirectory.empty()?terminalDirectory:panels[active].directory.native();
directory=panels[active].directory.native();
return CompletionQuery{std::move(line),std::move(directory),first};
}
@@ -1560,6 +1610,7 @@ void refreshPanel(Panel &panel)
{
cancelFolderSizes(panel);
panel.folderSizes.clear();
updateSelectionSummary(panel);
open(panel,panel.directory,false);
}
@@ -1628,14 +1679,19 @@ bool ensureTerminalView(HWND owner)
else if(message.starts_with(L"directory:"))
{
const auto directory=message.substr(10);
if(!terminalCommandPanels.empty())
if(!terminalCommands.empty())
{
const int panel=terminalCommandPanels.front();
terminalCommandPanels.pop_front();
std::error_code error;
if(panel>=0 && !panels[panel].peer && directory!=terminalDirectory &&
!directory.empty() && fs::is_directory(directory,error))
open(panels[panel],directory,false);
const auto command=std::move(terminalCommands.front());
terminalCommands.pop_front();
if(command.panel>=0 && !directory.empty() && directory!=command.directory.native())
{
auto &panel=panels[command.panel];
std::error_code error;
if(!panel.peer && !panel.ftp && panel.directory==command.directory &&
(!panel.scanRequest || panel.scanRequest->directory==command.directory) &&
fs::is_directory(directory,error))
open(panel,directory,false);
}
}
terminalDirectory=directory;
}
@@ -1687,8 +1743,8 @@ bool startTerminal(HWND owner,const fs::path &directory)
if(!ensureTerminalView(owner)) return false;
if(terminal.start(directory.c_str(),terminalSize))
{
terminalCommandPanels={-1};
terminalDirectory.clear();
terminalCommands={{}};
terminalDirectory=directory.native();
return true;
}
setStatus(L"Could not start PowerShell.");
@@ -1789,12 +1845,21 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
return true;
}
if(!startTerminal(owner,panel.directory)) return false;
if(!terminal.write(value+L"\r"))
// Use the directory displayed by the panel at submission time. A queued
// command may change location before PowerShell gets to this input.
const bool hasCommand=value.find_first_not_of(L" \t\r\n")!=value.npos;
std::wstring input;
if(hasCommand && (terminalDirectory!=panel.directory.native() ||
std::any_of(terminalCommands.begin(),terminalCommands.end(),
[](const auto &command){ return command.panel>=0; })))
input=L"try { Microsoft.PowerShell.Management\\Set-Location -LiteralPath "+
powerShellPath(panel.directory)+L" -ErrorAction Stop } catch { Write-Error $_; return }; ";
if(!terminal.write(input+value+L"\r"))
{
setStatus(L"Could not send PowerShell input.");
return false;
}
terminalCommandPanels.push_back(static_cast<int>(&panel-panels));
terminalCommands.push_back({hasCommand?static_cast<int>(&panel-panels):-1,panel.directory});
return true;
}
@@ -1885,6 +1950,52 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
return DefSubclassProc(input,message,wp,lp);
}
void updateSelectionSummary(const Panel &panel)
{
const bool hadSummary=hasSelectionSummary();
size_t marked=0,unmeasured=0;
uint64_t total=0;
bool partial=false;
if(!ftpProfileList(panel))
{
for(size_t row=0;row<panel.marked.size();++row)
{
if(!panel.marked[row] || panel.sizes[row]==L"Up") continue;
++marked;
uint64_t bytes;
if(panel.sizes[row]==L"Folder")
{
const auto measured=panel.folderSizes.find(panel.rows[row]);
if(measured==panel.folderSizes.end())
{
++unmeasured;
continue;
}
bytes=measured->second.bytes;
partial|=measured->second.partial;
}
else bytes=std::stoull(panel.sizes[row]);
if(bytes>UINT64_MAX-total)
{
total=UINT64_MAX;
partial=true;
}
else total+=bytes;
}
}
std::wstring summary;
if(marked)
{
summary=L"Selected: ";
if(partial || unmeasured) summary+=L"≥ ";
summary+=formatSize(total)+L" · "+std::to_wstring(marked)+(marked==1?L" item":L" items");
if(unmeasured) summary+=L" · "+std::to_wstring(unmeasured)+L" to measure";
if(partial) summary+=L" · partial";
}
SetWindowTextW(panel.selectionSummary,summary.c_str());
if(hadSummary!=hasSelectionSummary()) layout(GetParent(panel.list));
}
void showFileDetails(const Panel &panel)
{
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
@@ -2096,7 +2207,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
if(rememberElevationApproval || showFilesNotice(owner,question.c_str(),
L"KSwitcher Files",{.confirm=true,.remember=&remember})==IDYES)
{
auto elevated=std::make_shared<ElevatedFolderListing>();
auto elevated=std::make_shared<ElevatedHelper>();
const auto result=launchElevatedFolder(owner,directory,*elevated);
SetForegroundWindow(owner);
SetFocus(panel.list);
@@ -2214,6 +2325,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
}
if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(panel.list,nullptr,FALSE);
updateSelectionSummary(panel);
if(partial && &panel==&panels[active])
setStatus(L"Partial: "+std::to_wstring(folders.size()+files.size()));
else if(!partial && error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND)
@@ -2478,10 +2590,12 @@ void collectFolderSizes(Panel &panel)
invalidateFolderSizeRow(panel,path);
}
if(finished) cancelFolderSizes(panel);
if(!completed.empty()) updateSelectionSummary(panel);
if((finished || !completed.empty()) && &panel==&panels[active]) showFileDetails(panel);
}
void openSelectedText(const Panel &panel, bool edit, bool external);
void compareSelectedFiles(HWND owner);
INT_PTR confirmTextSave(HWND owner,bool draft);
bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format);
INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption);
@@ -2615,6 +2729,7 @@ void selectDrive()
else if(menuIndex==2 && row==3) showFolderShortcuts(panels[active],-1);
else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true);
else if(menuIndex==2 && (row==6 || row==7)) runActivePeerAction(owner,row==7);
else if(menuIndex==2 && row==8) compareSelectedFiles(owner);
else
{
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
@@ -3330,6 +3445,7 @@ void prepareCopyDialog(HWND dialog)
return TRUE;
},0);
const auto style=GetWindowLongPtrW(dialog,GWL_STYLE);
if(style&WS_MAXIMIZEBOX) return;
SetWindowLongPtrW(dialog,GWL_STYLE,style&~(WS_CAPTION|WS_SYSMENU|WS_THICKFRAME));
const auto extended=GetWindowLongPtrW(dialog,GWL_EXSTYLE);
SetWindowLongPtrW(dialog,GWL_EXSTYLE,extended&~WS_EX_DLGMODALFRAME);
@@ -4755,7 +4871,9 @@ FileEntries childrenOf(FilesConnection &host,const fs::path &path)
return children;
}
#include "files_elevation.inl"
#include "files_ftp_copy.inl"
#include "files_compare.inl"
ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile)
{
@@ -4843,7 +4961,7 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path
request["append"]=append;
request["size"]=info.size;
request["modified"]=info.modified;
checkFileReply(hosts.source.files->call(request,update));
checkFileReply(hosts.source.request(request,update));
return;
}
ks::lan::streamFile(*hosts.source.files,*hosts.target.files,hosts.sourceId,from,to,
@@ -4868,7 +4986,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
auto request=fileRequest("move",from);
request["target"]=ks::utf8(target.native());
request["replace"]=replace;
const auto reply=hosts.source.files->call(request);
const auto reply=hosts.source.request(request);
if(reply.at("error")==ERROR_NOT_SAME_DEVICE) return false;
checkFileReply(reply);
return true;
@@ -4897,7 +5015,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
{
progress.localLockSource=hosts.sourceLocal?from:fs::path{};
progress.localLockTarget.clear();
checkFileReply(hosts.source.files->call(fileRequest("rmdir",from)));
checkFileReply(hosts.source.request(fileRequest("rmdir",from)));
}
return result;
}
@@ -4916,7 +5034,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
auto remove=fileRequest("remove",from);
remove["size"]=incoming->size;
remove["modified"]=incoming->modified;
checkFileReply(hosts.source.files->call(remove));
checkFileReply(hosts.source.request(remove));
}
}
progress.bytes+=fileSize;
@@ -5055,7 +5173,9 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
try
{
progress.ui.run(progress.window,progress.canceled,[&] {
CopyHost sourceHost(request.sourcePeer,sourceFtp);
FileOperationElevation elevation(progress.window,progress.canceled,&progress.ui);
auto *admin=!ftp && !request.sourcePeer && !targetPeer?&elevation:nullptr;
CopyHost sourceHost(request.sourcePeer,sourceFtp,admin);
if(ftpRename)
{
const auto &path=request.sources.front();
@@ -5076,7 +5196,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
return;
}
std::unique_ptr<CopyHost> otherHost;
if(!sameHost) otherHost=std::make_unique<CopyHost>(targetPeer,destinationFtp);
if(!sameHost) otherHost=std::make_unique<CopyHost>(targetPeer,destinationFtp,admin);
const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost,
request.sourcePeer?request.sourcePeer->id:"local",!request.sourcePeer && !sourceFtp,
!targetPeer && !destinationFtp};
@@ -5091,7 +5211,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
{
const auto canonical=[&](const fs::path &name)
{
const auto reply=sourceHost.files->call(fileRequest("canonical",name));
const auto reply=sourceHost.request(fileRequest("canonical",name));
checkFileReply(reply);
return filePath(reply.at("path"));
};
@@ -5140,6 +5260,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
progressDialog.close();
activeCopy=nullptr;
copyInProgress=false;
updateSelectionSummary(source);
for(auto &panel:panels) EnableWindow(panel.list,TRUE);
for(const auto command:commands) EnableWindow(command,TRUE);
if(progress.closeOwner)
@@ -5404,7 +5525,8 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
try
{
ui.run(window,canceled,[&] {
CopyHost host(panel.peer?&*panel.peer:nullptr,ftp);
FileOperationElevation elevation(window,canceled,&ui);
CopyHost host(panel.peer?&*panel.peer:nullptr,ftp,&elevation);
const auto collect=[&](auto &&self,const fs::path &path,std::vector<fs::path> &group)->void
{
for(const auto &[child,info]:host.children(path,canceled))
@@ -5515,7 +5637,9 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
{
const auto error=probeDeleteAccess(current);
if(isSharingError(error)) throw std::system_error(error,std::system_category());
if(!ks::lan::recycleFile(window,current))
if(error==ERROR_ACCESS_DENIED)
checkFileReply(elevation.retry(fileRequest("recycle",current),{{"error",error}}));
else if(!ks::lan::recycleFile(window,current))
{
// The Shell can hide the error from an individual item in a folder.
lockPaths.insert(current);
@@ -5527,6 +5651,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
}
catch(const std::system_error &e)
{
if(canceled && e.code().value()==ERROR_CANCELLED) break;
recordFailure(e,current);
if(e.code().value()>=10000) break;
}
@@ -5714,6 +5839,8 @@ INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
fs::path current;
std::atomic_bool canceled{};
FileOperationElevation elevation(dialog,canceled);
try
{
FilesConnection host(request->peer);
@@ -5727,14 +5854,17 @@ INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
operation["target"]=ks::utf8(resolved.lexically_normal().native());
operation["kind"]=kind==1?"junction":"symlink";
}
checkFileReply(host.call(operation));
checkFileReply(request->peer?host.call(operation):elevation.call(host,operation));
request->created=current;
}
}
catch(const std::system_error &failure)
{
const auto details=current.filename().wstring()+L": "+fileError(failure);
error(details.c_str(),input);
if(!canceled)
{
const auto details=current.filename().wstring()+L": "+fileError(failure);
error(details.c_str(),input);
}
if(!request->created.empty()) FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
@@ -6034,6 +6164,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
if(panel.sizes[i]!=L"Up") panel.marked[i]=mark;
SendMessageW(window,LB_SETCURSEL,target,0);
InvalidateRect(window,nullptr,FALSE);
updateSelectionSummary(panel);
showFileDetails(panel);
return 0;
}
@@ -6139,6 +6270,7 @@ bool loadFilesPreferences(HWND window)
alignFolders=preference(L"AlignFolders",defaultAlignFolders)!=0;
statusFields=preference(L"StatusFields",defaultStatusFields)&15;
loadCommandHistoryKeys();
loadComparisonShortcut();
return true;
}
@@ -6169,17 +6301,13 @@ void openMenu(HWND window, int index)
else if(index==2)
{
rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4"};
if(panels[active].peer)
{
rows.push_back(L"Hibernate remote PC");
rows.push_back(L"Update remote KSwitcher");
}
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel()};
}
commandActions.clear();
if(index==2)
{
commandActions={0,3,-1,1,2,4,5};
commandActions={0,3,-1,1,2,4,5,8};
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
}
else
@@ -6222,7 +6350,10 @@ void openMenu(HWND window, int index)
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&anchor),2);
GetClientRect(window,&client);
const int inset=dialogFrameMetrics(GetDpiForWindow(window)).content();
const int width=std::max(1,std::min(static_cast<int>(client.right)-2*inset,26*cellWidth+16));
int columns=26;
for(const auto action:commandActions)
if(action>=0) columns=std::max(columns,static_cast<int>(rows[action].size())+3);
const int width=std::max(1,std::min(static_cast<int>(client.right)-2*inset,columns*cellWidth+16));
const int x=std::clamp(static_cast<int>(anchor.left)+inset,inset,
std::max(inset,static_cast<int>(client.right)-width-inset));
const int y=anchor.bottom+5;
@@ -6524,8 +6655,10 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
0, 0, 0, 0, window, reinterpret_cast<HMENU>(102 + static_cast<INT_PTR>(i)), instance, nullptr);
panel.heading=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW,
0,0,0,0,window,reinterpret_cast<HMENU>(140+static_cast<INT_PTR>(i)),instance,nullptr);
if (!panel.path || !panel.list || !panel.heading) return -1;
for (auto child : {panel.path, panel.list})
panel.selectionSummary=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_ENDELLIPSIS,
0,0,0,0,window,reinterpret_cast<HMENU>(154+static_cast<INT_PTR>(i)),instance,nullptr);
if (!panel.path || !panel.list || !panel.heading || !panel.selectionSummary) return -1;
for (auto child : {panel.path, panel.list, panel.selectionSummary})
SendMessageW(child, WM_SETFONT, reinterpret_cast<WPARAM>(mono), FALSE);
SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight);
wchar_t system[MAX_PATH]{};
@@ -6569,7 +6702,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
RECT rect{};
GetClientRect(window, &rect);
const int width = rect.right;
int middle = std::clamp(split ? split : width / 2, 120, std::max(120, width - 120));
const int middle=panelDivider(width);
if (point.y >= 0 && point.y < rect.bottom-2*textHeight-14 && abs(point.x - middle) <= 4)
{
SetCursor(LoadCursorW(nullptr, IDC_SIZEWE));
@@ -6593,7 +6726,12 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
break;
}
case WM_MOUSEMOVE:
if (dragging) { split = std::max(1, GET_X_LPARAM(lp)); layout(window); }
if(dragging)
{
RECT client{};
GetClientRect(window,&client);
setPanelDivider(window,client.right,GET_X_LPARAM(lp));
}
return 0;
case WM_LBUTTONUP:
if (dragging) ReleaseCapture();
@@ -7087,16 +7225,6 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
{
bool writeLog=ks::Settings{}.writeLog;
try
{
const auto settings=ks::dataDirectory()/L"settings.json";
if(std::filesystem::exists(settings))
writeLog=Json::parse(ks::readFile(settings,1024*1024)).value("writeLog",writeLog);
}
catch(const std::exception &) {}
ks::setLogFilename(L"kswitcher-files.log");
ks::setLoggingEnabled(writeLog);
int count{};
if(auto args=CommandLineToArgvW(GetCommandLineW(),&count))
{
@@ -7106,6 +7234,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
LocalFree(args);
return static_cast<int>(result);
}
if(count==4 && std::wstring_view(args[1])==L"--elevated-file-operation")
{
const auto result=serveElevatedFileOperations(args[2],args[3]);
LocalFree(args);
return static_cast<int>(result);
}
for(int i=1;i<count;++i)
if(std::wstring_view(args[i])==L"--terminal-trace" ||
std::wstring_view(args[i])==L"--terminal-output-trace")
@@ -7120,7 +7254,18 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
}
LocalFree(args);
}
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS|ICC_TREEVIEW_CLASSES|ICC_HOTKEY_CLASS};
bool writeLog=ks::Settings{}.writeLog;
try
{
const auto settings=ks::dataDirectory()/L"settings.json";
if(std::filesystem::exists(settings))
writeLog=Json::parse(ks::readFile(settings,1024*1024)).value("writeLog",writeLog);
}
catch(const std::exception &) {}
ks::setLogFilename(L"kswitcher-files.log");
ks::setLoggingEnabled(writeLog);
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS|ICC_TREEVIEW_CLASSES|
ICC_HOTKEY_CLASS|ICC_BAR_CLASSES};
InitCommonControlsEx(&controls);
loadCommandHistory();
WNDCLASSW type{};
@@ -7142,6 +7287,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
{
if(GetForegroundWindow()==window || IsChild(window,GetFocus())) restoreCommandFocus();
if(GetMessageW(&message,nullptr,0,0)<=0) break;
if(handleComparisonMessage(message)) continue;
if(message.message==WM_KEYDOWN && message.wParam==VK_TAB &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
ks::files::cycleTextWindows(GetAncestor(message.hwnd,GA_ROOT),(GetKeyState(VK_SHIFT)&0x8000)!=0))
@@ -7225,6 +7371,18 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
}
const bool panelFocused=message.hwnd==panels[0].list || message.hwnd==panels[1].list;
const bool mainInput=panelFocused || message.hwnd==terminalInput;
if(mainInput && !terminalVisible && !copyInProgress && !commandHistoryWindow &&
!FilesModalDialog::activeFor(window) && message.message==WM_KEYDOWN &&
(message.wParam==VK_LEFT || message.wParam==VK_RIGHT) &&
(GetKeyState(VK_CONTROL)&0x8000) &&
!((GetKeyState(VK_SHIFT)|GetKeyState(VK_MENU)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
{
RECT client{};
GetClientRect(window,&client);
const int direction=message.wParam==VK_LEFT?-1:1;
setPanelDivider(window,client.right,panelDivider(client.right)+direction*cellWidth);
continue;
}
if(message.message==WM_KEYDOWN && mainInput && !terminalVisible &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
!(GetKeyState(VK_LWIN)&0x8000) && !(GetKeyState(VK_RWIN)&0x8000) &&
@@ -7242,6 +7400,21 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
continue;
}
const bool filesMessage=message.hwnd==window || IsChild(window,message.hwnd);
if(filesMessage && !terminalVisible && !copyInProgress && !commandHistoryWindow &&
!FilesModalDialog::activeFor(window) && message.message==WM_KEYDOWN &&
!(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
!(GetKeyState(VK_RWIN)&0x8000) && (GetKeyState(VK_SHIFT)&0x8000) &&
MAKEWORD(message.wParam,HOTKEYF_SHIFT|((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0))==
comparisonShortcut)
{
if(!(message.lParam & (1LL<<30)))
{
hidePicker();
showMenu(false);
compareSelectedFiles(window);
}
continue;
}
if(mainInput && !terminalVisible && !copyInProgress &&
message.message==WM_KEYDOWN && message.wParam>=VK_F1 && message.wParam<=VK_F12 &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
+97 -7
View File
@@ -1,7 +1,12 @@
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372;
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions };
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",L"Viewer",L"Editor"};
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions, CompareFiles };
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",
L"Viewer",L"Editor",L"All settings",L"File comparison"};
constexpr int comparisonFontLabel=408,comparisonChooseFont=409,comparisonColorCombo=411,
comparisonChooseColor=412,comparisonColorValue=413,comparisonShortcutControl=415;
constexpr int comparisonControls[]{comparisonFontLabel,comparisonChooseFont,410,comparisonColorCombo,
comparisonChooseColor,comparisonColorValue,414,comparisonShortcutControl};
constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background",
L"Menu selection",L"Command bar",L"File cursor"};
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
@@ -89,12 +94,15 @@ struct OptionsBaseline
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
std::array<bool,2> wide{panels[0].wide,panels[1].wide};
ks::files::TextSettings text=ks::files::loadTextPreferences();
ComparisonAppearance comparison=readComparisonAppearance();
WORD compareShortcut=comparisonShortcut;
};
struct OptionsDraft
{
OptionsBaseline baseline;
ks::files::TextSettings text=baseline.text;
ComparisonAppearance comparison=baseline.comparison;
HWND filesWindow{};
LOGFONTW font=displayFont;
int points=fontPoints;
@@ -163,7 +171,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
draft.text!=base.text;
draft.text!=base.text || draft.comparison!=base.comparison ||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0)!=base.compareShortcut;
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
}
@@ -409,6 +418,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
return true;
}
void showComparisonOptions(HWND dialog,const ComparisonAppearance &appearance)
{
const auto points=appearance.points;
const auto description=std::wstring(appearance.font.lfFaceName)+L" · "+std::to_wstring(points/10)+
(points%10?L"."+std::to_wstring(points%10):L"")+L" pt";
SetDlgItemTextW(dialog,comparisonFontLabel,description.c_str());
const auto index=SendDlgItemMessageW(dialog,comparisonColorCombo,CB_GETCURSEL,0,0);
if(index<0 || index>=CompareColorCount) return;
const auto color=appearance.palette[index];
wchar_t hex[8]{};
swprintf_s(hex,L"#%02X%02X%02X",unsigned(GetRValue(color)),unsigned(GetGValue(color)),unsigned(GetBValue(color)));
SetDlgItemTextW(dialog,comparisonColorValue,hex);
}
void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
{
draft.page=page;
@@ -420,7 +443,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
{
title=optionsTitles[page];
if(markdown) title=L"Markdown";
else if(section>=0 && !textOptionsPage(page))
else if(section>=0 && !textOptionsPage(page) && page!=CompareFiles)
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";
@@ -451,6 +474,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
show(wideColumnControls,page==PanelModes && section==WideColumns);
show(statusColumnControls,page==PanelModes && section==StatusColumns);
show(appearanceControls,page==Appearance && section==Font);
show(comparisonControls,page==CompareFiles);
if(page==CompareFiles) showComparisonOptions(dialog,draft.comparison);
show(dialogFrameControls,page==Appearance && section==DialogFrame);
if(page==Appearance && section==DialogFrame)
{
@@ -524,8 +549,9 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
draft.markdownNode=nullptr;
const auto root=add(L"All settings",allOptions,-1,TVI_ROOT);
HTREEITEM first{},selected{};
for(int page=PanelModes;page<allOptions;++page)
for(int page=PanelModes;page<=CompareFiles;++page)
{
if(page==allOptions) continue;
HTREEITEM category{};
const bool wholeCategory=matches(optionsTitles[page]) || (!query.empty() && matches(L"All settings"));
const auto addSection=[&](const wchar_t *label,int section,bool aliasMatches=false)
@@ -562,6 +588,9 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
else if(page==CommandLine) addSection(L"Command history",0,
matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here") ||
matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here"));
else if(page==CompareFiles)
addSection(L"Font and colors",0,matches(L"Compare files shortcut") || std::any_of(std::begin(comparisonColorNames),
std::end(comparisonColorNames),matches));
else if(textOptionsPage(page))
{
const bool propertyMatches=matches(L"Tab width") ||
@@ -611,6 +640,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
showMarkdownOptions(dialog,draft.text.markdown);
for(const auto label:comparisonColorNames)
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_SETCURSEL,0,0);
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETRULES,HKCOMB_NONE,HOTKEYF_SHIFT);
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0);
for(const auto &option:frameOptions)
for(DWORD value=0;value<=option.maximum;++value)
@@ -701,6 +735,28 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
showOptionsPage(dialog,*draft,Appearance,Font);
updateOptionsApply(dialog,*draft);
return TRUE;
case comparisonChooseFont:
if(chooseDisplayFont(dialog,draft->comparison.font,draft->comparison.points))
{
draft->comparison.font.lfHeight=draft->comparison.font.lfWidth=0;
showComparisonOptions(dialog,draft->comparison);
updateOptionsApply(dialog,*draft);
}
return TRUE;
case comparisonColorCombo:
if(HIWORD(wp)==CBN_SELCHANGE) showComparisonOptions(dialog,draft->comparison);
return TRUE;
case comparisonChooseColor:
{
const auto index=SendDlgItemMessageW(dialog,comparisonColorCombo,CB_GETCURSEL,0,0);
if(index>=0 && index<CompareColorCount &&
choosePanelColor(dialog,draft->comparison.palette[index],draft->custom.data()))
{
showComparisonOptions(dialog,draft->comparison);
updateOptionsApply(dialog,*draft);
}
return TRUE;
}
case markdownWidth: case markdownSize: case markdownFamily:
if(HIWORD(wp)==EN_CHANGE)
{
@@ -773,6 +829,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
return TRUE;
case optionsReset:
if(draft->page==allOptions || draft->page==CompareFiles)
{
draft->comparison=ComparisonAppearance{};
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,defaultComparisonShortcut,0);
}
if(draft->page==allOptions || draft->page==CommandLine)
{
setOptionHistoryKeys(dialog,defaultHistoryKeys);
@@ -823,12 +884,22 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
updateOptionsApply(dialog,*draft);
return TRUE;
case 321: case 323:
case 321: case 323: case comparisonShortcutControl:
updateOptionsApply(dialog,*draft);
return TRUE;
case optionsApply:
case IDOK:
{
const auto compareShortcut=static_cast<WORD>(
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0));
if(!validComparisonShortcut(compareShortcut))
{
showFilesNotice(dialog,L"Choose Shift or Ctrl+Shift with a function key. Shift+F4 and Shift+F8 are reserved.",
optionsTitles[CompareFiles]);
if(IsWindowVisible(GetDlgItem(dialog,comparisonShortcutControl)))
SetFocus(GetDlgItem(dialog,comparisonShortcutControl));
return TRUE;
}
if(draft->markdownError)
{
if(!draft->markdownNode) SetDlgItemTextW(dialog,optionsSearch,L"");
@@ -856,6 +927,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
const auto &base=draft->baseline;
const auto storedComparison=readComparisonAppearance();
const bool comparisonChanged=draft->comparison!=base.comparison;
if(comparisonChanged && storedComparison!=base.comparison && storedComparison!=draft->comparison)
{
showFilesNotice(dialog,L"Comparison settings changed in another window. Reopen Options before editing them again.",
optionsTitles[CompareFiles]);
return TRUE;
}
const bool textChanged=draft->text!=base.text;
auto textSettings=ks::files::loadTextPreferences();
if(draft->text.markdown!=base.text.markdown)
@@ -918,11 +997,19 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
showFilesNotice(dialog,L"Could not apply the selected font.",optionsTitles[Appearance]);
return TRUE;
}
if(comparisonChanged && !saveComparisonAppearance(draft->comparison))
{
if(fontChanged) applyFont(owner,base.font,base.points);
if(stylesChanged) saveFileStyles(fileStyles);
showFilesNotice(dialog,L"Could not save comparison settings.",optionsTitles[CompareFiles]);
return TRUE;
}
if(textChanged)
{
try { ks::files::saveTextPreferences(textSettings); }
catch(const std::exception &error)
{
if(comparisonChanged) saveComparisonAppearance(storedComparison);
if(fontChanged) applyFont(owner,base.font,base.points);
if(stylesChanged) saveFileStyles(fileStyles);
const auto message=L"Could not save text settings. "+ks::wide(error.what());
@@ -938,6 +1025,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto inputKeys=optionHistoryKeys(dialog);
saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]);
saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]);
saveChanged(comparisonShortcutKey,compareShortcut,base.compareShortcut);
saveChanged(ks::lan::remoteTerminalPreference,checked(optionsRemoteTerminal),base.remoteTerminal);
saveChanged(ks::lan::remoteHibernatePreference,checked(optionsRemoteHibernate),base.remoteHibernate);
saveChanged(ks::lan::remoteUpdatePreference,checked(optionsRemoteUpdate),base.remoteUpdate);
@@ -972,6 +1060,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;
draft->comparison=draft->baseline.comparison;
showMarkdownOptions(dialog,draft->text.markdown);
populateTextSchemes(dialog,draft->text);
draft->font=displayFont;
@@ -987,6 +1076,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,274,panels[1].wide);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
@@ -1010,7 +1100,7 @@ void runOptions(HWND owner,int page)
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
const DWORD initial=static_cast<DWORD>((page<<8)|1);
const auto saved=preference(optionsLocationKey,initial);
draft.location=(saved>>8)<=allOptions?saved:initial;
draft.location=(saved>>8)<=CompareFiles?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());
+1
View File
@@ -42,6 +42,7 @@ public:
bool save();
bool saveNew(std::filesystem::path path, TextSaveFormat format);
const wchar_t *encodingName() const;
TextEncoding encoding() const { return encoding_; }
private:
struct Change { uint64_t offset; size_t size; };
+189 -17
View File
@@ -806,7 +806,7 @@ private:
bool uploadPending{};
bool switchAfterSave{};
FilesTerminalView preview;
bool previewWanted{}, previewVisible{};
bool previewWanted{}, previewVisible{}, previewRetried{};
ULONGLONG previewDeadline{};
ULONGLONG nextFileCheck{};
struct FileStamp
@@ -816,6 +816,16 @@ private:
bool operator==(const FileStamp &) const = default;
};
std::optional<FileStamp> previewStamp;
struct MarkdownTask
{
uint64_t revision;
size_t line,column;
bool checked;
};
std::string previewText;
uint64_t previewRevision{};
std::optional<MarkdownTask> pendingTask;
std::optional<size_t> taskOffset;
std::string previewFragment;
struct PreviewLocation
{
@@ -858,6 +868,7 @@ private:
static constexpr UINT openPreviewLink = WM_APP + 3;
static constexpr UINT previewRendered = WM_APP + 4;
static constexpr UINT cycleWindow = WM_APP + 5;
static constexpr UINT savePreviewTask = WM_APP + 6;
LRESULT send(UINT message, WPARAM wparam = 0, LPARAM lparam = 0) const
{
@@ -907,11 +918,15 @@ private:
bool needsSave() const;
bool canPreview() const;
void updatePreview();
bool startPreviewBrowser();
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 startMarkdownTask();
void finishMarkdownTask();
void reportMarkdownTask(uint64_t revision,bool saved);
void cancelPreviewImages();
void previewMessage(const std::wstring &value);
void navigatePreview(PreviewLink request);
@@ -1406,6 +1421,11 @@ void TextWindow::finishSave()
{
if (!busy() || saving.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready) return;
KillTimer(window, saveTimer);
if(taskOffset)
{
finishMarkdownTask();
return;
}
send(SCI_SETREADONLY, !edit);
const auto change = std::exchange(switchAfterSave, false);
const auto reopened = saving.get();
@@ -1537,25 +1557,35 @@ void TextWindow::updateIcons(UINT dpi)
set(largeIcon,ICON_BIG,SM_CXICON,SM_CYICON);
}
void TextWindow::updateTaskbarGroup(bool closing)
}
void setFileWindowTaskbar(HWND window,int iconResource,const wchar_t *identity)
{
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");
auto icon=identity?executable()+L",-"+std::to_wstring(iconResource):std::wstring{};
auto group=identity?std::wstring(identity):std::wstring{};
IPropertyStore *properties{};
if(FAILED(SHGetPropertyStoreForWindow(window,IID_PPV_ARGS(&properties)))) return;
PROPVARIANT value{};
if(!closing)
if(identity)
{
value.vt=VT_LPWSTR;
value.pwszVal=icon.data();
}
properties->SetValue(PKEY_AppUserModel_RelaunchIconResource,value);
if(!closing) value.pwszVal=identity.data();
if(identity) value.pwszVal=group.data();
// Setting the group ID tells Explorer to refresh the taskbar button.
properties->SetValue(PKEY_AppUserModel_ID,value);
properties->Release();
}
namespace
{
void TextWindow::updateTaskbarGroup(bool closing)
{
setFileWindowTaskbar(window,edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER,closing?nullptr:
edit?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
}
bool TextWindow::canPreview() const
{
return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit;
@@ -1569,14 +1599,21 @@ void TextWindow::updatePreview()
return;
}
previewWanted=true;
previewDeadline=GetTickCount64()+8000;
previewRetried=false;
previewStamp=previewFileStamp();
nextFileCheck=GetTickCount64()+350;
cancelImages=std::make_shared<std::atomic<bool>>(false);
if(!SetTimer(window,previewTimer,50,nullptr)) { stopPreview(); return; }
if(preview.initialized()) renderPreview();
else if(!preview.create(window,[this](const auto &value){previewMessage(value);},
[this]{PostMessageW(window,previewFailed,0,0);},true,[this](UINT key)
else if(!startPreviewBrowser()) { stopPreview(); return; }
layout();
}
bool TextWindow::startPreviewBrowser()
{
previewDeadline=GetTickCount64()+8000;
return preview.create(window,[this](const auto &value){previewMessage(value);},
[this]{previewDeadline=GetTickCount64()+300;},true,[this](UINT key)
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
@@ -1599,9 +1636,7 @@ void TextWindow::updatePreview()
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0);
return true;
}))
stopPreview();
layout();
});
}
void TextWindow::stopPreview(bool refresh,bool keepBrowser)
@@ -1609,6 +1644,9 @@ void TextWindow::stopPreview(bool refresh,bool keepBrowser)
KillTimer(window,previewTimer);
previewWanted=previewVisible=false;
previewStamp.reset();
++previewRevision;
previewText.clear();
pendingTask.reset();
cancelPreviewImages();
previewLinks.clear();
if(keepBrowser && preview.initialized()) preview.post(L"{\"action\":\"clear\"}");
@@ -1661,11 +1699,12 @@ void TextWindow::renderPreview(bool keepPosition)
{
applyMarkdownPreferences(loadTextPreferences().markdown);
previewDeadline=GetTickCount64()+30000;
std::string text;
previewText.clear();
for(uint64_t index=0;index<document->pages();++index)
text+=document->readPage(index);
previewText+=document->readPage(index);
if(!remote) document->releaseReadHandle();
nlohmann::json message{{"action","render"},{"text",std::move(text)},
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
{"canSave",!remote || remote->revision.editable},
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
{"keepPosition",keepPosition}};
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
@@ -1682,7 +1721,7 @@ void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences
void TextWindow::refreshPreview()
{
if(remote || !previewVisible || navigation.valid() || GetTickCount64()<nextFileCheck) return;
if(remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
nextFileCheck=GetTickCount64()+350;
const auto stamp=previewFileStamp();
if(!stamp || stamp==previewStamp) return;
@@ -1706,6 +1745,121 @@ void TextWindow::refreshPreview()
}
}
void TextWindow::reportMarkdownTask(uint64_t revision,bool saved)
{
preview.post(wide(nlohmann::json{{"action","task-result"},{"revision",revision},{"saved",saved}}.dump()));
}
void TextWindow::startMarkdownTask()
{
const auto task=std::exchange(pendingTask,{});
if(!task) return;
if(!previewVisible || edit || busy() || navigation.valid() || task->revision!=previewRevision ||
(remote && !remote->revision.editable))
{
reportMarkdownTask(task->revision,false);
return;
}
size_t lineStart=0;
const auto reject=[&]{reportMarkdownTask(task->revision,false);};
for(size_t line=0;line<task->line;++line)
{
const auto end=previewText.find_first_of("\r\n",lineStart);
if(end==previewText.npos) { reject(); return; }
lineStart=end+1;
if(previewText[end]=='\r' && lineStart<previewText.size() && previewText[lineStart]=='\n') ++lineStart;
}
if(!task->column || task->column>=previewText.size()-lineStart) { reject(); return; }
const auto offset=lineStart+task->column;
const auto lineEnd=previewText.find_first_of("\r\n",lineStart);
if((lineEnd!=previewText.npos && offset>=lineEnd) || offset+1>=previewText.size() ||
previewText[offset-1]!='[' || previewText[offset+1]!=']' ||
(previewText[offset]!=' ' && previewText[offset]!='x' && previewText[offset]!='X'))
{
reject();
return;
}
const auto next=task->checked?'x':' ';
if((previewText[offset]!=' ')==task->checked) { reportMarkdownTask(task->revision,true); return; }
if(!SetTimer(window,saveTimer,75,nullptr)) { reject(); return; }
const auto encoding=document->encoding();
try
{
saving=std::async(std::launch::async,[this,expected=previewText,offset,next,encoding]
{
const auto path=remote?remote->cache:original;
std::filesystem::path candidate;
struct RemoveCandidate
{
std::filesystem::path &path;
~RemoveCandidate(){if(!path.empty()){std::error_code ec;std::filesystem::remove(path,ec);}}
} cleanup{candidate};
if(remote)
{
const auto stage=path.parent_path()/(path.filename()==L"content"?L"task-update":L"content");
std::filesystem::copy_file(path,stage);
candidate=stage;
}
TextDocument fresh(remote?candidate:path,true,encoding);
if(fresh.size()>TextDocument::editLimit)
throw std::runtime_error("The Markdown file grew outside KSwitcher.");
size_t start=0;
for(uint64_t index=0;index<fresh.pages();++index)
{
auto text=fresh.readPage(index);
if(std::string_view(expected).substr(start,text.size())!=text)
throw std::runtime_error("The Markdown text changed outside KSwitcher.");
const auto end=start+text.size();
if(offset>=start && offset<end)
{
text[offset-start]=next;
fresh.stage(index,text);
}
start=end;
}
if(start!=expected.size()) throw std::runtime_error("The Markdown text changed outside KSwitcher.");
fresh.save();
if(remote)
{
remote->revision=remote->source.upload(original,candidate,remote->revision);
remote->cache.swap(candidate);
}
return next=='x';
});
taskOffset=offset;
}
catch(...)
{
KillTimer(window,saveTimer);
reject();
throw;
}
}
void TextWindow::finishMarkdownTask()
{
const auto offset=*std::exchange(taskOffset,{});
const auto revision=previewRevision;
bool checked{};
try {checked=saving.get();}
catch(const std::exception &error)
{
reportMarkdownTask(revision,false);
search.style.message(window,(L"Could not save the Markdown checkbox. "+wide(error.what())).c_str());
return;
}
if(offset<previewText.size()) previewText[offset]=checked?'x':' ';
reportMarkdownTask(revision,true);
const auto encoding=document->encoding();
document=std::make_unique<TextDocument>(remote?remote->cache:original,false,encoding);
loadPage(std::min(page,document->pages()-1));
if(!remote)
{
previewStamp=previewFileStamp();
document->releaseReadHandle();
}
}
void TextWindow::previewMessage(const std::wstring &value)
{
if(!previewWanted) return;
@@ -1733,6 +1887,16 @@ void TextWindow::previewMessage(const std::wstring &value)
PostMessageW(window,previewRendered,0,0);
return;
}
if(action=="save-task")
{
if(!pendingTask && !busy())
{
pendingTask=MarkdownTask{message.at("revision"),message.at("line"),message.at("column"),
message.at("checked")};
PostMessageW(window,savePreviewTask,0,0);
}
return;
}
// Defer transitions until WebView2 returns from its event callback.
if(action=="edit" || action=="close")
{
@@ -1783,7 +1947,7 @@ void TextWindow::syncNavigation()
void TextWindow::navigatePreview(PreviewLink request)
{
if(edit || navigation.valid() || navigationHistory.empty()) return;
if(edit || busy() || pendingTask || navigation.valid() || navigationHistory.empty()) return;
if(request.newWindow)
{
if(remote)
@@ -1869,6 +2033,13 @@ void TextWindow::pollImages()
refreshPreview();
if(!previewVisible && GetTickCount64()>=previewDeadline)
{
if(!preview.initialized() && !previewRetried)
{
// The previous window's WebView2 process may still be shutting down.
previewRetried=true;
preview.close();
if(startPreviewBrowser()) return;
}
stopPreview();
return;
}
@@ -2321,6 +2492,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
}
break;
case previewFailed: self->stopPreview(); return 0;
case savePreviewTask: self->startMarkdownTask(); return 0;
case previewRendered:
if(self->previewWanted)
{
+2
View File
@@ -23,6 +23,8 @@ struct TextWindowFont
int tenthsOfPoint;
};
void setFileWindowTaskbar(HWND window,int iconResource,const wchar_t *identity);
struct FarDropDownPalette
{
COLORREF surface, text, selection;
+69 -21
View File
@@ -110,7 +110,14 @@ void lan::wakeFilesPeer(const std::string &id)
struct LanService::Impl
{
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; };
struct Peer
{
std::string name,epoch;
sockaddr_in address{};
uint64_t seen{},verified{};
bool files{};
bool present(uint64_t now)const{return verified && now-verified<lan::PeerLifetime;}
};
std::filesystem::path path;
std::string id,epoch=lan::randomHex(16),name=hostName(),status="Disabled.";
std::map<std::string,Peer> peers;
@@ -129,7 +136,7 @@ struct LanService::Impl
bool shareInput{};
std::string inputPeer;
int inputEdge=1;
std::atomic<bool> inputConnected{false},abortInput{false};
std::atomic<bool> abortInput{false};
std::atomic<uint64_t> inputEpoch{0};
std::atomic<uint64_t> inputConfiguration{0};
std::atomic<bool> layoutChanged{false};
@@ -139,6 +146,8 @@ struct LanService::Impl
std::map<std::string,uint64_t> inputReady;
std::unique_ptr<lan::InputMesh> router;
std::string inputStatus="Input sharing disabled.";
size_t inputConnectedPeers{}, inputOnlinePeers{};
bool inputWorkerStopped{};
bool inputNeedsHelp{};
HWND inputWindow{};std::atomic<bool> inputNotification{false};
explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window)
@@ -212,6 +221,7 @@ struct LanService::Impl
void start()
{
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
updateInputStatus(0,0,"Waiting for paired computers...",false);
worker=std::thread([this]{ run(); });
}
void stop()
@@ -219,17 +229,39 @@ struct LanService::Impl
if(router)router->cancel(GetTickCount64());
stopping=true;
if(worker.joinable()) worker.join();
inputConnected=false;++inputEpoch;
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
std::lock_guard lock(mutex); pending.reset(); peers.clear();clipboard=std::make_unique<lan::ClipboardExchange>(id);
transfers=std::make_unique<lan::ClipboardExchange>(id,"file-transfer");incomingFiles.clear();logDownload.reset();
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,0,FALSE);
}
void updateInputStatus(size_t connected,size_t online,std::string status,bool needsHelp,bool stopped=false)
{
bool changed;
{
std::lock_guard lock(mutex);
changed=connected!=inputConnectedPeers||online!=inputOnlinePeers||stopped!=inputWorkerStopped;
inputConnectedPeers=connected;
inputOnlinePeers=online;
inputWorkerStopped=stopped;
inputStatus=std::move(status);
inputNeedsHelp=needsHelp;
}
if(changed&&inputWindow)PostMessageW(inputWindow,LanInputStatusMessage,0,0);
}
void send(SOCKET socket,const sockaddr_in &address,const Json &j)
{
auto bytes=j.dump(); if(bytes.size()>2048) return;
sendto(socket,bytes.data(),int(bytes.size()),0,(const sockaddr*)&address,sizeof(address));
}
Json discoveryAnnouncement(bool filesListening)const
{
auto hello=lan::envelope("hello",id);
hello["name"]=name;
hello["epoch"]=epoch;
hello["clipboardSession"]=clipboard->session();
hello["fileSession"]=transfers->session();
hello["filesBrowse"]=filesListening;
return hello;
}
std::string heartbeat(const std::string &from,const std::string &to,const std::string &a,const std::string &b)
{ return "KSwitcher LAN v1|presence|"+from+"|"+to+"|"+a+"|"+b; }
void receiveTransfers(uint64_t now)
@@ -267,7 +299,7 @@ struct LanService::Impl
}
transfers->deliveries.clear();
}
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now)
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now,bool filesListening)
{
if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return;
auto other=j.value("id",""); if(!lan::identifier(other)||other==id) return;
@@ -278,19 +310,23 @@ struct LanService::Impl
if(display.empty()||display.size()>128||!lan::identifier(session)||
std::any_of(display.begin(),display.end(),[](unsigned char c){return c<32||c==127;})) return;
// Discovery is untrusted and never grants input access.
if(!peers.contains(other) && peers.size()>=64) return;
const bool firstAnnouncement=!peers.contains(other);
if(firstAnnouncement && peers.size()>=64) return;
auto &peer=peers[other];
// A fresh announcement rotates the challenge every three seconds; it
// does not revoke a recent successful proof for the same address.
// Only a valid presence response renews verified, so untrusted/replayed
// announcements cannot extend its PeerLifetime expiry.
if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0;
const bool addressChanged=peer.address.sin_addr.s_addr!=address.sin_addr.s_addr;
if(addressChanged) peer.verified=0;
clipboard->peerSession(other,j.value("clipboardSession",""));
transfers->peerSession(other,j.value("fileSession",""));
peer.files=j.value("filesBrowse",false);
peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now;
if(trusted.contains(other))
{
// A returning peer can prove presence right away using our current challenge.
if(firstAnnouncement) send(socket,address,discoveryAnnouncement(filesListening));
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
const auto &key=trusted[other].at("key");
const auto challenge=heartbeat(id,other,epoch,session);
@@ -409,13 +445,16 @@ struct LanService::Impl
});
clipboardActive=clipboard->active()||transfers->active();
if(shareInput)for(auto &[peer,entry]:trusted.items())
endpoints.push_back({peer,entry.at("key"),peers.contains(peer)?peers.at(peer).address.sin_addr.s_addr:0});
{
const auto found=peers.find(peer);
const bool discovered=found!=peers.end()&&found->second.present(now);
endpoints.push_back({.id=peer,.key=entry.at("key"),
.address=discovered?found->second.address.sin_addr.s_addr:0,.discovered=discovered});
}
if(refreshFiles.exchange(false) || now>=nextHello)
{
epoch=lan::randomHex(16); // Fresh challenge prevents replayed presence from staying online.
auto hello=lan::envelope("hello",id); hello["name"]=name; hello["epoch"]=epoch;hello["clipboardSession"]=clipboard->session();
hello["fileSession"]=transfers->session();
hello["filesBrowse"]=filesListening;
const auto hello=discoveryAnnouncement(filesListening);
for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); }
nextHello=now+3000;
}
@@ -434,7 +473,7 @@ struct LanService::Impl
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
hub.poll(endpoints,out,in,now);
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
auto readyPeers=hub.ready();const auto connected=readyPeers.size();
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
for(auto &frame:in){
if(!inputIn.empty()&&inputIn.back().peer==frame.peer&&inputIn.back().epoch==frame.epoch){
@@ -447,8 +486,10 @@ struct LanService::Impl
}
if(!in.empty()&&inputWindow&&!inputNotification.exchange(true))
if(!PostMessageW(inputWindow,LanInputReadyMessage,0,0))inputNotification=false;
{std::lock_guard lock(mutex);inputStatus=hub.status();inputNeedsHelp=hub.needsHelp();}
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,!endpoints.empty()||clipboardActive?5000:100000};
const auto online=hub.onlinePeers();
updateInputStatus(connected,online,online||endpoints.empty()?hub.status():
"All paired PCs are offline. Waiting for LAN discovery.",hub.needsHelp());
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,online||clipboardActive?5000:100000};
int ready=select(0,&read,nullptr,nullptr,&delay);
if(ready==SOCKET_ERROR) throw std::runtime_error("LAN discovery socket failed.");
if(ready>0) for(int count=0;count<64;++count)
@@ -463,15 +504,16 @@ struct LanService::Impl
bool allowed=false;auto peer=j.value("id","");
{std::lock_guard lock(mutex);allowed=shareInput&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
if(allowed)hub.receiveDatagram(j,GetTickCount64());
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64());}
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64(),filesListening);}
}
catch(const Json::exception &) {} // Malformed network data cannot interrupt discovery.
}
}
}
catch(const std::exception &e) { std::lock_guard lock(mutex); status=std::string("LAN stopped: ")+e.what(); }
inputConnected=false;++inputEpoch;
{std::lock_guard lock(mutex);if(shareInput)inputStatus="Input connection closed.";}
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
++inputEpoch;
updateInputStatus(0,0,"Input connection closed.",false,true);
if(socket!=INVALID_SOCKET) closesocket(socket);
if(winsock) WSACleanup();
}
@@ -503,8 +545,7 @@ struct LanService::Impl
{
auto peer=j.at("peer").get<std::string>();
const auto checkPeer = [&] {
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
now-peers.at(peer).verified>=lan::PeerLifetime)
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).present(now))
throw std::runtime_error("Select an online paired computer.");
if(!transfers->hasSession(peer))
throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers.");
@@ -628,7 +669,7 @@ struct LanService::Impl
status="Pair removed on this computer.";
}
Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()},
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnected.load()},
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnectedPeers!=0},
{"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
result["shareLogs"]=shareLogs;
@@ -649,7 +690,7 @@ struct LanService::Impl
if(action=="filesPeers" && !trusted.contains(peer)) continue;
char ip[INET_ADDRSTRLEN]{}; InetNtopA(AF_INET,(void*)&p.address.sin_addr,ip,sizeof(ip));
result["peers"].push_back({{"id",peer},{"name",p.name},{"address",ip},{"paired",trusted.contains(peer)},
{"verified",p.verified && now-p.verified<lan::PeerLifetime},{"online",true},
{"verified",p.present(now)},{"online",true},
{"fileTransfer",transfers->hasSession(peer)},{"filesBrowse",p.files}});
}
for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer))
@@ -682,6 +723,13 @@ std::vector<LanClipboard> LanService::takeClipboard()
impl->clipboard->deliveries.clear();return result;
}
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput;}
LanInputConnections LanService::inputConnections()const
{
std::lock_guard lock(impl->mutex);
if(!inputEnabled())return {};
const auto paired=impl->trusted.size();
return {std::min(impl->inputConnectedPeers,paired),std::min(impl->inputOnlinePeers,paired),paired,impl->inputWorkerStopped};
}
bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);}
bool LanService::keyboard(const KBDLLHOOKSTRUCT &k,bool down){return impl->router&&impl->router->keyboard(k,down,GetTickCount64());}
bool LanService::mouse(UINT message,const MSLLHOOKSTRUCT &m,bool allowEnter){return impl->router&&impl->router->mouse(message,m,GetTickCount64(),allowEnter);}
+9
View File
@@ -7,7 +7,15 @@ namespace ks
inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69;
inline constexpr UINT LanFilesChangedMessage=WM_APP+70;
inline constexpr UINT LanUpdateRequestedMessage=WM_APP+90;
inline constexpr UINT LanInputStatusMessage=WM_APP+91;
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
struct LanInputConnections
{
size_t connected{}, online{}, paired{};
bool stopped{};
bool reconnecting()const{return !stopped&&connected<online;}
bool operator==(const LanInputConnections &) const = default;
};
// Discovery, pairing and optional encrypted input within the resident process.
class LanService
{
@@ -21,6 +29,7 @@ class LanService
void publishClipboard(Bytes, const std::string &);
std::vector<LanClipboard> takeClipboard();
bool inputEnabled() const;
LanInputConnections inputConnections() const;
bool tickInput(bool allowEnter = true);
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
bool mouse(UINT, const MSLLHOOKSTRUCT &, bool allowEnter);
+25 -11
View File
@@ -213,6 +213,7 @@ bool InputChannel::adopt(uintptr_t accepted,uint64_t now)
impl->connecting=false;impl->begin(now);impl->socket=SOCKET(accepted);return true;
}
bool InputChannel::ready()const{return impl->authenticated;}
bool InputChannel::handshaking()const{return impl->socket!=INVALID_SOCKET&&!impl->authenticated;}
uint64_t InputChannel::generation()const{return impl->changed;}
std::string InputChannel::status()const{
return impl->lastError.empty() ? impl->state : impl->lastError+" Retrying automatically.";
@@ -221,7 +222,16 @@ void InputChannel::disconnect(){impl->reset(GetTickCount64(),"Input disconnected
std::string InputChannel::transport()const{return impl->reverse?"reverse TCP":"direct TCP";}
struct InputHub::Impl
{
struct Link { InputEndpoint endpoint;std::unique_ptr<InputChannel> channel;std::unique_ptr<InputDatagram> udp;uint64_t generation{},epoch{},since{},failedSince{};bool udpReady{};std::string lastState; };
struct Link
{
InputEndpoint endpoint;
std::unique_ptr<InputChannel> channel;
std::unique_ptr<InputDatagram> udp;
uint64_t generation{},epoch{},since{},failedSince{};
bool udpReady{};
std::string lastState;
bool ready()const{return channel->ready()||udp->ready();}
};
struct Pending {SOCKET socket;uint32_t address;uint64_t since;};
std::string local;uint16_t port;SOCKET listener=INVALID_SOCKET;
std::map<std::string,Link> links;std::vector<Pending> pending;uint64_t epoch{},retry{};
@@ -235,17 +245,18 @@ struct InputHub::Impl
currentTime=now;
for(auto it=links.begin();it!=links.end();){
auto match=std::find_if(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id==it->first&&e.key==it->second.endpoint.key&&e.port==it->second.endpoint.port;});
if(match==endpoints.end())it=links.erase(it);else ++it;
// Discovery gates new attempts. An authenticated connection can outlive discovery.
if(match==endpoints.end()||(!match->discovered&&!it->second.ready()))it=links.erase(it);else ++it;
}
for(auto &e:endpoints)if(e.id!=local&&!links.contains(e.id)){
for(auto &e:endpoints)if(e.discovered&&e.id!=local&&!links.contains(e.id)){
Link link;link.endpoint=e;link.channel=std::make_unique<InputChannel>(local,e.id,e.key,0,e.port,true);
link.udp=std::make_unique<InputDatagram>(local,e.id,e.key);link.since=link.failedSince=now;link.epoch=++epoch;links.emplace(e.id,std::move(link));
}
// Discovery is a hint, not the lifetime of authenticated input sessions.
// Keep the last usable address across missed announcements. A new address
// is used only once a channel is down, never to tear down working input.
for(auto &e:endpoints){if(e.id==local)continue;auto &link=links.at(e.id);
if(e.address&&!link.channel->ready()&&e.address!=link.endpoint.address){
for(auto &e:endpoints){if(!e.discovered||e.id==local)continue;auto &link=links.at(e.id);
if(e.address&&!link.ready()&&e.address!=link.endpoint.address){
link.channel->disconnect();link.endpoint.address=e.address;
}
}
@@ -279,14 +290,16 @@ struct InputHub::Impl
}
for(auto &[id,link]:links){
std::vector<InputFrame> frames,received;for(auto &f:out)if(f.peer==id&&(!f.epoch||f.epoch==link.epoch))enqueueInput(frames,f.frame);
if(sendDatagram&&!link.channel->ready()&&!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);link.channel->disconnect();frames.clear();}
// Let an in-flight TCP connection finish or hit its own deadline.
// Check before poll() so another TCP retry cannot starve UDP fallback.
if(sendDatagram&&!link.channel->ready()&&!link.channel->handshaking()&&
!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);frames.clear();}
if(link.udp->active()){
link.udp->poll(frames,received,now,sendDatagram);
if(!link.udp->active()){link.since=now;link.channel->disconnect();received.clear();}
}else link.channel->poll(link.endpoint.address,frames,received,now);
if(link.udpReady!=link.udp->ready()){link.udpReady=link.udp->ready();link.epoch=++epoch;}
bool ready=link.channel->ready()||link.udp->ready();
if(ready)link.failedSince=link.since=now;
if(link.ready())link.failedSince=link.since=now;
auto state=link.udp->ready()?"Input connected via encrypted UDP.":link.udp->active()?"Trying encrypted UDP over discovery...":link.channel->ready()?"Input connected via "+link.channel->transport()+".":link.channel->status();
if(state!=link.lastState){link.lastState=state;log(L"LAN input peer "+wide(id.substr(0,8))+L": "+wide(state));}
if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;}
@@ -297,7 +310,8 @@ struct InputHub::Impl
InputHub::InputHub(std::string id,uint16_t port):impl(std::make_unique<Impl>(std::move(id),port)){}
InputHub::~InputHub()=default;
void InputHub::poll(const std::vector<InputEndpoint> &peers,const std::vector<RoutedInput> &out,std::vector<RoutedInput> &in,uint64_t now){impl->poll(peers,out,in,now);}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.channel->ready()||l.udp->ready())result[id]=l.epoch;return result;}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.ready())result[id]=l.epoch;return result;}
size_t InputHub::onlinePeers()const{return impl->links.size();}
std::string InputHub::status()const{
auto count=ready().size();if(count==impl->links.size()&&count){
std::string routes;for(auto &[id,l]:impl->links){if(!routes.empty())routes+=", ";routes+=id.substr(0,8)+": "+(l.udp->ready()?"encrypted UDP":l.channel->transport());}
@@ -305,7 +319,7 @@ std::string InputHub::status()const{
}
if(needsHelp())return "Automatic connection attempts have not succeeded for every PC. Enable input on both PCs. Open Connection help for firewall commands.";
if(!impl->error.empty())return impl->error;
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready())return l.lastState;
for(auto &[id,l]:impl->links)if(!l.ready())return l.lastState;
return "Waiting for paired computers...";
}
void InputHub::disconnect(){for(auto &[id,l]:impl->links){l.channel->disconnect();l.udp->reset();l.since=impl->currentTime;}}
@@ -318,7 +332,7 @@ void InputHub::receiveDatagram(const Json &j,uint64_t now){
if(!active&&link.udp->active())link.channel->disconnect();
}
bool InputHub::needsHelp()const{
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready()&&impl->currentTime-l.failedSince>=15000)return true;
for(auto &[id,l]:impl->links)if(!l.ready()&&impl->currentTime-l.failedSince>=15000)return true;
return false;
}
}
+9 -1
View File
@@ -55,12 +55,19 @@ class InputChannel
void poll(uint32_t peerAddress,const std::vector<InputFrame> &out,std::vector<InputFrame> &in,uint64_t now);
bool adopt(uintptr_t socket,uint64_t now);
bool ready() const;
bool handshaking() const;
uint64_t generation() const;
std::string status() const;
void disconnect();
std::string transport()const;
};
struct InputEndpoint {std::string id,key;uint32_t address{};uint16_t port=45884;};
struct InputEndpoint
{
std::string id,key;
uint32_t address{};
uint16_t port=45884;
bool discovered=true;
};
struct RoutedInput {std::string peer;InputFrame frame;uint64_t epoch{};};
class InputHub
{
@@ -70,6 +77,7 @@ class InputHub
~InputHub();
void poll(const std::vector<InputEndpoint> &,const std::vector<RoutedInput> &,std::vector<RoutedInput> &,uint64_t now);
std::map<std::string,uint64_t> ready()const;
size_t onlinePeers()const;
std::string status()const;
void disconnect();
using SendDatagram=std::function<void(const std::string &,const Json &)>;
+16 -4
View File
@@ -211,9 +211,18 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
if(!connected||!env.desktop()){cancel(now);return;}
if(f.type==InputType::Enter)
{
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535||held()||returning||
mode_==ControlMode::Sending||mode_==ControlMode::Receiving||(mode_==ControlMode::Requesting&&preferLocal))
{post({InputType::Return,f.token,32768});return;}
const wchar_t *declined=nullptr;
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535)
declined=L"invalid edge or position";
else if(held())declined=L"a local key or mouse button is held";
else if(returning||mode_==ControlMode::Sending||mode_==ControlMode::Receiving||
(mode_==ControlMode::Requesting&&preferLocal))
declined=L"another handoff is active";
if(declined)
{
log(std::wstring(L"LAN input: declined cursor handoff: ")+declined);
post({InputType::Return,f.token,32768});return;
}
if(mode_==ControlMode::Requesting)cancel(now);
if(multi)edge=f.a^1;
crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
@@ -231,7 +240,10 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
return;
}
if(f.token!=token||!token)return;
if(f.type==InputType::Return){log(L"LAN input: peer returned control");local(now,std::clamp(f.a,0,65535));return;}
if(f.type==InputType::Return){
log(mode_==ControlMode::Requesting?L"LAN input: peer declined cursor handoff":L"LAN input: peer returned control");
local(now,std::clamp(f.a,0,65535));return;
}
if(mode_!=ControlMode::Receiving)return;
bool ok=true;
if(f.type==InputType::Move)
+1
View File
@@ -50,6 +50,7 @@ class InputMesh
if(!ready.contains(peer)||!positions.contains(peer))return;
if(f.type==InputType::Enter){
if(!allowEnter||f.a<0||f.a>3||(router.mode()!=ControlMode::Local&&active!=peer)){
if(!allowEnter)log(L"LAN input: declined cursor handoff during a local text operation or shortcut capture");
send(peer,{InputType::Return,f.token,32768});return;
}
if(router.mode()==ControlMode::Local)select(peer,f.a^1,now);
+29 -11
View File
@@ -11,8 +11,19 @@ class PasteProbe
IUIAutomationElement *element{};
IUIAutomationTextPattern *pattern{};
static std::optional<std::wstring> rangeText(IUIAutomationTextRange *range)
{
BSTR value{};
const HRESULT hr = range->GetText(8193, &value);
std::wstring text(value ? value : L"", SysStringLen(value));
SysFreeString(value);
if (FAILED(hr)) return {};
return text;
}
public:
std::wstring status = L"not-requested";
std::optional<std::wstring> precedingCharacter;
PasteProbe(bool enabled, HWND target)
{
if (!enabled)
@@ -48,11 +59,11 @@ class PasteProbe
!pattern)
return;
}
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr)
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr, bool readPreceding = false)
: PasteProbe(enabled, target)
{
if (!pattern) return;
auto selected = read(1, false);
auto selected = read(1, false, readPreceding);
auto normalize = [](std::wstring value)
{
for (size_t at = 0; (at = value.find(L"\r\n", at)) != value.npos;)
@@ -80,7 +91,7 @@ class PasteProbe
if (automation)
automation->Release();
}
std::optional<std::wstring> read(int characters, bool allowCaret = true)
std::optional<std::wstring> read(int characters, bool allowCaret = true, bool readPreceding = false)
{
if (!pattern)
return {};
@@ -162,19 +173,26 @@ class PasteProbe
if (SUCCEEDED(hr) && moved != -characters)
hr = E_FAIL;
}
BSTR value{};
if (SUCCEEDED(hr))
hr = range->GetText(8193, &value);
auto text = SUCCEEDED(hr) ? rangeText(range) : std::nullopt;
if (readPreceding && text &&
SUCCEEDED(range->MoveEndpointByRange(TextPatternRangeEndpoint_End, range, TextPatternRangeEndpoint_Start)))
{
int moved{};
if (SUCCEEDED(range->MoveEndpointByUnit(TextPatternRangeEndpoint_Start, TextUnit_Character, -1, &moved)))
{
if (moved == 0)
precedingCharacter.emplace();
else if (auto previous = rangeText(range); previous && !previous->empty())
precedingCharacter = std::move(previous);
}
}
range->Release();
if (FAILED(hr))
if (!text)
{
SysFreeString(value);
status = L"range-read-failed";
return {};
}
std::wstring text(value ? value : L"", SysStringLen(value));
SysFreeString(value);
if (text.size() > 8192)
if (text->size() > 8192)
{
status = L"readback-size-limit";
return {};
+7 -7
View File
@@ -50,13 +50,12 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
std::wstring token;
bool autoOpenEditor=false, writeLog=false;
int argc{}; auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
if(argc==3 && std::wstring(argv[1])==L"--clipboard-snapshot") {
std::filesystem::path request=argv[2]; LocalFree(argv);
return ks::runClipboardSnapshot(request);
}
if(argc==5 && std::wstring_view(argv[1])==L"--history-image-worker") {
HANDLE handles[3]{};
for(int i=0;i<3;++i)
const bool clipboardSnapshot = argc == 6 && std::wstring_view(argv[1]) == L"--clipboard-snapshot";
const bool historyImageWorker = argc == 5 && std::wstring_view(argv[1]) == L"--history-image-worker";
if (clipboardSnapshot || historyImageWorker)
{
HANDLE handles[4]{};
for (int i = 0; i < argc - 2; ++i)
{
wchar_t *end{};
const auto value=std::wcstoull(argv[i+2],&end,10);
@@ -64,6 +63,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
handles[i]=reinterpret_cast<HANDLE>(static_cast<uintptr_t>(value));
}
LocalFree(argv);
if (clipboardSnapshot) return ks::runClipboardSnapshot(handles[0], handles[1], handles[2], handles[3]);
const auto initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
if(FAILED(initialized)) return 1;
const auto result=ks::runHistoryImageWorker(handles[0],handles[1],handles[2]);
+138 -134
View File
@@ -703,26 +703,98 @@ struct ImageWorkerHandle
if(value) CloseHandle(std::exchange(value,nullptr));
}
};
template <typename Control>
struct ImageWorkerView
{
ImageWorkerControl *control{};
Control *control{};
~ImageWorkerView() { reset(); }
void reset()
{
if(control) UnmapViewOfFile(std::exchange(control,nullptr));
}
};
template <typename Control>
struct ImageWorkerChannel
{
ImageWorkerHandle mapping, requestReady, responseReady, process;
ImageWorkerView<Control> view;
~ImageWorkerChannel() { stop(); }
void stop() noexcept
{
if (process.value && WaitForSingleObject(process.value, 0) == WAIT_TIMEOUT)
{
TerminateProcess(process.value, ERROR_CANCELLED);
WaitForSingleObject(process.value, INFINITE);
}
process.reset();
view.reset();
mapping.reset();
requestReady.reset();
responseReady.reset();
}
void open()
{
SECURITY_ATTRIBUTES security{sizeof(security), nullptr, TRUE};
mapping.value = CreateFileMappingW(INVALID_HANDLE_VALUE, &security, PAGE_READWRITE, 0, sizeof(Control), nullptr);
requestReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
responseReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
if (!mapping.value || !requestReady.value || !responseReady.value)
throw std::runtime_error("Cannot create image helper channel");
view.control = static_cast<Control *>(MapViewOfFile(mapping.value, FILE_MAP_WRITE, 0, 0, sizeof(Control)));
if (!view.control) throw std::runtime_error("Cannot map image helper channel");
}
void start(std::wstring_view mode, HANDLE parent = nullptr)
{
std::vector<HANDLE> inherited{mapping.value, requestReady.value, responseReady.value};
if (parent) inherited.push_back(parent);
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr, 1, 0, &bytes);
Bytes storage(bytes);
auto attributes = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if (!InitializeProcThreadAttributeList(attributes, 1, 0, &bytes))
throw std::runtime_error("Cannot initialize image helper startup");
struct Attributes
{
LPPROC_THREAD_ATTRIBUTE_LIST value;
~Attributes() { DeleteProcThreadAttributeList(value); }
} cleanup{attributes};
if (!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inherited.data(), inherited.size() * sizeof(HANDLE), nullptr, nullptr))
throw std::runtime_error("Cannot configure image helper startup");
const auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" ";
command += mode;
for (auto handle : inherited) command += L" " + std::to_wstring(reinterpret_cast<uintptr_t>(handle));
STARTUPINFOEXW startup{};
startup.StartupInfo.cb = sizeof(startup);
startup.lpAttributeList = attributes;
PROCESS_INFORMATION child{};
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, TRUE,
CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, nullptr, helper.parent_path().c_str(),
&startup.StartupInfo, &child))
throw std::runtime_error(utf8(lastError(L"Cannot start image helper")));
process.value = child.hProcess;
CloseHandle(child.hThread);
for (auto handle : inherited) SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
}
DWORD waitForResponse(DWORD timeout) const
{
HANDLE signals[]{responseReady.value, process.value};
return WaitForMultipleObjects(2, signals, FALSE, timeout);
}
};
struct HistoryImageWorker
{
std::timed_mutex mutex;
ImageWorkerHandle mapping, requestReady, responseReady, process;
ImageWorkerView view;
~HistoryImageWorker() { stop(); }
void stop();
void start();
ImageWorkerChannel<ImageWorkerControl> channel;
int perform(const std::filesystem::path &, const std::function<bool()> &);
};
struct ClipboardSnapshotControl
{
DWORD sequence;
};
}
struct HistoryImageWorkers
@@ -778,42 +850,15 @@ void History::reload()
std::lock_guard lock(mutex_);
loadIndex();
}
void ClipboardSnapshot::cleanup() noexcept
struct ClipboardSnapshot::Helper
{
if (request_.empty()) return;
std::error_code ignored;
for (const auto *suffix : {L"", L".snapshot", L".result"})
std::filesystem::remove(std::filesystem::path(request_.wstring() + suffix), ignored);
request_.clear();
}
ClipboardSnapshot::~ClipboardSnapshot() { cleanup(); }
DWORD ClipboardSnapshot::run(bool restore, DWORD sequence)
{
atomicWrite(request_, protect(jsonBytes(Json{{"schema", 1}, {"restore", restore}, {"sequence", sequence}})));
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" --clipboard-snapshot \"" + request_.wstring() + L"\"";
STARTUPINFOW startup{sizeof(startup)};
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
PROCESS_INFORMATION process{};
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
nullptr, helper.parent_path().c_str(), &startup, &process))
throw std::runtime_error("Cannot start clipboard snapshot helper");
CloseHandle(process.hThread);
auto wait = WaitForSingleObject(process.hProcess, 10000);
DWORD result = ERROR_GEN_FAILURE;
if (wait != WAIT_OBJECT_0)
{
TerminateProcess(process.hProcess, ERROR_TIMEOUT);
WaitForSingleObject(process.hProcess, INFINITE);
}
GetExitCodeProcess(process.hProcess, &result);
CloseHandle(process.hProcess);
if (wait != WAIT_OBJECT_0 || result) throw std::runtime_error("Clipboard snapshot helper failed");
return parse(unprotect(readFile(request_.wstring() + L".result", 4096))).at("sequence").get<DWORD>();
}
ImageWorkerChannel<ClipboardSnapshotControl> channel;
};
ClipboardSnapshot::ClipboardSnapshot() = default;
ClipboardSnapshot::~ClipboardSnapshot() = default;
void ClipboardSnapshot::capture(HWND window, DWORD sequence)
{
cleanup();
helper_.reset();
clip_ = {};
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
!IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")))
@@ -821,39 +866,53 @@ void ClipboardSnapshot::capture(HWND window, DWORD sequence)
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence);
return;
}
request_ = std::filesystem::temp_directory_path() / (L"ks-clipboard-" + newSnippetId() + L".request");
try { run(false, sequence); }
catch (...) { cleanup(); throw; }
auto helper = std::make_unique<Helper>();
auto &channel = helper->channel;
channel.open();
channel.view.control->sequence = sequence;
// Let the helper discard its private copy if the resident exits unexpectedly.
ImageWorkerHandle parent;
const auto self = GetCurrentProcess();
if (!DuplicateHandle(self, self, self, &parent.value, SYNCHRONIZE, TRUE, 0))
throw std::runtime_error("Cannot pass resident lifetime to clipboard helper");
channel.start(L"--clipboard-snapshot", parent.value);
if (channel.waitForResponse(10000) != WAIT_OBJECT_0)
throw std::runtime_error("Clipboard snapshot helper failed to capture");
helper_ = std::move(helper);
}
DWORD ClipboardSnapshot::restore(HWND window, DWORD sequence)
{
return request_.empty() ? writeClipboardGuarded(window, clip_, sequence) : run(true, sequence);
if (!helper_) return writeClipboardGuarded(window, clip_, sequence);
auto &channel = helper_->channel;
if (!channel.process.value)
throw std::runtime_error("Clipboard snapshot helper is unavailable");
channel.view.control->sequence = sequence;
DWORD result{};
if (!SetEvent(channel.requestReady.value) || WaitForSingleObject(channel.process.value, 10000) != WAIT_OBJECT_0 ||
!GetExitCodeProcess(channel.process.value, &result) || result != 0)
{
channel.stop();
throw std::runtime_error("Clipboard snapshot helper failed to restore");
}
return channel.view.control->sequence;
}
int runClipboardSnapshot(const std::filesystem::path &request)
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent)
{
try
{
if (!request.is_absolute() || !request.filename().wstring().starts_with(L"ks-clipboard-") ||
request.extension() != L".request") return 1;
auto job = parse(unprotect(readFile(request, 4096)));
if (job.at("schema") != 1) return 1;
auto sequence = job.at("sequence").get<DWORD>();
const auto snapshot = request.wstring() + L".snapshot";
if (job.at("restore").get<bool>())
{
auto clip = decodeClip(unprotect(readFile(snapshot, 70 * 1024 * 1024)));
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
if (!window) return 1;
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
sequence = writeClipboardGuarded(window, clip, sequence);
}
else
{
auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
if (sequence != GetClipboardSequenceNumber()) return 2;
atomicWrite(snapshot, protect(encodeClip(clip)));
}
atomicWrite(request.wstring() + L".result", protect(jsonBytes(Json{{"sequence", sequence}})));
ImageWorkerView<ClipboardSnapshotControl> view{static_cast<ClipboardSnapshotControl *>(
MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(ClipboardSnapshotControl)))};
if (!view.control) return 1;
const auto sequence = view.control->sequence;
const auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
if (sequence != GetClipboardSequenceNumber() || !SetEvent(responseReady)) return 1;
// Only the clipboard sequence crosses the channel. The captured formats stay in this process.
HANDLE signals[]{parent, requestReady};
if (WaitForMultipleObjects(2, signals, FALSE, INFINITE) != WAIT_OBJECT_0 + 1) return 1;
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
if (!window) return 1;
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
view.control->sequence = writeClipboardGuarded(window, clip, view.control->sequence);
return 0;
}
catch (...) { return 1; }
@@ -1163,61 +1222,6 @@ void History::clear()
}
namespace
{
void HistoryImageWorker::stop()
{
if(process.value && WaitForSingleObject(process.value,0)==WAIT_TIMEOUT)
{
TerminateProcess(process.value,ERROR_CANCELLED);
WaitForSingleObject(process.value,INFINITE);
}
process.reset();
view.reset();
mapping.reset();
requestReady.reset();
responseReady.reset();
}
void HistoryImageWorker::start()
{
SECURITY_ATTRIBUTES security{sizeof(security),nullptr,TRUE};
mapping.value=CreateFileMappingW(INVALID_HANDLE_VALUE,&security,PAGE_READWRITE,0,sizeof(ImageWorkerControl),nullptr);
requestReady.value=CreateEventW(&security,FALSE,FALSE,nullptr);
responseReady.value=CreateEventW(&security,FALSE,FALSE,nullptr);
if(!mapping.value || !requestReady.value || !responseReady.value)
throw std::runtime_error("Cannot create history OCR worker channel");
view.control=static_cast<ImageWorkerControl *>(MapViewOfFile(mapping.value,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)));
if(!view.control) throw std::runtime_error("Cannot map history OCR worker channel");
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
Bytes storage(bytes);
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes))
throw std::runtime_error("Cannot initialize history OCR worker startup");
struct Attributes
{
LPPROC_THREAD_ATTRIBUTE_LIST value;
~Attributes() { DeleteProcThreadAttributeList(value); }
} cleanup{attributes};
HANDLE inherited[]{mapping.value,requestReady.value,responseReady.value};
if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr))
throw std::runtime_error("Cannot configure history OCR worker startup");
const auto helper=std::filesystem::path(executable()).parent_path()/L"KSwitcher.Screenshot.exe";
auto command=L"\""+helper.wstring()+L"\" --history-image-worker";
for(auto handle:inherited) command+=L" "+std::to_wstring(reinterpret_cast<uintptr_t>(handle));
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.lpAttributeList=attributes;
PROCESS_INFORMATION child{};
if(!CreateProcessW(helper.c_str(),command.data(),nullptr,nullptr,TRUE,
CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,nullptr,helper.parent_path().c_str(),&startup.StartupInfo,&child))
throw std::runtime_error(utf8(lastError(L"Cannot start history OCR helper")));
process.value=child.hProcess;
CloseHandle(child.hThread);
for(const auto handle:inherited) SetHandleInformation(handle,HANDLE_FLAG_INHERIT,0);
}
int HistoryImageWorker::perform(const std::filesystem::path &request,const std::function<bool()> &cancelled)
{
std::unique_lock lock(mutex,std::defer_lock);
@@ -1234,42 +1238,42 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
{
for(int attempt=0;attempt<2;++attempt)
{
if(!process.value || WaitForSingleObject(process.value,0)!=WAIT_TIMEOUT)
if(!channel.process.value || WaitForSingleObject(channel.process.value,0)!=WAIT_TIMEOUT)
{
stop();
start();
channel.stop();
channel.open();
channel.start(L"--history-image-worker");
}
checkCancelled();
std::copy(path.begin(),path.end(),view.control->request);
view.control->request[path.size()]=L'\0';
if(!SetEvent(requestReady.value)) throw std::runtime_error("Cannot request history OCR");
HANDLE signals[]{responseReady.value,process.value};
std::copy(path.begin(),path.end(),channel.view.control->request);
channel.view.control->request[path.size()]=L'\0';
if(!SetEvent(channel.requestReady.value)) throw std::runtime_error("Cannot request history OCR");
const auto deadline=GetTickCount64()+60000;
for(;;)
{
const auto wait=WaitForMultipleObjects(2,signals,FALSE,100);
const auto wait=channel.waitForResponse(100);
if(wait==WAIT_OBJECT_0)
{
checkCancelled();
return view.control->result;
return channel.view.control->result;
}
if(wait==WAIT_OBJECT_0+1)
{
DWORD code{};
if(GetExitCodeProcess(process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
if(GetExitCodeProcess(channel.process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
throw std::runtime_error("History OCR helper exited before responding");
}
if(wait!=WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper");
checkCancelled();
if(GetTickCount64()>=deadline) throw std::runtime_error("History OCR helper timed out");
}
stop();
channel.stop();
}
}
catch(...)
{
// The child must stop writing before the request and response files are cleaned up.
stop();
channel.stop();
throw;
}
throw std::runtime_error("History OCR helper did not accept the request");
@@ -1278,7 +1282,7 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
int runHistoryImageWorker(HANDLE mapping,HANDLE requestReady,HANDLE responseReady)
{
ImageWorkerView view{static_cast<ImageWorkerControl *>(
ImageWorkerView<ImageWorkerControl> view{static_cast<ImageWorkerControl *>(
MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)))};
if(!view.control) return 1;
for(;;)
+5 -6
View File
@@ -58,20 +58,19 @@ bool sameClipboardImage(const Clip &, const Clip &);
int runImageHistoryCapture(const std::filesystem::path &request);
int runHistoryOcr(const std::filesystem::path &request);
int runHistoryImageWorker(HANDLE mapping, HANDLE requestReady, HANDLE responseReady);
// Image backups stay encrypted on disk and are read/written only by a short-lived helper.
// Image backups are held in memory by a helper for the lifetime of the transaction.
class ClipboardSnapshot
{
struct Helper;
Clip clip_;
std::filesystem::path request_;
void cleanup() noexcept;
DWORD run(bool restore, DWORD sequence);
std::unique_ptr<Helper> helper_;
public:
ClipboardSnapshot() = default;
ClipboardSnapshot();
ClipboardSnapshot(const ClipboardSnapshot &) = delete;
ClipboardSnapshot &operator=(const ClipboardSnapshot &) = delete;
~ClipboardSnapshot();
void capture(HWND, DWORD sequence);
DWORD restore(HWND, DWORD sequence);
};
int runClipboardSnapshot(const std::filesystem::path &request);
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent);
} // namespace ks
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.117";
inline constexpr wchar_t AppVersion[] = L"0.6.123";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+21 -4
View File
@@ -44,7 +44,9 @@ int main(int argc,char**argv) {
HWND w=owner(); int result=0; ks::Clip original; bool saved=false;
try {
std::string mode=argc>1?argv[1]:"suite";
if(mode=="publish") {
if(mode=="temporary") {
ks::writeClipboard(w,ks::textClip(L"temporary"));
} else if(mode=="publish") {
ks::Pixels p{1566,1068,ks::Bytes(1566*1068*4,255)}; p.bgra[0]=77;
auto dib=ks::imageDib(p); auto v5=dib;
BITMAPV5HEADER h{}; h.bV5Size=sizeof(h); h.bV5Width=p.width; h.bV5Height=-p.height;
@@ -60,9 +62,17 @@ int main(int argc,char**argv) {
auto clip=ks::readClipboard(w,64*1024*1024);
ks::writeClipboard(w,ks::textClip(L"temporary")); ks::writeClipboard(w,clip);
} else {
ks::ClipboardSnapshot snapshot; snapshot.capture(w,GetClipboardSequenceNumber());
auto seq=ks::writeClipboard(w,ks::textClip(L"temporary"));
require(snapshot.restore(w,seq)==GetClipboardSequenceNumber(),"helper returns current sequence");
ks::ClipboardSnapshot snapshot;
auto started=GetTickCount64();
snapshot.capture(w,GetClipboardSequenceNumber());
std::cout<<"Image snapshot capture: "<<GetTickCount64()-started<<" ms\n";
// A separate publisher avoids blocking clipboard notifications on this waiting test thread.
child(L"temporary");
const auto seq=GetClipboardSequenceNumber();
started=GetTickCount64();
const auto restored=snapshot.restore(w,seq);
std::cout<<"Image snapshot restore: "<<GetTickCount64()-started<<" ms\n";
require(restored==GetClipboardSequenceNumber(),"helper returns current sequence");
}
auto after=resident();
auto report="baseline="+std::to_string(baseline)+" after="+std::to_string(after)+" delta="+std::to_string(int64_t(after)-int64_t(baseline))+"\n";
@@ -78,6 +88,13 @@ int main(int argc,char**argv) {
bool rejected=false;
try {ks::readClipboard(w,32*1024*1024,ks::ClipboardRead::WithoutImages,seq);} catch(...) {rejected=true;}
require(rejected,"resident rejects images before reading their data");
{
ks::ClipboardSnapshot snapshot;
try {snapshot.capture(w,seq-1); rejected=false;} catch(...) {rejected=true;}
require(rejected,"stale image snapshot is rejected");
snapshot.capture(w,seq);
}
require(GetClipboardSequenceNumber()==seq,"discarding an image snapshot leaves the clipboard untouched");
{
ks::ClipboardSnapshot snapshot; snapshot.capture(w,seq);
auto stale=ks::writeClipboard(w,ks::textClip(L"temporary"));
+9 -2
View File
@@ -84,9 +84,11 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) {
{
ks::App app(instance,false,folder/L"data");app.window=owner;
app.settings.history=false;app.settings.autoCorrect=false;app.settings.writeLog=true;
auto prepare=[&](wchar_t last=L'r') {
auto prepare=[&](wchar_t last=L'r', wchar_t prefix=0) {
if(!ks::activateWindow(target))throw std::runtime_error("isolated Far lost foreground");
key(VK_ESCAPE);key('Y',0,LEFT_CTRL_PRESSED);key(VK_OEM_1,L':',SHIFT_PRESSED);key(WORD(towupper(last)),last);
key(VK_ESCAPE);key('Y',0,LEFT_CTRL_PRESSED);
if(prefix)key(prefix==L' '?VK_SPACE:WORD(towupper(prefix)),prefix);
key(VK_OEM_1,L':',SHIFT_PRESSED);key(WORD(towupper(last)),last);
app.run.reset();app.run.window=target;app.run.layout=ks::windowLayout(target);
app.run.at=GetTickCount64();app.run.keys=L":r";
};
@@ -103,6 +105,11 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int) {
require(ks::readClipboard(owner).text()==sentinel.text(),"snippet restores original clipboard");
prepare(L'x');before=position();original=row();expand(L"rider .{enter}");
require(row()==original && position().X==before.X,"mismatched trigger restores original caret and never executes Enter");
prepare(L'r',L'x');before=position();original=row();expand(L"rider .");
require(row()==original && position().X==before.X,"trigger inside a word restores original caret");
prepare(L'r',L' ');before=position();expand(L"rider .");
require(row().substr(before.X-3,8)==L" rider ." && position().X==before.X+5,
"trigger after a space preserves the separator");
prepare();before=position();original=row();expand(L"left{cursor}right");
require(row().substr(before.X-2,9)==L"leftright" && position().X==before.X+2,"cursor marker uses Far selection semantics");
prepare();before=position();original=row();expand(L"first\nsecond{enter}");
+32 -1
View File
@@ -460,6 +460,34 @@ function startTerminalFixture() {
([IO.File]::ReadAllLines($listing) -ccontains 'zzzz-dir-second')
}
Write-Output 'Verified repeated dir commands in the same terminal with file panes hidden and visible.'
$rightChild = Join-Path $rightDir "Command's [folder]"
[void][IO.Directory]::CreateDirectory($rightChild)
$childRow = "[$([IO.Path]::GetFileName($rightChild))]"
Wait-Until 'new folder in the right panel' { (Find-Row $right $childRow) -ge 0 }
$keys.SendKeys('{TAB}')
Send-InteractiveTerminal 'cmd /d /c "cd > panel-cwd.txt"'
Wait-Until 'native command running in the newly active right panel' {
(Test-Path -LiteralPath (Join-Path $rightDir 'panel-cwd.txt')) -and
(Find-Row $right 'panel-cwd.txt') -ge 0
}
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr](Find-Row $right $childRow), [IntPtr]::Zero)
Press-Enter $inputBox
$rightPath = [FilesActivationUi]::GetDlgItem($window, 143)
Wait-Until 'navigation to the right panel subfolder' { (Read-Text $rightPath) -ceq $rightChild }
Send-InteractiveTerminal 'cmd /d /c "cd > child-cwd.txt"'
Wait-Until 'native command running in the navigated folder' {
(Test-Path -LiteralPath (Join-Path $rightChild 'child-cwd.txt')) -and
(Find-Row $right 'child-cwd.txt') -ge 0
}
Send-InteractiveTerminal 'cd ..'
Wait-Until 'PowerShell cd navigating the right panel' { (Find-Row $right 'panel-cwd.txt') -ge 0 }
$keys.SendKeys('{TAB}')
Send-InteractiveTerminal 'cmd /d /c "cd > left-cwd.txt"'
Wait-Until 'native command running back in the left panel' {
(Test-Path -LiteralPath (Join-Path $leftDir 'left-cwd.txt')) -and
(Find-Row $left 'left-cwd.txt') -ge 0
}
Write-Output 'Verified native commands follow panel switches and folder navigation in the same PowerShell session.'
$marker=Join-Path $root 'webview-enter.txt'
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$command)
@@ -470,7 +498,10 @@ function startTerminalFixture() {
!(Read-Text $inputBox)
}
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
Select-Row $left '[Test folder]'
# The left panel is already active after the working-directory check.
$folderRow = Find-Row $left '[Test folder]'
if ($folderRow -lt 0) { throw 'Missing folder for the terminal clipboard check.' }
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
$outputSelection = 'terminal-output-copy-fixture'
Send-InteractiveTerminal "Write-Output '$outputSelection'"
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
+156
View File
@@ -0,0 +1,156 @@
param([Parameter(Mandatory)][string]$Executable)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class ComparisonSplitterUi {
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
public struct Point { public int X, Y; }
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point);
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
[DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(18, 0, 0, UIntPtr.Zero);
keybd_event(18, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
}
'@
function Wait-For([string]$Name, [scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 50; ++$attempt) {
$value = & $Condition
if ($value) { return $value }
Start-Sleep -Milliseconds 100
}
throw "Timed out waiting for $Name."
}
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance'
$saved = @{}
foreach ($name in $names) {
if ($name -in $preferences.GetValueNames()) {
$saved[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
}
}
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
$root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N'))
$dpi = [ComparisonSplitterUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
$process = $null
try {
$left = Join-Path $root 'left'
$right = Join-Path $root 'right'
[void][IO.Directory]::CreateDirectory($left)
[void][IO.Directory]::CreateDirectory($right)
[IO.File]::WriteAllText((Join-Path $left 'sample.txt'), "one`ntwo")
[IO.File]::WriteAllText((Join-Path $right 'sample.txt'), "one`nthree")
$preferences.SetValue('LeftPath', $left)
$preferences.SetValue('RightPath', $right)
foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance') {
$preferences.DeleteValue($name, $false)
}
$process = Start-Process -FilePath (Resolve-Path -LiteralPath $Executable) -PassThru
$main = Wait-For 'the Files window' {
$process.Refresh()
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
}
foreach ($id in 102, 103) {
$panel = [ComparisonSplitterUi]::GetDlgItem($main, $id)
[void](Wait-For 'the test file in the panel' {
[ComparisonSplitterUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2
})
[void][ComparisonSplitterUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
}
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr]132, [IntPtr]::Zero)
$picker = [ComparisonSplitterUi]::GetDlgItem($main, 121)
[void](Wait-For 'the Commands menu' { [ComparisonSplitterUi]::IsWindowVisible($picker) })
$row = -1
$count = [ComparisonSplitterUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
for ($i = 0; $i -lt $count; ++$i) {
$label = [Text.StringBuilder]::new(128)
[void][ComparisonSplitterUi]::Read($picker, 393, [IntPtr]$i, $label)
if ($label.ToString() -like 'Compare files*') { $row = $i; break }
}
if ($row -lt 0) { throw 'Missing Compare files command.' }
[void][ComparisonSplitterUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero)
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr](0x20000 + 121), $picker)
$list = Wait-For 'the foreground comparison list' {
$dialog = [IntPtr]::Zero
while (($dialog = [ComparisonSplitterUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
[uint32]$ownerPid = 0
[void][ComparisonSplitterUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
if ($ownerPid -ne $process.Id) { continue }
$control = [ComparisonSplitterUi]::GetDlgItem($dialog, 402)
if ([ComparisonSplitterUi]::IsWindowVisible($control) -and [ComparisonSplitterUi]::Activate($dialog)) {
return $control
}
}
}
$bounds = [ComparisonSplitterUi+Rect]::new()
[void][ComparisonSplitterUi]::GetClientRect($list, [ref]$bounds)
$middle = [int]($bounds.Right / 2)
$destination = [int]($bounds.Right * 0.65)
$mouseY = 30 -shl 16
[void][ComparisonSplitterUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
for ($x = $middle + 5; $x -lt $destination; $x += 5) {
[void][ComparisonSplitterUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
}
[void][ComparisonSplitterUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
$origin = [ComparisonSplitterUi+Point]::new()
[void][ComparisonSplitterUi]::ClientToScreen($list, [ref]$origin)
$bitmap = [Drawing.Bitmap]::new($bounds.Right, 1)
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try { $graphics.CopyFromScreen($origin.X, ($origin.Y + $bounds.Bottom - 10), 0, 0, $bitmap.Size) }
finally { $graphics.Dispose() }
$ink = @(for ($x = $middle - 4; $x -le $destination + 4; ++$x) {
if ($bitmap.GetPixel($x, 0).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x }
})
# Desktop scaling can spread the single-pixel divider across two adjacent screen pixels.
if (!$ink.Count -or $ink.Count -gt 2 -or [Math]::Abs($ink[0] - $destination) -gt 1 -or
($ink.Count -eq 2 -and $ink[1] - $ink[0] -ne 1)) {
throw "Expected one divider under the last row at $destination. Found $($ink.Count) marked pixels, starting at $($ink | Select-Object -First 8)."
}
} finally { $bitmap.Dispose() }
'Verified that dragging leaves exactly one divider below the file contents.'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $preferences.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $preferences.DeleteValue($name, $false) }
}
$preferences.Dispose()
if ($dpi) { [void][ComparisonSplitterUi]::SetThreadDpiAwarenessContext($dpi) }
if (Test-Path -LiteralPath $root) {
$resolved = (Resolve-Path -LiteralPath $root).Path
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-files-splitter-*') {
Remove-Item -LiteralPath $resolved -Recurse -Force
}
}
}
+55 -3
View File
@@ -117,6 +117,18 @@ function Scintilla($Window) {
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
}
function Assert-ReopenedMarkdown($Window, $File) {
try { Browser 'reopen' '' $File }
finally {
if ([MarkdownUi]::IsWindowVisible((Scintilla $Window))) { throw "$File opened as raw text." }
}
}
function Close-Preview($Window) {
Post $Window 0x10 0
[void](Wait-For 'the Markdown preview to close' { ![MarkdownUi]::IsWindowVisible($Window) })
}
function Assert-TextWindowAppearance($Window, [string]$Mode) {
$identity = "HrynCo.KSwitcher.Files.$Mode"
$resource = if($Mode -eq 'Editor') { ',-104' } else { ',-103' }
@@ -189,7 +201,7 @@ try {
~~~mermaid
flowchart TD
A[Render target] --> B[Result]
A[Render target] -->|Transition| B[Result]
~~~
~~~mermaid
@@ -204,6 +216,8 @@ const value = 42;
'@
$original = Join-Path $docs 'Preview.md'
[IO.File]::WriteAllText($original,$fixture)
[IO.File]::WriteAllText("$docs\Reopen.md",'# Reopened Markdown')
[IO.File]::WriteAllText("$docs\Second.md",'# Second Markdown')
$childText = '# Linked Markdown' + "`n`n" + (("Filler paragraph.`n`n") * 60) + '## Target heading'
[IO.File]::WriteAllText("$docs\child\Other.md",$childText)
[IO.File]::WriteAllText("$docs\Plain.txt",'Plain text')
@@ -235,6 +249,30 @@ const value = 42;
[MarkdownUi]::Activate($main)
$panel = [MarkdownUi]::GetDlgItem($main,102)
$previewScript = Join-Path $app 'terminal\markdown.js'
$originalScript = [IO.File]::ReadAllText($previewScript)
try {
# Let the page load without sending the ready message until Files starts a new WebView.
[IO.File]::WriteAllText($previewScript,"document.documentElement.dataset.startup = 'stalled';")
Open-File 'Reopen.md' 0x72
$window = Wait-For 'the stalled Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Reopen.md' }
Browser 'startup-stalled'
} finally { [IO.File]::WriteAllText($previewScript,$originalScript) }
Assert-ReopenedMarkdown $window 'Reopen.md'
Close-Preview $window
Write-Output 'Verified that the same viewer renders Markdown after a stalled WebView2 startup.'
Open-File 'Reopen.md' 0x72
$window = Wait-For 'the Markdown viewer before early close' { Find-Window 'KSwitcher.Files.Text' 'Reopen.md' }
Close-Preview $window
foreach ($file in 'Reopen.md','Second.md','Reopen.md','Second.md','Reopen.md','Second.md') {
Open-File $file 0x72
$window = Wait-For "the reopened $file viewer" { Find-Window 'KSwitcher.Files.Text' $file }
Assert-ReopenedMarkdown $window $file
Close-Preview $window
}
Write-Output 'Verified six immediate Markdown reopens after closing the initial preview during startup.'
Open-File 'Preview.md' 0x72
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
@@ -276,7 +314,18 @@ const value = 42;
[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.' }
Browser 'toggle-first-task'
$checkedFixture=$fixture.Replace('- [ ] Pending','- [x] Pending')
[void](Wait-For 'Markdown checkbox saved to the source file' { [IO.File]::ReadAllText($original) -ceq $checkedFixture })
Browser 'close'
[void](Wait-For 'the initial preview to close' { ![MarkdownUi]::IsWindowVisible($window) })
[MarkdownUi]::Activate($main)
Wait-Foreground $main
Open-File 'Preview.md' 0x72
$window=Wait-For 'the reopened Markdown preview' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
Browser 'first-task-checked'
Browser 'toggle-first-task'
[void](Wait-For 'the unchecked Markdown marker to save' { [IO.File]::ReadAllText($original) -ceq $fixture })
[IO.File]::WriteAllText($original,($fixture.Replace('Перегляд Markdown','Зміна на диску')))
Browser 'Зміна на диску' '' 'Preview.md'
$replacement = Join-Path $docs 'Preview-replacement.md'
@@ -393,7 +442,8 @@ const value = 42;
}
Post $control 0x100 0x75
Answer-Save 7
Post $window 0x10 0
Browser 'external-replacement'
Browser 'close'
[void](Wait-For 'the conflict fixture to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Plain.txt' 0x72
@@ -437,6 +487,8 @@ const value = 42;
$window = Wait-For 'the LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Loopback peer' }
[void](Assert-TextWindowAppearance $window 'Viewer')
Browser 'render'
Browser 'toggle-first-task'
[void](Wait-For 'Markdown checkbox uploaded to the LAN peer' { [IO.File]::ReadAllText($original) -ceq $checkedFixture })
Browser 'search'
Browser 'edit'
if ((Wait-For 'LAN F6 editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }) -ne $window) {
+55 -2
View File
@@ -117,6 +117,14 @@ try {
'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(`(() => {
const paths = document.querySelector('figure svg g.edgePaths');
const labels = document.querySelector('figure svg g.edgeLabels');
const background = labels?.querySelector('.edgeLabel rect');
return !!(paths && labels && background && labels.textContent.includes('Transition') &&
(paths.compareDocumentPosition(labels) & Node.DOCUMENT_POSITION_FOLLOWING) &&
getComputedStyle(background).opacity === '1');
})()`), true);
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
document.querySelector('main').textContent.includes('Invalid Mermaid diagram')`), true);
assert.equal(await evaluate(`!!document.querySelector('pre code.language-js') && !document.querySelector('iframe')`), true);
@@ -125,14 +133,59 @@ try {
await waitFor(() => evaluate(`document.querySelector('img[alt="Missing image"]')?.title === 'Image unavailable'`),
'missing image feedback');
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => box.checked)`), [false, true]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [true, false]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [false, true]);
if (artifact) {
const { cssContentSize } = await command('Page.getLayoutMetrics');
const { data } = await command('Page.captureScreenshot', { captureBeyondViewport: true,
clip: { x:0, y:0, width:cssContentSize.width, height:Math.min(cssContentSize.height, 620), scale:1 } });
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} else if (scenario === 'startup-stalled') {
await waitFor(() => evaluate(`document.documentElement?.dataset.startup === 'stalled'`),
'the preview page to load without announcing readiness');
} else if (scenario === 'reopen') {
const heading = title === 'Reopen.md' ? 'Reopened Markdown' : 'Second Markdown';
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
document.querySelector('h1')?.textContent === ${JSON.stringify(heading)}`), heading);
assert.equal(await evaluate(`performance.getEntriesByName(new URL('mermaid.js', location.href).href).length`),
0, 'Reopening a document without diagrams must not load Mermaid');
} else if (scenario === 'external-replacement') {
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
document.querySelector('main')?.textContent.trim() === 'An external replacement'`),
'the replacement file rendered after discarding edits');
} else if (scenario === 'diagram-reference') {
await waitFor(() => evaluate("document.documentElement.classList.contains('rendered')"), 'rendered diagram page');
const diagram = await evaluate(`(() => {
const svg = document.querySelector('figure svg');
const paths = svg?.querySelector('g.edgePaths');
const labels = svg?.querySelector('g.edgeLabels');
return {
error: document.querySelector('pre code.language-mermaid')?.parentElement.previousElementSibling?.title,
labels: [...(labels?.querySelectorAll('.edgeLabel') ?? [])]
.map(label => label.textContent.trim()).filter(Boolean),
paintedAbove: !!(paths && labels &&
(paths.compareDocumentPosition(labels) & Node.DOCUMENT_POSITION_FOLLOWING)),
opaque: [...(labels?.querySelectorAll('.edgeLabel rect') ?? [])].every(rect =>
getComputedStyle(rect).opacity === '1'),
};
})()`);
assert.equal(diagram.error, undefined, diagram.error);
assert.deepEqual(diagram.labels.sort(), ['F3', 'F6', 'F6']);
assert.equal(diagram.paintedAbove && diagram.opaque, true);
if (artifact) {
const { data } = await command('Page.captureScreenshot');
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} else if (scenario === 'toggle-first-task' || scenario === 'first-task-checked') {
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
!!document.querySelector('main li.task input')`), 'rendered Markdown task');
if (scenario === 'toggle-first-task') {
const target = "document.querySelector('main li.task input')";
const before = await evaluate(target + '.checked');
await evaluate(target + '.click()');
await waitFor(() => evaluate(`!pendingTask && ${target}.checked !== ${before}`), 'saved Markdown task');
}
else
assert.equal(await evaluate(`document.querySelector('main li.task input').checked`), true);
} else if (scenario === 'search-menu' || scenario === 'search') {
const searchFocused = 'document.activeElement === document.getElementById("search-query")';
const searchClosed = 'document.getElementById("search").hidden';
+54
View File
@@ -42,6 +42,10 @@ struct InputRegressionAccess
++*reinterpret_cast<int *>(context);
return DefSubclassProc(window, message, wp, lp);
}, 1, reinterpret_cast<DWORD_PTR>(&hideCount));
expireRun(app);
}
static void expireRun(App &app)
{
std::lock_guard lock(app.stateMutex);
app.run.at = GetTickCount64() - 2500;
}
@@ -867,6 +871,54 @@ LRESULT CALLBACK procedure(HWND w, UINT msg, WPARAM wp, LPARAM lp)
pasteBehavior = 0;
finish();
break;
case 84:
saved = ks::readClipboard(app->window, 64 * 1024 * 1024);
captured = true;
app->ownSequence = ks::writeClipboard(app->window, ks::textClip(sentinel));
app->settings.snippets = {{L";r", L"rider ."}, {L"[g", L"expanded"}};
app->settings.autoCorrect = false;
ActivateKeyboardLayout(app->layouts[ru].handle, 0);
prepare(L"", false);
typeKeys({'G', 'J', 'L', 'L', 'T', VK_OEM_1, 'R'});
break;
case 85:
require(text() == L"поддежк", "layout variant does not expand at the end of a word");
prepare(L"поддека", false);
SendMessageW(field, EM_SETSEL, 5, 5);
typeKeys({VK_OEM_1, 'R'});
break;
case 86:
require(text() == L"поддежкка", "layout variant does not expand at a caret inside existing text");
require(LOWORD(SendMessageW(field, EM_GETSEL, 0, 0)) == 7,
"skipping expansion restores the caret before the rest of the word");
prepare(L"", false);
typeKeys({'G', 'J', 'L', 'L', 'T'});
break;
case 87:
require(text() == L"подде", "editor received the first part of the word");
ks::InputRegressionAccess::expireRun(*app);
typeKeys({VK_OEM_1, 'R'});
break;
case 88:
require(text() == L"поддежк", "layout variant does not expand after the typing buffer expires");
prepare(L"prefix (", false);
typeKeys({VK_OEM_1, 'R'});
break;
case 89:
require(text() == L"prefix (rider .", "layout variant expands after punctuation");
prepare(L"token_", false);
typeKeys({VK_OEM_4, 'G'});
break;
case 90:
require(text() == L"token_хп", "word boundary also applies to other trigger prefixes");
prepare(L"", false);
typeKeys({VK_OEM_4, 'G'});
break;
case 91:
require(text() == L"expanded", "another layout variant expands at the start of the field");
require(ks::readClipboard(app->window).text() == sentinel, "word boundary check restores the clipboard");
finish();
break;
case 20:
if (!captured)
{
@@ -1182,6 +1234,8 @@ int main(int argc, char **argv)
stage = 64;
if (argc > 1 && std::string(argv[1]) == "--snippet-autocomplete")
stage = 66;
if (argc > 1 && std::string(argv[1]) == "--snippet-word-boundaries")
stage = 84;
SetTimer(host, 1, 100, nullptr);
auto forwarding = SetWindowsHookExW(WH_KEYBOARD_LL,forwardingHook,GetModuleHandleW(nullptr),0);
require(forwarding!=nullptr,"downstream forwarding fixture installed before application hook");
+64 -4
View File
@@ -319,10 +319,10 @@ void hubChecks()
while((hubs[0]->ready().size()!=2||hubs[1]->ready().size()!=2||hubs[2]->ready().size()!=2)&&GetTickCount64()<deadline)pump();
check(hubs[0]->ready().size()==2&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"three TCP hubs authenticate all independent pair channels on one listener per PC");
auto generation=hubs[0]->ready();
for(auto &list:endpoints)for(auto &e:list)e.address=0;
for(auto &list:endpoints)for(auto &e:list){e.address=0;e.discovered=false;}
for(int n=0;n<20;++n)pump();
check(hubs[0]->ready()==generation&&hubs[1]->ready().size()==2&&hubs[2]->ready().size()==2,"expired discovery does not destroy authenticated channels");
for(auto &list:endpoints)for(auto &e:list)e.address=htonl(INADDR_LOOPBACK);
for(auto &list:endpoints)for(auto &e:list){e.address=htonl(INADDR_LOOPBACK);e.discovered=true;}
InputFrame keyFrame{InputType::Key,7,'A',0,1},cross{InputType::Cross,8,2,30000};
hubs[0]->poll(endpoints[0],{{ids[1],keyFrame},{ids[2],cross}},incoming[0],GetTickCount64());
for(int n=0;n<100&&(incoming[1].empty()||incoming[2].empty());++n)pump();
@@ -340,16 +340,76 @@ void hubChecks()
for(int n=0;n<300&&(server.ready().empty()||client.ready().empty());++n){
server.poll(unknown,{},a,GetTickCount64());client.poll(known,{},b,GetTickCount64());Sleep(1);
}
check(server.ready().size()==1&&client.ready().size()==1,"saved pair listens and authenticates without receiving a discovery announcement");
check(server.ready().size()==1&&client.ready().size()==1,"available peer can accept inbound TCP without dialing");
}
endpoints[0].erase(endpoints[0].begin());hubs[0]->poll(endpoints[0],{},incoming[0],GetTickCount64()+1800);
check(!hubs[0]->ready().contains(ids[1])&&hubs[0]->ready().contains(ids[2]),"forgetting one pair revokes only its channel");
}
void offlineDiscoveryChecks()
{
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
struct Close{~Close(){WSACleanup();}} close;
std::string a(32,'a'),b(32,'b'),key(64,'f');
const auto pa=freePort(),pb=freePort();
InputHub left(a,pa),right(b,pb);
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),pb,false}},eb{{a,key,htonl(INADDR_LOOPBACK),pa,false}};
std::vector<RoutedInput> ia,ib;
int datagrams=0;
left.datagrams([&](const auto &,const auto &){++datagrams;});
auto now=GetTickCount64();
auto pump=[&](uint64_t step=1){now+=step;right.poll(eb,{},ib,now);left.poll(ea,{},ia,now);};
auto checkIdle=[&]{
check(left.onlinePeers()==0&&left.ready().empty()&&!left.needsHelp()&&datagrams==0,
"offline saved peer does not trigger input retries or connection help");
SOCKET probe=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
sockaddr_in addr{};addr.sin_family=AF_INET;addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);addr.sin_port=htons(pa);
int result=connect(probe,(sockaddr*)&addr,sizeof(addr));
const auto error=WSAGetLastError();closesocket(probe);
check(result==SOCKET_ERROR&&error==WSAECONNREFUSED,"input TCP listener is closed while all peers are offline");
};
pump();pump(20000);checkIdle();
auto rediscover=[&]{
ea.front().discovered=eb.front().discovered=true;
for(int n=0;n<200&&(left.ready().empty()||right.ready().empty());++n){pump(20);Sleep(1);}
check(left.onlinePeers()==1&&left.ready().contains(b)&&right.ready().contains(a),
"input TCP connects when the saved peer reappears in discovery");
};
rediscover();
const auto oldEpoch=left.ready().at(b);
ea.front().discovered=false;
eb.clear(); // The other instance stops while discovery is already stale.
for(int n=0;n<30;++n){pump(20);Sleep(1);}
pump(20000);checkIdle();
eb={{a,key,htonl(INADDR_LOOPBACK),pa,false}};
rediscover();
check(left.ready().at(b)!=oldEpoch,"rediscovery replaces the disconnected input generation");
}
void fallbackChecks()
{
WSADATA data{};if(WSAStartup(MAKEWORD(2,2),&data))throw std::runtime_error("WSAStartup");
struct Close{~Close(){WSACleanup();}} close;
std::string a(32,'a'),b(32,'b'),key(64,'f');
{
auto pa=freePort(),pb=freePort();InputHub left(a,pa),right(b,pb);
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),pb}},eb{{a,key,0}};
std::vector<RoutedInput> ia,ib;
int datagrams=0;
left.datagrams([&](const auto &,const auto &){++datagrams;});
auto now=GetTickCount64();
right.poll(eb,{},ib,now); // Listen, but delay reading and authenticating the TCP connection.
left.poll(ea,{},ia,now);
for(int n=0;n<100&&left.status().find("authenticating")==std::string::npos;++n){
Sleep(1);left.poll(ea,{},ia,now+1);
}
check(left.status().find("authenticating")!=std::string::npos,"TCP connection is waiting for the peer handshake");
now+=6000;
left.poll(ea,{},ia,now);
for(int n=0;n<100&&(left.ready().empty()||right.ready().empty());++n){
++now;right.poll(eb,{},ib,now);left.poll(ea,{},ia,now);Sleep(1);
}
check(left.ready().contains(b)&&right.ready().contains(a)&&datagrams==0,
"UDP fallback does not cancel a TCP handshake within its deadline");
}
for(bool udp:{false,true}){
auto pa=freePort(),pb=freePort(),blocked=freePort();InputHub left(a,pa),right(b,pb);
std::vector<InputEndpoint> ea{{b,key,htonl(INADDR_LOOPBACK),blocked}},eb{{a,key,htonl(INADDR_LOOPBACK),udp?blocked:pa}};
@@ -507,6 +567,6 @@ void channelChecks()
}
int main()
{
try{channelChecks();hubChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
try{channelChecks();hubChecks();offlineDiscoveryChecks();fallbackChecks();datagramChecks();routerChecks();meshChecks();std::cout<<"Passed "<<passed<<" LAN input checks\n";}
catch(const std::exception &e){std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;}
}