Compare commits

...
36 Commits
Author SHA1 Message Date
agrynco 524a2d4329 Release KSwitcher v0.6.116 (#62)
Show folder reading progress and allow partial results. Improve terminal file-open output and history.
2026-11-17 20:27:27 +02:00
agrynco 5bca97f864 Record the v0.6.116 package manifest and checksum 2026-11-17 20:26:36 +02:00
agrynco 0d714147ea Prepare KSwitcher v0.6.116 with cancellable folder scans 2026-11-17 20:26:09 +02:00
agrynco a0aeb62270 Release KSwitcher v0.6.115 (#61)
Add Shift+F4, prevent editor flicker, and record file launches as short start commands.
2026-11-17 17:30:07 +02:00
agrynco 4be9b24c4b Record the v0.6.115 package manifest and checksum 2026-11-17 17:29:31 +02:00
agrynco 9c30dd91b4 Prepare KSwitcher v0.6.115 with new files and concise open history 2026-11-17 17:27:08 +02:00
agrynco 5ba51ebb00 Release KSwitcher v0.6.114 (#60)
Move the active pane highlight directly to the clicked row.
2026-11-17 16:35:49 +02:00
agrynco 2bc6eb60c9 Record the v0.6.114 package manifest and checksum 2026-11-17 16:35:40 +02:00
agrynco 9c1badcb45 Prepare KSwitcher v0.6.114 with direct panel cursor highlighting 2026-11-17 16:30:18 +02:00
agrynco 9dcc20673a Release KSwitcher v0.6.113 (#59)
Prevent the terminal startup flash and stabilize the clipboard regression test.
2026-11-17 16:14:27 +02:00
agrynco ec4079b346 Record the v0.6.113 package manifest and checksum 2026-11-17 16:13:36 +02:00
agrynco 41cef4d4f3 Prepare KSwitcher v0.6.113 with a dark terminal from startup 2026-11-17 16:11:41 +02:00
agrynco b53b5715ab Release KSwitcher v0.6.112 (#58)
Add backward Ctrl+Shift+Tab cycling in Files, Editor and Viewer.
2026-11-17 15:45:25 +02:00
agrynco 01f44d22b5 Record the v0.6.112 package manifest and checksum 2026-11-17 15:44:36 +02:00
agrynco c78090f7d4 Prepare KSwitcher v0.6.112 with reverse Files window cycling 2026-11-17 15:42:44 +02:00
agrynco 0d797c4f35 Release KSwitcher v0.6.111 (#57)
Ship faster Files folder navigation, panel shortcuts, and Far-style scrollbars.
2026-11-17 15:35:12 +02:00
agrynco b6eaa2c85d Use stripped binaries in the v0.6.111 portable archive 2026-11-17 15:30:50 +02:00
agrynco 72024c3385 Record the v0.6.111 package manifest and legacy upgrade instructions 2026-11-17 15:29:03 +02:00
agrynco d60ef626f0 Prepare KSwitcher v0.6.111 with Files navigation and scrollbars 2026-11-17 15:23:22 +02:00
agrynco e144cd6607 Release KSwitcher v0.6.110 (#56)
Fix unrelated panel repaint and preserve uppercase personal dictionary corrections.
2026-11-17 14:16:03 +02:00
agrynco 05a3f7a8f4 Record the package manifest for KSwitcher v0.6.110 2026-11-17 14:15:41 +02:00
agrynco 12b8f5090c Release KSwitcher v0.6.110 with panel repaint and uppercase correction fixes
Refresh only the affected panel after folder navigation. Preserve uppercase when the target is in the personal dictionary.
2026-11-17 14:10:59 +02:00
agrynco 19d574edcf Release KSwitcher v0.6.109 (#55)
Digit-specific folder shortcuts and support for hyphenated personal words.

Refs #23
2026-11-17 13:31:18 +02:00
agrynco 3840744819 Record the package manifest for KSwitcher v0.6.109 2026-11-17 13:30:44 +02:00
agrynco 94e8ba4304 Release KSwitcher v0.6.109 with digit-specific folder shortcuts
Use Ctrl+0–9 to open each folder group and Ctrl+F1/F2 for panel modes. Allow internal hyphens in personal dictionary entries. Synchronize the rendered Files tests with asynchronous directory scans.

Refs #23
2026-11-17 13:28:25 +02:00
agrynco edb1440be0 Release KSwitcher v0.6.108 (#53)
Wake-on-LAN for offline paired PCs in KSwitcher Files.
2026-11-17 10:56:54 +02:00
agrynco 8ef13ca9bd Record the package manifest for KSwitcher v0.6.108 2026-11-17 10:56:21 +02:00
agrynco c0eca89738 Release KSwitcher v0.6.108 with Wake-on-LAN in Files 2026-11-17 10:55:01 +02:00
agrynco 0b6709495b Release KSwitcher v0.6.107 (#52)
Files command suggestions, contextual Windows help, and the FAR-style icon.
2026-11-16 23:12:42 +02:00
agrynco 5f0c51b557 Restore command suggestions after focus returns
Refs #8
2026-11-16 23:12:36 +02:00
agrynco 733b6deefa Record the package manifest for KSwitcher v0.6.107 2026-11-16 23:08:28 +02:00
agrynco b3a1e762ec Release KSwitcher v0.6.107 with Files command completion
Refs #8
Refs #18
2026-11-16 23:06:09 +02:00
agrynco 219bdd4883 Keep release ZIPs out of the source tree 2026-11-16 20:00:09 +02:00
agrynco d018b91397 Release KSwitcher v0.6.106 (#51) 2026-11-16 19:51:19 +02:00
agrynco 2d4df0daa8 Record the package manifest for KSwitcher v0.6.106 2026-11-16 19:48:04 +02:00
agrynco 773df250a4 Release KSwitcher v0.6.106 with responsive Files operations 2026-11-16 19:45:45 +02:00
65 changed files with 7634 additions and 1071 deletions

No files matched your search

+6 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.105 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.116 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
@@ -7,6 +7,10 @@ set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico")
include(cmake/FilesTextLibraries.cmake)
set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files")
target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
@@ -56,6 +60,7 @@ set_target_properties(KSwitcherConfig PROPERTIES OUTPUT_NAME "KSwitcher.Config")
target_compile_definitions(KSwitcherConfig PRIVATE KS_CONFIG_APP)
target_link_libraries(KSwitcherConfig PRIVATE kscore)
add_executable(KSwitcherTests tests/tests.cpp)
target_include_directories(KSwitcherTests PRIVATE vendor)
add_executable(KSwitcherSyncTests tests/sync.cpp)
target_include_directories(KSwitcherSyncTests PRIVATE vendor)
target_link_libraries(KSwitcherSyncTests PRIVATE kscore)
+95 -12
View File
@@ -1,6 +1,7 @@
# Оформлення KSwitcher Files
Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far.
Іконка головного вікна показує дві сині панелі з бірюзовою рамкою та виділеним рядком.
Власні модальні діалоги панелей, редактора й переглядача використовують
`FilesModalDialog`. Escape і клік поза діалогом у клієнтській області Files
@@ -18,6 +19,10 @@ Far Manager є зразком для оформлення файлового м
не займають місця. Перед завершенням змін перевір коротке повідомлення й
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
Панелі, списки попапів і довгі повідомлення використовують вузьку смугу
прокрутки зі стрілками вгорі й унизу та крапковою доріжкою. Відтінки доріжки
й повзунка залежать від фону, на якому вони малюються. Повзунок світліший
за доріжку й показує положення та розмір видимої частини списку.
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
Warning і початковий фокус на No.
@@ -32,24 +37,67 @@ Warning і початковий фокус на No.
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
панелі LAN, спочатку скопіюй його до локальної папки.
Після успішного відкриття локального файла через Windows його шлях
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
його курсор приховано. При виборі
з історії у командний рядок підставляється команда, яка повторює відкриття.
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
- У головному вікні клавіатурний фокус залишається в командному рядку.
Tab перемикає активну панель, клік вибирає рядок, а стрілки вгору й вниз,
Page Up і Page Down пересувають курсор у панелі навіть під час набору команди.
Tab без модифікаторів перемикає активну панель, а клік вибирає рядок.
Ctrl+U міняє видимі панелі місцями разом із їхніми папками, режимами,
курсорами й позначками. Активна панель залишається активною на новому боці.
Page Up і Page Down пересувають курсор у панелі. Стрілки вгору й вниз
керують панеллю, коли список підказок закритий.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
курсора він мав інше оформлення.
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
текст із буфера обміну в позицію курсора або замінюють виділення.
Enter і Shift+Enter спочатку виконують введену команду. Коли рядок
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
виконує команду одразу. Коли рядок
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
Enter передає порожній рядок у термінал. Escape очищає рядок.
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
Під час запуску термінала область виводу має темне тло, поки WebView2
готує сторінку.
Промпт і текст команди вирівняні по спільній базовій лінії.
- Під час набору локальної команди над полем з’являються підказки PowerShell.
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
та шляхи відносно робочої папки термінала або активної панелі до запуску
термінала. Після `cd ` список пропонує папки,
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
Enter вставляє виділену, а клік вставляє підказку під вказівником.
Щоб виконати команду після вставлення, натисни Enter ще раз.
Escape закриває список зі збереженням тексту. Без списку Escape очищає
рядок, а Tab перемикає панель, якщо панелі відкриті. Доступні підказки стандартної локальної
сесії PowerShell, включно з програмами з PATH. Для команд без аргументів,
як-от `cls`, список не пропонує шляхи.
Для `dotnet` підкоманди й параметри підказує встановлений .NET SDK.
Для `git` підкоманди, параметри й доречні назви гілок бере штатний
скрипт Git for Windows. Підказки використовують локальні дані репозиторію.
- Довідник Windows Commands надає офлайн підказки ключів і підкоманд для
системних утиліт. Наприклад, `ipconfig /re` пропонує `/release` і `/renew`,
`reg q` пропонує `query`, а `cmd /c dir /` пропонує ключі `dir` для CMD.
Каталог також підказує вкладені підкоманди та значення, перелічені в
синтаксисі. Наприклад, `netsh interface ipv4 show co` пропонує `config`,
а `schtasks /query /fo ` пропонує `CSV`, `LIST` і `TABLE`. F1 у командному
рядку відкриває статтю Microsoft Learn для поточної команди чи підкоманди.
Якщо ввести `dir` безпосередньо у Files, PowerShell підказує власні параметри.
Після `ipconfig /renew ` або `ipconfig /release ` список підказує назви
локальних адаптерів із DHCP для IPv4. Назви з пробілами вставляються в лапках.
- Коли курсор у кінці рядка, список спочатку показує до 5 різних
останніх команд з історії, які починаються з набраного тексту.
Вибір підставляє всю команду. Підказки з історії доступні й у LAN-панелі.
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
що й клавіша F8.
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
@@ -69,6 +117,15 @@ Warning і початковий фокус на No.
**Options → Command line → Command history → Allow paired PCs to hibernate this PC**.
Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Для цієї дії
потрібні оновлення на обох ПК і ввімкнена гібернація Windows.
- У **Change drive** (Alt+F1 або Alt+F2) підкреслена дія **Wake** є праворуч
від стану офлайн-ПК. Клік по слову або Enter з фокусом на дії надсилає пакет.
Статус відображається на тлі списку. Для текстових дій усередині рядків
використовуй спільний компонент `InlineListAction` для малювання, фокуса
й обробки кліків. KSwitcher
має зберегти MAC-адресу мережевого адаптера. Оновіть KSwitcher та дайте
обом ПК побачити один одного в локальній мережі. На цільовому ПК потрібна
підтримка Wake-on-LAN у прошивці та налаштуваннях адаптера. Рядок стану
повідомляє про надсилання пакета або відсутність збереженої MAC-адреси.
- **F9 → Commands → Update remote KSwitcher** запускає штатне оновлення для
ПК активної LAN-панелі. Підтвердження з іменем ПК показується у Files
відправника. На цільовому ПК потрібен дозвіл **Options → Command line →
@@ -83,6 +140,18 @@ Warning і початковий фокус на No.
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
панелі показує «Reading» з лічильником прочитаних файлів і папок та
підказкою [Esc].
До завершення читання панель зберігає попередній список. Escape зупиняє
сканування активної панелі й відкриває прочитану частину папки. Якщо
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
повторює сканування, щоб отримати повний список. Після переходу
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
панель не перемальовується через цей перехід.
Якщо надійшов новіший запит, результат попереднього
сканування пропускається. Після підтвердження UAC очікування списку
від підвищеного процесу теж відбувається у фоні.
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
зберігаються для наявних елементів, а підраховані через F3 розміри папок
скидаються. F2 також виконує цю дію.
@@ -139,7 +208,8 @@ Warning і початковий фокус на No.
- Глобальне скорочення повертає до відкритого вікна Files у поточній сесії Windows або запускає Files, якщо такого вікна немає. Пункт **Files** у треї відкриває нове вікно.
- Ctrl+Shift+0–9 відкриває діалог Title і Path із поточною папкою. OK додає запис без дублювання, Escape скасовує. Title необов’язковий, порожнє значення показує шлях. Записи LAN зберігають ID ПК, а редагування Path залишає запис на тому самому ПК.
- Ctrl+0–9 одразу відкриває єдину папку. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису. Brief і Wide доступні в меню Left/Right та Options.
- Ctrl+0–9 відкриває лише папки, призначені натиснутій цифрі. Єдина папка відкривається одразу. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options.
## Налаштування Files
@@ -159,7 +229,13 @@ Warning і початковий фокус на No.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття.
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
порядку. Коли відкрито лише Files, активна панель не змінюється.
- Shift+F4 у локальній панелі відкриває Editor для наявного або нового файла.
Порожнє ім’я підставляє `New_File_<дата>_<час>.txt`. Новий файл з’являється
на диску після збереження. Esc після змін пропонує Save, Discard або Cancel.
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
рядків. Скасування параметрів залишає текст у редакторі.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
@@ -267,10 +343,6 @@ Warning і початковий фокус на No.
у відкритих локальних папках. Фокус залишається там, де був, а курсор
лишається на поточному елементі, якщо той ще існує.
- Ctrl+8 відкриває список усіх ярликів папок. Кожен рядок показує групу
й назву або шлях. Enter відкриває папку в активній панелі, F4 редагує
ярлик, а Delete прибирає його зі списку.
- У Change drive повідомлення No paired computers з’являється після
успішної відповіді з порожнім списком. Збої локального запиту до
KSwitcher відображаються окремо.
@@ -313,7 +385,9 @@ Warning і початковий фокус на No.
- Власні діалоги Files блокують дії панелей і командного рядка, залишаючи
системний заголовок і рамку головного вікна доступними. Клік у Files поза діалогом
діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває
підтвердження скасування.
підтвердження скасування. Перелік і обробка файлів виконуються у фоновому
потоці. Діалог залишається доступним під час очікування файлового вводу-виводу.
Скасування перевіряється між кроками операції та під час передачі блоків.
- Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No.
@@ -326,7 +400,16 @@ Warning і початковий фокус на No.
- Search і спільні нижні секції Far використовують компактні проміжки між рядками й кнопками, прив’язані до метрик моноширинного шрифту. У Search висота кнопки дорівнює висоті одного рядка.
- Нижні кнопки Far групуються по центру. Їхня ширина залежить від напису й дужок, а проміжок між ними становить приблизно половину символу.
- Прапорці Far у Search, Copy і попередженнях використовують спільний компонент. У фокусі короткий системний курсор блимає між дужками, а тло рядка зберігає колір діалогу.
- У Copy і Rename/Move помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
- У Copy і Rename/Move шлях перевіряється у фоновому потоці, і в цей час
діалог можна скасувати. Помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
- Помилки копіювання, переміщення й видалення показуються в червоному
модальному діалозі Far із причиною помилки та кнопкою OK.
- Якщо локальне перейменування або видалення заблоковане, кнопка Processes… відкриває
список процесів із назвою та PID. Перевірка папки включає вкладені елементи.
End process завершує вибраний процес після окремого підтвердження, після
чого список оновлюється. Якщо Windows обмежила доступ або перевірку
великої папки завершено частково, про це повідомляється в діалозі.
Операцію можна повторити після звільнення файла чи папки.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
+24 -16
View File
@@ -148,12 +148,14 @@ updating the application. After verifying a new package, the updater closes File
screenshot editors, Settings, and bundled StayHere for that installation. Save open work before approving an update.
If settings change in the tray while the configurator is open, a conflicting Save is rejected; reopen
the configurator to load the latest settings.
Updates from v0.3.x–v0.4.1 first install the compatible **v0.4.2 bridge** through
Update in the tray menu. Select Update again to install the full current release;
manual extraction is not required. Future full releases use stable `release-vX.Y.Z`
tags, which the bridge and newer clients recognize. Older clients ignore those tags
and continue to find the bridge instead of skipping it. Versions v0.2.3 and earlier
still require the previously documented initial configurator migration.
Updates from v0.3.x–v0.4.1 go through the compatible **v0.4.2 bridge**. If tray
**Update** does not find it, download [v0.4.2](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2),
close KSwitcher and its editors, and extract the bridge ZIP into the installation
directory while keeping personal data, dictionaries, and tools. Start v0.4.2
and select **Update** to install the current full release. Full releases use
stable `release-vX.Y.Z` tags recognized by the bridge and newer clients.
Versions v0.2.3 and earlier still require the previously documented initial
configurator migration.
Modern ZIPs contain `release-files.json` (schema, version, file paths, sizes and SHA-256
hashes). The updater validates that every packaged file is declared, all hashes match,
@@ -600,8 +602,9 @@ Pressing the history shortcut a second time pastes the second-most-recent item.
Data is in `data/` beside the executable, falling back to `%LOCALAPPDATA%/KSwitcher` when
the executable's directory is not writable. Each clipboard payload is an encrypted disk file;
only bounded previews/metadata stay in memory. Image data is loaded on demand and released when
the history popup is hidden. Settings **Write log** (`writeLog`, enabled by default) controls all
log writes. Disabling it also clears diagnostic context from memory; existing log files remain.
the history popup is hidden. Settings **Write log** (`writeLog`, off by default) controls all
log writes. Enable it when collecting diagnostics that may include typed or copied text.
Disabling it also clears diagnostic context from memory. Existing log files remain.
Diagnostic stages stay in a memory buffer of at most 128 events for 30 seconds.
Selection diagnostics include the expected text, each copied candidate before and after suffix
recovery, paced Shift+Left progress or batch delivery counts, and clipboard sequence changes,
@@ -872,7 +875,8 @@ after Space, not immediately after a punctuation key. Save Settings to apply cha
only to words with a rank at or below that number (for example, 10000). All dictionary words still
protect already valid input, and ambiguous alternatives remain unchanged regardless of this limit.
**My dictionary** provides separate English, Ukrainian and Russian fields for correct words missing
from the bundled dictionaries. Enter words separated by commas or new lines, then click OK and Save
from the bundled dictionaries. A hyphen is allowed between letters, as in `test-mt` or `dev-mt`.
Enter words separated by commas or new lines, then click OK and Save
in Settings. Case and duplicates are normalized automatically; no file editing or ranks are needed.
The v0.6.23 bundled Ukrainian dictionary includes `поточні`. The updater preserves existing dictionary files;
if upgrading from an older dictionary, add this word in My dictionary → Ukrainian and click OK → Save.
@@ -896,8 +900,10 @@ language in the configured dictionary order (the UI uses English, Ukrainian, Rus
Different valid spellings remain ambiguous and are left unchanged.
**Minimum word length** defaults to 3 and can be set from 1 to 32 letters. Surrounding punctuation
does not count toward this minimum; the maximum word length is 32 letters.
Known words, ambiguous alternatives, ALL CAPS, mixed-case identifiers, numbers, URLs and email
addresses are left unchanged. Short trailing punctuation is retained when the editor selects it
Known words, ambiguous alternatives, mixed-case identifiers, numbers, URLs and email addresses
are left unchanged. Fully uppercase words can be corrected when the target is in **My dictionary**.
For example, add `qa` under English and set the minimum word length to 2 or lower to correct
`ЙФ` to `QA` after Space. Short trailing punctuation is retained when the editor selects it
together with the word. Actual selected text is verified before replacement. Layout switching follows
the existing switch-layout setting. The configured Undo shortcut restores the original and suppresses
that word for the rest of the session (until restart).
@@ -923,8 +929,9 @@ CC BY-SA 4.0; attribution, pinned source revision and license are in `dictionari
Download the portable Windows x64 ZIP from [Gitea Releases](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases).
The [Release folder](Release/README.md) tracks the release notes, manifest and SHA-256 checksum.
Run `./package.ps1 -PublishRelease` after building and testing, then upload the generated ZIP,
manifest and checksum as release assets.
Run `./package.ps1 -PublishRelease` after building and testing. Upload `dist/KSwitcher-win-x64.zip`,
`dist/KSwitcher/release-files.json` and `Release/SHA256SUMS.txt` as Gitea release assets.
Keep the ZIP in `dist/` and attach it to the release without committing it to Git.
## Verification
@@ -992,8 +999,7 @@ Keep `v0.4.2` as the last legacy `vX.Y.Z` release. Publish full packages as
`release-vX.Y.Z` (stable, not prerelease), including `release-files.json`,
`KSwitcher-win-x64.zip` and `SHA256SUMS.txt`. Never publish a manifest package under a
legacy version tag: clients that have not installed the bridge would select it.
Keep the compatibility bridge in the first 100 releases returned by Gitea while
supporting old clients; their immutable update code only reads that page.
Legacy clients only read the first 100 releases returned by Gitea. The bridge is now outside that page. For v0.3.x–v0.4.1, follow the manual bridge installation instructions above.
### Editors that omit copied trailing spaces
@@ -1019,7 +1025,9 @@ Check **★ Pinned only** beside the history search box to show only pinned entr
History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc** closes it even when focus is on the window or an action button, releasing Windows UI allocations with the process. The resident keeps keyboard hooks, clipboard capture and history storage. Search and the pinned-only filter are preserved in encrypted view state. Each fresh opening selects and reveals the newest matching entry; background refreshes preserve the selected record while browsing. If a full-text item viewer is still open, the helper stays alive until the last viewer closes. Pin/delete, formatted/plain paste and OCR remain available; settings and default shortcuts are unchanged.
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels. 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.
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.
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.
+125 -1
View File
@@ -1,5 +1,129 @@
# Latest Windows release
## v0.6.116 — 2026-11-17
- Files displays a live count while reading a folder. **Esc** stops the scan and shows the entries already read. **Ctrl+R** reads the folder again. Mouse selection works beyond the first 65,536 rows.
- Files shows the path of files opened through Windows in the terminal and command history. Choosing a history entry still inserts the command that reopens the file. The embedded terminal hides its inactive cursor.
**Українською.**
- Files показує лічильник під час читання папки. **Esc** зупиняє читання й показує вже прочитані записи. **Ctrl+R** перечитує папку. Вибір мишею працює після перших 65 536 рядків.
- Files показує шлях до файла, відкритого через Windows, у терміналі й історії команд. Вибір запису історії підставляє команду для повторного відкриття. Вбудований термінал приховує курсор, коли він неактивний.
## v0.6.115 — 2026-11-17
- **Shift+F4** opens or creates a file in the active local panel. Leave the name blank for a generated `New_File_…txt` name. After editing a draft, **Esc → Save** opens options for the file name, encoding, BOM, and line endings.
- Typing updates the editor status line without repainting the menu or flashing the editor window.
- When **Enter** opens a local file through Windows, Files displays `start 'path'` in the terminal and saves it in command history.
**Українською.**
- **Shift+F4** відкриває або створює файл в активній локальній панелі. Якщо залишити ім’я порожнім, Files підставить `New_File_…txt`. Після редагування чернетки **Esc → Save** відкриває параметри імені, кодування, BOM і кінців рядків.
- Під час набору редактор оновлює рядок стану без перемальовування меню й миготіння вікна.
- Коли **Enter** відкриває локальний файл через Windows, Files показує `start 'шлях'` у терміналі й додає команду до історії.
## v0.6.114 — 2026-11-17
In KSwitcher Files, clicking a row in the inactive pane highlights that row immediately. The previous cursor row in that pane no longer flashes with the active highlight. If it had a custom unfocused cursor color, it returns directly to its normal style.
**Українською.**
У KSwitcher Files клік по рядку неактивної панелі одразу підсвічує вибраний рядок. Попередній рядок курсора цієї панелі більше не блимає активним підсвічуванням. Якщо він мав окремий колір неактивного курсора, рядок одразу повертається до звичайного оформлення.
## v0.6.113 — 2026-11-17
- KSwitcher Files keeps the terminal output area dark while WebView2 initializes. This fixes the white flash during startup.
- The terminal copy regression test checks for a new clipboard write and verifies its contents without first taking clipboard ownership.
**Українською.**
- Під час запуску термінала область виводу KSwitcher Files залишається темною, поки WebView2 готує сторінку. Це усуває білий спалах під час відкриття термінала.
- Тест копіювання з термінала перевіряє новий запис і його вміст без попереднього захоплення буфера обміну.
## v0.6.112 — 2026-11-17
In KSwitcher Files, **Ctrl+Shift+Tab** cycles backward through Files, Editor, and Viewer windows. **Ctrl+Tab** cycles forward. Both shortcuts wrap at the ends of the window list, including in the Markdown preview.
**Українською.**
У KSwitcher Files **Ctrl+Shift+Tab** обходить вікна Files, редактора й переглядача у зворотному порядку. **Ctrl+Tab** обходить їх у прямому порядку. Обидві комбінації працюють циклічно, зокрема в перегляді Markdown.
## v0.6.111 — 2026-11-17
- KSwitcher Files updates a panel as soon as its background folder scan finishes.
- **Ctrl+U** swaps the panels, keeping their folders, view modes, cursors, marked items, and active panel together. Use **Tab** by itself to switch the active panel. **Ctrl+Tab** cycles between Files, Editor, and Viewer windows.
- Panels and scrollable Files popups share a Far-style scrollbar with up and down arrows, a dotted track, and a thumb lighter than its background.
**Українською.**
- KSwitcher Files оновлює панель одразу після завершення фонового читання папки.
- **Ctrl+U** міняє панелі місцями разом із папками, режимами перегляду, курсорами й позначками. Активна панель залишається активною на новому боці. Для перемикання активної панелі натисніть **Tab** без модифікаторів. **Ctrl+Tab** перемикає вікна Files, редактора й переглядача.
- Панелі та попапи з прокруткою у Files мають спільний скролбар у стилі Far зі стрілками вгорі й унизу, крапковою доріжкою та повзунком, світлішим за фон.
## v0.6.110 — 2026-11-17
Entering a folder or returning to its parent in KSwitcher Files refreshes the affected panel and the command line without repainting the other panel.
Auto-correction can preserve all uppercase letters when correcting to a word in **My dictionary**. With `qa` in the English personal dictionary and **Minimum word length** set to 2 or lower, typing `ЙФ` and pressing Space yields `QA`.
**Українською.**
Під час входу в папку або повернення до батьківської папки KSwitcher Files оновлює потрібну панель і командний рядок. Сусідня панель більше не перемальовується через цей перехід.
Автокорекція зберігає верхній регістр для слів з **My dictionary**. Якщо в особистому словнику English є `qa`, а **Minimum word length** дорівнює 2 або менше, після пробілу `ЙФ` виправиться на `QA`.
## v0.6.109 — 2026-11-17
**Ctrl+0–9** in KSwitcher Files opens the assigned folder or shows only the folders assigned to that digit. **Ctrl+F1** selects Brief and **Ctrl+F2** selects Wide in the active panel. **Ctrl+F3–F12** are reserved for other panel modes. If command history used a Ctrl+function shortcut, set a new binding under **Options → Command line → Command history**.
**My dictionary** accepts hyphens between letters, for example `test-mt` and `dev-mt`. Enter the correct spelling in the dictionary for its language, then click **OK → Save**. Update all PCs that share settings before syncing hyphenated entries.
**Українською.**
У KSwitcher Files **Ctrl+0–9** відкриває призначену папку або показує лише папки, призначені натиснутій цифрі. **Ctrl+F1** вмикає Brief, а **Ctrl+F2** вмикає Wide в активній панелі. **Ctrl+F3–F12** зарезервовані для інших режимів панелей. Якщо історія команд використовувала Ctrl із функціональною клавішею, задайте нову комбінацію в **Options → Command line → Command history**.
**My dictionary** приймає дефіси між літерами, наприклад `test-mt` і `dev-mt`. Введіть правильне написання у словник відповідної мови й натисніть **OK → Save**. Перед синхронізацією слів із дефісами оновіть усі ПК, які обмінюються налаштуваннями.
## v0.6.108 — 2026-11-17
KSwitcher Files adds **Wake** beside the offline status of a paired PC in **Change drive** (Alt+F1 or Alt+F2). Click **Wake** or focus it with the arrow keys and press **Enter**. The status bar reports whether KSwitcher sent the Wake-on-LAN packet.
Update both PCs and let them discover each other once while the target is online so KSwitcher can save its network adapter’s MAC address. Enable Wake-on-LAN on the target. Ethernet is the most reliable option. Wi-Fi requires compatible Wake on Wireless LAN hardware and drivers.
**Українською.**
У KSwitcher Files біля статусу спареного офлайн-ПК у меню **Change drive** (Alt+F1 або Alt+F2) є дія **Wake**. Клацніть **Wake** або виберіть її стрілками й натисніть **Enter**. Рядок стану повідомить, чи вдалося надіслати пакет Wake-on-LAN.
Оновіть обидва ПК і дайте їм один раз побачити один одного, поки цільовий ПК увімкнено, щоб KSwitcher зберіг MAC-адресу його мережевого адаптера. Увімкніть Wake-on-LAN на цільовому ПК. Найнадійніше підключення через Ethernet. Для Wi-Fi потрібна підтримка Wake on Wireless LAN з боку обладнання й драйвера.
## v0.6.107 — 2026-11-16
KSwitcher Files suggests recent commands, PowerShell commands and parameters, and paths as you type. The list works with the panes visible or hidden. Use **Up** or **Down** to select, **Tab** or **Enter** on a selected suggestion to insert it, and **Escape** to close the list. Press **F1** in the command line to open the Microsoft Learn article for a documented Windows command or subcommand.
The offline Windows command catalog includes nested syntax and documented choices such as `schtasks /query /fo LIST`. After `ipconfig /renew ` or `ipconfig /release `, Files suggests local IPv4 adapters configured for DHCP. With Git for Windows, Git completion includes options and matching branch names. With the .NET SDK, `dotnet` completion delegates to the CLI. The main Files window has a new blue two-pane icon inspired by FAR.
**Українською.**
KSwitcher Files підказує недавні команди з історії, команди й параметри PowerShell та шляхи під час набору. Список працює з відкритими й прихованими панелями. Стрілки **↑** і **↓** вибирають підказку, **Tab** або **Enter** на вибраній підказці вставляє її, а **Escape** закриває список. **F1** у командному рядку відкриває статтю Microsoft Learn для документованої команди чи підкоманди Windows.
Офлайн-каталог команд Windows містить вкладений синтаксис і документовані значення, наприклад `schtasks /query /fo LIST`. Після `ipconfig /renew ` або `ipconfig /release ` Files підказує локальні адаптери з DHCP для IPv4. За наявності Git for Windows підказки Git включають параметри й відповідні назви гілок. За наявності .NET SDK підказки для `dotnet` надає сама утиліта. Головне вікно Files має нову синю іконку з двома панелями в стилі FAR.
## v0.6.106 — 2026-11-16
Files scans local and LAN folders and runs copy, move, rename and delete in the background. Copy and Rename/Move validate destinations in the background. A failed operation opens a red Far-style dialog. For local sharing violations, **Processes…** shows possible blockers and **End process** ends the selected process after confirmation. Retry **F6**, **F8**, or **Shift+Delete** after releasing the item.
The screenshot editor repaints the affected area while dragging. History reuses separate OCR and thumbnail helpers, and Windows OCR scales images to the engine’s size limit. Shortcut and snippet processing does less work on keystrokes, and LAN transfers wait for a timeout before retrying unacknowledged chunks.
**Write log** defaults to off for new settings. Existing explicit choices still apply. When enabled, diagnostic logs can contain typed or copied text.
**Українською.**
Files сканує локальні й LAN-каталоги та виконує копіювання, переміщення, перейменування й видалення у фоні. Copy і Rename/Move перевіряють шлях у фоні. Помилки операцій відкривають червоний діалог у стилі Far. При локальному блокуванні **Processes…** показує можливі процеси, а **End process** завершує вибраний процес після підтвердження. Після звільнення повторіть **F6**, **F8** або **Shift+Delete**.
Редактор скриншотів перемальовує змінену область під час перетягування. Історія повторно використовує окремі процеси OCR і мініатюр, а Windows OCR масштабує зображення до ліміту рушія. Обробка хоткеїв і сніпетів виконує менше роботи під час набору. LAN-передача повторно надсилає непідтверджені блоки після тайм-ауту.
**Write log** вимкнено за замовчуванням для нових налаштувань. Явно збережений вибір продовжує діяти. Увімкнений журнал може містити введений або скопійований текст.
## v0.6.105 — 2026-11-16
KSwitcher Files gives the Editor a pencil icon and the Viewer an eye icon. The two modes have separate taskbar groups, and **F6** switches the icon and group in the same window. On a PC running KSwitcher as administrator, LAN PowerShell commands such as `dir` now start with standard user rights. This fixes the `0xC0000142` startup failure on that path. This release replaces v0.6.104.
@@ -374,7 +498,7 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
## Upgrade
Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
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.
+1 -1
View File
@@ -1 +1 @@
41b5353f049d7c6da5e664dda316e1308c5e996cdbd5a7a9b51689c02dda8674 KSwitcher-win-x64.zip
5a885ca54c703dd82a5ce82b6fdbe919337f30ca08daeb6c8958f7e36832aef2 KSwitcher-win-x64.zip
+65 -65
View File
@@ -1,166 +1,166 @@
{
"version": "0.6.116",
"files": [
{
"path": "KSwitcher.exe",
"size": 2362368,
"sha256": "87a61d636e941adc8b37385dd72fa0e15248368867adc301df5f3af894938e24"
"sha256": "b7c7f60c0a1e598359f3bd3775fca67fa2eaf9ebcc41f96da0034b3a92687863",
"size": 2479104
},
{
"path": "KSwitcher.Config.exe",
"size": 2360320,
"sha256": "ea5640173dd0c0338d0b6843f737595b2c67793cceb1202e7e293ca42fe835b8"
"sha256": "96a956ab0498269244371355b1549cc89e29d5d9175e36e39d8bef8ab53f6a5f",
"size": 2458112
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3337728,
"sha256": "c785ed267aeb3e1c1c27a8aa8fe296a98283553af3d67a9ee171fc873f4dd58c"
"sha256": "d001683200e1d86caaf96e8c37f004ab2717f8acaad8c172350581792026540d",
"size": 3060224
},
{
"path": "KSwitcher.Files.exe",
"size": 3801088,
"sha256": "6cbb9cf16e251f618e543d0af3a014932123f455ed9a2c04f86c948a5852987e"
"sha256": "cc1bea0d8d7aafe23e7a3be72177123963c7b3d250be93840850953a2aa547a6",
"size": 4232704
},
{
"path": "WebView2Loader.dll",
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
},
{
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
},
{
"path": "terminal/addon-fit.js",
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
},
{
"path": "terminal/index.html",
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
},
{
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073
},
{
"path": "terminal/markdown-it.js",
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786
},
{
"path": "terminal/markdown.html",
"size": 3530,
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c",
"size": 3530
},
{
"path": "terminal/markdown.js",
"size": 14660,
"sha256": "fe202fa3d3c362aff2ab9028b40bd2aee61240bf9bd4a44af55e45d1a4081cf0"
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763",
"size": 15014
},
{
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089
},
{
"path": "terminal/mermaid.js",
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838
},
{
"path": "terminal/terminal.js",
"size": 5033,
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a"
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"size": 5065
},
{
"path": "terminal/xterm-LICENSE.txt",
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
},
{
"path": "terminal/xterm.css",
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
},
{
"path": "terminal/xterm.js",
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
},
{
"path": "LICENSE",
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
},
{
"path": "json-LICENSE.txt",
"size": 1075,
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86"
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096
},
{
"path": "files-text-license.txt",
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883
},
{
"path": "README.md",
"size": 94502,
"sha256": "b4b561d2bdf1ef80291c3abcadb625407b94279185fd33fd9dc113658ab9b486"
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8",
"size": 95317
},
{
"path": "LAN-PREVIEW.md",
"size": 11577,
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
"size": 11577
},
{
"path": "dictionaries/en.txt",
"size": 682867,
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21"
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485
},
{
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20138,
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5"
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566
},
{
"path": "dictionaries/README.md",
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
},
{
"path": "dictionaries/ru.txt",
"size": 1060364,
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b"
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134
},
{
"path": "dictionaries/sources.json",
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
},
{
"path": "dictionaries/uk.txt",
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
},
{
"path": "tools/README.txt",
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
},
{
"path": "tools/StayHere.exe",
"size": 134656,
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
"sha256": "c893d20af87a53cad90306951b80342c553d1cb188291a0377c3f28bd014b2c0",
"size": 133120
},
{
"path": "tools/StayHere-README.md",
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
}
],
"version": "0.6.105",
"schema": 1
}
+3 -4
View File
@@ -41,12 +41,11 @@ try {
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,(Join-Path $destination $name),$name,[IO.Compression.CompressionLevel]::Optimal) | Out-Null
}
} finally { $zip.Dispose(); $stream.Dispose() }
Get-FileHash -LiteralPath $archive -Algorithm SHA256
$archiveHash = Get-FileHash -LiteralPath $archive -Algorithm SHA256
$archiveHash
if ($PublishRelease) {
$release = Join-Path $root 'Release'
New-Item -ItemType Directory -Force $release | Out-Null
$published = Join-Path $release 'KSwitcher-win-x64.zip'
Copy-Item -LiteralPath $archive -Destination $published -Force
$hash = (Get-FileHash -LiteralPath $published -Algorithm SHA256).Hash.ToLowerInvariant()
$hash = $archiveHash.Hash.ToLowerInvariant()
"$hash KSwitcher-win-x64.zip" | Set-Content -LiteralPath (Join-Path $release 'SHA256SUMS.txt') -Encoding ascii
}
+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,105,0
PRODUCTVERSION 0,6,105,0
FILEVERSION 0,6,116,0
PRODUCTVERSION 0,6,116,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.105"
VALUE "FileVersion", "0.6.116"
END
END
BLOCK "VarFileInfo"
+50 -1
View File
@@ -50,16 +50,65 @@ BEGIN
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
END
611 DIALOGEX 0, 0, 332, 96
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "&Open/create file:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
CONTROL "", 467, "Static", NOT WS_VISIBLE, 14, 72, 1, 1
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 76, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 76, 60, 16
END
612 DIALOGEX 0, 0, 332, 184
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "Save file &as:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
AUTOCHECKBOX "Add signature (&BOM)", 464, 14, 66, 304, 12
CONTROL "", 468, "Static", NOT WS_VISIBLE, 14, 86, 1, 1
LTEXT "Change line breaks to:", 469, 14, 87, 304, 12
AUTORADIOBUTTON "Do &not change", 470, 14, 100, 304, 12, WS_GROUP | WS_TABSTOP
AUTORADIOBUTTON "&Windows (CR LF)", 471, 14, 112, 304, 12
AUTORADIOBUTTON "&Unix (LF)", 472, 14, 124, 304, 12
AUTORADIOBUTTON "&Mac (CR)", 473, 14, 136, 304, 12
CONTROL "", 467, "Static", NOT WS_VISIBLE | WS_GROUP, 14, 155, 1, 1
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 157, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 157, 60, 16
END
607 DIALOGEX 0, 0, 185, 57
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL, 14, 16, 157, 13
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL, 14, 16, 157, 13
AUTOCHECKBOX "&Remember for this session", 101, 14, 30, 157, 13, NOT WS_VISIBLE
CONTROL "", 102, "Static", NOT WS_VISIBLE, 14, 35, 1, 1
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 129, 38, 51, 15
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
END
609 DIALOGEX 0, 0, 350, 135
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 430, 14, 17, 322, 20
LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
CONTROL "", 432, "Static", NOT WS_VISIBLE, 14, 108, 1, 1
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 56, 110, 80, 16
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 140, 110, 74, 16
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 218, 110, 65, 16
END
608 DIALOGEX 0, 0, 220, 67
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

+1 -1
View File
@@ -282,7 +282,7 @@ document.addEventListener('keydown', event => {
event.preventDefault();
} else if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
event.preventDefault();
send('cycle');
send('cycle', {reverse: event.shiftKey});
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
event.preventDefault();
+1
View File
@@ -3,6 +3,7 @@ const terminal = new Terminal({
fontFamily: 'Consolas, monospace',
fontSize: 16,
cursorBlink: false,
cursorInactiveStyle: 'none',
disableStdin: true,
theme: { background: '#181818', foreground: '#e8e8e8' },
});
+45 -27
View File
@@ -178,6 +178,28 @@ std::vector<std::pair<int, std::wstring>> shortcuts(const Settings &s)
out.emplace_back(Direct + (int)i, s.direct[i]);
return out;
}
std::vector<std::wstring> buildSnippetVariants(const std::wstring &trigger, const std::vector<Layout> &layouts)
{
std::vector<std::wstring> variants{lower(trigger)};
for (auto &l : layouts)
{
bool valid = true;
std::wstring normalized;
for (wchar_t c : trigger)
{
auto p = physicalLayout().at(l.code(c));
if (!p)
{
valid = false;
break;
}
normalized += p;
}
if (valid)
variants.push_back(lower(normalized));
}
return variants;
}
size_t caretSteps(std::wstring text)
{
size_t n = 0;
@@ -976,6 +998,10 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation)
if (validateOcrInstallation && ocrProfile(s) != ocrProfile(settings)) validateTesseract(s);
if (s.autoCorrect)
{
{
std::lock_guard lock(stateMutex);
predictor.shareDictionaries(autoPredictor);
}
predictor.configure(std::filesystem::path(executable()).parent_path() / L"dictionaries", s.autoLanguages);
}
if (!registerHotkeys(s))
@@ -1008,6 +1034,7 @@ void App::applySettings(const Settings &requested, bool validateOcrInstallation)
{
std::lock_guard lock(stateMutex);
settings = s;
snippetTriggers.clear();
autoPredictor = std::move(predictor);
setLoggingEnabled(s.writeLog);
run.reset();
@@ -1038,6 +1065,7 @@ void App::reloadLayouts()
{
std::lock_guard lock(stateMutex);
layouts = std::move(latest);
snippetTriggers.clear();
settings = s;
run.reset();
last.reset();
@@ -1062,13 +1090,9 @@ void App::setHotkeyCapture(HWND field)
bool App::isHotkey(DWORD key, UINT mods)
{
if (registeredFilesHotkey.key && registeredFilesHotkey.key == key && registeredFilesHotkey.modifiers == mods) return true;
for (auto &[id, text] : shortcuts(settings))
{
auto h = Hotkey::parse(text);
if (h && h->key == key && h->modifiers == mods)
return true;
}
return false;
return std::any_of(hookBindings.begin(), hookBindings.end(), [&](const auto &binding) {
return binding.second == Hotkey{mods, key};
});
}
void App::resetLanInput()
{
@@ -1187,30 +1211,24 @@ void App::matchSnippets(HWND fg, bool expandExact)
const std::wstring_view prefix = std::wstring_view(keys).substr(start == keys.npos ? 0 : start + 1);
const bool suggest = prefix.size() >= 3 || prefix.starts_with(L';');
std::vector<size_t> matches;
std::set<std::wstring> seen;
auto snippetProcess = processName(fg);
std::set<std::wstring_view> seen;
snippetTriggers.resize(settings.snippets.size());
std::optional<std::wstring> snippetProcess;
for (int priority : {2, 1})
for (size_t i = 0; i < settings.snippets.size(); ++i)
{
auto &sn = settings.snippets[i];
if (snippetAppPriority(sn, snippetProcess) != priority) continue;
std::vector<std::wstring> variants{lower(sn.trigger)};
for (auto &l : layouts)
if (sn.apps.empty() != (priority == 1)) continue;
if (!sn.apps.empty())
{
bool valid = true;
std::wstring normalized;
for (wchar_t c : sn.trigger)
{
auto p = physicalLayout().at(l.code(c));
if (!p)
{
valid = false;
break;
}
normalized += p;
}
if (valid)
variants.push_back(lower(normalized));
if (!snippetProcess) snippetProcess = processName(fg);
if (snippetAppPriority(sn, *snippetProcess) != priority) continue;
}
auto &[trigger, variants] = snippetTriggers[i];
if (variants.empty() || trigger != sn.trigger)
{
variants = buildSnippetVariants(sn.trigger, layouts);
trigger = sn.trigger;
}
if (expandExact && std::any_of(variants.begin(), variants.end(), [&](const auto &trigger) {
return keys.ends_with(trigger);
@@ -1221,7 +1239,7 @@ void App::matchSnippets(HWND fg, bool expandExact)
}
if (suggest && std::any_of(variants.begin(), variants.end(), [&](const auto &trigger) {
return trigger.size() > prefix.size() && trigger.starts_with(prefix);
}) && seen.insert(lower(sn.trigger)).second)
}) && seen.insert(variants.front()).second)
matches.push_back(i);
}
if (matches.empty()) return;
+1
View File
@@ -192,6 +192,7 @@ class App
RECT snippetPopupAnchor{};
bool snippetCaretPending{};
std::optional<RECT> snippetCaret;
std::vector<std::pair<std::wstring, std::vector<std::wstring>>> snippetTriggers;
std::vector<size_t> snippetMatches;
std::array<bool, 256> snippetKeys{};
void matchSnippets(HWND, bool expandExact);
+11 -4
View File
@@ -34,13 +34,14 @@ std::wstring layoutLanguage(const Layout &layout)
return {};
}
}
bool safeAutoWord(const std::wstring &word, int minimumLength)
bool safeAutoWord(const std::wstring &word, int minimumLength, bool allowUppercase)
{
if (minimumLength < 1 || minimumLength > 32 || word.size() < (size_t)minimumLength || word.size() > 32 ||
!std::all_of(word.begin(), word.end(), letter))
return false;
auto small = lower(word);
return word == small || (word.substr(1) == small.substr(1) && word != upper(word));
const bool allUppercase = word == upper(word);
return word == small || (allUppercase ? allowUppercase : word.substr(1) == small.substr(1));
}
namespace {
constexpr size_t DictionaryBlockWords = 32;
@@ -289,9 +290,15 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
if (dictionary == dictionaries.end())
continue;
auto converted = convert(word, layouts[source], layouts[i], true);
if (converted == word || !safeAutoWord(converted, settings.autoMinLength))
if (converted == word)
continue;
int rank = personal(dictionary->first, converted) ? 1 : dictionary->second->rank(converted);
const bool knownPersonal = personal(dictionary->first, converted);
auto letters = converted;
if (knownPersonal)
std::erase(letters, L'-');
if (!safeAutoWord(letters, settings.autoMinLength, knownPersonal))
continue;
int rank = knownPersonal ? 1 : dictionary->second->rank(converted);
if (!rank)
continue;
if (matchedText && *matchedText != converted)
+1 -1
View File
@@ -12,7 +12,7 @@ struct AutoSuggestion
std::wstring text;
};
std::wstring layoutLanguage(const Layout &);
bool safeAutoWord(const std::wstring &, int minimumLength = 3);
bool safeAutoWord(const std::wstring &, int minimumLength = 3, bool allowUppercase = false);
bool autoClosingSelection(const std::wstring &, const Settings & = {});
int matchAutoInput(const Run &, const std::wstring &, const std::vector<Layout> &, const Layout &,
const Settings & = {});
+12 -2
View File
@@ -3,6 +3,7 @@
#include <cwctype>
#include <map>
#include <stdexcept>
#include <string_view>
namespace ks
{
@@ -21,20 +22,29 @@ int snippetAppPriority(const Snippet &snippet, const std::wstring &process)
for (const auto &app : snippet.apps) if (snippetAppName(app) == name && !name.empty()) return 2;
return 0;
}
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet)
static bool validSeparatedWord(const std::wstring &text, const std::wstring &alphabet,
std::wstring_view separators)
{
if (text.empty() || text.size() > 32) return false;
auto isLetter = [&](wchar_t c) { return alphabet.find(c) != alphabet.npos; };
for (size_t i = 0; i < text.size(); ++i)
{
if (isLetter(text[i])) continue;
if (text[i] != L' ' && text[i] != L'\'' && text[i] != L'\u2019' && text[i] != L'\u02bc')
if (separators.find(text[i]) == separators.npos)
return false;
if (i == 0 || i + 1 == text.size() || !isLetter(text[i - 1]) || !isLetter(text[i + 1]))
return false;
}
return true;
}
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet)
{
return validSeparatedWord(text, alphabet, L" '\u2019\u02bc");
}
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet)
{
return validSeparatedWord(lower(text), alphabet, L"-");
}
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet)
{
return text.find(L' ') == text.npos && text.find_first_of(alphabet) != text.npos &&
+2 -1
View File
@@ -22,6 +22,7 @@ struct Layout
bool letter(wchar_t ch);
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet);
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet);
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet);
std::wstring lower(std::wstring text);
std::wstring upper(std::wstring text);
std::wstring convert(const std::wstring &, const Layout &, const Layout &, bool force = false);
@@ -78,7 +79,7 @@ struct Settings
bool autoCorrect = false;
bool autoReplace = false, autoTypos = false;
std::map<std::wstring, std::wstring> autoReplacements;
bool writeLog = true;
bool writeLog = false;
bool screenshotAutoOpenEditor = false;
bool useTesseract = false;
std::wstring tesseractPath;
+321
View File
@@ -0,0 +1,321 @@
#pragma once
#include "platform.h"
#include "files_powershell.h"
#include "files_windows_command_catalog.h"
#include "../vendor/json.hpp"
#include <optional>
#include <vector>
namespace ks::files
{
class CommandCompletion
{
public:
using Json = nlohmann::json;
CommandCompletion() = default;
CommandCompletion(const CommandCompletion &) = delete;
CommandCompletion &operator=(const CommandCompletion &) = delete;
~CommandCompletion() { close(); }
bool request(const std::wstring &line, DWORD caret, const std::wstring &directory)
{
auto message=Json{{"line",utf8(line)},{"caret",caret},{"directory",utf8(directory)}}.dump(
-1,' ',true,Json::error_handler_t::replace)+"\n";
if(message.size()>32768 || (!process && !start())) return false;
if(!write(message))
{
close();
return false;
}
deadline=GetTickCount64()+5000;
return true;
}
// An empty optional means the request is still running.
std::optional<Json> poll()
{
DWORD available{},count{};
char chunk[8192];
if(!PeekNamedPipe(output,nullptr,0,nullptr,&available,nullptr) ||
GetTickCount64()>=deadline || pending.size()>1024*1024)
{
close();
return Json{};
}
if(available && ReadFile(output,chunk,std::min<DWORD>(available,sizeof(chunk)),&count,nullptr))
pending.append(chunk,count);
const auto end=pending.find('\n');
if(end==pending.npos) return {};
auto result=Json::parse(pending.begin(),pending.begin()+end,nullptr,false);
pending.erase(0,end+1);
return result;
}
private:
HANDLE process{},input{},output{},job{};
ULONGLONG deadline{};
std::string pending;
bool write(std::string_view message)
{
DWORD written{};
return WriteFile(input,message.data(),static_cast<DWORD>(message.size()),&written,nullptr) &&
written==message.size();
}
bool start()
{
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
HANDLE childInput{},childOutput{};
std::string catalog;
for(const auto row:windowsCommandCatalog) catalog.append(row).push_back('\n');
const auto initial=Json{{"catalog",std::move(catalog)}}.dump()+"\n";
const auto inputCapacity=static_cast<DWORD>(initial.size()+32768);
const bool pipes=CreatePipe(&childInput,&input,&inheritable,inputCapacity) &&
CreatePipe(&output,&childOutput,&inheritable,65536) &&
SetHandleInformation(input,HANDLE_FLAG_INHERIT,0) &&
SetHandleInformation(output,HANDLE_FLAG_INHERIT,0);
const bool started=pipes && launch(childInput,childOutput) && write(initial);
if(childInput) CloseHandle(childInput);
if(childOutput) CloseHandle(childOutput);
if(!started) close();
return started;
}
bool launch(HANDLE childInput,HANDLE childOutput)
{
const auto shell=windowsPowerShell();
if(shell.empty()) return false;
// The request is data on stdin. PowerShell parses it for completion in this separate session.
wchar_t command[]=LR"PS(powershell.exe -NoLogo -NoProfile -NonInteractive -Command "
$ProgressPreference = 'SilentlyContinue';
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);
function Get-CompletedArguments($command, $position, $includeCurrent) {
foreach ($element in ($command.CommandElements | Select-Object -Skip 1)) {
if ($element.Extent.EndOffset -gt $position -or
(!$includeCurrent -and $element.Extent.EndOffset -eq $position)) { break }
if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
$element.Value;
} else { $element.Extent.Text }
}
}
function New-ArgumentCompletion([string]$value) {
$text = $value;
if ($value.StartsWith('@') -or $value -notmatch '^[\p{L}\p{M}\p{N}._/@:+,=\-]+$') {
$quote = [string][char]39;
$text = $quote + [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($value) + $quote;
}
[System.Management.Automation.CompletionResult]::new($text, $value, 'ParameterValue', $value)
}
function Get-DhcpAdapterNames {
foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
try {
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
} catch {}
}
}
$initial = ConvertFrom-Json -InputObject ([Console]::ReadLine());
$windowsCommands = @{};
$windowsHelp = @{};
foreach ($row in ($initial.catalog -split '\r?\n')) {
if (!$row) { continue }
$name, $values, $article = $row.Split([char]9, 3);
$windowsCommands[$name] = if ($values) { $values.Split(' ') } else { @() };
if ($article) { $windowsHelp[$name] = $article }
}
$windowsRoots = @($windowsCommands.Keys | Where-Object { !($_.Contains(' ')) } | Sort-Object);
$windowsPrograms = @(foreach ($name in $windowsRoots) { $name; $name + '.exe'; $name + '.com' });
function Get-WindowsCommandContext($command, $position, $includeCurrent) {
if (!$command) { return }
$invoked = $command.GetCommandName();
if (!$invoked -or !$windowsCommands.ContainsKey([IO.Path]::GetFileNameWithoutExtension($invoked))) { return }
$resolved = Get-Command -Name ([WildcardPattern]::Escape($invoked)) -ErrorAction SilentlyContinue |
Select-Object -First 1;
if ($resolved -is [System.Management.Automation.AliasInfo]) { $resolved = $resolved.ResolvedCommand }
if ($resolved -isnot [System.Management.Automation.ApplicationInfo]) { return }
$name = [IO.Path]::GetFileNameWithoutExtension($resolved.Name);
$arguments = @(Get-CompletedArguments $command $position $includeCurrent);
$values = $null;
if ($name -eq 'cmd') {
for ($i = 0; $i -lt $arguments.Count; ++$i) {
if ($arguments[$i] -notin '/c', '/k') { continue }
if ($i + 1 -lt $arguments.Count) {
$name = [IO.Path]::GetFileNameWithoutExtension($arguments[$i + 1]);
$arguments = @($arguments | Select-Object -Skip ($i + 2));
} else { $values = $windowsRoots }
break
}
}
$root = $name;
$article = $windowsHelp[$name];
if (!$values) {
foreach ($argument in $arguments) {
$child = $name + ' ' + $argument;
if (!$windowsCommands.ContainsKey($child)) { break }
$name = $child;
if ($windowsHelp[$name]) { $article = $windowsHelp[$name] }
}
$values = $windowsCommands[$name];
}
@{ root = $root; values = $values; arguments = $arguments; article = $article }
}
Register-ArgumentCompleter -Native -CommandName $windowsPrograms -ScriptBlock {
param($word, $command, $position)
$context = Get-WindowsCommandContext $command $position $false;
if (!$context) { return }
if ($context.root -eq 'ipconfig' -and $context.arguments.Count -and
$context.arguments[0] -in '/renew','/release') {
$script:adapterArguments = $true;
if ($context.arguments.Count -ne 1) { return }
$prefix = ([string]$word).Trim([char[]]@([char]39, [char]34));
foreach ($adapterName in (Get-DhcpAdapterNames | Sort-Object -Unique)) {
if ($adapterName.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
New-ArgumentCompletion $adapterName
}
}
return
}
if ($word -eq '?') { $word = '/?' }
foreach ($value in $context.values) {
if ($value.StartsWith([string]$word, [StringComparison]::OrdinalIgnoreCase)) {
[System.Management.Automation.CompletionResult]::new($value)
}
}
};
Register-ArgumentCompleter -Native -CommandName dotnet,dotnet.exe -ScriptBlock {
param($word, $command, $position)
$offset = $position - $command.Extent.StartOffset;
dotnet.exe complete --position $offset $command.ToString() 2>$null | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_)
}
};
function Find-GitCompletionTools {
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1;
if (!$git) { return }
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source));
for ($level = 0; $location -and $level -lt 3; ++$level) {
$root = $location.FullName;
$location = $location.Parent;
$bash = Join-Path $root 'usr/bin/bash.exe';
if (![IO.File]::Exists($bash)) { continue }
foreach ($architecture in 'mingw64', 'mingw32', 'clangarm64') {
$script = Join-Path $root ($architecture + '/share/git/completion/git-completion.bash');
if ([IO.File]::Exists($script)) { return @{ bash = $bash; script = $script } }
}
}
}
# Send words as data to Git for Windows. Backslash-quote escapes are for Windows PowerShell's native argv.
$gitCompletionRunner = @'
export GIT_ALLOW_PROTOCOL= GIT_TERMINAL_PROMPT=0
mapfile -t input
for i in ~${!input[@]}~; do input[i]=~${input[i]%$'\r'}~; done
source ~${input[0]}~ || exit
words=(~${input[@]:1}~)
cword=$(( ${#words[@]} - 1 ))
cur=${words[cword]}
prev=${words[cword-1]}
__git_main
if (( ${#COMPREPLY[@]} )); then printf '%s\n' ~${COMPREPLY[@]}~; fi
'@.Replace('~', ('\' + [char]34));
$OutputEncoding = [Console]::OutputEncoding;
Register-ArgumentCompleter -Native -CommandName git,git.exe -ScriptBlock {
param($word, $command, $position)
if (!$script:gitCompletionTools) { $script:gitCompletionTools = Find-GitCompletionTools }
if (!$script:gitCompletionTools) { return }
$arguments = @('git') + @(Get-CompletedArguments $command $position) + @([string]$word);
@($script:gitCompletionTools.script) + $arguments |
& $script:gitCompletionTools.bash --noprofile --norc -p -c $gitCompletionRunner 2>$null |
ForEach-Object {
$value = $_.TrimEnd();
if ($value) { New-ArgumentCompletion $value }
}
};
function Get-CompletionCommand($request) {
$prefix = $request.line.Substring(0, $request.caret).TrimEnd();
$ast = [System.Management.Automation.Language.Parser]::ParseInput($prefix, [ref]$null, [ref]$null);
$ast.FindAll({
param($node)
$node -is [System.Management.Automation.Language.CommandAst] -and
$node.Extent.EndOffset -eq $prefix.Length
}, $true) | Select-Object -Last 1;
}
function Test-NoCommandArguments($command) {
if (!$command) { return $false }
$name = $command.GetCommandName();
if (!$name) { return $false }
$info = Get-Command -Name ([WildcardPattern]::Escape($name)) -ErrorAction SilentlyContinue;
if ($info -is [System.Management.Automation.AliasInfo]) { $info = $info.ResolvedCommand }
return ($info -is [System.Management.Automation.FunctionInfo] -or
$info -is [System.Management.Automation.CmdletInfo]) -and $info.Parameters.Count -eq 0;
}
while ($null -ne ($line = [Console]::ReadLine())) {
try {
$request = ConvertFrom-Json -InputObject $line -ErrorAction Stop;
Set-Location -LiteralPath $request.directory -ErrorAction Stop;
$script:adapterArguments = $false;
$command = Get-CompletionCommand $request;
$context = Get-WindowsCommandContext $command $request.caret $true;
$result = TabExpansion2 -inputScript $request.line -cursorColumn $request.caret;
$candidates = $result.CompletionMatches;
if ($candidates.Count -and $candidates[0].ResultType -in 'ProviderItem','ProviderContainer' -and
($script:adapterArguments -or (Test-NoCommandArguments $command))) {
$candidates = $candidates | Where-Object { $_.ResultType -notin 'ProviderItem','ProviderContainer' };
}
$items = @($candidates | Select-Object -First 100 | ForEach-Object {
@{ label = $_.ListItemText; text = $_.CompletionText; directory = ($_.ResultType -eq 'ProviderContainer') }
});
$reply = @{ index = $result.ReplacementIndex; length = $result.ReplacementLength;
matches = $items; article = [string]$context.article };
[Console]::WriteLine((ConvertTo-Json -InputObject $reply -Compress -Depth 4));
} catch { [Console]::WriteLine('{}') }
}")PS";
job=CreateJobObjectW(nullptr,nullptr);
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(!job || !SetInformationJobObject(job,JobObjectExtendedLimitInformation,&limits,sizeof(limits))) return false;
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
std::vector<unsigned char> storage(bytes);
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes)) return false;
HANDLE inherited[]{childInput,childOutput};
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput=childInput;
startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=childOutput;
startup.lpAttributeList=attributes;
PROCESS_INFORMATION child{};
const bool started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inherited,sizeof(inherited),nullptr,nullptr) &&
CreateProcessW(shell.c_str(),command,nullptr,nullptr,TRUE,
CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,
nullptr,nullptr,&startup.StartupInfo,&child);
DeleteProcThreadAttributeList(attributes);
if(!started) return false;
process=child.hProcess;
const bool running=AssignProcessToJobObject(job,process) && ResumeThread(child.hThread)!=DWORD(-1);
if(!running) TerminateProcess(process,1);
CloseHandle(child.hThread);
return running;
}
void close()
{
for(const auto handle:{job,input,output,process})
if(handle) CloseHandle(handle);
job=input=output=process=nullptr;
pending.clear();
}
};
}
+18 -1
View File
@@ -2,6 +2,23 @@ constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MA
auto commandHistoryKeys=defaultHistoryKeys;
constexpr size_t commandHistoryLimit=1000;
std::wstring commandHistoryLabel(const std::wstring &command)
{
constexpr std::wstring_view prefix=L"start '";
if(!command.starts_with(prefix) || command.size()<=prefix.size() || command.back()!=L'\'')
return command;
const std::wstring_view literal(command.data()+prefix.size(),command.size()-prefix.size()-1);
std::wstring path;
for(size_t i=0;i<literal.size();++i)
{
const auto character=literal[i];
if(character==L'\'' || character==L'\u2018' || character==L'\u2019')
if(++i==literal.size() || literal[i]!=character) return command;
path+=character;
}
return fs::path(path).is_absolute()?path:command;
}
bool validHistoryKeys(const std::array<WORD,2> &keys)
{
if(keys[0]==keys[1]) return false;
@@ -12,7 +29,7 @@ bool validHistoryKeys(const std::array<WORD,2> &keys)
const bool function=key>=VK_F1 && key<=VK_F12;
if(!letter && !function) return false;
if(modifiers==HOTKEYF_CONTROL)
return (letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
return letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y';
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
return false;
});
+8 -12
View File
@@ -69,7 +69,7 @@ void populateCommandHistory(HWND dialog)
{
return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;});
};
if(containsAll(command+L" "+entry.date))
if(containsAll(command+L" "+historyLower(commandHistoryLabel(entry.command))+L" "+entry.date))
{
matches[0].push_back(index);
continue;
@@ -91,7 +91,7 @@ void populateCommandHistory(HWND dialog)
if(first || date!=lastDate) add(date,-1);
first=false;
lastDate=date;
const auto row=add(entry.command,index);
const auto row=add(commandHistoryLabel(entry.command),index);
if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row;
}
}
@@ -140,13 +140,7 @@ LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UI
SendMessageW(GetParent(list),WM_COMMAND,IDOK,0);
return 0;
}
if(message==LB_GETTOPINDEX || message==WM_NCDESTROY)
return DefSubclassProc(list,message,wp,lp);
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
const auto result=scrollList(list,message,wp,lp);
if(top!=SendMessageW(list,LB_GETTOPINDEX,0,0))
InvalidateRect(GetParent(list),nullptr,FALSE);
return result;
return DefSubclassProc(list,message,wp,lp);
}
void sizeCommandHistory(HWND dialog,HWND list)
@@ -165,8 +159,9 @@ void sizeCommandHistory(HWND dialog,HWND list)
LONG longest{};
for(const auto &entry:terminalHistory)
{
const auto label=commandHistoryLabel(entry.command);
SIZE size{};
if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast<int>(entry.command.size()),&size))
if(GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.size()),&size))
longest=std::max(longest,size.cx);
}
SelectObject(dc,previous);
@@ -179,7 +174,7 @@ void sizeCommandHistory(HWND dialog,HWND list)
const int gap=MulDiv(4,dpi,96);
const int listTop=top+2*textHeight+2*gap;
const LONG desired=std::max<LONG>(MulDiv(320,dpi,96),
longest+2*cellWidth+2*historyRowInset(dpi)+GetSystemMetricsForDpi(SM_CXVSCROLL,dpi))+2*inset;
longest+2*cellWidth+2*historyRowInset(dpi)+scrollBarWidth(list))+2*inset;
const auto target=std::min(desired,area.right-area.left);
const auto rows=std::max<LRESULT>(1,SendMessageW(list,LB_GETCOUNT,0,0));
RECT listWindow{},listClient{};
@@ -198,7 +193,7 @@ void sizeCommandHistory(HWND dialog,HWND list)
};
place(GetDlgItem(dialog,historySearchLabel),top,textHeight);
place(GetDlgItem(dialog,historySearch),top+textHeight+gap,textHeight);
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-5),
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-scrollBarWidth(list)),
std::max(1L,height-listTop-inset),SWP_NOZORDER|SWP_NOACTIVATE);
GetClientRect(list,&listClient);
if(rows*textHeight<=listClient.bottom) SendMessageW(list,LB_SETTOPINDEX,0,0);
@@ -221,6 +216,7 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM
prepareCopyDialog(dialog);
const auto list=GetDlgItem(dialog,historyList);
SetWindowSubclass(list,historyListScroll,1,0);
installScrollBar(list,dialog);
SendMessageW(list,WM_SETFONT,reinterpret_cast<WPARAM>(mono),TRUE);
SendMessageW(list,LB_SETITEMHEIGHT,0,std::max(1,textHeight));
const auto search=GetDlgItem(dialog,historySearch);
+15 -32
View File
@@ -187,8 +187,6 @@ struct FolderShortcutView
std::vector<int> digits;
int rowHeight{};
Panel *panel{};
bool all{};
std::vector<std::pair<int,size_t>> entries;
};
std::wstring shortcutLabel(const FolderShortcut &entry)
@@ -201,7 +199,6 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
const auto list=GetDlgItem(dialog,shortcutList);
SendMessageW(list,LB_RESETCONTENT,0,0);
view.digits.clear();
view.entries.clear();
const auto owner=GetWindow(dialog,GW_OWNER);
const auto dc=GetDC(dialog);
const auto font=SelectObject(dc,mono);
@@ -219,23 +216,14 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
GetTextExtentPoint32W(dc,label.data(),static_cast<int>(label.size()),&size);
return static_cast<int>(size.cx);
};
int width=std::max(measure(L"Folder shortcuts"),measure(view.all?L"Del F4":view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
int width=std::max(measure(L"Folder shortcuts"),measure(view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
const int textInset=dialogRowTextInset(cellWidth);
const auto add=[&](const std::wstring &label)
{
width=std::max(width,measure(label)+2*textInset);
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
};
if(view.all)
{
for(int digit=0;digit<static_cast<int>(folderShortcuts.size());++digit)
for(size_t index=0;index<folderShortcuts[digit].size();++index)
{
view.entries.emplace_back(digit,index);
add(std::to_wstring(digit)+L" "+shortcutLabel(folderShortcuts[digit][index]));
}
}
else if(view.digit<0)
if(view.digit<0)
{
for(int digit=0;digit<10;++digit)
if(!folderShortcuts[digit].empty())
@@ -255,7 +243,8 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
GetWindowRect(owner,&parent);
const auto windowWidth=std::max(px(260),static_cast<int>(parent.right-parent.left));
const auto windowHeight=std::max(px(140),static_cast<int>(parent.bottom-parent.top));
width=std::min(width,std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
width=std::min(width+scrollBarWidth(list),
std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
const auto maxRows=std::max(1,(std::min(windowHeight,static_cast<int>(work.bottom-work.top))-2*listTop)/view.rowHeight);
const auto count=static_cast<int>(SendMessageW(list,LB_GETCOUNT,0,0));
const int rows=std::min(count,maxRows);
@@ -267,7 +256,8 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
const int y=std::clamp(static_cast<int>((parent.top+parent.bottom-h)/2),
static_cast<int>(work.top),std::max(static_cast<int>(work.top),static_cast<int>(work.bottom)-h));
SetWindowPos(dialog,nullptr,x,y,w,h,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(list,nullptr,inset,listTop,width,listHeight,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(list,nullptr,inset,listTop,std::max(1,width-scrollBarWidth(list)),listHeight,
SWP_NOZORDER|SWP_NOACTIVATE);
SendMessageW(list,LB_SETCURSEL,std::clamp(selection,0,std::max(0,count-1)),0);
InvalidateRect(dialog,nullptr,TRUE);
FilesModalDialog::refreshLayout(dialog);
@@ -290,7 +280,7 @@ LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags,
return 0;
}
}
return scrollList(list,message,key,flags);
return DefSubclassProc(list,message,key,flags);
}
INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
@@ -303,6 +293,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
layoutQuickFolders(dialog,view,0);
const auto list=GetDlgItem(dialog,shortcutList);
SetWindowSubclass(list,quickFolderKeys,1,0);
installScrollBar(list,dialog);
SetFocus(list);
return FALSE;
}
@@ -322,7 +313,8 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),teal,frame);
DeleteObject(frame);
paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono,
view->all?L"Del F4":view->digit<0?L"Enter Esc":quickFolderHints);
view->digit<0?L"Enter Esc":quickFolderHints);
paintScrollPosition(dialog,dc,GetDlgItem(dialog,shortcutList),colors[Dialog]);
EndPaint(dialog,&ps);
return TRUE;
}
@@ -349,7 +341,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(action!=quickRemove && action!=quickEdit && action!=quickInsert && action!=quickMoveUp &&
action!=quickMoveDown && action!=IDOK && !(action==shortcutList && HIWORD(wp)==LBN_DBLCLK)) return FALSE;
const auto row=SendDlgItemMessageW(dialog,shortcutList,LB_GETCURSEL,0,0);
if(!view->all && view->digit<0)
if(view->digit<0)
{
if((action==IDOK || action==shortcutList) && row>=0 && static_cast<size_t>(row)<view->digits.size())
{
@@ -358,16 +350,8 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
return TRUE;
}
int digit=view->digit;
size_t index=static_cast<size_t>(row);
if(view->all)
{
if(index>=view->entries.size() || action==quickInsert ||
action==quickMoveUp || action==quickMoveDown) return TRUE;
const auto &entry=view->entries[index];
digit=entry.first;
index=entry.second;
}
const auto digit=view->digit;
const auto index=static_cast<size_t>(row);
const auto &group=folderShortcuts[digit];
if(action==quickInsert)
{
@@ -414,7 +398,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
folderShortcuts=std::move(updated);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
if(view->all?view->entries.size()==1:folderShortcuts[digit].empty()) FilesModalDialog::finish(dialog,IDCANCEL);
if(folderShortcuts[digit].empty()) FilesModalDialog::finish(dialog,IDCANCEL);
else layoutQuickFolders(dialog,*view,static_cast<int>(row));
return TRUE;
}
@@ -424,7 +408,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
void showFolderShortcuts(Panel &panel,int digit,bool all)
void showFolderShortcuts(Panel &panel,int digit)
{
if(digit>=0)
{
@@ -447,7 +431,6 @@ void showFolderShortcuts(Panel &panel,int digit,bool all)
}
FolderShortcutView view{digit};
view.panel=&panel;
view.all=all;
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list),
quickFolderDialog,reinterpret_cast<LPARAM>(&view));
SetFocus(panel.list);
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#include <windows.h>
#include <algorithm>
#include <string_view>
#include <windowsx.h>
namespace ks::files
{
inline COLORREF hoverSurface(COLORREF surface)
{
return RGB(3*GetRValue(surface)/4,3*GetGValue(surface)/4,3*GetBValue(surface)/4);
}
class InlineListAction
{
std::wstring_view label;
LRESULT pressedRow=LB_ERR;
public:
explicit InlineListAction(std::wstring_view text):label(text){}
RECT bounds(RECT row,int cellWidth) const
{
row.right-=2*cellWidth;
row.left=std::max(row.left,row.right-static_cast<LONG>(label.size()*cellWidth));
return row;
}
bool hit(HWND list,LRESULT row,LPARAM point,int cellWidth) const
{
RECT item{};
if(SendMessageW(list,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&item))==LB_ERR) return false;
const auto action=bounds(item,cellWidth);
return PtInRect(&action,{GET_X_LPARAM(point),GET_Y_LPARAM(point)});
}
void press(HWND list,LRESULT row)
{
pressedRow=row;
SetCapture(list);
}
bool pressed() const { return pressedRow!=LB_ERR; }
void cancel() { pressedRow=LB_ERR; }
bool release(HWND list,LRESULT row,bool overAction)
{
const bool activate=pressedRow==row && overAction;
cancel();
if(GetCapture()==list) ReleaseCapture();
return activate;
}
void paint(HDC dc,const RECT &action,int textInset,COLORREF ink,COLORREF surface,bool highlighted) const
{
SetTextColor(dc,ink);
SetBkColor(dc,highlighted?hoverSurface(surface):surface);
ExtTextOutW(dc,action.left,action.top+textInset,ETO_OPAQUE|ETO_CLIPPED,&action,
label.data(),static_cast<UINT>(label.size()),nullptr);
TEXTMETRICW metrics{};
GetTextMetricsW(dc,&metrics);
const LONG underline=std::min(action.bottom-1,action.top+textInset+metrics.tmAscent+1);
const RECT line{action.left,underline,action.right,underline+1};
SetDCBrushColor(dc,ink);
FillRect(dc,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
};
}
+251
View File
@@ -0,0 +1,251 @@
bool isSharingError(int error)
{
return error==ERROR_SHARING_VIOLATION || error==ERROR_LOCK_VIOLATION;
}
constexpr DWORD lockProbeShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
constexpr DWORD lockProbeFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
DWORD probeDeleteAccess(const fs::path &path)
{
Handle probe{CreateFileW(path.c_str(),DELETE,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)};
return probe.value==INVALID_HANDLE_VALUE?GetLastError():ERROR_SUCCESS;
}
struct LockProcess
{
DWORD pid;
FILETIME started{};
std::wstring name;
};
struct LockScan
{
std::vector<LockProcess> processes;
bool incomplete{};
};
LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token stop)
{
LockScan result;
const auto query=reinterpret_cast<decltype(&NtQueryInformationFile)>(
GetProcAddress(GetModuleHandleW(L"ntdll.dll"),"NtQueryInformationFile"));
if(!query) { result.incomplete=true; return result; }
std::set<DWORD> pids;
std::vector<ULONG_PTR> buffer(128);
const auto inspect=[&](const fs::path &path) {
const auto error=probeDeleteAccess(path);
if(error==ERROR_SUCCESS) return;
if(!isSharingError(error))
{
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND) result.incomplete=true;
return;
}
Handle file{CreateFileW(path.c_str(),0,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) {result.incomplete=true;return;}
IO_STATUS_BLOCK status{};
// FileProcessIdsUsingFileInformation (47) returns an ULONG count followed by aligned ULONG_PTR PIDs.
auto code=query(file.value,&status,buffer.data(),static_cast<ULONG>(buffer.size()*sizeof(ULONG_PTR)),
static_cast<FILE_INFORMATION_CLASS>(47));
while((static_cast<ULONG>(code)==0xC0000023 || static_cast<ULONG>(code)==0x80000005 ||
static_cast<ULONG>(code)==0xC0000004) && buffer.size()<8192)
{
buffer.resize(buffer.size()*2);
code=query(file.value,&status,buffer.data(),static_cast<ULONG>(buffer.size()*sizeof(ULONG_PTR)),
static_cast<FILE_INFORMATION_CLASS>(47));
}
if(code<0 || status.Information<sizeof(ULONG_PTR)) {result.incomplete=true;return;}
ULONG count{};
memcpy(&count,buffer.data(),sizeof(count));
if(count>buffer.size()-1 || size_t(count)+1>status.Information/sizeof(ULONG_PTR))
{
result.incomplete=true;
return;
}
for(ULONG i=0;i<count;++i)
if(const auto pid=buffer[i+1];pid && pid<=MAXDWORD && pid!=GetCurrentProcessId())
pids.insert(static_cast<DWORD>(pid));
};
auto remaining=8192u;
const auto deadline=GetTickCount64()+4000;
for(const auto &path:paths)
{
if(stop.stop_requested()) return {};
inspect(path);
const auto attributes=GetFileAttributesW(path.c_str());
if(attributes==INVALID_FILE_ATTRIBUTES || !(attributes&FILE_ATTRIBUTE_DIRECTORY) ||
(attributes&FILE_ATTRIBUTE_REPARSE_POINT)) continue;
std::error_code error;
fs::recursive_directory_iterator it(path,error),end;
while(!error && it!=end)
{
if(stop.stop_requested()) return {};
if(!remaining || GetTickCount64()>=deadline) {result.incomplete=true;break;}
--remaining;
const auto item=it->path();
const auto flags=GetFileAttributesW(item.c_str());
if(flags==INVALID_FILE_ATTRIBUTES || flags&FILE_ATTRIBUTE_REPARSE_POINT)
it.disable_recursion_pending();
inspect(item);
it.increment(error);
}
if(error) result.incomplete=true;
}
for(const auto pid:pids)
{
Handle process{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,pid)};
LockProcess entry{pid};
if(process.value)
{
FILETIME exit{},kernel{},user{};
GetProcessTimes(process.value,&entry.started,&exit,&kernel,&user);
wchar_t path[32768];
DWORD count=std::size(path);
if(QueryFullProcessImageNameW(process.value,0,path,&count))
entry.name=fs::path(std::wstring_view(path,count)).filename().wstring();
}
if(entry.name.empty()) entry.name=L"Unknown process";
result.processes.push_back(std::move(entry));
}
return result;
}
struct LockDialog
{
std::vector<fs::path> paths;
std::vector<LockProcess> processes;
std::future<LockScan> scan;
std::stop_source stop;
};
constexpr UINT_PTR lockScanTimer=1;
void refreshLockProcesses(HWND window,LockDialog &state,std::shared_ptr<Handle> terminated={})
{
if(state.scan.valid()) return;
state.processes.clear();
SendDlgItemMessageW(window,431,LB_RESETCONTENT,0,0);
EnableWindow(GetDlgItem(window,433),FALSE);
EnableWindow(GetDlgItem(window,434),FALSE);
SetDlgItemTextW(window,430,L"Checking which processes are using the file or folder…");
try
{
std::packaged_task<LockScan()> task([paths=state.paths,stop=state.stop.get_token(),terminated=std::move(terminated)] {
if(terminated) WaitForSingleObject(terminated->value,2500);
return scanLockProcesses(paths,stop);
});
auto future=task.get_future();
if(!SetTimer(window,lockScanTimer,50,nullptr))
throw std::runtime_error("Could not start the process scan.");
std::thread(std::move(task)).detach();
state.scan=std::move(future);
}
catch(const std::exception &)
{
KillTimer(window,lockScanTimer);
EnableWindow(GetDlgItem(window,434),TRUE);
SetDlgItemTextW(window,430,L"Could not start the process scan.");
}
}
void endLockProcess(HWND window,LockDialog &state)
{
const auto index=SendDlgItemMessageW(window,431,LB_GETCURSEL,0,0);
if(index<0 || size_t(index)>=state.processes.size()) return;
const auto &entry=state.processes[index];
auto error=[&](const wchar_t *message) {
showFilesNotice(window,message,L"End process",{.tone=FilesNoticeTone::warning});
};
auto process=std::make_shared<Handle>();
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry.pid);
FILETIME started{},exited{},kernel{},user{};
BOOL critical{};
if(!process->value || !(entry.started.dwHighDateTime || entry.started.dwLowDateTime) ||
!GetProcessTimes(process->value,&started,&exited,&kernel,&user) ||
CompareFileTime(&started,&entry.started)!=0 || !IsProcessCritical(process->value,&critical) || critical)
{
error(L"This process has exited, is protected, or cannot be identified.");
return;
}
const auto question=L"End "+entry.name+L" (PID "+std::to_wstring(entry.pid)+
L")?\r\nUnsaved work in the process may be lost.";
if(showFilesNotice(window,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
return;
if(WaitForSingleObject(process->value,0)==WAIT_TIMEOUT && !TerminateProcess(process->value,1))
{
const auto message=ks::lastError(L"Could not end the process");
error(message.c_str());
return;
}
refreshLockProcesses(window,state,std::move(process));
}
INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
for(const auto id:{430,431}) SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
const auto list=GetDlgItem(window,431);
RECT bounds{};
GetWindowRect(list,&bounds);
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
installScrollBar(list,window);
layoutDialogButtons(window,432,{433,434,IDOK});
SendMessageW(window,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(window,IDOK));
refreshLockProcesses(window,*reinterpret_cast<LockDialog *>(lp));
return FALSE;
}
auto *data=reinterpret_cast<LockDialog *>(GetWindowLongPtrW(window,DWLP_USER));
if(!data) return FALSE;
auto &state=*data;
if(message==WM_TIMER && wp==lockScanTimer)
{
if(!state.scan.valid() || state.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
return TRUE;
KillTimer(window,lockScanTimer);
EnableWindow(GetDlgItem(window,434),TRUE);
try
{
auto result=state.scan.get();
for(auto &entry:result.processes)
{
const auto label=entry.name+L" (PID "+std::to_wstring(entry.pid)+L")";
if(SendDlgItemMessageW(window,431,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))>=0)
state.processes.push_back(std::move(entry));
}
SetDlgItemTextW(window,430,state.processes.empty()?
(result.incomplete?L"No processes found. Some items could not be checked.":L"No locking processes found."):
(result.incomplete?L"Possible locking processes. The scan was incomplete.":L"Processes using locked files or folders."));
if(!state.processes.empty())
{
SendDlgItemMessageW(window,431,LB_SETCURSEL,0,0);
EnableWindow(GetDlgItem(window,433),TRUE);
}
}
catch(const std::exception &) {SetDlgItemTextW(window,430,L"Could not check for locking processes.");}
return TRUE;
}
if(message==WM_COMMAND)
{
switch(LOWORD(wp))
{
case 433: endLockProcess(window,state); return TRUE;
case 434: refreshLockProcesses(window,state); return TRUE;
case IDOK:
case IDCANCEL: FilesModalDialog::finish(window,IDCANCEL); return TRUE;
}
}
if(message==WM_CLOSE) {FilesModalDialog::finish(window,IDCANCEL);return TRUE;}
return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432},false,GetDlgItem(window,431));
}
void showLockProcesses(HWND owner,std::vector<fs::path> paths)
{
LockDialog state{std::move(paths)};
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,lockProcessesDialog,
reinterpret_cast<LPARAM>(&state));
state.stop.request_stop();
}
+1697 -560
View File
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <windows.h>
#include <string>
namespace ks::files
{
inline std::wstring windowsPowerShell()
{
wchar_t system[MAX_PATH]{};
const auto length=GetSystemDirectoryW(system,MAX_PATH);
return length && length<MAX_PATH
? std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe" : std::wstring{};
}
}
+99
View File
@@ -0,0 +1,99 @@
#pragma once
#include <windows.h>
#include <algorithm>
namespace ks::files
{
inline int scrollBarWidth(HWND window) {return std::max(7,MulDiv(12,GetDpiForWindow(window),96));}
inline int scrollArrowHeight(RECT bounds)
{
return std::min(bounds.right-bounds.left,(bounds.bottom-bounds.top)/3);
}
struct ScrollPosition
{
int count, visible, top;
int last() const {return std::max(0,count-visible);}
RECT thumb(RECT track) const
{
const auto arrow=scrollArrowHeight(track);
track.top+=arrow;
track.bottom-=arrow;
const int height=track.bottom-track.top;
if(height<=0 || !last()) return {};
const int size=std::clamp(MulDiv(height,visible,count),std::min(height,arrow),height);
track.top+=MulDiv(std::clamp(top,0,last()),height-size,last());
track.bottom=track.top+size;
return track;
}
int click(RECT track,int y) const
{
const auto arrow=scrollArrowHeight(track);
const auto grip=thumb(track);
const int delta=y<track.top+arrow?-1:y>=track.bottom-arrow?1:
y<grip.top?-visible:y>=grip.bottom?visible:0;
return std::clamp(top+delta,0,last());
}
int drag(RECT track,int y,int offset) const
{
const auto grip=thumb(track);
const auto arrow=scrollArrowHeight(track);
const auto travel=track.bottom-track.top-2*arrow-(grip.bottom-grip.top);
return travel>0?std::clamp(MulDiv(y-track.top-arrow-offset,last(),travel),0,last()):top;
}
};
inline void paintScrollBar(HDC dc,RECT track,ScrollPosition position,COLORREF background)
{
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc,background);
FillRect(dc,&track,brush);
if(!position.last()) return;
const auto lighter=[&](int divisor){return RGB(GetRValue(background)+(257-GetRValue(background))/divisor,
GetGValue(background)+(257-GetGValue(background))/divisor,
GetBValue(background)+(257-GetBValue(background))/divisor);};
const auto ink=lighter(4),dots=lighter(7);
const int height=scrollArrowHeight(track);
struct
{
BITMAPINFOHEADER header{sizeof(BITMAPINFOHEADER),4,4,1,32,BI_RGB};
DWORD pixels[16]{};
} tile;
for(int y=0;y<4;++y)
for(int x=0;x<4;++x)
{
const auto color=y%2==0 && x%2==y/2?dots:background;
// DIB pixels are stored bottom-up in BGR order.
tile.pixels[(3-y)*4+x]=RGB(GetBValue(color),GetGValue(color),GetRValue(color));
}
if(const auto pattern=CreateDIBPatternBrushPt(&tile,DIB_RGB_COLORS))
{
const RECT channel{track.left,track.top+height,track.right,track.bottom-height};
POINT origin{};
SetBrushOrgEx(dc,channel.left,channel.top,&origin);
FillRect(dc,&channel,pattern);
SetBrushOrgEx(dc,origin.x,origin.y,nullptr);
DeleteObject(pattern);
}
SetDCBrushColor(dc,ink);
const auto thumb=position.thumb(track);
FillRect(dc,&thumb,brush);
const int middle=(track.left+track.right)/2;
const int radius=std::max(0,(height-3)/2);
for(int row=0;row<=radius;++row)
{
const int y=track.top+(height-radius-1)/2+row;
const int mirrored=track.bottom-1-(y-track.top);
const RECT up{middle-row,y,middle+row+1,y+1};
const RECT down{middle-row,mirrored,middle+row+1,mirrored+1};
FillRect(dc,&up,brush);
FillRect(dc,&down,brush);
}
}
}
+1
View File
@@ -128,6 +128,7 @@ struct FileRowStyle
{
COLORREF foreground,background;
unsigned decorations{};
bool operator==(const FileRowStyle &) const = default;
};
FileRowStyle resolveFileStyle(std::wstring_view extension,bool file,bool dimmed,bool protectedRow,
COLORREF foreground,COLORREF background,const std::vector<FileStyle> &styles=fileStyles,
+3 -4
View File
@@ -1,5 +1,6 @@
#pragma once
#include "files_powershell.h"
#include <mutex>
#include <string>
#include <thread>
@@ -50,10 +51,8 @@ public:
startup.lpAttributeList=attributes;
PROCESS_INFORMATION info{};
wchar_t command[]=L"powershell.exe -NoLogo -NoProfile -NoExit -Command \"Remove-Module PSReadLine -ErrorAction SilentlyContinue; function global:prompt { $location = Get-Location; $path = if ($location.Provider.Name -eq 'FileSystem') { [Uri]::EscapeDataString($location.ProviderPath) }; ([string][char]27) + ']633;ks-directory:' + $path + [char]7 + [char]27 + '[?25l' }; Clear-Host\"";
wchar_t system[MAX_PATH]{};
const auto length=GetSystemDirectoryW(system,MAX_PATH);
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
const bool started=length && length<MAX_PATH &&
const auto shell=ks::files::windowsPowerShell();
const bool started=!shell.empty() &&
UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
console,sizeof(console),nullptr,nullptr) &&
CreateProcessW(shell.c_str(),command,nullptr,nullptr,FALSE,EXTENDED_STARTUPINFO_PRESENT,
+35 -3
View File
@@ -3,6 +3,9 @@
#ifdef __MINGW32__
__CRT_UUID_DECL(ICoreWebView2_3, 0xA0D6DF20, 0x3B92, 0x416D, 0xAA, 0x0C, 0x43, 0x7A, 0x9C, 0x72, 0x78, 0x57)
__CRT_UUID_DECL(ICoreWebView2Controller2, 0xc979903e, 0xd4ca, 0x4228, 0x92, 0xeb, 0x47, 0xee, 0x3f, 0xa9, 0x6e, 0xab)
__CRT_UUID_DECL(ICoreWebView2ControllerOptions3, 0xb32b191a, 0x8998, 0x57ca, 0xb7, 0xcb, 0xe0, 0x46, 0x17, 0xe4, 0xce, 0x4a)
__CRT_UUID_DECL(ICoreWebView2Environment10, 0xee0eb9df, 0x6f12, 0x46ce, 0xb5, 0x3f, 0x3f, 0x47, 0xb9, 0xc9, 0x28, 0xe0)
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler, 0x4e8a3389, 0xc9d8, 0x4bd2, 0xb6, 0xb5, 0x12, 0x4f, 0xee, 0x6c, 0xc1, 0x4d)
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4819f3, 0xc9b7, 0x4260, 0x81, 0x27, 0xc9, 0xf5, 0xbd, 0xe7, 0xf6, 0x8c)
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
@@ -16,6 +19,8 @@ __CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa
#include <memory>
#include <utility>
inline constexpr COLORREF terminalSurface=RGB(24,24,24);
template<class Interface, class... Args>
class TerminalCallback final : public Interface
{
@@ -56,6 +61,7 @@ class FilesTerminalView
RECT bounds{};
bool ready{};
bool visible{};
bool waitForReady{};
public:
~FilesTerminalView() { close(); }
void focus()
@@ -94,9 +100,10 @@ public:
RECT current{};
if(FAILED(controller->get_Bounds(&current)) || !EqualRect(&current,&bounds))
controller->put_Bounds(bounds);
const bool showController=show && (!waitForReady || ready);
BOOL currentVisibility{};
if(FAILED(controller->get_IsVisible(&currentVisibility)) || !!currentVisibility!=show)
controller->put_IsVisible(show);
if(FAILED(controller->get_IsVisible(&currentVisibility)) || !!currentVisibility!=showController)
controller->put_IsVisible(showController);
}
void close()
{
@@ -140,6 +147,9 @@ public:
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
const auto assets=folder/L"terminal";
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
waitForReady=!markdown;
constexpr COREWEBVIEW2_COLOR background{
255,GetRValue(terminalSurface),GetGValue(terminalSurface),GetBValue(terminalSurface)};
lifetime=std::make_shared<int>(0);
const std::weak_ptr<int> alive=lifetime;
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
@@ -153,6 +163,12 @@ public:
if(alive.expired()) return S_OK;
if(FAILED(result) || !view) { failed(); return S_OK; }
controller=view;
if(!markdown)
{
view->put_IsVisible(FALSE);
Microsoft::WRL::ComPtr<ICoreWebView2Controller2> colors;
if(SUCCEEDED(controller.As(&colors))) colors->put_DefaultBackgroundColor(background);
}
view->get_CoreWebView2(&web);
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
@@ -207,7 +223,11 @@ public:
uri==source &&
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
{
if(wcscmp(value,L"ready")==0) ready=true;
if(!ready && wcscmp(value,L"ready")==0)
{
ready=true;
if(waitForReady) layout(bounds,visible);
}
if(ready) receive(value);
}
CoTaskMemFree(value);
@@ -222,6 +242,18 @@ public:
layout(bounds,visible);
return S_OK;
});
if(!markdown)
{
Microsoft::WRL::ComPtr<ICoreWebView2Environment10> configurable;
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions> options;
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions3> colors;
if(SUCCEEDED(env->QueryInterface(IID_PPV_ARGS(&configurable))) &&
SUCCEEDED(configurable->CreateCoreWebView2ControllerOptions(&options)) &&
SUCCEEDED(options.As(&colors)) &&
SUCCEEDED(colors->put_DefaultBackgroundColor(background)) &&
SUCCEEDED(configurable->CreateCoreWebView2ControllerWithOptions(host,options.Get(),completed.Get())))
return S_OK;
}
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
return S_OK;
});
+142 -42
View File
@@ -38,6 +38,15 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
return result;
}
HANDLE trackReplacement(const std::filesystem::path &path)
{
// A metadata-only handle survives the rename without blocking ReplaceFile.
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
return handle;
}
uint64_t fileSize(HANDLE file)
{
LARGE_INTEGER size{};
@@ -97,10 +106,87 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file");
return path;
}
bool isUtf16(TextEncoding encoding)
{
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
}
TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(std::move(path)), editable_(editable)
std::string_view signature(TextEncoding encoding)
{
switch(encoding)
{
case TextEncoding::utf16le: return "\xff\xfe";
case TextEncoding::utf16be: return "\xfe\xff";
case TextEncoding::utf8: return "\xef\xbb\xbf";
default: return {};
}
}
std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
{
const int length=static_cast<int>(bytes.size());
const auto required=MultiByteToWideChar(codePage,flags,bytes.data(),length,nullptr,0);
if(!required) fail("Decode text");
std::wstring units(required,L'\0');
if(!MultiByteToWideChar(codePage,flags,bytes.data(),length,units.data(),required)) fail("Decode text");
return units;
}
std::string encode(std::string_view utf8,TextEncoding encoding)
{
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
const auto units=decodeMultibyte(utf8,CP_UTF8,MB_ERR_INVALID_CHARS);
if(encoding==TextEncoding::windows1252)
{
BOOL substituted{};
const int length=static_cast<int>(units.size());
const auto required=WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,
nullptr,0,nullptr,&substituted);
if(!required) fail("Encode Windows-1252");
if(substituted) throw std::runtime_error("Some characters cannot be saved as Windows-1252. Choose a Unicode encoding.");
std::string bytes(required,'\0');
if(!WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,bytes.data(),required,nullptr,&substituted))
fail("Encode Windows-1252");
return bytes;
}
std::string bytes(units.size()*2,'\0');
const size_t low=encoding==TextEncoding::utf16le?0:1;
for(size_t i=0;i<units.size();++i)
{
bytes[2*i+low]=static_cast<char>(units[i]&0xff);
bytes[2*i+1-low]=static_cast<char>(units[i]>>8);
}
return bytes;
}
std::string convertLineEndings(std::string_view text,TextLineEnding ending)
{
if(ending==TextLineEnding::preserve) return std::string(text);
const std::string_view replacement=ending==TextLineEnding::crlf?"\r\n":ending==TextLineEnding::lf?"\n":"\r";
std::string result;
result.reserve(text.size());
for(size_t start=0;start<text.size();)
{
const auto next=text.find_first_of("\r\n",start);
result.append(text.substr(start,next==text.npos?text.npos:next-start));
if(next==text.npos) break;
result.append(replacement);
start=next+1;
if(text[next]=='\r' && start<text.size() && text[start]=='\n') ++start;
}
return result;
}
}
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
: path_(std::move(path)), editable_(editable)
{
if(path_.empty())
{
if(encoding!=TextEncoding::automatic) encoding_=encoding;
return;
}
File source{openSource(path_, editable)};
if (editable)
{
@@ -115,13 +201,15 @@ TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(st
}
size_ = fileSize(source.handle);
const auto prefix = read(source.handle, 0, static_cast<size_t>(std::min<uint64_t>(3, size_)));
if (prefix.starts_with("\xef\xbb\xbf")) bom_ = 3;
else if (prefix.starts_with("\xff\xfe") || prefix.starts_with("\xfe\xff"))
if(encoding==TextEncoding::automatic)
{
encoding_ = prefix.starts_with("\xff") ? Encoding::utf16le : Encoding::utf16be;
bom_ = 2;
if (size_ % 2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
encoding=TextEncoding::utf8;
for(const auto candidate:{TextEncoding::utf16le,TextEncoding::utf16be})
if(prefix.starts_with(signature(candidate))) encoding=candidate;
}
encoding_=encoding;
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
source_ = source.release();
}
@@ -135,8 +223,9 @@ const wchar_t *TextDocument::encodingName() const
{
switch (encoding_)
{
case Encoding::utf16le: return L"UTF-16 LE";
case Encoding::utf16be: return L"UTF-16 BE";
case TextEncoding::utf16le: return L"UTF-16 LE";
case TextEncoding::utf16be: return L"UTF-16 BE";
case TextEncoding::windows1252: return L"Windows-1252";
default: return bom_ ? L"UTF-8 BOM" : L"UTF-8";
}
}
@@ -160,40 +249,45 @@ uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
if (page >= pages()) return size_;
const auto offset = bom_ + page * pageBytes;
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
const auto unit = isUtf16(encoding_) ? 2u : 1u;
const auto sample = read(source, offset - unit,
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
const auto getUnit = [&](size_t i) -> unsigned {
const auto first = static_cast<unsigned char>(sample[i]);
if (unit == 1) return first;
const auto second = static_cast<unsigned char>(sample[i + 1]);
return encoding_ == Encoding::utf16le ? first | (second << 8) : (first << 8) | second;
return encoding_ == TextEncoding::utf16le ? first | (second << 8) : (first << 8) | second;
};
if (getUnit(0) == '\n') return offset;
for (size_t i = unit; i + unit < sample.size(); i += unit)
if (getUnit(i) == '\n') return offset + i;
size_t i = unit;
if (unit == 1)
if (encoding_ == TextEncoding::utf8)
{
// Advance past at most one UTF-8 code point, even on malformed input.
while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i;
}
else if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
else if (isUtf16(encoding_))
if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit;
return offset + i - unit;
}
std::string TextDocument::decode(std::string bytes) const
{
if (encoding_ == Encoding::utf8 || bytes.empty()) return bytes;
if (encoding_ == TextEncoding::utf8 || bytes.empty()) return bytes;
std::wstring units;
units.resize(bytes.size() / 2);
for (size_t i = 0; i < units.size(); ++i)
if(encoding_==TextEncoding::windows1252) units=decodeMultibyte(bytes,1252,0);
else
{
const auto a = static_cast<unsigned char>(bytes[2 * i]);
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
units[i] = static_cast<wchar_t>(encoding_ == Encoding::utf16le ? a | (b << 8) : (a << 8) | b);
units.resize(bytes.size() / 2);
for (size_t i = 0; i < units.size(); ++i)
{
const auto a = static_cast<unsigned char>(bytes[2 * i]);
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
}
}
const auto length = static_cast<int>(units.size());
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
@@ -204,25 +298,6 @@ std::string TextDocument::decode(std::string bytes) const
return result;
}
std::string TextDocument::encode(std::string_view utf8) const
{
if (encoding_ == Encoding::utf8 || utf8.empty()) return std::string(utf8);
const auto length = static_cast<int>(utf8.size());
const int required = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, nullptr, 0);
if (!required) fail("Encode UTF-16");
std::wstring units(required, L'\0');
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, units.data(), required))
fail("Encode UTF-16");
std::string bytes(units.size() * 2, '\0');
const int low = encoding_ == Encoding::utf16le ? 0 : 1;
for (size_t i = 0; i < units.size(); ++i)
{
bytes[2 * i + low] = static_cast<char>(units[i] & 0xff);
bytes[2 * i + 1 - low] = static_cast<char>(units[i] >> 8);
}
return bytes;
}
std::string TextDocument::readPage(uint64_t page) const
{
if (const auto it = changes_.find(page); it != changes_.end())
@@ -232,6 +307,7 @@ std::string TextDocument::readPage(uint64_t page) const
std::string TextDocument::readOriginal(uint64_t page) const
{
if(path_.empty()) return {};
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
const auto start = boundary(page,source);
@@ -298,17 +374,14 @@ bool TextDocument::save()
for (const auto &[page, change] : changes_)
{
copyUntil(offset, boundary(page));
append(encode(read(spool_, change.offset, change.size)));
append(encode(read(spool_, change.offset, change.size),encoding_));
offset = boundary(page + 1);
}
copyUntil(offset, size_);
if (!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
// A metadata-only handle survives the rename without blocking ReplaceFile's exclusive open.
File replacement{CreateFileW(pending.path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)};
if (replacement.handle == INVALID_HANDLE_VALUE) fail("Track replacement file");
File replacement{trackReplacement(pending.path)};
File current{openSource(path_, true)};
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
const auto backup = temporaryPath(path_.parent_path());
@@ -336,4 +409,31 @@ bool TextDocument::save()
spoolSize_ = 0;
return source_ != INVALID_HANDLE_VALUE;
}
bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
{
if(!path_.empty() || !editable_) throw std::logic_error("The document is not a new editable file.");
if(format.encoding==TextEncoding::automatic) format.encoding=TextEncoding::utf8;
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
const auto bom=format.bom?signature(format.encoding):std::string_view{};
PendingSave pending;
File output;
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
write(output.handle,bom);
write(output.handle,bytes);
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
File replacement{trackReplacement(pending.path)};
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Create new file");
pending.path.clear();
path_=std::move(path);
encoding_=format.encoding;
bom_=bom.size();
size_=bom_+bytes.size();
changes_.clear();
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
spoolSize_=0;
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
return source_!=INVALID_HANDLE_VALUE;
}
}
+14 -4
View File
@@ -9,13 +9,24 @@
namespace ks::files
{
enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 };
enum class TextLineEnding { preserve, crlf, lf, cr };
struct TextSaveFormat
{
TextEncoding encoding=TextEncoding::utf8;
bool bom{};
TextLineEnding lineEnding=TextLineEnding::preserve;
};
class TextDocument
{
public:
static constexpr uint64_t pageBytes = 1024 * 1024;
static constexpr size_t editLimit = 8 * pageBytes;
explicit TextDocument(std::filesystem::path path, bool editable = true);
explicit TextDocument(std::filesystem::path path, bool editable = true,
TextEncoding encoding=TextEncoding::automatic);
~TextDocument();
TextDocument(const TextDocument &) = delete;
TextDocument &operator=(const TextDocument &) = delete;
@@ -29,10 +40,10 @@ public:
bool modified() const { return !changes_.empty(); }
bool modifiedWith(uint64_t page, std::string_view current) const;
bool save();
bool saveNew(std::filesystem::path path, TextSaveFormat format);
const wchar_t *encodingName() const;
private:
enum class Encoding { utf8, utf16le, utf16be };
struct Change { uint64_t offset; size_t size; };
std::filesystem::path path_;
@@ -40,13 +51,12 @@ private:
HANDLE spool_ = INVALID_HANDLE_VALUE;
uint64_t size_{}, spoolSize_{};
size_t bom_{};
Encoding encoding_ = Encoding::utf8;
TextEncoding encoding_ = TextEncoding::utf8;
bool editable_;
std::map<uint64_t, Change> changes_;
std::string decode(std::string bytes) const;
uint64_t boundary(uint64_t page,HANDLE source) const;
std::string readOriginal(uint64_t page) const;
std::string encode(std::string_view utf8) const;
};
}
+151 -62
View File
@@ -2,6 +2,7 @@
#include "files_text_preferences.h"
#include "files_menu_paint.h"
#include "files_menu_navigation.h"
#include "files_scrollbar.h"
#include "files_history_date.h"
#include "files_text_document.h"
#include "files_text_language.h"
@@ -317,10 +318,17 @@ struct FarPopup
FarDropDownPalette palette;
HFONT font{};
int rowHeight{},inset{},visible{},top{},current{},result=-1;
int dragOffset=-1;
bool done{};
int rowTop() const { return inset+1+rowHeight/2; }
int bottomMargin() const { return inset+1+rowHeight/4; }
ScrollPosition scrollPosition() const {return {static_cast<int>(rows.size()),visible,top};}
RECT scrollTrack(HWND window,RECT bounds) const
{
const LONG right=bounds.right-inset-1;
return {std::max(bounds.left,right-scrollBarWidth(window)),rowTop(),right,rowTop()+visible*rowHeight};
}
void select(int row)
{
@@ -370,8 +378,9 @@ struct FarPopup
SetTextColor(dc,palette.text);
SelectObject(dc,font);
const LONG rowLeft=frame.left+inset;
const LONG scrollWidth=static_cast<int>(rows.size())>visible?rowHeight/2:0;
const LONG rowRight=scrollWidth?bounds.right-scrollWidth:frame.right-1;
const auto position=scrollPosition();
const auto track=scrollTrack(window,bounds);
const LONG rowRight=position.last()?track.left:frame.right-1;
LONG y=rowTop();
for(int offset=0;offset<visible;++offset,y+=rowHeight)
{
@@ -400,22 +409,7 @@ struct FarPopup
DrawTextW(dc,entry.text.data(),static_cast<int>(entry.text.size()),&box,
DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS|(entry.index<0?DT_CENTER:DT_LEFT));
}
if(scrollWidth)
{
RECT up{rowRight,rowTop(),bounds.right,rowTop()+rowHeight};
RECT down{rowRight,y-rowHeight,bounds.right,y};
DrawTextW(dc,L"▲",1,&up,DT_SINGLELINE|DT_CENTER|DT_VCENTER);
DrawTextW(dc,L"▼",1,&down,DT_SINGLELINE|DT_CENTER|DT_VCENTER);
RECT track{up.left,up.bottom,up.right,down.top};
for(LONG line=track.top;line<track.bottom;line+=2)
for(LONG x=track.left+(line%4==0?0:1);x<track.right;x+=2)
SetPixelV(dc,x,line,palette.text);
const auto travel=std::max(0L,track.bottom-track.top-rowHeight);
const auto thumbY=track.top+MulDiv(top,travel,static_cast<int>(rows.size())-visible);
RECT thumb{track.left,thumbY,track.right,std::min(track.bottom,thumbY+rowHeight)};
SetDCBrushColor(dc,palette.text);
FillRect(dc,&thumb,brush);
}
if(position.last()) paintScrollBar(dc,track,position,palette.surface);
}
};
@@ -482,17 +476,28 @@ LRESULT CALLBACK farPopupWindow(HWND window,UINT message,WPARAM wp,LPARAM lp)
RECT bounds{};
GetClientRect(window,&bounds);
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto position=state->scrollPosition();
const auto track=state->scrollTrack(window,bounds);
if(state->dragOffset>=0)
{
if(message==WM_MOUSEMOVE) state->top=position.drag(track,point.y,state->dragOffset);
if(message==WM_LBUTTONUP) state->dragOffset=-1;
InvalidateRect(window,nullptr,FALSE);
return 0;
}
if(!PtInRect(&bounds,point))
{
if(message==WM_LBUTTONDOWN) state->done=true;
return 0;
}
const auto offset=(point.y-state->rowTop())/state->rowHeight;
const bool scroll=static_cast<int>(state->rows.size())>state->visible &&
point.x>=bounds.right-state->rowHeight/2;
const bool scroll=position.last() && PtInRect(&track,point);
if(scroll && message==WM_LBUTTONDOWN)
state->top=std::clamp(state->top+(offset<state->visible/2?-1:1),0,
static_cast<int>(state->rows.size())-state->visible);
{
const auto thumb=position.thumb(track);
if(PtInRect(&thumb,point)) state->dragOffset=point.y-thumb.top;
else state->top=position.click(track,point.y);
}
if(!scroll && point.y>=state->rowTop() && offset<state->visible)
{
const auto row=state->top+offset;
@@ -724,13 +729,18 @@ class TextWindow
{
public:
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer,
std::string_view fragment)
std::string_view fragment,TextOpenOptions options)
: original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()),
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
search{dialogs}, previewFragment(fragment)
{
if (peer) remote=std::make_unique<RemoteTextFile>(RemoteTextFile{*peer,original});
else document=std::make_unique<TextDocument>(original,edit);
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
if(options.encoding!=TextEncoding::automatic)
{
newFormat.encoding=options.encoding;
newFormat.bom=options.encoding==TextEncoding::utf16le || options.encoding==TextEncoding::utf16be;
}
for (int index = 0; index < GetLexerCount(); ++index)
{
char name[128]{};
@@ -759,6 +769,9 @@ private:
std::unique_ptr<TextDocument> document;
std::wstring filename;
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
bool draft{};
TextSaveFormat newFormat;
std::filesystem::path pendingSavePath;
HICON smallIcon{},largeIcon{};
TextPreferences prefs;
TextWindowFont filesFont;
@@ -851,6 +864,9 @@ private:
bool dirty() const { return stagedDirty || (!busy() && uploadPending) || currentChanged(); }
bool busy() const { return saving.valid(); }
void invalidate() const { InvalidateRect(window, nullptr, FALSE); }
RECT statusBounds() const;
void invalidateStatus() const;
void invalidateHints() const;
void initializeDocument();
void finishOpen();
@@ -1337,22 +1353,25 @@ void TextWindow::finishOpen()
void TextWindow::saveFile(bool closeWhenDone)
{
if (busy() || !edit) return;
auto destination=original;
if(draft && !search.style.saveOptions(window,destination,newFormat)) return;
stagePage();
if (!stagedDirty && !uploadPending)
if (!draft && !stagedDirty && !uploadPending)
{
if (closeWhenDone) DestroyWindow(window);
else if (std::exchange(switchAfterSave, false)) changeMode();
return;
}
pendingCaret = send(SCI_GETCURRENTPOS);
if(draft) pendingSavePath=destination;
closeAfterSave = closeWhenDone;
if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer.");
send(SCI_SETREADONLY, TRUE);
try
{
saving=std::async(std::launch::async,[this]
saving=std::async(std::launch::async,[this,destination=std::move(destination)]
{
const auto reopened=document->save();
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
if(remote)
{
uploadPending=true;
@@ -1379,6 +1398,14 @@ void TextWindow::finishSave()
const auto change = std::exchange(switchAfterSave, false);
const auto reopened = saving.get();
stagedDirty = false;
const bool created=std::exchange(draft,false);
if(created)
{
original=std::move(pendingSavePath);
filename=original.filename().wstring();
navigationHistory.clear();
updateTitle();
}
if (!reopened)
{
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
@@ -1387,6 +1414,12 @@ void TextWindow::finishSave()
}
if (closeAfterSave) { DestroyWindow(window); return; }
if (change) { changeMode(); return; }
if(created)
{
initializeDocument();
send(SCI_GOTOPOS,std::min<LRESULT>(pendingCaret,send(SCI_GETLENGTH)));
return;
}
if (pageTotal == 1 && document->pages() == 1)
{
fileSize = document->size();
@@ -1403,7 +1436,7 @@ void TextWindow::requestClose()
if (busy()) return;
if (needsSave())
{
const auto answer = search.style.confirmSave(window);
const auto answer = search.style.confirmSave(window,draft);
if (answer == IDCANCEL) return;
if (answer == IDYES) { saveFile(true); return; }
if (answer != IDNO) return;
@@ -1418,10 +1451,11 @@ bool TextWindow::needsSave() const
void TextWindow::toggleMode()
{
if(navigation.valid()) return;
if (busy() || navigation.valid()) return;
if(draft) return;
if (edit && needsSave())
{
const auto answer = search.style.confirmSave(window);
const auto answer = search.style.confirmSave(window,false);
if (answer == IDYES)
{
switchAfterSave = true;
@@ -1542,7 +1576,7 @@ void TextWindow::updatePreview()
}
if(ctrl && !alt && key==VK_TAB)
{
PostMessageW(window,cycleWindow,0,0);
PostMessageW(window,cycleWindow,(GetKeyState(VK_SHIFT)&0x8000)!=0,0);
return true;
}
if(key==VK_BROWSER_BACK || key==VK_BROWSER_FORWARD || (alt && (key==VK_LEFT || key==VK_RIGHT)))
@@ -1674,7 +1708,7 @@ void TextWindow::previewMessage(const std::wstring &value)
const auto action=message.at("action").get<std::string>();
if(action=="cycle")
{
PostMessageW(window,cycleWindow,0,0);
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
return;
}
if(action=="failed")
@@ -1856,6 +1890,58 @@ void TextWindow::layout()
invalidate();
}
RECT TextWindow::statusBounds() const
{
RECT bounds{};
GetClientRect(window,&bounds);
bounds.top=chromeHeight();
bounds.bottom=2*bounds.top;
return bounds;
}
void TextWindow::invalidateStatus() const
{
const auto bounds=statusBounds();
InvalidateRect(window,&bounds,FALSE);
}
void TextWindow::invalidateHints() const
{
RECT bounds{};
GetClientRect(window,&bounds);
bounds.top=std::max(0L,bounds.bottom-chromeHeight());
InvalidateRect(window,&bounds,FALSE);
}
void drawEditorStatus(HDC dc,RECT bounds,HFONT font,COLORREF background,COLORREF foreground,
int inset,const std::wstring &status)
{
const auto width=bounds.right-bounds.left,height=bounds.bottom-bounds.top;
if(width<=0 || height<=0) return;
const auto memory=CreateCompatibleDC(dc);
const auto bitmap=memory?CreateCompatibleBitmap(dc,width,height):nullptr;
const auto target=bitmap?memory:dc;
const auto oldBitmap=bitmap?SelectObject(memory,bitmap):nullptr;
const auto oldFont=SelectObject(target,font);
auto row=bitmap?RECT{0,0,width,height}:bounds;
SetDCBrushColor(target,background);
FillRect(target,&row,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
SetBkMode(target,TRANSPARENT);
SetTextColor(target,foreground);
row.left+=inset;
row.right-=inset;
if(row.left<row.right)
DrawTextW(target,status.c_str(),-1,&row,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
SelectObject(target,oldFont);
if(bitmap)
{
BitBlt(dc,bounds.left,bounds.top,width,height,memory,0,0,SRCCOPY);
SelectObject(memory,oldBitmap);
DeleteObject(bitmap);
}
if(memory) DeleteDC(memory);
}
void TextWindow::paint()
{
PAINTSTRUCT paint{};
@@ -1865,12 +1951,12 @@ void TextWindow::paint()
const auto row = chromeHeight();
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc, color(TextColor::background));
FillRect(dc, &client, brush);
const RECT body{0,2*row,client.right,std::max<LONG>(2*row,client.bottom-row)};
FillRect(dc, &body, brush);
SetDCBrushColor(dc, color(TextColor::chromebg));
RECT menuBar{0, 0, client.right, row};
RECT top{0, row, client.right, 2 * row};
const RECT top=statusBounds();
RECT bottom{0, client.bottom - row, client.right, client.bottom};
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
FillRect(dc, &menuBar, brush);
const auto chromeFont = createChromeFont();
@@ -1899,27 +1985,27 @@ void TextWindow::paint()
}
SetTextColor(dc, color(TextColor::chrome));
bottom.left += scale(7);
const auto position = send(SCI_GETCURRENTPOS);
const auto line = send(SCI_LINEFROMPOSITION, position) + 1;
const auto column = send(SCI_GETCOLUMN, position) + 1;
const auto displayLanguage = textLanguageLabel(language);
auto status = filename + (edit ? L" (Edit)" : L" (View)") + (dirty() ? L" *" : L"") +
L" │ " + (document?document->encodingName():L"Loading…") + L" │ " + displayLanguage +
L" │ Ln " + std::to_wstring(line) + L":" + std::to_wstring(column);
if (pageTotal > 1)
status += L" │ Page " + std::to_wstring(page + 1) + L"/" + std::to_wstring(pageTotal) +
L" @ " + std::to_wstring(pageOffset);
status += L" │ " + std::to_wstring(fileSize) + L" B";
RECT statusPaint{};
if(IntersectRect(&statusPaint,&top,&paint.rcPaint))
{
const auto position=send(SCI_GETCURRENTPOS);
const auto line=send(SCI_LINEFROMPOSITION,position)+1;
const auto column=send(SCI_GETCOLUMN,position)+1;
auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+
L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+
L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column);
if(pageTotal>1)
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
L" @ "+std::to_wstring(pageOffset);
status+=L" │ "+std::to_wstring(fileSize)+L" B";
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
}
const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" :
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
previewVisible ? L"F6 Edit Ctrl+W Close" :
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
top.left += scale(12);
top.right -= scale(12);
if (top.left < top.right)
DrawTextW(dc, status.c_str(), -1, &top, format | DT_RIGHT);
DrawTextW(dc, hints, -1, &bottom, format);
SelectObject(dc, previous);
DeleteObject(chromeFont);
@@ -2039,6 +2125,7 @@ void TextWindow::notify(const SCNotification &notice)
case SCN_MODIFIED:
if (notice.modificationType & SC_MOD_INSERTCHECK)
{
const auto hadWarning=insertRejected;
if (send(SCI_GETLENGTH) + notice.length > static_cast<LRESULT>(TextDocument::editLimit))
{
send(SCI_CHANGEINSERTION, 0, reinterpret_cast<LPARAM>(""));
@@ -2046,6 +2133,7 @@ void TextWindow::notify(const SCNotification &notice)
MessageBeep(MB_ICONWARNING);
}
else insertRejected = false;
if(hadWarning!=insertRejected) invalidateHints();
}
if (notice.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
{
@@ -2053,8 +2141,8 @@ void TextWindow::notify(const SCNotification &notice)
undoBytes += static_cast<size_t>(notice.length) + 64;
if (undoBytes >= 32 * TextDocument::pageBytes)
PostMessageW(window, trimUndo, 0, 0);
invalidateStatus();
}
invalidate();
break;
case SCN_CHARADDED:
if (edit && prefs.autoIndent && (notice.ch == '\n' || (notice.ch == '\r' && send(SCI_GETEOLMODE) == SC_EOL_CR)))
@@ -2074,7 +2162,7 @@ void TextWindow::notify(const SCNotification &notice)
case SCN_UPDATEUI:
case SCN_SAVEPOINTREACHED:
case SCN_SAVEPOINTLEFT:
invalidate();
invalidateStatus();
break;
}
}
@@ -2208,7 +2296,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
return 0;
}
case WM_SETFOCUS: self->focusContent(); return 0;
case cycleWindow: cycleTextWindows(window); return 0;
case cycleWindow: cycleTextWindows(window,wparam!=0); return 0;
case WM_KEYDOWN:
if(self->previewWanted && !self->previewVisible)
{
@@ -2407,7 +2495,7 @@ void textWindowOwnerClosed()
if(textWindows.empty()) PostQuitMessage(0);
}
bool cycleTextWindows(HWND current)
bool cycleTextWindows(HWND current,bool reverse)
{
if(!current || (current!=filesOwner && !textWindows.contains(current))) return false;
std::vector<HWND> windows;
@@ -2417,11 +2505,12 @@ bool cycleTextWindows(HWND current)
if(windows.size()<2) return false;
const auto from=std::find(windows.begin(),windows.end(),current);
if(from==windows.end()) return false;
auto to=std::next(from);
if(to==windows.end()) to=windows.begin();
if(IsIconic(*to)) ShowWindow(*to,SW_RESTORE);
SetForegroundWindow(*to);
if(*to!=filesOwner) SendMessageW(*to,WM_SETFOCUS,0,0);
const auto index=static_cast<size_t>(from-windows.begin());
const auto step=reverse?windows.size()-1:1;
const auto target=windows[(index+step)%windows.size()];
if(IsIconic(target)) ShowWindow(target,SW_RESTORE);
SetForegroundWindow(target);
if(target!=filesOwner) SendMessageW(target,WM_SETFOCUS,0,0);
return true;
}
@@ -2452,7 +2541,7 @@ HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *pe
}
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow)
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow,TextOpenOptions options)
{
try
{
@@ -2484,7 +2573,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
}();
if(!registered) throw std::runtime_error("Cannot register the text window.");
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment);
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment,options);
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
(peer?peer->name+L" · ":std::wstring{})+path.wstring();
RECT bounds{};
+12 -3
View File
@@ -4,6 +4,7 @@
#include <filesystem>
#include <string_view>
#include <vector>
#include "files_text_document.h"
namespace ks::lan { struct FilesPeer; }
@@ -37,7 +38,7 @@ void installFarHistoryKey(HWND field,int arrowId);
struct TextDialogs
{
INT_PTR (*confirmSave)(HWND);
INT_PTR (*confirmSave)(HWND,bool draft);
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
void (*prepare)(HWND);
@@ -49,10 +50,18 @@ struct TextDialogs
void (*finish)(HWND,INT_PTR);
bool (*dismissOwned)(HWND);
bool (*confirmExisting)(HWND);
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
};
struct TextOpenOptions
{
TextEncoding encoding=TextEncoding::automatic;
bool draft{};
};
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false);
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
TextOpenOptions options={});
void textWindowOwnerClosed();
bool cycleTextWindows(HWND current);
bool cycleTextWindows(HWND current,bool reverse);
}
File diff suppressed because it is too large. Load diff
+115 -14
View File
@@ -7,6 +7,8 @@
#include "lan_mesh.h"
#include "lan_clipboard.h"
#include "lan_layout.h"
#include "lan_network.h"
#include "lan_wake.h"
#include <atomic>
#include <mutex>
#include <thread>
@@ -28,14 +30,41 @@ std::string hostName()
wchar_t name[256]{}; DWORD size=256;
return GetComputerNameW(name,&size) ? utf8(std::wstring(name,size)) : "KSwitcher";
}
std::vector<ULONG> broadcasts()
Bytes ipv4Adapters()
{
ULONG size=16384; Bytes data(size);
auto flags=GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER;
auto result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size);
if(result==ERROR_BUFFER_OVERFLOW) { data.resize(size); result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size); }
if(result!=NO_ERROR) return {};
return data;
}
std::string wakeMacFor(ULONG remote)
{
DWORD interfaceIndex{};
if(GetBestInterface(remote,&interfaceIndex)!=NO_ERROR) return {};
auto data=ipv4Adapters();
if(data.empty()) return {};
for(auto a=reinterpret_cast<const IP_ADAPTER_ADDRESSES*>(data.data());a;a=a->Next)
{
if(a->IfIndex!=interfaceIndex || a->OperStatus!=IfOperStatusUp || a->PhysicalAddressLength!=6 ||
(a->IfType!=IF_TYPE_ETHERNET_CSMACD && a->IfType!=IF_TYPE_IEEE80211)) continue;
std::string result;
for(size_t i=0;i<a->PhysicalAddressLength;++i)
{
const auto byte=a->PhysicalAddress[i];
result+="0123456789abcdef"[byte>>4];
result+="0123456789abcdef"[byte&15];
}
return lan::wakePacket(result)?result:std::string{};
}
return {};
}
std::vector<ULONG> broadcasts()
{
auto data=ipv4Adapters();
std::vector<ULONG> out;
if(result!=NO_ERROR) return out;
if(data.empty()) return out;
for(auto a=(IP_ADAPTER_ADDRESSES*)data.data();a;a=a->Next)
if(a->OperStatus==IfOperStatusUp)
for(auto u=a->FirstUnicastAddress;u;u=u->Next)
@@ -47,6 +76,38 @@ std::vector<ULONG> broadcasts()
return out;
}
}
void lan::wakeFilesPeer(const std::string &id)
{
const auto settings=Json::parse(unprotect(readFile(dataDirectory()/L"lan-pairing.bin",256*1024)));
const auto &trusted=settings.at("trusted");
if(!settings.value("enabled",false) || !trusted.contains(id))
throw std::runtime_error("Enable KSwitcher LAN and select a paired PC.");
const auto packet=wakePacket(trusted.at(id).value("wakeMac",""));
if(!packet) throw std::runtime_error("No saved MAC address. Run updated KSwitcher on this PC while it is online once.");
const auto destinations=broadcasts();
if(destinations.empty()) throw std::runtime_error("No local IPv4 network is available.");
Network network;
WinSocket socket{::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)};
if(socket.value==INVALID_SOCKET) socketError();
const BOOL broadcast=TRUE;
if(setsockopt(socket.value,SOL_SOCKET,SO_BROADCAST,reinterpret_cast<const char*>(&broadcast),sizeof(broadcast)))
socketError();
bool sent=false;
int error=WSAEHOSTUNREACH;
for(const auto ip:destinations)
{
sockaddr_in destination{};
destination.sin_family=AF_INET;
destination.sin_port=htons(9);
destination.sin_addr.s_addr=ip;
if(sendto(socket.value,reinterpret_cast<const char*>(packet->data()),static_cast<int>(packet->size()),0,
reinterpret_cast<const sockaddr*>(&destination),sizeof(destination))==SOCKET_ERROR)
error=WSAGetLastError();
else sent=true;
}
if(!sent) throw std::system_error(error,std::system_category());
}
struct LanService::Impl
{
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; };
@@ -231,7 +292,15 @@ struct LanService::Impl
if(trusted.contains(other))
{
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
response["proof"]=lan::mac(trusted[other].at("key"),heartbeat(id,other,epoch,session));
const auto &key=trusted[other].at("key");
const auto challenge=heartbeat(id,other,epoch,session);
response["proof"]=lan::mac(key,challenge);
const auto wakeMac=wakeMacFor(address.sin_addr.s_addr);
if(!wakeMac.empty())
{
response["wakeMac"]=wakeMac;
response["wakeProof"]=lan::mac(key,challenge+"|wake|"+wakeMac);
}
send(socket,address,response);
}
return;
@@ -260,7 +329,21 @@ struct LanService::Impl
}
if(type=="presence" && trusted.contains(other) && j.value("epoch","")==peer.epoch &&
lan::equal(j.value("proof",""),lan::mac(trusted[other].at("key"),heartbeat(other,id,peer.epoch,epoch))))
{ peer.verified=now; return; }
{
peer.verified=now;
auto &entry=trusted.at(other);
const auto wakeMac=j.value("wakeMac","");
if(lan::wakePacket(wakeMac) && wakeMac!=entry.value("wakeMac","") &&
lan::equal(j.value("wakeProof",""),
lan::mac(entry.at("key"),heartbeat(other,id,peer.epoch,epoch)+"|wake|"+wakeMac)))
{
auto previous=entry;
entry["wakeMac"]=wakeMac;
try {save();}
catch(const std::exception &){entry=std::move(previous);}
}
return;
}
if(pending && pending->peer==other)
{
for(const auto &response:pending->receive(j,now)) send(socket,address,response);
@@ -392,8 +475,10 @@ struct LanService::Impl
if(socket!=INVALID_SOCKET) closesocket(socket);
if(winsock) WSACleanup();
}
std::mutex commandGate;
Bytes command(const Bytes &input)
{
std::lock_guard commandLock(commandGate);
auto j=Json::parse(input); auto action=j.value("action","status");
if(action=="enable")
{
@@ -403,7 +488,7 @@ struct LanService::Impl
configureRouter();
if(enabled) start(); else status="Disabled. No discovery sockets or worker thread.";
}
std::lock_guard lock(mutex);
std::unique_lock lock(mutex);
auto now=GetTickCount64();
if(action=="filesPeers") refreshFiles=true;
if(action=="shareLogs")
@@ -417,12 +502,17 @@ struct LanService::Impl
if(action=="sendFile" || action=="requestLog")
{
auto peer=j.at("peer").get<std::string>();
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
now-peers.at(peer).verified>=lan::PeerLifetime)
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.");
const auto checkPeer = [&] {
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
now-peers.at(peer).verified>=lan::PeerLifetime)
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.");
};
checkPeer();
if(action=="sendFile")
{
lock.unlock();
auto file=std::filesystem::path(wide(j.at("path").get<std::string>()));
auto name=utf8(file.filename().wstring());
if(name.empty()||name.size()>1024)throw std::runtime_error("Invalid file name.");
@@ -432,6 +522,9 @@ struct LanService::Impl
if(std::filesystem::file_size(file)>fileLimit)throw std::runtime_error("File size limit is 16 MiB.");
auto bytes=readFile(file,fileLimit);
payload.insert(payload.end(),bytes.begin(),bytes.end());
lock.lock();
now=GetTickCount64();
checkPeer();
transfers->queue({peer},std::move(payload),"file",now);
return encoded({{"queued",true}});
}
@@ -463,16 +556,24 @@ struct LanService::Impl
}
if(action=="saveFile"||action=="discardFile")
{
auto found=std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){
return file.id==j.at("id").get<std::string>() && file.peer==j.at("peer").get<std::string>();
});
const auto id=j.at("id").get<std::string>(), peer=j.at("peer").get<std::string>();
const auto findFile = [&] {
return std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){
return file.id==id && file.peer==peer;
});
};
auto found=findFile();
if(found==incomingFiles.end())throw std::runtime_error("This file is no longer available.");
if(action=="saveFile")
{
auto start=std::find(found->bytes.begin(),found->bytes.end(),0)+1;
atomicWrite(wide(j.at("path").get<std::string>()),Bytes(start,found->bytes.end()));
const Bytes bytes(start,found->bytes.end());
lock.unlock();
atomicWrite(wide(j.at("path").get<std::string>()),bytes);
lock.lock();
found=findFile();
}
incomingFiles.erase(found);
if(found!=incomingFiles.end()) incomingFiles.erase(found);
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
}
if(action=="position")
+52 -14
View File
@@ -13,7 +13,20 @@ class ClipboardExchange
{
static constexpr size_t Limit=32*1024*1024, Chunk=480, Window=32;
struct Item {std::string id,app;Bytes bytes;};
struct Sending {std::deque<std::shared_ptr<Item>> queue;size_t ack{};bool begun{};uint64_t last{},progress{};};
struct Sending
{
std::deque<std::shared_ptr<Item>> queue;
size_t ack{}, sentUpTo{};
bool begun{};
uint64_t retryAt{}, progress{};
void reset(uint64_t now)
{
ack=sentUpTo=0;
begun=false;
retryAt=0;
progress=now;
}
};
struct Receiving {std::string id,app;Bytes bytes;size_t size{};uint64_t last{};DWORD sequence{};};
std::string local, type, domain, boot=randomHex(16);
std::map<std::string,std::string> sessions;
@@ -55,12 +68,12 @@ class ClipboardExchange
if(s.queue.empty())return;
bool reset=s.queue.front()->app.starts_with(prefix);
std::erase_if(s.queue,[&](const auto &item){return item->app.starts_with(prefix);});
if(reset){s.ack=0;s.begun=false;s.last=0;s.progress=GetTickCount64();}
if(reset)s.reset(GetTickCount64());
}
void peerSession(const std::string &peer,const std::string &value){
if(!identifier(value))return;
if(sessions.contains(peer)&&sessions.at(peer)!=value){
auto found=sending.find(peer);if(found!=sending.end()){found->second.ack=0;found->second.begun=false;found->second.last=0;}
auto found=sending.find(peer);if(found!=sending.end())found->second.reset(found->second.progress);
if(type!="clipboard"){
auto previous=receiving.find(peer);
if(previous!=receiving.end()){incomingBytes-=previous->second.size;receiving.erase(previous);}
@@ -76,7 +89,7 @@ class ClipboardExchange
for(auto &[peer,s]:sending)for(auto &item:s.queue)if(counted.insert(item.get()).second)total+=item->bytes.size();
if(total>2*Limit)throw std::runtime_error("LAN clipboard queue is full.");
auto item=std::make_shared<Item>(Item{randomHex(16),app.size()>128?std::string("Application"):app,std::move(bytes)});
for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty()){s.ack=0;s.begun=false;s.last=0;s.progress=now;}s.queue.push_back(item);}
for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty())s.reset(now);s.queue.push_back(item);}
if(!peers.empty())status=type=="clipboard"?"Sending clipboard to "+std::to_string(peers.size())+" paired computers...":"Sending…";
}
template<class Send>void poll(const Json &trusted,uint64_t now,Send send)
@@ -88,14 +101,30 @@ class ClipboardExchange
auto &peer=it->first;auto &s=it->second;
if(!trusted.contains(peer)||s.queue.empty()){it=sending.erase(it);continue;}
if(now-s.progress>30000){status="Transfer timed out.";it=sending.erase(it);continue;}
if(sessions.contains(peer)&&(!s.last||now-s.last>=100))
auto &item=*s.queue.front();
const auto limit=std::min(item.bytes.size(),s.ack+Window*Chunk);
const bool retry=s.retryAt && now>=s.retryAt;
const bool sendBegin=!s.begun && (!s.retryAt || retry);
const bool sendChunks=s.begun && (s.sentUpTo<limit || retry);
if(sessions.contains(peer) && (sendBegin || sendChunks))
{
auto &item=*s.queue.front();auto key=trusted.at(peer).at("key").template get<std::string>();
if(!s.begun)send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}}));
else for(size_t offset=s.ack,n=0;offset<item.bytes.size()&&n<Window;offset+=Chunk,++n)
send(peer,seal(peer,key,{{"op","chunk"},{"item",item.id},{"offset",offset},
{"bytes",Json::binary(Bytes(item.bytes.begin()+offset,item.bytes.begin()+std::min(offset+Chunk,item.bytes.size())))}}));
s.last=now;
auto key=trusted.at(peer).at("key").template get<std::string>();
if(sendBegin)
send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}}));
else
{
// ACKs open new slots. Only a timeout retransmits outstanding chunks.
if(retry) s.sentUpTo=s.ack;
while(s.sentUpTo<limit)
{
const auto offset=s.sentUpTo;
const auto end=std::min(offset+Chunk,item.bytes.size());
send(peer,seal(peer,key,{{"op","chunk"},{"item",item.id},{"offset",offset},
{"bytes",Json::binary(Bytes(item.bytes.begin()+offset,item.bytes.begin()+end))}}));
s.sentUpTo=end;
}
}
if(!s.retryAt || retry) s.retryAt=now+100;
}
++it;
}
@@ -119,10 +148,19 @@ class ClipboardExchange
{
auto found=sending.find(peer);if(found==sending.end()||found->second.queue.empty())return;
auto &s=found->second;auto &item=*s.queue.front();auto offset=body.at("offset").get<size_t>();
if(item.id!=id||offset>item.bytes.size()||offset<s.ack||offset>s.ack+Window*Chunk||(offset!=item.bytes.size()&&offset%Chunk))return;
const auto maxAck=s.begun?s.sentUpTo:Window*Chunk;
if(item.id!=id||offset>item.bytes.size()||offset<s.ack||offset>maxAck||(offset!=item.bytes.size()&&offset%Chunk))return;
if(offset==s.ack&&s.begun)return;
s.begun=true;s.ack=offset;s.progress=now;s.last=0;
if(offset==item.bytes.size()){s.queue.pop_front();s.ack=0;s.begun=false;status=type=="clipboard"?"Clipboard delivered.":"Transfer delivered.";}
s.begun=true;
s.ack=offset;
s.sentUpTo=std::max(s.sentUpTo,offset);
s.progress=now;
s.retryAt=offset<s.sentUpTo?now+100:0;
if(offset==item.bytes.size()){
s.queue.pop_front();
s.reset(now);
status=type=="clipboard"?"Clipboard delivered.":"Transfer delivered.";
}
return;
}
for(auto &done:completed[peer])if(done.first==id){ack(done.second);return;}
+4 -25
View File
@@ -1,3 +1,4 @@
#include "files_powershell.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <shellapi.h>
@@ -13,6 +14,7 @@
#include <thread>
#include "lan_files.h"
#include "lan_channel.h"
#include "lan_network.h"
namespace ks::lan
{
@@ -110,28 +112,6 @@ DWORD createJunction(const fs::path &name,const fs::path &target)
constexpr size_t FrameLimit=256*1024;
constexpr DWORD SocketTimeout=5000;
struct WinSocket
{
SOCKET value=INVALID_SOCKET;
~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);}
};
void socketError()
{
throw std::system_error(WSAGetLastError(),std::system_category());
}
struct Network
{
Network()
{
WSADATA data{};
if(const auto error=WSAStartup(MAKEWORD(2,2),&data))
throw std::system_error(error,std::system_category());
}
~Network(){WSACleanup();}
};
class Wire
{
SOCKET socket;
@@ -323,9 +303,8 @@ struct RemoteCommand
auto arguments=L"powershell.exe -NoLogo -NoProfile -NonInteractive -OutputFormat Text -Command "
L"\"& ([ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('"+
encoded+L"'))))\"";
wchar_t system[MAX_PATH]{};
if(!GetSystemDirectoryW(system,MAX_PATH)) return GetLastError();
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
const auto shell=ks::files::windowsPowerShell();
if(shell.empty()) return ERROR_PATH_NOT_FOUND;
FileHandle token,restricted,read,write,input,processJob;
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <winsock2.h>
#include <system_error>
namespace ks::lan
{
inline void socketError()
{
throw std::system_error(WSAGetLastError(),std::system_category());
}
struct WinSocket
{
SOCKET value=INVALID_SOCKET;
~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);}
};
struct Network
{
Network()
{
WSADATA data{};
if(const auto error=WSAStartup(MAKEWORD(2,2),&data))
throw std::system_error(error,std::system_category());
}
~Network(){WSACleanup();}
};
}
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <algorithm>
#include <array>
#include <optional>
#include <string>
#include <string_view>
namespace ks::lan
{
inline std::optional<std::array<unsigned char,102>> wakePacket(std::string_view mac)
{
constexpr std::string_view digits="0123456789abcdef";
std::array<unsigned char,6> address{};
if(mac.size()!=2*address.size()) return {};
for(size_t i=0;i<address.size();++i)
{
const auto high=digits.find(mac[2*i]),low=digits.find(mac[2*i+1]);
if(high==digits.npos || low==digits.npos) return {};
address[i]=static_cast<unsigned char>(16*high+low);
}
if((address.front()&1) || std::all_of(address.begin(),address.end(),[](auto byte){return byte==0;}))
return {};
std::array<unsigned char,102> packet{};
std::fill_n(packet.begin(),6,0xff);
for(auto next=packet.begin()+6;next!=packet.end();next+=address.size())
std::copy(address.begin(),address.end(),next);
return packet;
}
void wakeFilesPeer(const std::string &id);
}
+48 -17
View File
@@ -1,5 +1,6 @@
#include "ocr.h"
#include <memory>
#include <atomic>
#include <roapi.h>
#include <wincodec.h>
#include <winstring.h>
@@ -99,6 +100,38 @@ struct OcrOperation : IInspectable
virtual HRESULT STDMETHODCALLTYPE GetCompleted(IUnknown **) = 0;
virtual HRESULT STDMETHODCALLTYPE Results(OcrResult **) = 0;
};
class OcrCompletion final : public IUnknown
{
// Windows.Foundation.AsyncOperationCompletedHandler<Windows.Media.Ocr.OcrResult>.
static constexpr GUID interfaceId{0x989c1371,0x444a,0x5e7e,{0xb1,0x97,0x9e,0xaa,0xf9,0xd2,0x82,0x9a}};
static constexpr GUID agileId{0x94ea2b94,0xe9cc,0x49e0,{0xc0,0xff,0xee,0x64,0xca,0x8f,0x5b,0x90}};
std::atomic<ULONG> references{1};
public:
const HANDLE event=CreateEventW(nullptr,TRUE,FALSE,nullptr);
~OcrCompletion(){if(event) CloseHandle(event);}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **value) override
{
if(!value) return E_POINTER;
*value=nullptr;
if(iid!=IID_IUnknown && iid!=interfaceId && iid!=agileId) return E_NOINTERFACE;
*value=static_cast<IUnknown *>(this);
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE AddRef() override {return ++references;}
ULONG STDMETHODCALLTYPE Release() override
{
const auto count=--references;
if(!count) delete this;
return count;
}
virtual HRESULT STDMETHODCALLTYPE Invoke(OcrOperation *,INT32)
{
return SetEvent(event)?S_OK:HRESULT_FROM_WIN32(GetLastError());
}
};
struct AsyncInfo : IInspectable
{
virtual HRESULT STDMETHODCALLTYPE Id(UINT32 *) = 0;
@@ -253,13 +286,12 @@ std::wstring recognizeText(const Clip &clip)
RoUninitialize();
}
} apartment;
auto pixels = decodeImage(clip);
Com<OcrStatics> ocr;
factory(L"Windows.Media.Ocr.OcrEngine", L"{5bffa85a-3384-3540-9940-699120d428a8}", ocr);
UINT32 max{};
check(ocr->MaxDimension(&max));
if (pixels.width > max || pixels.height > max)
throw std::runtime_error("Image exceeds Windows OCR's maximum dimensions");
if (!max) throw std::runtime_error("Windows OCR reported an invalid image size limit");
auto pixels = decodeImage(clip,max,max);
Com<OcrEngine> engine;
check(ocr->FromProfile(engine.out()));
if (!engine.p)
@@ -282,21 +314,20 @@ std::wstring recognizeText(const Clip &clip)
check(engine->Recognize(bitmap.p, operation.out()));
Com<AsyncInfo> info;
check(operation->QueryInterface(guid(L"{00000036-0000-0000-c000-000000000046}"), (void **)info.out()));
auto deadline = GetTickCount64() + 30000;
INT32 status{};
do
Com<OcrCompletion> completed;
completed.p=new OcrCompletion;
if(!completed->event) check(HRESULT_FROM_WIN32(GetLastError()));
check(operation->PutCompleted(completed.p));
const auto wait=WaitForSingleObject(completed->event,30000);
if(wait!=WAIT_OBJECT_0)
{
check(info->Status(&status));
if (status == 0)
{
if (GetTickCount64() > deadline)
{
info->Cancel();
throw std::runtime_error("Windows OCR timed out");
}
Sleep(20);
}
} while (status == 0);
const auto error=wait==WAIT_FAILED?GetLastError():ERROR_TIMEOUT;
info->Cancel();
if(error==ERROR_TIMEOUT) throw std::runtime_error("Windows OCR timed out");
check(HRESULT_FROM_WIN32(error));
}
INT32 status{};
check(info->Status(&status));
if (status != 1)
{
HRESULT failure{};
+8 -3
View File
@@ -738,6 +738,11 @@ namespace
std::recursive_mutex logGate;
bool loggingEnabled = false;
std::wstring logFilename = L"kswitcher.log";
const std::filesystem::path &logDirectory()
{
static const auto directory = dataDirectory();
return directory;
}
DiagnosticBuffer diagnosticBuffer;
}
size_t DiagnosticBuffer::expire(ULONGLONG now)
@@ -778,7 +783,7 @@ void setLoggingEnabled(bool enabled)
std::wstring readDiagnosticLog(bool previous)
{
std::lock_guard lock(logGate);
auto path = dataDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
auto path = logDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
if (!std::filesystem::exists(path))
return previous ? L"No previous log is available yet." : L"No log yet. Entries will appear when a problem is detected.";
auto bytes = readFile(path, 2 * 1024 * 1024);
@@ -796,7 +801,7 @@ void clearDiagnosticLog(bool previous)
{
// Serialize clearing with writes and rotation. Never delete the other log.
std::lock_guard lock(logGate);
auto path = dataDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
auto path = logDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
std::filesystem::remove(path);
if (!previous)
diagnosticBuffer.clear();
@@ -845,7 +850,7 @@ void log(const std::wstring &message)
return;
try
{
auto path = dataDirectory() / logFilename;
auto path = logDirectory() / logFilename;
std::error_code ec;
auto size = std::filesystem::file_size(path, ec);
if (!ec && size > 256 * 1024)
+173 -26
View File
@@ -84,6 +84,13 @@ struct Surface
Surface(const Surface &) = delete;
Surface &operator=(const Surface &) = delete;
};
struct SavedDc
{
HDC dc;
int level;
explicit SavedDc(HDC value):dc(value),level(SaveDC(value)) {}
~SavedDc() { if(level) RestoreDC(dc,level); }
};
using Mark = ScreenshotMark;
HFONT textFont(const Mark &m)
{
@@ -169,7 +176,9 @@ struct Capture
{
ScreenshotHost &app;
std::unique_ptr<Surface> image;
std::unique_ptr<Surface> dimmed, frame;
std::unique_ptr<Surface> dimmed, frame, rendered;
bool renderedMarksValid{};
RECT dragDamage{};
bool editing{}, dragging{}, arrow{}, owned{}, copied{};
bool autoOpenEditor;
bool highlight{};
@@ -249,6 +258,7 @@ struct Capture
void remember(const std::vector<Mark> &previous)
{
copied=false;
renderedMarksValid=false;
history.remember(previous);
syncHistory();
}
@@ -471,6 +481,76 @@ RECT markBounds(const Mark &m)
}
return r;
}
RECT inkBounds(const Mark &m)
{
auto bounds=markBounds(m);
const auto padding=m.number?std::clamp(m.radius,8,200)+4:
m.isHighlight()?std::clamp(m.thickness,4,100)/2+4:
m.isText()?4:std::clamp(m.thickness,1,30)*5+14;
InflateRect(&bounds,padding,padding);
return bounds;
}
void includeInk(RECT &area,const Mark &m)
{
const auto bounds=inkBounds(m);
UnionRect(&area,&area,&bounds);
if(m.isLine() && !m.label.empty())
{
const auto labelBounds=inkBounds(screenshotArrowLabel(m));
UnionRect(&area,&area,&labelBounds);
}
}
Mark shapePreview(const Capture &c)
{
Mark preview{c.start,c.end,0};
preview.color=c.currentColor;
preview.style=c.lineStyle;
preview.ends=c.straight || c.shape!=ScreenshotShape::None?LineEnds::None:c.arrowEnds;
preview.shape=c.shape;
return preview;
}
RECT dragInk(const Capture &c)
{
RECT area{};
if(c.part!=MarkPart::None)
{
// Moving an attachment can update linked lines and their labels as well.
for(size_t i=0;i<c.marks.size();++i)
{
const auto &mark=c.marks[i];
if(i==static_cast<size_t>(c.selected) || mark.fromLink.target || mark.toLink.target ||
mark.fromNumber || mark.toNumber)
includeInk(area,mark);
}
}
else includeInk(area,(c.highlight || c.freehand)?c.stroke:shapePreview(c));
return area;
}
void invalidateDrag(HWND w,Capture &c,const RECT &before)
{
const auto after=dragInk(c);
RECT affected{};
UnionRect(&affected,&before,&after);
UnionRect(&c.dragDamage,&c.dragDamage,&affected);
const auto x=[&](LONG value) {return c.view.left+MulDiv(value,c.view.right-c.view.left,c.image->width);};
const auto y=[&](LONG value) {return c.view.top+MulDiv(value,c.view.bottom-c.view.top,c.image->height);};
RECT windowArea{x(affected.left),y(affected.top),x(affected.right),y(affected.bottom)};
// Handles and antialiased scaling extend beyond the rasterized ink.
int padding=4;
if(c.part!=MarkPart::None && c.selected>=0 && c.selected<int(c.marks.size()))
{
const auto &selected=c.marks[c.selected];
padding+=std::max(4,c.unit/8);
if(!selected.number && !selected.isHighlight()) padding+=c.unit*2;
}
InflateRect(&windowArea,padding,padding);
RECT visible{};
if(IntersectRect(&visible,&windowArea,&c.canvas)) InvalidateRect(w,&visible,FALSE);
}
std::pair<POINT,POINT> thicknessSegment(const Mark &m)
{
if(m.shape!=ScreenshotShape::None) {
@@ -492,7 +572,8 @@ void drawHighlight(HDC dc,const Mark &m)
r.left=std::max(0L,r.left-radius-1); r.top=std::max(0L,r.top-radius-1);
r.right=std::min(target.dsBm.bmWidth,r.right+radius+2);
r.bottom=std::min(target.dsBm.bmHeight,r.bottom+radius+2);
if(r.right<=r.left || r.bottom<=r.top) return;
RECT clip{};
if(GetClipBox(dc,&clip)==ERROR || !IntersectRect(&r,&r,&clip)) return;
Surface mask(r.right-r.left,r.bottom-r.top);
PatBlt(mask.dc,0,0,mask.width,mask.height,BLACKNESS);
LOGBRUSH white{BS_SOLID,RGB(255,255,255),0};
@@ -519,7 +600,7 @@ void drawHighlight(HDC dc,const Mark &m)
for(int channel=0;channel<3;++channel) at[channel]=static_cast<unsigned char>(at[channel]*(153+channels[channel]*102/255)/255);
}
}
void drawMarks(HDC dc, const std::vector<Mark> &marks, const Mark *preview = nullptr)
void drawMarks(HDC dc,const std::vector<Mark> &marks,const Mark *preview=nullptr,const RECT *damage=nullptr)
{
for(const auto &m:marks) if(m.isHighlight()) drawHighlight(dc,m);
if(preview && preview->isHighlight()) drawHighlight(dc,*preview);
@@ -533,6 +614,12 @@ void drawMarks(HDC dc, const std::vector<Mark> &marks, const Mark *preview = nul
SetTextColor(dc, RGB(255,255,255));
auto draw = [&](const Mark &m)
{
if(damage)
{
const auto bounds=inkBounds(m);
RECT overlap{};
if(!IntersectRect(&overlap,&bounds,damage)) return;
}
auto markPen=CreatePen(PS_SOLID,3,m.color);
auto markBrush=CreateSolidBrush(m.color);
auto previousMarkPen=SelectObject(dc,markPen),previousMarkBrush=SelectObject(dc,markBrush);
@@ -1050,6 +1137,8 @@ void edit(HWND w, Capture &c)
c.image = std::move(cropped);
c.dimmed.reset();
c.frame.reset();
c.rendered.reset();
c.renderedMarksValid=false;
c.editing = true;
if (activeCapture == w) activeCapture = nullptr;
MONITORINFO monitor{sizeof(monitor)};
@@ -1184,6 +1273,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
bool pencil=c->selected>=0 && c->marks[c->selected].freehand;
if(pencil && c->marks[c->selected].smoothing!=amount) {
if(!c->smoothingDrag) c->remember(c->marks);
c->renderedMarksValid=false;
setScreenshotSmoothing(c->marks[c->selected],amount);
resolveScreenshotLinks(c->marks);
c->smoothingDrag=LOWORD(wp)==TB_THUMBTRACK;
@@ -1296,7 +1386,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (LOWORD(wp)==12 || LOWORD(wp)==18)
{
bool changed=LOWORD(wp)==12?c->history.undo(c->marks):c->history.redo(c->marks);
if(changed) { c->copied=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; }
if(changed) { c->copied=false; c->renderedMarksValid=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; }
c->syncHistory();
}
if (LOWORD(wp)==10 || LOWORD(wp)==11 || LOWORD(wp)==19 || LOWORD(wp)==36 || LOWORD(wp)==37 || LOWORD(wp)==38 || (LOWORD(wp)>=21 && LOWORD(wp)<=27))
@@ -1321,6 +1411,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
InvalidateRect(GetDlgItem(w,38),nullptr,FALSE);
}
if(c->dragging) c->renderedMarksValid=false;
SetFocus(w); captureCursor(w,*c); InvalidateRect(w,nullptr,FALSE); return 0;
case WM_KEYDOWN:
if(wp==VK_SHIFT && c->editing && c->dragging && c->freehand && c->part==MarkPart::None && !c->strokeConstrained) {
@@ -1463,6 +1554,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
c->strokeUsedConstraint=(wp&MK_SHIFT)!=0;
}
c->dragging=true; SetCapture(w);
if(c->editing) invalidateDrag(w,*c,{});
}
InvalidateRect(w,nullptr,FALSE); return 0;
}
@@ -1522,7 +1614,18 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (c->dragging)
{
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto previousSelection=region(c->start,c->end);
const auto previousInk=c->editing && msg==WM_MOUSEMOVE?dragInk(*c):RECT{};
c->end=c->editing?imagePoint(*c,p,c->part!=MarkPart::Thickness && c->part!=MarkPart::Rotation):POINT{std::clamp(p.x,0L,LONG(c->image->width)),std::clamp(p.y,0L,LONG(c->image->height))};
if(!c->editing && msg==WM_MOUSEMOVE)
{
const auto selection=region(c->start,c->end);
RECT dirty{};
if(UnionRect(&dirty,&previousSelection,&selection))
InvalidateRect(w,&dirty,FALSE);
captureCursor(w,*c);
return 0;
}
if(c->editing && c->part==MarkPart::None && c->shape!=ScreenshotShape::None)
c->end=constrainScreenshotShape(c->shape,c->start,c->end,c->image->width,c->image->height);
if(c->editing && (c->highlight || c->freehand) && c->part==MarkPart::None) {
@@ -1593,6 +1696,12 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
c->marks[c->selected]=dragScreenshotMark(c->original,c->part,c->start,c->end,c->image->width,c->image->height,(GetKeyState(VK_SHIFT)&0x8000)!=0);
resolveScreenshotLinks(c->marks);
}
if(c->editing && msg==WM_MOUSEMOVE)
{
invalidateDrag(w,*c,previousInk);
captureCursor(w,*c);
return 0;
}
if (msg==WM_LBUTTONUP)
{
c->dragging=false; ReleaseCapture();
@@ -1675,9 +1784,10 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
c->panning=false;
if(c->dragging && c->part!=MarkPart::None)
{
c->marks=std::move(c->beforeDrag); c->part=MarkPart::None;
c->marks=std::move(c->beforeDrag); c->renderedMarksValid=false; c->part=MarkPart::None;
}
c->dragging=false; InvalidateRect(w,nullptr,FALSE); return 0;
c->dragging=false; c->renderedMarksValid=false; c->dragDamage={};
InvalidateRect(w,nullptr,FALSE); return 0;
case WM_GETMINMAXINFO:
if (c->editing)
{
@@ -1710,14 +1820,16 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
// Compose the entire frame off screen. Never expose a cleared desktop
// or a partially drawn selection between mouse moves.
auto buffer=c->frame->dc;
BitBlt(buffer,0,0,c->image->width,c->image->height,c->dimmed->dc,0,0,SRCCOPY);
const auto &dirty=ps.rcPaint;
const int width=dirty.right-dirty.left,height=dirty.bottom-dirty.top;
BitBlt(buffer,dirty.left,dirty.top,width,height,c->dimmed->dc,dirty.left,dirty.top,SRCCOPY);
if (c->dragging)
{
auto r=region(c->start,c->end);
BitBlt(buffer,r.left,r.top,r.right-r.left,r.bottom-r.top,c->image->dc,r.left,r.top,SRCCOPY);
FrameRect(buffer,&r,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
}
BitBlt(dc,0,0,c->image->width,c->image->height,buffer,0,0,SRCCOPY);
BitBlt(dc,dirty.left,dirty.top,width,height,buffer,dirty.left,dirty.top,SRCCOPY);
}
else
{
@@ -1725,6 +1837,9 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (!c->frame || c->frame->width!=width || c->frame->height!=height)
c->frame=std::make_unique<Surface>(width,height);
auto buffer=c->frame->dc;
const SavedDc savedFrame(buffer);
const auto &dirty=ps.rcPaint;
IntersectClipRect(buffer,dirty.left,dirty.top,dirty.right,dirty.bottom);
FillRect(buffer,&client,GetSysColorBrush(COLOR_APPWORKSPACE));
RECT toolbar{0,0,client.right,c->panelHeight};
FillRect(buffer,&toolbar,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
@@ -1737,26 +1852,58 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
LineTo(buffer,MulDiv(x,dpi,96),MulDiv(31,dpi,96));
}
SelectObject(buffer,previous); DeleteObject(divider);
Surface rendered(c->image->width,c->image->height);
BitBlt(rendered.dc,0,0,rendered.width,rendered.height,c->image->dc,0,0,SRCCOPY);
Mark preview{c->start,c->end,0};
preview.color=c->currentColor;
preview.style=c->lineStyle; preview.ends=c->straight || c->shape!=ScreenshotShape::None?LineEnds::None:c->arrowEnds;
preview.shape=c->shape;
auto visibleMarks=c->marks;
if(c->inlineText && c->textIndex>=0) {
if(c->editingLabel) visibleMarks[c->textIndex].label.clear();
else visibleMarks.erase(visibleMarks.begin()+c->textIndex);
const auto preview=shapePreview(*c);
const auto *previewMark=c->dragging && c->part==MarkPart::None?
((c->highlight || c->freehand)?&c->stroke:&preview):nullptr;
const auto *source=c->image.get();
if(!c->marks.empty() || previewMark)
{
const bool inlineEdit=c->inlineText && c->textIndex>=0;
const bool partial=c->renderedMarksValid && !inlineEdit;
if(!c->rendered)
c->rendered=std::make_unique<Surface>(source->width,source->height);
auto &rendered=*c->rendered;
RECT imageArea{0,0,rendered.width,rendered.height}, repaint=imageArea;
if(partial) IntersectRect(&repaint,&imageArea,&c->dragDamage);
if(!IsRectEmpty(&repaint))
{
c->renderedMarksValid=false;
BitBlt(rendered.dc,repaint.left,repaint.top,repaint.right-repaint.left,repaint.bottom-repaint.top,
source->dc,repaint.left,repaint.top,SRCCOPY);
if(inlineEdit)
{
auto visibleMarks=c->marks;
if(c->editingLabel) visibleMarks[c->textIndex].label.clear();
else visibleMarks.erase(visibleMarks.begin()+c->textIndex);
drawMarks(rendered.dc,visibleMarks,previewMark);
}
else if(partial)
{
const SavedDc previousClip(rendered.dc);
IntersectClipRect(rendered.dc,repaint.left,repaint.top,repaint.right,repaint.bottom);
drawMarks(rendered.dc,c->marks,previewMark,&repaint);
}
else drawMarks(rendered.dc,c->marks,previewMark);
c->renderedMarksValid=!inlineEdit;
}
source=&rendered;
}
drawMarks(rendered.dc,visibleMarks,c->dragging && c->part==MarkPart::None?((c->highlight || c->freehand)?&c->stroke:&preview):nullptr);
else
{
c->rendered.reset();
c->renderedMarksValid=false;
}
c->dragDamage={};
SetStretchBltMode(buffer,HALFTONE); SetBrushOrgEx(buffer,0,0,nullptr);
int savedCanvas=SaveDC(buffer);
IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom);
StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top,
rendered.dc,0,0,rendered.width,rendered.height,SRCCOPY);
drawHandles(buffer,*c);
RestoreDC(buffer,savedCanvas);
BitBlt(dc,0,0,width,height,buffer,0,0,SRCCOPY);
{
const SavedDc savedCanvas(buffer);
IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom);
StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top,
source->dc,0,0,source->width,source->height,SRCCOPY);
drawHandles(buffer,*c);
}
BitBlt(dc,dirty.left,dirty.top,dirty.right-dirty.left,dirty.bottom-dirty.top,
buffer,dirty.left,dirty.top,SRCCOPY);
}
}
catch (...) { EndPaint(w,&ps); throw; }
+16
View File
@@ -54,6 +54,22 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
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)
{
wchar_t *end{};
const auto value=std::wcstoull(argv[i+2],&end,10);
if(!value || *end || value>UINTPTR_MAX) { LocalFree(argv); return 1; }
handles[i]=reinterpret_cast<HANDLE>(static_cast<uintptr_t>(value));
}
LocalFree(argv);
const auto initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
if(FAILED(initialized)) return 1;
const auto result=ks::runHistoryImageWorker(handles[0],handles[1],handles[2]);
CoUninitialize();
return result;
}
if(argc==3 && (std::wstring(argv[1])==L"--capture-history" || std::wstring(argv[1])==L"--history-ocr")) {
bool ocr=std::wstring(argv[1])==L"--history-ocr";
std::filesystem::path request=argv[2]; LocalFree(argv);
+207 -43
View File
@@ -28,9 +28,9 @@ std::wstring newSnippetId()
}
namespace
{
Bytes jsonBytes(const Json &j)
Bytes jsonBytes(const Json &j, int indent = 2)
{
auto s = j.dump(2);
auto s = j.dump(indent);
return Bytes(s.begin(), s.end());
}
Json parse(const Bytes &bytes)
@@ -269,8 +269,9 @@ void validateSettings(const Settings &s)
if (alphabet.empty() || words.size() > 10000)
throw std::runtime_error("Invalid personal dictionary language or too many words");
for (const auto &word : words)
if (word.empty() || word.size() > 32 || lower(word).find_first_not_of(alphabet) != word.npos)
throw std::runtime_error("Personal words must contain 1-32 letters of their selected language");
if (!validPersonalWord(word, alphabet))
throw std::runtime_error("Personal words must be 1-32 characters, with letters of the selected language. "
"A hyphen (-) is allowed between letters.");
}
if (s.maxItems < 10 || s.maxItems > 10000 || s.maxMiB < 1 || s.maxMiB > 2048 || s.maxImageMiB < 1 ||
s.maxImageMiB > 64)
@@ -327,7 +328,7 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
throw std::runtime_error("Not a KSwitcher or Typlo settings file");
s.recent = j.value("convertLastWord", true);
s.switchLayout = j.value("switchSystemLayout", true);
s.writeLog = j.value("writeLog", true);
s.writeLog = j.value("writeLog", s.writeLog);
s.history = j.value("historyEnabled", true);
s.useTesseract = j.value("useTesseract", false);
s.tesseractPath = str(j, "tesseractPath");
@@ -685,7 +686,54 @@ Clip decodeClip(const Bytes &b)
throw std::runtime_error("Trailing clipboard data");
return clip;
}
History::History(const std::filesystem::path &folder) : folder_(folder)
namespace
{
struct ImageWorkerControl
{
static constexpr size_t MaxPath=32768;
wchar_t request[MaxPath];
int result;
};
struct ImageWorkerHandle
{
HANDLE value{};
~ImageWorkerHandle() { reset(); }
void reset()
{
if(value) CloseHandle(std::exchange(value,nullptr));
}
};
struct ImageWorkerView
{
ImageWorkerControl *control{};
~ImageWorkerView() { reset(); }
void reset()
{
if(control) UnmapViewOfFile(std::exchange(control,nullptr));
}
};
struct HistoryImageWorker
{
std::timed_mutex mutex;
ImageWorkerHandle mapping, requestReady, responseReady, process;
ImageWorkerView view;
~HistoryImageWorker() { stop(); }
void stop();
void start();
int perform(const std::filesystem::path &, const std::function<bool()> &);
};
}
struct HistoryImageWorkers
{
// A slow recognition must not delay history thumbnails.
HistoryImageWorker recognition, thumbnails;
};
History::~History() = default;
History::History(const std::filesystem::path &folder)
: folder_(folder), imageWorkers_(std::make_unique<HistoryImageWorkers>())
{
std::filesystem::create_directories(folder_);
loadIndex();
@@ -724,7 +772,12 @@ void History::loadIndex()
}
entries_ = std::move(loaded);
}
void History::reload() { std::lock_guard lock(mutex_); loadIndex(); }
void History::reload()
{
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
loadIndex();
}
void ClipboardSnapshot::cleanup() noexcept
{
if (request_.empty()) return;
@@ -809,7 +862,7 @@ bool History::captureImage(DWORD sequence, const std::wstring &app, const Settin
{
// Serialize helper index changes with all resident history mutations. Only
// metadata is reloaded: GetClipboardData's image allocations die with the child.
std::lock_guard lock(mutex_);
std::lock_guard writer(indexWriter_);
if (sequence != GetClipboardSequenceNumber()) return false;
auto request = std::filesystem::absolute(folder_) / (L"capture-" + newSnippetId() + L".request");
struct Cleanup {
@@ -838,7 +891,10 @@ bool History::captureImage(DWORD sequence, const std::wstring &app, const Settin
}
GetExitCodeProcess(process.hProcess, &result);
CloseHandle(process.hProcess);
loadIndex(); // Also reconcile any completed atomic save before a child failure.
{
std::lock_guard lock(mutex_);
loadIndex(); // Also reconcile any completed atomic save before a child failure.
}
if (wait != WAIT_OBJECT_0) throw std::runtime_error("Image history helper timed out");
if (result == 2) return false;
if (result == 3) throw std::runtime_error("Clipboard exceeds the configured size limit");
@@ -893,7 +949,7 @@ void History::saveIndex()
{"files", e.files}, {"ocrState", e.ocrState}, {"ocrProfile", utf8(e.ocrProfile)},
{"fingerprintVersion", 1}, {"contentHash", e.contentHash},
{"imageHash", e.imageHash}, {"pixelHash", e.pixelHash}});
atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j)));
atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j, -1)));
}
std::vector<Entry> History::entries() const
{
@@ -1007,6 +1063,7 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s,
image |= f.id == CF_DIB || f.id == CF_DIBV5 || f.name == L"PNG";
files |= f.id == CF_HDROP;
}
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
Entry fingerprints;
fingerprints.contentHash = clipboardHash(data);
@@ -1068,6 +1125,7 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s,
}
void History::remove(const std::wstring &id)
{
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
if (!validId(id))
return;
@@ -1082,6 +1140,7 @@ void History::remove(const std::wstring &id)
}
void History::pin(const std::wstring &id)
{
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
for (auto &e : entries_)
if (e.id == id)
@@ -1090,6 +1149,7 @@ void History::pin(const std::wstring &id)
}
void History::clear()
{
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
auto old = entries_;
entries_.clear();
@@ -1101,7 +1161,139 @@ void History::clear()
std::filesystem::remove(folder_ / (e.id + L".ocr"), ec);
}
}
static Bytes historyImageJob(const std::filesystem::path &folder, const std::wstring &id,
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);
const auto checkCancelled=[&] {
if(cancelled && cancelled()) throw std::runtime_error("History OCR cancelled");
};
while(!lock.try_lock_for(std::chrono::milliseconds(100))) checkCancelled();
checkCancelled();
const auto &path=request.native();
if(path.size()>=ImageWorkerControl::MaxPath)
throw std::runtime_error("History OCR request path is too long");
try
{
for(int attempt=0;attempt<2;++attempt)
{
if(!process.value || WaitForSingleObject(process.value,0)!=WAIT_TIMEOUT)
{
stop();
start();
}
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};
const auto deadline=GetTickCount64()+60000;
for(;;)
{
const auto wait=WaitForMultipleObjects(2,signals,FALSE,100);
if(wait==WAIT_OBJECT_0)
{
checkCancelled();
return view.control->result;
}
if(wait==WAIT_OBJECT_0+1)
{
DWORD code{};
if(GetExitCodeProcess(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();
}
}
catch(...)
{
// The child must stop writing before the request and response files are cleaned up.
stop();
throw;
}
throw std::runtime_error("History OCR helper did not accept the request");
}
}
int runHistoryImageWorker(HANDLE mapping,HANDLE requestReady,HANDLE responseReady)
{
ImageWorkerView view{static_cast<ImageWorkerControl *>(
MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)))};
if(!view.control) return 1;
for(;;)
{
const auto wait=WaitForSingleObject(requestReady,30000);
if(wait==WAIT_TIMEOUT) return WAIT_TIMEOUT;
if(wait!=WAIT_OBJECT_0) return 1;
const auto &request=view.control->request;
const auto end=std::find(std::begin(request),std::end(request),L'\0');
view.control->result=end==std::end(request)?1:runHistoryOcr(std::wstring(std::begin(request),end));
if(!SetEvent(responseReady)) return 1;
}
}
static Bytes historyImageJob(HistoryImageWorker &worker,const std::filesystem::path &folder,const std::wstring &id,
const Json &job, const std::function<bool()> &cancelled)
{
if (!validId(id)) throw std::runtime_error("Invalid history ID");
@@ -1117,36 +1309,7 @@ static Bytes historyImageJob(const std::filesystem::path &folder, const std::wst
}
} cleanup{request, response};
atomicWrite(request, protect(jsonBytes(job)));
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" --history-ocr \"" + 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(utf8(lastError(L"Cannot start history OCR helper")));
CloseHandle(process.hThread);
struct Child {
HANDLE handle;
~Child() {
if (WaitForSingleObject(handle, 0) != WAIT_OBJECT_0) {
TerminateProcess(handle, ERROR_CANCELLED);
WaitForSingleObject(handle, INFINITE);
}
CloseHandle(handle);
}
} child{process.hProcess};
auto deadline = GetTickCount64() + 60000;
for (;;) {
auto wait = WaitForSingleObject(child.handle, 100);
if (wait == WAIT_OBJECT_0) break;
if (wait != WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper");
if (cancelled && cancelled()) throw std::runtime_error("History OCR cancelled");
if (GetTickCount64() >= deadline) throw std::runtime_error("History OCR helper timed out");
}
DWORD result{};
if (!GetExitCodeProcess(child.handle, &result) || result)
throw std::runtime_error("History OCR helper failed: " + std::to_string(result));
if(worker.perform(request,cancelled)) throw std::runtime_error("History OCR helper failed");
return unprotect(readFile(response, 8 * 1024 * 1024));
}
std::wstring History::recognizeImage(const std::wstring &id, const Settings &settings,
@@ -1154,14 +1317,14 @@ std::wstring History::recognizeImage(const std::wstring &id, const Settings &set
{
Json job{{"schema", 1}, {"id", utf8(id)}, {"tesseract", settings.useTesseract},
{"path", utf8(settings.tesseractPath)}, {"languages", utf8(settings.tesseractLanguages)}};
auto reply = parse(historyImageJob(folder_, id, job, cancelled));
auto reply = parse(historyImageJob(imageWorkers_->recognition,folder_, id, job, cancelled));
if (reply.at("schema") != 1 || str(reply, "id") != id)
throw std::runtime_error("Invalid history OCR response");
return str(reply, "text");
}
Pixels History::thumbnail(const std::wstring &id, const std::function<bool()> &cancelled) const
{
auto bytes = historyImageJob(folder_, id, Json{{"schema", 1}, {"id", utf8(id)}, {"thumbnail", true}}, cancelled);
auto bytes = historyImageJob(imageWorkers_->thumbnails,folder_, id, Json{{"schema", 1}, {"id", utf8(id)}, {"thumbnail", true}}, cancelled);
size_t at = 0;
auto width = get32(bytes, at), height = get32(bytes, at);
if (!width || !height || width > 208 || height > 128 || bytes.size() - at != width * height * 4)
@@ -1200,6 +1363,7 @@ int runHistoryOcr(const std::filesystem::path &request)
}
bool History::saveOcr(const std::wstring &id, const std::optional<std::wstring> &text, const Settings &settings)
{
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
auto it = std::find_if(entries_.begin(), entries_.end(), [&](auto &e) { return e.id == id; });
// A late OCR completion must never recreate a deleted/pruned image.
+5
View File
@@ -5,6 +5,7 @@
namespace ks
{
struct Pixels;
struct HistoryImageWorkers;
Settings loadSettings(const std::filesystem::path &, const std::vector<Layout> &);
Settings decodeSettings(const Bytes &, const std::vector<Layout> &);
Bytes encodeSettings(const Settings &);
@@ -26,12 +27,15 @@ class History
std::filesystem::path folder_;
std::vector<Entry> entries_;
mutable std::mutex mutex_;
std::unique_ptr<HistoryImageWorkers> imageWorkers_;
std::mutex indexWriter_; // Serializes resident mutations with the image capture helper.
void saveIndex();
void loadIndex();
void prune(const Settings &);
public:
explicit History(const std::filesystem::path &);
~History();
void reload();
std::vector<Entry> entries() const;
Clip load(const std::wstring &id) const;
@@ -53,6 +57,7 @@ Clip decodeClip(const Bytes &);
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.
class ClipboardSnapshot
{
+1 -1
View File
@@ -1705,7 +1705,7 @@ void showAutoOptions(HWND parent, SettingsView *v)
label(w, L"Never correct these words (comma-separated)", 18, 184, 525);
edit(w, 405, 18, 212, 524, 52, ES_MULTILINE | WS_VSCROLL | ES_AUTOVSCROLL);
value(w, 405, commaList(v->draft.autoNever));
label(w, L"My dictionary: correct words, separated by commas or new lines", 18, 276, 525);
label(w, L"My dictionary: separate words by commas or new lines. Internal hyphens allowed.", 18, 276, 525);
for (auto [id, language] : {std::pair{411, L"en"}, {412, L"uk"}, {413, L"ru"}})
{
int x = 18 + (id - 411) * 178;
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.105";
inline constexpr wchar_t AppVersion[] = L"0.6.116";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+378 -16
View File
@@ -3,6 +3,7 @@ param(
[Parameter(Mandatory)][string]$Fixture,
[switch]$SystemOpenOnly,
[switch]$TerminalOnly,
[int]$ScanEntries = 0,
[string]$Node='node'
)
$ErrorActionPreference = 'Stop'
@@ -12,6 +13,10 @@ using System.Text;
using System.Runtime.InteropServices;
public static class FilesActivationUi {
public static void CreateScanFiles(string directory, int count) {
for (int i = 0; i < count; i++)
using (System.IO.File.Create(System.IO.Path.Combine(directory, i.ToString("D6") + ".txt"))) {}
}
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
@@ -23,7 +28,35 @@ public static class FilesActivationUi {
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint relation);
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr window);
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr window, IntPtr dc);
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
public static uint ReadScreenCenter(IntPtr window) {
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
try {
Rect bounds;
if (!GetWindowRect(window, out bounds)) throw new InvalidOperationException("Missing terminal output.");
var dc = GetDC(IntPtr.Zero);
if (dc == IntPtr.Zero) throw new InvalidOperationException("Could not read the screen.");
try { return GetPixel(dc, (bounds.Left + bounds.Right) / 2, (bounds.Top + bounds.Bottom) / 2); }
finally { ReleaseDC(IntPtr.Zero, dc); }
} finally {
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
}
}
public static bool HasWarningBackground(IntPtr window) {
var dc = GetDC(window);
if (dc == IntPtr.Zero) return false;
try { return GetPixel(dc, 2, 2) == 0x80; }
finally { ReleaseDC(window, dc); }
}
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
@@ -75,6 +108,42 @@ function Wait-Until([string]$Description, [scriptblock]$Condition) {
throw "Timed out waiting for $Description"
}
function Invoke-ClipboardOperation([scriptblock]$Operation) {
for ($attempt = 1; $attempt -le 3; $attempt++) {
try { return (& $Operation) }
catch {
# CLIPBRD_E_CANT_OPEN means another process is using the shared clipboard.
if ($_.Exception.GetBaseException().HResult -ne 0x800401D0 -or
$attempt -eq 3) { throw }
[Windows.Forms.Application]::DoEvents()
Start-Sleep -Milliseconds 25
}
}
}
function Find-OperationDialog($Owner, [int]$Control) {
$candidate = [IntPtr]::Zero
while ($true) {
$candidate = [FilesActivationUi]::FindWindowEx([IntPtr]::Zero, $candidate, '#32770', [NullString]::Value)
if ($candidate -eq [IntPtr]::Zero) { return [IntPtr]::Zero }
if (![FilesActivationUi]::IsWindowVisible($candidate) -or
[FilesActivationUi]::GetDlgItem($candidate, $Control) -eq [IntPtr]::Zero) { continue }
$parent = [FilesActivationUi]::GetWindow($candidate, 4)
while ($parent -ne [IntPtr]::Zero) {
if ($parent -eq $Owner) { return $candidate }
$parent = [FilesActivationUi]::GetWindow($parent, 4)
}
}
}
function Answer-OperationDialog([int]$Control, [int]$Answer) {
Wait-Until "operation dialog with control $Control" {
(Find-OperationDialog $window $Control) -ne [IntPtr]::Zero
}
$dialog = Find-OperationDialog $window $Control
[void][FilesActivationUi]::PostMessage($dialog, 0x111, [IntPtr]$Answer, [IntPtr]::Zero)
}
function Read-Text($Control, $Message = 0x0D, $Parameter = 32768) {
$buffer = [Text.StringBuilder]::new(32768)
[void][FilesActivationUi]::Read($Control, $Message, [IntPtr]$Parameter, $buffer)
@@ -138,7 +207,7 @@ $extension = ".ksfiles$unique"
$progId = "KSwitcher.Files.Test.$unique"
$saved = @{}
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
'ShowDetails', 'StatusFields', 'CommandHistory', 'WindowPlacement'
'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement'
$process = $null
$trace = $null
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
@@ -180,6 +249,18 @@ try {
$profile.SetValue('StatusFields', 3)
if($TerminalOnly){
$terminalPage = Join-Path $app 'terminal/index.html'
$page = Get-Content -Raw -LiteralPath $terminalPage
$page = $page.Replace('<style>','<style media="not all">').Replace('src="terminal.js"','src="startup-fixture.js"')
[IO.File]::WriteAllText($terminalPage,$page)
[IO.File]::WriteAllText((Join-Path $app 'terminal/startup-fixture.js'), @'
function startTerminalFixture() {
document.querySelector('style').media = 'all';
const script = document.createElement('script');
script.src = 'terminal.js';
document.body.append(script);
}
'@)
$listener=[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$listener.Start()
$port=$listener.LocalEndpoint.Port
@@ -187,6 +268,13 @@ try {
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=$port"
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $root 'webview'
}
if($SystemOpenOnly) {
$profile.SetValue('PreviousCommandKey',0x0245,'DWord')
$profile.SetValue('CommandHistoryKey',0x0477,'DWord')
}
if ($ScanEntries) {
[FilesActivationUi]::CreateScanFiles("$leftDir\Test folder", $ScanEntries)
}
$process = Start-Process -FilePath $testExe -ArgumentList '--terminal-output-trace' -PassThru
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
@@ -197,6 +285,49 @@ try {
$output = [FilesActivationUi]::GetDlgItem($window, 145)
$inputBox = [FilesActivationUi]::FindWindowEx($window, [IntPtr]::Zero, 'Edit', $null)
if ($ScanEntries) {
Wait-Until 'visible Files window' { [FilesActivationUi]::Activate($window) }
Wait-Until 'folder fixture row' { (Find-Row $left '[Test folder]') -ge 0 }
$folderRow = Find-Row $left '[Test folder]'
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
Press-Enter $inputBox
Wait-Until 'nonzero folder scan progress' {
[FilesActivationUi]::IsWindowVisible($status) -and
(Read-Text $status) -match '^Reading ([1-9][0-9]*) \[Esc\]$'
}
$progress = Read-Text $status
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]27, [IntPtr]::Zero)
Wait-Until 'partial folder result' { (Read-Text $status) -match '^Partial: \d+$' }
$partial = [FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() - 1
$partialStatus = Read-Text $status
if ($partial -le 0 -or $partial -ge $ScanEntries -or
$partialStatus -ne "Partial: $partial" -or
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -ne "$leftDir\Test folder") {
throw "Unexpected partial listing of $partial entries."
}
$keys = New-Object -ComObject WScript.Shell
$fullScan = [Diagnostics.Stopwatch]::StartNew()
$keys.SendKeys('^r')
Wait-Until 'complete folder result after Ctrl+R' {
[FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $ScanEntries + 1
}
$fullScan.Stop()
Write-Output "$progress. $partialStatus. Full scan: $ScanEntries files in $($fullScan.ElapsedMilliseconds) ms."
$target = 65536
[void][FilesActivationUi]::Send($left, 0x197, [IntPtr]$target, [IntPtr]::Zero)
if ([FilesActivationUi]::Send($left, 0x18E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $target) {
throw "Could not scroll row $target to the top."
}
$point = [IntPtr]((2 -shl 16) -bor 6)
[void][FilesActivationUi]::PostMessage($left, 0x201, [IntPtr]1, $point)
[void][FilesActivationUi]::PostMessage($left, 0x202, [IntPtr]::Zero, $point)
Wait-Until 'mouse selection past the 16-bit row limit' {
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $target
}
Write-Output "Clicked row $target after scrolling it to the top."
return
}
if($SystemOpenOnly) {
$keys = New-Object -ComObject WScript.Shell
$explorer = New-Object -ComObject Shell.Application
@@ -237,11 +368,55 @@ try {
Wait-Until 'plain Enter invoking the default Windows file association' {
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
}
$command="start '$($document.Replace("'","''"))'"
Wait-Until 'the system open action in terminal output and command history' {
$history=$profile.GetValue('CommandHistory')
[FilesActivationUi]::IsWindowVisible($output) -and $history -and
([Text.Encoding]::Unicode.GetString($history).Split([char]0) -ccontains $command) -and
(Select-String -LiteralPath $trace -Pattern ('^'+[regex]::Escape($document.Substring(0,24))) -Quiet)
}
Wait-Until 'Files active for command history' { [FilesActivationUi]::Activate($window) }
$keys.SendKeys('%{F8}')
$historyDialog=[IntPtr]::Zero
Wait-Until 'command history showing only the opened file path' {
$script:historyDialog=[FilesActivationUi]::GetForegroundWindow()
$list=[FilesActivationUi]::GetDlgItem($historyDialog,324)
$list -ne [IntPtr]::Zero -and (Find-Row $list $document) -ge 0
}
$historyList=[FilesActivationUi]::GetDlgItem($historyDialog,324)
$historyRow=Find-Row $historyList $document
[void][FilesActivationUi]::Send($historyList,0x186,[IntPtr]$historyRow,[IntPtr]::Zero)
[void][FilesActivationUi]::PostMessage($historyDialog,0x111,[IntPtr]1,[IntPtr]::Zero)
Wait-Until 'selecting the history path restoring a runnable command' { (Read-Text $inputBox) -ceq $command }
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
Remove-Item -LiteralPath "$document.opened"
}
if($SystemOpenOnly -or $TerminalOnly){
$keys = New-Object -ComObject WScript.Shell
if ($TerminalOnly) {
Wait-Until 'Files active for the terminal startup check' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$keys.SendKeys('^o')
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-pause'
if ($LASTEXITCODE) { throw 'Could not pause terminal page initialization.' }
foreach ($frame in 1..10) {
if ([FilesActivationUi]::GetForegroundWindow() -ne $window -or
![FilesActivationUi]::IsWindowVisible($output)) { throw 'The terminal must be visible for the startup check.' }
$pixel = [FilesActivationUi]::ReadScreenCenter($output)
if ($pixel -ne 0x181818) { throw ('Unexpected terminal startup background 0x{0:X6}.' -f $pixel) }
Start-Sleep -Milliseconds 30
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-resume'
if ($LASTEXITCODE) { throw 'Could not resume terminal page initialization.' }
Wait-Until 'the terminal rendering after startup' {
Select-String -LiteralPath $trace -SimpleMatch ' web-anchor ' -Quiet -ErrorAction SilentlyContinue
}
$keys.SendKeys('^o')
Wait-Until 'file panes restored after the startup check' { [FilesActivationUi]::IsWindowVisible($left) }
Write-Output 'Verified the dark terminal background before WebView initialization completes.'
}
foreach($case in @(
@{Name='enter-panes'; Keys='{ENTER}'},
@{Name='shift-enter-panes'; Keys='+{ENTER}'},
@@ -300,21 +475,21 @@ try {
Send-InteractiveTerminal "Write-Output '$outputSelection'"
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard = [Windows.Forms.Clipboard]::GetDataObject()
$savedClipboard = Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
try {
$nativeDraft = "Get-Item -LiteralPath '$leftDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$nativeDraft)
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]0,[IntPtr]4)
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the full command line with a partial selection' {
[Windows.Forms.Clipboard]::GetText() -ceq $nativeDraft
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $nativeDraft
}
$webviewDraft = "Get-Item -LiteralPath '$rightDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$webviewDraft)
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-copy'
if($LASTEXITCODE){throw 'Could not send Ctrl+Insert through the terminal WebView.'}
Wait-Until 'Ctrl+Insert copying the command line with focus in the terminal WebView' {
[Windows.Forms.Clipboard]::GetText() -ceq $webviewDraft
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $webviewDraft
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-select-output'
if($LASTEXITCODE){throw 'Could not select the terminal output fixture.'}
@@ -322,22 +497,26 @@ try {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
foreach($key in '^c','^{INSERT}') {
[Windows.Forms.Clipboard]::SetText($webviewDraft)
# Require a new clipboard write without making the test process the clipboard owner.
$beforeCopy = [FilesActivationUi]::GetClipboardSequenceNumber()
$keys.SendKeys($key)
Wait-Until "$key copying only the selected terminal output with a command present" {
[Windows.Forms.Clipboard]::GetText() -ceq $outputSelection
[FilesActivationUi]::GetClipboardSequenceNumber() -ne $beforeCopy -and
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $outputSelection
}
if ((Read-Text $inputBox) -cne $webviewDraft) { throw 'Copying output changed the command line.' }
}
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the selected folder name when the command line is empty' {
[Windows.Forms.Clipboard]::GetText() -ceq 'Test folder'
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq 'Test folder'
}
} finally {
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
Invoke-ClipboardOperation {
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
}
Write-Output 'Verified Ctrl+C and Ctrl+Insert copy the selected output, then fall back to the command line or panel.'
@@ -443,7 +622,7 @@ try {
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard=[Windows.Forms.Clipboard]::GetDataObject()
$savedClipboard=Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
$programName=[IO.Path]::GetFileName($program)
$expectedNames="Test folder`r`n$programName"
try {
@@ -456,18 +635,20 @@ try {
}
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
[Windows.Forms.Clipboard]::GetText() -ceq $expectedNames
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $expectedNames
}
Select-Row $right $fileName
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
[Windows.Forms.Clipboard]::GetText() -ceq $fileName
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $fileName
}
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
} finally {
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
Invoke-ClipboardOperation {
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
}
@@ -514,6 +695,187 @@ try {
(Find-Row $right '[Size B]')
}
Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.'
$operationName = 'Background operation.txt'
$leftOperation = Join-Path $leftDir 'Operations'
$rightOperation = Join-Path $rightDir 'Operations'
New-Item -ItemType Directory -Path $leftOperation, $rightOperation | Out-Null
$operationSource = Join-Path $leftOperation $operationName
$operationTarget = Join-Path $rightOperation $operationName
Invoke-Row $left '[Operations]' $false
Invoke-Row $right '[Operations]' $false
Wait-Until 'operation folders loaded in both panes' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 142))) -eq $leftOperation -and
(Read-Text ([FilesActivationUi]::GetDlgItem($window, 143))) -eq $rightOperation
}
[IO.File]::WriteAllText($operationSource, 'source contents')
[IO.File]::WriteAllText($operationTarget, 'original target')
Select-Row $left $operationName
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x74, [IntPtr]::Zero)
Answer-OperationDialog 211 1
Answer-OperationDialog 230 6
Wait-Until 'copy after overwrite confirmation' {
(Read-Text $status) -ceq 'Copy complete.' -and
[FilesActivationUi]::Focus($window) -eq $inputBox
}
if ([IO.File]::ReadAllText($operationTarget) -cne 'source contents') {
throw 'Copy did not replace the target contents.'
}
[IO.File]::Delete($operationTarget)
Select-Row $left $operationName
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero)
Wait-Until 'move destination field' { (Find-OperationDialog $window 211) -ne [IntPtr]::Zero }
$moveDialog = Find-OperationDialog $window 211
$destinationField = [FilesActivationUi]::GetDlgItem($moveDialog, 211)
$validDestination = Read-Text $destinationField
$missingDestination = Join-Path $rightOperation 'missing\destination.txt'
[void][FilesActivationUi]::Write($destinationField, 0x0C, [IntPtr]::Zero, $missingDestination)
Answer-OperationDialog 211 1
Answer-OperationDialog 100 1
Wait-Until 'focus returns to the move destination after asynchronous validation' {
[FilesActivationUi]::Focus($window) -eq $destinationField
}
if (!(Test-Path -LiteralPath $operationSource)) { throw 'Invalid destination started the move.' }
[void][FilesActivationUi]::Write($destinationField, 0x0C, [IntPtr]::Zero, $validDestination)
$lockReady = Join-Path $root 'lock.ready'
$locker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $operationSource,$lockReady) -WindowStyle Hidden -PassThru
try {
Wait-Until 'file locked by the fixture process' { Test-Path -LiteralPath $lockReady }
Answer-OperationDialog 211 1
Wait-Until 'red modal error for a locked file' {
$errorDialog = Find-OperationDialog $window 100
$errorDialog -ne [IntPtr]::Zero -and [FilesActivationUi]::HasWarningBackground($errorDialog)
}
$errorDialog = Find-OperationDialog $window 100
$reason = Read-Text ([FilesActivationUi]::GetDlgItem($errorDialog, 100))
if (!$reason -or (Read-Text $status).Contains($reason)) {
throw 'The move failure reason must appear in the modal dialog.'
}
Answer-OperationDialog 100 103
Wait-Until 'the locker appears with its PID' {
$dialog = Find-OperationDialog $window 431
if ($dialog -eq [IntPtr]::Zero) { return $false }
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
(Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $locker.Id)) -ge 0
}
$dialog = Find-OperationDialog $window 431
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
$row = Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $locker.Id)
[void][FilesActivationUi]::Send($list, 0x186, [IntPtr]$row, [IntPtr]::Zero)
Answer-OperationDialog 431 433
Answer-OperationDialog 100 7
Wait-Until 'End process confirmation closes after No' {
(Find-OperationDialog $window 100) -eq [IntPtr]::Zero
}
if ($locker.HasExited) { throw 'Declining the confirmation ended the process.' }
Answer-OperationDialog 431 433
Answer-OperationDialog 100 6
if (!$locker.WaitForExit(5000)) { throw 'Confirming End process did not terminate the locker.' }
Wait-Until 'the process list refreshes after termination' {
(Read-Text ([FilesActivationUi]::GetDlgItem($dialog, 430))) -like 'No locking processes found*'
}
Answer-OperationDialog 431 1
} finally {
if (!$locker.HasExited) { $locker.Kill(); $locker.WaitForExit() }
$locker.Dispose()
}
Select-Row $left $operationName
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero)
Answer-OperationDialog 211 1
Wait-Until 'move and asynchronous pane refresh' {
!(Test-Path -LiteralPath $operationSource) -and
(Find-Row $left $operationName) -eq -1 -and (Find-Row $right $operationName) -ge 0
}
Select-Row $right $operationName
Wait-Until 'Files activation for Shift+Delete' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$shell.SendKeys('+{DELETE}')
Answer-OperationDialog 240 6
Wait-Until 'permanent deletion and asynchronous pane refresh' {
!(Test-Path -LiteralPath $operationTarget) -and (Find-Row $right $operationName) -eq -1 -and
[FilesActivationUi]::Focus($window) -eq $inputBox
}
Write-Output 'Copy overwrite, move and permanent deletion completed through their Files dialogs.'
$lockedFolder = Join-Path $leftOperation 'Locked folder'
[IO.Directory]::CreateDirectory($lockedFolder) | Out-Null
$folderReady = Join-Path $root 'folder-lock.ready'
$folderLocker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $lockedFolder,$folderReady) -WindowStyle Hidden -PassThru
try {
Wait-Until 'folder locked by the fixture process' { Test-Path -LiteralPath $folderReady }
Select-Row $left '[Locked folder]'
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x75, [IntPtr]::Zero)
Answer-OperationDialog 211 1
Answer-OperationDialog 100 103
Wait-Until 'the folder locker appears with its PID' {
$dialog = Find-OperationDialog $window 431
if ($dialog -eq [IntPtr]::Zero) { return $false }
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
(Find-Row $list ("KSwitcherFilesActivationFixture.exe (PID {0})" -f $folderLocker.Id)) -ge 0
}
Answer-OperationDialog 431 1
} finally {
if (!$folderLocker.HasExited) { $folderLocker.Kill(); $folderLocker.WaitForExit() }
$folderLocker.Dispose()
}
Write-Output 'The blocking-process dialog identified both a file lock and a folder lock by PID.'
foreach ($useRecycleBin in $false, $true) {
$name = if ($useRecycleBin) { 'Held for Recycle Bin' } else { 'Held for permanent deletion.txt' }
$target = Join-Path $leftOperation $name
if ($useRecycleBin) { [IO.Directory]::CreateDirectory($target) | Out-Null }
else { [IO.File]::WriteAllText($target, 'fixture') }
$label = if ($useRecycleBin) { "[$name]" } else { $name }
$ready = Join-Path $root "delete-lock-$useRecycleBin.ready"
$deleteLocker = Start-Process -FilePath $Fixture -ArgumentList ('--hold "{0}" "{1}"' -f $target,$ready) -WindowStyle Hidden -PassThru
try {
Wait-Until 'deletion target held by the fixture' { Test-Path -LiteralPath $ready }
Select-Row $left $label
if ($useRecycleBin) {
[void][FilesActivationUi]::PostMessage($left, 0x100, [IntPtr]0x77, [IntPtr]::Zero)
} else {
Wait-Until 'Files activation for blocked Shift+Delete' { [FilesActivationUi]::Activate($window) }
$shell.SendKeys('+{DELETE}')
}
Answer-OperationDialog 240 6
Wait-Until 'red failure dialog for blocked deletion' {
$dialog = Find-OperationDialog $window 100
$dialog -ne [IntPtr]::Zero -and [FilesActivationUi]::HasWarningBackground($dialog)
}
Answer-OperationDialog 100 103
$processLabel = 'KSwitcherFilesActivationFixture.exe (PID {0})' -f $deleteLocker.Id
Wait-Until 'deletion blocker appears in the process list' {
$dialog = Find-OperationDialog $window 431
$dialog -ne [IntPtr]::Zero -and
(Find-Row ([FilesActivationUi]::GetDlgItem($dialog, 431)) $processLabel) -ge 0
}
$dialog = Find-OperationDialog $window 431
$list = [FilesActivationUi]::GetDlgItem($dialog, 431)
[void][FilesActivationUi]::Send($list, 0x186, [IntPtr](Find-Row $list $processLabel), [IntPtr]::Zero)
Answer-OperationDialog 431 433
Answer-OperationDialog 100 6
if (!$deleteLocker.WaitForExit(5000)) { throw 'End process did not release the deletion target.' }
Wait-Until 'deletion blocker list refreshes' {
(Read-Text ([FilesActivationUi]::GetDlgItem($dialog, 430))) -like 'No locking processes found*'
}
Answer-OperationDialog 431 1
Wait-Until 'Files regains focus after closing the process list' {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
} finally {
if (!$deleteLocker.HasExited) { $deleteLocker.Kill(); $deleteLocker.WaitForExit() }
$deleteLocker.Dispose()
}
Select-Row $left $label
Wait-Until 'Files activation for deletion retry' { [FilesActivationUi]::Activate($window) }
$shell.SendKeys('+{DELETE}')
Answer-OperationDialog 240 6
Wait-Until 'deletion succeeds after ending the blocker' {
!(Test-Path -LiteralPath $target) -and (Find-Row $left $label) -eq -1
}
}
Write-Output 'Blocked permanent file deletion and folder recycling opened the shared process dialog and released their blockers.'
} catch {
if ($inputBox -and $status) {
Write-Output "Command input length: $((Read-Text $inputBox).Length). Status: $(Read-Text $status)"
+13
View File
@@ -1,9 +1,22 @@
#include <windows.h>
#include <filesystem>
#include <fstream>
#include <string_view>
int wmain(int argc,wchar_t **argv)
{
if(argc==4 && std::wstring_view(argv[1])==L"--hold")
{
const auto handle=CreateFileW(argv[2],GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,nullptr,
OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,nullptr);
if(handle==INVALID_HANDLE_VALUE) return 1;
const auto ready=CreateFileW(argv[3],GENERIC_WRITE,FILE_SHARE_READ,nullptr,CREATE_ALWAYS,0,nullptr);
if(ready==INVALID_HANDLE_VALUE){CloseHandle(handle);return 1;}
CloseHandle(ready);
Sleep(INFINITE);
CloseHandle(handle);
return 0;
}
// A launch through the embedded terminal would inherit its console.
DWORD consoleProcesses[1]{};
if(GetConsoleProcessList(consoleProcesses,1)>1) return 1;
+446
View File
@@ -0,0 +1,446 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$Screenshot
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class CompletionTest {
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string name, string title);
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, IntPtr process);
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern bool AttachThreadInput(uint first, uint second, bool attach);
[DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
public static void Activate(IntPtr window) {
var own = GetCurrentThreadId();
var foreground = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
bool attached = foreground != 0 && own != foreground && AttachThreadInput(own, foreground, true);
try { SetForegroundWindow(window); }
finally { if (attached) AttachThreadInput(own, foreground, false); }
}
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect bounds);
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint relation);
[StructLayout(LayoutKind.Sequential)]
public struct Point { public int X, Y; }
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(Point point);
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, int message, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, int message, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SetText(IntPtr window, int message, IntPtr w, string text);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr GetText(IntPtr window, int message, IntPtr w, StringBuilder text);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr ItemRect(IntPtr window, int message, IntPtr w, out Rect bounds);
}
"@
function Wait-Until([string]$Description, [scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 120; ++$attempt) {
if (& $Condition) { return }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for $Description"
}
function Set-Line([string]$Line) {
[void][CompletionTest]::SetText($edit, 0x000C, 0, $Line)
[void][CompletionTest]::Send($edit, 0x00B1, $Line.Length, $Line.Length)
}
function Read-Line {
$text = [Text.StringBuilder]::new(2049)
[void][CompletionTest]::GetText($edit, 0x000D, $text.Capacity, $text)
$text.ToString()
}
function Suggestions([string]$Expected, [int]$Count = -1) {
Wait-Until "suggestion '$Expected' (count $Count)" {
if (![CompletionTest]::IsWindowVisible($list)) { return $false }
$found = [CompletionTest]::SetText($list, 0x01A2, -1, $Expected).ToInt64()
$size = [CompletionTest]::Send($list, 0x018B, 0, 0).ToInt64()
$found -ge 0 -and ($Count -lt 0 -or $size -eq $Count)
}
}
function Press-Key([int]$Key) {
if (![CompletionTest]::PostMessage($edit, 0x0100, $Key, 1)) { throw 'Could not post key' }
}
function Toggle-Panels {
Wait-Until 'foreground Files window before toggling panes' {
if ([CompletionTest]::GetForegroundWindow() -eq $window) { return $true }
[void]$keyboard.AppActivate($process.Id)
[CompletionTest]::Activate($window)
[CompletionTest]::GetForegroundWindow() -eq $window
}
$keyboard.SendKeys('^o')
}
function Read-SuggestionFrameColor {
$frame = [CompletionTest]::GetWindow($list, 2)
$bounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($frame, [ref]$bounds)
$pixel = [Drawing.Bitmap]::new(1, 1)
$graphics = [Drawing.Graphics]::FromImage($pixel)
try {
$graphics.CopyFromScreen($bounds.Left + 2, $bounds.Top + 2, 0, 0, $pixel.Size)
$pixel.GetPixel(0, 0).ToArgb()
} finally {
$graphics.Dispose()
$pixel.Dispose()
}
}
function Test-DotnetCompletion {
if (!$hasDotnetSdk) { return }
Set-Line 'dotnet '
Suggestions 'build'
Set-Line 'dotnet bu'
Suggestions 'build'
Set-Line 'dotnet build --no-res'
Suggestions '--no-restore'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, '--no-restore')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'dotnet option insertion' { (Read-Line) -ceq 'dotnet build --no-restore' }
}
function Test-GitCompletion {
if (!$gitFixture) { return }
Set-Line 'git ch'
Suggestions 'checkout'
Set-Line 'git --ver'
Suggestions '--version'
$switch = 'git -C "' + $gitFixture + '" switch '
Set-Line ($switch + '--de')
Suggestions '--detach'
$prefix = $switch + 'comp'
Set-Line $prefix
Suggestions 'completion-one'
Suggestions 'completion-two'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'completion-one')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'Git branch insertion' { (Read-Line) -ceq ($prefix + 'letion-one') }
}
function Test-WindowsCommandCompletion {
Set-Line 'ipconfig '
Suggestions '/all'
Set-Line 'ipconfig /re'
Suggestions '/renew'
Suggestions '/release'
Set-Line 'ipconfig ?'
Suggestions '/?'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, '/?')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'ipconfig help switch insertion' { (Read-Line) -ceq 'ipconfig /?' }
Set-Line 'tasklist.exe /f'
Suggestions '/fo'
Set-Line 'robocopy /mi'
Suggestions '/mir'
Set-Line 'reg q'
Suggestions 'query'
Set-Line 'reg query /r'
Suggestions '/reg:64'
Set-Line 'cmd /c dir /'
Suggestions '/w'
Set-Line 'dir -Fi'
Suggestions 'File'
}
function Test-NestedWindowsCommandCompletion {
Set-Line 'netsh interface ip'
Suggestions 'ipv4'
Set-Line 'netsh interface ipv4 sh'
Suggestions 'show'
Set-Line 'netsh interface ipv4 show co'
Suggestions 'config'
Set-Line 'netsh interface ipv4 show config na'
Suggestions 'name='
Set-Line 'fsutil file queryallocranges of'
Suggestions 'offset='
Set-Line 'wevtutil query-events /sb'
Suggestions '/sbm:'
Set-Line 'schtasks /query /fo L'
Suggestions 'LIST'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'LIST')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'nested Windows option insertion' { (Read-Line) -ceq 'schtasks /query /fo LIST' }
}
function Test-IpconfigAdapterCompletion {
$adapters = foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
try {
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
} catch {}
}
if (!$adapters) { return }
$name = $adapters | Where-Object { $_ -match '^[\p{L}\p{N}-]+ [\p{L}\p{N} ]+$' } | Select-Object -First 1
if ($name) {
$prefix = '"' + $name.Substring(0, $name.IndexOf(' ') + 1)
$expected = "'" + $name + "'"
} else {
$name = $adapters | Where-Object { $_ -match '^[\p{L}\p{N}-]+$' } | Select-Object -First 1
if (!$name) { return }
$prefix = $name.Substring(0, 1).ToUpperInvariant()
$expected = $name
}
Set-Line 'ipconfig /renew '
Suggestions $name
Set-Line ('ipconfig.exe /release ' + $prefix)
Suggestions $name
$row = [CompletionTest]::SetText($list, 0x01A2, -1, $name)
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'ipconfig adapter insertion' { (Read-Line) -ceq ('ipconfig.exe /release ' + $expected) }
}
function Test-PathCompletion {
$prefix = 'cd "' + $root + '\Al'
Set-Line $prefix
Suggestions 'Alpine' 2
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'p', 1)
Suggestions 'Alpha Space' 2
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'h', 1)
Suggestions 'Alpha Space' 1
$row = [CompletionTest+Rect]::new()
[void][CompletionTest]::ItemRect($list, 0x0198, 0, [ref]$row)
$listBounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($list, [ref]$listBounds)
$mouse = [CompletionTest+Point]::new()
$mouse.X = $listBounds.Left + 5
$mouse.Y = $listBounds.Top + (($row.Top + $row.Bottom) -shr 1)
if ([CompletionTest]::WindowFromPoint($mouse) -ne $list) { throw 'The suggestions list is covered' }
$point = ((($row.Top + $row.Bottom) -shr 1) -shl 16) -bor 5
[void][CompletionTest]::PostMessage($list, 0x0201, 1, $point)
Wait-Until 'click insertion with quotes' { (Read-Line) -ceq ('cd "' + $root + '\Alpha Space"') }
[void][CompletionTest]::Send($edit, 0x0102, [int][char]'\', 1)
Suggestions 'Nested' 1
Press-Key 0x1B
Wait-Until 'Escape dismissal' { ![CompletionTest]::IsWindowVisible($list) }
if ((Read-Line) -cne ('cd "' + $root + '\Alpha Space\"')) { throw 'Escape changed the command line' }
}
$root = Join-Path ([IO.Path]::GetTempPath()) ("KSwitcherCompletion-" + [guid]::NewGuid().ToString('N'))
$process = $null
$dotnet = Get-Command dotnet.exe -CommandType Application -ErrorAction SilentlyContinue
$hasDotnetSdk = $dotnet -and [bool](& $dotnet.Source --list-sdks)
$historyKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$historyPrefix = "Write-Output 'completion-$([guid]::NewGuid().ToString('N'))"
$latest = "$historyPrefix-alpha-recent'"
$earlier = "$historyPrefix-alpha-earlier'"
$other = "$historyPrefix-beta'"
$combined = "Get-ChildItem -Name # $([guid]::NewGuid().ToString('N'))"
$clearPrefix = ' cls '
$clearHistory = "$clearPrefix# $([guid]::NewGuid().ToString('N'))"
$fixture = "2026-01-01`0$earlier`02026-01-01`0$other`02026-01-01`0$earlier`02026-01-01`0$latest`02026-01-01`0$combined`02026-01-01`0$clearHistory`0"
function Remove-HistoryFixture {
$bytes = $historyKey.GetValue('CommandHistory')
if ($bytes -isnot [byte[]]) { return }
$current = [Text.Encoding]::Unicode.GetString($bytes)
$clean = $current.Replace($fixture, '')
if ($clean -ceq $current) { return }
if ($clean.Length -eq 0 -and $null -eq $originalHistory) {
$historyKey.DeleteValue('CommandHistory', $false)
} else {
$historyKey.SetValue('CommandHistory', [Text.Encoding]::Unicode.GetBytes($clean), 'Binary')
}
}
try {
$originalHistory = $historyKey.GetValue('CommandHistory')
$history = if ($null -ne $originalHistory) { [Text.Encoding]::Unicode.GetString($originalHistory) } else { '' }
$historyKey.SetValue('CommandHistory', [Text.Encoding]::Unicode.GetBytes($history + $fixture), 'Binary')
[void](New-Item -ItemType Directory -Path "$root\Alpha Space\Nested", "$root\Alpine")
$gitFixture = $null
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($git) {
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source))
for ($level = 0; $location -and $level -lt 3; ++$level) {
$installation = $location.FullName
$location = $location.Parent
if (!(Test-Path -LiteralPath (Join-Path $installation 'usr/bin/bash.exe'))) { continue }
$gitFixture = Join-Path $root 'Git Repo'
[void](New-Item -ItemType Directory -Path $gitFixture)
& $git.Source -C $gitFixture init --quiet --template= --initial-branch=main
if ($LASTEXITCODE) { throw 'Could not initialize the Git fixture' }
& $git.Source -C $gitFixture -c user.name=Test -c user.email=test@example.invalid -c commit.gpgSign=false -c core.hooksPath=NUL commit --quiet --allow-empty -m fixture
if ($LASTEXITCODE) { throw 'Could not create the Git fixture commit' }
& $git.Source -C $gitFixture branch completion-one
if ($LASTEXITCODE) { throw 'Could not create Git fixture branch completion-one' }
& $git.Source -C $gitFixture branch completion-two
if ($LASTEXITCODE) { throw 'Could not create Git fixture branch completion-two' }
break
}
}
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru -WindowStyle Normal
Wait-Until 'Files window' {
$process.Refresh()
$process.MainWindowHandle -ne [IntPtr]::Zero
}
Remove-HistoryFixture
$window = $process.MainWindowHandle
$keyboard = New-Object -ComObject WScript.Shell
Wait-Until 'foreground Files window' {
[void]$keyboard.AppActivate($process.Id)
[CompletionTest]::Activate($window)
[CompletionTest]::GetForegroundWindow() -eq $window
}
$edit = [CompletionTest]::FindWindowEx($window, 0, 'Edit', [System.Management.Automation.Language.NullString]::Value)
$list = [CompletionTest]::GetDlgItem($window, 149)
if (!$edit -or !$list) { throw 'Missing command line or suggestions list' }
[void][CompletionTest]::SetThreadDpiAwarenessContext(-4)
$status = [CompletionTest]::GetDlgItem($window, 144)
$panel = [CompletionTest]::GetDlgItem($window, 102)
$statusBounds = [CompletionTest+Rect]::new()
$panelBounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($panel, [ref]$panelBounds)
[void][CompletionTest]::GetWindowRect($status, [ref]$statusBounds)
if ($statusBounds.Left -ge $panelBounds.Right) {
Press-Key 0x09
Wait-Until 'left panel active' {
$bounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($status, [ref]$bounds)
$bounds.Left -lt $panelBounds.Right
}
[void][CompletionTest]::GetWindowRect($status, [ref]$statusBounds)
}
Set-Line $clearPrefix
Suggestions $clearHistory 1
Set-Line 'Get-Chi'
Suggestions 'Get-ChildItem'
Suggestions $combined
$frame = [CompletionTest]::GetWindow($list, 2)
$frameBounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($frame, [ref]$frameBounds)
$x = [Math]::Max($statusBounds.Left, $frameBounds.Left)
$y = [Math]::Max($statusBounds.Top, $frameBounds.Top)
$w = [Math]::Min($statusBounds.Right, $frameBounds.Right) - $x
$h = [Math]::Min($statusBounds.Bottom, $frameBounds.Bottom) - $y
if ($w -le 0 -or $h -le 0) { throw 'Suggestions and status must overlap for the repaint check' }
$before = [Drawing.Bitmap]::new($w, $h)
$after = [Drawing.Bitmap]::new($w, $h)
try {
$graphics = [Drawing.Graphics]::FromImage($before)
try { $graphics.CopyFromScreen($x, $y, 0, 0, $before.Size) } finally { $graphics.Dispose() }
[void][CompletionTest]::SetText($status, 0x000C, 0, ('Status repaint test ' * 48))
[void][CompletionTest]::RedrawWindow($status, 0, 0, 0x0105)
$graphics = [Drawing.Graphics]::FromImage($after)
try { $graphics.CopyFromScreen($x, $y, 0, 0, $after.Size) } finally { $graphics.Dispose() }
for ($rowPixel = 0; $rowPixel -lt $h; ++$rowPixel) {
for ($columnPixel = 0; $columnPixel -lt $w; ++$columnPixel) {
if ($before.GetPixel($columnPixel, $rowPixel) -ne $after.GetPixel($columnPixel, $rowPixel)) {
throw 'Status repaint drew over command suggestions'
}
}
}
} finally {
$before.Dispose()
$after.Dispose()
}
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'Get-ChildItem')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x09
Wait-Until 'Tab insertion' { (Read-Line) -ceq 'Get-ChildItem' }
Set-Line ($historyPrefix.ToUpperInvariant())
Suggestions $latest 3
Set-Line "$historyPrefix-alpha"
Suggestions $earlier 2
Press-Key 0x09
Wait-Until 'most recent history insertion' { (Read-Line) -ceq $latest }
Set-Line 'Get-ChildItem -Pa'
Suggestions 'Path'
$row = [CompletionTest]::SetText($list, 0x01A2, -1, 'Path')
[void][CompletionTest]::Send($list, 0x0186, $row, 0)
Press-Key 0x0D
Wait-Until 'Enter insertion' { (Read-Line) -ceq 'Get-ChildItem -Path' }
Test-PathCompletion
Test-DotnetCompletion
Test-GitCompletion
Test-WindowsCommandCompletion
Test-NestedWindowsCommandCompletion
Test-IpconfigAdapterCompletion
# Toggle with a populated list and verify the same draft and suggestions remain accessible.
Set-Line "$historyPrefix-alpha"
Suggestions $latest 2
$frameColor = Read-SuggestionFrameColor
$output = [CompletionTest]::GetDlgItem($window, 145)
Toggle-Panels
Wait-Until 'terminal-only view' {
[CompletionTest]::IsWindowVisible($output) -and ![CompletionTest]::IsWindowVisible($panel) -and
[CompletionTest]::GetWindow($output, 5) -ne [IntPtr]::Zero
}
Suggestions $latest 2
# Let WebView2 finish its first compositor update after showing the terminal.
Start-Sleep -Milliseconds 350
if ((Read-SuggestionFrameColor) -ne $frameColor) {
throw 'Terminal output drew over command suggestions with panels hidden'
}
if ($Screenshot) {
[void][CompletionTest]::SetThreadDpiAwarenessContext(-4)
$bounds = [CompletionTest+Rect]::new()
[void][CompletionTest]::GetWindowRect($window, [ref]$bounds)
$bitmap = [Drawing.Bitmap]::new($bounds.Right - $bounds.Left, $bounds.Bottom - $bounds.Top)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bitmap.Size)
$bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png)
} finally {
$graphics.Dispose()
$bitmap.Dispose()
}
}
Press-Key 0x28
Press-Key 0x0D
Wait-Until 'history insertion with panels hidden' { (Read-Line) -ceq $latest }
Test-PathCompletion
Test-DotnetCompletion
Test-GitCompletion
Test-WindowsCommandCompletion
Test-NestedWindowsCommandCompletion
Test-IpconfigAdapterCompletion
Toggle-Panels
Wait-Until 'panels restored' { [CompletionTest]::IsWindowVisible($panel) }
Set-Line "$historyPrefix-alpha"
Suggestions $latest 2
'Command completion passed with panels visible and hidden'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id }
Remove-HistoryFixture
$historyKey.Dispose()
if ($gitFixture -and (Test-Path -LiteralPath $gitFixture)) {
$resolved = (Resolve-Path -LiteralPath $gitFixture).ProviderPath
if ($resolved -eq [IO.Path]::GetFullPath((Join-Path $root 'Git Repo'))) {
Remove-Item -LiteralPath $resolved -Recurse -Force
}
}
foreach ($path in "$root\Alpha Space\Nested", "$root\Alpha Space", "$root\Alpine", $root) {
if (Test-Path -LiteralPath $path) { [IO.Directory]::Delete($path) }
}
}
+74 -1
View File
@@ -1,15 +1,26 @@
param([string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe")
param(
[string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe",
[switch]$OfflineWake,
[string]$Screenshot
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class FilesDriveShortcutTest {
[StructLayout(LayoutKind.Sequential)]
public struct Rect { public int Left, Top, Right, Bottom; }
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr SendMessage(IntPtr window, uint msg, IntPtr w, StringBuilder text);
[DllImport("user32.dll", EntryPoint="SendMessageW")]
public static extern IntPtr SendRect(IntPtr window, uint msg, IntPtr w, out Rect rect);
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags);
}
'@
function Wait-Until([scriptblock]$Condition) {
@@ -38,6 +49,68 @@ try {
[void][FilesDriveShortcutTest]::PostMessage($picker, 258, [IntPtr][int]$Key, [IntPtr]::Zero)
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
}
if ($OfflineWake) {
function Read-Picker {
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i }
}
function Render-Picker {
$client = [FilesDriveShortcutTest+Rect]::new()
[void][FilesDriveShortcutTest]::GetClientRect($picker, [ref]$client)
$bitmap = [Drawing.Bitmap]::new($client.Right, $client.Bottom)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try {
if (![FilesDriveShortcutTest]::PrintWindow($picker, $dc, 2)) { throw 'Could not render drive picker.' }
} finally { $graphics.ReleaseHdc($dc) }
return $bitmap
} finally { $graphics.Dispose() }
}
function Click-Picker([int]$X, [int]$Y) {
$point = [IntPtr](($Y -shl 16) -bor $X)
[void][FilesDriveShortcutTest]::PostMessage($picker, 513, [IntPtr]1, $point)
[void][FilesDriveShortcutTest]::PostMessage($picker, 514, [IntPtr]::Zero, $point)
}
Open-Picker
$rows = @(Read-Picker)
$wake = -1
for ($i = 0; $i -lt $rows.Count; $i++) {
if ($rows[$i] -match '^ (Offline|Looking for PC\.\.\.) \tWake$') { $wake = $i; break }
}
if ($wake -lt 0) { throw 'This check requires an offline paired PC with a Wake action.' }
$rect = [FilesDriveShortcutTest+Rect]::new()
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]$wake, [ref]$rect)
$original = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null)
Click-Picker ($rect.Left + 16) ([int](($rect.Top + $rect.Bottom) / 2))
Start-Sleep -Milliseconds 100
if (![FilesDriveShortcutTest]::IsWindowVisible($picker) -or
[FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null) -ne $original) {
throw 'Clicking outside the Wake label selected or activated the status row.'
}
[void][FilesDriveShortcutTest]::PostMessage($picker, 675, [IntPtr]::Zero, [IntPtr]::Zero)
$normal = Render-Picker
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$wake, $null)
$focused = Render-Picker
try {
$changed = @(for ($x = $rect.Left; $x -lt [Math]::Min($rect.Right, $normal.Width); $x++) {
if ($normal.GetPixel($x,$rect.Top) -ne $focused.GetPixel($x,$rect.Top)) { $x }
})
$width = $rect.Right - $rect.Left
if (!$changed.Count -or $changed[0] -lt ($rect.Left + $width / 2) -or $changed[-1] -ge $rect.Right - 2) {
throw 'Wake focus must highlight only the inline action and leave the status and trailing space unchanged.'
}
if ($Screenshot) { $focused.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png) }
Click-Picker ([int](($changed[0]+$changed[-1])/2)) ([int](($rect.Top+$rect.Bottom)/2))
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
} finally { $normal.Dispose(); $focused.Dispose() }
Open-Picker
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$wake, $null)
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]13, [IntPtr]::Zero)
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
Write-Output 'Wake focus and mouse activation are limited to the inline action. Enter activates the focused action.'
return
}
Open-Picker
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
$rows = @(for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i })
+226
View File
@@ -0,0 +1,226 @@
param(
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe",
[string]$Screenshot
)
$ErrorActionPreference = 'Stop'
Add-Type @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class FilesShortcutWindow {
[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 GetForegroundWindow();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint command);
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr window, ref Point point);
[DllImport("user32.dll", EntryPoint="SendMessageW")]
public static extern IntPtr Send(IntPtr window, uint message, IntPtr w, IntPtr l);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr SendMessage(IntPtr window, uint msg, IntPtr w, StringBuilder text);
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(0x12, 0, 0, UIntPtr.Zero);
keybd_event(0x12, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
}
'@
function Wait-Until([scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 100; $attempt++) {
if (& $Condition) { return }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for: $Condition"
}
function Read-Text($Control, $Message = 13, $Parameter = 2048) {
$buffer = [Text.StringBuilder]::new(2048)
[void][FilesShortcutWindow]::SendMessage($Control, $Message, [IntPtr]$Parameter, $buffer)
$buffer.ToString()
}
function Read-ShortcutDialog {
$foreground = [FilesShortcutWindow]::GetForegroundWindow()
if ([FilesShortcutWindow]::GetWindow($foreground, 4) -eq $window -and
[FilesShortcutWindow]::GetDlgItem($foreground, 310) -ne [IntPtr]::Zero) { return $foreground }
return [IntPtr]::Zero
}
$exe = (Resolve-Path $Executable).Path
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$saved = @{}
$names = 'FolderShortcuts', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
foreach ($name in $names) {
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
}
$folder = [IO.Directory]::CreateTempSubdirectory('ks-files-shortcuts-').FullName
$previousDpi = [FilesShortcutWindow]::SetThreadDpiAwarenessContext([IntPtr](-4))
try {
$groups = [object[]]::new(10)
for ($digit = 0; $digit -lt 10; $digit++) { $groups[$digit] = @() }
foreach ($entry in @(@(3, 'Three'), @(4, 'Four'), @(8, 'Eight A'), @(8, 'Eight B'))) {
$path = [IO.Directory]::CreateDirectory((Join-Path $folder $entry[1])).FullName
$groups[$entry[0]] += @{ path = $path; peer = ''; name = ''; title = $entry[1] }
}
$groups[9] = @(1..200 | ForEach-Object {
@{ path = (Join-Path $folder "Folder $_"); peer = ''; name = ''; title = "Folder $_" }
})
$key.SetValue('FolderShortcuts', [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $groups -Depth 4)), 'Binary')
foreach ($name in 'LeftWide', 'RightWide') { $key.SetValue($name, 1, 'DWord') }
foreach ($name in 'LeftPath', 'RightPath') { $key.SetValue($name, $folder, 'String') }
$key.DeleteValue('WindowPlacement', $false)
$process = Start-Process -FilePath $exe -PassThru
$keyboard = New-Object -ComObject WScript.Shell
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
$window = $process.MainWindowHandle
Wait-Until { [FilesShortcutWindow]::Activate($window) }
$heading = [FilesShortcutWindow]::GetDlgItem($window, 140)
$rightHeading = [FilesShortcutWindow]::GetDlgItem($window, 141)
$leftPath = [FilesShortcutWindow]::GetDlgItem($window, 142)
Wait-Until { (Read-Text $leftPath) -eq $folder }
$keyboard.SendKeys('^8')
Wait-Until { (Read-ShortcutDialog) -ne [IntPtr]::Zero }
$dialog = Read-ShortcutDialog
$list = [FilesShortcutWindow]::GetDlgItem($dialog, 310)
$count = [FilesShortcutWindow]::SendMessage($list, 395, [IntPtr]::Zero, $null).ToInt32()
$rows = for ($row = 0; $row -lt $count; $row++) { Read-Text $list 393 $row }
if (($rows -join '|') -cne 'Eight A|Eight B') {
throw "Ctrl+8 should display only its two assigned folders. Actual rows: $($rows -join ' | ')"
}
if ($Screenshot) {
Add-Type -AssemblyName System.Drawing
$bounds = [FilesShortcutWindow+Rect]::new()
if (![FilesShortcutWindow]::GetWindowRect($dialog, [ref]$bounds)) { throw 'Cannot locate the rendered popup.' }
$bitmap = [Drawing.Bitmap]::new(($bounds.Right - $bounds.Left), ($bounds.Bottom - $bounds.Top))
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try { $graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bitmap.Size) }
finally { $graphics.Dispose() }
$bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png)
} finally { $bitmap.Dispose() }
}
$keyboard.SendKeys('{ESC}')
Wait-Until { [FilesShortcutWindow]::GetForegroundWindow() -eq $window }
$keyboard.SendKeys('^4')
Wait-Until { (Read-Text $leftPath) -eq (Join-Path $folder 'Four') }
if (![FilesShortcutWindow]::IsWindowVisible($heading)) { throw 'Ctrl+4 changed panel mode.' }
$keyboard.SendKeys('^{TAB}')
$keyboard.SendKeys('^{F1}')
Wait-Until {
![FilesShortcutWindow]::IsWindowVisible($heading) -or
![FilesShortcutWindow]::IsWindowVisible($rightHeading)
}
if (![FilesShortcutWindow]::IsWindowVisible($rightHeading)) {
throw 'Ctrl+Tab changed the active panel.'
}
$keyboard.SendKeys('{TAB}')
$keyboard.SendKeys('^{F1}')
Wait-Until { ![FilesShortcutWindow]::IsWindowVisible($rightHeading) }
$keyboard.SendKeys('^{F2}')
Wait-Until { [FilesShortcutWindow]::IsWindowVisible($rightHeading) }
$keyboard.SendKeys('{TAB}')
Wait-Until { ![FilesShortcutWindow]::IsWindowVisible($heading) }
$rightPath = [FilesShortcutWindow]::GetDlgItem($window, 143)
$leftList = [FilesShortcutWindow]::GetDlgItem($window, 102)
$rightList = [FilesShortcutWindow]::GetDlgItem($window, 103)
$keyboard.SendKeys('^u')
Wait-Until {
(Read-Text ([FilesShortcutWindow]::GetDlgItem($window, 142))) -eq $folder -and
(Read-Text ([FilesShortcutWindow]::GetDlgItem($window, 143))) -eq (Join-Path $folder 'Four') -and
[FilesShortcutWindow]::IsWindowVisible($rightHeading)
}
$movedLeft = [FilesShortcutWindow+Rect]::new()
$movedRight = [FilesShortcutWindow+Rect]::new()
if (![FilesShortcutWindow]::GetWindowRect($rightList, [ref]$movedLeft) -or
![FilesShortcutWindow]::GetWindowRect($leftList, [ref]$movedRight) -or
$movedLeft.Right -gt $movedRight.Left -or
[FilesShortcutWindow]::IsWindowVisible($heading)) {
throw 'Ctrl+U did not move the visible panel lists with their modes.'
}
$keyboard.SendKeys('^3')
Wait-Until { (Read-Text $leftPath) -eq (Join-Path $folder 'Three') }
if ((Read-Text $rightPath) -ne $folder) { throw 'Ctrl+U did not preserve the active panel.' }
$keyboard.SendKeys('^u')
Wait-Until { [FilesShortcutWindow]::GetDlgItem($window, 142) -eq $leftPath }
$keyboard.SendKeys('^{F2}')
Wait-Until { [FilesShortcutWindow]::IsWindowVisible($heading) }
$keyboard.SendKeys('^9')
Wait-Until { (Read-ShortcutDialog) -ne [IntPtr]::Zero }
$dialog = Read-ShortcutDialog
$list = [FilesShortcutWindow]::GetDlgItem($dialog, 310)
Add-Type -AssemblyName System.Drawing
$bounds = [FilesShortcutWindow+Rect]::new()
if (![FilesShortcutWindow]::GetWindowRect($list, [ref]$bounds)) { throw 'Missing overflow list.' }
Start-Sleep -Milliseconds 150
$barWidth = [int][Math]::Round(12 * [FilesShortcutWindow]::GetDpiForWindow($list) / 96)
$bitmap = [Drawing.Bitmap]::new($barWidth, ($bounds.Bottom - $bounds.Top))
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try { $graphics.CopyFromScreen($bounds.Right, $bounds.Top, 0, 0, $bitmap.Size) }
finally { $graphics.Dispose() }
$background = $bitmap.GetPixel(0, 0)
$thumb = $bitmap.GetPixel(0, $barWidth + 1)
$trackColors = @(0..4 | ForEach-Object {
$x = $_
0..7 | ForEach-Object { $bitmap.GetPixel($x, [int]($bitmap.Height / 2) + $_).ToArgb() }
} | Sort-Object -Unique)
$hasArrow = {
param($y)
$center = [int][Math]::Floor($barWidth / 2)
@(0..($barWidth - 1) | Where-Object {
$bitmap.GetPixel($center, $y + $_).ToArgb() -eq $thumb.ToArgb()
}).Count -gt 0
}
if ($thumb.GetBrightness() -le $background.GetBrightness() -or $trackColors.Count -ne 2 -or
!(& $hasArrow 0) -or !(& $hasArrow ($bitmap.Height - $barWidth))) {
throw "Unexpected scrollbar pixels. Background $background, thumb $thumb, track colors $($trackColors.Count), arrows $(& $hasArrow 0)/$(& $hasArrow ($bitmap.Height - $barWidth))."
}
} finally { $bitmap.Dispose() }
$arrow = [FilesShortcutWindow+Point]::new()
$arrow.X = $bounds.Right + [int]($barWidth / 2)
$arrow.Y = $bounds.Bottom - [int]($barWidth / 2)
if (![FilesShortcutWindow]::ScreenToClient($dialog, [ref]$arrow)) { throw 'Cannot locate the down arrow.' }
$arrowPoint = [IntPtr](($arrow.Y -shl 16) -bor $arrow.X)
[void][FilesShortcutWindow]::Send($dialog, 0x0201, [IntPtr]1, $arrowPoint)
if ([FilesShortcutWindow]::Send($list, 0x018E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne 1) {
throw 'The down arrow should scroll the list by one row.'
}
$grip = [FilesShortcutWindow+Point]::new()
$grip.X = $bounds.Right + [int]($barWidth / 2)
$grip.Y = $bounds.Top + $barWidth + 4
if (![FilesShortcutWindow]::ScreenToClient($dialog, [ref]$grip)) { throw 'Cannot locate the thumb.' }
$gripPoint = [IntPtr](($grip.Y -shl 16) -bor $grip.X)
$dragPoint = [IntPtr]((($grip.Y + 3 * $barWidth) -shl 16) -bor $grip.X)
[void][FilesShortcutWindow]::Send($dialog, 0x0201, [IntPtr]1, $gripPoint)
[void][FilesShortcutWindow]::Send($dialog, 0x0200, [IntPtr]1, $dragPoint)
[void][FilesShortcutWindow]::Send($dialog, 0x0202, [IntPtr]::Zero, $dragPoint)
if ([FilesShortcutWindow]::Send($list, 0x018E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -le 1) {
throw 'Dragging the scrollbar thumb should advance the list.'
}
$keyboard.SendKeys('{ESC}')
Write-Output 'Verified folder shortcuts, panel swapping, and the rendered overflow scrollbar.'
} finally {
if ($previousDpi) { [void][FilesShortcutWindow]::SetThreadDpiAwarenessContext($previousDpi) }
if ($process -and !$process.HasExited) {
$keyboard.SendKeys('{ESC}')
if (!$process.CloseMainWindow() -or !$process.WaitForExit(2500)) { $process.Kill(); $process.WaitForExit() }
}
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $key.DeleteValue($name, $false) }
}
$key.Dispose()
[IO.Directory]::Delete($folder, $true)
}
+14 -1
View File
@@ -54,10 +54,12 @@ public static class MarkdownUi {
keybd_event(0x12,0,2,UIntPtr.Zero);
SetForegroundWindow(window);
}
public static void CycleWindow() {
public static void CycleWindow(bool reverse = false) {
keybd_event(0x11,0,0,UIntPtr.Zero);
if (reverse) keybd_event(0x10,0,0,UIntPtr.Zero);
keybd_event(0x09,0,0,UIntPtr.Zero);
keybd_event(0x09,0,2,UIntPtr.Zero);
if (reverse) keybd_event(0x10,0,2,UIntPtr.Zero);
keybd_event(0x11,0,2,UIntPtr.Zero);
}
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
@@ -328,8 +330,19 @@ const value = 42;
Wait-Foreground $window
Browser 'cycle' '' 'Preview.md'
Wait-Foreground $child
Browser 'cycle-reverse' '' 'Other.md'
Wait-Foreground $window
Browser 'edit' '' 'Preview.md'
[void](Wait-For 'the first window to switch to Editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' })
[MarkdownUi]::CycleWindow($true)
Wait-Foreground $main
[MarkdownUi]::CycleWindow($true)
Wait-Foreground $child
Write-Output 'Verified backward Ctrl+Shift+Tab cycling through three windows and wrapping at Files.'
Browser 'close' '' 'Other.md'
[void](Wait-For 'Ctrl+W to close the Shift+click window' { ![MarkdownUi]::IsWindowVisible($child) })
Post (Scintilla $window) 0x100 0x75
Browser 'Перегляд Markdown' '' 'Preview.md'
Browser 'follow'
if ((Wait-For 'the in-place Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
throw 'A normal click did not stay in the same window.'
+10 -4
View File
@@ -3,7 +3,7 @@ import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
const [port, scenario, artifact, title] = process.argv.slice(2);
const terminalScenario = ['terminal-enter', 'terminal-copy', 'terminal-select-output'].includes(scenario);
const terminalScenario = scenario.startsWith('terminal-');
let socket;
const pending = new Map();
let sequence = 0;
@@ -69,7 +69,10 @@ await new Promise((resolve, reject) => {
});
try {
if (scenario === 'terminal-select-output') {
if (scenario === 'terminal-startup-pause' || scenario === 'terminal-startup-resume') {
await waitFor(() => evaluate('typeof startTerminalFixture === "function"'), 'the delayed terminal page');
if (scenario === 'terminal-startup-resume') await evaluate('startTerminalFixture()');
} else if (scenario === 'terminal-select-output') {
const selection = await waitFor(() => evaluate(`(() => {
const marker = 'terminal-output-copy-fixture';
const buffer = terminal.buffer.active;
@@ -82,6 +85,8 @@ try {
})()`), 'the terminal output fixture');
assert.equal(selection, 'terminal-output-copy-fixture');
} else if (terminalScenario) {
assert.equal(await evaluate('terminal.options.cursorInactiveStyle'), 'none');
assert.equal(await evaluate('document.querySelectorAll(".xterm-cursor-outline").length'), 0);
await evaluate('document.querySelector(".xterm-helper-textarea").focus()');
const key = scenario === 'terminal-copy'
? { key:'Insert', code:'Insert', modifiers:2, windowsVirtualKeyCode:45 }
@@ -209,8 +214,9 @@ try {
} else if (scenario === 'back' || scenario === 'forward') {
await waitFor(() => evaluate(`!document.getElementById('${scenario}').disabled`), scenario);
await evaluate(`document.getElementById('${scenario}').click()`);
} else if (scenario === 'cycle') {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers:2, windowsVirtualKeyCode:9});
} else if (scenario === 'cycle' || scenario === 'cycle-reverse') {
const modifiers = scenario === 'cycle-reverse' ? 10 : 2;
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers, windowsVirtualKeyCode:9});
} else if (scenario === 'close') {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'w', code:'KeyW', modifiers:2, windowsVirtualKeyCode:87});
} else {
+1 -1
View File
@@ -57,7 +57,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
return font;
};
dialogs.confirmExisting=[](HWND){return true;};
dialogs.confirmSave=[](HWND)->INT_PTR {return IDYES;};
dialogs.confirmSave=[](HWND,bool)->INT_PTR {return IDYES;};
dialogs.message=[](HWND,const wchar_t *message){log(message);};
dialogs.dismissOwned=[](HWND){return false;};
files::openTextWindow(owner,document,false,dialogs,&peer);
+150 -33
View File
@@ -1,4 +1,4 @@
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly)
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly,[switch]$CreateFileOnly)
$ErrorActionPreference='Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @"
@@ -19,6 +19,21 @@ public static class SearchArrowTest {
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags);
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
[DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr hwnd, IntPtr rect, bool erase);
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
[DllImport("gdi32.dll")] static extern bool SetPixelV(IntPtr dc, int x, int y, uint color);
public static bool EditorMenuProbe(IntPtr window, bool write) {
const uint color = 0x00ff00ff;
var dc = GetDC(window);
if (dc == IntPtr.Zero) throw new InvalidOperationException("Cannot sample the editor.");
try {
if (write && !SetPixelV(dc, 4, 4, color))
throw new InvalidOperationException("Cannot mark the editor menu.");
return GetPixel(dc, 4, 4) == color;
} finally { ReleaseDC(window, dc); }
}
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out Rect rect);
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
@@ -242,7 +257,7 @@ foreach($name in 'A.txt','B.txt','C.txt','D.txt'){
$copy=Join-Path $scratch 'KSwitcher.Files.search-arrow-test.exe'
Copy-Item -LiteralPath $Executable -Destination $copy
$profile=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement','FileStyles'
$saved=@{}
foreach($name in $keysToRestore){
if($name -in $profile.GetValueNames()){
@@ -256,19 +271,130 @@ try {
$profile.SetValue('RightPath',$rightFixture)
$profile.DeleteValue('LeftCursor',$false)
$profile.DeleteValue('RightCursor',$false)
$styles='[{"extension":".txt","background":3158064,"states":[{},{},{"background":3166352}]}]'
$profile.SetValue('FileStyles',[Text.Encoding]::UTF8.GetBytes($styles),'Binary')
$process=Start-Process -FilePath $copy -ArgumentList '--terminal-trace' -PassThru -WindowStyle Normal
$paintTrace=Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
$previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
$main = Wait-Until { Find-Window 'KSwitcher.Files' $process.Id }
$leftPanel=[SearchArrowTest]::GetDlgItem($main,102)
$rightPanel=[SearchArrowTest]::GetDlgItem($main,103)
$clicks=if(!$KeyboardCursorOnly){
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
# Initial directory scans repaint both panels when their results arrive.
[void](Wait-Until {
[SearchArrowTest]::SendText($leftPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0 -and
[SearchArrowTest]::SendText($rightPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0
})
if ($CreateFileOnly) {
function Assert-DialogSurface($Dialog, [int]$Red, [int]$Green) {
$bounds=Read-Bounds $Dialog
$bitmap=[Drawing.Bitmap]::new(1,1)
try {
$graphics=[Drawing.Graphics]::FromImage($bitmap)
try {
[void](Wait-Until {
$graphics.CopyFromScreen(($bounds.Left+4),($bounds.Top+4),0,0,$bitmap.Size)
$pixel=$bitmap.GetPixel(0,0)
$pixel.R -eq $Red -and $pixel.G -eq $Green -and $pixel.B -eq $Green
})
} finally { $graphics.Dispose() }
} finally { $bitmap.Dispose() }
}
$keyboard=New-Object -ComObject WScript.Shell
[void](Wait-Until { $keyboard.AppActivate($process.Id) })
$keyboard.SendKeys('+{F4}')
$open=Wait-Until { Find-Window '#32770' $process.Id 461 }
Assert-DialogSurface $open 192 192
Post $open 0x111 1
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
$title=[Text.StringBuilder]::new(1024)
[void][SearchArrowTest]::GetText($editor,0xD,$title.Capacity,$title)
if ($title.ToString() -notmatch '(New_File_[0-9-]+_[0-9.]+\.txt)$') { throw "Missing generated name in $title." }
$generated=$Matches[1]
if (Test-Path -LiteralPath (Join-Path $scratch $generated)) { throw 'Opening a draft created a file.' }
$control=Wait-Until { [SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[NullString]::Value) }
Start-Sleep -Milliseconds 150
if (![SearchArrowTest]::EditorMenuProbe($editor,$true)) { throw 'Cannot mark the editor menu for the repaint check.' }
foreach($ch in 'First'.ToCharArray()){Post $control 0x102 ([int]$ch)}
Post $control 0x100 13
foreach($ch in 'Second'.ToCharArray()){Post $control 0x102 ([int]$ch)}
[void](Wait-Until { [SearchArrowTest]::Send($control,2159,0,0).ToInt64() })
Start-Sleep -Milliseconds 150
$menuWasPreserved=[SearchArrowTest]::EditorMenuProbe($editor,$false)
[void][SearchArrowTest]::InvalidateRect($editor,0,$false)
if (!$menuWasPreserved) { throw 'Typing in a draft repainted the unchanged editor menu.' }
foreach($cancel in $true,$false) {
Post $control 0x100 27
$confirm=Wait-Until { Find-Window '#32770' $process.Id 6 }
Assert-DialogSurface $confirm 128 0
Post $confirm 0x111 6
$save=Wait-Until { Find-Window '#32770' $process.Id 464 }
Assert-DialogSurface $save 192 192
$name=[SearchArrowTest]::GetDlgItem($save,461)
$current=[Text.StringBuilder]::new(1024)
[void][SearchArrowTest]::GetText($name,0xD,$current.Capacity,$current)
if ($current.ToString() -ne $generated) { throw 'Save options did not carry the generated name.' }
if ($cancel) {
Post $save 0x111 2
[void](Wait-Until { ![SearchArrowTest]::IsWindow($save) -and [SearchArrowTest]::IsWindow($editor) })
continue
}
[void][SearchArrowTest]::SendText($name,0x0C,0,'created.txt')
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,464),0xF1,1,0)
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,472),0xF5,0,0)
Post $save 0x111 1
}
$result=Join-Path $scratch 'created.txt'
[void](Wait-Until { (Test-Path -LiteralPath $result) -and ![SearchArrowTest]::IsWindow($editor) })
if ([Convert]::ToHexString([IO.File]::ReadAllBytes($result)) -ne 'EFBBBF46697273740A5365636F6E64') {
throw 'The saved bytes must contain a UTF-8 BOM and LF line endings.'
}
Write-Output 'Verified Shift+F4, the generated name, Escape confirmation, cancellation, and Save options.'
return
}
if (!$KeyboardCursorOnly) {
$leftPath = [SearchArrowTest]::GetDlgItem($main,142)
foreach ($step in @(@{ Row='[Right fixture]'; Path=$rightFixture }, @{ Row='..'; Path=$scratch })) {
Select-Row $leftPanel $step.Row
Start-Sleep -Milliseconds 150
$lineCount = @(Get-Content -LiteralPath $paintTrace).Count
Post $leftPanel 0x100 13
[void](Wait-Until {
$path = [Text.StringBuilder]::new(1024)
[void][SearchArrowTest]::GetText($leftPath,0xD,$path.Capacity,$path)
$path.ToString() -eq $step.Path
})
[void](Wait-Until {
$highlight = Read-PanelHighlights $paintTrace $lineCount
@($highlight.Keys -like '0/*').Count -gt 0
})
Start-Sleep -Milliseconds 150
$draws = (Read-PanelHighlights $paintTrace $lineCount).Keys
if ($draws -like '1/*') { throw "Opening $($step.Row) repainted rows in the other panel." }
}
Write-Output 'Verified folder navigation repaints only the panel that changes directories.'
}
$clicks=if(!$KeyboardCursorOnly){
@(@{Panel=$leftPanel; Index=0},
@{Panel=$rightPanel; Index=1; Label='A.txt'},
@{Panel=$leftPanel; Index=0; Label='A.txt'},
@{Panel=$rightPanel; Index=1; Label='..'; UnfocusedStyle=$true},
@{Panel=$rightPanel; Index=1; Label='A.txt'})
}
$activeIndex=0
foreach($check in $clicks) {
$before=[SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32()
$top=[SearchArrowTest]::Send($check.Panel,0x18E,0,0).ToInt32()
$row=if($before -eq $top){$top+1}else{$top}
$row=if($check.Label){[SearchArrowTest]::SendText($check.Panel,0x1A2,-1,$check.Label).ToInt32()}
elseif($before -eq $top){$top+1}else{$top}
if($row -lt 0 -or $row -eq $before){throw 'The click fixture must move the cursor.'}
$previousKey="$($check.Index)/$before"
$expected=@{"$($check.Index)/$row"='1'}
if($check.Index -ne $activeIndex){
$source=if($activeIndex -eq 0){$leftPanel}else{$rightPanel}
$sourceRow=[SearchArrowTest]::Send($source,0x188,0,0).ToInt32()
$expected["$activeIndex/$sourceRow"]='0'
}
if($check.Index -eq $activeIndex -or $check.UnfocusedStyle){$expected[$previousKey]='0'}
[void](Wait-Until { Test-Path -LiteralPath $paintTrace })
Start-Sleep -Milliseconds 150
$lineCount=@(Get-Content -LiteralPath $paintTrace).Count
@@ -276,14 +402,15 @@ try {
[void](Wait-Until { [SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32() -eq $row })
Start-Sleep -Milliseconds 150
$highlight=Read-PanelHighlights $paintTrace $lineCount
$draws=@($highlight.Keys)
if("$($check.Index)/$row" -notin $draws -or $draws.Count -gt 3){
throw "Clicking a row repainted unrelated file rows. Drawn rows: $draws"
if($highlight.Count -ne $expected.Count -or
@($expected.Keys | Where-Object {$highlight[$_] -ne $expected[$_]}).Count){
throw "Unexpected cursor redraw. Expected rows: $($expected.Keys -join ', '). Drawn rows: $($highlight.Keys -join ', ')."
}
if($highlight["$($check.Index)/$row"] -ne '1' -or
($before -ge $top -and $highlight["$($check.Index)/$before"] -ne '0')){
throw 'The new row must be painted active and the previous visible row must lose its highlight.'
if($check.Index -ne $activeIndex -and (Get-Content -LiteralPath $paintTrace | Select-Object -Skip $lineCount |
Where-Object {$_ -match "^\d+ panel-draw $($check.Index) $before 1 "})){
throw 'The old row in the destination panel flashed as the active cursor.'
}
$activeIndex=$check.Index
}
if($clicks){Write-Output 'Verified file clicks repaint only cursor rows in the active pane and when changing panes.'}
Post $main 0x111 132
@@ -319,22 +446,7 @@ try {
Post $commandMenu 0x100 27
[void](Wait-Until { ![SearchArrowTest]::IsWindowVisible($commandMenu) })
Write-Output 'Verified Commands grouping, arrow navigation, and inert separators.'
$panel = Wait-Until { $handle = [SearchArrowTest]::GetDlgItem($main,102); if ($handle -ne [IntPtr]::Zero) { $handle } }
$pathControl = [SearchArrowTest]::GetDlgItem($main,142)
$pathText = [Text.StringBuilder]::new(1024)
[void][SearchArrowTest]::GetText($pathControl,0xD,$pathText.Capacity,$pathText)
$path=$pathText.ToString()
if ([IO.Path]::GetPathRoot($path) -ne [IO.Path]::GetPathRoot($scratch)) {
throw 'Select a local left-panel folder on the test executable drive before running this interactive test.'
}
foreach ($component in $path.Substring(3).Split('\',[System.StringSplitOptions]::RemoveEmptyEntries)) {
Select-Row $panel '..'
[void][SearchArrowTest]::Send($panel,0x100,13,0)
}
foreach ($component in $scratch.Substring(3).Split('\')) {
Select-Row $panel "[$component]"
[void][SearchArrowTest]::Send($panel,0x100,13,0)
}
$panel = $leftPanel
$fixtureRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,([IO.Path]::GetFileName($fixture))).ToInt32()
Click-PanelRow $panel $fixtureRow
[void](Wait-Until { [SearchArrowTest]::Send($panel,0x188,0,0).ToInt32() -eq $fixtureRow })
@@ -421,10 +533,10 @@ try {
if (!(Test-Path -LiteralPath (Join-Path $scratch $newFolder) -PathType Container)) {
throw 'F7 did not create the folder in the active panel.'
}
$newRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,"[$newFolder]")
if ($newRow.ToInt64() -lt 0 -or [SearchArrowTest]::Send($panel,0x188,0,0) -ne $newRow) {
throw 'F7 did not select the new folder.'
}
[void](Wait-Until {
$newRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,"[$newFolder]")
$newRow.ToInt64() -ge 0 -and [SearchArrowTest]::Send($panel,0x188,0,0) -eq $newRow
})
Post $main 0x111 115
$makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 }
$nameField=[SearchArrowTest]::GetDlgItem($makeDialog,361)
@@ -526,6 +638,10 @@ try {
!(Test-Path -LiteralPath (Join-Path $linkPath 'link-target.txt') -PathType Leaf)) {
throw "F7 did not create a $expected pointing to Alpha."
}
[void](Wait-Until {
$linkRow = [SearchArrowTest]::SendText($panel,0x1A2,-1,"[$linkName]")
$linkRow.ToInt64() -ge 0 -and [SearchArrowTest]::Send($panel,0x188,0,0) -eq $linkRow
})
}
Write-Output 'Verified F7 history, quoted batch names, and directory link handling.'
Select-Row $panel ([IO.Path]::GetFileName($fixture))
@@ -649,6 +765,7 @@ try {
} finally { $bitmap.Dispose() }
}
Select-Row $panel ([IO.Path]::GetFileName($fixture))
Post $panel 0x100 0x73
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
$firstControl=[SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[System.Management.Automation.Language.NullString]::Value)
@@ -684,8 +801,8 @@ try {
if ([SearchArrowTest]::GetWindow($otherEditor,4) -ne [IntPtr]::Zero) { throw 'The second editor is owned.' }
$editorIdentity=[SearchArrowTest]::TaskbarIdentity($editor)
$otherIdentity=[SearchArrowTest]::TaskbarIdentity($otherEditor)
if (!$editorIdentity -or !$otherIdentity -or $editorIdentity -eq $otherIdentity) {
throw 'Editor windows do not have distinct Windows taskbar identities.'
if ($editorIdentity -cne 'HrynCo.KSwitcher.Files.Editor' -or $otherIdentity -cne $editorIdentity) {
throw 'Both editor windows must use the Editor group on the Windows taskbar.'
}
Post $otherEditor 0x10 0
[void](Wait-Until { ![SearchArrowTest]::IsWindow($otherEditor) })
+40
View File
@@ -8,6 +8,8 @@
namespace fs = std::filesystem;
using ks::files::TextDocument;
using ks::files::TextEncoding;
using ks::files::TextLineEnding;
namespace
{
@@ -141,6 +143,43 @@ void sparseFile(const fs::path &file)
document.stage(index, "edited");
check(document.readPage(index) == "edited", "Stage an edit past 4 GiB");
}
void saveDraft(const fs::path &file)
{
TextDocument draft({});
check(draft.readPage(0).empty() && draft.pages()==1, "Start with an empty draft");
draft.stage(0,"one\r\ntwo\rthree\n");
writeFile(file,"existing");
bool rejected{};
try {draft.saveNew(file,{});}
catch(const std::exception &) {rejected=true;}
check(rejected && draft.modified() && readFile(file)=="existing", "Preserve a conflicting file and the draft");
fs::remove(file);
check(draft.saveNew(file,{TextEncoding::utf8,true,TextLineEnding::lf}), "Save a draft as a new file");
check(readFile(file)=="\xef\xbb\xbfone\ntwo\nthree\n" && draft.readPage(0)=="one\ntwo\nthree\n",
"Save a UTF-8 signature and normalize mixed line endings");
draft.stage(0,"after");
check(draft.save() && readFile(file)=="\xef\xbb\xbf" "after", "Edit normally after the first save");
const auto ansiFile=file.parent_path()/L"windows1252.txt";
TextDocument ansiDraft({});
ansiDraft.stage(0,"caf\xc3\xa9\n");
check(ansiDraft.saveNew(ansiFile,{TextEncoding::windows1252,false,TextLineEnding::crlf}),
"Save a draft in Windows-1252");
check(readFile(ansiFile)=="caf\xe9\r\n" && ansiDraft.readPage(0)=="caf\xc3\xa9\r\n",
"Round-trip Windows-1252 text and CRLF");
TextDocument ansiReader(ansiFile,false,TextEncoding::windows1252);
check(ansiReader.readPage(0)=="caf\xc3\xa9\r\n", "Open an existing file with an explicit code page");
const auto unicodeFile=file.parent_path()/L"utf16be.txt";
TextDocument unicodeDraft({});
unicodeDraft.stage(0,"a\n");
check(unicodeDraft.saveNew(unicodeFile,{TextEncoding::utf16be,true,TextLineEnding::cr}),
"Save a UTF-16 draft with a signature");
TextDocument unicodeReader(unicodeFile,false);
check(readFile(unicodeFile)==std::string("\xfe\xff\0a\0\r",6) && unicodeReader.readPage(0)=="a\r",
"Detect the UTF-16 signature and read CR line endings");
}
}
int main()
@@ -151,6 +190,7 @@ int main()
editsAcrossPages(fixture.directory / L"pages.txt");
unicodeBoundaries(fixture.directory / L"unicode.txt");
rejectExternalReplacement(fixture.directory / L"external.txt");
saveDraft(fixture.directory / L"created.txt");
sparseFile(fixture.directory / L"5gib.log");
std::cout << "Files text document regressions passed.\n";
}
+23
View File
@@ -1,5 +1,6 @@
#include "lan.h"
#include "lan_pairing.h"
#include "lan_wake.h"
#include <iostream>
#include <tlhelp32.h>
@@ -29,6 +30,15 @@ int main(int argc,char **argv)
check(identifier(randomHex(16)),"cryptographic instance ID");
check(mac("key","The quick brown fox jumps over the lazy dog")=="f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", "HMAC SHA256 known vector");
check(equal("abc","abc")&&!equal("abc","abd")&&!equal("abc","ab"),"proof comparison");
const auto magic=wakePacket("02468ace1357");
const std::array<unsigned char,6> hardwareAddress{0x02,0x46,0x8a,0xce,0x13,0x57};
check(magic && std::all_of(magic->begin(),magic->begin()+6,[](auto byte){return byte==0xff;}),
"Wake-on-LAN synchronization bytes");
for(size_t repeat=0;repeat<16;++repeat)
check(std::equal(hardwareAddress.begin(),hardwareAddress.end(),magic->begin()+6*(repeat+1)),
"Wake-on-LAN repeats the target MAC address");
check(!wakePacket("ffffffffffff") && !wakePacket("000000000000") &&
!wakePacket("023456789abx") && !wakePacket("023456789ab"),"invalid Wake-on-LAN addresses rejected");
Pairing left(a,b,code,100),right(b,a,code,100),wrong(b,a,std::string(32,'f'),100);
check(wrong.receive(left.offer(),101).empty(),"different code cannot acknowledge");
auto forged=left.offer();forged["id"]=c;
@@ -118,6 +128,19 @@ int main(int argc,char **argv)
check(request(restored,{{"action","status"}})["peers"].empty(),"forget removes offline pair");
check(!request(restored,{{"action","status"}}).at("shareInput").get<bool>(),"forgetting the input peer revokes persisted input permission");
}
{
const auto folder=root/L"wake";
std::filesystem::create_directory(folder);
const auto saved=Json{{"version",1},{"id",a},{"enabled",true},{"trusted",{
{b,{{"name","Wake peer"},{"key",left.derived},{"wakeMac","02468ace1357"}}},
{c,{{"name","Legacy peer"},{"key",left.derived}}}}}}.dump();
atomicWrite(folder/L"lan-pairing.bin",protect(Bytes(saved.begin(),saved.end())));
LanService restored(folder);
const auto peers=request(restored,{{"action","filesPeers"}}).at("peers");
check(peers.size()==2 && peers[0].at("id")==b && peers[0].at("address")=="" &&
peers[1].at("id")==c,"offline PCs remain selectable in Files with or without a saved MAC address");
check(peers.dump().find("02468ace1357")==std::string::npos,"Files snapshot omits the stored MAC address");
}
if(argc>1&&std::string(argv[1])=="--network")
{
auto saved=Json::parse(unprotect(readFile(root/L"lan-pairing.bin",256*1024)));
+31
View File
@@ -30,6 +30,37 @@ int main(){try{
check(b.deliveries.size()==1&&c.deliveries.size()==1,"all paired instances receive exactly once despite loss/duplicates");
check(b.deliveries[0].bytes==payload&&c.deliveries[0].bytes==payload,"binary clipboard survives retransmission");
check(b.deliveries[0].sequence==123&&b.deliveries[0].app=="editor.exe","capture sequence and origin retained");
{
ClipboardExchange sender(aid),receiver(bid);
sender.peerSession(bid,receiver.session());
receiver.peerSession(aid,sender.session());
const Bytes large(480*90+7,42);
sender.queue({bid},large,"no loss",1);
size_t emitted=0;
const auto deliver=[&](const std::string &to,const Json &packet) {
++emitted;
packets.emplace_back(to,packet);
};
for(uint64_t now=2;now<300 && receiver.deliveries.empty();++now)
{
sender.poll(trusted,now,deliver);
// Interleave ACKs and sender polls while part of the current window is still in flight.
if(!packets.empty())
{
auto packet=std::move(packets.front().second);
packets.pop_front();
receiver.receive(aid,key,packet,now,321,ack);
}
while(!acks.empty())
{
auto packet=std::move(acks.front().second);
acks.pop_front();
sender.receive(bid,key,packet,now,321,deliver);
}
}
check(receiver.deliveries.size()==1 && receiver.deliveries.front().bytes==large,"sliding window delivers without loss");
check(emitted==92,"ACK advancement sends each chunk once without retransmitting in-flight slots");
}
b.receive(aid,key,firstPacket,10000,123,ack);
check(acks.empty(),"authenticated old packet replay is ignored");
ClipboardExchange restarted(bid);restarted.peerSession(aid,a.session());
+47
View File
@@ -1,11 +1,27 @@
#include "ocr.h"
#include "app.h"
#include <algorithm>
#include <set>
#include <tlhelp32.h>
#include <iostream>
namespace ks {
struct InputRegressionAccess {
static void scheduleOcr(App &app) { app.scheduleHistoryOcr(app.settings); }
};
}
std::set<DWORD> historyImageHelpers()
{
const auto snapshot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if(snapshot==INVALID_HANDLE_VALUE) throw std::runtime_error("Cannot enumerate OCR fixtures");
struct Cleanup {HANDLE handle;~Cleanup(){CloseHandle(handle);}} cleanup{snapshot};
std::set<DWORD> children;
PROCESSENTRY32W entry{sizeof(entry)};
for(auto ok=Process32FirstW(snapshot,&entry);ok;ok=Process32NextW(snapshot,&entry))
if(entry.th32ParentProcessID==GetCurrentProcessId() && lstrcmpiW(entry.szExeFile,L"KSwitcher.Screenshot.exe")==0)
children.insert(entry.th32ProcessID);
return children;
}
int main(int argc, char **argv)
{
const bool tesseract = argc == 2 && std::string(argv[1]) == "--tesseract";
@@ -52,6 +68,16 @@ int main(int argc, char **argv)
throw std::runtime_error("OCR fixture was not recognized");
if (tesseract && ks::lower(text).find(L"привіт") == std::wstring::npos)
throw std::runtime_error("Ukrainian OCR fixture was not recognized");
if (!tesseract)
{
constexpr UINT width=20000;
ks::Pixels wideFixture{width,pixels.height,ks::Bytes(size_t(width)*pixels.height*4,255)};
for(UINT y=0;y<pixels.height;++y)
std::copy_n(pixels.bgra.data()+size_t(y)*pixels.width*4,pixels.width*4,
wideFixture.bgra.data()+size_t(y)*width*4);
if(ks::upper(ks::recognizeText(ks::Clip{{ks::imageDib(wideFixture)}},config)).find(L"HELLO")==std::wstring::npos)
throw std::runtime_error("OCR did not recognize the downscaled wide image");
}
auto temp = std::filesystem::temp_directory_path() / (L"KSwitcher-auto-ocr-" + std::to_wstring(GetCurrentProcessId()));
auto sequence = GetClipboardSequenceNumber();
{
@@ -61,6 +87,16 @@ int main(int argc, char **argv)
auto id = app.history->entries().front().id;
auto isolated = app.history->recognizeImage(id, config);
if (isolated != text) throw std::runtime_error("Helper and in-process OCR results differ");
const auto recognitionWorker=historyImageHelpers();
if(recognitionWorker.size()!=1 || app.history->recognizeImage(id,config)!=text ||
historyImageHelpers()!=recognitionWorker)
throw std::runtime_error("Successive history requests did not reuse the OCR process");
const auto thumbnail=app.history->thumbnail(id);
const auto previewWorkers=historyImageHelpers();
const auto repeated=app.history->thumbnail(id);
if(previewWorkers.size()!=2 || historyImageHelpers()!=previewWorkers ||
thumbnail.width!=repeated.width || thumbnail.height!=repeated.height || thumbnail.bgra!=repeated.bgra)
throw std::runtime_error("Successive thumbnail requests did not reuse the independent preview worker");
bool cancelled = false;
try { app.history->recognizeImage(id, config, [] { return true; }); }
catch (const std::exception &) { cancelled = true; }
@@ -71,6 +107,16 @@ int main(int argc, char **argv)
bool failed = false;
try { app.history->recognizeImage(id, invalid); }
catch (const std::exception &) { failed = true; }
if(historyImageHelpers()!=previewWorkers || app.history->recognizeImage(id,config)!=text)
throw std::runtime_error("An OCR job error ended the reusable helper");
const auto child=OpenProcess(PROCESS_TERMINATE|SYNCHRONIZE,FALSE,*recognitionWorker.begin());
if(!child) throw std::runtime_error("Cannot open OCR crash fixture");
const auto terminated=TerminateProcess(child,ERROR_PROCESS_ABORTED) &&
WaitForSingleObject(child,5000)==WAIT_OBJECT_0;
CloseHandle(child);
if(!terminated || app.history->recognizeImage(id,config)!=text || historyImageHelpers()==previewWorkers)
throw std::runtime_error("History OCR did not restart its exited helper");
std::cout << "PASS OCR and thumbnail process reuse and restart after worker exit\n";
if (!failed || app.history->entries().front().ocrState != 1)
throw std::runtime_error("Failed helper modified history metadata");
for (const auto &file : std::filesystem::directory_iterator(temp / L"history"))
@@ -98,6 +144,7 @@ int main(int argc, char **argv)
throw std::runtime_error("Background OCR changed the clipboard");
std::cout << "PASS automatic background OCR, persisted search and unchanged clipboard\n";
}
if(!historyImageHelpers().empty()) throw std::runtime_error("Closing history left OCR workers running");
std::filesystem::remove_all(temp);
std::cout << (tesseract ? "PASS optional Tesseract, mixed Ukrainian/English and cache migration\n" :
"PASS native Windows OCR, DIB decoding and async result retrieval\n");
+85 -1
View File
@@ -531,7 +531,7 @@ int main(int argc, char **argv)
auto dib=ks::screenshotClip(cursorPreview.dc,784,448,{}).formats[0].data;
BITMAPFILEHEADER bmp{}; bmp.bfType=0x4d42; bmp.bfOffBits=sizeof(bmp)+sizeof(BITMAPINFOHEADER); bmp.bfSize=DWORD(sizeof(bmp)+dib.size());
ks::Bytes preview(sizeof(bmp)); memcpy(preview.data(),&bmp,sizeof(bmp)); preview.insert(preview.end(),dib.begin(),dib.end());
ks::atomicWrite(L"build/cursor-preview.bmp",preview);
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"cursor-preview.bmp",preview);
for(int tool:{27,26,21,10,11,22,23,24,25,19}) {
SendMessageW(window,WM_COMMAND,tool,0);
HCURSOR expected=nullptr;
@@ -806,6 +806,90 @@ int main(int argc, char **argv)
require(IsWindow(window),"Escape does not close the screenshot editor");
SendMessageW(window,WM_CLOSE,0,0);
require(!IsWindow(window),"copied screenshot closes without confirmation");
{
ks::Capture cached(app);
constexpr int imageWidth=400,imageHeight=240;
cached.image=std::make_unique<ks::Surface>(imageWidth,imageHeight);
PatBlt(cached.image->dc,0,0,imageWidth,imageHeight,WHITENESS);
cached.end={imageWidth,imageHeight};
const auto editor=CreateWindowW(cls.lpszClassName,L"Cached marks test",WS_POPUP,0,0,imageWidth,imageHeight,
app.window,nullptr,app.instance,&cached);
require(editor,"cached marks test window");
ks::edit(editor,cached);
cached.marks.push_back({{50,50},{50,50},1});
const auto paint=[&] {InvalidateRect(editor,nullptr,FALSE);UpdateWindow(editor);};
paint();
require(cached.rendered && cached.renderedMarksValid,"paint caches committed marks");
SetPixelV(cached.rendered->dc,0,0,RGB(19,23,27));
paint();
require(GetPixel(cached.rendered->dc,0,0)==RGB(19,23,27),"unchanged paint reuses the marked surface");
cached.remember(cached.marks);
cached.marks.front().color=RGB(0,128,255);
paint();
require(GetPixel(cached.rendered->dc,0,0)==RGB(255,255,255),"mark edit rebuilds the cached surface");
SetPixelV(cached.rendered->dc,0,0,RGB(19,23,27));
SendMessageW(editor,WM_COMMAND,12,0);
paint();
require(GetPixel(cached.rendered->dc,0,0)==RGB(255,255,255),"undo rebuilds the cached surface");
ks::Mark highlight{{10,48},{180,52},0};
highlight.points={{10,48},{54,50},{92,52}};
highlight.thickness=9;
cached.marks.push_back(std::move(highlight));
cached.renderedMarksValid=false;
paint();
cached.selected=0;
cached.dragging=true;
cached.part=ks::MarkPart::Body;
cached.original=cached.marks.front();
cached.start={50,50};
SetPixelV(cached.rendered->dc,0,0,RGB(19,23,27));
const int mouseX=cached.view.left+MulDiv(70,cached.view.right-cached.view.left,imageWidth);
const int mouseY=cached.view.top+MulDiv(50,cached.view.bottom-cached.view.top,imageHeight);
SendMessageW(editor,WM_MOUSEMOVE,MK_LBUTTON,MAKELPARAM(mouseX,mouseY));
RECT update{};
require(GetUpdateRect(editor,&update,FALSE) && update.right-update.left<cached.view.right-cached.view.left,
"drag invalidates a portion of the image");
UpdateWindow(editor);
require(GetPixel(cached.rendered->dc,0,0)==RGB(19,23,27),"drag preserves pixels outside the damaged area");
ks::Surface reference(imageWidth,imageHeight);
PatBlt(reference.dc,0,0,imageWidth,imageHeight,WHITENESS);
ks::drawMarks(reference.dc,cached.marks);
GdiFlush();
const auto *expected=static_cast<const unsigned char *>(reference.pixels);
const auto *actual=static_cast<const unsigned char *>(cached.rendered->pixels);
for(size_t pixel=1;pixel<imageWidth*imageHeight;++pixel)
require(std::equal(expected+pixel*4,expected+pixel*4+3,actual+pixel*4),
"damaged raster matches a full repaint");
cached.dragging=false;
cached.copied=true;
DestroyWindow(editor);
}
{
ks::Capture selection(app);
selection.image=std::make_unique<ks::Surface>(100,100);
selection.dimmed=std::make_unique<ks::Surface>(100,100);
selection.frame=std::make_unique<ks::Surface>(100,100);
PatBlt(selection.image->dc,0,0,100,100,WHITENESS);
PatBlt(selection.dimmed->dc,0,0,100,100,BLACKNESS);
auto overlay=CreateWindowW(cls.lpszClassName,L"Selection repaint test",WS_POPUP,0,0,100,100,
app.window,nullptr,app.instance,&selection);
require(overlay,"selection repaint window");
ShowWindow(overlay,SW_SHOWNOACTIVATE);
UpdateWindow(overlay);
selection.dragging=true;
selection.start=selection.end={10,10};
SendMessageW(overlay,WM_MOUSEMOVE,MK_LBUTTON,MAKELPARAM(70,70));
UpdateWindow(overlay);
require(GetPixel(selection.frame->dc,55,55)==RGB(255,255,255),"drag reveals undimmed selection");
SendMessageW(overlay,WM_MOUSEMOVE,MK_LBUTTON,MAKELPARAM(40,40));
RECT dirty{};
require(GetUpdateRect(overlay,&dirty,FALSE) && dirty.left==10 && dirty.top==10 &&
dirty.right==70 && dirty.bottom==70,"drag invalidates old and new selection bounds");
UpdateWindow(overlay);
require(GetPixel(selection.frame->dc,55,55)==RGB(0,0,0) &&
GetPixel(selection.frame->dc,20,20)==RGB(255,255,255),"shrinking selection restores its old background");
DestroyWindow(overlay);
}
static bool published=false;
static bool notificationAccepted=false;
static HWND notificationWindow{};
+28 -3
View File
@@ -399,6 +399,25 @@ int main(int argc, char **argv)
require(!supplemental.suggest(L"релызик ", 1, layouts, options),
"never-correct list takes precedence over personal word");
options.autoNever.clear();
options.autoWords[L"en"] = {L"test-mt", L"dev-mt"};
auto hyphenated = supplemental.suggest(L"Еуые-ье ", 1, layouts, options);
require(hyphenated && hyphenated->text == L"Test-mt " && hyphenated->target == 0,
"hyphenated personal word corrects from the wrong layout");
options.autoMinLength = 2;
require(!supplemental.suggest(L"ЙФ ", 2, layouts, options),
"uppercase layout correction requires a personal dictionary entry");
options.autoWords[L"en"].push_back(L"qa");
auto acronym = supplemental.suggest(L"(ЙФ)! ", 2, layouts, options);
require(acronym && acronym->text == L"(QA)! " && acronym->target == 0,
"uppercase personal acronym corrects without changing case or punctuation");
require(!supplemental.suggest(L"йФ ", 2, layouts, options),
"mixed-case personal words remain protected");
auto uppercaseHyphenated = supplemental.suggest(L"ЕУЫЕ-ЬЕ ", 1, layouts, options);
require(uppercaseHyphenated && uppercaseHyphenated->text == L"TEST-MT ",
"uppercase hyphenated personal words correct without changing case");
options.autoMinLength = 3;
require(!supplemental.suggest(L"ЙФ ", 2, layouts, options),
"uppercase personal words respect minimum length");
options.autoWords[L"uk"].push_back(L"робить");
auto commaWord = supplemental.suggest(L"hj,bnm ", 0, layouts, options);
require(commaWord && commaWord->text == L"робить " && commaWord->target == 2,
@@ -739,7 +758,7 @@ int main(int argc, char **argv)
settings.autoPrefixChars = L"(#";
settings.autoSuffixChars = L");%";
settings.autoNever = {L"myWord"};
settings.autoWords = {{L"uk", {L"релізик"}}, {L"en", {L"kswitcher"}}};
settings.autoWords = {{L"uk", {L"релізик"}}, {L"en", {L"kswitcher", L"test-mt", L"dev-mt"}}};
settings.autoExcluded = {L"Code.exe"};
settings.cycle = {L"en", L"uk"};
settings.snippets = {{L";address", L"Line 1\r\n{cursor}Line 2"}};
@@ -765,13 +784,19 @@ int main(int argc, char **argv)
auto invalidWords = settings;
invalidWords.autoWords[L"uk"] = {L"hello"};
rejects([&] { ks::validateSettings(invalidWords); }, "personal dictionary rejects wrong language letters");
for (const auto *word : {L"-test", L"test-", L"test--mt", L"test-і"})
{
invalidWords = settings;
invalidWords.autoWords[L"en"] = {word};
rejects([&] { ks::validateSettings(invalidWords); }, "personal dictionary rejects malformed hyphenated words");
}
require(ks::encodeSettings(ks::decodeSettings(ks::encodeSettings(settings), {})) == ks::encodeSettings(settings),
"configurator snapshot survives serialization without changing the concurrency token");
rejects([&] { ks::decodeSettings(ks::Bytes{'{', '}'}, {}); },
"configurator rejects missing settings format");
require(!restored.writeLog, "logging setting persists when disabled");
require(ks::loadSettings(temp / L"defaults.json", {}).writeLog,
"logging defaults on for existing diagnostic installations");
require(!ks::loadSettings(temp / L"defaults.json", {}).writeLog,
"logging defaults off until explicitly enabled");
require(restored.snippets[0].text == settings.snippets[0].text, "settings snippet roundtrip");
require(restored.cycle == settings.cycle, "layout order roundtrip");
require(restored.elevatedAutostart, "elevated autostart setting roundtrip");
+45 -4
View File
@@ -1,8 +1,50 @@
"""Regenerate the native multi-resolution icon (development only; requires Pillow)."""
"""Regenerate the native multi-resolution icons (development only; requires Pillow)."""
from argparse import ArgumentParser
from pathlib import Path
from PIL import Image, ImageDraw
root = Path(__file__).resolve().parents[1] / 'resources'
icon_sizes = [(size, size) for size in (16, 20, 24, 32, 40, 48, 64, 128, 256)]
def draw_files_icon(size):
image = Image.new('RGBA', (size, size))
draw = ImageDraw.Draw(image)
def block(left, top, right, bottom, color):
scale = size / 32
draw.rectangle((round(left * scale), round(top * scale),
round(right * scale) - 1, round(bottom * scale) - 1), fill=color)
# Draw each size on its own pixel grid so the pane divider stays sharp.
frame = '#3DDDEB'
panel = '#101E89'
block(2, 2, 30, 30, '#10163D')
block(2, 2, 30, 26, frame)
block(4, 4, 28, 24, panel)
divider = max(1, round(size / 16))
center = size // 2 - divider // 2
draw.rectangle((center, round(size / 8), center + divider - 1, round(size * 3 / 4) - 1), fill=frame)
block(6, 6, 12, 8, '#FFE368')
block(19, 6, 25, 8, '#FFE368')
for y in (10, 18, 22):
block(6, y, 12, y + 2, frame)
for y, end in ((10, 26), (14, 24), (18, 26)):
block(19, y, end, y + 2, frame)
block(4, 14, 15, 16, '#5EEAD4')
for left in (4, 10, 16, 22):
block(left, 28, left + 4, 30, '#1AA3AD')
return image
parser = ArgumentParser(description=__doc__)
parser.add_argument('--files-only', action='store_true', help='Regenerate only the main Files icon.')
args = parser.parse_args()
frames = [draw_files_icon(size) for size, _ in icon_sizes]
frames[-1].save(root / 'kswitcher-files.ico', sizes=icon_sizes, append_images=frames[:-1])
if args.files_only:
raise SystemExit
# Geometric K: white stem/upper arm, mint lower arm on an indigo keycap.
polygons = [('#FFFFFF', [(8, 7), (12, 7), (12, 25), (8, 25)]),
('#FFFFFF', [(11, 15), (22, 6), (25, 9), (14, 18)]),
@@ -20,7 +62,7 @@ for color, points in polygons:
draw.polygon([(x*scale,y*scale) for x,y in points], fill=color)
im = im.resize((256,256),Image.Resampling.LANCZOS)
im.save(root / 'kswitcher.png')
im.save(root / 'kswitcher.ico', sizes=[(s,s) for s in (16,20,24,32,40,48,64,128,256)])
im.save(root / 'kswitcher.ico', sizes=icon_sizes)
for mode, color in [('editor', '#4F46E5'), ('viewer', '#087C73')]:
image = Image.new('RGBA', (32*scale, 32*scale))
@@ -35,5 +77,4 @@ for mode, color in [('editor', '#4F46E5'), ('viewer', '#087C73')]:
[(5, 16), (8, 12), (12, 9), (16, 8), (20, 9), (24, 12),
(27, 16), (24, 20), (20, 23), (16, 24), (12, 23), (8, 20)]], fill='white')
draw.ellipse((12*scale, 12*scale, 20*scale, 20*scale), fill=color)
image.resize((256, 256), Image.Resampling.LANCZOS).save(root / f'kswitcher-files-{mode}.ico',
sizes=[(s, s) for s in (16, 20, 24, 32, 40, 48, 64, 128, 256)])
image.resize((256, 256), Image.Resampling.LANCZOS).save(root / f'kswitcher-files-{mode}.ico', sizes=icon_sizes)
@@ -0,0 +1,159 @@
param(
[Parameter(Mandatory)][string]$DocumentationCheckout,
[string]$Output = "$PSScriptRoot/../src/files_windows_command_catalog.h"
)
$ErrorActionPreference = 'Stop'
$docs = Join-Path $DocumentationCheckout 'WindowsServerDocs/administration/windows-commands'
$revision = git -C $DocumentationCheckout rev-parse HEAD
if ($LASTEXITCODE) { throw 'Could not determine the documentation revision.' }
$index = Get-Content -LiteralPath (Join-Path $docs 'windows-commands.md') -Raw
$entries = @{}
$articles = @{}
function Add-Entry([string]$Name) {
if (!$entries.ContainsKey($Name)) {
$entries[$Name] = [Collections.Generic.SortedSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
}
}
function Add-CommandPath([string]$Name, [string]$Article) {
Add-Entry $Name
if (!$articles.ContainsKey($Name)) { $articles[$Name] = $Article }
$words = $Name.Split(' ')
for ($i = 1; $i -lt $words.Count; ++$i) {
$parent = $words[0..($i - 1)] -join ' '
Add-Entry $parent
[void]$entries[$parent].Add($words[$i])
}
}
function Add-Options([string]$Name, [string]$Field) {
$field = $Field -replace '<[^<>\r\n]*>', ''
foreach ($option in [regex]::Matches($field, $switch)) {
[void]$entries[$Name].Add($option.Groups['flag'].Value)
}
}
# Only extract literal command names and options. Ignore prose, examples and placeholders.
$links = [regex]::Matches($index, '(?m)^\s*- \[`(?<name>[\w.-]+(?: [\w.-]+)*)`\]\((?:\./)?(?<file>[\w.-]+\.md)\)')
$switch = '(?i)(?:^|[\s\[\{|,`*])(?<flag>[-/+][a-z0-9?][a-z0-9?-]*(?::[a-z0-9]+|[:=])?|[a-z][a-z0-9-]*=)(?=$|[\s\[\]{}|,<>=)`*])'
$documents = @{}
foreach ($link in $links) {
$name = ($link.Groups['name'].Value.ToLowerInvariant() -replace '\.exe(?= |$)', '')
$documents[$name] = $link.Groups['file'].Value
}
foreach ($name in @($documents.Keys)) {
if ($name.Contains(' ')) { continue }
$file = Join-Path $docs $documents[$name]
if (!(Test-Path -LiteralPath $file)) { continue }
$text = Get-Content -LiteralPath $file -Raw
foreach ($link in [regex]::Matches($text, '\[(?<label>[\w./ -]+)\]\((?:\./)?(?<file>[\w.-]+\.md)\)')) {
$childFile = $link.Groups['file'].Value
$label = $link.Groups['label'].Value.ToLowerInvariant()
if (!$childFile.StartsWith($name + '-') -or !$label.StartsWith($name + ' ')) { continue }
$childPath = Join-Path $docs $childFile
if (!(Test-Path -LiteralPath $childPath)) { continue }
$firstArgument = [regex]::Match((Get-Content -LiteralPath $childPath -Raw),
'(?m)^' + [regex]::Escape($name) + '(?:\.exe)?\s+\[?(?<operation>/[\w-]+)(?=[\]\s]|$)')
if ($firstArgument.Success -and $label -eq ($name + ' ' + $firstArgument.Groups['operation'].Value.TrimStart('/'))) {
$label = $name + ' ' + $firstArgument.Groups['operation'].Value
}
if (!$documents.ContainsKey($label)) { $documents[$label] = $childFile }
}
}
foreach ($name in $documents.Keys) {
$article = Join-Path $docs $documents[$name]
if (!(Test-Path -LiteralPath $article)) { continue }
$text = Get-Content -LiteralPath $article -Raw
$slug = [IO.Path]::GetFileNameWithoutExtension($article)
Add-CommandPath $name $slug
$articles[$name] = $slug
$syntax = [regex]::Matches($text, '(?ims)^(?:#{2,6}[^\r\n]*\b)?syntax[ \t]*\r?\n(?<body>.*?)(?=^#{1,6} |\z)')
$hasChildren = $false
$root = $name.Split(' ')[0]
$rootPattern = '^\s*' + [regex]::Escape($root) + '(?:\.exe)?(?=\s|$)\s*'
$blocks = @(
foreach ($section in $syntax) {
[regex]::Matches($section.Groups['body'].Value, '(?ms)^```[^\r\n]*\r?\n(?<code>.*?)^```') |
ForEach-Object { $_.Groups['code'].Value }
}
)
foreach ($block in $blocks) {
if ($block -match ($rootPattern + '\[\{')) {
$operations = [regex]::Matches($block,
'(?is)\[\{\s*(?<names>[a-z0-9-]+(?:\s*\|\s*[a-z0-9-]+)+)\s*\}(?<options>.*?)(?=\[\{|\z)')
foreach ($operation in $operations) {
foreach ($operationName in ($operation.Groups['names'].Value -split '\s*\|\s*')) {
$context = $name + ' ' + $operationName.ToLowerInvariant()
Add-CommandPath $context $slug
Add-Options $context $operation.Groups['options'].Value
$hasChildren = $true
}
}
if ($operations.Count) { continue }
}
$command = $name
foreach ($line in ($block -split '\r?\n')) {
if ($line -match $rootPattern) {
$tail = $line -replace $rootPattern, ''
$command = $root
while ($tail -match '^\[?(?<word>[a-z0-9][a-z0-9-]*)\]?(?=\s|$)(?!\s*\|)\s*') {
$command += ' ' + $Matches.word.ToLowerInvariant()
$tail = $tail.Substring($Matches[0].Length)
}
if ($command.Length -lt $name.Length) {
$command = $name
$operation = $name.Substring($root.Length).Trim()
if ($operation.StartsWith('/')) {
$tail = $tail -replace ('^\[?' + [regex]::Escape($operation) + '\]?(?=\s|$)\s*'), ''
}
}
Add-CommandPath $command $slug
if ($command.StartsWith($name + ' ')) { $hasChildren = $true }
if ($tail -match '^[\[{]+\s*(?<choices>[a-z0-9?-]+(?:\s*\|\s*[a-z0-9?-]+)+)\s*[\]}]') {
foreach ($choice in ($Matches.choices -split '\s*\|\s*')) {
[void]$entries[$command].Add($choice)
}
$hasChildren = $true
}
Add-Options $command $tail
} else {
Add-Options $command $line
}
foreach ($choice in [regex]::Matches($line, '(?<flag>[/\-][a-z][a-z0-9-]*)\s+\{(?<values>[a-z0-9_-]+(?:\s*\|\s*[a-z0-9_-]+)+)\}', 'IgnoreCase')) {
$context = $command + ' ' + $choice.Groups['flag'].Value.ToLowerInvariant()
Add-CommandPath $context $slug
foreach ($value in ($choice.Groups['values'].Value -split '\s*\|\s*')) {
[void]$entries[$context].Add($value)
}
}
}
}
if (!$hasChildren) {
foreach ($parameter in [regex]::Matches($text, '(?m)^\|\s*(?<value>[^|\r\n]+)\|')) {
$field = $parameter.Groups['value'].Value
if ($name.Contains(' /') -and $field.Trim() -eq $name.Split(' ')[-1]) { continue }
Add-Options $name $field
}
}
}
[string[]]$names = $entries.Keys
[Array]::Sort($names, [StringComparer]::Ordinal)
$lines = @(
'#pragma once'
'#include <string_view>'
''
'namespace ks::files'
'{'
'// Generated by tools/generate-windows-command-completion.ps1 from Microsoft Learn Windows Commands.'
"// https://github.com/MicrosoftDocs/windowsserverdocs/tree/$revision/WindowsServerDocs/administration/windows-commands"
'inline constexpr std::string_view windowsCommandCatalog[] = {'
foreach ($name in $names) {
' R"catalog(' + $name + "`t" + ($entries[$name] -join ' ') + "`t" + $articles[$name] + ')catalog",'
}
'};'
'}'
)
$lines | Set-Content -LiteralPath $Output -Encoding ascii