Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
219bdd4883 | ||
|
|
d018b91397 | ||
|
|
2d4df0daa8 | ||
|
|
773df250a4 | ||
|
|
b5924feb23 | ||
|
|
c285505d79 | ||
|
|
2e1b0446bc | ||
|
|
5ac3735db3 | ||
|
|
03984705fe | ||
|
|
dedc42f0db | ||
|
|
e5d639a72f | ||
|
|
4d68c80409 | ||
|
|
6af042a524 | ||
|
|
b28789a4f5 | ||
|
|
eaae5389d9 | ||
|
|
88b8536116 | ||
|
|
b8997d1dd2 | ||
|
|
1926bce15f | ||
|
|
afddcafdac | ||
|
|
21d28a0f6d | ||
|
|
f73dce7bb3 | ||
|
|
3c5f59ed91 | ||
|
|
e50fbbc119 | ||
|
|
6c5b09132f | ||
|
|
92774881ed | ||
|
|
353f4c2919 | ||
|
|
733f1b0fc9 | ||
|
|
878ae8fce8 | ||
|
|
edd9b2b3f9 | ||
|
|
36b0002404 | ||
|
|
8ffafde12a | ||
|
|
2bd325d294 | ||
|
|
d4c4f9be76 | ||
|
|
af388be4a7 | ||
|
|
3efdd2ef06 | ||
|
|
01b467e149 | ||
|
|
cf2dd6c419 | ||
|
|
293c5fd47e | ||
|
|
1dd6d75596 | ||
|
|
1aa23636ea | ||
|
|
886532f831 | ||
|
|
abaf73a050 | ||
|
|
b16e50bee9 | ||
|
|
3ed17fa6e8 | ||
|
|
a1df56177d | ||
|
|
09db0e1051 | ||
|
|
e1d8343c32 | ||
|
|
1ecd57a5e4 | ||
|
|
1ba169874a |
No files matched your search
@@ -4,5 +4,6 @@
|
||||
/.vs/
|
||||
/.idea/
|
||||
/dist/
|
||||
/Release/KSwitcher-win-x64.zip
|
||||
/build-output.txt
|
||||
*.user
|
||||
+37
-1
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.90 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.106 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
@@ -56,6 +56,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)
|
||||
@@ -149,6 +150,39 @@ add_test(NAME files-activation-and-refresh
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>")
|
||||
set_tests_properties(files-activation-and-refresh PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
|
||||
add_test(NAME files-system-open
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
|
||||
-SystemOpenOnly)
|
||||
set_tests_properties(files-system-open PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
|
||||
find_program(KSWITCHER_NODE NAMES node)
|
||||
if(KSWITCHER_NODE)
|
||||
add_test(NAME files-terminal-enter
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
|
||||
-TerminalOnly -Node "${KSWITCHER_NODE}")
|
||||
set_tests_properties(files-terminal-enter PROPERTIES RUN_SERIAL TRUE TIMEOUT 90)
|
||||
add_executable(KSwitcherFilesMarkdownLanFixture WIN32 tests/files_markdown_lan.cpp
|
||||
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
|
||||
target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText)
|
||||
add_dependencies(KSwitcherFilesMarkdownLanFixture KSwitcherTerminalAssets)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesMarkdownLanFixture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
target_compile_options(KSwitcherFilesMarkdownLanFixture PRIVATE /utf-8)
|
||||
else()
|
||||
target_link_options(KSwitcherFilesMarkdownLanFixture PRIVATE -municode -static)
|
||||
endif()
|
||||
add_test(NAME files-markdown-viewer
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_markdown.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Node "${KSWITCHER_NODE}"
|
||||
-LanFixture "$<TARGET_FILE:KSwitcherFilesMarkdownLanFixture>")
|
||||
set_tests_properties(files-markdown-viewer PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
|
||||
endif()
|
||||
add_executable(KSwitcherLanInputTests tests/lan_input.cpp)
|
||||
target_link_libraries(KSwitcherLanInputTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
@@ -166,6 +200,8 @@ else()
|
||||
target_link_options(KSwitcherChatProfileTests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests)
|
||||
add_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout)
|
||||
set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
|
||||
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
|
||||
target_link_libraries(KSwitcherHistoryHostTests PRIVATE kscore psapi)
|
||||
set_target_properties(KSwitcherHistoryHostTests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/history-host-fixture-$<CONFIG>")
|
||||
|
||||
+87
-8
@@ -24,20 +24,36 @@ Warning і початковий фокус на No.
|
||||
|
||||
## Скорочення
|
||||
|
||||
- У меню Files і його списках, що випадають, стрілки вгору й вниз
|
||||
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
|
||||
|
||||
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
|
||||
документ — у програмі, призначеній для його типу у Windows. EXE запускається
|
||||
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
|
||||
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
|
||||
панелі LAN, спочатку скопіюй його до локальної папки.
|
||||
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
|
||||
елемент через Windows.
|
||||
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
|
||||
|
||||
- У головному вікні клавіатурний фокус залишається в командному рядку.
|
||||
Tab перемикає активну панель, клік вибирає рядок, а стрілки вгору й вниз,
|
||||
Page Up і Page Down пересувають курсор у панелі навіть під час набору команди.
|
||||
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
|
||||
командний рядок порожній.
|
||||
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
|
||||
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
|
||||
текст із буфера обміну в позицію курсора або замінюють виділення.
|
||||
Enter запускає введену команду або відкриває поточний елемент, якщо рядок
|
||||
порожній. Escape очищає рядок.
|
||||
Enter і Shift+Enter спочатку виконують введену команду. Коли рядок
|
||||
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
|
||||
Enter передає порожній рядок у термінал. Escape очищає рядок.
|
||||
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
|
||||
командного рядка й виконують відповідну дію за тими самими правилами.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
|
||||
що й клавіша F8.
|
||||
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
|
||||
а назви дій темні на бірюзових сегментах.
|
||||
- У віддаленій панелі Enter запускає введену команду PowerShell на
|
||||
спареному ПК в поточному каталозі цієї панелі. Вивід і код завершення
|
||||
з’являються в терміналі Files як текст. Службовий прогрес PowerShell
|
||||
@@ -67,8 +83,21 @@ Warning і початковий фокус на No.
|
||||
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
|
||||
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
|
||||
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
|
||||
- Ctrl+C копіює весь введений у командний рядок текст, навіть коли виділено
|
||||
лише його частину.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу
|
||||
активна панель показує «Loading folder…» і зберігає попередній список до
|
||||
завершення сканування. Якщо надійшов новіший запит, результат попереднього
|
||||
сканування пропускається. Після підтвердження UAC очікування списку
|
||||
від підвищеного процесу теж відбувається у фоні.
|
||||
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
|
||||
зберігаються для наявних елементів, а підраховані через F3 розміри папок
|
||||
скидаються. F2 також виконує цю дію.
|
||||
- Ctrl+C і Ctrl+Insert копіюють виділений текст із виводу термінала.
|
||||
- За відсутності виділення у виводі Ctrl+C копіює весь введений у командний
|
||||
рядок текст, навіть коли виділено лише його частину.
|
||||
- Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок
|
||||
порожній, копіюються імена позначених файлів і папок активної панелі в
|
||||
порядку відображення, по одному на рядок. Якщо позначок немає, копіюється
|
||||
ім’я під курсором. Шляхи й рядок `..` пропускаються.
|
||||
|
||||
- Ctrl+E підставляє останню команду. Повторне натискання
|
||||
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
|
||||
@@ -126,9 +155,43 @@ Warning і початковий фокус на No.
|
||||
відкриває файл у програмі, призначеній Windows для цього типу, а Alt+F4
|
||||
викликає зареєстровану дію Edit. Ці команди також є в меню Commands.
|
||||
F10 або × закривають головне вікно Files. Вбудовані Viewer та Editor
|
||||
відкриваються в окремих немодальних вікнах із власними кнопками на панелі
|
||||
завдань Windows. При повторному відкритті Files пропонує перейти до вже
|
||||
відкриваються в окремих немодальних вікнах. Редактор має іконку олівця,
|
||||
переглядач — іконку ока. Ці іконки видно в заголовку, в Alt+Tab і в окремих
|
||||
групах на панелі завдань Windows. F6 змінює іконку й групу поточного вікна.
|
||||
При повторному відкритті Files пропонує перейти до вже
|
||||
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
|
||||
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
|
||||
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
|
||||
Помилка збереження залишає відкритим редактор зі змінами.
|
||||
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
|
||||
у порядку їх відкриття.
|
||||
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
|
||||
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
|
||||
із підсвічуванням Markdown.
|
||||
HTML усередині Markdown підтримує таблиці, текстове форматування, посилання,
|
||||
відносні зображення й окремі стилі, зокрема `white-space: nowrap` у клітинках.
|
||||
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
|
||||
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
|
||||
Вихідний текст приховано, доки Markdown і Mermaid готують перегляд.
|
||||
Звичайний клік відкриває внутрішнє посилання в тому самому вікні,
|
||||
Shift+клік відкриває окреме вікно. Назад і вперед працюють через стрілки
|
||||
перегляду, бічні кнопки миші й Alt+←/→. Ctrl+W закриває перегляд.
|
||||
Ctrl+F або кнопка пошуку відкриває пошук у відрендерованому документі.
|
||||
Пошук без урахування регістру показує кількість збігів і підсвічує поточний.
|
||||
Enter і F3 переходять до наступного збігу, а Shift+Enter і Shift+F3 — до
|
||||
попереднього, циклічно. Escape спочатку закриває поле пошуку.
|
||||
Коли локальний Markdown оновлюється на диску, відкритий перегляд
|
||||
перерендерюється зі збереженням позиції прокрутки.
|
||||
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
|
||||
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
|
||||
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
|
||||
8 МіБ, F3 відкриває текстовий перегляд.
|
||||
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
|
||||
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
|
||||
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
|
||||
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
|
||||
junction не обходяться. Недоступний вміст позначається як частковий результат.
|
||||
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
|
||||
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
|
||||
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
|
||||
@@ -163,6 +226,11 @@ Warning і початковий фокус на No.
|
||||
кодування. Нередаговані байти копіюються без перетворення.
|
||||
- Команда Options у панелях, редакторі й переглядачі відкриває один діалог
|
||||
KSwitcher Files Options. Розділи Viewer та Editor зберігають окремі профілі.
|
||||
**Viewer → Markdown** задає максимальну ширину документа (0 — усе вікно),
|
||||
гарнітуру та розмір основного тексту. Порожня гарнітура використовує системний
|
||||
шрифт. Apply одразу оновлює відкриті перегляди Markdown.
|
||||
Після повторного відкриття Options відновлюється останній розділ, зокрема
|
||||
після Cancel. Пошуковий запит і чернетка змін не зберігаються.
|
||||
З редактора або переглядача діалог відкриває відповідний розділ. Apply
|
||||
застосовує зміни до відкритих вікон, Cancel відкидає незастосовану чернетку.
|
||||
Доступні перенесення рядків, номери рядків, показ пробілів і
|
||||
@@ -250,7 +318,9 @@ Warning і початковий фокус на No.
|
||||
- Власні діалоги Files блокують дії панелей і командного рядка, залишаючи
|
||||
системний заголовок і рамку головного вікна доступними. Клік у Files поза діалогом
|
||||
діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває
|
||||
підтвердження скасування.
|
||||
підтвердження скасування. Перелік і обробка файлів виконуються у фоновому
|
||||
потоці. Діалог залишається доступним під час очікування файлового вводу-виводу.
|
||||
Скасування перевіряється між кроками операції та під час передачі блоків.
|
||||
|
||||
- Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No.
|
||||
|
||||
@@ -263,7 +333,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 мають системне оформлення.
|
||||
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
|
||||
|
||||
@@ -39,6 +39,8 @@ the local resident process running and log downloads enabled on the remote PC.
|
||||
1. Install the v0.6.58 or newer on every participating PC. Input protocol v2 requires all participants to update; earlier one-pair builds cannot connect. Preserve local data; do not copy pairing identities between PCs.
|
||||
2. Open **Settings → Computers → Manage computers…** and enable discovery on both PCs.
|
||||
Only running LAN-enabled KSwitcher instances appear, not generic network devices.
|
||||
The computer list and pairing controls are on the left, the monitor grid and
|
||||
input sharing are on the right, and file, log and help actions are below.
|
||||
3. Match the computer name and instance-ID prefix displayed on the other PC.
|
||||
Select each other, generate one code, enter that same code on both, then click
|
||||
Pair on both within two minutes. Spaces, hyphens and uppercase hex are accepted.
|
||||
|
||||
@@ -144,7 +144,8 @@ in the resident app. Screen capture and all screenshot editors run on demand in
|
||||
process. Closing the last editor (or cancelling the only selection) exits that process. It does not
|
||||
load resident settings, dictionaries, clipboard history or keyboard hooks. Editor windows have
|
||||
stable numbered titles within that process. Keep all three executables together when copying or
|
||||
updating the application. Close screenshot editors before installing an update.
|
||||
updating the application. After verifying a new package, the updater closes Files, the text and
|
||||
screenshot editors, Settings, and bundled StayHere for that installation. Save open work before approving an update.
|
||||
If settings change in the tray while the configurator is open, a conflicting Save is rejected; reopen
|
||||
the configurator to load the latest settings.
|
||||
Updates from v0.3.x–v0.4.1 first install the compatible **v0.4.2 bridge** through
|
||||
@@ -599,8 +600,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,
|
||||
@@ -920,8 +922,11 @@ CC BY-SA 4.0; attribution, pinned source revision and license are in `dictionari
|
||||
|
||||
## Latest compiled release
|
||||
|
||||
The [Release folder](Release/README.md) contains the latest portable Windows x64 ZIP and SHA-256 checksum.
|
||||
Run `./package.ps1 -PublishRelease` after building and testing to refresh the tracked release archive.
|
||||
Download the portable Windows x64 ZIP from [Gitea Releases](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases).
|
||||
The [Release folder](Release/README.md) tracks the release notes, manifest and SHA-256 checksum.
|
||||
Run `./package.ps1 -PublishRelease` after building and testing. 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
|
||||
|
||||
@@ -1016,7 +1021,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.
|
||||
|
||||
|
||||
@@ -1,5 +1,111 @@
|
||||
# Latest Windows release
|
||||
|
||||
## 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.
|
||||
|
||||
**Українською.** Редактор KSwitcher Files має іконку олівця, а переглядач — іконку ока. Режими мають окремі групи на панелі завдань Windows, і **F6** перемикає іконку й групу в тому самому вікні. Якщо KSwitcher на ПК-отримувачі запущено від адміністратора, команди PowerShell через LAN, зокрема `dir`, запускаються з правами звичайного користувача. Виправлено помилку запуску `0xC0000142` у цьому сценарії. Цей реліз замінює v0.6.104.
|
||||
|
||||
## v0.6.104 — 2026-11-16
|
||||
|
||||
**Ctrl+F** or the search icon opens search in the rendered KSwitcher Files Markdown preview. Search ignores case and highlights the current match. **Enter** or **F3** moves to the next match, and **Shift+Enter** or **Shift+F3** moves back. **Escape** closes the search first. This release includes the HTML, Markdown appearance, Options and terminal copy updates from v0.6.103.
|
||||
|
||||
**Українською.** **Ctrl+F** або піктограма пошуку відкриває пошук у відрендерованому Markdown у KSwitcher Files. Пошук ігнорує регістр і підсвічує поточний збіг. **Enter** або **F3** переходить до наступного збігу, а **Shift+Enter** або **Shift+F3** повертає до попереднього. **Escape** спочатку закриває пошук. Реліз включає підтримку HTML, налаштування вигляду Markdown, запам’ятовування розділу Options і копіювання з термінала з v0.6.103.
|
||||
|
||||
## v0.6.103 — 2026-11-16
|
||||
|
||||
The KSwitcher Files Markdown preview renders embedded HTML tables and inline styles such as `white-space: nowrap`. **Options → Viewer → Markdown** sets the preview width, font family and font size. Files Options reopens the last section. **Ctrl+C** and **Ctrl+Insert** copy selected terminal output. This release replaces v0.6.102.
|
||||
|
||||
**Українською.** Перегляд Markdown у KSwitcher Files відображає вбудовані HTML-таблиці й стилі, зокрема `white-space: nowrap`. У **Options → Viewer → Markdown** можна задати ширину перегляду, гарнітуру й розмір шрифту. Options відкриває останній відвіданий розділ. **Ctrl+C** і **Ctrl+Insert** копіюють виділений текст із виводу термінала. Цей реліз замінює v0.6.102.
|
||||
|
||||
## v0.6.102 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Ctrl+Insert copies the full command line when it contains text. With an empty command line, it copies names from the active pane. The LAN host returns Windows PowerShell startup errors without waiting for a system error dialog. Files explains DLL initialization failure `0xC0000142` and accepts another command. This release replaces v0.6.101.
|
||||
|
||||
**Українською.** У KSwitcher Files Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок порожній, копіюються імена з активної панелі. ПК, який приймає LAN-команду, повертає помилки запуску Windows PowerShell без очікування системного діалогу. Files пояснює помилку ініціалізації DLL `0xC0000142` і знову приймає команди. Цей реліз замінює v0.6.101.
|
||||
|
||||
## v0.6.101 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Enter opens the selected item when the command line is empty, including when focus is in the terminal output. The Computers window places pairing and the monitor grid side by side so the bottom actions fit at high display scaling. This release replaces v0.6.100.
|
||||
|
||||
**Українською.** У KSwitcher Files Enter відкриває вибраний елемент, коли командний рядок порожній, зокрема коли фокус у виводі термінала. У вікні Computers спарювання та схема моніторів розташовані поруч, тож нижні дії поміщаються і при високому масштабі. Цей реліз замінює v0.6.100.
|
||||
|
||||
## v0.6.100 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Enter and Shift+Enter submit the command line when focus is in the terminal output. The terminal scrolls to the latest output when a command is submitted. While a LAN command is still running, Files shows how to cancel it and keeps the next command in the input field. This release replaces v0.6.99.
|
||||
|
||||
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують введену команду, коли фокус у виводі термінала. Під час запуску команди термінал прокручується до останнього виводу. Поки виконується LAN-команда, Files показує, як її скасувати, і зберігає наступну команду в полі вводу. Цей реліз замінює v0.6.99.
|
||||
|
||||
## v0.6.99 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, Enter and Shift+Enter run the command in the command line, including when the file panes are hidden. With visible panes and an empty command line, the keys act on the selected item. A command reveals the terminal output if it was hidden. This release replaces v0.6.98.
|
||||
|
||||
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують команду з командного рядка, зокрема коли файлові панелі приховані. Коли панелі видимі й рядок порожній, клавіші діють на вибраний елемент. Якщо вивід термінала приховано, команда відкриває його. Цей реліз замінює v0.6.98.
|
||||
|
||||
## v0.6.98 — 2026-11-16
|
||||
|
||||
In Files, Enter opens folders in the current pane, uses the Windows default action for local files, and runs BAT and CMD in the embedded terminal. Shift+Enter opens local folders in File Explorer and passes files, including BAT and CMD, to Windows. It preserves the draft command. Left and Right clear the previous cursor highlight when jumping to the first or last row. The FAR-style key bar uses gray key labels on black and dark action names on teal.
|
||||
|
||||
**Українською.** У Files Enter відкриває папки в поточній панелі, викликає стандартну дію Windows для локальних файлів, а BAT і CMD запускає у вбудованому терміналі. Shift+Enter відкриває локальні папки у Провіднику й передає файли, зокрема BAT і CMD, Windows. Чернетка команди зберігається. Стрілки вліво й вправо скидають старе підсвічування при переході до першого чи останнього рядка. Нижній рядок клавіш у стилі FAR має сірі позначення клавіш на чорному тлі й темні назви дій на бірюзовому.
|
||||
|
||||
## v0.6.97 — 2026-11-16
|
||||
|
||||
KSwitcher Files clears the highlight from the previous cursor row after a selection change and highlights the new row. It keeps the targeted repaint introduced in v0.6.96. This release replaces v0.6.96.
|
||||
|
||||
**Українською.** KSwitcher Files знімає підсвічування з попереднього рядка курсора після зміни вибору й виділяє новий рядок. Панель і далі перемальовує лише потрібні рядки. Цей реліз замінює v0.6.96.
|
||||
|
||||
## v0.6.96 — 2026-11-16
|
||||
|
||||
Clicking a file row in Files now redraws only the affected cursor rows, including when switching panes. The key bar adds **F8 Delete**, which opens the same confirmation as pressing F8.
|
||||
|
||||
**Українською.** Клік по рядку у Files перемальовує лише рядки курсора, зокрема при переході на іншу панель. У нижньому рядку клавіш є **F8 Delete**, що відкриває той самий діалог підтвердження, що й клавіша F8.
|
||||
|
||||
## v0.6.95 — 2026-11-16
|
||||
|
||||
Files shows Markdown after rendering completes, refreshes local previews when the file changes on disk, and opens internal links in the same window. Shift+click opens a separate window. The arrow controls, mouse side buttons and Alt+Left/Right navigate history. Ctrl+W closes the viewer. Ctrl+Tab cycles through Files and its open editors and viewers. Up and Down wrap in Files menus and drop-downs. Manual and LAN updates close Files, editors, Settings and bundled StayHere from the target installation before replacing its files. Save open work before updating. When installing this release with an older updater, close Files and its separate windows first. This release replaces v0.6.94.
|
||||
|
||||
**Українською.** Files показує Markdown після рендерингу й автоматично оновлює локальний перегляд після змін на диску. Внутрішні посилання відкриваються в тому самому вікні, Shift+клік — в окремому. Історією керують стрілки перегляду, бічні кнопки миші та Alt+←/→. Ctrl+W закриває перегляд. Ctrl+Tab циклічно перемикає Files та відкриті редактори й переглядачі. Стрілки вгору й вниз циклічно проходять меню та розкривні списки. Ручне оновлення й оновлення через LAN закривають Files, редактори, Settings і вбудований StayHere цільової інсталяції перед заміною файлів. Збережіть відкриті правки перед оновленням. Якщо цей реліз встановлює старий оновлювач, спочатку закрийте Files та його окремі вікна. Цей реліз замінює v0.6.94.
|
||||
|
||||
## v0.6.94 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, F3 renders Markdown with offline Mermaid diagrams, tables, and interactive task lists. Relative links and images work for local and LAN documents. Checkbox changes last for the current preview. F4 opens the syntax-highlighted text editor and F6 switches between View and Edit in the same window, prompting before leaving unsaved edits.
|
||||
|
||||
**Українською.** У KSwitcher Files клавіша F3 відкриває форматований Markdown із діаграмами Mermaid, таблицями та інтерактивними списками завдань. Mermaid працює офлайн. Відносні посилання й зображення працюють для локальних і LAN-файлів. Відмітки чекбоксів діють у поточному сеансі перегляду. F4 відкриває редактор із підсвічуванням синтаксису, а F6 перемикає перегляд і редагування в тому самому вікні. Якщо є незбережені зміни, Files пропонує їх зберегти.
|
||||
|
||||
## v0.6.93 — 2026-11-16
|
||||
|
||||
In Files, Ctrl+R refreshes the active pane as in FAR Manager. The menu and key bar show Ctrl+R. F2 also refreshes the pane. Refresh preserves marks and the cursor where possible, and clears folder sizes calculated with F3.
|
||||
|
||||
**Українською.** У Files Ctrl+R перечитує активну панель, як у FAR Manager. Комбінація показана в меню та рядку клавіш. F2 також перечитує панель. Перечитування зберігає позначки й курсор для наявних елементів і скидає розміри папок, підраховані через F3.
|
||||
|
||||
## v0.6.92 — 2026-11-16
|
||||
|
||||
In Files, F3 on a folder measures file sizes throughout the directory tree. If folders are marked, Files measures each marked folder separately. Results appear in the Size column in Wide mode. F3 on a file opens the viewer even when folders are marked. Folder sizing runs in the background and supports LAN panes.
|
||||
|
||||
**Українською.** У Files F3 на папці підраховує сумарний розмір файлів у всьому дереві. Якщо позначено папки, Files рахує розмір кожної окремо. Результат з’являється в колонці Size у широкому режимі. F3 на файлі відкриває переглядач, навіть коли позначено папки. Підрахунок виконується у фоні й підтримує LAN-панелі.
|
||||
|
||||
## v0.6.91 — 2026-11-16
|
||||
|
||||
Ctrl+Insert copies the marked file and folder names from the active pane, one per line. Without marks, it copies the name under the cursor. LAN Files retries opening TCP 45885 if the port is busy at startup, and Change drive retries failed drive queries. A remote update request waits for an in-progress update check. The updater identifies and closes companion processes from its installation, including Files running from an update backup, and records confirmed exits in the journal.
|
||||
|
||||
**Українською.** Ctrl+Insert копіює імена позначених файлів і папок активної панелі, по одному на рядок. Якщо позначок немає, копіюється ім’я під курсором. LAN Files повторює відкриття TCP 45885, якщо порт зайнятий під час старту, а Change drive повторює невдалі запити дисків. Запит віддаленого оновлення чекає завершення поточної перевірки. Оновлювач визначає й закриває процеси своєї інсталяції, зокрема Files із резервної папки, і записує підтверджене завершення в журнал.
|
||||
|
||||
## v0.6.90 — 2026-11-16
|
||||
|
||||
Files groups Commands into navigation, viewing and editing, and remote PC actions. The remote group appears in an active LAN pane. Shared notices fit their contents and show a scrollbar only when needed. Remote hibernation and update confirmations use a compact red warning with No focused by default.
|
||||
|
||||
@@ -1 +1 @@
|
||||
67db5adc069f847aa1d9987e4043dfd488b03ae15444a99b007774ac01556461 KSwitcher-win-x64.zip
|
||||
1094524ee07ae94bebddd7dcfa6047fb1ca3d5ce86df9072aa1e881e90b95412 KSwitcher-win-x64.zip
|
||||
+49
-19
@@ -1,24 +1,25 @@
|
||||
{
|
||||
"version": "0.6.90",
|
||||
"schema": 1,
|
||||
"version": "0.6.106",
|
||||
"files": [
|
||||
{
|
||||
"size": 2465792,
|
||||
"sha256": "7f6d0d1508a324ccc793455f6667084dcd1003cbc472dca9f6262c014068f99b",
|
||||
"size": 2369024,
|
||||
"sha256": "0b53535ef8f50f9ec504ed82b930dd2afc862105acdc38a9cfc09059123f0ff2",
|
||||
"path": "KSwitcher.exe"
|
||||
},
|
||||
{
|
||||
"size": 2445824,
|
||||
"sha256": "2ae249c373b6f8a8f232daffae84738751d9aad7d1f39bd7335fb379a415e50c",
|
||||
"size": 2366464,
|
||||
"sha256": "d4f1338575cb808497bfc3cb334a32129a66f0efd164a26c8cc5d0a8d5eca8bc",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
},
|
||||
{
|
||||
"size": 3052544,
|
||||
"sha256": "bd1fca6c5dfa35ac2ae4afab5becb67ed7701d011ce6e671a05340f0634150e2",
|
||||
"size": 3346432,
|
||||
"sha256": "1416152e756cdbd37ce29d6337806cce5ceea26f3a03680f050ba8282a380de0",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
},
|
||||
{
|
||||
"size": 3675136,
|
||||
"sha256": "bbcddc17a1cd69824a8cbdff7301854739c295b6b4fb27227acb00d375a9ab3a",
|
||||
"size": 3866112,
|
||||
"sha256": "8be3992909882beb7c94280f3b6902b59f19854f67f0a68d4b753682750edb85",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
},
|
||||
{
|
||||
@@ -42,8 +43,38 @@
|
||||
"path": "terminal/index.html"
|
||||
},
|
||||
{
|
||||
"size": 4268,
|
||||
"sha256": "fb302b2902fea6a815a8266811f350d1e4c108ca88fafd49e6eddcbfff90a5e5",
|
||||
"size": 1073,
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"path": "terminal/markdown-it-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 100786,
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"path": "terminal/markdown-it.js"
|
||||
},
|
||||
{
|
||||
"size": 3530,
|
||||
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c",
|
||||
"path": "terminal/markdown.html"
|
||||
},
|
||||
{
|
||||
"size": 14660,
|
||||
"sha256": "fe202fa3d3c362aff2ab9028b40bd2aee61240bf9bd4a44af55e45d1a4081cf0",
|
||||
"path": "terminal/markdown.js"
|
||||
},
|
||||
{
|
||||
"size": 1089,
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"path": "terminal/mermaid-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 5537838,
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"path": "terminal/mermaid.js"
|
||||
},
|
||||
{
|
||||
"size": 5033,
|
||||
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a",
|
||||
"path": "terminal/terminal.js"
|
||||
},
|
||||
{
|
||||
@@ -77,13 +108,13 @@
|
||||
"path": "files-text-license.txt"
|
||||
},
|
||||
{
|
||||
"size": 94223,
|
||||
"sha256": "7b34f2af7341f57d7bac1b5b7e55a40595a6bc20f461f98c0c6320336d0deba7",
|
||||
"size": 94769,
|
||||
"sha256": "adda764fa7ca0cf80958ef44ed446b438ffa18b5f996c7ef19b553132d0f112a",
|
||||
"path": "README.md"
|
||||
},
|
||||
{
|
||||
"size": 11418,
|
||||
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
|
||||
"size": 11577,
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
|
||||
"path": "LAN-PREVIEW.md"
|
||||
},
|
||||
{
|
||||
@@ -122,8 +153,8 @@
|
||||
"path": "tools/README.txt"
|
||||
},
|
||||
{
|
||||
"size": 133120,
|
||||
"sha256": "9e914d996864d7f982ba50e481381d673e4e84ee7ad5d1f477f0898aa1816256",
|
||||
"size": 134656,
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
|
||||
"path": "tools/StayHere.exe"
|
||||
},
|
||||
{
|
||||
@@ -131,6 +162,5 @@
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"path": "tools/StayHere-README.md"
|
||||
}
|
||||
],
|
||||
"schema": 1
|
||||
]
|
||||
}
|
||||
+3
-4
@@ -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
@@ -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,90,0
|
||||
PRODUCTVERSION 0,6,90,0
|
||||
FILEVERSION 0,6,106,0
|
||||
PRODUCTVERSION 0,6,106,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.90"
|
||||
VALUE "FileVersion", "0.6.106"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#pragma code_page(65001)
|
||||
#include <windows.h>
|
||||
#include <commctrl.h>
|
||||
#include "resource.h"
|
||||
|
||||
#define FAR_EDIT(id, mode, x, y, width, height) \
|
||||
CONTROL "", id, "KSwitcher.Files.FarEdit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height
|
||||
|
||||
1 ICON "kswitcher-files.ico"
|
||||
IDI_FILES_VIEWER ICON "kswitcher-files-viewer.ico"
|
||||
IDI_FILES_EDITOR ICON "kswitcher-files-editor.ico"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
601 RCDATA "files-text-license.txt"
|
||||
|
||||
@@ -57,6 +60,19 @@ BEGIN
|
||||
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 "&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_VSCROLL | 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
|
||||
@@ -144,6 +160,13 @@ BEGIN
|
||||
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
|
||||
LTEXT "", 367, 345, 184, 45, 12
|
||||
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
|
||||
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
|
||||
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12
|
||||
EDITTEXT 376, 131, 68, 168, 14, ES_AUTOHSCROLL
|
||||
PUSHBUTTON "Choose &font…", 377, 306, 68, 76, 14
|
||||
LTEXT "Font &size (8–72 pt)", 378, 131, 99, 184, 12
|
||||
EDITTEXT 379, 318, 96, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
|
||||
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
@@ -1,4 +1,6 @@
|
||||
#pragma once
|
||||
#define IDI_KSWITCHER 101
|
||||
#define IDI_SCREENSHOT_QUESTION 102
|
||||
#define IDI_FILES_VIEWER 103
|
||||
#define IDI_FILES_EDITOR 104
|
||||
#define IDC_SCREENSHOT_PENCIL 500
|
||||
@@ -0,0 +1,56 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'">
|
||||
<title>Markdown preview</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; font: 16px/1.55 system-ui, sans-serif; }
|
||||
:root:not(.rendered) body { visibility: hidden; }
|
||||
body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
|
||||
main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); }
|
||||
nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; }
|
||||
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
|
||||
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
|
||||
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
|
||||
nav button:hover:not(:disabled) { text-decoration: underline; }
|
||||
nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
#search { margin-inline-start: auto; display: flex; align-items: center; gap: .35em;
|
||||
flex: 0 1 22em; min-width: 0; max-width: 100%; }
|
||||
#search[hidden] { display: none; }
|
||||
#search-query { box-sizing: border-box; flex: 1; min-width: 0; width: 0; font: inherit; }
|
||||
#search-status { white-space: nowrap; font-size: .8em; }
|
||||
::highlight(markdown-search-active) { background: #ffab45; color: #171717; }
|
||||
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
|
||||
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
|
||||
a { color: LinkText; }
|
||||
pre, table, figure { overflow: auto; }
|
||||
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
|
||||
pre { padding: .75em; }
|
||||
code { padding: .1em .25em; }
|
||||
pre code { padding: 0; background: none; }
|
||||
blockquote { margin-left: 0; padding-left: 1em; border-left: 3px solid GrayText; }
|
||||
table { display: block; border-collapse: collapse; }
|
||||
th, td { border: 1px solid GrayText; padding: .3em .65em; }
|
||||
img, svg { max-width: 100%; height: auto; }
|
||||
figure { margin: 1em 0; }
|
||||
.task { list-style: none; }
|
||||
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
|
||||
</style>
|
||||
<nav aria-label="Markdown preview">
|
||||
<button id="back" type="button" title="Back (Alt+Left)" aria-label="Back" disabled>←</button>
|
||||
<button id="forward" type="button" title="Forward (Alt+Right)" aria-label="Forward" disabled>→</button>
|
||||
<button id="search-open" type="button" title="Find (Ctrl+F)" aria-label="Find in document" aria-controls="search" aria-expanded="false">⌕</button>
|
||||
<div id="search" role="search" hidden>
|
||||
<input id="search-query" type="search" aria-label="Find in document" placeholder="Find in document" autocomplete="off">
|
||||
<output id="search-status" for="search-query" aria-live="polite"></output>
|
||||
<button id="search-previous" type="button" title="Previous match (Shift+Enter)" aria-label="Previous match" disabled>↑</button>
|
||||
<button id="search-next" type="button" title="Next match (Enter)" aria-label="Next match" disabled>↓</button>
|
||||
<button id="search-close" type="button" title="Close search (Esc)" aria-label="Close search">×</button>
|
||||
</div>
|
||||
</nav>
|
||||
<main></main>
|
||||
<script src="markdown-it.js"></script>
|
||||
<script src="mermaid.js"></script>
|
||||
<script src="markdown.js"></script>
|
||||
</html>
|
||||
@@ -0,0 +1,327 @@
|
||||
'use strict';
|
||||
|
||||
const bridge = window.chrome.webview;
|
||||
const content = document.querySelector('main');
|
||||
const back = document.querySelector('#back');
|
||||
const forward = document.querySelector('#forward');
|
||||
const searchOpen = document.querySelector('#search-open');
|
||||
const search = document.querySelector('#search');
|
||||
const searchQuery = document.querySelector('#search-query');
|
||||
const searchStatus = document.querySelector('#search-status');
|
||||
const searchPrevious = document.querySelector('#search-previous');
|
||||
const searchNext = document.querySelector('#search-next');
|
||||
const markdown = markdownit({ html: true, linkify: true });
|
||||
let generation = 0;
|
||||
let images = [];
|
||||
let matches = [];
|
||||
let activeMatch = -1;
|
||||
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: 'strict',
|
||||
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
|
||||
suppressErrorRendering: true,
|
||||
flowchart: { htmlLabels: false }
|
||||
});
|
||||
|
||||
markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
|
||||
for (let i = 2; i < tokens.length; ++i) {
|
||||
const token = tokens[i];
|
||||
if (token.type !== 'inline' || tokens[i - 1].type !== 'paragraph_open' ||
|
||||
tokens[i - 2].type !== 'list_item_open') continue;
|
||||
const text = token.children[0];
|
||||
const marker = text?.type === 'text' && /^\[([ xX])\][ \t]+/.exec(text.content);
|
||||
if (!marker) continue;
|
||||
text.content = text.content.slice(marker[0].length);
|
||||
const box = new text.constructor('task_checkbox', '', 0);
|
||||
box.checked = marker[1] !== ' ';
|
||||
box.content = token.content.slice(marker[0].length);
|
||||
token.children.unshift(box);
|
||||
tokens[i - 2].attrJoin('class', 'task');
|
||||
}
|
||||
});
|
||||
markdown.renderer.rules.task_checkbox = (tokens, i) =>
|
||||
'<input type="checkbox" aria-label="' + markdown.utils.escapeHtml(tokens[i].content) + '"' +
|
||||
(tokens[i].checked ? ' checked' : '') + '>';
|
||||
markdown.renderer.rules.image = (tokens, i) => {
|
||||
const token = tokens[i];
|
||||
const alt = markdown.renderer.renderInlineAsText(token.children, markdown.options, {});
|
||||
const escape = markdown.utils.escapeHtml;
|
||||
return '<img alt="' + escape(alt) + '" data-path="' + escape(token.attrGet('src')) + '">';
|
||||
};
|
||||
|
||||
const htmlTags = new Set(`a abbr address article aside b blockquote br caption code col colgroup dd del
|
||||
details div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hr i img input ins kbd li
|
||||
mark ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
|
||||
tr u ul var wbr`.split(/\s+/));
|
||||
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
|
||||
const tagAttributes = {
|
||||
a: ['href'], col: ['span'], colgroup: ['span'], details: ['open'], img: ['alt', 'width', 'height'],
|
||||
input: ['type', 'checked', 'disabled'], ol: ['start', 'reversed', 'type'], li: ['value'],
|
||||
td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan', 'scope'], time: ['datetime']
|
||||
};
|
||||
const inlineStyles = ['white-space', 'text-align', 'vertical-align', 'color', 'background-color',
|
||||
'font-weight', 'font-style', 'text-decoration-line', 'width', 'max-width'];
|
||||
|
||||
function relativeResource(path) {
|
||||
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
|
||||
}
|
||||
|
||||
function renderContent(text) {
|
||||
// Parse in an inert template and allow only document markup before attaching it to the preview.
|
||||
const template = document.createElement('template');
|
||||
template.innerHTML = markdown.render(text);
|
||||
for (const element of template.content.querySelectorAll('*')) {
|
||||
const tag = element.localName;
|
||||
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
|
||||
(tag === 'input' && element.type !== 'checkbox')) {
|
||||
element.remove();
|
||||
continue;
|
||||
}
|
||||
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
|
||||
const styles = element.hasAttribute('style')
|
||||
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
|
||||
for (const { name } of [...element.attributes]) {
|
||||
if (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name)) element.removeAttribute(name);
|
||||
}
|
||||
for (const [name, value] of styles) {
|
||||
if (value) element.style.setProperty(name, value);
|
||||
}
|
||||
if (relativeResource(imagePath)) element.dataset.path = imagePath;
|
||||
if (tag === 'a' && element.hasAttribute('href')) {
|
||||
const path = element.getAttribute('href').trim();
|
||||
if (relativeResource(path) || /^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i.test(path)) element.setAttribute('href', path);
|
||||
else element.removeAttribute('href');
|
||||
}
|
||||
}
|
||||
content.replaceChildren(template.content);
|
||||
}
|
||||
|
||||
function send(action, options = {}) {
|
||||
bridge.postMessage(JSON.stringify({ action, ...options }));
|
||||
}
|
||||
|
||||
function scrollToHeading(fragment) {
|
||||
if (!fragment) { window.scrollTo(0, 0); return; }
|
||||
try { content.querySelector('#' + CSS.escape(decodeURIComponent(fragment)))?.scrollIntoView(); } catch {}
|
||||
}
|
||||
|
||||
function restorePosition({ fragment, scroll }) {
|
||||
if (typeof scroll === 'number') window.scrollTo(0, scroll);
|
||||
else scrollToHeading(fragment);
|
||||
}
|
||||
|
||||
function navigate(action) {
|
||||
const button = action === 'back' ? back : forward;
|
||||
if (!button.disabled) send(action, { scroll: Math.round(window.scrollY) });
|
||||
}
|
||||
|
||||
back.addEventListener('click', () => navigate('back'));
|
||||
forward.addEventListener('click', () => navigate('forward'));
|
||||
|
||||
function updateSearch(reveal = true) {
|
||||
matches = [];
|
||||
activeMatch = -1;
|
||||
const query = searchQuery.value.trim();
|
||||
if (query) {
|
||||
const pattern = query.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
|
||||
const expression = new RegExp(pattern, 'giu');
|
||||
const blockTags = 'article,aside,blockquote,caption,dd,div,dt,figcaption,footer,h1,h2,h3,h4,h5,h6,header,li,p,pre,section,summary,td,th,text';
|
||||
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
|
||||
let block = null;
|
||||
let parts = [];
|
||||
let text = '';
|
||||
const searchBlock = () => {
|
||||
let first = 0;
|
||||
let last = 0;
|
||||
for (const match of text.matchAll(expression)) {
|
||||
const end = match.index + match[0].length;
|
||||
while (parts[first].end <= match.index) ++first;
|
||||
last = Math.max(last, first);
|
||||
while (parts[last].end < end) ++last;
|
||||
matches.push([parts[first].node, match.index - parts[first].start,
|
||||
parts[last].node, end - parts[last].start]);
|
||||
}
|
||||
parts = [];
|
||||
text = '';
|
||||
};
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
const element = node.parentElement;
|
||||
if (!node.length || element.closest('style,svg title,svg desc,svg defs') ||
|
||||
!element.checkVisibility({ visibilityProperty: true })) continue;
|
||||
const nextBlock = element.closest(blockTags);
|
||||
if (block !== nextBlock) searchBlock();
|
||||
block = nextBlock;
|
||||
const start = text.length;
|
||||
text += node.data;
|
||||
parts.push({ node, start, end: text.length });
|
||||
}
|
||||
searchBlock();
|
||||
}
|
||||
showSearchMatch(matches.length ? 0 : -1, reveal);
|
||||
}
|
||||
|
||||
function showSearchMatch(index, reveal) {
|
||||
activeMatch = index;
|
||||
searchPrevious.disabled = searchNext.disabled = matches.length < 2;
|
||||
searchStatus.value = !searchQuery.value.trim() ? '' : index < 0 ? 'No matches' : (index + 1) + ' / ' + matches.length;
|
||||
CSS.highlights.delete('markdown-search-active');
|
||||
if (index < 0) return;
|
||||
const [start, from, end, to] = matches[index];
|
||||
const range = new Range();
|
||||
range.setStart(start, from);
|
||||
range.setEnd(end, to);
|
||||
CSS.highlights.set('markdown-search-active', new Highlight(range));
|
||||
if (!reveal) return;
|
||||
const rect = range.getBoundingClientRect();
|
||||
const toolbarBottom = search.parentElement.getBoundingClientRect().bottom;
|
||||
if (rect.top < toolbarBottom || rect.bottom > innerHeight) {
|
||||
scrollBy(0, rect.top - Math.max(toolbarBottom, innerHeight / 2));
|
||||
}
|
||||
const scroller = start.parentElement.closest('pre, table');
|
||||
if (scroller) {
|
||||
const bounds = scroller.getBoundingClientRect();
|
||||
if (rect.left < bounds.left || rect.right > bounds.right) {
|
||||
scroller.scrollLeft += rect.left - bounds.left;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openSearch() {
|
||||
search.hidden = false;
|
||||
searchOpen.setAttribute('aria-expanded', 'true');
|
||||
searchQuery.focus({ preventScroll: true });
|
||||
searchQuery.select();
|
||||
}
|
||||
|
||||
function closeSearch() {
|
||||
if (search.hidden) return false;
|
||||
const hadFocus = search.contains(document.activeElement);
|
||||
search.hidden = true;
|
||||
searchOpen.setAttribute('aria-expanded', 'false');
|
||||
searchQuery.value = '';
|
||||
updateSearch();
|
||||
if (hadFocus) searchOpen.focus({ preventScroll: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
function stepSearch(direction) {
|
||||
if (search.hidden) openSearch();
|
||||
else if (matches.length) showSearchMatch((activeMatch + direction + matches.length) % matches.length, true);
|
||||
}
|
||||
|
||||
searchOpen.addEventListener('click', openSearch);
|
||||
document.querySelector('#search-close').addEventListener('click', closeSearch);
|
||||
searchQuery.addEventListener('input', () => updateSearch());
|
||||
searchPrevious.addEventListener('click', () => stepSearch(-1));
|
||||
searchNext.addEventListener('click', () => stepSearch(1));
|
||||
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
|
||||
|
||||
async function render({ text, fragment, scroll, title, keepPosition }) {
|
||||
const current = ++generation;
|
||||
if (keepPosition) scroll = window.scrollY;
|
||||
else closeSearch();
|
||||
document.documentElement.classList.remove('rendered');
|
||||
document.title = title;
|
||||
renderContent(text);
|
||||
const headings = new Set();
|
||||
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
|
||||
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
||||
let id = base;
|
||||
for (let n = 1; headings.has(id); ++n) id = base + '-' + n;
|
||||
heading.id = id;
|
||||
headings.add(id);
|
||||
}
|
||||
images = Array.from(content.querySelectorAll('img[data-path]'));
|
||||
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
|
||||
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
|
||||
for (const [index, block] of blocks.entries()) {
|
||||
try {
|
||||
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
|
||||
if (current !== generation) return;
|
||||
const figure = document.createElement('figure');
|
||||
figure.innerHTML = svg;
|
||||
block.parentElement.replaceWith(figure);
|
||||
} catch {
|
||||
if (current !== generation) return;
|
||||
const caption = document.createElement('div');
|
||||
caption.textContent = 'Invalid Mermaid diagram';
|
||||
block.parentElement.before(caption);
|
||||
}
|
||||
}
|
||||
restorePosition({ fragment, scroll });
|
||||
document.documentElement.classList.add('rendered');
|
||||
if (!search.hidden) updateSearch(false);
|
||||
send('rendered');
|
||||
}
|
||||
|
||||
content.addEventListener('click', event => {
|
||||
const link = event.target.closest('a');
|
||||
if (!link) return;
|
||||
event.preventDefault();
|
||||
const path = link.getAttribute('href');
|
||||
if (!path || event.ctrlKey || event.metaKey || link.closest('svg')) return;
|
||||
send('link', { path, newWindow: event.shiftKey, scroll: Math.round(window.scrollY) });
|
||||
});
|
||||
|
||||
document.addEventListener('pointerup', event => {
|
||||
if (event.button !== 3 && event.button !== 4) return;
|
||||
event.preventDefault();
|
||||
navigate(event.button === 3 ? 'back' : 'forward');
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.isComposing) return;
|
||||
if (event.ctrlKey && !event.altKey && event.key.toLowerCase() === 'f') {
|
||||
event.preventDefault();
|
||||
openSearch();
|
||||
} else if (event.key === 'F3' || (event.key === 'Enter' && event.target === searchQuery)) {
|
||||
event.preventDefault();
|
||||
stepSearch(event.shiftKey ? -1 : 1);
|
||||
} else if (event.key === 'Escape' && closeSearch()) {
|
||||
event.preventDefault();
|
||||
} else if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
|
||||
event.preventDefault();
|
||||
send('cycle');
|
||||
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
|
||||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
navigate(['ArrowLeft', 'BrowserBack'].includes(event.key) ? 'back' : 'forward');
|
||||
} else if (event.key === 'F6' || event.key === 'Escape' || event.key === 'F10' ||
|
||||
(event.ctrlKey && event.key.toLowerCase() === 'w')) {
|
||||
event.preventDefault();
|
||||
send(event.key === 'F6' ? 'edit' : 'close');
|
||||
}
|
||||
});
|
||||
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
const message = JSON.parse(data);
|
||||
if (message.action === 'clear') {
|
||||
++generation;
|
||||
closeSearch();
|
||||
document.documentElement.classList.remove('rendered');
|
||||
content.replaceChildren();
|
||||
}
|
||||
if (message.action === 'render') void render(message).catch(() => send('failed'));
|
||||
if (message.action === 'appearance') {
|
||||
const style = document.documentElement.style;
|
||||
style.setProperty('--markdown-width', message.width ? message.width + 'px' : 'none');
|
||||
style.setProperty('--markdown-font-size', message.fontSize + 'pt');
|
||||
style.setProperty('--markdown-font', message.font ? CSS.escape(message.font) + ', system-ui, sans-serif' : 'system-ui, sans-serif');
|
||||
}
|
||||
if (message.action === 'anchor') restorePosition(message);
|
||||
if (message.action === 'find') openSearch();
|
||||
if (message.action === 'find-next') stepSearch(message.previous ? -1 : 1);
|
||||
if (message.action === 'escape' && !closeSearch()) send('close');
|
||||
if (message.action === 'back' || message.action === 'forward') navigate(message.action);
|
||||
if (message.action === 'history') {
|
||||
back.disabled = !message.back;
|
||||
forward.disabled = !message.forward;
|
||||
}
|
||||
if (message.action === 'image' && message.generation === generation && images[message.index]) {
|
||||
const image = images[message.index];
|
||||
if (message.source) image.src = message.source;
|
||||
else image.title = 'Image unavailable';
|
||||
}
|
||||
});
|
||||
bridge.postMessage('ready');
|
||||
@@ -3,7 +3,7 @@ const terminal = new Terminal({
|
||||
fontFamily: 'Consolas, monospace',
|
||||
fontSize: 16,
|
||||
cursorBlink: false,
|
||||
stdinDisabled: true,
|
||||
disableStdin: true,
|
||||
theme: { background: '#181818', foreground: '#e8e8e8' },
|
||||
});
|
||||
const fit = new FitAddon.FitAddon();
|
||||
@@ -20,6 +20,7 @@ terminal.parser.registerOscHandler(633, data => {
|
||||
terminal.loadAddon(fit);
|
||||
const host = document.getElementById('terminal');
|
||||
terminal.open(host);
|
||||
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
|
||||
host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true);
|
||||
const screen = host.querySelector('.xterm-screen');
|
||||
let traceEnabled = false;
|
||||
@@ -51,6 +52,11 @@ function anchorOutput() {
|
||||
trace(2);
|
||||
}
|
||||
terminal.attachCustomKeyEventHandler(event => {
|
||||
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
|
||||
if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter');
|
||||
event.preventDefault();
|
||||
return false;
|
||||
}
|
||||
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) return true;
|
||||
if (event.code === 'KeyO') bridge.postMessage('toggle');
|
||||
else if (event.code === 'ArrowUp') bridge.postMessage('grow');
|
||||
@@ -61,6 +67,12 @@ terminal.attachCustomKeyEventHandler(event => {
|
||||
else if (event.key === 'Enter') {
|
||||
if (!event.repeat) bridge.postMessage('insert-name');
|
||||
}
|
||||
else if (event.key === 'Insert') {
|
||||
if (!event.repeat) bridge.postMessage('copy-command-line-or-panel-names');
|
||||
}
|
||||
else if (event.code === 'KeyR') {
|
||||
if (!event.repeat) bridge.postMessage('refresh-panel');
|
||||
}
|
||||
else return true;
|
||||
event.preventDefault();
|
||||
return false;
|
||||
@@ -72,6 +84,15 @@ terminal.onScroll(() => {
|
||||
anchorOutput();
|
||||
});
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
if (data === 'clear-selection') {
|
||||
terminal.clearSelection();
|
||||
return;
|
||||
}
|
||||
if (data === 'scroll-bottom') {
|
||||
terminal.scrollToBottom();
|
||||
anchorOutput();
|
||||
return;
|
||||
}
|
||||
if (data === 'trace:on' || data === 'trace:output') {
|
||||
traceEnabled = true;
|
||||
traceOutput = data === 'trace:output';
|
||||
|
||||
+40
-18
@@ -411,20 +411,50 @@ function Write-Result($Value) {
|
||||
}
|
||||
function Write-UpdateJournal([string]$Message) {
|
||||
if (!$Journal) { return }
|
||||
[IO.File]::AppendAllText($Journal, "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') LAN update: $Message`n",
|
||||
$label = if ($Unattended) { 'LAN update' } else { 'Update' }
|
||||
[IO.File]::AppendAllText($Journal, "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ${label}: $Message`n",
|
||||
[Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
function Stop-UpdateCompanions([string]$Directory) {
|
||||
if (!('KSwitcherUpdateProcessImage' -as [type])) {
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
public static class KSwitcherUpdateProcessImage {
|
||||
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
||||
[DllImport("kernel32.dll", CharSet=CharSet.Unicode)]
|
||||
static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder image, ref int length);
|
||||
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
||||
|
||||
public static string Read(int pid) {
|
||||
var process = OpenProcess(0x1000, false, pid);
|
||||
if (process == IntPtr.Zero) return null;
|
||||
try {
|
||||
var length = 32768;
|
||||
var image = new StringBuilder(length);
|
||||
return QueryFullProcessImageName(process, 0, image, ref length) ? image.ToString() : null;
|
||||
} finally { CloseHandle(process); }
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
$root = [IO.Path]::GetFullPath($Directory).TrimEnd('\')
|
||||
$prefix = [regex]::Escape($root + '\')
|
||||
$pattern = '^' + $prefix + '(?:\.kswitcher-update-[0-9a-f]{32}\\backup\\)?KSwitcher\.(?:Config|Screenshot|Files)\.exe$'
|
||||
foreach ($process in @(Get-Process 'KSwitcher.Config','KSwitcher.Screenshot','KSwitcher.Files' -ErrorAction SilentlyContinue)) {
|
||||
if ($process.Path -notmatch $pattern) { continue }
|
||||
$pattern = '^' + $prefix + '(?:\.kswitcher-update-[0-9a-f]{32}\\backup\\)?(?:KSwitcher(?:\.(?:Config|Screenshot|Files))?\.exe|tools\\StayHere\.exe)$'
|
||||
foreach ($process in @(Get-Process 'KSwitcher','KSwitcher.Config','KSwitcher.Screenshot','KSwitcher.Files','StayHere' -ErrorAction SilentlyContinue)) {
|
||||
$image = [KSwitcherUpdateProcessImage]::Read($process.Id)
|
||||
if (!$image -and !$process.HasExited) {
|
||||
Write-UpdateJournal "Could not identify $($process.ProcessName) (PID $($process.Id))."
|
||||
}
|
||||
if ($image -notmatch $pattern) { continue }
|
||||
Write-UpdateJournal "Closing $($process.ProcessName) (PID $($process.Id))."
|
||||
if (!$process.HasExited) {
|
||||
try { $process.Kill() } catch { if (!$process.HasExited) { throw } }
|
||||
if (!$process.WaitForExit(10000)) { throw "Could not close $($process.ProcessName) (PID $($process.Id))." }
|
||||
}
|
||||
Write-UpdateJournal "Closed $($process.ProcessName) (PID $($process.Id))."
|
||||
}
|
||||
}
|
||||
if ($Library) { return }
|
||||
@@ -463,19 +493,15 @@ try {
|
||||
Assert-Checksum $archive $checksum
|
||||
Show-UpdateProgress 'Preparing installation' 'Validating and unpacking the release files'
|
||||
Expand-Release $archive $stage (Get-StableVersion $release.version)
|
||||
$screenshotPath = [IO.Path]::GetFullPath((Join-Path $InstallDirectory 'KSwitcher.Screenshot.exe'))
|
||||
if (!$Unattended -and (Get-Process 'KSwitcher.Screenshot' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $screenshotPath })) {
|
||||
throw 'Close screenshot editors before installing an update.'
|
||||
}
|
||||
if ($Unattended) {
|
||||
Write-UpdateJournal "Verified $($release.version). Closing KSwitcher (PID $ParentProcessId)."
|
||||
}
|
||||
Write-UpdateJournal "Verified $($release.version). Closing KSwitcher (PID $ParentProcessId)."
|
||||
Write-Result @{state='prepared';version=$release.version}
|
||||
Show-UpdateProgress 'Closing KSwitcher' 'Waiting for the running application to exit safely'
|
||||
$ready.Set() | Out-Null
|
||||
if (!$parentProcess.WaitForExit(120000)) { throw 'KSwitcher did not exit; the installed files were not changed.' }
|
||||
$parentExited = $true
|
||||
if ($Unattended) { Stop-UpdateCompanions $InstallDirectory }
|
||||
Write-UpdateJournal "Closed KSwitcher (PID $ParentProcessId)."
|
||||
Show-UpdateProgress 'Closing KSwitcher components' 'Closing Files, editors, Settings and StayHere'
|
||||
Stop-UpdateCompanions $InstallDirectory
|
||||
Show-UpdateProgress 'Installing update' 'Replacing application files; keeping your personal data'
|
||||
Install-Files $stage $InstallDirectory $backup $changed
|
||||
$startedName = 'Local\KSwitcher.Update.Started.'+[guid]::NewGuid().ToString('N')
|
||||
@@ -484,9 +510,7 @@ try {
|
||||
$child = Start-Process -FilePath (Join-Path $InstallDirectory 'KSwitcher.exe') -ArgumentList "--update-ready-event=$startedName" -WorkingDirectory $InstallDirectory -WindowStyle Hidden -PassThru
|
||||
if (!$started.WaitOne(30000) -or $child.HasExited) { throw 'The updated application did not confirm startup.' }
|
||||
$success = $true
|
||||
if ($Unattended) {
|
||||
try { Write-UpdateJournal "Completed $($release.version). KSwitcher restarted." } catch {}
|
||||
}
|
||||
try { Write-UpdateJournal "Completed $($release.version). KSwitcher restarted." } catch {}
|
||||
if ($script:progressWindow) {
|
||||
$uiFinished = Complete-UpdateProgress 'Update completed' "KSwitcher $(Get-StableVersion $release.version) is now running." $true
|
||||
}
|
||||
@@ -505,9 +529,7 @@ try {
|
||||
}
|
||||
}
|
||||
Write-Result @{state='error';error=$message}
|
||||
if ($Unattended) {
|
||||
try { Write-UpdateJournal "Failed. $($message -replace '[\r\n]+',' ')" } catch {}
|
||||
}
|
||||
try { Write-UpdateJournal "Failed. $($message -replace '[\r\n]+',' ')" } catch {}
|
||||
if (!$Unattended -and $ready -and $ready.WaitOne(0)) {
|
||||
if ($script:progressWindow) {
|
||||
$uiFinished = Complete-UpdateProgress 'Update failed' $message $false
|
||||
|
||||
+60
-34
@@ -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;
|
||||
@@ -2942,11 +2960,6 @@ void App::trayMenu()
|
||||
void App::checkUpdate(bool interactive, bool install, const std::wstring &version)
|
||||
{
|
||||
if (updateRunning) return;
|
||||
if (install && interactive && FindWindowW(L"KSwitcher.Config", nullptr))
|
||||
{
|
||||
report(L"Close the configurator before installing an update.");
|
||||
return;
|
||||
}
|
||||
if (install && interactive && busy)
|
||||
{
|
||||
report(L"Wait for the current text operation to finish, then select Update again.");
|
||||
@@ -3010,7 +3023,13 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
case LanUpdateRequestedMessage:
|
||||
if (!lan::remoteUpdateAllowed()) return 0;
|
||||
if (app->updateRunning)
|
||||
log(L"LAN update request ignored because an update is already running.");
|
||||
{
|
||||
if (!app->installingUpdate)
|
||||
{
|
||||
app->lanUpdatePending = true;
|
||||
log(L"LAN update queued behind an update check.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
log(L"Starting unattended KSwitcher update requested over LAN.");
|
||||
@@ -3030,13 +3049,20 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
// The helper has verified and staged the package; it waits for process exit.
|
||||
DestroyWindow(hwnd);
|
||||
}
|
||||
else if (std::exchange(app->lanUpdatePending, false) && lan::remoteUpdateAllowed() &&
|
||||
result->state != L"current")
|
||||
{
|
||||
log(L"Starting queued unattended KSwitcher update.");
|
||||
app->checkUpdate(false, true);
|
||||
}
|
||||
else if (result->state == L"available")
|
||||
{
|
||||
app->availableUpdate = result->version;
|
||||
if (result->interactive)
|
||||
{
|
||||
auto prompt = L"Install KSwitcher " + result->version +
|
||||
L"?\n\nThe program will close and restart. Settings, history and existing dictionaries are preserved.";
|
||||
L"?\n\nKSwitcher will restart after closing Files, editors, Settings and StayHere from this installation. "
|
||||
L"Save any unsaved work before continuing.";
|
||||
if (MessageBoxW(hwnd, prompt.c_str(), L"KSwitcher Update", MB_YESNO | MB_ICONQUESTION) == IDYES)
|
||||
app->checkUpdate(true, true, result->version);
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@ class App
|
||||
std::vector<SyncConflict> pendingSyncConflicts;
|
||||
Bytes syncSnapshot;
|
||||
std::wstring syncStatus = L"Not connected.";
|
||||
bool updateRunning{}, installingUpdate{};
|
||||
bool updateRunning{}, installingUpdate{}, lanUpdatePending{};
|
||||
std::wstring availableUpdate, notifiedUpdate;
|
||||
bool (*updateNotifier)(const std::wstring &){};
|
||||
bool stop{};
|
||||
@@ -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);
|
||||
|
||||
+1
-1
@@ -78,7 +78,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;
|
||||
|
||||
@@ -12,7 +12,7 @@ bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
const bool function=key>=VK_F1 && key<=VK_F12;
|
||||
if(!letter && !function) return false;
|
||||
if(modifiers==HOTKEYF_CONTROL)
|
||||
return (letter && key!='C' && key!='F' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
|
||||
return (letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
|
||||
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
|
||||
return false;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
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);
|
||||
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});
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
+1114
-496
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
template<class Index, class Selectable>
|
||||
Index adjacentMenuRow(Index current, Index size, int direction, Selectable selectable)
|
||||
{
|
||||
auto row=current;
|
||||
for(Index visited=0;visited<size;++visited)
|
||||
{
|
||||
row+=direction;
|
||||
if(row<0) row=size-1;
|
||||
if(row>=size) row=0;
|
||||
if(selectable(row)) return row;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
}
|
||||
+104
-11
@@ -19,6 +19,9 @@ constexpr int textTabWidth=357,textLineEnding=359,
|
||||
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
|
||||
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme};
|
||||
constexpr int editingControls[]{354,355,358,textLineEnding};
|
||||
constexpr int markdownSection=1,markdownWidth=374,markdownFamily=376,markdownChoose=377,markdownSize=379;
|
||||
constexpr int markdownControls[]{373,markdownWidth,375,markdownFamily,markdownChoose,378,markdownSize};
|
||||
constexpr wchar_t optionsLocationKey[]=L"OptionsLocation";
|
||||
constexpr struct
|
||||
{
|
||||
int id;
|
||||
@@ -102,7 +105,9 @@ struct OptionsDraft
|
||||
int styleIndex=0;
|
||||
bool styleSuggestionsLoaded{};
|
||||
int page=PanelModes, section=PanelLayout;
|
||||
HTREEITEM wideColumnsNode{};
|
||||
DWORD location{};
|
||||
int markdownError{};
|
||||
HTREEITEM wideColumnsNode{},markdownNode{};
|
||||
RECT initialClient{};
|
||||
UINT initialDpi=96;
|
||||
OptionsControl controls[8]{
|
||||
@@ -150,7 +155,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
DWORD fields=0;
|
||||
for(int i=0;i<4;++i) if(checked(205+i)) fields|=1u<<i;
|
||||
const auto &base=draft.baseline;
|
||||
const bool dirty=!valid || width!=base.width ||
|
||||
const bool dirty=!valid || draft.markdownError || width!=base.width ||
|
||||
checked(273)!=base.wide[0] || checked(274)!=base.wide[1] ||
|
||||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
|
||||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
|
||||
@@ -333,9 +338,31 @@ void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const k
|
||||
refreshTextColor(dialog,profile);
|
||||
}
|
||||
|
||||
void showMarkdownOptions(HWND dialog,const ks::files::MarkdownPreferences &settings)
|
||||
{
|
||||
// SetDlgItemText sends EN_CHANGE synchronously, so take a snapshot first.
|
||||
const auto values=settings;
|
||||
SetDlgItemInt(dialog,markdownWidth,values.width,FALSE);
|
||||
SetDlgItemInt(dialog,markdownSize,values.fontSize,FALSE);
|
||||
SetDlgItemTextW(dialog,markdownFamily,values.font.c_str());
|
||||
}
|
||||
|
||||
int readMarkdownOptions(HWND dialog,ks::files::MarkdownPreferences &settings)
|
||||
{
|
||||
BOOL widthValid{}, sizeValid{};
|
||||
const auto width=GetDlgItemInt(dialog,markdownWidth,&widthValid,FALSE);
|
||||
const auto size=GetDlgItemInt(dialog,markdownSize,&sizeValid,FALSE);
|
||||
if(!widthValid || width>999999) return markdownWidth;
|
||||
if(!sizeValid || size<8 || size>72) return markdownSize;
|
||||
wchar_t font[LF_FACESIZE]{};
|
||||
GetDlgItemTextW(dialog,markdownFamily,font,std::size(font));
|
||||
settings={width,size,font};
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
{
|
||||
if(!textOptionsPage(draft.page)) return false;
|
||||
if(!textOptionsPage(draft.page) || (draft.page==TextViewer && draft.section==markdownSection)) return false;
|
||||
auto &profile=draft.text.profiles[draft.page==TextEditor];
|
||||
const auto id=LOWORD(command);
|
||||
const auto row=[&](int control){return SendDlgItemMessageW(dialog,control,CB_GETCURSEL,0,0);};
|
||||
@@ -386,12 +413,14 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
{
|
||||
draft.page=page;
|
||||
draft.section=section;
|
||||
const bool markdown=page==TextViewer && section==markdownSection;
|
||||
const wchar_t *title=L"No matching settings";
|
||||
if(page==allOptions) title=L"All settings";
|
||||
else if(page>=0)
|
||||
{
|
||||
title=optionsTitles[page];
|
||||
if(section>=0 && !textOptionsPage(page))
|
||||
if(markdown) title=L"Markdown";
|
||||
else if(section>=0 && !textOptionsPage(page))
|
||||
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
|
||||
(section==fileStyleSection?L"File type styles":colorNames[section]):
|
||||
page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font";
|
||||
@@ -430,9 +459,10 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
}
|
||||
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
|
||||
show(commandLineControls,page==CommandLine && section==0);
|
||||
show(textControls,textOptionsPage(page));
|
||||
show(markdownControls,markdown);
|
||||
show(textControls,textOptionsPage(page) && !markdown);
|
||||
show(editingControls,page==TextEditor);
|
||||
if(textOptionsPage(page)) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
|
||||
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
|
||||
const bool fileTypes=page==PanelColors && section==fileStyleSection;
|
||||
constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState};
|
||||
show(fileStyleControls,fileTypes);
|
||||
@@ -491,6 +521,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
const int previousPage=draft.page,previousSection=draft.section;
|
||||
TreeView_DeleteAllItems(tree);
|
||||
draft.wideColumnsNode=nullptr;
|
||||
draft.markdownNode=nullptr;
|
||||
const auto root=add(L"All settings",allOptions,-1,TVI_ROOT);
|
||||
HTREEITEM first{},selected{};
|
||||
for(int page=PanelModes;page<allOptions;++page)
|
||||
@@ -500,11 +531,16 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
const auto addSection=[&](const wchar_t *label,int section,bool aliasMatches=false)
|
||||
{
|
||||
if(!wholeCategory && !aliasMatches && !matches(label)) return;
|
||||
if(!category) category=add(optionsTitles[page],page,-1,root);
|
||||
if(!category)
|
||||
{
|
||||
category=add(optionsTitles[page],page,-1,root);
|
||||
if(page==previousPage && previousSection<0) selected=category;
|
||||
}
|
||||
const auto node=add(label,page,section,category);
|
||||
if(!first) first=node;
|
||||
if(page==previousPage && section==previousSection) selected=node;
|
||||
if(page==PanelModes && section==WideColumns) draft.wideColumnsNode=node;
|
||||
if(page==TextViewer && section==markdownSection) draft.markdownNode=node;
|
||||
};
|
||||
if(page==PanelModes)
|
||||
{
|
||||
@@ -535,6 +571,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
{return (page==TextEditor || check.id<354) && matches(check.name);}) ||
|
||||
std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches);
|
||||
addSection(page==TextEditor?L"Editing and appearance":L"Viewing and appearance",0,propertyMatches);
|
||||
if(page==TextViewer) addSection(L"Markdown",markdownSection,
|
||||
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size"));
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -569,6 +607,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
|
||||
SendDlgItemMessageW(dialog,201,EM_SETLIMITTEXT,2,0);
|
||||
SendDlgItemMessageW(dialog,markdownWidth,EM_SETLIMITTEXT,6,0);
|
||||
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
|
||||
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
|
||||
showMarkdownOptions(dialog,draft.text.markdown);
|
||||
SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0);
|
||||
for(const auto &option:frameOptions)
|
||||
for(DWORD value=0;value<=option.maximum;++value)
|
||||
@@ -626,7 +668,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
const auto &change=*reinterpret_cast<const NMTREEVIEWW*>(lp);
|
||||
if(change.hdr.code==TVN_SELCHANGEDW && change.itemNew.hItem)
|
||||
showOptionsPage(dialog,*draft,static_cast<int>(change.itemNew.lParam>>8),static_cast<int>(change.itemNew.lParam&255)-1);
|
||||
{
|
||||
const auto page=static_cast<int>(change.itemNew.lParam>>8);
|
||||
if(page!=allOptions || !GetWindowTextLengthW(GetDlgItem(dialog,optionsSearch)))
|
||||
draft->location=static_cast<DWORD>(change.itemNew.lParam);
|
||||
showOptionsPage(dialog,*draft,page,static_cast<int>(change.itemNew.lParam&255)-1);
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
@@ -654,6 +701,27 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
showOptionsPage(dialog,*draft,Appearance,Font);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case markdownWidth: case markdownSize: case markdownFamily:
|
||||
if(HIWORD(wp)==EN_CHANGE)
|
||||
{
|
||||
draft->markdownError=readMarkdownOptions(dialog,draft->text.markdown);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
case markdownChoose:
|
||||
{
|
||||
LOGFONTW font{};
|
||||
const auto &settings=draft->text.markdown;
|
||||
wcsncpy_s(font.lfFaceName,settings.font.empty()?L"Segoe UI":settings.font.c_str(),_TRUNCATE);
|
||||
auto size=static_cast<int>(settings.fontSize)*10;
|
||||
font.lfHeight=-MulDiv(size,GetDpiForWindow(dialog),720);
|
||||
if(chooseDisplayFont(dialog,font,size,72))
|
||||
{
|
||||
SetDlgItemTextW(dialog,markdownFamily,font.lfFaceName);
|
||||
SetDlgItemInt(dialog,markdownSize,(size+5)/10,FALSE);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
case outerFramePadding: case innerFramePadding: case rowTextPadding:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE)
|
||||
{
|
||||
@@ -731,8 +799,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
draft->framePadding=defaultDialogFramePadding;
|
||||
if(draft->page==allOptions || textOptionsPage(draft->page))
|
||||
for(int page=TextViewer;page<=TextEditor;++page)
|
||||
if(draft->page==allOptions || draft->page==page)
|
||||
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
|
||||
draft->text.profiles[page==TextEditor]=ks::files::TextPreferences{};
|
||||
if(draft->page==allOptions || (draft->page==TextViewer && (draft->section<0 || draft->section==markdownSection)))
|
||||
showMarkdownOptions(dialog,ks::files::MarkdownPreferences{});
|
||||
showOptionsPage(dialog,*draft,draft->page,draft->section);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
@@ -759,6 +829,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
case optionsApply:
|
||||
case IDOK:
|
||||
{
|
||||
if(draft->markdownError)
|
||||
{
|
||||
if(!draft->markdownNode) SetDlgItemTextW(dialog,optionsSearch,L"");
|
||||
TreeView_SelectItem(GetDlgItem(dialog,optionsTree),draft->markdownNode);
|
||||
showFilesNotice(dialog,L"Enter a width in pixels (0 for full window) and a font size from 8 to 72 pt.",L"Markdown");
|
||||
SetFocus(GetDlgItem(dialog,draft->markdownError));
|
||||
return TRUE;
|
||||
}
|
||||
BOOL valid{};
|
||||
const auto width=GetDlgItemInt(dialog,201,&valid,FALSE);
|
||||
if(!valid || width<6 || width>16)
|
||||
@@ -780,6 +858,16 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto &base=draft->baseline;
|
||||
const bool textChanged=draft->text!=base.text;
|
||||
auto textSettings=ks::files::loadTextPreferences();
|
||||
if(draft->text.markdown!=base.text.markdown)
|
||||
{
|
||||
if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown)
|
||||
{
|
||||
showFilesNotice(dialog,L"Markdown settings changed in another window. Reopen Options before editing them again.",
|
||||
L"KSwitcher Files Options");
|
||||
return TRUE;
|
||||
}
|
||||
textSettings.markdown=draft->text.markdown;
|
||||
}
|
||||
for(size_t i=0;i<textSettings.profiles.size();++i)
|
||||
{
|
||||
if(draft->text.profiles[i]==base.text.profiles[i]) continue;
|
||||
@@ -884,6 +972,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
SendMessageW(dialogOwner,filesPreferencesChanged,reinterpret_cast<WPARAM>(owner),0);
|
||||
draft->baseline=OptionsBaseline{};
|
||||
draft->text=draft->baseline.text;
|
||||
showMarkdownOptions(dialog,draft->text.markdown);
|
||||
populateTextSchemes(dialog,draft->text);
|
||||
draft->font=displayFont;
|
||||
draft->points=fontPoints;
|
||||
@@ -919,12 +1008,16 @@ void runOptions(HWND owner,int page)
|
||||
{
|
||||
OptionsDraft draft;
|
||||
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
|
||||
draft.page=page;
|
||||
draft.section=textOptionsPage(page)?0:PanelLayout;
|
||||
const DWORD initial=static_cast<DWORD>((page<<8)|1);
|
||||
const auto saved=preference(optionsLocationKey,initial);
|
||||
draft.location=(saved>>8)<=allOptions?saved:initial;
|
||||
draft.page=static_cast<int>(draft.location>>8);
|
||||
draft.section=static_cast<int>(draft.location&255)-1;
|
||||
std::copy(std::begin(colors),std::end(colors),draft.palette.begin());
|
||||
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog,
|
||||
reinterpret_cast<LPARAM>(&draft));
|
||||
if(result==-1) setStatus(L"Could not open Files Options.");
|
||||
else savePreference(optionsLocationKey,draft.location);
|
||||
}
|
||||
|
||||
void editOptions(HWND owner)
|
||||
|
||||
+62
-21
@@ -8,8 +8,10 @@ __CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4
|
||||
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
|
||||
__CRT_UUID_DECL(ICoreWebView2NewWindowRequestedEventHandler, 0xd4c185fe, 0xc81c, 0x4989, 0x97, 0xaf, 0x2d, 0x3f, 0xa7, 0xab, 0x56, 0x51)
|
||||
__CRT_UUID_DECL(ICoreWebView2NavigationStartingEventHandler, 0x9adbe429, 0xf36d, 0x432b, 0x9d, 0xdc, 0xf8, 0x88, 0x1f, 0xbd, 0x76, 0xe3)
|
||||
__CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa79, 0x41a8, 0x8e, 0x44, 0x65, 0x81, 0x1c, 0x76, 0xdc, 0xb2)
|
||||
#endif
|
||||
#include <wrl/client.h>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
@@ -50,11 +52,20 @@ class FilesTerminalView
|
||||
{
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2Controller> controller;
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2> web;
|
||||
HMODULE loader{};
|
||||
std::shared_ptr<int> lifetime;
|
||||
RECT bounds{};
|
||||
bool ready{};
|
||||
bool visible{};
|
||||
int viewportHeight{};
|
||||
public:
|
||||
~FilesTerminalView() { close(); }
|
||||
void focus()
|
||||
{
|
||||
if(controller) controller->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
|
||||
}
|
||||
void post(const std::wstring &message)
|
||||
{
|
||||
if(ready) web->PostWebMessageAsString(message.c_str());
|
||||
}
|
||||
bool initialized() const { return ready; }
|
||||
void enableTrace(bool output)
|
||||
{
|
||||
@@ -70,12 +81,16 @@ public:
|
||||
}
|
||||
void layout(HWND host,bool show,int fullHeight)
|
||||
{
|
||||
RECT area{};
|
||||
GetClientRect(host,&area);
|
||||
area.top=area.bottom-fullHeight;
|
||||
layout(area,show);
|
||||
}
|
||||
void layout(RECT area,bool show)
|
||||
{
|
||||
bounds=area;
|
||||
visible=show;
|
||||
viewportHeight=fullHeight;
|
||||
if(!controller) return;
|
||||
RECT bounds{};
|
||||
GetClientRect(host,&bounds);
|
||||
bounds.top=bounds.bottom-viewportHeight;
|
||||
RECT current{};
|
||||
if(FAILED(controller->get_Bounds(¤t)) || !EqualRect(¤t,&bounds))
|
||||
controller->put_Bounds(bounds);
|
||||
@@ -85,6 +100,7 @@ public:
|
||||
}
|
||||
void close()
|
||||
{
|
||||
lifetime.reset();
|
||||
if(controller) controller->Close();
|
||||
web.Reset();
|
||||
controller.Reset();
|
||||
@@ -103,12 +119,13 @@ public:
|
||||
}
|
||||
return SUCCEEDED(web->PostWebMessageAsString(message.c_str()));
|
||||
}
|
||||
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed)
|
||||
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed,
|
||||
bool markdown=false,std::function<bool(UINT)> handleKey={})
|
||||
{
|
||||
wchar_t exe[MAX_PATH]{};
|
||||
if(!GetModuleFileNameW(nullptr,exe,MAX_PATH)) return false;
|
||||
const auto folder=std::filesystem::path(exe).parent_path();
|
||||
loader=LoadLibraryExW((folder/L"WebView2Loader.dll").c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
static const auto loader=LoadLibraryExW((folder/L"WebView2Loader.dll").c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
if(!loader) return false;
|
||||
using Create=HRESULT (STDAPICALLTYPE*)(PCWSTR,PCWSTR,ICoreWebView2EnvironmentOptions*,
|
||||
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
|
||||
@@ -118,23 +135,28 @@ public:
|
||||
wchar_t local[MAX_PATH]{};
|
||||
const auto length=GetEnvironmentVariableW(L"LOCALAPPDATA",local,MAX_PATH);
|
||||
if(!length || length>=MAX_PATH) return false;
|
||||
const auto profile=std::filesystem::path(local)/L"KSwitcher"/L"TerminalWebView";
|
||||
const auto profile=std::filesystem::path(local)/L"KSwitcher"/(markdown?L"MarkdownWebView":L"TerminalWebView");
|
||||
const auto origin=markdown?L"kswitcher-markdown.invalid":L"kswitcher-terminal.invalid";
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
|
||||
const auto assets=folder/L"terminal";
|
||||
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
|
||||
lifetime=std::make_shared<int>(0);
|
||||
const std::weak_ptr<int> alive=lifetime;
|
||||
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
|
||||
HRESULT,ICoreWebView2Environment*>([=,this](HRESULT hr,ICoreWebView2Environment *env)
|
||||
{
|
||||
if(!IsWindow(host)) return S_OK;
|
||||
if(alive.expired()) return S_OK;
|
||||
if(FAILED(hr) || !env) { failed(); return S_OK; }
|
||||
auto completed=terminalCallback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler,
|
||||
HRESULT,ICoreWebView2Controller*>([=,this](HRESULT result,ICoreWebView2Controller *view)
|
||||
{
|
||||
if(!IsWindow(host)) return S_OK;
|
||||
if(alive.expired()) return S_OK;
|
||||
if(FAILED(result) || !view) { failed(); return S_OK; }
|
||||
controller=view;
|
||||
view->get_CoreWebView2(&web);
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
|
||||
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
|
||||
L"kswitcher-terminal.invalid",assets.c_str(),COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY)))
|
||||
origin,assets.c_str(),COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY)))
|
||||
{ failed(); return S_OK; }
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2Settings> settings;
|
||||
if(SUCCEEDED(web->get_Settings(&settings)))
|
||||
@@ -144,14 +166,32 @@ public:
|
||||
settings->put_AreHostObjectsAllowed(FALSE);
|
||||
}
|
||||
EventRegistrationToken token{};
|
||||
auto navigation=terminalCallback<ICoreWebView2NavigationStartingEventHandler,
|
||||
ICoreWebView2*,ICoreWebView2NavigationStartingEventArgs*>([](auto*,auto *args)
|
||||
if(handleKey)
|
||||
{
|
||||
PWSTR uri{};
|
||||
if(SUCCEEDED(args->get_Uri(&uri)))
|
||||
auto accelerator=terminalCallback<ICoreWebView2AcceleratorKeyPressedEventHandler,
|
||||
ICoreWebView2Controller*,ICoreWebView2AcceleratorKeyPressedEventArgs*>(
|
||||
[alive,handleKey](auto*,auto *args)
|
||||
{
|
||||
COREWEBVIEW2_KEY_EVENT_KIND kind{};
|
||||
UINT key{};
|
||||
if(!alive.expired() && SUCCEEDED(args->get_KeyEventKind(&kind)) &&
|
||||
(kind==COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN ||
|
||||
kind==COREWEBVIEW2_KEY_EVENT_KIND_SYSTEM_KEY_DOWN) &&
|
||||
SUCCEEDED(args->get_VirtualKey(&key)) && handleKey(key))
|
||||
args->put_Handled(TRUE);
|
||||
return S_OK;
|
||||
});
|
||||
if(FAILED(view->add_AcceleratorKeyPressed(accelerator.Get(),&token)))
|
||||
{ failed(); return S_OK; }
|
||||
}
|
||||
auto navigation=terminalCallback<ICoreWebView2NavigationStartingEventHandler,
|
||||
ICoreWebView2*,ICoreWebView2NavigationStartingEventArgs*>([uri](auto*,auto *args)
|
||||
{
|
||||
PWSTR address{};
|
||||
if(SUCCEEDED(args->get_Uri(&address)))
|
||||
{
|
||||
args->put_Cancel(wcscmp(uri,L"https://kswitcher-terminal.invalid/index.html")!=0);
|
||||
CoTaskMemFree(uri);
|
||||
args->put_Cancel(uri!=address);
|
||||
CoTaskMemFree(address);
|
||||
}
|
||||
return S_OK;
|
||||
});
|
||||
@@ -161,9 +201,10 @@ public:
|
||||
auto messages=terminalCallback<ICoreWebView2WebMessageReceivedEventHandler,
|
||||
ICoreWebView2*,ICoreWebView2WebMessageReceivedEventArgs*>([=,this](auto*,auto *args)
|
||||
{
|
||||
if(alive.expired()) return S_OK;
|
||||
PWSTR source{}, value{};
|
||||
if(SUCCEEDED(args->get_Source(&source)) &&
|
||||
wcscmp(source,L"https://kswitcher-terminal.invalid/index.html")==0 &&
|
||||
uri==source &&
|
||||
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
|
||||
{
|
||||
if(wcscmp(value,L"ready")==0) ready=true;
|
||||
@@ -176,9 +217,9 @@ public:
|
||||
if(FAILED(web->add_NavigationStarting(navigation.Get(),&token)) ||
|
||||
FAILED(web->add_NewWindowRequested(newWindow.Get(),&token)) ||
|
||||
FAILED(web->add_WebMessageReceived(messages.Get(),&token)) ||
|
||||
FAILED(web->Navigate(L"https://kswitcher-terminal.invalid/index.html")))
|
||||
FAILED(web->Navigate(uri.c_str())))
|
||||
failed();
|
||||
layout(host,visible,viewportHeight);
|
||||
layout(bounds,visible);
|
||||
return S_OK;
|
||||
});
|
||||
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
|
||||
|
||||
@@ -147,13 +147,21 @@ uint64_t TextDocument::pages() const
|
||||
}
|
||||
|
||||
uint64_t TextDocument::boundary(uint64_t page) const
|
||||
{
|
||||
if (!page) return bom_;
|
||||
if (page >= pages()) return size_;
|
||||
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
|
||||
return boundary(page,source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_);
|
||||
}
|
||||
|
||||
uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
|
||||
{
|
||||
if (!page) return bom_;
|
||||
if (page >= pages()) return size_;
|
||||
|
||||
const auto offset = bom_ + page * pageBytes;
|
||||
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
|
||||
const auto sample = read(source_, offset - unit,
|
||||
const auto sample = read(source, offset - unit,
|
||||
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
|
||||
const auto getUnit = [&](size_t i) -> unsigned {
|
||||
const auto first = static_cast<unsigned char>(sample[i]);
|
||||
@@ -224,8 +232,16 @@ std::string TextDocument::readPage(uint64_t page) const
|
||||
|
||||
std::string TextDocument::readOriginal(uint64_t page) const
|
||||
{
|
||||
const auto start = boundary(page);
|
||||
return decode(read(source_, start, static_cast<size_t>(boundary(page + 1) - start)));
|
||||
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
|
||||
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
|
||||
const auto start = boundary(page,source);
|
||||
return decode(read(source, start, static_cast<size_t>(boundary(page + 1,source) - start)));
|
||||
}
|
||||
|
||||
void TextDocument::releaseReadHandle()
|
||||
{
|
||||
if(!editable_ && source_!=INVALID_HANDLE_VALUE)
|
||||
CloseHandle(std::exchange(source_,INVALID_HANDLE_VALUE));
|
||||
}
|
||||
|
||||
bool TextDocument::modifiedWith(uint64_t page, std::string_view current) const
|
||||
|
||||
@@ -24,6 +24,7 @@ public:
|
||||
uint64_t size() const { return size_; }
|
||||
uint64_t boundary(uint64_t page) const;
|
||||
std::string readPage(uint64_t page) const;
|
||||
void releaseReadHandle();
|
||||
void stage(uint64_t page, std::string_view utf8);
|
||||
bool modified() const { return !changes_.empty(); }
|
||||
bool modifiedWith(uint64_t page, std::string_view current) const;
|
||||
@@ -44,6 +45,7 @@ private:
|
||||
std::map<uint64_t, Change> changes_;
|
||||
|
||||
std::string decode(std::string bytes) const;
|
||||
uint64_t boundary(uint64_t page,HANDLE source) const;
|
||||
std::string readOriginal(uint64_t page) const;
|
||||
std::string encode(std::string_view utf8) const;
|
||||
};
|
||||
|
||||
@@ -44,10 +44,18 @@ struct NamedTextPalette
|
||||
};
|
||||
inline constexpr size_t maxTextPalettes = 48;
|
||||
inline constexpr size_t maxTextPaletteName = 48;
|
||||
struct MarkdownPreferences
|
||||
{
|
||||
unsigned width{960}, fontSize{12};
|
||||
std::wstring font;
|
||||
bool operator==(const MarkdownPreferences &) const = default;
|
||||
};
|
||||
|
||||
struct TextSettings
|
||||
{
|
||||
TextPreferencesSet profiles;
|
||||
std::vector<NamedTextPalette> schemes;
|
||||
MarkdownPreferences markdown;
|
||||
bool operator==(const TextSettings &) const = default;
|
||||
};
|
||||
TextSettings loadTextPreferences();
|
||||
|
||||
+737
-33
File diff suppressed because it is too large.
Load diff
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::lan { struct FilesPeer; }
|
||||
@@ -51,6 +52,7 @@ struct TextDialogs
|
||||
};
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer=nullptr);
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false);
|
||||
void textWindowOwnerClosed();
|
||||
bool cycleTextWindows(HWND current);
|
||||
}
|
||||
+35
-13
@@ -305,10 +305,15 @@ struct LanService::Impl
|
||||
std::lock_guard lock(mutex);
|
||||
if(shareInput&&trusted.contains(target)&&peers.contains(target))send(socket,peers.at(target).address,packet);
|
||||
});
|
||||
const bool filesListening=files.port()!=0;
|
||||
if(!filesListening) diagnosticEvent(L"LAN Files could not listen on TCP 45885.");
|
||||
bool filesListening=files.port()!=0;
|
||||
while(!stopping)
|
||||
{
|
||||
files.poll();
|
||||
if(filesListening!=(files.port()!=0))
|
||||
{
|
||||
filesListening=files.port()!=0;
|
||||
nextHello=0;
|
||||
}
|
||||
auto now=GetTickCount64();bool clipboardActive=false;
|
||||
std::vector<lan::InputEndpoint> endpoints;
|
||||
{
|
||||
@@ -346,7 +351,6 @@ struct LanService::Impl
|
||||
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
|
||||
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
|
||||
hub.poll(endpoints,out,in,now);
|
||||
files.poll();
|
||||
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
|
||||
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
|
||||
for(auto &frame:in){
|
||||
@@ -388,8 +392,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")
|
||||
{
|
||||
@@ -399,7 +405,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")
|
||||
@@ -413,12 +419,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.");
|
||||
@@ -428,6 +439,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}});
|
||||
}
|
||||
@@ -459,16 +473,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
@@ -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;}
|
||||
|
||||
+73
-16
@@ -7,6 +7,7 @@
|
||||
#include <bcrypt.h>
|
||||
#include <wincrypt.h>
|
||||
#include <sddl.h>
|
||||
#include <winsafer.h>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
@@ -257,6 +258,40 @@ DWORD requestSystemHibernate()
|
||||
return GetExitCodeProcess(process.value,&exitCode)?exitCode:GetLastError();
|
||||
}
|
||||
|
||||
DWORD restrictElevatedCommandToken(HANDLE token,FileHandle &restricted)
|
||||
{
|
||||
// A synthetic LUA token made directly from an elevated token can fail to
|
||||
// initialize KernelBase when the child starts without a console window.
|
||||
SAFER_LEVEL_HANDLE level{};
|
||||
if(!SaferCreateLevel(SAFER_SCOPEID_USER,SAFER_LEVELID_NORMALUSER,SAFER_LEVEL_OPEN,&level,nullptr))
|
||||
return GetLastError();
|
||||
const auto filtered=SaferComputeTokenFromLevel(level,token,&restricted.value,0,nullptr);
|
||||
const auto filterError=GetLastError();
|
||||
SaferCloseLevel(level);
|
||||
if(!filtered) return filterError;
|
||||
|
||||
// Preserve DISABLE_MAX_PRIVILEGE without creating a second filtered token.
|
||||
LUID changeNotify{};
|
||||
if(!LookupPrivilegeValueW(nullptr,SE_CHANGE_NOTIFY_NAME,&changeNotify)) return GetLastError();
|
||||
DWORD size{};
|
||||
if(!GetTokenInformation(restricted.value,TokenPrivileges,nullptr,0,&size) &&
|
||||
GetLastError()!=ERROR_INSUFFICIENT_BUFFER) return GetLastError();
|
||||
std::vector<BYTE> storage(size);
|
||||
const auto privileges=reinterpret_cast<TOKEN_PRIVILEGES *>(storage.data());
|
||||
if(!GetTokenInformation(restricted.value,TokenPrivileges,privileges,size,&size)) return GetLastError();
|
||||
DWORD removed{};
|
||||
for(DWORD i=0;i<privileges->PrivilegeCount;++i)
|
||||
{
|
||||
const auto &luid=privileges->Privileges[i].Luid;
|
||||
if(luid.LowPart!=changeNotify.LowPart || luid.HighPart!=changeNotify.HighPart)
|
||||
privileges->Privileges[removed++]={luid,SE_PRIVILEGE_REMOVED};
|
||||
}
|
||||
if(!removed) return ERROR_SUCCESS;
|
||||
privileges->PrivilegeCount=removed;
|
||||
AdjustTokenPrivileges(restricted.value,FALSE,privileges,0,nullptr,nullptr);
|
||||
return GetLastError();
|
||||
}
|
||||
|
||||
struct RemoteCommand
|
||||
{
|
||||
FileHandle job,process,output;
|
||||
@@ -294,9 +329,17 @@ struct RemoteCommand
|
||||
|
||||
FileHandle token,restricted,read,write,input,processJob;
|
||||
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|
|
||||
TOKEN_ADJUST_DEFAULT,&token.value) ||
|
||||
!CreateRestrictedToken(token.value,DISABLE_MAX_PRIVILEGE|LUA_TOKEN,0,nullptr,0,nullptr,0,nullptr,
|
||||
&restricted.value)) return GetLastError();
|
||||
TOKEN_ADJUST_DEFAULT,&token.value)) return GetLastError();
|
||||
TOKEN_ELEVATION elevation{};
|
||||
DWORD elevationSize{};
|
||||
if(!GetTokenInformation(token.value,TokenElevation,&elevation,sizeof(elevation),&elevationSize))
|
||||
return GetLastError();
|
||||
if(elevation.TokenIsElevated)
|
||||
{
|
||||
if(const auto error=restrictElevatedCommandToken(token.value,restricted)) return error;
|
||||
}
|
||||
else if(!CreateRestrictedToken(token.value,DISABLE_MAX_PRIVILEGE|LUA_TOKEN,0,nullptr,0,nullptr,0,nullptr,
|
||||
&restricted.value)) return GetLastError();
|
||||
PSID medium{};
|
||||
if(!ConvertStringSidToSidW(L"S-1-16-8192",&medium)) return GetLastError();
|
||||
TOKEN_MANDATORY_LABEL label{{medium,SE_GROUP_INTEGRITY}};
|
||||
@@ -1031,30 +1074,43 @@ struct FilesListener::Impl
|
||||
HostAction hibernate,update;
|
||||
WinSocket listener;
|
||||
std::vector<std::unique_ptr<Client>> clients;
|
||||
uint16_t boundPort{};
|
||||
uint16_t requestedPort{},boundPort{};
|
||||
ULONGLONG nextBind{};
|
||||
DWORD lastBindError{};
|
||||
Impl(std::string id,PairKey lookup,uint16_t port,TerminalPermission permission,HostAction hibernateAction,
|
||||
HostAction updateAction):
|
||||
local(std::move(id)),key(std::move(lookup)),terminalPermission(std::move(permission)),
|
||||
hibernate(std::move(hibernateAction)),update(std::move(updateAction))
|
||||
hibernate(std::move(hibernateAction)),update(std::move(updateAction)),requestedPort(port)
|
||||
{
|
||||
listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
|
||||
if(listener.value==INVALID_SOCKET) return;
|
||||
bindListener();
|
||||
}
|
||||
void bindListener()
|
||||
{
|
||||
nextBind=GetTickCount64()+1000;
|
||||
WinSocket candidate{socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)};
|
||||
BOOL exclusive=TRUE;
|
||||
u_long mode=1;
|
||||
sockaddr_in address{};
|
||||
address.sin_family=AF_INET;
|
||||
address.sin_port=htons(port);
|
||||
if(setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
|
||||
ioctlsocket(listener.value,FIONBIO,&mode) ||
|
||||
bind(listener.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) ||
|
||||
listen(listener.value,8))
|
||||
address.sin_port=htons(requestedPort);
|
||||
int length=sizeof(address);
|
||||
if(candidate.value==INVALID_SOCKET ||
|
||||
setsockopt(candidate.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
|
||||
ioctlsocket(candidate.value,FIONBIO,&mode) ||
|
||||
bind(candidate.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) ||
|
||||
listen(candidate.value,8) ||
|
||||
getsockname(candidate.value,reinterpret_cast<sockaddr*>(&address),&length))
|
||||
{
|
||||
closesocket(std::exchange(listener.value,INVALID_SOCKET));
|
||||
const auto error=static_cast<DWORD>(WSAGetLastError());
|
||||
if(requestedPort==FilesPort && lastBindError!=error)
|
||||
log(L"LAN Files TCP 45885 unavailable; retrying. Windows error "+std::to_wstring(error));
|
||||
lastBindError=error;
|
||||
return;
|
||||
}
|
||||
int length=sizeof(address);
|
||||
if(!getsockname(listener.value,reinterpret_cast<sockaddr*>(&address),&length))
|
||||
boundPort=ntohs(address.sin_port);
|
||||
listener.value=std::exchange(candidate.value,INVALID_SOCKET);
|
||||
boundPort=ntohs(address.sin_port);
|
||||
if(requestedPort==FilesPort) log(L"LAN Files listener ready on TCP 45885.");
|
||||
lastBindError=0;
|
||||
}
|
||||
void serve(SOCKET socket)
|
||||
{
|
||||
@@ -1089,6 +1145,7 @@ struct FilesListener::Impl
|
||||
void poll()
|
||||
{
|
||||
std::erase_if(clients,[](const auto &client){return client->done.load();});
|
||||
if(listener.value==INVALID_SOCKET && GetTickCount64()>=nextBind) bindListener();
|
||||
if(listener.value==INVALID_SOCKET || clients.size()>=16) return;
|
||||
sockaddr_in address{};
|
||||
int size=sizeof(address);
|
||||
|
||||
@@ -38,6 +38,8 @@ bool shouldElevateOnLaunch()
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
|
||||
{
|
||||
// Inherited by unattended children such as the LAN PowerShell process.
|
||||
SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS);
|
||||
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
int argc{};
|
||||
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
|
||||
|
||||
+48
-17
@@ -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
@@ -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
@@ -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; }
|
||||
|
||||
@@ -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);
|
||||
|
||||
+204
-41
@@ -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)
|
||||
@@ -327,7 +327,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 +685,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 +771,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 +861,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 +890,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 +948,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 +1062,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 +1124,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 +1139,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 +1148,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 +1160,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 +1308,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 +1316,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 +1362,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,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
|
||||
{
|
||||
|
||||
+50
-41
@@ -91,14 +91,8 @@ void refreshLan(HWND w,LanView &v)
|
||||
for(const auto &peer:next["peers"])
|
||||
{
|
||||
auto id=peer.at("id").get<std::string>();ids.push_back(id);
|
||||
std::wstring state=L"Not paired";
|
||||
if(peer.at("paired").get<bool>()){
|
||||
bool connected=next.value("inputReady",nlohmann::json::object()).contains(id);
|
||||
state=connected?L"Pair saved — input connected":
|
||||
!next.value("shareInput",false)?L"Pair saved — input disabled here":
|
||||
!peer.value("online",false)?L"Pair saved — computer offline":L"Pair saved — input not connected";
|
||||
}
|
||||
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"] — "+state);
|
||||
rows.push_back(wide(peer.at("name").get<std::string>())+L" ["+wide(id.substr(0,8))+L"]"+
|
||||
(peer.at("paired").get<bool>()?L" — Paired":L""));
|
||||
}
|
||||
// Presence/challenge refreshes must not repaint or reset the pairing list.
|
||||
if(v.ids!=ids||v.rows!=rows)
|
||||
@@ -131,11 +125,21 @@ void refreshLan(HWND w,LanView &v)
|
||||
std::wstring peerName;
|
||||
for(const auto &peer:v.snapshot["peers"])
|
||||
if(peer.at("id")==v.snapshot.value("pendingPeer",std::string{}))peerName=wide(peer.at("name").get<std::string>());
|
||||
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair there too. Pair is not saved yet.";
|
||||
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair on the other PC.";
|
||||
}
|
||||
value(w,708,v.error.empty() ? pairingStatus : v.error);
|
||||
value(w,705,pending ? L"Waiting..." : L"&Pair");
|
||||
value(w,710,v.ids.empty() ? (enabled ? L"No KSwitcher found. Enable discovery on the other PC too. UDP 45883 must be allowed on your private network." : L"Discovery is disabled on this computer.") : L"Select the matching KSwitcher name and ID shown on the other computer.");
|
||||
const wchar_t *peerStatus=L"Select the name and ID shown on the other PC.";
|
||||
if(v.ids.empty()) peerStatus=enabled?L"No computers found. Enable discovery on both PCs and allow UDP 45883.":
|
||||
L"Discovery is disabled on this computer.";
|
||||
else if(paired)
|
||||
{
|
||||
const bool connected=v.snapshot.value("inputReady",nlohmann::json::object()).contains(selected);
|
||||
peerStatus=connected?L"Pair saved — input connected":
|
||||
!v.snapshot.value("shareInput",false)?L"Pair saved — input disabled here":
|
||||
!online?L"Pair saved — computer offline":L"Pair saved — input not connected";
|
||||
}
|
||||
value(w,710,peerStatus);
|
||||
EnableWindow(GetDlgItem(w,705),enabled&&online&&!pending&&!paired);
|
||||
EnableWindow(GetDlgItem(w,706),pending);
|
||||
EnableWindow(GetDlgItem(w,707),paired);
|
||||
@@ -157,8 +161,7 @@ void refreshLan(HWND w,LanView &v)
|
||||
EnableWindow(GetDlgItem(w,716),v.snapshot.value("shareInput",false));
|
||||
auto gridState=positions.dump()+v.snapshot["peers"].dump()+selected+v.snapshot.value("controlPeer",std::string{})+v.snapshot.value("inputReady",nlohmann::json::object()).dump()+(v.snapshot.value("shareInput",false)?"1":"0");
|
||||
if(gridState!=v.gridState){v.gridState=std::move(gridState);InvalidateRect(GetDlgItem(w,721),nullptr,FALSE);}
|
||||
std::wstring detail=L"Drag paired monitors to empty cells. This PC stays fixed. Arrow keys also work.";
|
||||
detail=L"Drag monitors to neighboring cells. Mouse crosses shared edges; empty cells block passage.";
|
||||
const std::wstring detail=L"Drag monitors or use arrow keys. The pointer crosses shared edges.";
|
||||
value(w,719,v.error.empty()?detail:v.error);
|
||||
auto inputStatus=wide(v.snapshot.value("inputStatus",std::string("Input sharing disabled.")));
|
||||
if(!v.snapshot.value("shareInput",false))
|
||||
@@ -257,38 +260,44 @@ LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
void showLan(HWND parent,App &app)
|
||||
{
|
||||
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,740,908,0,false);
|
||||
HWND w=makeWindow(app,L"KSwitcher.LAN",L"KSwitcher computers",lanProc,730,498,0,false);
|
||||
windowLayoutState(w)->fixedClient=true;
|
||||
SetWindowLongPtrW(w,GWLP_HWNDPARENT,(LONG_PTR)parent);
|
||||
auto v=new LanView{parent,&app};SetWindowLongPtrW(w,GWLP_USERDATA,(LONG_PTR)v);
|
||||
label(w,L"Changes here save automatically. No need to click Save in Settings.",18,16,700);
|
||||
control(w,L"STATIC",L"",0,709,18,45,700,24);
|
||||
button(w,L"&Enable discovery",701,18,78,210);
|
||||
label(w,L"Only enabled KSwitcher instances announce themselves.",244,82,470);
|
||||
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,18,120,700,96);
|
||||
control(w,L"STATIC",L"",0,710,18,224,700,40);
|
||||
label(w,L"Same pairing c&ode on both computers",18,273,700);
|
||||
edit(w,703,18,301,470);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
|
||||
button(w,L"&Generate code",704,504,300,214);
|
||||
label(w,L"Generate once, enter that code on both PCs, select each other, then click Pair on both.",18,338,700);
|
||||
button(w,L"&Pair",705,18,370,140);button(w,L"Cancel &pairing",706,174,370,160);button(w,L"&Forget pair",707,350,370,160);
|
||||
control(w,L"STATIC",L"",0,708,18,412,700,40);
|
||||
label(w,L"Arrange your computers",18,458,700);
|
||||
label(w,L"Changes save automatically.",16,12,698);
|
||||
control(w,L"STATIC",L"",0,709,16,35,698,22);
|
||||
|
||||
button(w,L"&Enable discovery",701,16,62,164);
|
||||
control(w,L"LISTBOX",L"",WS_TABSTOP|WS_VSCROLL|WS_BORDER|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,702,16,98,332,70);
|
||||
control(w,L"STATIC",L"",0,710,16,173,332,36);
|
||||
label(w,L"Same pairing c&ode on both computers",16,211,332);
|
||||
edit(w,703,16,234,189);SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
|
||||
button(w,L"&Generate code",704,213,234,135);
|
||||
button(w,L"&Pair",705,16,268,76);
|
||||
button(w,L"Cancel &pairing",706,100,268,125);
|
||||
button(w,L"&Forget pair",707,233,268,115);
|
||||
control(w,L"STATIC",L"Use one code on both PCs. Select each other and click Pair on both.",0,0,16,302,332,37);
|
||||
control(w,L"STATIC",L"",0,708,16,344,332,53);
|
||||
|
||||
constexpr int right=366,rightWidth=348,gridTop=92,gridHeight=185;
|
||||
label(w,L"Arrange your computers",right,65,rightWidth);
|
||||
WNDCLASSW gridClass{};gridClass.lpfnWndProc=lanGridProc;gridClass.hInstance=app.instance;gridClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);gridClass.lpszClassName=L"KSwitcher.LAN.Layout";RegisterClassW(&gridClass);
|
||||
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer above, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
|
||||
scale(w,18),scale(w,486),scale(w,700),scale(w,180),w,reinterpret_cast<HMENU>(721),app.instance,v);
|
||||
windowLayoutState(w)->controls.push_back({grid,{18,486,718,666}});
|
||||
control(w,L"STATIC",L"",0,719,18,674,700,24);
|
||||
button(w,L"Enable &input sharing",715,18,706,330);
|
||||
button(w,L"&Stop input sharing",716,370,706,240);
|
||||
control(w,L"STATIC",L"",0,718,18,744,700,30);
|
||||
button(w,L"Send file…",726,18,774,144);
|
||||
button(w,L"Incoming files…",730,174,774,160);
|
||||
button(w,L"Download log…",727,346,774,164);
|
||||
button(w,L"Previous log…",728,522,774,196);
|
||||
control(w,L"BUTTON",L"Allow paired computers to download diagnostic logs",BS_AUTOCHECKBOX|WS_TABSTOP,729,18,808,700,24);
|
||||
control(w,L"STATIC",L"",0,731,18,835,700,24);
|
||||
button(w,L"Connection &help",722,18,864,300);
|
||||
button(w,L"&Close",IDCANCEL,618,864,100);
|
||||
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer in the list, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
|
||||
scale(w,right),scale(w,gridTop),scale(w,rightWidth),scale(w,gridHeight),w,reinterpret_cast<HMENU>(721),app.instance,v);
|
||||
windowLayoutState(w)->controls.push_back({grid,{right,gridTop,right+rightWidth,gridTop+gridHeight}});
|
||||
control(w,L"STATIC",L"",0,719,right,283,rightWidth,37);
|
||||
button(w,L"Enable &input sharing",715,right,323,172);
|
||||
button(w,L"&Stop input sharing",716,546,323,168);
|
||||
control(w,L"STATIC",L"",0,718,right,357,rightWidth,40);
|
||||
|
||||
button(w,L"Send file…",726,16,403,168);
|
||||
button(w,L"Incoming files…",730,192,403,168);
|
||||
button(w,L"Download log…",727,368,403,168);
|
||||
button(w,L"Previous log…",728,544,403,170);
|
||||
control(w,L"STATIC",L"",0,731,16,436,698,20);
|
||||
checkbox(w,L"Allow paired computers to download diagnostic logs",729,16,464,418);
|
||||
button(w,L"Connection &help",722,444,460,162);
|
||||
button(w,L"&Close",IDCANCEL,614,460,100);
|
||||
EnableWindow(parent,FALSE);showRequestedWindow(w);SetForegroundWindow(w);
|
||||
SetTimer(w,1,1000,nullptr);
|
||||
try {refreshLan(w,*v);} catch(const std::exception &e){v->error=wide(e.what());value(w,708,v->error);}
|
||||
|
||||
+4
-4
@@ -55,12 +55,12 @@ UpdateResult runUpdate(bool install, const std::wstring &expectedVersion, bool s
|
||||
L" -CurrentVersion " + quoteArgument(AppVersion) + L" -WorkDirectory " + quoteArgument(work.wstring()) +
|
||||
L" -InstallDirectory " + quoteArgument(std::filesystem::path(executable()).parent_path().wstring()) +
|
||||
L" -ParentProcessId " + std::to_wstring(GetCurrentProcessId()) + L" -ReadyEvent " + quoteArgument(readyName);
|
||||
if (install && expectedVersion.empty())
|
||||
if (install)
|
||||
{
|
||||
command += L" -Unattended -Journal " + quoteArgument((dataDirectory() / L"kswitcher.log").wstring());
|
||||
command += L" -Journal " + quoteArgument((dataDirectory() / L"kswitcher.log").wstring());
|
||||
if (expectedVersion.empty()) command += L" -Unattended";
|
||||
else command += L" -ExpectedVersion " + quoteArgument(expectedVersion);
|
||||
}
|
||||
else if (install)
|
||||
command += L" -ExpectedVersion " + quoteArgument(expectedVersion);
|
||||
if (showProgress) command += L" -ShowProgress";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
PROCESS_INFORMATION process{};
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.90";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.106";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
+59
-2
@@ -22,6 +22,56 @@ void require(bool ok, const char *message)
|
||||
if (!ok) throw std::runtime_error(message);
|
||||
++passed;
|
||||
}
|
||||
void lanWindowLayoutChecks(const std::filesystem::path &root)
|
||||
{
|
||||
const std::string peer(32,'b');
|
||||
const nlohmann::json fixture={{"version",1},{"id",std::string(32,'a')},{"enabled",false},
|
||||
{"trusted",{{peer,{{"name","Paired desktop"},{"key",std::string(64,'f')}}}}},
|
||||
{"positions",{{peer,nlohmann::json::array({1,0})}}}};
|
||||
const auto data=fixture.dump();
|
||||
std::filesystem::create_directories(root);
|
||||
ks::atomicWrite(root/L"lan-pairing.bin",ks::protect(ks::Bytes(data.begin(),data.end())));
|
||||
ks::App app(GetModuleHandleW(nullptr),true,root);
|
||||
ks::showSettings(app);
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,262,0);
|
||||
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
|
||||
require(lan!=nullptr,"Computers window opens");
|
||||
const auto dpi=GetDpiForWindow(lan);
|
||||
RECT room{0,0,MulDiv(750,dpi,96),MulDiv(510,dpi,96)};
|
||||
AdjustWindowRectExForDpi(&room,GetWindowLongPtrW(lan,GWL_STYLE)&~(WS_HSCROLL|WS_VSCROLL),
|
||||
FALSE,GetWindowLongPtrW(lan,GWL_EXSTYLE),dpi);
|
||||
RECT frame{};GetWindowRect(lan,&frame);
|
||||
SetWindowPos(lan,nullptr,0,0,std::min(frame.right-frame.left,room.right-room.left),
|
||||
std::min(frame.bottom-frame.top,room.bottom-room.top),SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
require(!(GetWindowLongPtrW(lan,GWL_STYLE)&(WS_HSCROLL|WS_VSCROLL)),"Computers window fits without scrollbars");
|
||||
RECT client{};GetClientRect(lan,&client);
|
||||
std::vector<std::pair<int,RECT>> placed;
|
||||
for(HWND child=GetWindow(lan,GW_CHILD);child;child=GetWindow(child,GW_HWNDNEXT))
|
||||
{
|
||||
RECT bounds{};GetWindowRect(child,&bounds);
|
||||
MapWindowPoints(nullptr,lan,reinterpret_cast<POINT *>(&bounds),2);
|
||||
require(bounds.left>=0&&bounds.top>=0&&bounds.right<=client.right&&bounds.bottom<=client.bottom,
|
||||
"Computers control is fully visible");
|
||||
const int id=GetDlgCtrlID(child);
|
||||
for(const auto &[otherId,other]:placed)
|
||||
{
|
||||
RECT overlap{};
|
||||
if(IntersectRect(&overlap,&bounds,&other))
|
||||
throw std::runtime_error("Computers controls overlap: "+std::to_string(id)+" and "+std::to_string(otherId)+
|
||||
" at "+std::to_string(overlap.left)+","+std::to_string(overlap.top));
|
||||
}
|
||||
placed.push_back({id,bounds});
|
||||
}
|
||||
RedrawWindow(lan,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN);
|
||||
auto dc=GetDC(lan);
|
||||
auto screenshot=ks::screenshotClip(dc,client.right,client.bottom,{});
|
||||
ReleaseDC(lan,dc);
|
||||
ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"lan-compact-layout.png",
|
||||
ks::encodePng(ks::decodeImage(screenshot)));
|
||||
SendMessageW(lan,WM_COMMAND,IDCANCEL,0);
|
||||
SendMessageW(app.settingsWindow,WM_COMMAND,IDCANCEL,0);
|
||||
std::cout<<"Computers layout verified at "<<dpi<<" DPI.\n";
|
||||
}
|
||||
void contextChecks()
|
||||
{
|
||||
ks::Settings scoped;
|
||||
@@ -114,12 +164,19 @@ void contextChecks()
|
||||
require(hook.update('A', true, MOD_ALT, true) == 0, "ordinary keys pass");
|
||||
}
|
||||
}
|
||||
int main()
|
||||
int main(int argc,char **argv)
|
||||
{
|
||||
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-chat-tests-" + std::to_wstring(GetCurrentProcessId()));
|
||||
try
|
||||
{
|
||||
if(argc==2 && std::string_view(argv[1])=="--lan-layout")
|
||||
{
|
||||
lanWindowLayoutChecks(root);
|
||||
std::filesystem::remove_all(root);
|
||||
CoUninitialize();
|
||||
return 0;
|
||||
}
|
||||
contextChecks();
|
||||
{
|
||||
ks::App app(GetModuleHandleW(nullptr), true, root);
|
||||
@@ -451,7 +508,7 @@ int main()
|
||||
SendMessageW(pairedApp.settingsWindow,WM_COMMAND,262,0);
|
||||
HWND lan=findTestWindow(L"KSwitcher.LAN",nullptr);
|
||||
require(SendDlgItemMessageW(lan,702,LB_GETCURSEL,0,0)==0,"single saved pair selected automatically when opening LAN settings");
|
||||
wchar_t pairState[512]{};SendDlgItemMessageW(lan,702,LB_GETTEXT,0,(LPARAM)pairState);
|
||||
wchar_t pairState[512]{};GetDlgItemTextW(lan,710,pairState,std::size(pairState));
|
||||
require(std::wstring(pairState).find(L"Pair saved — input disabled here")!=std::wstring::npos,"saved pairing does not imply an active input connection");
|
||||
require(!IsWindowEnabled(GetDlgItem(lan,705))&&!IsWindowEnabled(GetDlgItem(lan,703))&&!IsWindowEnabled(GetDlgItem(lan,704)),"saved pair disables pairing and code controls");
|
||||
SendDlgItemMessageW(lan,702,LB_SETCURSEL,-1,0);
|
||||
|
||||
+471
-2
@@ -1,6 +1,9 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Executable,
|
||||
[Parameter(Mandatory)][string]$Fixture
|
||||
[Parameter(Mandatory)][string]$Fixture,
|
||||
[switch]$SystemOpenOnly,
|
||||
[switch]$TerminalOnly,
|
||||
[string]$Node='node'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type @"
|
||||
@@ -20,6 +23,17 @@ 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);
|
||||
|
||||
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")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
@@ -72,6 +86,29 @@ function Wait-Until([string]$Description, [scriptblock]$Condition) {
|
||||
throw "Timed out waiting for $Description"
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -113,6 +150,11 @@ function Send-Terminal([string]$Command) {
|
||||
Press-Enter $inputBox
|
||||
}
|
||||
|
||||
function Send-InteractiveTerminal([string]$Command, [string]$EnterKey = '{ENTER}') {
|
||||
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, $Command)
|
||||
$keys.SendKeys($EnterKey)
|
||||
}
|
||||
|
||||
function Assert-Open($List, $Target, [bool]$DoubleClick) {
|
||||
$report = "$Target.opened"
|
||||
Remove-Item -LiteralPath $report -ErrorAction SilentlyContinue
|
||||
@@ -133,6 +175,8 @@ $profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide
|
||||
'ShowDetails', 'StatusFields', 'CommandHistory', 'WindowPlacement'
|
||||
$process = $null
|
||||
$trace = $null
|
||||
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
$webviewProfile=$env:WEBVIEW2_USER_DATA_FOLDER
|
||||
try {
|
||||
foreach ($name in $profileValues) {
|
||||
if ($name -in $profile.GetValueNames()) {
|
||||
@@ -149,7 +193,7 @@ try {
|
||||
Copy-Item -LiteralPath "$source\WebView2Loader.dll", "$source\terminal" -Destination $app -Recurse
|
||||
$program = Join-Path $leftDir 'Test program.exe'
|
||||
Copy-Item -LiteralPath $Fixture -Destination $program
|
||||
$document = Join-Path $rightDir "Test document$extension"
|
||||
$document = Join-Path $(if($SystemOpenOnly -or $TerminalOnly){$leftDir}else{$rightDir}) "Test document$extension"
|
||||
[IO.File]::WriteAllText($document, 'Document fixture')
|
||||
$association = $classes.CreateSubKey($extension)
|
||||
$association.SetValue('', $progId)
|
||||
@@ -169,6 +213,14 @@ try {
|
||||
foreach ($name in 'LeftWide', 'RightWide', 'ShowDetails') { $profile.SetValue($name, 1) }
|
||||
$profile.SetValue('StatusFields', 3)
|
||||
|
||||
if($TerminalOnly){
|
||||
$listener=[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$listener.Start()
|
||||
$port=$listener.LocalEndpoint.Port
|
||||
$listener.Stop()
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=$port"
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $root 'webview'
|
||||
}
|
||||
$process = Start-Process -FilePath $testExe -ArgumentList '--terminal-output-trace' -PassThru
|
||||
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
|
||||
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
@@ -179,6 +231,159 @@ try {
|
||||
$output = [FilesActivationUi]::GetDlgItem($window, 145)
|
||||
$inputBox = [FilesActivationUi]::FindWindowEx($window, [IntPtr]::Zero, 'Edit', $null)
|
||||
|
||||
if($SystemOpenOnly) {
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
$explorer = New-Object -ComObject Shell.Application
|
||||
$existingExplorerWindows = @($explorer.Windows() | ForEach-Object { $_.HWND })
|
||||
Wait-Until 'Files ready for Shift+Enter' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$folderRow=Find-Row $left '[Test folder]'
|
||||
if($folderRow -lt 0){throw 'The folder fixture is missing.'}
|
||||
[void][FilesActivationUi]::Send($left,0x186,[IntPtr]$folderRow,[IntPtr]::Zero)
|
||||
$keys.SendKeys('+{ENTER}')
|
||||
$folderWindow = $null
|
||||
Wait-Until 'Shift+Enter opening the selected folder in Explorer' {
|
||||
$script:folderWindow = $explorer.Windows() | Where-Object {
|
||||
$_.Document.Folder.Self.Path -eq "$leftDir\Test folder"
|
||||
} | Select-Object -First 1
|
||||
$null -ne $script:folderWindow
|
||||
}
|
||||
if($folderWindow.HWND -notin $existingExplorerWindows){$folderWindow.Quit()}
|
||||
if((Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -ne $leftDir){
|
||||
throw 'Shift+Enter changed the folder in the Files panel.'
|
||||
}
|
||||
Wait-Until 'Files active for the registered document test' { [FilesActivationUi]::Activate($window) }
|
||||
$documentRow=Find-Row $left ([IO.Path]::GetFileName($document))
|
||||
if($documentRow -lt 0){throw 'The document fixture is missing.'}
|
||||
[void][FilesActivationUi]::Send($left,0x186,[IntPtr]$documentRow,[IntPtr]::Zero)
|
||||
Wait-Until 'Files command line focused for document Shift+Enter' {
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$keys.SendKeys('+{ENTER}')
|
||||
Wait-Until 'Shift+Enter invoking the default Windows file association' {
|
||||
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
|
||||
}
|
||||
Wait-Until 'Files active for plain Enter' { [FilesActivationUi]::Activate($window) }
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
|
||||
Remove-Item -LiteralPath "$document.opened"
|
||||
$keys.SendKeys('{ENTER}')
|
||||
Wait-Until 'plain Enter invoking the default Windows file association' {
|
||||
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
|
||||
}
|
||||
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
|
||||
Remove-Item -LiteralPath "$document.opened"
|
||||
}
|
||||
if($SystemOpenOnly -or $TerminalOnly){
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
foreach($case in @(
|
||||
@{Name='enter-panes'; Keys='{ENTER}'},
|
||||
@{Name='shift-enter-panes'; Keys='+{ENTER}'},
|
||||
@{Name='enter-terminal'; Keys='{ENTER}'; HidePanes=$true},
|
||||
@{Name='shift-enter-terminal'; Keys='+{ENTER}'}
|
||||
)) {
|
||||
Wait-Until 'Files command line active' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
if($case.HidePanes){
|
||||
$keys.SendKeys('^o')
|
||||
Wait-Until 'file panes hidden' { ![FilesActivationUi]::IsWindowVisible($left) }
|
||||
}
|
||||
$marker=Join-Path $root "$($case.Name).txt"
|
||||
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
|
||||
Send-InteractiveTerminal $command $case.Keys
|
||||
Wait-Until "$($case.Name) running the command" {
|
||||
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
|
||||
!(Read-Text $inputBox)
|
||||
}
|
||||
if(Test-Path -LiteralPath "$document.opened"){
|
||||
throw "$($case.Name) did not give the command line priority."
|
||||
}
|
||||
}
|
||||
Write-Output 'Verified command-line priority for Enter and Shift+Enter with panels visible and hidden.'
|
||||
if(!$TerminalOnly){return}
|
||||
foreach($name in 'zzzz-dir-first','zzzz-dir-second'){
|
||||
[IO.File]::WriteAllText((Join-Path $leftDir $name),'dir marker')
|
||||
Send-InteractiveTerminal 'dir'
|
||||
Wait-Until "dir rendering $name in terminal output" {
|
||||
!(Read-Text $inputBox) -and
|
||||
(Select-String -LiteralPath $trace -SimpleMatch $name -Quiet -ErrorAction SilentlyContinue)
|
||||
}
|
||||
}
|
||||
$keys.SendKeys('^o')
|
||||
Wait-Until 'file panes visible again' { [FilesActivationUi]::IsWindowVisible($left) }
|
||||
$listing=Join-Path $root 'dir-visible.txt'
|
||||
Send-InteractiveTerminal "dir -Name | Set-Content -LiteralPath '$($listing.Replace("'","''"))'"
|
||||
Wait-Until 'dir running after restoring the file panes' {
|
||||
!(Read-Text $inputBox) -and (Test-Path -LiteralPath $listing) -and
|
||||
([IO.File]::ReadAllLines($listing) -ccontains 'zzzz-dir-second')
|
||||
}
|
||||
Write-Output 'Verified repeated dir commands in the same terminal with file panes hidden and visible.'
|
||||
$marker=Join-Path $root 'webview-enter.txt'
|
||||
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$command)
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
|
||||
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
|
||||
Wait-Until 'the terminal WebView forwarding Enter to the command line' {
|
||||
(Test-Path -LiteralPath $marker) -and [IO.File]::ReadAllText($marker) -ceq 'executed' -and
|
||||
!(Read-Text $inputBox)
|
||||
}
|
||||
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
|
||||
Select-Row $left '[Test folder]'
|
||||
$outputSelection = 'terminal-output-copy-fixture'
|
||||
Send-InteractiveTerminal "Write-Output '$outputSelection'"
|
||||
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$savedClipboard = [Windows.Forms.Clipboard]::GetDataObject()
|
||||
try {
|
||||
$nativeDraft = "Get-Item -LiteralPath '$leftDir'"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$nativeDraft)
|
||||
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]0,[IntPtr]4)
|
||||
$keys.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the full command line with a partial selection' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $nativeDraft
|
||||
}
|
||||
$webviewDraft = "Get-Item -LiteralPath '$rightDir'"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$webviewDraft)
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-copy'
|
||||
if($LASTEXITCODE){throw 'Could not send Ctrl+Insert through the terminal WebView.'}
|
||||
Wait-Until 'Ctrl+Insert copying the command line with focus in the terminal WebView' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $webviewDraft
|
||||
}
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-select-output'
|
||||
if($LASTEXITCODE){throw 'Could not select the terminal output fixture.'}
|
||||
Wait-Until 'focus returned to the command line after selecting terminal output' {
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
foreach($key in '^c','^{INSERT}') {
|
||||
[Windows.Forms.Clipboard]::SetText($webviewDraft)
|
||||
$keys.SendKeys($key)
|
||||
Wait-Until "$key copying only the selected terminal output with a command present" {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $outputSelection
|
||||
}
|
||||
if ((Read-Text $inputBox) -cne $webviewDraft) { throw 'Copying output changed the command line.' }
|
||||
}
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
|
||||
$keys.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the selected folder name when the command line is empty' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq 'Test folder'
|
||||
}
|
||||
} finally {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
}
|
||||
}
|
||||
Write-Output 'Verified Ctrl+C and Ctrl+Insert copy the selected output, then fall back to the command line or panel.'
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-enter'
|
||||
if($LASTEXITCODE){throw 'Could not send Enter through the terminal WebView.'}
|
||||
Wait-Until 'Enter from the terminal opening the selected folder in the pane' {
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -eq "$leftDir\Test folder"
|
||||
}
|
||||
Write-Output 'Verified Enter from the terminal opens the selected folder with an empty command line.'
|
||||
return
|
||||
}
|
||||
|
||||
Select-Row $left '..'
|
||||
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr]::Zero, [IntPtr]::Zero)
|
||||
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
|
||||
@@ -270,7 +475,271 @@ try {
|
||||
}
|
||||
if ([FilesActivationUi]::Focus($window) -ne $inputBox) { throw 'Deletion moved focus.' }
|
||||
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
|
||||
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$savedClipboard=[Windows.Forms.Clipboard]::GetDataObject()
|
||||
$programName=[IO.Path]::GetFileName($program)
|
||||
$expectedNames="Test folder`r`n$programName"
|
||||
try {
|
||||
Select-Row $left '[Test folder]'
|
||||
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
Select-Row $left $programName
|
||||
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
Wait-Until 'Files activation for Ctrl+Insert' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $expectedNames
|
||||
}
|
||||
Select-Row $right $fileName
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $fileName
|
||||
}
|
||||
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
|
||||
} finally {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
}
|
||||
}
|
||||
|
||||
$sizeA=Join-Path $rightDir 'Size A'
|
||||
$sizeB=Join-Path $rightDir 'Size B'
|
||||
$sizeC=Join-Path $rightDir 'Size C'
|
||||
New-Item -ItemType Directory -Path "$sizeA\nested", $sizeB, $sizeC | Out-Null
|
||||
[IO.File]::WriteAllBytes("$sizeA\file.bin",[byte[]]::new(4))
|
||||
[IO.File]::WriteAllBytes("$sizeA\nested\file.bin",[byte[]]::new(7))
|
||||
[IO.File]::WriteAllBytes("$sizeB\file.bin",[byte[]]::new(23))
|
||||
[IO.File]::WriteAllBytes("$sizeC\file.bin",[byte[]]::new(31))
|
||||
Select-Row $right '[Size A]'
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
Wait-Until 'F3 recursive size for the current folder' { (Read-Text $status) -ceq 'Size A 11 B' }
|
||||
foreach($name in 'Size A','Size B'){
|
||||
Select-Row $right "[$name]"
|
||||
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
}
|
||||
Select-Row $right '[Size C]'
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
Wait-Until 'completion of the marked size batch' { (Read-Text $status) -ceq 'Size C Folder' }
|
||||
Select-Row $right '[Size B]'
|
||||
Wait-Until 'F3 size for a marked folder' { (Read-Text $status) -ceq 'Size B 23 B' }
|
||||
Select-Row $right '[Size C]'
|
||||
if ((Read-Text $status) -cne 'Size C Folder') { throw 'F3 measured the unmarked cursor folder.' }
|
||||
Select-Row $right $fileName
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
$viewerTitle='Viewer '+[char]0x2014+" $document"
|
||||
Wait-Until 'F3 opening a file when folders are marked' {
|
||||
[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle) -ne [IntPtr]::Zero
|
||||
}
|
||||
$viewer=[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle)
|
||||
[void][FilesActivationUi]::PostMessage($viewer,0x10,[IntPtr]::Zero,[IntPtr]::Zero)
|
||||
Write-Output 'F3 measured the current folder recursively and measured marked folders without measuring the unmarked cursor folder.'
|
||||
|
||||
Select-Row $right '[Size B]'
|
||||
Wait-Until 'Files activation for Ctrl+R' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$shell.SendKeys('^r')
|
||||
Wait-Until 'Ctrl+R clearing the measured size and retaining the current folder' {
|
||||
(Read-Text $status) -ceq 'Size B Folder' -and
|
||||
[FilesActivationUi]::Send($right,0x188,[IntPtr]::Zero,[IntPtr]::Zero).ToInt32() -eq
|
||||
(Find-Row $right '[Size B]')
|
||||
}
|
||||
Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.'
|
||||
|
||||
$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)"
|
||||
}
|
||||
if ($trace -and (Test-Path -LiteralPath $trace)) {
|
||||
Get-Content -LiteralPath $trace -Tail 25
|
||||
}
|
||||
throw
|
||||
} finally {
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=$webviewFlags
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER=$webviewProfile
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
if (!$process.WaitForExit(4000)) { $process.Kill(); $process.WaitForExit() }
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Executable,
|
||||
[string]$Screenshot,
|
||||
[string]$SearchScreenshot,
|
||||
[string]$Node = 'node',
|
||||
[string]$LanFixture
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type @"
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class MarkdownUi {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct PropertyKey {
|
||||
public Guid Format;
|
||||
public uint Id;
|
||||
}
|
||||
[StructLayout(LayoutKind.Explicit, Size = 24)]
|
||||
struct PropertyValue {
|
||||
[FieldOffset(0)] public ushort Type;
|
||||
[FieldOffset(8)] public IntPtr Text;
|
||||
}
|
||||
[ComImport, Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
interface IPropertyStore {
|
||||
void GetCount(out uint count);
|
||||
void GetAt(uint index, out PropertyKey key);
|
||||
void GetValue(ref PropertyKey key, out PropertyValue value);
|
||||
}
|
||||
[DllImport("shell32.dll", PreserveSig = false)]
|
||||
static extern void SHGetPropertyStoreForWindow(IntPtr window, ref Guid iid, out IPropertyStore store);
|
||||
[DllImport("ole32.dll")] static extern int PropVariantClear(ref PropertyValue value);
|
||||
|
||||
public static string TaskbarProperty(IntPtr window, uint property) {
|
||||
var iid = typeof(IPropertyStore).GUID;
|
||||
var key = new PropertyKey { Format = new Guid("9f4c2855-9f79-4b39-a8d0-e1d42de1d5f3"), Id = property };
|
||||
SHGetPropertyStoreForWindow(window, ref iid, out var store);
|
||||
try {
|
||||
store.GetValue(ref key, out var value);
|
||||
try { return value.Type == 31 ? Marshal.PtrToStringUni(value.Text) : null; }
|
||||
finally { PropVariantClear(ref value); }
|
||||
} finally { Marshal.ReleaseComObject(store); }
|
||||
}
|
||||
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
public static void Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return;
|
||||
keybd_event(0x12,0,0,UIntPtr.Zero);
|
||||
keybd_event(0x12,0,2,UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
}
|
||||
public static void CycleWindow() {
|
||||
keybd_event(0x11,0,0,UIntPtr.Zero);
|
||||
keybd_event(0x09,0,0,UIntPtr.Zero);
|
||||
keybd_event(0x09,0,2,UIntPtr.Zero);
|
||||
keybd_event(0x11,0,2,UIntPtr.Zero);
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr window, StringBuilder title, int capacity);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SendText(IntPtr window, uint msg, IntPtr w, string l);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
}
|
||||
"@
|
||||
|
||||
function Wait-For([string]$Name, [scriptblock]$Check) {
|
||||
for ($i=0; $i -lt 150; $i++) {
|
||||
$value = & $Check
|
||||
if ($value) { return $value }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
throw "Timed out waiting for $Name"
|
||||
}
|
||||
|
||||
function Find-Window([string]$Class, [string]$Title = '', [IntPtr]$Except = 0) {
|
||||
$window = [IntPtr]::Zero
|
||||
while (($window = [MarkdownUi]::FindWindowEx(0,$window,$Class,[NullString]::Value)) -ne [IntPtr]::Zero) {
|
||||
[uint32]$pidFound = 0
|
||||
[void][MarkdownUi]::GetWindowThreadProcessId($window,[ref]$pidFound)
|
||||
if ($pidFound -ne $process.Id -or $window -eq $Except -or ![MarkdownUi]::IsWindowVisible($window)) { continue }
|
||||
$buffer = [Text.StringBuilder]::new(2048)
|
||||
[void][MarkdownUi]::GetWindowText($window,$buffer,$buffer.Capacity)
|
||||
if ($buffer.ToString() -like "*$Title*") { return $window }
|
||||
}
|
||||
}
|
||||
|
||||
function Post($Window, $Message, $Key) {
|
||||
if (![MarkdownUi]::PostMessage($Window,$Message,$Key,0)) { throw 'Could not drive the Files window.' }
|
||||
}
|
||||
|
||||
function Open-File($File, $Key) {
|
||||
$row = [MarkdownUi]::SendText($panel,0x1A2,-1,$File)
|
||||
if ($row.ToInt64() -lt 0) { throw "Missing row $File" }
|
||||
[void][MarkdownUi]::Send($panel,0x186,$row,0)
|
||||
Post $panel 0x100 $Key
|
||||
}
|
||||
|
||||
function Browser($Scenario, $Image = '', $Title = '') {
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port $Scenario $Image $Title
|
||||
if ($LASTEXITCODE) { throw "WebView2 verification failed for $Scenario" }
|
||||
}
|
||||
|
||||
function Wait-Foreground($Window) {
|
||||
$buffer = [Text.StringBuilder]::new(2048)
|
||||
[void][MarkdownUi]::GetWindowText($Window,$buffer,$buffer.Capacity)
|
||||
[void](Wait-For "foreground window $buffer" { [MarkdownUi]::GetForegroundWindow() -eq $Window })
|
||||
}
|
||||
|
||||
function Scintilla($Window) {
|
||||
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
|
||||
}
|
||||
|
||||
function Assert-TextWindowAppearance($Window, [string]$Mode) {
|
||||
$identity = "HrynCo.KSwitcher.Files.$Mode"
|
||||
$resource = if($Mode -eq 'Editor') { ',-104' } else { ',-103' }
|
||||
[void](Wait-For "the $Mode taskbar group" { [MarkdownUi]::TaskbarProperty($Window,5) -ceq $identity })
|
||||
$taskbarIcon = [MarkdownUi]::TaskbarProperty($Window,3)
|
||||
if (!$taskbarIcon -or !$taskbarIcon.EndsWith($resource)) {
|
||||
throw "$Mode taskbar icon was '$taskbarIcon'."
|
||||
}
|
||||
$small = [MarkdownUi]::Send($Window,0x7f,0,0)
|
||||
$large = [MarkdownUi]::Send($Window,0x7f,1,0)
|
||||
if (!$small.ToInt64() -or !$large.ToInt64() -or $small -eq $large) {
|
||||
throw "$Mode must expose both a small title-bar icon and a large switcher icon."
|
||||
}
|
||||
@{ Small = $small; Large = $large }
|
||||
}
|
||||
|
||||
function Append-Character($Control, [char]$Character) {
|
||||
[void][MarkdownUi]::Send($Control,2318,0,0)
|
||||
[void][MarkdownUi]::Send($Control,0x102,[int]$Character,0)
|
||||
}
|
||||
|
||||
function Answer-Save($Button) {
|
||||
$dialog = Wait-For 'the save confirmation' {
|
||||
$candidate = Find-Window '#32770'
|
||||
if ($candidate -and [MarkdownUi]::GetDlgItem($candidate,7) -ne [IntPtr]::Zero) { $candidate }
|
||||
}
|
||||
Post $dialog 0x111 $Button
|
||||
[void](Wait-For 'the save confirmation to close' { ![MarkdownUi]::IsWindowVisible($dialog) })
|
||||
}
|
||||
|
||||
$source = Split-Path (Resolve-Path -LiteralPath $Executable)
|
||||
$root = Join-Path ([IO.Path]::GetTempPath()) ('ks-markdown-test-' + [Guid]::NewGuid().ToString('N'))
|
||||
$app = Join-Path $root 'app'
|
||||
$docs = Join-Path $root 'docs'
|
||||
$profileCaptured = $false
|
||||
$profile = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$saved = @{}
|
||||
$profileValues = 'LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement','OptionsLocation'
|
||||
$process = $null
|
||||
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
$data = $env:WEBVIEW2_USER_DATA_FOLDER
|
||||
try {
|
||||
New-Item -ItemType Directory -Path $app,$docs,"$docs\child","$docs\images" | Out-Null
|
||||
Copy-Item -LiteralPath $Executable,"$source\WebView2Loader.dll","$source\terminal" -Destination $app -Recurse
|
||||
$fixture = @'
|
||||
# Перегляд Markdown
|
||||
|
||||
| Header |
|
||||
| ------ |
|
||||
| Cell |
|
||||
| <span id="nowrap-cell" style="white-space: nowrap; color: red; position: fixed" onclick="void 0">In Development</span> |
|
||||
|
||||
<table id="html-table">
|
||||
<caption>Raw HTML table</caption>
|
||||
<tr><th colspan="2">Priority</th></tr>
|
||||
<tr><td><strong>Highest</strong></td><td>—</td></tr>
|
||||
</table>
|
||||
|
||||
- [ ] Pending
|
||||
- [x] Complete
|
||||
|
||||
## Збіг пошуку
|
||||
|
||||
Рядок для **збіг пошуку**.
|
||||
|
||||

|
||||

|
||||
<img alt="HTML relative image" src="images/tiny%20image.png">
|
||||
<a href="child/Other.md#target-heading">Child</a>
|
||||
|
||||
~~~mermaid
|
||||
flowchart TD
|
||||
A[Render target] --> B[Result]
|
||||
~~~
|
||||
|
||||
~~~mermaid
|
||||
this is not a diagram
|
||||
~~~
|
||||
|
||||
~~~js
|
||||
const value = 42;
|
||||
~~~
|
||||
|
||||
<iframe src="https://example.invalid">Raw HTML</iframe>
|
||||
'@
|
||||
$original = Join-Path $docs 'Preview.md'
|
||||
[IO.File]::WriteAllText($original,$fixture)
|
||||
$childText = '# Linked Markdown' + "`n`n" + (("Filler paragraph.`n`n") * 60) + '## Target heading'
|
||||
[IO.File]::WriteAllText("$docs\child\Other.md",$childText)
|
||||
[IO.File]::WriteAllText("$docs\Plain.txt",'Plain text')
|
||||
$largeFile = [IO.File]::Create("$docs\Large.md")
|
||||
try {
|
||||
$line = [Text.Encoding]::UTF8.GetBytes(("# Large Markdown file`n" * 1024))
|
||||
while ($largeFile.Length -le 8MB) { $largeFile.Write($line,0,$line.Length) }
|
||||
} finally { $largeFile.Dispose() }
|
||||
[IO.File]::WriteAllBytes("$docs\images\tiny image.png",[Convert]::FromBase64String(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jBo0AAAAASUVORK5CYII='))
|
||||
foreach ($name in $profileValues) {
|
||||
if ($name -in $profile.GetValueNames()) {
|
||||
$saved[$name] = @($profile.GetValue($name),$profile.GetValueKind($name))
|
||||
}
|
||||
}
|
||||
$profileCaptured = $true
|
||||
$profile.SetValue('LeftPath',$docs)
|
||||
$profile.SetValue('RightPath',$docs)
|
||||
foreach ($name in 'LeftCursor','RightCursor','WindowPlacement','OptionsLocation') { $profile.DeleteValue($name,$false) }
|
||||
|
||||
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$listener.Start()
|
||||
$port = $listener.LocalEndpoint.Port
|
||||
$listener.Stop()
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = "--remote-debugging-port=$port --disable-background-networking"
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'webview'
|
||||
$process = Start-Process -FilePath (Join-Path $app (Split-Path -Leaf $Executable)) -PassThru -WindowStyle Normal
|
||||
$main = Wait-For 'Files' { Find-Window 'KSwitcher.Files' }
|
||||
[MarkdownUi]::Activate($main)
|
||||
$panel = [MarkdownUi]::GetDlgItem($main,102)
|
||||
|
||||
Open-File 'Preview.md' 0x72
|
||||
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
|
||||
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
|
||||
if ([MarkdownUi]::IsWindowVisible((Scintilla $window))) {
|
||||
throw 'F3 showed the source text while starting the Markdown preview.'
|
||||
}
|
||||
Browser 'render' $Screenshot
|
||||
Post $window 0x111 3
|
||||
Browser 'search-menu'
|
||||
Browser 'search' $SearchScreenshot
|
||||
Post $main 0x111 133
|
||||
$options = Wait-For 'the shared Files Options dialog' { Find-Window '#32770' 'KSwitcher Files Options' }
|
||||
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,270),0x0C,0,'Markdown')
|
||||
[void](Wait-For 'the Markdown settings section' { [MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374)) })
|
||||
foreach($field in @(@(374,'1200'),@(376,'Georgia'),@(379,'18'))){
|
||||
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,$field[0]),0x0C,0,$field[1])
|
||||
}
|
||||
Post $options 0x111 1
|
||||
[void](Wait-For 'Options to close after saving Markdown settings' { ![MarkdownUi]::IsWindowVisible($options) })
|
||||
Browser 'appearance-width'
|
||||
|
||||
Post $main 0x111 133
|
||||
$options = Wait-For 'reopened Files Options' { Find-Window '#32770' 'KSwitcher Files Options' }
|
||||
if (![MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374))) {
|
||||
throw 'Files Options did not restore its last section.'
|
||||
}
|
||||
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,374),0x0C,0,'0')
|
||||
Post $options 0x111 2
|
||||
[void](Wait-For 'Options to close on Cancel' { ![MarkdownUi]::IsWindowVisible($options) })
|
||||
Browser 'appearance-width'
|
||||
|
||||
Post $main 0x111 133
|
||||
$options = Wait-For 'Files Options after Cancel' { Find-Window '#32770' 'KSwitcher Files Options' }
|
||||
if (![MarkdownUi]::IsWindowVisible([MarkdownUi]::GetDlgItem($options,374))) {
|
||||
throw 'Cancel did not preserve the last Options section.'
|
||||
}
|
||||
[void][MarkdownUi]::SendText([MarkdownUi]::GetDlgItem($options,374),0x0C,0,'0')
|
||||
Post $options 0x111 1
|
||||
[void](Wait-For 'Options to close after saving full width' { ![MarkdownUi]::IsWindowVisible($options) })
|
||||
Browser 'appearance-full'
|
||||
Write-Output 'Verified live Markdown width and font settings, Cancel and reopening the last Options section.'
|
||||
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Checking a task modified the read-only file.' }
|
||||
[IO.File]::WriteAllText($original,($fixture.Replace('Перегляд Markdown','Зміна на диску')))
|
||||
Browser 'Зміна на диску' '' 'Preview.md'
|
||||
$replacement = Join-Path $docs 'Preview-replacement.md'
|
||||
[IO.File]::WriteAllText($replacement,$fixture)
|
||||
[IO.File]::Move($replacement,$original,$true)
|
||||
Browser 'Перегляд Markdown' '' 'Preview.md'
|
||||
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window) { throw 'Reload changed windows.' }
|
||||
Browser 'edit'
|
||||
$editor = Wait-For 'F6 in WebView2 to open the editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
|
||||
if ($editor -ne $window) { throw 'F6 changed windows.' }
|
||||
$editorIcons = Assert-TextWindowAppearance $window 'Editor'
|
||||
if ($editorIcons.Small -eq $viewerIcons.Small -or $editorIcons.Large -eq $viewerIcons.Large) {
|
||||
throw 'F6 did not replace both viewer icons with editor icons.'
|
||||
}
|
||||
[MarkdownUi]::Activate($window)
|
||||
Wait-Foreground $window
|
||||
[MarkdownUi]::CycleWindow()
|
||||
Wait-Foreground $main
|
||||
[MarkdownUi]::CycleWindow()
|
||||
Wait-Foreground $window
|
||||
Write-Output 'Verified Ctrl+Tab between Files and the Markdown editor.'
|
||||
$control = Scintilla $window
|
||||
if ([MarkdownUi]::Send($control,2140,0,0).ToInt64()) { throw 'The editor is read-only.' }
|
||||
Append-Character $control 'X'
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 2
|
||||
if ((Find-Window 'KSwitcher.Files.Text' 'Editor') -ne $window -or ![MarkdownUi]::Send($control,2159,0,0).ToInt64()) {
|
||||
throw 'Cancel lost unsaved changes.'
|
||||
}
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 7
|
||||
Browser 'Перегляд Markdown'
|
||||
$viewerIcons = Assert-TextWindowAppearance $window 'Viewer'
|
||||
if ($viewerIcons.Small -eq $editorIcons.Small -or $viewerIcons.Large -eq $editorIcons.Large) {
|
||||
throw 'F6 did not restore both viewer icons.'
|
||||
}
|
||||
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Discard changed the Markdown file.' }
|
||||
Browser 'ctrl-follow'
|
||||
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window -or (Find-Window 'KSwitcher.Files.Text' 'Other.md')) {
|
||||
throw 'Ctrl+click navigated without tabs.'
|
||||
}
|
||||
Browser 'shift-follow'
|
||||
$child = Wait-For 'the Shift+click Markdown window' { Find-Window 'KSwitcher.Files.Text' 'Other.md' $window }
|
||||
[void](Assert-TextWindowAppearance $child 'Viewer')
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
[MarkdownUi]::Activate($child)
|
||||
Wait-Foreground $child
|
||||
Browser 'cycle' '' 'Other.md'
|
||||
Wait-Foreground $main
|
||||
[MarkdownUi]::CycleWindow()
|
||||
Wait-Foreground $window
|
||||
Browser 'cycle' '' 'Preview.md'
|
||||
Wait-Foreground $child
|
||||
Browser 'close' '' 'Other.md'
|
||||
[void](Wait-For 'Ctrl+W to close the Shift+click window' { ![MarkdownUi]::IsWindowVisible($child) })
|
||||
Browser 'follow'
|
||||
if ((Wait-For 'the in-place Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
|
||||
throw 'A normal click did not stay in the same window.'
|
||||
}
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'mouse-back' '' 'Other.md'
|
||||
Browser 'Перегляд Markdown' '' 'Preview.md'
|
||||
Browser 'mouse-forward' '' 'Preview.md'
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'back' '' 'Other.md'
|
||||
Browser 'Перегляд Markdown' '' 'Preview.md'
|
||||
Browser 'forward' '' 'Preview.md'
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'close' '' 'Other.md'
|
||||
[void](Wait-For 'the Markdown viewers to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
|
||||
Open-File 'Preview.md' 0x73
|
||||
$window = Wait-For 'F4 to open the Markdown editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
|
||||
[void](Assert-TextWindowAppearance $window 'Editor')
|
||||
Write-Output 'Verified F3/F4 icons, separate taskbar groups and regrouping when the same window switches modes with F6.'
|
||||
$control = Scintilla $window
|
||||
Append-Character $control 'Y'
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 6
|
||||
Browser 'Перегляд Markdown'
|
||||
Browser 'appearance-full'
|
||||
if (![IO.File]::ReadAllText($original).EndsWith('Y')) { throw 'F6 rendered before saving.' }
|
||||
Post $window 0x10 0
|
||||
[void](Wait-For 'the saved Markdown viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
|
||||
Open-File 'Preview.md' 0x73
|
||||
$window = Wait-For 'the editor before a save conflict' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
|
||||
$control = Scintilla $window
|
||||
Append-Character $control 'Z'
|
||||
[IO.File]::Move($original,"$docs\replaced.md")
|
||||
[IO.File]::WriteAllText($original,'An external replacement')
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 6
|
||||
$errorDialog = Wait-For 'a save conflict error' {
|
||||
$candidate = Find-Window '#32770'
|
||||
if ($candidate -and [MarkdownUi]::GetDlgItem($candidate,1) -ne [IntPtr]::Zero) { $candidate }
|
||||
}
|
||||
Post $errorDialog 0x111 1
|
||||
if ((Find-Window 'KSwitcher.Files.Text' 'Editor') -ne $window -or
|
||||
[MarkdownUi]::Send($control,2140,0,0).ToInt64() -or
|
||||
[IO.File]::ReadAllText($original) -cne 'An external replacement') {
|
||||
throw 'The failed save left editing mode or overwrote an externally replaced file.'
|
||||
}
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 7
|
||||
Post $window 0x10 0
|
||||
[void](Wait-For 'the conflict fixture to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
|
||||
Open-File 'Plain.txt' 0x72
|
||||
$window = Wait-For 'plain-text viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
|
||||
$control = Scintilla $window
|
||||
[void](Wait-For 'plain-text read-only view' { [MarkdownUi]::Send($control,2140,0,0).ToInt64() })
|
||||
Post $control 0x100 0x75
|
||||
[void](Wait-For 'F6 plain-text editor' { !( [MarkdownUi]::Send($control,2140,0,0).ToInt64() ) })
|
||||
Post $control 0x100 0x75
|
||||
[void](Wait-For 'F6 plain-text viewer' { [MarkdownUi]::Send($control,2140,0,0).ToInt64() })
|
||||
Post $window 0x10 0
|
||||
[void](Wait-For 'plain-text viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
Open-File 'Large.md' 0x72
|
||||
$window = Wait-For 'large Markdown text fallback' { Find-Window 'KSwitcher.Files.Text' 'Large.md' }
|
||||
$control = Scintilla $window
|
||||
if (![MarkdownUi]::IsWindowVisible($control) -or ![MarkdownUi]::Send($control,2140,0,0).ToInt64()) {
|
||||
throw 'Large Markdown did not open in the text viewer.'
|
||||
}
|
||||
Post $window 0x10 0
|
||||
[void](Wait-For 'large-file viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
$previewPage = Join-Path $app 'terminal\markdown.html'
|
||||
[IO.File]::Move($previewPage,"$previewPage.disabled")
|
||||
try {
|
||||
Open-File 'Preview.md' 0x72
|
||||
$window = Wait-For 'text fallback without preview assets' { Find-Window 'KSwitcher.Files.Text' 'Preview.md' }
|
||||
$control = Scintilla $window
|
||||
if (![MarkdownUi]::IsWindowVisible($control) -or ![MarkdownUi]::Send($control,2140,0,0).ToInt64()) {
|
||||
throw 'Markdown did not open in the text viewer when preview assets were missing.'
|
||||
}
|
||||
} finally { [IO.File]::Move("$previewPage.disabled",$previewPage) }
|
||||
Write-Output 'Verified Markdown rendering, Mermaid, task checkboxes, local relative resources, F3/F4, F6 Save/Discard/Cancel/save failure and text fallback.'
|
||||
if ($LanFixture) {
|
||||
Post $window 0x10 0
|
||||
Post $main 0x10 0
|
||||
if (!$process.WaitForExit(5000)) { throw 'Files did not close before the LAN check.' }
|
||||
[IO.File]::WriteAllText($original,$fixture)
|
||||
$lanExe = Join-Path $app 'KSwitcherFilesMarkdownLanFixture.exe'
|
||||
Copy-Item -LiteralPath $LanFixture -Destination $lanExe
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'lan-webview'
|
||||
$process = Start-Process -FilePath $lanExe -ArgumentList ('"{0}"' -f $original) -PassThru -WindowStyle Normal
|
||||
$window = Wait-For 'the LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Loopback peer' }
|
||||
[void](Assert-TextWindowAppearance $window 'Viewer')
|
||||
Browser 'render'
|
||||
Browser 'search'
|
||||
Browser 'edit'
|
||||
if ((Wait-For 'LAN F6 editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }) -ne $window) {
|
||||
throw 'LAN F6 changed windows.'
|
||||
}
|
||||
[void](Assert-TextWindowAppearance $window 'Editor')
|
||||
$control = Scintilla $window
|
||||
Append-Character $control 'L'
|
||||
Post $control 0x100 0x75
|
||||
Browser 'Перегляд Markdown'
|
||||
if (![IO.File]::ReadAllText($original).EndsWith('L')) { throw 'F6 rendered before uploading the LAN edit.' }
|
||||
Browser 'follow'
|
||||
if ((Wait-For 'the in-place LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
|
||||
throw 'A LAN link did not stay in the same window.'
|
||||
}
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'back' '' 'Other.md'
|
||||
Browser 'Перегляд Markdown' '' 'Preview.md'
|
||||
Browser 'forward' '' 'Preview.md'
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'close' '' 'Other.md'
|
||||
if (!$process.WaitForExit(5000) -or $process.ExitCode) { throw 'The LAN fixture did not close normally.' }
|
||||
Write-Output 'Verified Markdown, Mermaid, relative links/images and F6 saving through an authenticated loopback LAN connection.'
|
||||
}
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
Stop-Process -Id $process.Id
|
||||
[void]$process.WaitForExit(5000)
|
||||
}
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = $data
|
||||
if ($profileCaptured) {
|
||||
foreach ($name in $profileValues) {
|
||||
if ($saved.ContainsKey($name)) { $profile.SetValue($name,$saved[$name][0],$saved[$name][1]) }
|
||||
else { $profile.DeleteValue($name,$false) }
|
||||
}
|
||||
}
|
||||
$profile.Dispose()
|
||||
if (Test-Path -LiteralPath $root) {
|
||||
$resolved = (Resolve-Path -LiteralPath $root).Path
|
||||
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
|
||||
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-markdown-test-*') {
|
||||
for ($attempt=0; $attempt -lt 40 -and (Test-Path -LiteralPath $resolved); ++$attempt) {
|
||||
try { Remove-Item -LiteralPath $resolved -Recurse -Force }
|
||||
catch {
|
||||
if ($attempt -eq 39) { throw }
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
const [port, scenario, artifact, title] = process.argv.slice(2);
|
||||
const terminalScenario = ['terminal-enter', 'terminal-copy', 'terminal-select-output'].includes(scenario);
|
||||
let socket;
|
||||
const pending = new Map();
|
||||
let sequence = 0;
|
||||
|
||||
async function waitFor(callback, label) {
|
||||
for (let i = 0; i < 150; ++i) {
|
||||
const result = await callback();
|
||||
if (result) return result;
|
||||
await delay(100);
|
||||
}
|
||||
throw new Error('Timed out waiting for ' + label);
|
||||
}
|
||||
|
||||
function command(method, params = {}) {
|
||||
const id = ++sequence;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
reject(new Error('DevTools timed out on ' + method));
|
||||
}, 5000);
|
||||
pending.set(id, reply => {
|
||||
clearTimeout(timer);
|
||||
if (reply.error) reject(new Error(reply.error.message));
|
||||
else resolve(reply.result);
|
||||
});
|
||||
socket.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
}
|
||||
|
||||
async function evaluate(expression) {
|
||||
const reply = await command('Runtime.evaluate', { expression, returnByValue: true });
|
||||
if (reply.exceptionDetails) throw new Error(reply.exceptionDetails.exception.description);
|
||||
return reply.result.value;
|
||||
}
|
||||
|
||||
async function pressKey(key, code, windowsVirtualKeyCode, modifiers = 0) {
|
||||
const params = { key, code, windowsVirtualKeyCode, modifiers };
|
||||
await command('Input.dispatchKeyEvent', { type: 'keyDown', ...params });
|
||||
await command('Input.dispatchKeyEvent', { type: 'keyUp', ...params });
|
||||
}
|
||||
|
||||
const target = await waitFor(async () => {
|
||||
const response = await fetch('http://127.0.0.1:' + port + '/json/list').catch(() => null);
|
||||
if (!response?.ok) return;
|
||||
const url = terminalScenario
|
||||
? 'https://kswitcher-terminal.invalid/index.html'
|
||||
: 'https://kswitcher-markdown.invalid/markdown.html';
|
||||
return (await response.json()).find(item => item.url === url &&
|
||||
(!title || item.title === title));
|
||||
}, 'the target WebView2 page');
|
||||
socket = new WebSocket(target.webSocketDebuggerUrl);
|
||||
socket.addEventListener('message', event => {
|
||||
const reply = JSON.parse(event.data);
|
||||
const callback = pending.get(reply.id);
|
||||
if (callback) {
|
||||
pending.delete(reply.id);
|
||||
callback(reply);
|
||||
}
|
||||
});
|
||||
await new Promise((resolve, reject) => {
|
||||
socket.addEventListener('open', resolve, { once: true });
|
||||
socket.addEventListener('error', reject, { once: true });
|
||||
});
|
||||
|
||||
try {
|
||||
if (scenario === 'terminal-select-output') {
|
||||
const selection = await waitFor(() => evaluate(`(() => {
|
||||
const marker = 'terminal-output-copy-fixture';
|
||||
const buffer = terminal.buffer.active;
|
||||
for (let row = buffer.viewportY; row < buffer.viewportY + terminal.rows; row++) {
|
||||
if (buffer.getLine(row)?.translateToString(true) !== marker) continue;
|
||||
terminal.select(0, row, marker.length);
|
||||
document.querySelector('#terminal').dispatchEvent(new PointerEvent('pointerup', { bubbles:true }));
|
||||
return terminal.getSelection();
|
||||
}
|
||||
})()`), 'the terminal output fixture');
|
||||
assert.equal(selection, 'terminal-output-copy-fixture');
|
||||
} else if (terminalScenario) {
|
||||
await evaluate('document.querySelector(".xterm-helper-textarea").focus()');
|
||||
const key = scenario === 'terminal-copy'
|
||||
? { key:'Insert', code:'Insert', modifiers:2, windowsVirtualKeyCode:45 }
|
||||
: { key:'Enter', code:'Enter', windowsVirtualKeyCode:13 };
|
||||
await command('Input.dispatchKeyEvent', { type:'keyDown', ...key });
|
||||
await command('Input.dispatchKeyEvent', { type:'keyUp', ...key });
|
||||
} else if (scenario === 'render') {
|
||||
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
|
||||
!!document.querySelector('figure svg') &&
|
||||
document.querySelector('img')?.naturalWidth === 1`), 'rendered Mermaid SVG and relative image');
|
||||
assert.equal(await evaluate(`document.querySelector('h1').textContent`), 'Перегляд Markdown');
|
||||
assert.equal(await evaluate(`[...document.querySelectorAll('nav button')].every(button => {
|
||||
const style = getComputedStyle(button);
|
||||
return style.borderTopWidth === '0px' && style.backgroundColor === 'rgba(0, 0, 0, 0)';
|
||||
})`), true);
|
||||
assert.equal(await evaluate(`document.querySelector('td').textContent`), 'Cell');
|
||||
assert.deepEqual(await evaluate(`(() => {
|
||||
const span = document.querySelector('td #nowrap-cell');
|
||||
return span && [span.textContent, getComputedStyle(span).whiteSpace,
|
||||
getComputedStyle(span).color, span.style.position, span.hasAttribute('onclick')];
|
||||
})()`), ['In Development', 'nowrap', 'rgb(255, 0, 0)', '', false]);
|
||||
assert.deepEqual(await evaluate(`(() => {
|
||||
const table = document.querySelector('#html-table');
|
||||
return table && [table.caption.textContent, table.querySelector('th').colSpan,
|
||||
table.querySelector('td strong').textContent];
|
||||
})()`), ['Raw HTML table', 2, 'Highest']);
|
||||
await waitFor(() => evaluate(`document.querySelector('img[alt="HTML relative image"]')?.naturalWidth === 1`),
|
||||
'the relative image in HTML');
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').getBoundingClientRect().height > 0`), true);
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').textContent.includes('Render target')`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
|
||||
document.querySelector('main').textContent.includes('Invalid Mermaid diagram')`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-js') && !document.querySelector('iframe')`), true);
|
||||
assert.equal(await evaluate(`performance.getEntriesByType('resource')
|
||||
.every(entry => entry.name.startsWith(location.origin + '/') || entry.name.startsWith('data:'))`), true);
|
||||
await waitFor(() => evaluate(`document.querySelector('img[alt="Missing image"]')?.title === 'Image unavailable'`),
|
||||
'missing image feedback');
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => box.checked)`), [false, true]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [true, false]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [false, true]);
|
||||
if (artifact) {
|
||||
const { cssContentSize } = await command('Page.getLayoutMetrics');
|
||||
const { data } = await command('Page.captureScreenshot', { captureBeyondViewport: true,
|
||||
clip: { x:0, y:0, width:cssContentSize.width, height:Math.min(cssContentSize.height, 620), scale:1 } });
|
||||
await writeFile(artifact, Buffer.from(data, 'base64'));
|
||||
}
|
||||
} else if (scenario === 'search-menu' || scenario === 'search') {
|
||||
const searchFocused = 'document.activeElement === document.getElementById("search-query")';
|
||||
const searchClosed = 'document.getElementById("search").hidden';
|
||||
if (scenario === 'search-menu') {
|
||||
await waitFor(() => evaluate(searchFocused), 'the viewer menu opening rendered Markdown search');
|
||||
await pressKey('Escape', 'Escape', 27);
|
||||
await waitFor(() => evaluate(searchClosed), 'Escape closing only the search');
|
||||
} else {
|
||||
await pressKey('f', 'KeyF', 70, 2);
|
||||
await waitFor(() => evaluate(searchFocused), 'Ctrl+F opening search and focusing the search field');
|
||||
const status = 'document.getElementById("search-status").value';
|
||||
const active = '[...(CSS.highlights.get("markdown-search-active") || [])][0]?.toString()';
|
||||
const query = async text => {
|
||||
await evaluate('document.getElementById("search-query").select()');
|
||||
await command('Input.insertText', { text });
|
||||
};
|
||||
await query('ЗБІГ ПОШУКУ');
|
||||
assert.equal(await evaluate(status), '1 / 2');
|
||||
const toolbar = await evaluate(`({
|
||||
queryWidth: document.getElementById('search-query').getBoundingClientRect().width,
|
||||
closeRight: document.getElementById('search-close').getBoundingClientRect().right,
|
||||
viewportWidth: document.documentElement.clientWidth
|
||||
})`);
|
||||
assert.ok(toolbar.queryWidth >= 100 && toolbar.closeRight <= toolbar.viewportWidth,
|
||||
'The search controls must fit the viewer: ' + JSON.stringify(toolbar));
|
||||
assert.equal(await evaluate(active), 'Збіг пошуку');
|
||||
await pressKey('Enter', 'Enter', 13);
|
||||
assert.equal(await evaluate(status), '2 / 2');
|
||||
assert.equal(await evaluate(active), 'збіг пошуку');
|
||||
await pressKey('F3', 'F3', 114);
|
||||
assert.equal(await evaluate(status), '1 / 2');
|
||||
await pressKey('Enter', 'Enter', 13, 8);
|
||||
assert.equal(await evaluate(status), '2 / 2');
|
||||
await pressKey('F3', 'F3', 114, 8);
|
||||
assert.equal(await evaluate(status), '1 / 2');
|
||||
await evaluate('document.getElementById("search-previous").click()');
|
||||
assert.equal(await evaluate(status), '2 / 2');
|
||||
await evaluate('document.getElementById("search-next").click()');
|
||||
assert.equal(await evaluate(status), '1 / 2');
|
||||
if (artifact) {
|
||||
const { data } = await command('Page.captureScreenshot');
|
||||
await writeFile(artifact, Buffer.from(data, 'base64'));
|
||||
}
|
||||
await query('для збіг пошуку');
|
||||
assert.equal(await evaluate(status), '1 / 1');
|
||||
assert.equal(await evaluate(active), 'для збіг пошуку');
|
||||
await query('RENDER TARGET');
|
||||
assert.equal(await evaluate(status), '1 / 1');
|
||||
assert.equal(await evaluate(active), 'Render target');
|
||||
await query('[no matches]');
|
||||
assert.equal(await evaluate(status), 'No matches');
|
||||
assert.equal(await evaluate(active), undefined);
|
||||
await pressKey('Escape', 'Escape', 27);
|
||||
assert.equal(await evaluate(searchClosed), true);
|
||||
assert.equal(await evaluate('document.documentElement.classList.contains("rendered")'), true);
|
||||
await evaluate('document.getElementById("search-open").click()');
|
||||
assert.equal(await evaluate(searchFocused), true);
|
||||
await evaluate('document.getElementById("search-close").click()');
|
||||
assert.equal(await evaluate(searchClosed), true);
|
||||
}
|
||||
} else if (scenario === 'appearance-width' || scenario === 'appearance-full') {
|
||||
const width = scenario === 'appearance-full' ? 'none' : '1200px';
|
||||
await waitFor(() => evaluate(`(() => {
|
||||
const text = getComputedStyle(document.querySelector('main'));
|
||||
return getComputedStyle(document.body).maxWidth === ${JSON.stringify(width)} &&
|
||||
text.fontSize === '24px' && text.fontFamily.startsWith('Georgia,');
|
||||
})()`), 'the saved Markdown width, font family and font size');
|
||||
} else if (scenario === 'edit') {
|
||||
await command('Input.dispatchKeyEvent', { type: 'keyDown', key: 'F6', code: 'F6', windowsVirtualKeyCode: 117 });
|
||||
} else if (['follow', 'shift-follow', 'ctrl-follow'].includes(scenario)) {
|
||||
await evaluate(`document.querySelector('a[href^="child/"]').dispatchEvent(new MouseEvent('click', {
|
||||
bubbles: true, cancelable: true, shiftKey: ${scenario === 'shift-follow'}, ctrlKey: ${scenario === 'ctrl-follow'}
|
||||
}))`);
|
||||
} else if (scenario === 'mouse-back' || scenario === 'mouse-forward') {
|
||||
const button = scenario === 'mouse-back' ? 'back' : 'forward';
|
||||
await waitFor(() => evaluate(`!document.getElementById('${button}').disabled`), button);
|
||||
await command('Input.dispatchMouseEvent', {type:'mousePressed', x:15, y:80, button, buttons:button === 'back' ? 8 : 16});
|
||||
await command('Input.dispatchMouseEvent', {type:'mouseReleased', x:15, y:80, button, buttons:0});
|
||||
} else if (scenario === 'back' || scenario === 'forward') {
|
||||
await waitFor(() => evaluate(`!document.getElementById('${scenario}').disabled`), scenario);
|
||||
await evaluate(`document.getElementById('${scenario}').click()`);
|
||||
} else if (scenario === 'cycle') {
|
||||
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers:2, windowsVirtualKeyCode:9});
|
||||
} else if (scenario === 'close') {
|
||||
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'w', code:'KeyW', modifiers:2, windowsVirtualKeyCode:87});
|
||||
} else {
|
||||
await waitFor(() => evaluate('document.documentElement?.classList.contains("rendered") && ' +
|
||||
'document.querySelector("h1")?.textContent === ' + JSON.stringify(scenario)), scenario);
|
||||
if (scenario === 'Linked Markdown') {
|
||||
await waitFor(() => evaluate('scrollY > 0 && document.getElementById("target-heading").getBoundingClientRect().top < innerHeight'),
|
||||
'the relative heading fragment to scroll into view');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
socket.close();
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
#include <winsock2.h>
|
||||
#include "files_text_window.h"
|
||||
#include "lan_files.h"
|
||||
#include "platform.h"
|
||||
#include <shellapi.h>
|
||||
#include <thread>
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
||||
{
|
||||
int count{};
|
||||
auto args=CommandLineToArgvW(GetCommandLineW(),&count);
|
||||
if(!args || count!=2)
|
||||
{
|
||||
if(args) LocalFree(args);
|
||||
return 1;
|
||||
}
|
||||
const std::filesystem::path document=args[1];
|
||||
LocalFree(args);
|
||||
if(FAILED(CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED))) return 1;
|
||||
WSADATA network{};
|
||||
if(WSAStartup(MAKEWORD(2,2),&network))
|
||||
{
|
||||
CoUninitialize();
|
||||
return 1;
|
||||
}
|
||||
int result=0;
|
||||
try
|
||||
{
|
||||
using namespace ks;
|
||||
using namespace ks::lan;
|
||||
const auto serverId=randomHex(16), clientId=randomHex(16), key=randomHex(32);
|
||||
FilesListener listener(serverId,[&](const auto &id){return id==clientId?key:std::string{};},0);
|
||||
if(!listener.port()) throw std::runtime_error("Could not bind the LAN test listener.");
|
||||
const auto pairing=Json{{"enabled",true},{"id",clientId},
|
||||
{"trusted",{{serverId,{{"key",key}}}}}}.dump();
|
||||
atomicWrite(dataDirectory()/L"lan-pairing.bin",protect(Bytes(pairing.begin(),pairing.end())));
|
||||
const FilesPeer peer{serverId,"127.0.0.1",L"Loopback peer",listener.port()};
|
||||
std::jthread server([&](std::stop_token stop) {
|
||||
while(!stop.stop_requested()) { listener.poll(); Sleep(5); }
|
||||
});
|
||||
WNDCLASSW type{};
|
||||
type.hInstance=instance;
|
||||
type.lpszClassName=L"KSwitcher.Files.MarkdownFixture";
|
||||
type.lpfnWndProc=[](HWND window,UINT message,WPARAM wparam,LPARAM lparam)->LRESULT {
|
||||
if(message==WM_DESTROY) { files::textWindowOwnerClosed(); return 0; }
|
||||
return DefWindowProcW(window,message,wparam,lparam);
|
||||
};
|
||||
if(!RegisterClassW(&type)) throw std::runtime_error("Could not register the LAN fixture.");
|
||||
const auto owner=CreateWindowW(type.lpszClassName,L"LAN Markdown fixture",WS_OVERLAPPEDWINDOW,
|
||||
20,20,960,720,nullptr,nullptr,instance,nullptr);
|
||||
if(!owner) throw std::runtime_error("Could not open the LAN fixture.");
|
||||
files::TextDialogs dialogs{};
|
||||
dialogs.readFont=[] {
|
||||
files::TextWindowFont font{};
|
||||
wcscpy_s(font.font.lfFaceName,L"Consolas");
|
||||
font.tenthsOfPoint=100;
|
||||
return font;
|
||||
};
|
||||
dialogs.confirmExisting=[](HWND){return true;};
|
||||
dialogs.confirmSave=[](HWND)->INT_PTR {return IDYES;};
|
||||
dialogs.message=[](HWND,const wchar_t *message){log(message);};
|
||||
dialogs.dismissOwned=[](HWND){return false;};
|
||||
files::openTextWindow(owner,document,false,dialogs,&peer);
|
||||
DestroyWindow(owner);
|
||||
MSG message{};
|
||||
while(GetMessageW(&message,nullptr,0,0)>0)
|
||||
{
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
ks::log(L"LAN Markdown fixture: "+ks::wide(error.what()));
|
||||
result=1;
|
||||
}
|
||||
WSACleanup();
|
||||
CoUninitialize();
|
||||
return result;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
param([Parameter(Mandatory)][string]$Executable)
|
||||
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly)
|
||||
$ErrorActionPreference='Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @"
|
||||
@@ -10,6 +10,7 @@ public static class SearchArrowTest {
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr hwnd, int id);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr hwnd, uint message, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr SendRect(IntPtr hwnd, uint message, IntPtr w, out Rect rect);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SendText(IntPtr hwnd, uint message, IntPtr w, string l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr GetText(IntPtr hwnd, uint message, IntPtr w, StringBuilder l);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hwnd, uint message, IntPtr w, IntPtr l);
|
||||
@@ -94,6 +95,23 @@ function Select-Row($Panel, $Name) {
|
||||
function Post($Window, $Message, $W, $L = 0) {
|
||||
if (![SearchArrowTest]::PostMessage($Window, $Message, $W, $L)) { throw "Post failed" }
|
||||
}
|
||||
function Click-PanelRow($Panel, $Row) {
|
||||
$bounds=[SearchArrowTest+Rect]::new()
|
||||
if([SearchArrowTest]::SendRect($Panel,0x198,$Row,[ref]$bounds).ToInt64() -eq -1){
|
||||
throw "Missing file panel row $Row"
|
||||
}
|
||||
$point=([int](($bounds.Top+$bounds.Bottom)/2) -shl 16) -bor 6
|
||||
Post $Panel 0x201 1 $point
|
||||
Post $Panel 0x202 0 $point
|
||||
}
|
||||
function Read-PanelHighlights($Trace, $Start) {
|
||||
$highlight=@{}
|
||||
Get-Content -LiteralPath $Trace | Select-Object -Skip $Start |
|
||||
ForEach-Object { if($_ -match '^\d+ panel-draw ([01]) (\d+) ([01]) '){
|
||||
$highlight["$($Matches[1])/$($Matches[2])"]=$Matches[3]
|
||||
} }
|
||||
return $highlight
|
||||
}
|
||||
function Assert-FarCheckbox($Dialog, [int]$Id, $NextControl) {
|
||||
$checkbox=[SearchArrowTest]::GetDlgItem($Dialog,$Id)
|
||||
Post $Dialog 0x28 $checkbox 1
|
||||
@@ -213,12 +231,61 @@ $scratch=Join-Path ([IO.Path]::GetDirectoryName((Resolve-Path -LiteralPath $Exec
|
||||
New-Item -ItemType Directory -Path $scratch | Out-Null
|
||||
$fixture = Join-Path $scratch ('files-editor-ui-' + [Guid]::NewGuid().ToString('N') + '.cs')
|
||||
[IO.File]::WriteAllText($fixture, "public class Test {`r`n}`r`n")
|
||||
foreach($name in 'A.txt','B.txt','C.txt','D.txt'){
|
||||
[IO.File]::WriteAllText((Join-Path $scratch $name),'Cursor test fixture')
|
||||
}
|
||||
$rightFixture=Join-Path $scratch 'Right fixture'
|
||||
New-Item -ItemType Directory -Path $rightFixture | Out-Null
|
||||
foreach($name in 'A.txt','B.txt','C.txt','D.txt'){
|
||||
[IO.File]::WriteAllText((Join-Path $rightFixture $name),'Cursor test fixture')
|
||||
}
|
||||
$copy=Join-Path $scratch 'KSwitcher.Files.search-arrow-test.exe'
|
||||
Copy-Item -LiteralPath $Executable -Destination $copy
|
||||
$process = Start-Process -FilePath $copy -PassThru -WindowStyle Hidden
|
||||
$profile=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
|
||||
$saved=@{}
|
||||
foreach($name in $keysToRestore){
|
||||
if($name -in $profile.GetValueNames()){
|
||||
$saved[$name]=@($profile.GetValue($name),$profile.GetValueKind($name))
|
||||
}
|
||||
}
|
||||
$process=$null
|
||||
$paintTrace=$null
|
||||
try {
|
||||
$profile.SetValue('LeftPath',$scratch)
|
||||
$profile.SetValue('RightPath',$rightFixture)
|
||||
$profile.DeleteValue('LeftCursor',$false)
|
||||
$profile.DeleteValue('RightCursor',$false)
|
||||
$process=Start-Process -FilePath $copy -ArgumentList '--terminal-trace' -PassThru -WindowStyle Normal
|
||||
$paintTrace=Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
|
||||
$previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$main = Wait-Until { Find-Window 'KSwitcher.Files' $process.Id }
|
||||
$leftPanel=[SearchArrowTest]::GetDlgItem($main,102)
|
||||
$rightPanel=[SearchArrowTest]::GetDlgItem($main,103)
|
||||
$clicks=if(!$KeyboardCursorOnly){
|
||||
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
|
||||
}
|
||||
foreach($check in $clicks) {
|
||||
$before=[SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32()
|
||||
$top=[SearchArrowTest]::Send($check.Panel,0x18E,0,0).ToInt32()
|
||||
$row=if($before -eq $top){$top+1}else{$top}
|
||||
[void](Wait-Until { Test-Path -LiteralPath $paintTrace })
|
||||
Start-Sleep -Milliseconds 150
|
||||
$lineCount=@(Get-Content -LiteralPath $paintTrace).Count
|
||||
Click-PanelRow $check.Panel $row
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32() -eq $row })
|
||||
Start-Sleep -Milliseconds 150
|
||||
$highlight=Read-PanelHighlights $paintTrace $lineCount
|
||||
$draws=@($highlight.Keys)
|
||||
if("$($check.Index)/$row" -notin $draws -or $draws.Count -gt 3){
|
||||
throw "Clicking a row repainted unrelated file rows. Drawn rows: $draws"
|
||||
}
|
||||
if($highlight["$($check.Index)/$row"] -ne '1' -or
|
||||
($before -ge $top -and $highlight["$($check.Index)/$before"] -ne '0')){
|
||||
throw 'The new row must be painted active and the previous visible row must lose its highlight.'
|
||||
}
|
||||
}
|
||||
if($clicks){Write-Output 'Verified file clicks repaint only cursor rows in the active pane and when changing panes.'}
|
||||
Post $main 0x111 132
|
||||
$commandMenu=Wait-Until {
|
||||
$list=[SearchArrowTest]::GetDlgItem($main,121)
|
||||
@@ -230,9 +297,13 @@ try {
|
||||
[void][SearchArrowTest]::GetText($commandMenu,0x189,$i,$label)
|
||||
$label.ToString()
|
||||
})
|
||||
if (($rows -join '|') -cne "Refresh`tF2|Folder shortcuts||View`tF3|Edit`tF4|View externally`tAlt+F3|Edit externally`tAlt+F4") {
|
||||
if (($rows -join '|') -cne "Refresh panel`tCtrl+R|Folder shortcuts||View`tF3|Edit`tF4|View externally`tAlt+F3|Edit externally`tAlt+F4") {
|
||||
throw 'Commands did not group local actions or showed a LAN-only section.'
|
||||
}
|
||||
Post $commandMenu 0x100 38
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq ($count-1) })
|
||||
Post $commandMenu 0x100 40
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 0 })
|
||||
Post $commandMenu 0x100 40
|
||||
Post $commandMenu 0x100 40
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 3 })
|
||||
@@ -264,6 +335,71 @@ try {
|
||||
Select-Row $panel "[$component]"
|
||||
[void][SearchArrowTest]::Send($panel,0x100,13,0)
|
||||
}
|
||||
$fixtureRow=[SearchArrowTest]::SendText($panel,0x1A2,-1,([IO.Path]::GetFileName($fixture))).ToInt32()
|
||||
Click-PanelRow $panel $fixtureRow
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($panel,0x188,0,0).ToInt32() -eq $fixtureRow })
|
||||
$inputBox=[SearchArrowTest]::FindWindowEx($main,0,'Edit',[NullString]::Value)
|
||||
[void](Wait-Until { [SearchArrowTest]::FocusedControl($main) -eq $inputBox })
|
||||
[void][SearchArrowTest]::SendText($inputBox,0xC,0,'')
|
||||
$last=[SearchArrowTest]::Send($panel,0x18B,0,0).ToInt32()-1
|
||||
$keys=@(
|
||||
@{Name='Left'; Code=37; Row=0}
|
||||
@{Name='Right'; Code=39; Row=$last}
|
||||
@{Name='Left'; Code=37; Row=0}
|
||||
@{Name='Down'; Code=40; Row=1}
|
||||
@{Name='Up'; Code=38; Row=0}
|
||||
@{Name='End'; Code=35; Row=$last}
|
||||
@{Name='Home'; Code=36; Row=0}
|
||||
@{Name='Page Down'; Code=34; Row=$last}
|
||||
@{Name='Page Up'; Code=33; Row=0}
|
||||
)
|
||||
foreach($key in $keys){
|
||||
$previous=[SearchArrowTest]::Send($panel,0x188,0,0).ToInt32()
|
||||
Start-Sleep -Milliseconds 100
|
||||
$lineCount=@(Get-Content -LiteralPath $paintTrace).Count
|
||||
Post $inputBox 0x100 $key.Code
|
||||
try {
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($panel,0x188,0,0).ToInt32() -eq $key.Row })
|
||||
} catch {
|
||||
$actual=[SearchArrowTest]::Send($panel,0x188,0,0).ToInt32()
|
||||
throw "$($key.Name) selected row $actual, expected row $($key.Row)."
|
||||
}
|
||||
Start-Sleep -Milliseconds 150
|
||||
$highlight=Read-PanelHighlights $paintTrace $lineCount
|
||||
if($highlight["0/$($key.Row)"] -ne '1' -or $highlight["0/$previous"] -ne '0'){
|
||||
throw "$($key.Name) left the previous row highlighted or did not paint the new row active."
|
||||
}
|
||||
}
|
||||
Write-Output 'Verified cursor highlighting after arrows, Home, End, Page Up and Page Down from the command line.'
|
||||
if($KeyboardCursorOnly){return}
|
||||
Click-PanelRow $panel $fixtureRow
|
||||
$deleteButton=[SearchArrowTest]::GetDlgItem($main,117)
|
||||
$deleteLabel=[Text.StringBuilder]::new(64)
|
||||
[void][SearchArrowTest]::GetText($deleteButton,0xD,$deleteLabel.Capacity,$deleteLabel)
|
||||
if($deleteLabel.ToString() -cne 'F8 Delete'){throw 'The F8 Delete key bar button is missing.'}
|
||||
$bounds=Read-Bounds $deleteButton
|
||||
$windowBounds=Read-Bounds $main
|
||||
$bitmap=[Drawing.Bitmap]::new($windowBounds.Right-$windowBounds.Left,$windowBounds.Bottom-$windowBounds.Top)
|
||||
try {
|
||||
$graphics=[Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
$dc=$graphics.GetHdc()
|
||||
try { if(![SearchArrowTest]::PrintWindow($main,$dc,0)){throw 'Could not render the Files window.'} }
|
||||
finally { $graphics.ReleaseHdc($dc) }
|
||||
} finally {$graphics.Dispose()}
|
||||
$y=$bounds.Top-$windowBounds.Top+1
|
||||
$cap=$bitmap.GetPixel(($bounds.Left-$windowBounds.Left+1),$y)
|
||||
$action=$bitmap.GetPixel(($bounds.Right-$windowBounds.Left-2),$y)
|
||||
if($cap.ToArgb() -ne [Drawing.Color]::Black.ToArgb() -or $action.ToArgb() -eq $cap.ToArgb()){
|
||||
throw 'The key bar no longer separates its dark key cap from the action segment.'
|
||||
}
|
||||
} finally {$bitmap.Dispose()}
|
||||
Post $deleteButton 0xF5 0
|
||||
$deleteDialog=Wait-Until { Find-Window '#32770' $process.Id 6 }
|
||||
Post $deleteDialog 0x111 2
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindow($deleteDialog) })
|
||||
if(!(Test-Path -LiteralPath $fixture)){throw 'Canceling F8 Delete removed the fixture.'}
|
||||
Write-Output 'Verified F8 Delete on the key bar opens the normal confirmation.'
|
||||
$newFolder='F7 тестова папка'
|
||||
Post $panel 0x100 0x76
|
||||
$makeDialog=Wait-Until { Find-Window '#32770' $process.Id 361 }
|
||||
@@ -348,7 +484,11 @@ try {
|
||||
Post $selector 0x100 0x73
|
||||
$popup=Wait-Until { Find-Window 'KSwitcher.Files.DropDown' $process.Id }
|
||||
Assert-FarDropDown $popup $selector ($arrowBounds.Right-$arrowBounds.Left)
|
||||
for ($row=0; $row -lt $kind; $row++) { Post $popup 0x100 0x28 }
|
||||
Post $popup 0x100 0x26
|
||||
if ($kind -eq 1) {
|
||||
Post $popup 0x100 0x28
|
||||
Post $popup 0x100 0x28
|
||||
}
|
||||
Post $popup 0x100 13
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindow($popup) })
|
||||
[void](Wait-Until { [SearchArrowTest]::IsWindowEnabled($targetField) })
|
||||
@@ -679,11 +819,17 @@ try {
|
||||
if (!$process.WaitForExit(5000)) { throw 'Files did not exit after its last window closed.' }
|
||||
}
|
||||
finally {
|
||||
if (!$process.HasExited) {
|
||||
if ($process -and !$process.HasExited) {
|
||||
Stop-Process -Id $process.Id
|
||||
[void]$process.WaitForExit(5000)
|
||||
}
|
||||
if ($previousDpi) { [void][SearchArrowTest]::SetThreadDpiAwarenessContext($previousDpi) }
|
||||
if($paintTrace -and (Test-Path -LiteralPath $paintTrace)){Remove-Item -LiteralPath $paintTrace -Force}
|
||||
foreach($name in $keysToRestore){
|
||||
if($saved.ContainsKey($name)){$profile.SetValue($name,$saved[$name][0],$saved[$name][1])}
|
||||
else{$profile.DeleteValue($name,$false)}
|
||||
}
|
||||
$profile.Dispose()
|
||||
$resolved=(Resolve-Path -LiteralPath $scratch).Path
|
||||
$root=(Resolve-Path -LiteralPath (Split-Path -Parent $scratch)).Path
|
||||
if ([IO.Path]::GetDirectoryName($resolved) -eq $root -and (Split-Path -Leaf $resolved) -like 'search-arrow-test-*') {
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -133,6 +133,27 @@ int main()
|
||||
fs::create_directory(root);
|
||||
const auto client=randomHex(16),first=randomHex(16),second=randomHex(16),key=randomHex(32);
|
||||
auto lookup=[&](const std::string &id){return id==client?key:std::string{};};
|
||||
{
|
||||
auto previous=std::make_unique<FilesListener>(first,lookup,0);
|
||||
const auto port=previous->port();
|
||||
require(port!=0,"old listener bound before restart");
|
||||
FilesListener restarting(first,lookup,port);
|
||||
require(restarting.port()==0,"new listener must not take over an occupied port");
|
||||
previous.reset();
|
||||
const auto deadline=GetTickCount64()+4000;
|
||||
while(!restarting.port() && GetTickCount64()<deadline)
|
||||
{
|
||||
restarting.poll();
|
||||
Sleep(20);
|
||||
}
|
||||
require(restarting.port()==port,"listener automatically recovers after its port becomes available");
|
||||
std::jthread pollingRestarted([&](std::stop_token stop)
|
||||
{
|
||||
while(!stop.stop_requested()){restarting.poll();Sleep(5);}
|
||||
});
|
||||
FilesConnection recovered(FilesPeer{first,"127.0.0.1",L"Recovered",port},client,key);
|
||||
checkFileReply(recovered.call({{"action","drives"}}));
|
||||
}
|
||||
std::atomic<bool> allowTerminal{};
|
||||
std::atomic<unsigned> hibernateRequests{};
|
||||
std::atomic<unsigned> updateRequests{};
|
||||
@@ -190,11 +211,33 @@ int main()
|
||||
require(console.find("PowerShell error")!=console.npos && console.find("CLIXML")==console.npos,
|
||||
"remote PowerShell errors were not returned as text");
|
||||
console.clear();
|
||||
const auto restrictionsExit=runRemoteCommand(host,root,
|
||||
L"$principal=[Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()); "
|
||||
L"if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -or "
|
||||
L"$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::PowerUser)) { exit 8 }; "
|
||||
L"$privileges=& (Join-Path $env:SystemRoot 'System32\\whoami.exe') /priv /fo csv /nh; "
|
||||
L"if ($LASTEXITCODE -or ($privileges | ConvertFrom-Csv -Header Name,Description,State | "
|
||||
L"Where-Object { $_.Name -like 'Se*Privilege' -and $_.Name -ne 'SeChangeNotifyPrivilege' })) { exit 9 }; "
|
||||
L"Write-Output 'LAN shell is restricted'",
|
||||
[&](std::string_view part){console+=part;});
|
||||
require(restrictionsExit==0 && console.find("LAN shell is restricted")!=console.npos,
|
||||
"remote PowerShell must run with standard user rights and without extra token privileges");
|
||||
console.clear();
|
||||
const auto directoryExit=runRemoteCommand(host,root,
|
||||
L"Write-Progress -Activity 'Hidden progress probe' -Status 'Working'; dir",
|
||||
[&](std::string_view part){console+=part;});
|
||||
require(directoryExit==0 && console.find("CLIXML")==console.npos &&
|
||||
console.find("Hidden progress probe")==console.npos,"remote directory command included progress metadata");
|
||||
for(const auto marker:{L"dir-first-marker.txt",L"dir-second-marker.txt"})
|
||||
{
|
||||
save(root/marker,"remote directory fixture");
|
||||
FilesConnection separateCommand(one,client,key);
|
||||
console.clear();
|
||||
const auto code=runRemoteCommand(separateCommand,root,L"dir",
|
||||
[&](std::string_view part){console+=part;});
|
||||
require(code==0 && console.find(utf8(marker))!=console.npos,
|
||||
"successive remote dir commands must list the current files and exit");
|
||||
}
|
||||
std::stop_source cancel;
|
||||
try
|
||||
{
|
||||
|
||||
@@ -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
@@ -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{};
|
||||
|
||||
+2
-2
@@ -770,8 +770,8 @@ int main(int argc, char **argv)
|
||||
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");
|
||||
|
||||
+16
-4
@@ -11,6 +11,8 @@ try {
|
||||
$otherRoot=Join-Path $root 'other-install'
|
||||
[IO.Directory]::CreateDirectory($companionRoot) | Out-Null
|
||||
[IO.Directory]::CreateDirectory($otherRoot) | Out-Null
|
||||
[IO.Directory]::CreateDirectory((Join-Path $companionRoot 'tools')) | Out-Null
|
||||
[IO.Directory]::CreateDirectory((Join-Path $otherRoot 'tools')) | Out-Null
|
||||
$companions=@()
|
||||
$Journal=Join-Path $root 'update.log'
|
||||
try {
|
||||
@@ -18,15 +20,25 @@ try {
|
||||
@{Root=$companionRoot; Name='KSwitcher.Files.exe'},
|
||||
@{Root=$companionRoot; Name='KSwitcher.Screenshot.exe'},
|
||||
@{Root=$companionRoot; Name='KSwitcher.Config.exe'},
|
||||
@{Root=$otherRoot; Name='KSwitcher.Files.exe'})) {
|
||||
@{Root=$companionRoot; Name='KSwitcher.exe'},
|
||||
@{Root=$otherRoot; Name='KSwitcher.Files.exe'},
|
||||
@{Root=$companionRoot; Name='tools/StayHere.exe'},
|
||||
@{Root=$otherRoot; Name='tools/StayHere.exe'})) {
|
||||
$path=Join-Path $fixture.Root $fixture.Name
|
||||
Copy-Item -LiteralPath (Join-Path ([Environment]::SystemDirectory) 'ping.exe') -Destination $path
|
||||
$companions+=Start-Process -FilePath $path -ArgumentList '-t','127.0.0.1' -WindowStyle Hidden -PassThru
|
||||
}
|
||||
$oldFiles=Join-Path $companionRoot 'KSwitcher.Files.exe'
|
||||
$backup=Join-Path $companionRoot '.kswitcher-update-0123456789abcdef0123456789abcdef/backup'
|
||||
[IO.Directory]::CreateDirectory($backup) | Out-Null
|
||||
Move-Item -LiteralPath $oldFiles -Destination $backup
|
||||
Copy-Item -LiteralPath (Join-Path $backup 'KSwitcher.Files.exe') -Destination $oldFiles
|
||||
$companions+=Start-Process -FilePath $oldFiles -ArgumentList '-t','127.0.0.1' -WindowStyle Hidden -PassThru
|
||||
Stop-UpdateCompanions $companionRoot
|
||||
Assert (@($companions[0..2] | Where-Object HasExited).Count -eq 3) 'unattended update closes all companions in its installation'
|
||||
Assert (!$companions[3].HasExited) 'unattended update leaves a companion from another installation running'
|
||||
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'LAN update: Closing KSwitcher\.' }).Count -eq 3) 'unattended update journals every companion closure'
|
||||
Assert (@($companions[0,1,2,3,5,7] | Where-Object HasExited).Count -eq 6) 'update closes resident helpers, both Files processes and bundled StayHere in its installation'
|
||||
Assert (!$companions[4].HasExited -and !$companions[6].HasExited) 'update leaves Files and StayHere from another installation running'
|
||||
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'Update: Closing (KSwitcher|StayHere)' }).Count -eq 6) 'update journals every companion closure'
|
||||
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'Update: Closed (KSwitcher|StayHere)' }).Count -eq 6) 'update confirms each companion exited'
|
||||
} finally {
|
||||
foreach ($companion in $companions) {
|
||||
if (!$companion.HasExited) { $companion.Kill(); $companion.WaitForExit() }
|
||||
|
||||
@@ -21,3 +21,19 @@ for color, points in polygons:
|
||||
im = im.resize((256,256),Image.Resampling.LANCZOS)
|
||||
im.save(root / 'kswitcher.png')
|
||||
im.save(root / 'kswitcher.ico', sizes=[(s,s) for s in (16,20,24,32,40,48,64,128,256)])
|
||||
|
||||
for mode, color in [('editor', '#4F46E5'), ('viewer', '#087C73')]:
|
||||
image = Image.new('RGBA', (32*scale, 32*scale))
|
||||
draw = ImageDraw.Draw(image)
|
||||
draw.rounded_rectangle((scale, scale, 31*scale, 31*scale), radius=7*scale, fill=color)
|
||||
if mode == 'editor':
|
||||
draw.polygon([(x*scale, y*scale) for x, y in
|
||||
[(7, 25), (8, 19), (20, 7), (23, 7), (26, 10), (26, 12), (14, 24)]], fill='white')
|
||||
draw.line([(18*scale, 9*scale), (24*scale, 15*scale)], fill=color, width=2*scale)
|
||||
else:
|
||||
draw.polygon([(x*scale, y*scale) for x, y in
|
||||
[(5, 16), (8, 12), (12, 9), (16, 8), (20, 9), (24, 12),
|
||||
(27, 16), (24, 20), (20, 23), (16, 24), (12, 23), (8, 20)]], fill='white')
|
||||
draw.ellipse((12*scale, 12*scale, 20*scale, 20*scale), fill=color)
|
||||
image.resize((256, 256), Image.Resampling.LANCZOS).save(root / f'kswitcher-files-{mode}.ico',
|
||||
sizes=[(s, s) for s in (16, 20, 24, 32, 40, 48, 64, 128, 256)])
|
||||
@@ -10,7 +10,9 @@ if (!(Test-Path "$deps/sdk/build/native/include/WebView2.h")) {
|
||||
$assets = New-Item -ItemType Directory -Force (Join-Path $Destination 'terminal')
|
||||
foreach ($package in @(
|
||||
@{ Name='xterm'; Spec='@xterm/[email protected]'; Archive='xterm-xterm-6.0.0.tgz'; Files=@{'lib/xterm.js'='xterm.js'; 'css/xterm.css'='xterm.css'; 'LICENSE'='xterm-LICENSE.txt'} },
|
||||
@{ Name='fit'; Spec='@xterm/[email protected]'; Archive='xterm-addon-fit-0.11.0.tgz'; Files=@{'lib/addon-fit.js'='addon-fit.js'; 'LICENSE'='addon-fit-LICENSE.txt'} }
|
||||
@{ Name='fit'; Spec='@xterm/[email protected]'; Archive='xterm-addon-fit-0.11.0.tgz'; Files=@{'lib/addon-fit.js'='addon-fit.js'; 'LICENSE'='addon-fit-LICENSE.txt'} },
|
||||
@{ Name='markdown-it'; Spec='[email protected]'; Archive='markdown-it-15.0.3.tgz'; Files=@{'dist/browser/markdown-it.umd.min.js'='markdown-it.js'; 'LICENSE'='markdown-it-LICENSE.txt'} },
|
||||
@{ Name='mermaid'; Spec='[email protected]'; Archive='mermaid-12.3.0.tgz'; Files=@{'dist/mermaid.min.js'='mermaid.js'; 'LICENSE'='mermaid-LICENSE.txt'} }
|
||||
)) {
|
||||
if (!(Test-Path "$deps/$($package.Archive)")) {
|
||||
& npm.cmd pack $package.Spec --pack-destination $deps.FullName --silent | Out-Host
|
||||
|
||||
Reference in new issue
Block a user