Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
626fb685e5 | ||
|
|
8538c595e1 | ||
|
|
7f54f12bf2 | ||
|
|
e4ae9b6415 | ||
|
|
c789cdb1fe | ||
|
|
dc645b9e46 | ||
|
|
19b3a24a71 | ||
|
|
48ca436b7d | ||
|
|
6da3af0ae2 | ||
|
|
4eb41bac2b | ||
|
|
2ea4f6f914 | ||
|
|
36f0b6ef8e | ||
|
|
3aafc1f937 | ||
|
|
6215675cb4 | ||
|
|
56c6257465 | ||
|
|
64b03a2168 | ||
|
|
36baeeb081 | ||
|
|
7698ea040d | ||
|
|
84d911ae9e |
No files matched your search
+22
-1
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.89 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.96 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
@@ -149,6 +149,27 @@ 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)
|
||||
find_program(KSWITCHER_NODE NAMES node)
|
||||
if(KSWITCHER_NODE)
|
||||
add_executable(KSwitcherFilesMarkdownLanFixture WIN32 tests/files_markdown_lan.cpp
|
||||
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp)
|
||||
target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText)
|
||||
add_dependencies(KSwitcherFilesMarkdownLanFixture KSwitcherTerminalAssets)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesMarkdownLanFixture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
target_compile_options(KSwitcherFilesMarkdownLanFixture PRIVATE /utf-8)
|
||||
else()
|
||||
target_link_options(KSwitcherFilesMarkdownLanFixture PRIVATE -municode -static)
|
||||
endif()
|
||||
add_test(NAME files-markdown-viewer
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_markdown.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Node "${KSWITCHER_NODE}"
|
||||
-LanFixture "$<TARGET_FILE:KSwitcherFilesMarkdownLanFixture>")
|
||||
set_tests_properties(files-markdown-viewer PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
|
||||
endif()
|
||||
add_executable(KSwitcherLanInputTests tests/lan_input.cpp)
|
||||
target_link_libraries(KSwitcherLanInputTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
|
||||
+50
@@ -13,8 +13,20 @@ Far Manager є зразком для оформлення файлового м
|
||||
Це діє і для вкладених діалогів. Під час файлової операції Cancel спершу
|
||||
просить підтвердити переривання.
|
||||
|
||||
Спільне повідомлення Files підлаштовується під заголовок і кількість рядків.
|
||||
Висота діалогу залежить від видимого вмісту. Приховані та порожні секції
|
||||
не займають місця. Перед завершенням змін перевір коротке повідомлення й
|
||||
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
|
||||
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
|
||||
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
|
||||
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
|
||||
Warning і початковий фокус на No.
|
||||
|
||||
## Скорочення
|
||||
|
||||
- У меню Files і його списках, що випадають, стрілки вгору й вниз
|
||||
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
|
||||
|
||||
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
|
||||
документ — у програмі, призначеній для його типу у Windows. EXE запускається
|
||||
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
|
||||
@@ -24,11 +36,14 @@ Far Manager є зразком для оформлення файлового м
|
||||
- У головному вікні клавіатурний фокус залишається в командному рядку.
|
||||
Tab перемикає активну панель, клік вибирає рядок, а стрілки вгору й вниз,
|
||||
Page Up і Page Down пересувають курсор у панелі навіть під час набору команди.
|
||||
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
|
||||
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
|
||||
текст із буфера обміну в позицію курсора або замінюють виділення.
|
||||
Enter запускає введену команду або відкриває поточний елемент, якщо рядок
|
||||
порожній. Escape очищає рядок.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
|
||||
що й клавіша F8.
|
||||
- У віддаленій панелі Enter запускає введену команду PowerShell на
|
||||
спареному ПК в поточному каталозі цієї панелі. Вивід і код завершення
|
||||
з’являються в терміналі Files як текст. Службовий прогрес PowerShell
|
||||
@@ -58,8 +73,14 @@ Far Manager є зразком для оформлення файлового м
|
||||
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
|
||||
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
|
||||
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
|
||||
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
|
||||
зберігаються для наявних елементів, а підраховані через F3 розміри папок
|
||||
скидаються. F2 також виконує цю дію.
|
||||
- Ctrl+C копіює весь введений у командний рядок текст, навіть коли виділено
|
||||
лише його частину.
|
||||
- Ctrl+Insert копіює імена позначених файлів і папок активної панелі в порядку
|
||||
відображення, по одному на рядок. Якщо позначок немає, копіюється ім’я під
|
||||
курсором. Шляхи й рядок `..` пропускаються.
|
||||
|
||||
- Ctrl+E підставляє останню команду. Повторне натискання
|
||||
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
|
||||
@@ -98,6 +119,10 @@ Far Manager є зразком для оформлення файлового м
|
||||
а Enter відкриває поточний елемент.
|
||||
- F9 перемикає головне меню Files. Після закриття фокус повертається в командний рядок. Коли меню відкрите, Alt з літерою верхнього рівня відкриває відповідний пункт.
|
||||
- Коли головне меню відкрите, L, F, C, O та R відкривають Left, Files, Commands, Options та Right. У підменю підсвічена літера викликає відповідну команду. Літери унікальні в межах поточного рівня. Усталені мнемоніки мають пріоритет, зокрема X для Exit.
|
||||
- У Commands лінії відокремлюють навігацію панелі, перегляд і редагування
|
||||
та керування віддаленим ПК. Остання група з’являється разом зі своїм
|
||||
роздільником лише в активній LAN-панелі. Роздільники пропускаються під
|
||||
час навігації й не реагують на клік.
|
||||
- Глобальне скорочення **Open KSwitcher Files** можна змінити або очистити в налаштуваннях. Для профілю без цього поля пропонується Ctrl+Alt+F, якщо Windows реєструє комбінацію і вона вільна серед прив’язок KSwitcher.
|
||||
- Глобальне скорочення повертає до відкритого вікна Files у поточній сесії Windows або запускає Files, якщо такого вікна немає. Пункт **Files** у треї відкриває нове вікно.
|
||||
|
||||
@@ -116,6 +141,31 @@ Far Manager є зразком для оформлення файлового м
|
||||
відкриваються в окремих немодальних вікнах із власними кнопками на панелі
|
||||
завдань Windows. При повторному відкритті Files пропонує перейти до вже
|
||||
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
|
||||
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
|
||||
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
|
||||
Помилка збереження залишає відкритим редактор зі змінами.
|
||||
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
|
||||
у порядку їх відкриття.
|
||||
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
|
||||
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
|
||||
із підсвічуванням Markdown.
|
||||
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
|
||||
Вихідний текст приховано, доки Markdown і Mermaid готують перегляд.
|
||||
Звичайний клік відкриває внутрішнє посилання в тому самому вікні,
|
||||
Shift+клік відкриває окреме вікно. Назад і вперед працюють через стрілки
|
||||
перегляду, бічні кнопки миші й Alt+←/→. Ctrl+W закриває перегляд.
|
||||
Коли локальний Markdown оновлюється на диску, відкритий перегляд
|
||||
перерендерюється зі збереженням позиції прокрутки.
|
||||
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
|
||||
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
|
||||
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
|
||||
8 МіБ, F3 відкриває текстовий перегляд.
|
||||
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
|
||||
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
|
||||
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
|
||||
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
|
||||
junction не обходяться. Недоступний вміст позначається як частковий результат.
|
||||
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
|
||||
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
|
||||
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
|
||||
|
||||
@@ -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
|
||||
|
||||
Binary file not shown.
@@ -1,5 +1,47 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.6.96 — 2026-11-16
|
||||
|
||||
Clicking a file row in Files now redraws only the affected cursor rows, including when switching panes. The key bar adds **F8 Delete**, which opens the same confirmation as pressing F8.
|
||||
|
||||
**Українською.** Клік по рядку у Files перемальовує лише рядки курсора, зокрема при переході на іншу панель. У нижньому рядку клавіш є **F8 Delete**, що відкриває той самий діалог підтвердження, що й клавіша F8.
|
||||
|
||||
## v0.6.95 — 2026-11-16
|
||||
|
||||
Files shows Markdown after rendering completes, refreshes local previews when the file changes on disk, and opens internal links in the same window. Shift+click opens a separate window. The arrow controls, mouse side buttons and Alt+Left/Right navigate history. Ctrl+W closes the viewer. Ctrl+Tab cycles through Files and its open editors and viewers. Up and Down wrap in Files menus and drop-downs. Manual and LAN updates close Files, editors, Settings and bundled StayHere from the target installation before replacing its files. Save open work before updating. When installing this release with an older updater, close Files and its separate windows first. This release replaces v0.6.94.
|
||||
|
||||
**Українською.** Files показує Markdown після рендерингу й автоматично оновлює локальний перегляд після змін на диску. Внутрішні посилання відкриваються в тому самому вікні, Shift+клік — в окремому. Історією керують стрілки перегляду, бічні кнопки миші та Alt+←/→. Ctrl+W закриває перегляд. Ctrl+Tab циклічно перемикає Files та відкриті редактори й переглядачі. Стрілки вгору й вниз циклічно проходять меню та розкривні списки. Ручне оновлення й оновлення через LAN закривають Files, редактори, Settings і вбудований StayHere цільової інсталяції перед заміною файлів. Збережіть відкриті правки перед оновленням. Якщо цей реліз встановлює старий оновлювач, спочатку закрийте Files та його окремі вікна. Цей реліз замінює v0.6.94.
|
||||
|
||||
## v0.6.94 — 2026-11-16
|
||||
|
||||
In KSwitcher Files, F3 renders Markdown with offline Mermaid diagrams, tables, and interactive task lists. Relative links and images work for local and LAN documents. Checkbox changes last for the current preview. F4 opens the syntax-highlighted text editor and F6 switches between View and Edit in the same window, prompting before leaving unsaved edits.
|
||||
|
||||
**Українською.** У KSwitcher Files клавіша F3 відкриває форматований Markdown із діаграмами Mermaid, таблицями та інтерактивними списками завдань. Mermaid працює офлайн. Відносні посилання й зображення працюють для локальних і LAN-файлів. Відмітки чекбоксів діють у поточному сеансі перегляду. F4 відкриває редактор із підсвічуванням синтаксису, а F6 перемикає перегляд і редагування в тому самому вікні. Якщо є незбережені зміни, Files пропонує їх зберегти.
|
||||
|
||||
## v0.6.93 — 2026-11-16
|
||||
|
||||
In Files, Ctrl+R refreshes the active pane as in FAR Manager. The menu and key bar show Ctrl+R. F2 also refreshes the pane. Refresh preserves marks and the cursor where possible, and clears folder sizes calculated with F3.
|
||||
|
||||
**Українською.** У Files Ctrl+R перечитує активну панель, як у FAR Manager. Комбінація показана в меню та рядку клавіш. F2 також перечитує панель. Перечитування зберігає позначки й курсор для наявних елементів і скидає розміри папок, підраховані через F3.
|
||||
|
||||
## v0.6.92 — 2026-11-16
|
||||
|
||||
In Files, F3 on a folder measures file sizes throughout the directory tree. If folders are marked, Files measures each marked folder separately. Results appear in the Size column in Wide mode. F3 on a file opens the viewer even when folders are marked. Folder sizing runs in the background and supports LAN panes.
|
||||
|
||||
**Українською.** У Files F3 на папці підраховує сумарний розмір файлів у всьому дереві. Якщо позначено папки, Files рахує розмір кожної окремо. Результат з’являється в колонці Size у широкому режимі. F3 на файлі відкриває переглядач, навіть коли позначено папки. Підрахунок виконується у фоні й підтримує LAN-панелі.
|
||||
|
||||
## v0.6.91 — 2026-11-16
|
||||
|
||||
Ctrl+Insert copies the marked file and folder names from the active pane, one per line. Without marks, it copies the name under the cursor. LAN Files retries opening TCP 45885 if the port is busy at startup, and Change drive retries failed drive queries. A remote update request waits for an in-progress update check. The updater identifies and closes companion processes from its installation, including Files running from an update backup, and records confirmed exits in the journal.
|
||||
|
||||
**Українською.** Ctrl+Insert копіює імена позначених файлів і папок активної панелі, по одному на рядок. Якщо позначок немає, копіюється ім’я під курсором. LAN Files повторює відкриття TCP 45885, якщо порт зайнятий під час старту, а Change drive повторює невдалі запити дисків. Запит віддаленого оновлення чекає завершення поточної перевірки. Оновлювач визначає й закриває процеси своєї інсталяції, зокрема Files із резервної папки, і записує підтверджене завершення в журнал.
|
||||
|
||||
## v0.6.90 — 2026-11-16
|
||||
|
||||
Files groups Commands into navigation, viewing and editing, and remote PC actions. The remote group appears in an active LAN pane. Shared notices fit their contents and show a scrollbar only when needed. Remote hibernation and update confirmations use a compact red warning with No focused by default.
|
||||
|
||||
**Українською.** Меню Commands у Files групує навігацію, перегляд і редагування та дії для віддаленого ПК. Віддалена група доступна в активній LAN-панелі. Спільні повідомлення підлаштовуються під вміст і показують прокрутку лише за потреби. Гібернація та віддалене оновлення використовують компактне червоне підтвердження з фокусом на No.
|
||||
|
||||
## v0.6.89 — 2026-11-16
|
||||
|
||||
In Files, Commands now offers **Hibernate remote PC** and **Update remote KSwitcher** for the active LAN pane. The target PC has separate, default-off permissions for each action. Unattended updates verify the stable package, close the target installation's Files, Config and screenshot windows, and restart KSwitcher. Forced closure discards unsaved changes. The target journal records closed processes and the update result.
|
||||
|
||||
@@ -1 +1 @@
|
||||
06d74702f466c8f793fafbbf54942fd1688e36f975b4d709652bbdb023e2fc2f KSwitcher-win-x64.zip
|
||||
feec0c9bb0b45f1118524e5b358938c41d2d7fa065e0bbf739d5ca0dd7267b3e KSwitcher-win-x64.zip
|
||||
+85
-55
@@ -1,136 +1,166 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"version": "0.6.89",
|
||||
"files": [
|
||||
{
|
||||
"size": 2361856,
|
||||
"path": "KSwitcher.exe",
|
||||
"sha256": "411340c538f2b76424b7e4d228c217ab1b56e059ee640c109888f59115d9d5ec",
|
||||
"size": 2465792
|
||||
"sha256": "89472489f12d46b44ebe2732b9cf3c330c2c981241b0ea18eea895322b404b27"
|
||||
},
|
||||
{
|
||||
"size": 2359808,
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"sha256": "f48c68669147e32090823465639d8301798f2e4934e160becd1b5fd42d6708bb",
|
||||
"size": 2445824
|
||||
"sha256": "ad2836f34eed4bd69c53fec6cc657899ddf843edbc044fce367b7b2c7d46b43a"
|
||||
},
|
||||
{
|
||||
"size": 3337216,
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"sha256": "311ebf1a3d135fe6ce8bfd0978a9552fbb64c7d7f9a791f4aa4c5bd2c439f06f",
|
||||
"size": 3052544
|
||||
"sha256": "71fada8b0e4248cb524bc70e3be4451a794c9a6db3fe218bbf4d0e700fd41293"
|
||||
},
|
||||
{
|
||||
"size": 3736576,
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"sha256": "73acd9be067451c3db83706be0164959f2ac130259c41c48841d16d1aa2792d5",
|
||||
"size": 3671552
|
||||
"sha256": "6110e13aa7776a76e13d7b78a077d527ad01e38902be608b54180fd6c5d312f7"
|
||||
},
|
||||
{
|
||||
"size": 194912,
|
||||
"path": "WebView2Loader.dll",
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"size": 194912
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
|
||||
},
|
||||
{
|
||||
"size": 1103,
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"size": 1103
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
|
||||
},
|
||||
{
|
||||
"size": 1521,
|
||||
"path": "terminal/addon-fit.js",
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"size": 1521
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
|
||||
},
|
||||
{
|
||||
"size": 527,
|
||||
"path": "terminal/index.html",
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"size": 527
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
|
||||
},
|
||||
{
|
||||
"size": 1073,
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
|
||||
},
|
||||
{
|
||||
"size": 100786,
|
||||
"path": "terminal/markdown-it.js",
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
|
||||
},
|
||||
{
|
||||
"size": 2212,
|
||||
"path": "terminal/markdown.html",
|
||||
"sha256": "27d3c6d39325d4995162911c352a8e20603513445683ceb0409e628949c39237"
|
||||
},
|
||||
{
|
||||
"size": 6534,
|
||||
"path": "terminal/markdown.js",
|
||||
"sha256": "dbf9a062364dcc90b59fd98eb0adb0f153ed95accf26e28f7be9cce8c13ae324"
|
||||
},
|
||||
{
|
||||
"size": 1089,
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
|
||||
},
|
||||
{
|
||||
"size": 5537838,
|
||||
"path": "terminal/mermaid.js",
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
|
||||
},
|
||||
{
|
||||
"size": 4478,
|
||||
"path": "terminal/terminal.js",
|
||||
"sha256": "fb302b2902fea6a815a8266811f350d1e4c108ca88fafd49e6eddcbfff90a5e5",
|
||||
"size": 4268
|
||||
"sha256": "0f3edde02b30e7b0f76d0cc88daae5791d720a4b74cf8b34e7c0b4dbe0cf9c9d"
|
||||
},
|
||||
{
|
||||
"size": 1261,
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"size": 1261
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
|
||||
},
|
||||
{
|
||||
"size": 7112,
|
||||
"path": "terminal/xterm.css",
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"size": 7112
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
|
||||
},
|
||||
{
|
||||
"size": 488663,
|
||||
"path": "terminal/xterm.js",
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"size": 488663
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
|
||||
},
|
||||
{
|
||||
"size": 4401,
|
||||
"path": "LICENSE",
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"size": 4401
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
|
||||
},
|
||||
{
|
||||
"size": 1096,
|
||||
"path": "json-LICENSE.txt",
|
||||
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86",
|
||||
"size": 1075
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
|
||||
},
|
||||
{
|
||||
"size": 883,
|
||||
"path": "files-text-license.txt",
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"size": 883
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
|
||||
},
|
||||
{
|
||||
"size": 94357,
|
||||
"path": "README.md",
|
||||
"sha256": "7b34f2af7341f57d7bac1b5b7e55a40595a6bc20f461f98c0c6320336d0deba7",
|
||||
"size": 94223
|
||||
"sha256": "fca41227e9b38bf061298d69806ea66fb00086ae03aec49665e4f68ed2c3f8e9"
|
||||
},
|
||||
{
|
||||
"size": 11418,
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
|
||||
"size": 11418
|
||||
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada"
|
||||
},
|
||||
{
|
||||
"size": 732485,
|
||||
"path": "dictionaries/en.txt",
|
||||
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21",
|
||||
"size": 682867
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
|
||||
},
|
||||
{
|
||||
"size": 20566,
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5",
|
||||
"size": 20138
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
|
||||
},
|
||||
{
|
||||
"size": 2265,
|
||||
"path": "dictionaries/README.md",
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"size": 2265
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
|
||||
},
|
||||
{
|
||||
"size": 1109134,
|
||||
"path": "dictionaries/ru.txt",
|
||||
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b",
|
||||
"size": 1060364
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
|
||||
},
|
||||
{
|
||||
"size": 1280,
|
||||
"path": "dictionaries/sources.json",
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"size": 1280
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
|
||||
},
|
||||
{
|
||||
"size": 940799,
|
||||
"path": "dictionaries/uk.txt",
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"size": 940799
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
|
||||
},
|
||||
{
|
||||
"size": 993,
|
||||
"path": "tools/README.txt",
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"size": 993
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
|
||||
},
|
||||
{
|
||||
"size": 134656,
|
||||
"path": "tools/StayHere.exe",
|
||||
"sha256": "2b214b0ed2b6f754611f3355ccdcc6797c6bc5c2aac70bd51e060ba25eb4c3a5",
|
||||
"size": 133120
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
|
||||
},
|
||||
{
|
||||
"size": 2796,
|
||||
"path": "tools/StayHere-README.md",
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"size": 2796
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
|
||||
}
|
||||
]
|
||||
],
|
||||
"version": "0.6.96",
|
||||
"schema": 1
|
||||
}
|
||||
+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,89,0
|
||||
PRODUCTVERSION 0,6,89,0
|
||||
FILEVERSION 0,6,96,0
|
||||
PRODUCTVERSION 0,6,96,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.89"
|
||||
VALUE "FileVersion", "0.6.96"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
+5
-13
@@ -47,24 +47,16 @@ BEGIN
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
|
||||
END
|
||||
|
||||
607 DIALOGEX 0, 0, 300, 106
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL | WS_TABSTOP, 18, 22, 264, 52
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 120, 80, 60, 17
|
||||
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 85, 80, 60, 17
|
||||
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 155, 80, 60, 17
|
||||
AUTOCHECKBOX "&Remember for this session", 101, 18, 63, 264, 13, NOT WS_VISIBLE
|
||||
END
|
||||
|
||||
609 DIALOGEX 0, 0, 185, 57
|
||||
607 DIALOGEX 0, 0, 185, 57
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 100, 14, 16, 157, 13, SS_NOPREFIX
|
||||
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL, 14, 16, 157, 13
|
||||
AUTOCHECKBOX "&Remember for this session", 101, 14, 30, 157, 13, NOT WS_VISIBLE
|
||||
CONTROL "", 102, "Static", NOT WS_VISIBLE, 14, 35, 1, 1
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
|
||||
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
|
||||
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
|
||||
END
|
||||
|
||||
608 DIALOGEX 0, 0, 220, 67
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'">
|
||||
<title>Markdown preview</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; font: 16px/1.55 system-ui, sans-serif; }
|
||||
:root:not(.rendered) body { visibility: hidden; }
|
||||
body { max-width: 960px; margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
|
||||
nav { position: sticky; top: 0; display: flex; gap: .4em; padding-block: .25em; background: Canvas; }
|
||||
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
|
||||
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
|
||||
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
|
||||
nav button:hover:not(:disabled) { text-decoration: underline; }
|
||||
nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
|
||||
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
|
||||
a { color: LinkText; }
|
||||
pre, table, figure { overflow: auto; }
|
||||
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
|
||||
pre { padding: .75em; }
|
||||
code { padding: .1em .25em; }
|
||||
pre code { padding: 0; background: none; }
|
||||
blockquote { margin-left: 0; padding-left: 1em; border-left: 3px solid GrayText; }
|
||||
table { display: block; border-collapse: collapse; }
|
||||
th, td { border: 1px solid GrayText; padding: .3em .65em; }
|
||||
img, svg { max-width: 100%; height: auto; }
|
||||
figure { margin: 1em 0; }
|
||||
.task { list-style: none; }
|
||||
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
|
||||
</style>
|
||||
<nav aria-label="Document history">
|
||||
<button id="back" type="button" title="Back (Alt+Left)" aria-label="Back" disabled>←</button>
|
||||
<button id="forward" type="button" title="Forward (Alt+Right)" aria-label="Forward" disabled>→</button>
|
||||
</nav>
|
||||
<main></main>
|
||||
<script src="markdown-it.js"></script>
|
||||
<script src="mermaid.js"></script>
|
||||
<script src="markdown.js"></script>
|
||||
</html>
|
||||
@@ -0,0 +1,153 @@
|
||||
'use strict';
|
||||
|
||||
const bridge = window.chrome.webview;
|
||||
const content = document.querySelector('main');
|
||||
const back = document.querySelector('#back');
|
||||
const forward = document.querySelector('#forward');
|
||||
const markdown = markdownit({ html: false, linkify: true });
|
||||
let generation = 0;
|
||||
let images = [];
|
||||
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: 'strict',
|
||||
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
|
||||
suppressErrorRendering: true,
|
||||
flowchart: { htmlLabels: false }
|
||||
});
|
||||
|
||||
markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
|
||||
for (let i = 2; i < tokens.length; ++i) {
|
||||
const token = tokens[i];
|
||||
if (token.type !== 'inline' || tokens[i - 1].type !== 'paragraph_open' ||
|
||||
tokens[i - 2].type !== 'list_item_open') continue;
|
||||
const text = token.children[0];
|
||||
const marker = text?.type === 'text' && /^\[([ xX])\][ \t]+/.exec(text.content);
|
||||
if (!marker) continue;
|
||||
text.content = text.content.slice(marker[0].length);
|
||||
const box = new text.constructor('task_checkbox', '', 0);
|
||||
box.checked = marker[1] !== ' ';
|
||||
box.content = token.content.slice(marker[0].length);
|
||||
token.children.unshift(box);
|
||||
tokens[i - 2].attrJoin('class', 'task');
|
||||
}
|
||||
});
|
||||
markdown.renderer.rules.task_checkbox = (tokens, i) =>
|
||||
'<input type="checkbox" aria-label="' + markdown.utils.escapeHtml(tokens[i].content) + '"' +
|
||||
(tokens[i].checked ? ' checked' : '') + '>';
|
||||
markdown.renderer.rules.image = (tokens, i) => {
|
||||
const token = tokens[i];
|
||||
const alt = markdown.renderer.renderInlineAsText(token.children, markdown.options, {});
|
||||
const escape = markdown.utils.escapeHtml;
|
||||
return '<img alt="' + escape(alt) + '" data-path="' + escape(token.attrGet('src')) + '">';
|
||||
};
|
||||
|
||||
function send(action, options = {}) {
|
||||
bridge.postMessage(JSON.stringify({ action, ...options }));
|
||||
}
|
||||
|
||||
function scrollToHeading(fragment) {
|
||||
if (!fragment) { window.scrollTo(0, 0); return; }
|
||||
try { document.getElementById(decodeURIComponent(fragment))?.scrollIntoView(); } catch {}
|
||||
}
|
||||
|
||||
function restorePosition({ fragment, scroll }) {
|
||||
if (typeof scroll === 'number') window.scrollTo(0, scroll);
|
||||
else scrollToHeading(fragment);
|
||||
}
|
||||
|
||||
function navigate(action) {
|
||||
const button = action === 'back' ? back : forward;
|
||||
if (!button.disabled) send(action, { scroll: Math.round(window.scrollY) });
|
||||
}
|
||||
|
||||
back.addEventListener('click', () => navigate('back'));
|
||||
forward.addEventListener('click', () => navigate('forward'));
|
||||
|
||||
async function render({ text, fragment, scroll, title, keepPosition }) {
|
||||
const current = ++generation;
|
||||
if (keepPosition) scroll = window.scrollY;
|
||||
document.documentElement.classList.remove('rendered');
|
||||
document.title = title;
|
||||
content.innerHTML = markdown.render(text);
|
||||
const headings = new Set();
|
||||
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
|
||||
const base = heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
||||
let id = base;
|
||||
for (let n = 1; headings.has(id); ++n) id = base + '-' + n;
|
||||
heading.id = id;
|
||||
headings.add(id);
|
||||
}
|
||||
images = Array.from(content.querySelectorAll('img[data-path]'));
|
||||
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
|
||||
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
|
||||
for (const [index, block] of blocks.entries()) {
|
||||
try {
|
||||
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
|
||||
if (current !== generation) return;
|
||||
const figure = document.createElement('figure');
|
||||
figure.innerHTML = svg;
|
||||
block.parentElement.replaceWith(figure);
|
||||
} catch {
|
||||
if (current !== generation) return;
|
||||
const caption = document.createElement('div');
|
||||
caption.textContent = 'Invalid Mermaid diagram';
|
||||
block.parentElement.before(caption);
|
||||
}
|
||||
}
|
||||
restorePosition({ fragment, scroll });
|
||||
document.documentElement.classList.add('rendered');
|
||||
send('rendered');
|
||||
}
|
||||
|
||||
content.addEventListener('click', event => {
|
||||
const link = event.target.closest('a');
|
||||
if (!link) return;
|
||||
event.preventDefault();
|
||||
const path = link.getAttribute('href');
|
||||
if (!path || event.ctrlKey || event.metaKey || link.closest('svg')) return;
|
||||
send('link', { path, newWindow: event.shiftKey, scroll: Math.round(window.scrollY) });
|
||||
});
|
||||
|
||||
document.addEventListener('pointerup', event => {
|
||||
if (event.button !== 3 && event.button !== 4) return;
|
||||
event.preventDefault();
|
||||
navigate(event.button === 3 ? 'back' : 'forward');
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
|
||||
event.preventDefault();
|
||||
send('cycle');
|
||||
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
|
||||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
navigate(['ArrowLeft', 'BrowserBack'].includes(event.key) ? 'back' : 'forward');
|
||||
} else if (event.key === 'F6' || event.key === 'Escape' || event.key === 'F10' ||
|
||||
(event.ctrlKey && event.key.toLowerCase() === 'w')) {
|
||||
event.preventDefault();
|
||||
send(event.key === 'F6' ? 'edit' : 'close');
|
||||
}
|
||||
});
|
||||
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
const message = JSON.parse(data);
|
||||
if (message.action === 'clear') {
|
||||
++generation;
|
||||
document.documentElement.classList.remove('rendered');
|
||||
content.replaceChildren();
|
||||
}
|
||||
if (message.action === 'render') void render(message).catch(() => send('failed'));
|
||||
if (message.action === 'anchor') restorePosition(message);
|
||||
if (message.action === 'back' || message.action === 'forward') navigate(message.action);
|
||||
if (message.action === 'history') {
|
||||
back.disabled = !message.back;
|
||||
forward.disabled = !message.forward;
|
||||
}
|
||||
if (message.action === 'image' && message.generation === generation && images[message.index]) {
|
||||
const image = images[message.index];
|
||||
if (message.source) image.src = message.source;
|
||||
else image.title = 'Image unavailable';
|
||||
}
|
||||
});
|
||||
bridge.postMessage('ready');
|
||||
@@ -61,6 +61,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-panel-names');
|
||||
}
|
||||
else if (event.code === 'KeyR') {
|
||||
if (!event.repeat) bridge.postMessage('refresh-panel');
|
||||
}
|
||||
else return true;
|
||||
event.preventDefault();
|
||||
return false;
|
||||
|
||||
+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
|
||||
|
||||
+15
-7
@@ -2942,11 +2942,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 +3005,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 +3031,20 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
// The helper has verified and staged the package; it waits for process exit.
|
||||
DestroyWindow(hwnd);
|
||||
}
|
||||
else if (std::exchange(app->lanUpdatePending, false) && lan::remoteUpdateAllowed() &&
|
||||
result->state != L"current")
|
||||
{
|
||||
log(L"Starting queued unattended KSwitcher update.");
|
||||
app->checkUpdate(false, true);
|
||||
}
|
||||
else if (result->state == L"available")
|
||||
{
|
||||
app->availableUpdate = result->version;
|
||||
if (result->interactive)
|
||||
{
|
||||
auto prompt = L"Install KSwitcher " + result->version +
|
||||
L"?\n\nThe program will close and restart. Settings, history and existing dictionaries are preserved.";
|
||||
L"?\n\nKSwitcher will restart after closing Files, editors, Settings and StayHere from this installation. "
|
||||
L"Save any unsaved work before continuing.";
|
||||
if (MessageBoxW(hwnd, prompt.c_str(), L"KSwitcher Update", MB_YESNO | MB_ICONQUESTION) == IDYES)
|
||||
app->checkUpdate(true, true, result->version);
|
||||
}
|
||||
|
||||
@@ -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{};
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
+454
-132
@@ -21,6 +21,7 @@
|
||||
#include <objbase.h>
|
||||
#include "files_terminal.h"
|
||||
#include "files_text_window.h"
|
||||
#include "files_menu_navigation.h"
|
||||
#include "files_text_preferences.h"
|
||||
#include "files_menu_paint.h"
|
||||
#include "files_dropdown_paint.h"
|
||||
@@ -247,6 +248,49 @@ DWORD requestElevatedFolder(HWND owner,const fs::path &directory,
|
||||
}
|
||||
return ERROR_TIMEOUT;
|
||||
}
|
||||
struct FolderSize
|
||||
{
|
||||
uint64_t bytes{};
|
||||
bool partial{};
|
||||
};
|
||||
using FolderSizes=std::map<fs::path,FolderSize>;
|
||||
|
||||
FolderSize measureFolder(FilesConnection &host,const fs::path &root,std::stop_token stop)
|
||||
{
|
||||
FolderSize size;
|
||||
std::vector<fs::path> pending{root};
|
||||
while(!pending.empty() && !stop.stop_requested())
|
||||
{
|
||||
const auto directory=std::move(pending.back());
|
||||
pending.pop_back();
|
||||
try
|
||||
{
|
||||
const auto info=statFile(host,directory);
|
||||
if(!info || !(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
|
||||
{
|
||||
size.partial=true;
|
||||
continue;
|
||||
}
|
||||
if(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)
|
||||
{
|
||||
if(directory==root) size.partial=true;
|
||||
continue;
|
||||
}
|
||||
listFiles(host,directory,[&](const fs::path &path,const FileInfo &entry)
|
||||
{
|
||||
if(stop.stop_requested()) return false;
|
||||
if(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT) return true;
|
||||
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY) pending.push_back(path);
|
||||
else if(entry.size>UINT64_MAX-size.bytes) size.partial=true;
|
||||
else size.bytes+=entry.size;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
catch(const std::exception &) {size.partial=true;}
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
struct Panel
|
||||
{
|
||||
HWND path{}, list{}, heading{};
|
||||
@@ -274,6 +318,9 @@ struct Panel
|
||||
std::vector<std::wstring> sizes;
|
||||
std::vector<bool> dimmed;
|
||||
std::vector<bool> marked;
|
||||
FolderSizes folderSizes;
|
||||
std::future<FolderSizes> folderSizeQuery;
|
||||
std::stop_source folderSizeStop;
|
||||
std::set<fs::path> transferResults;
|
||||
size_t fileExtensionLength{}, folderExtensionLength{};
|
||||
bool wide{};
|
||||
@@ -308,7 +355,12 @@ std::vector<CommandEntry> terminalHistory;
|
||||
size_t terminalHistoryIndex{};
|
||||
constexpr UINT_PTR transferHighlightTimer=1;
|
||||
unsigned transferHighlightPhase{};
|
||||
HWND status{}, commands[7]{};
|
||||
constexpr struct KeyBarCommand { int id; WPARAM key; const wchar_t *label; } keyBar[]{
|
||||
{110,VK_F2,L"Ctrl+R Refresh"}, {111,VK_F3,L"F3 View"}, {112,VK_F4,L"F4 Edit"},
|
||||
{113,VK_F5,L"F5 Copy"}, {114,VK_F6,L"F6 Move"}, {115,VK_F7,L"F7 Mkdir"},
|
||||
{117,VK_F8,L"F8 Delete"}, {116,VK_F10,L"F10 Exit"}
|
||||
};
|
||||
HWND status{}, commands[std::size(keyBar)]{};
|
||||
int active{}, split{};
|
||||
bool dragging{};
|
||||
bool rememberElevationApproval{};
|
||||
@@ -316,6 +368,7 @@ HWND picker{}, pickerFrame{}, menuBar{};
|
||||
HWND menuItems[5]{};
|
||||
constexpr std::wstring_view menuAccessKeys=L"LFCOR";
|
||||
std::vector<size_t> commandAccessPositions;
|
||||
std::vector<int> commandActions;
|
||||
int menuIndex{};
|
||||
bool commandPicker{};
|
||||
constexpr int defaultSizeWidth=6, defaultFontPoints=110;
|
||||
@@ -344,8 +397,7 @@ struct DriveChoice { FilesPeer peer; fs::path path; };
|
||||
std::vector<DriveQuery> driveQueries;
|
||||
std::map<LRESULT,DriveChoice> remoteDriveRows;
|
||||
constexpr UINT_PTR driveQueryTimer=3;
|
||||
bool refreshDriveAddresses{};
|
||||
ULONGLONG driveOpened{};
|
||||
ULONGLONG nextDriveRefresh{},driveRefreshDeadline{};
|
||||
int drivePickerWidth{};
|
||||
int pickerPanel{};
|
||||
std::wstring panelSearchPrefix;
|
||||
@@ -388,13 +440,19 @@ void savePlacement(HWND window)
|
||||
&placement,sizeof(placement));
|
||||
}
|
||||
void chooseDrive(int index, bool fromMenu = false);
|
||||
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,bool confirm=false,
|
||||
bool *remember=nullptr,bool warning=false);
|
||||
enum class FilesNoticeTone { dialog, neutral, warning };
|
||||
struct FilesNoticeOptions
|
||||
{
|
||||
bool confirm{};
|
||||
bool *remember{};
|
||||
FilesNoticeTone tone{FilesNoticeTone::dialog};
|
||||
};
|
||||
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
|
||||
void openMenu(HWND window, int index);
|
||||
void showFileDetails(const Panel &panel);
|
||||
void editOptions(HWND owner);
|
||||
void showFolderShortcuts(Panel &panel,int digit,bool all=false);
|
||||
void layout(HWND window);
|
||||
void layout(HWND window,bool activeOnly=false);
|
||||
|
||||
DWORD preference(const wchar_t *name, DWORD fallback)
|
||||
{
|
||||
@@ -458,7 +516,6 @@ BOOL CALLBACK updateDialogFont(HWND window,LPARAM parameter)
|
||||
return TRUE;
|
||||
}
|
||||
HBRUSH blue{}, teal{}, terminalBackground{};
|
||||
void layout(HWND window);
|
||||
|
||||
LOGFONTW defaultFilesFont()
|
||||
{
|
||||
@@ -708,6 +765,7 @@ void hidePicker()
|
||||
void selectDrive();
|
||||
void showMenu(bool show)
|
||||
{
|
||||
if(!show && !IsWindowVisible(menuBar)) return;
|
||||
if (show) SetWindowPos(menuBar,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW);
|
||||
for (auto item : menuItems)
|
||||
{
|
||||
@@ -776,7 +834,7 @@ void closePanelSearch()
|
||||
if(IsWindowVisible(panelSearchPopup)) ShowWindow(panelSearchPopup,SW_HIDE);
|
||||
}
|
||||
|
||||
void layout(HWND window)
|
||||
void layout(HWND window,bool activeOnly)
|
||||
{
|
||||
RECT rect{};
|
||||
GetClientRect(window, &rect);
|
||||
@@ -795,21 +853,24 @@ void layout(HWND window)
|
||||
if(control) SetWindowPos(control,nullptr,x,y,width,height,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW);
|
||||
};
|
||||
for (int i = 0; i < 2; ++i)
|
||||
if(!activeOnly)
|
||||
{
|
||||
int x = i ? middle + 2 : 0;
|
||||
int end = i ? width : middle - 2;
|
||||
place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight);
|
||||
int headingHeight=panels[i].wide?textHeight:0;
|
||||
place(panels[i].heading,x+5,textHeight+10,std::max(0,end-x-13),headingHeight);
|
||||
ShowWindow(panels[i].heading,!terminalVisible && panels[i].wide?SW_SHOWNA:SW_HIDE);
|
||||
place(panels[i].list, x + 5, textHeight+10+headingHeight, std::max(0, end - x - 13),
|
||||
std::max(0, panelBottom-textHeight-10-headingHeight));
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
int x = i ? middle + 2 : 0;
|
||||
int end = i ? width : middle - 2;
|
||||
place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight);
|
||||
int headingHeight=panels[i].wide?textHeight:0;
|
||||
place(panels[i].heading,x+5,textHeight+10,std::max(0,end-x-13),headingHeight);
|
||||
ShowWindow(panels[i].heading,!terminalVisible && panels[i].wide?SW_SHOWNA:SW_HIDE);
|
||||
place(panels[i].list, x + 5, textHeight+10+headingHeight, std::max(0, end - x - 13),
|
||||
std::max(0, panelBottom-textHeight-10-headingHeight));
|
||||
}
|
||||
place(menuBar,0,0,width,textHeight+4);
|
||||
const int menuEdges[]{0,7,15,27,38,46};
|
||||
for(int i=0;i<5;++i)
|
||||
place(menuItems[i],4+menuEdges[i]*cellWidth,0,(menuEdges[i+1]-menuEdges[i])*cellWidth,textHeight+4);
|
||||
}
|
||||
place(menuBar,0,0,width,textHeight+4);
|
||||
const int menuEdges[]{0,7,15,27,38,46};
|
||||
for(int i=0;i<5;++i)
|
||||
place(menuItems[i],4+menuEdges[i]*cellWidth,0,(menuEdges[i+1]-menuEdges[i])*cellWidth,textHeight+4);
|
||||
const int detailsLeft=active?middle+2:0;
|
||||
const int detailsRight=active?width:middle-2;
|
||||
place(status,detailsLeft+8,panelBottom+4,std::max(0,detailsRight-detailsLeft-16),textHeight);
|
||||
@@ -827,6 +888,14 @@ void layout(HWND window)
|
||||
const int promptWidth=std::min(width/2,static_cast<int>(promptExtent.cx));
|
||||
place(terminalPrompt,4,inputTop,promptWidth,textHeight);
|
||||
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),textHeight);
|
||||
if(activeOnly)
|
||||
{
|
||||
const RECT details{0,panelBottom+4,width,panelBottom+4+textHeight};
|
||||
const RECT commandLine{0,inputTop,width,inputTop+textHeight};
|
||||
if(!terminalVisible) RedrawWindow(window,&details,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
RedrawWindow(window,&commandLine,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
return;
|
||||
}
|
||||
// Keep the WebView in place while the panels reveal more or less of it.
|
||||
place(terminalOutput,4,4,std::max(0,width-8),terminalBottom-4);
|
||||
if(showOutput)
|
||||
@@ -837,10 +906,14 @@ void layout(HWND window)
|
||||
ShowWindow(terminalOutput,showOutput?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(status,terminalVisible?SW_HIDE:SW_SHOWNA);
|
||||
terminalView.layout(terminalOutput,showOutput,terminalBottom-4);
|
||||
constexpr int refreshExtra=4;
|
||||
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
|
||||
{
|
||||
const int count=static_cast<int>(std::size(commands));
|
||||
place(commands[i],i*width/count,height-textHeight,(i+1)*width/count-i*width/count,textHeight);
|
||||
constexpr int unit=10;
|
||||
const int total=static_cast<int>(std::size(commands))*unit+refreshExtra;
|
||||
const int left=i?(i*unit+refreshExtra)*width/total:0;
|
||||
const int right=((i+1)*unit+refreshExtra)*width/total;
|
||||
place(commands[i],left,height-textHeight,right-left,textHeight);
|
||||
}
|
||||
if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window);
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
|
||||
@@ -872,9 +945,12 @@ void activatePanel(int index)
|
||||
for(const auto &panel:panels)
|
||||
{
|
||||
InvalidateRect(panel.path,nullptr,FALSE);
|
||||
InvalidateRect(panel.list,nullptr,FALSE);
|
||||
const auto cursor=SendMessageW(panel.list,LB_GETCURSEL,0,0);
|
||||
RECT row{};
|
||||
if(cursor!=LB_ERR && SendMessageW(panel.list,LB_GETITEMRECT,cursor,reinterpret_cast<LPARAM>(&row))!=LB_ERR)
|
||||
InvalidateRect(panel.list,&row,FALSE);
|
||||
}
|
||||
layout(GetParent(panels[index].list));
|
||||
layout(GetParent(panels[index].list),true);
|
||||
}
|
||||
|
||||
std::wstring terminalInputText()
|
||||
@@ -898,6 +974,41 @@ LRESULT currentPanelRow(const Panel &panel)
|
||||
return row>=0 && static_cast<size_t>(row)<panel.rows.size()?row:LB_ERR;
|
||||
}
|
||||
|
||||
std::vector<fs::path> selectedPanelPaths(const Panel &panel)
|
||||
{
|
||||
std::vector<fs::path> paths;
|
||||
for(size_t i=0;i<panel.rows.size();++i)
|
||||
if(panel.marked[i] && panel.sizes[i]!=L"Up") paths.push_back(panel.rows[i]);
|
||||
if(paths.empty())
|
||||
{
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(row!=LB_ERR && panel.sizes[row]!=L"Up") paths.push_back(panel.rows[row]);
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
void copyPanelNames(HWND owner)
|
||||
{
|
||||
const auto paths=selectedPanelPaths(panels[active]);
|
||||
if(paths.empty()) return;
|
||||
std::wstring names;
|
||||
for(const auto &path:paths)
|
||||
{
|
||||
if(!names.empty()) names+=L"\r\n";
|
||||
names+=path.filename().native();
|
||||
}
|
||||
try { ks::writeClipboard(owner,ks::textClip(names)); }
|
||||
catch(const std::exception &) { setStatus(L"Could not copy file names."); }
|
||||
}
|
||||
|
||||
void refreshPanel(Panel &panel)
|
||||
{
|
||||
panel.folderSizeStop.request_stop();
|
||||
panel.folderSizeQuery={};
|
||||
panel.folderSizes.clear();
|
||||
open(panel,panel.directory,false);
|
||||
}
|
||||
|
||||
std::wstring powerShellPath(const fs::path &path)
|
||||
{
|
||||
std::wstring quoted=L"'";
|
||||
@@ -979,6 +1090,8 @@ bool ensureTerminalView(HWND owner)
|
||||
else if(message==L"insert-path") insertCurrentPanelPath();
|
||||
else if(message==L"insert-name") insertCurrentPanelPath(true);
|
||||
else if(message==L"copy-command-line") SendMessageW(terminalInput,WM_COPY,0,0);
|
||||
else if(message==L"copy-panel-names") copyPanelNames(owner);
|
||||
else if(message==L"refresh-panel") refreshPanel(panels[active]);
|
||||
else if(message==L"toggle") showTerminal(owner,!terminalVisible);
|
||||
else if(!terminalVisible && (message==L"grow" || message==L"shrink"))
|
||||
{
|
||||
@@ -1226,7 +1339,11 @@ void showFileDetails(const Panel &panel)
|
||||
if(statusFields&2)
|
||||
{
|
||||
const auto &size=panel.sizes[row];
|
||||
details+=L" "+(size==L"Folder" || size==L"Up"?size:formatSize(std::stoull(size)));
|
||||
const auto measured=panel.folderSizes.find(path);
|
||||
if(size==L"Folder" && measured!=panel.folderSizes.end())
|
||||
details+=L" "+formatSize(measured->second.bytes)+(measured->second.partial?L" (partial)":L"");
|
||||
else
|
||||
details+=L" "+(size==L"Folder" || size==L"Up"?size:formatSize(std::stoull(size)));
|
||||
}
|
||||
std::wstring timestamp=date;
|
||||
if((statusFields&4) && timestamp.size()>=12) details+=timestamp.substr(0,12);
|
||||
@@ -1279,7 +1396,7 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
|
||||
const auto question=L"Windows denied access to this folder.\r\n"+path+
|
||||
L"\r\n\r\nTry opening as administrator? Windows may still ask for UAC.";
|
||||
if(rememberElevationApproval || showFilesNotice(owner,question.c_str(),
|
||||
L"KSwitcher Files",true,&remember)==IDYES)
|
||||
L"KSwitcher Files",{.confirm=true,.remember=&remember})==IDYES)
|
||||
{
|
||||
const auto result=requestElevatedFolder(owner,directory,folders,files,metadata);
|
||||
SetForegroundWindow(owner);
|
||||
@@ -1326,6 +1443,12 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
|
||||
}
|
||||
panel.directory = directory;
|
||||
panel.peer=std::move(peer);
|
||||
if(!sameDirectory)
|
||||
{
|
||||
panel.folderSizeStop.request_stop();
|
||||
panel.folderSizeQuery={};
|
||||
panel.folderSizes.clear();
|
||||
}
|
||||
if(!sameDirectory || nextWatch.handle!=INVALID_HANDLE_VALUE)
|
||||
{
|
||||
panel.watch.reset();
|
||||
@@ -1409,6 +1532,61 @@ void refreshChangedPanels()
|
||||
}
|
||||
}
|
||||
|
||||
void calculateFolderSizes(Panel &panel,LRESULT current)
|
||||
{
|
||||
if(panel.folderSizeQuery.valid())
|
||||
{
|
||||
setStatus(L"Calculating folder sizes...");
|
||||
return;
|
||||
}
|
||||
std::vector<fs::path> folders;
|
||||
for(size_t i=0;i<panel.rows.size();++i)
|
||||
if(panel.marked[i] && panel.sizes[i]==L"Folder") folders.push_back(panel.rows[i]);
|
||||
if(folders.empty()) folders.push_back(panel.rows[current]);
|
||||
|
||||
panel.folderSizeStop=std::stop_source{};
|
||||
std::packaged_task<FolderSizes()> task(
|
||||
[folders=std::move(folders),peer=panel.peer,stop=panel.folderSizeStop.get_token()]
|
||||
{
|
||||
FolderSizes results;
|
||||
try
|
||||
{
|
||||
FilesConnection host(peer?&*peer:nullptr);
|
||||
for(const auto &folder:folders)
|
||||
{
|
||||
if(stop.stop_requested()) break;
|
||||
results.emplace(folder,measureFolder(host,folder,stop));
|
||||
}
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
for(const auto &folder:folders) results.try_emplace(folder,FolderSize{0,true});
|
||||
}
|
||||
return results;
|
||||
});
|
||||
panel.folderSizeQuery=task.get_future();
|
||||
try {std::thread(std::move(task)).detach();}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
panel.folderSizeQuery={};
|
||||
setStatus(fileError(error));
|
||||
return;
|
||||
}
|
||||
setStatus(L"Calculating folder sizes...");
|
||||
}
|
||||
|
||||
void collectFolderSizes()
|
||||
{
|
||||
for(auto &panel:panels)
|
||||
{
|
||||
if(!panel.folderSizeQuery.valid() ||
|
||||
panel.folderSizeQuery.wait_for(std::chrono::seconds(0))!=std::future_status::ready) continue;
|
||||
for(const auto &[path,size]:panel.folderSizeQuery.get()) panel.folderSizes.insert_or_assign(path,size);
|
||||
InvalidateRect(panel.list,nullptr,FALSE);
|
||||
if(&panel==&panels[active]) showFileDetails(panel);
|
||||
}
|
||||
}
|
||||
|
||||
void openSelectedText(const Panel &panel, bool edit, bool external);
|
||||
INT_PTR confirmTextSave(HWND owner);
|
||||
INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption);
|
||||
@@ -1431,7 +1609,8 @@ void runActivePeerAction(HWND owner,bool update)
|
||||
const auto question=update
|
||||
? L"Update KSwitcher on "+peer.name+L"? Open KSwitcher windows there will close if an update is available."
|
||||
: L"Hibernate "+peer.name+L"?";
|
||||
if(showFilesNotice(owner,question.c_str(),update?L"Update remote KSwitcher":L"Hibernate remote PC",true)!=IDYES)
|
||||
if(showFilesNotice(owner,question.c_str(),update?L"Update remote KSwitcher":L"Hibernate remote PC",
|
||||
{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
|
||||
return;
|
||||
|
||||
std::packaged_task<std::wstring()> task([peer,update]
|
||||
@@ -1481,6 +1660,11 @@ void runActivePeerAction(HWND owner,bool update)
|
||||
void selectDrive()
|
||||
{
|
||||
auto row=SendMessageW(picker,LB_GETCURSEL,0,0);
|
||||
if(commandPicker)
|
||||
{
|
||||
if(row<0 || static_cast<size_t>(row)>=commandActions.size() || commandActions[row]<0) return;
|
||||
row=commandActions[row];
|
||||
}
|
||||
if(!commandPicker && (row<0 || static_cast<size_t>(row)==drivePaths.size())) return;
|
||||
const auto remote=remoteDriveRows.find(row);
|
||||
if(commandPicker || row<static_cast<LRESULT>(drivePaths.size()) || remote!=remoteDriveRows.end())
|
||||
@@ -1516,6 +1700,34 @@ void selectDrive()
|
||||
|
||||
LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||||
{
|
||||
if(commandPicker)
|
||||
{
|
||||
const auto separator=[](LRESULT row)
|
||||
{
|
||||
return row>=0 && static_cast<size_t>(row)<commandActions.size() && commandActions[row]<0;
|
||||
};
|
||||
if(msg==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN))
|
||||
{
|
||||
const auto current=SendMessageW(window,LB_GETCURSEL,0,0);
|
||||
const auto row=ks::files::adjacentMenuRow(current,static_cast<LRESULT>(commandActions.size()),
|
||||
wp==VK_UP?-1:1,[&](LRESULT candidate){return !separator(candidate);});
|
||||
if(row!=current) SendMessageW(window,LB_SETCURSEL,row,0);
|
||||
return 0;
|
||||
}
|
||||
if(msg==WM_KEYDOWN && (wp==VK_PRIOR || wp==VK_NEXT))
|
||||
{
|
||||
const auto result=DefSubclassProc(window,msg,wp,lp);
|
||||
const auto row=SendMessageW(window,LB_GETCURSEL,0,0);
|
||||
if(separator(row))
|
||||
SendMessageW(window,LB_SETCURSEL,row+((wp==VK_UP || wp==VK_PRIOR)?-1:1),0);
|
||||
return result;
|
||||
}
|
||||
if(msg==WM_LBUTTONDOWN || msg==WM_LBUTTONDBLCLK || (msg==WM_MOUSEMOVE && (wp&MK_LBUTTON)))
|
||||
{
|
||||
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
|
||||
if(!HIWORD(hit) && separator(LOWORD(hit))) return 0;
|
||||
}
|
||||
}
|
||||
if(!commandPicker && msg==WM_CHAR)
|
||||
{
|
||||
const auto key=towupper(static_cast<wchar_t>(wp));
|
||||
@@ -1679,7 +1891,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
|
||||
add(query.peer.name);
|
||||
if(query.pending.valid()) add(L" Loading drives...");
|
||||
else if(!query.error.empty()) add(L" "+query.error);
|
||||
else if(query.peer.address.empty()) add(refreshDriveAddresses?L" Looking for PC...":L" Offline");
|
||||
else if(query.peer.address.empty()) add(nextDriveRefresh?L" Looking for PC...":L" Offline");
|
||||
else if(query.drives.empty()) add(L" No drives");
|
||||
for(const auto &entry:query.drives)
|
||||
{
|
||||
@@ -1706,26 +1918,30 @@ void pollDriveQueries(HWND owner)
|
||||
return;
|
||||
}
|
||||
bool changed=false, pending=false;
|
||||
if(refreshDriveAddresses && GetTickCount64()-driveOpened>=500)
|
||||
const auto now=GetTickCount64();
|
||||
if(nextDriveRefresh && now>=nextDriveRefresh)
|
||||
{
|
||||
refreshDriveAddresses=false;
|
||||
nextDriveRefresh=now<driveRefreshDeadline?now+2000:0;
|
||||
queryDrivePeers();
|
||||
for(const auto &peer:drivePeers)
|
||||
if(std::none_of(driveQueries.begin(),driveQueries.end(),[&](const DriveQuery &query){return query.peer.id==peer.id;}))
|
||||
{
|
||||
auto entry=std::find_if(driveQueries.begin(),driveQueries.end(),[&](const DriveQuery &query)
|
||||
{return query.peer.id==peer.id;});
|
||||
if(entry==driveQueries.end())
|
||||
{
|
||||
auto &query=driveQueries.emplace_back();
|
||||
query.peer=peer;
|
||||
startDriveQuery(query);
|
||||
}
|
||||
for(auto &query:driveQueries)
|
||||
if(query.peer.address.empty())
|
||||
for(const auto &peer:drivePeers)
|
||||
if(peer.id==query.peer.id && !peer.address.empty())
|
||||
{
|
||||
query.peer=peer;
|
||||
startDriveQuery(query);
|
||||
break;
|
||||
}
|
||||
else if(!entry->pending.valid() && (entry->peer.address!=peer.address ||
|
||||
entry->peer.address.empty() || !entry->error.empty()))
|
||||
{
|
||||
entry->peer=peer;
|
||||
entry->drives=Json::array();
|
||||
entry->error.clear();
|
||||
startDriveQuery(*entry);
|
||||
}
|
||||
}
|
||||
changed=true;
|
||||
}
|
||||
for(auto &query:driveQueries)
|
||||
@@ -1739,7 +1955,8 @@ void pollDriveQueries(HWND owner)
|
||||
try {query.drives=query.pending.get();}
|
||||
catch(const std::system_error &e)
|
||||
{
|
||||
ks::log(L"LAN Files drive query failed: Windows error "+std::to_wstring(e.code().value()));
|
||||
ks::log(L"LAN Files drive query for "+query.peer.name+L" ("+ks::wide(query.peer.address)+
|
||||
L") failed: Windows error "+std::to_wstring(e.code().value()));
|
||||
if(e.code()==std::error_code(WSAETIMEDOUT,std::system_category()))
|
||||
query.error=L"Connection timed out";
|
||||
else
|
||||
@@ -1752,8 +1969,12 @@ void pollDriveQueries(HWND owner)
|
||||
}
|
||||
changed=true;
|
||||
}
|
||||
if(!pending && drivePeerLookupError.empty() &&
|
||||
std::none_of(driveQueries.begin(),driveQueries.end(),[](const DriveQuery &query)
|
||||
{return query.peer.address.empty() || !query.error.empty();}))
|
||||
nextDriveRefresh=0;
|
||||
if(changed) showRemoteDrives();
|
||||
if(!pending && !refreshDriveAddresses) KillTimer(owner,driveQueryTimer);
|
||||
if(!pending && !nextDriveRefresh) KillTimer(owner,driveQueryTimer);
|
||||
}
|
||||
|
||||
void chooseDrive(int index,bool fromMenu)
|
||||
@@ -1773,8 +1994,9 @@ void chooseDrive(int index,bool fromMenu)
|
||||
query.peer=peer;
|
||||
startDriveQuery(query);
|
||||
}
|
||||
refreshDriveAddresses=true;
|
||||
driveOpened=GetTickCount64();
|
||||
const auto now=GetTickCount64();
|
||||
nextDriveRefresh=now+500;
|
||||
driveRefreshDeadline=now+20000;
|
||||
const DWORD disks=GetLogicalDrives();
|
||||
int selected=0;
|
||||
int textWidth=0;
|
||||
@@ -1881,7 +2103,8 @@ void openSelectedText(const Panel &panel, bool edit, bool external)
|
||||
farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned,
|
||||
[](HWND owner)
|
||||
{
|
||||
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",true)==IDYES;
|
||||
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",
|
||||
{.confirm=true})==IDYES;
|
||||
}},panel.peer?&*panel.peer:nullptr);
|
||||
}
|
||||
|
||||
@@ -2514,7 +2737,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(LOWORD(wp)!=IDOK) return FALSE;
|
||||
const auto showError=[&](const wchar_t *message)
|
||||
{
|
||||
showFilesNotice(dialog,message,L"Error",false,nullptr,true);
|
||||
showFilesNotice(dialog,message,L"Error",{.tone=FilesNoticeTone::warning});
|
||||
SetFocus(GetDlgItem(dialog,pathField));
|
||||
};
|
||||
try
|
||||
@@ -2904,11 +3127,55 @@ struct FilesNotice
|
||||
{
|
||||
const wchar_t *text;
|
||||
std::wstring title;
|
||||
bool confirm;
|
||||
bool *remember;
|
||||
bool warning;
|
||||
FilesNoticeOptions options;
|
||||
};
|
||||
|
||||
void layoutFilesNotice(HWND dialog)
|
||||
{
|
||||
const auto ¬ice=*reinterpret_cast<const FilesNotice *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
|
||||
const auto inset=frame.content();
|
||||
const auto top=dialogListInset(frame,textHeight);
|
||||
const auto field=GetDlgItem(dialog,100);
|
||||
RECT client{};
|
||||
GetClientRect(dialog,&client);
|
||||
const auto contentWidth=std::max(1L,client.right-2*inset);
|
||||
TEXTMETRICW metrics{};
|
||||
if(const auto dc=GetDC(field))
|
||||
{
|
||||
const auto previous=SelectObject(dc,mono);
|
||||
GetTextMetricsW(dc,&metrics);
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(field,dc);
|
||||
}
|
||||
const auto lineHeight=std::max(1L,metrics.tmHeight);
|
||||
const auto place=[&](int id,int y,int height)
|
||||
{
|
||||
SetWindowPos(GetDlgItem(dialog,id),nullptr,inset,y,contentWidth,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
};
|
||||
constexpr LRESULT maxLines=8;
|
||||
ShowScrollBar(field,SB_VERT,FALSE);
|
||||
place(100,top,maxLines*lineHeight);
|
||||
const auto lines=SendMessageW(field,EM_GETLINECOUNT,0,0);
|
||||
const bool overflow=lines>maxLines;
|
||||
const auto height=static_cast<int>(std::clamp<LRESULT>(lines,1,maxLines))*lineHeight;
|
||||
place(100,top,height);
|
||||
ShowScrollBar(field,SB_VERT,overflow);
|
||||
const auto style=GetWindowLongPtrW(field,GWL_STYLE);
|
||||
SetWindowLongPtrW(field,GWL_STYLE,overflow?style|WS_TABSTOP:style&~WS_TABSTOP);
|
||||
if(!overflow) SendMessageW(field,EM_LINESCROLL,0,-SendMessageW(field,EM_GETFIRSTVISIBLELINE,0,0));
|
||||
auto bottom=top+height;
|
||||
if(notice.options.remember)
|
||||
{
|
||||
bottom+=dialogRowGap();
|
||||
place(101,bottom,textHeight);
|
||||
bottom+=textHeight;
|
||||
}
|
||||
place(102,bottom+dialogRowGap()+4,1);
|
||||
if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO});
|
||||
else layoutDialogButtons(dialog,102,{IDOK});
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
@@ -2916,70 +3183,73 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
SetWindowLongPtrW(window,DWLP_USER,lp);
|
||||
const auto ¬ice=*reinterpret_cast<const FilesNotice *>(lp);
|
||||
prepareTextDialog(window);
|
||||
SetDlgItemTextW(window,100,notice.text);
|
||||
if(notice.warning)
|
||||
const auto field=GetDlgItem(window,100);
|
||||
SendMessageW(field,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,0);
|
||||
SetWindowTextW(field,notice.text);
|
||||
if(notice.options.remember)
|
||||
{
|
||||
const auto bounds=dialogControlBounds(window,100);
|
||||
const auto divider=dialogControlBounds(window,102);
|
||||
RECT text{0,0,bounds.right-bounds.left,0};
|
||||
if(const auto dc=GetDC(window))
|
||||
{
|
||||
const auto previous=SelectObject(dc,mono);
|
||||
DrawTextW(dc,notice.text,-1,&text,DT_CALCRECT|DT_WORDBREAK|DT_NOPREFIX);
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(window,dc);
|
||||
}
|
||||
const auto height=std::max<LONG>(text.bottom,textHeight);
|
||||
SetWindowPos(GetDlgItem(window,100),nullptr,bounds.left,bounds.top,bounds.right-bounds.left,height,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SetWindowPos(GetDlgItem(window,102),nullptr,divider.left,bounds.top+height+dialogRowGap()+4,0,0,
|
||||
SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
layoutDialogButtons(window,102,{IDOK});
|
||||
const auto checkbox=GetDlgItem(window,101);
|
||||
installFarCheckbox(checkbox,notice.options.tone==FilesNoticeTone::warning?FarCheckboxSurface::warning:
|
||||
notice.options.tone==FilesNoticeTone::neutral?FarCheckboxSurface::gray:FarCheckboxSurface::dialog);
|
||||
ShowWindow(checkbox,SW_SHOW);
|
||||
}
|
||||
if(notice.remember)
|
||||
{
|
||||
const auto field=GetDlgItem(window,100);
|
||||
RECT bounds{};
|
||||
GetWindowRect(field,&bounds);
|
||||
SetWindowPos(field,nullptr,0,0,bounds.right-bounds.left,
|
||||
(bounds.bottom-bounds.top)*3/4,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
ShowWindow(GetDlgItem(window,101),SW_SHOW);
|
||||
}
|
||||
if(notice.confirm)
|
||||
if(notice.options.confirm)
|
||||
{
|
||||
ShowWindow(GetDlgItem(window,IDOK),SW_HIDE);
|
||||
ShowWindow(GetDlgItem(window,IDYES),SW_SHOW);
|
||||
ShowWindow(GetDlgItem(window,IDNO),SW_SHOW);
|
||||
groupDialogButtons(window,{IDYES,IDNO});
|
||||
}
|
||||
else if(!notice.warning) groupDialogButtons(window,{IDOK});
|
||||
const auto defaultButton=notice.confirm?IDNO:IDOK;
|
||||
RECT caption{},text{};
|
||||
if(const auto dc=GetDC(window))
|
||||
{
|
||||
const auto previous=SelectObject(dc,mono);
|
||||
DrawTextW(dc,notice.title.c_str(),-1,&caption,DT_CALCRECT|DT_SINGLELINE|DT_NOPREFIX);
|
||||
DrawTextW(dc,notice.text,-1,&text,DT_CALCRECT|DT_NOPREFIX|DT_EXPANDTABS);
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(window,dc);
|
||||
}
|
||||
const auto inset=dialogFrameMetrics(GetDpiForWindow(window)).content();
|
||||
const auto minimum=std::max({24L*cellWidth,caption.right+6*cellWidth,
|
||||
notice.options.remember?30L*cellWidth:0L})+2*inset;
|
||||
const auto width=std::clamp(text.right+cellWidth+2*inset,minimum,std::max(minimum,60L*cellWidth+2*inset));
|
||||
SetWindowPos(window,nullptr,0,0,width,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
layoutFilesNotice(window);
|
||||
FilesModalDialog::fitWidthToOwner(window,minimum,layoutFilesNotice);
|
||||
const auto defaultButton=notice.options.confirm?IDNO:IDOK;
|
||||
SendMessageW(window,DM_SETDEFID,defaultButton,0);
|
||||
SetFocus(GetDlgItem(window,defaultButton));
|
||||
return FALSE;
|
||||
}
|
||||
const auto *notice=reinterpret_cast<const FilesNotice *>(GetWindowLongPtrW(window,DWLP_USER));
|
||||
if(!notice) return FALSE;
|
||||
if(const auto painted=paintCopyDialog(window,message,wp,lp,notice->title.c_str(),
|
||||
notice->warning,notice->warning?std::initializer_list<int>{102}:std::initializer_list<int>{},
|
||||
!notice->warning)) return painted;
|
||||
const bool warning=notice->options.tone==FilesNoticeTone::warning;
|
||||
const bool palette=notice->options.tone==FilesNoticeTone::dialog;
|
||||
if(message==WM_CTLCOLORSTATIC && reinterpret_cast<HWND>(lp)==GetDlgItem(window,100) && !palette)
|
||||
{
|
||||
const auto dc=reinterpret_cast<HDC>(wp);
|
||||
SetTextColor(dc,warning?RGB(255,255,255):RGB(0,0,0));
|
||||
SetBkColor(dc,warning?RGB(128,0,0):RGB(192,192,192));
|
||||
return reinterpret_cast<INT_PTR>(warning?warningBrush:GetStockObject(LTGRAY_BRUSH));
|
||||
}
|
||||
if(const auto painted=paintCopyDialog(window,message,wp,lp,notice->title.c_str(),warning,{102},palette))
|
||||
return painted;
|
||||
const auto command=LOWORD(wp);
|
||||
if(message==WM_COMMAND && (command==IDOK || command==IDCANCEL || command==IDYES || command==IDNO))
|
||||
{
|
||||
if(command==IDYES && notice->remember)
|
||||
*notice->remember=IsDlgButtonChecked(window,101)==BST_CHECKED;
|
||||
if(command==IDYES && notice->options.remember)
|
||||
*notice->options.remember=IsDlgButtonChecked(window,101)==BST_CHECKED;
|
||||
FilesModalDialog::finish(window,command);
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,bool confirm,bool *remember,bool warning)
|
||||
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options)
|
||||
{
|
||||
const bool createBrush=warning && !warningBrush;
|
||||
const bool createBrush=options.tone==FilesNoticeTone::warning && !warningBrush;
|
||||
if(createBrush) warningBrush=CreateSolidBrush(RGB(128,0,0));
|
||||
FilesNotice notice{text,std::wstring(L" ")+title+L" ",confirm,remember,warning};
|
||||
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(warning?609:607),owner,filesNoticeDialog,
|
||||
FilesNotice notice{text,std::wstring(L" ")+title+L" ",options};
|
||||
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(607),owner,filesNoticeDialog,
|
||||
reinterpret_cast<LPARAM>(¬ice));
|
||||
if(createBrush)
|
||||
{
|
||||
@@ -3442,14 +3712,8 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
|
||||
request.otherDirectory=destination.directory;
|
||||
request.sourcePeer=source.peer?&*source.peer:nullptr;
|
||||
request.otherPeer=request.destinationPeer=destination.peer?&*destination.peer:nullptr;
|
||||
for(size_t i=0;i<source.rows.size();++i)
|
||||
if(source.marked[i]) request.sources.push_back(source.rows[i]);
|
||||
if(request.sources.empty())
|
||||
{
|
||||
const auto row=SendMessageW(source.list,LB_GETCURSEL,0,0);
|
||||
if(row<0 || static_cast<size_t>(row)>=source.rows.size() || source.sizes[row]==L"Up") return;
|
||||
request.sources.push_back(source.rows[row]);
|
||||
}
|
||||
request.sources=selectedPanelPaths(source);
|
||||
if(request.sources.empty()) return;
|
||||
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(102),owner,copyDialog,
|
||||
reinterpret_cast<LPARAM>(&request));
|
||||
if(result==-1) setStatus(L"Could not open the Copy dialog.");
|
||||
@@ -3753,15 +4017,8 @@ bool pumpDeletion(HWND window,bool &canceled)
|
||||
void deleteSelection(HWND owner,Panel &panel,bool permanent)
|
||||
{
|
||||
if(copyInProgress) return;
|
||||
std::vector<fs::path> paths;
|
||||
for(size_t i=0;i<panel.rows.size();++i)
|
||||
if(panel.marked[i] && panel.sizes[i]!=L"Up") paths.push_back(panel.rows[i]);
|
||||
if(paths.empty())
|
||||
{
|
||||
const auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0);
|
||||
if(row<0 || static_cast<size_t>(row)>=panel.rows.size() || panel.sizes[row]==L"Up") return;
|
||||
paths.push_back(panel.rows[row]);
|
||||
}
|
||||
auto paths=selectedPanelPaths(panel);
|
||||
if(paths.empty()) return;
|
||||
const auto shown=std::min<size_t>(paths.size(),10);
|
||||
std::wstring entries;
|
||||
for(size_t i=0;i<shown;++i)
|
||||
@@ -4092,7 +4349,7 @@ INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(command!=IDOK) return FALSE;
|
||||
const auto error=[&](const wchar_t *text,HWND focus)
|
||||
{
|
||||
showFilesNotice(dialog,text,L"Error",false,nullptr,true);
|
||||
showFilesNotice(dialog,text,L"Error",{.tone=FilesNoticeTone::warning});
|
||||
SetFocus(focus);
|
||||
};
|
||||
const auto entered=dialogFieldText(input);
|
||||
@@ -4158,16 +4415,37 @@ void makeFolder(HWND owner,Panel &panel)
|
||||
|
||||
LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR index)
|
||||
{
|
||||
if(message==WM_LBUTTONDOWN)
|
||||
if(message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK ||
|
||||
(message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window))
|
||||
{
|
||||
auto &panel=panels[index];
|
||||
activatePanel(static_cast<int>(index));
|
||||
const auto count=SendMessageW(window,LB_GETCOUNT,0,0);
|
||||
RECT last{};
|
||||
if(count>0 && SendMessageW(window,LB_GETITEMRECT,count-1,reinterpret_cast<LPARAM>(&last))!=LB_ERR &&
|
||||
GET_Y_LPARAM(lp)>=last.bottom)
|
||||
if(!count || count==LB_ERR) return 0;
|
||||
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
|
||||
const auto row=static_cast<LRESULT>(LOWORD(hit));
|
||||
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
RECT bounds{};
|
||||
const bool rowHit=!HIWORD(hit) && row<count &&
|
||||
SendMessageW(window,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR &&
|
||||
PtInRect(&bounds,point);
|
||||
if(rowHit)
|
||||
{
|
||||
selectPanelEdge(panels[index],false);
|
||||
return 0;
|
||||
if(row!=SendMessageW(window,LB_GETCURSEL,0,0))
|
||||
SendMessageW(window,LB_SETCURSEL,row,0);
|
||||
}
|
||||
else if(point.y>=0 && message==WM_LBUTTONDOWN)
|
||||
SendMessageW(window,LB_SETCURSEL,count-1,0);
|
||||
showFileDetails(panel);
|
||||
if(message==WM_LBUTTONDOWN) SetCapture(window);
|
||||
if(message==WM_LBUTTONDBLCLK && rowHit) enter(panel);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_LBUTTONUP && GetCapture()==window)
|
||||
{
|
||||
ReleaseCapture();
|
||||
restoreCommandFocus();
|
||||
return 0;
|
||||
}
|
||||
const bool rangeKey=wp==VK_UP || wp==VK_DOWN || wp==VK_LEFT || wp==VK_RIGHT;
|
||||
if(message==WM_KEYDOWN && (wp==VK_INSERT || (rangeKey && (GetKeyState(VK_SHIFT)&0x8000))))
|
||||
@@ -4207,11 +4485,18 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
{
|
||||
if(wp==VK_TAB) { activatePanel(static_cast<int>(1-index)); SetFocus(terminalInput); return 0; }
|
||||
if (wp == VK_RETURN) { enter(panels[index]); return 0; }
|
||||
if (wp == VK_F2) { open(panels[index], panels[index].directory); return 0; }
|
||||
if (wp == VK_F2)
|
||||
{
|
||||
refreshPanel(panels[index]);
|
||||
return 0;
|
||||
}
|
||||
if (wp == VK_F10) { SendMessageW(GetParent(window), WM_CLOSE, 0, 0); return 0; }
|
||||
if (wp == VK_F3 || wp == VK_F4)
|
||||
{
|
||||
openSelectedText(panels[index],wp==VK_F4,false);
|
||||
auto &panel=panels[index];
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(wp==VK_F3 && row!=LB_ERR && panel.sizes[row]==L"Folder") calculateFolderSizes(panel,row);
|
||||
else openSelectedText(panel,wp==VK_F4,false);
|
||||
return 0;
|
||||
}
|
||||
if (wp == VK_F5 || wp == VK_F6)
|
||||
@@ -4299,7 +4584,7 @@ void openMenu(HWND window, int index)
|
||||
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"};
|
||||
else if(index==2)
|
||||
{
|
||||
rows={L"Refresh\tF2",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
|
||||
rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
|
||||
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4"};
|
||||
if(panels[active].peer)
|
||||
{
|
||||
@@ -4307,15 +4592,23 @@ void openMenu(HWND window, int index)
|
||||
rows.push_back(L"Update remote KSwitcher");
|
||||
}
|
||||
}
|
||||
commandActions.clear();
|
||||
if(index==2)
|
||||
{
|
||||
commandActions={0,3,-1,1,2,4,5};
|
||||
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
|
||||
}
|
||||
else
|
||||
for(size_t i=0;i<rows.size();++i) commandActions.push_back(static_cast<int>(i));
|
||||
std::set<wchar_t> used;
|
||||
commandAccessPositions.assign(rows.size(),std::wstring::npos);
|
||||
std::vector<size_t> accessPositions(rows.size(),std::wstring::npos);
|
||||
const auto reserve=[&](size_t row,wchar_t key)
|
||||
{
|
||||
const auto &text=rows[row];
|
||||
for(size_t pos=0;pos<text.size() && text[pos]!=L'\t';++pos)
|
||||
if(towupper(text[pos])==key && used.insert(key).second)
|
||||
{
|
||||
commandAccessPositions[row]=pos;
|
||||
accessPositions[row]=pos;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -4326,14 +4619,19 @@ void openMenu(HWND window, int index)
|
||||
for(size_t i=0;i<rows.size();++i)
|
||||
{
|
||||
const auto &text=rows[i];
|
||||
if(commandAccessPositions[i]==std::wstring::npos)
|
||||
if(accessPositions[i]==std::wstring::npos)
|
||||
for(const auto ch:text)
|
||||
{
|
||||
if(ch==L'\t') break;
|
||||
const auto key=towupper(ch);
|
||||
if(key>=L'A' && key<=L'Z' && reserve(i,static_cast<wchar_t>(key))) break;
|
||||
}
|
||||
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(text.c_str()));
|
||||
}
|
||||
commandAccessPositions.clear();
|
||||
for(const auto action:commandActions)
|
||||
{
|
||||
commandAccessPositions.push_back(action<0?std::wstring::npos:accessPositions[action]);
|
||||
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(action<0?L"":rows[action].c_str()));
|
||||
}
|
||||
RECT anchor{}, client{};
|
||||
GetWindowRect(menuItems[index],&anchor);
|
||||
@@ -4344,7 +4642,7 @@ void openMenu(HWND window, int index)
|
||||
const int x=std::clamp(static_cast<int>(anchor.left)+inset,inset,
|
||||
std::max(inset,static_cast<int>(client.right)-width-inset));
|
||||
const int y=anchor.bottom+5;
|
||||
const int height=static_cast<int>(rows.size())*static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0));
|
||||
const int height=static_cast<int>(commandActions.size())*static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0));
|
||||
SetWindowPos(pickerFrame,HWND_TOP,x-inset,y-inset,width+2*inset,height+2*inset,SWP_SHOWWINDOW);
|
||||
SetWindowPos(picker,HWND_TOP,x,y,width,height,SWP_SHOWWINDOW);
|
||||
SendMessageW(picker,LB_SETCURSEL,0,0);
|
||||
@@ -4528,7 +4826,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
updateTerminalOutput();
|
||||
return 0;
|
||||
}
|
||||
if(wp==directoryWatchTimer) { refreshChangedPanels(); return 0; }
|
||||
if(wp==directoryWatchTimer) { refreshChangedPanels(); collectFolderSizes(); return 0; }
|
||||
if(wp!=transferHighlightTimer) break;
|
||||
++transferHighlightPhase;
|
||||
for(auto &panel:panels)
|
||||
@@ -4580,10 +4878,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
SetTimer(window,directoryWatchTimer,200,nullptr);
|
||||
if (!mono || !blue || !teal || !menuBar || !picker || !pickerFrame || !status || !panelSearchPopup) return -1;
|
||||
SendMessageW(status, WM_SETFONT, reinterpret_cast<WPARAM>(mono), FALSE);
|
||||
const wchar_t *labels[]{L"F2 Refresh", L"F3 View", L"F4 Edit", L"F5 Copy", L"F6 Move", L"F7 Mkdir", L"F10 Exit"};
|
||||
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
|
||||
commands[i] = CreateWindowW(L"BUTTON", labels[i], WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
|
||||
0, 0, 0, 0, window, reinterpret_cast<HMENU>(110 + static_cast<INT_PTR>(i)), instance, nullptr);
|
||||
commands[i] = CreateWindowW(L"BUTTON", keyBar[i].label, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
|
||||
0, 0, 0, 0, window, reinterpret_cast<HMENU>(static_cast<INT_PTR>(keyBar[i].id)), instance, nullptr);
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
auto &panel = panels[i];
|
||||
@@ -4850,6 +5147,15 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
auto background=item.CtlType==ODT_BUTTON?Footer:item.hwndItem==picker?Dialog:PanelBlue;
|
||||
auto foreground=colors[Text];
|
||||
if(item.hwndItem==picker && commandPicker && item.itemID<commandActions.size() && commandActions[item.itemID]<0)
|
||||
{
|
||||
FillRect(item.hDC,&item.rcItem,teal);
|
||||
const auto y=(item.rcItem.top+item.rcItem.bottom)/2;
|
||||
const RECT line{item.rcItem.left,y,item.rcItem.right,y+1};
|
||||
SetDCBrushColor(item.hDC,colors[Frame]);
|
||||
FillRect(item.hDC,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
return TRUE;
|
||||
}
|
||||
if(item.hwndItem==picker && !commandPicker && item.itemID==drivePaths.size())
|
||||
{
|
||||
auto row=item.rcItem;
|
||||
@@ -4869,6 +5175,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
const bool activePanelRow=panelRow && item.hwndItem==panels[active].list;
|
||||
if(panelRow)
|
||||
{
|
||||
traceTerminal("panel-draw",item.CtlID-102,item.itemID);
|
||||
const auto cursor=SendMessageW(item.hwndItem,LB_GETCURSEL,0,0);
|
||||
if(activePanelRow && cursor!=LB_ERR &&
|
||||
static_cast<UINT>(cursor)==item.itemID) background=PanelCursor;
|
||||
@@ -4995,7 +5302,14 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
paintText(item.hDC,name,text.c_str(),foreground,rowBackground,false,rowFont);
|
||||
const auto &amount=panel.sizes[item.itemID];
|
||||
auto visible=amount;
|
||||
if(amount!=L"Folder" && amount!=L"Up")
|
||||
const auto measured=folder?panel.folderSizes.find(panel.rows[item.itemID]):panel.folderSizes.end();
|
||||
if(measured!=panel.folderSizes.end())
|
||||
{
|
||||
const auto partial=measured->second.partial;
|
||||
visible=formatSize(measured->second.bytes,static_cast<size_t>(sizeWidth)-(partial?1:0));
|
||||
if(partial) visible+=L"+";
|
||||
}
|
||||
else if(amount!=L"Folder" && amount!=L"Up")
|
||||
visible=formatSize(std::stoull(amount),static_cast<size_t>(sizeWidth));
|
||||
paintText(item.hDC,size,visible.c_str(),foreground,rowBackground,true);
|
||||
RECT line{size.left,size.top,size.left+1,size.bottom};
|
||||
@@ -5022,17 +5336,16 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
openMenu(window,LOWORD(wp)-130);
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wp) >= 110 && LOWORD(wp) < 110+std::size(commands) && HIWORD(wp) == BN_CLICKED)
|
||||
if (HIWORD(wp) == BN_CLICKED)
|
||||
{
|
||||
const WPARAM keys[]{VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F10};
|
||||
SendMessageW(panels[active].list, WM_KEYDOWN, keys[LOWORD(wp) - 110], 0);
|
||||
for(const auto &command:keyBar)
|
||||
if(LOWORD(wp)==command.id) SendMessageW(panels[active].list,WM_KEYDOWN,command.key,0);
|
||||
}
|
||||
if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_DBLCLK)
|
||||
enter(panels[LOWORD(wp) - 102]);
|
||||
if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_SELCHANGE)
|
||||
{
|
||||
const auto &panel=panels[LOWORD(wp) - 102];
|
||||
InvalidateRect(panel.list,nullptr,FALSE);
|
||||
showFileDetails(panel);
|
||||
}
|
||||
return 0;
|
||||
@@ -5065,6 +5378,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
DestroyWindow(window);
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
for(auto &panel:panels) panel.folderSizeStop.request_stop();
|
||||
KillTimer(window,terminalTimer);
|
||||
KillTimer(window,directoryWatchTimer);
|
||||
for(auto &panel:panels) panel.watch.reset();
|
||||
@@ -5139,6 +5453,10 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
{
|
||||
if(GetForegroundWindow()==window || IsChild(window,GetFocus())) restoreCommandFocus();
|
||||
if(GetMessageW(&message,nullptr,0,0)<=0) break;
|
||||
if(message.message==WM_KEYDOWN && message.wParam==VK_TAB &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
|
||||
ks::files::cycleTextWindows(GetAncestor(message.hwnd,GA_ROOT)))
|
||||
continue;
|
||||
if(!IsWindow(window) || (message.hwnd && GetAncestor(message.hwnd,GA_ROOTOWNER)!=window))
|
||||
{
|
||||
TranslateMessage(&message);
|
||||
@@ -5226,12 +5544,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
{
|
||||
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
|
||||
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
|
||||
if(ctrl && !shift && (message.wParam=='F' || message.wParam=='C' || message.wParam==VK_RETURN))
|
||||
if(ctrl && !shift &&
|
||||
(message.wParam=='F' || message.wParam=='C' || message.wParam=='R' ||
|
||||
message.wParam==VK_RETURN || message.wParam==VK_INSERT))
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)))
|
||||
{
|
||||
if(message.wParam=='F') insertCurrentPanelPath();
|
||||
else if(message.wParam=='R') refreshPanel(panels[active]);
|
||||
else if(message.wParam==VK_RETURN) insertCurrentPanelPath(true);
|
||||
else if(message.wParam==VK_INSERT) copyPanelNames(window);
|
||||
else SendMessageW(terminalInput,WM_COPY,0,0);
|
||||
}
|
||||
continue;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -306,7 +306,8 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
|
||||
[&](const auto &scheme){return sameSchemeName(name,scheme.name.c_str());});
|
||||
if(existing!=settings.schemes.end())
|
||||
{
|
||||
if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",true)!=IDYES) return;
|
||||
if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",
|
||||
{.confirm=true,.tone=FilesNoticeTone::neutral})!=IDYES) return;
|
||||
existing->colors=profile.colors;
|
||||
profile.scheme=existing->name;
|
||||
}
|
||||
|
||||
+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;
|
||||
};
|
||||
|
||||
+644
-17
@@ -1,9 +1,11 @@
|
||||
#include "files_text_window.h"
|
||||
#include "files_text_preferences.h"
|
||||
#include "files_menu_paint.h"
|
||||
#include "files_menu_navigation.h"
|
||||
#include "files_history_date.h"
|
||||
#include "files_text_document.h"
|
||||
#include "files_text_language.h"
|
||||
#include "files_terminal_view.h"
|
||||
#include "platform.h"
|
||||
#include "lan_files.h"
|
||||
|
||||
@@ -14,6 +16,7 @@
|
||||
#include <atomic>
|
||||
#include <windowsx.h>
|
||||
#include <commdlg.h>
|
||||
#include <wincrypt.h>
|
||||
#include <Scintilla.h>
|
||||
#include <ILexer.h>
|
||||
#include <Lexilla.h>
|
||||
@@ -26,6 +29,8 @@
|
||||
#include <cwctype>
|
||||
#include <deque>
|
||||
#include <future>
|
||||
#include <fstream>
|
||||
#include <thread>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
@@ -181,7 +186,8 @@ void drawMenuTitle(HDC dc, RECT bounds, const MenuLabel &label, COLORREF accessI
|
||||
enum Command : UINT
|
||||
{
|
||||
save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage,
|
||||
undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options,
|
||||
undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, switchMode,
|
||||
historyBack, historyForward,
|
||||
lexerStart = 1000,
|
||||
};
|
||||
|
||||
@@ -324,6 +330,12 @@ struct FarPopup
|
||||
}
|
||||
}
|
||||
|
||||
void stepMenu(int direction)
|
||||
{
|
||||
select(adjacentMenuRow(current,static_cast<int>(rows.size()),direction,
|
||||
[this](int candidate){return rows[candidate].index>=0;}));
|
||||
}
|
||||
|
||||
void accept()
|
||||
{
|
||||
result=rows[current].index;
|
||||
@@ -435,8 +447,8 @@ LRESULT CALLBACK farPopupWindow(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
case VK_ESCAPE: state->done=true; break;
|
||||
case VK_RETURN: state->accept(); break;
|
||||
case VK_UP: state->step(-1); break;
|
||||
case VK_DOWN: state->step(1); break;
|
||||
case VK_UP: state->stepMenu(-1); break;
|
||||
case VK_DOWN: state->stepMenu(1); break;
|
||||
case VK_PRIOR: state->step(-1,state->visible); break;
|
||||
case VK_NEXT: state->step(1,state->visible); break;
|
||||
case VK_HOME: state->step(-1,static_cast<int>(state->rows.size())); break;
|
||||
@@ -558,6 +570,7 @@ struct RemoteTextFile
|
||||
lan::FilesPeer peer;
|
||||
std::filesystem::path original,cache;
|
||||
lan::FileRevision revision{};
|
||||
bool editable{};
|
||||
|
||||
~RemoteTextFile()
|
||||
{
|
||||
@@ -574,7 +587,7 @@ struct RemoteTextFile
|
||||
return {reply.at("size").get<uint64_t>(),reply.at("modified").get<uint64_t>()};
|
||||
}
|
||||
|
||||
void download(bool edit,const lan::FileProgress &progress)
|
||||
void download(bool edit,const lan::FileProgress &progress,uint64_t sizeLimit=UINT64_MAX)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
@@ -587,11 +600,14 @@ struct RemoteTextFile
|
||||
lan::FilesConnection source(&peer),target;
|
||||
const auto info=source.call(lan::fileRequest("stat",original));
|
||||
lan::checkFileReply(info);
|
||||
editable=info.value("editCommit",false) &&
|
||||
!(info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY);
|
||||
if(edit && !info.value("editCommit",false))
|
||||
throw std::runtime_error("Update KSwitcher on the remote computer to edit this file.");
|
||||
if(edit && (info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY))
|
||||
throw std::runtime_error("The remote file is read-only.");
|
||||
revision={info.at("size"),info.at("modified")};
|
||||
if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview.");
|
||||
try
|
||||
{
|
||||
lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress);
|
||||
@@ -620,6 +636,8 @@ struct RemoteTextFile
|
||||
|
||||
class TextWindow;
|
||||
std::map<HWND,std::shared_ptr<TextWindow>> textWindows;
|
||||
std::vector<HWND> textWindowOrder;
|
||||
HWND filesOwner{};
|
||||
bool textOwnerClosed=false;
|
||||
constexpr ULONG_PTR openDocumentQuery=0x4B534644;
|
||||
|
||||
@@ -628,12 +646,76 @@ std::wstring documentIdentity(const std::filesystem::path &path,std::string_view
|
||||
return wide(std::string(peer))+L"\n"+path.native();
|
||||
}
|
||||
|
||||
std::filesystem::path markdownTarget(const std::filesystem::path &document,std::string_view url)
|
||||
{
|
||||
url=url.substr(0,url.find_first_of("?#"));
|
||||
std::string decoded;
|
||||
const auto hex=[](char c) {
|
||||
if(c>='0' && c<='9') return c-'0';
|
||||
if(c>='a' && c<='f') return c-'a'+10;
|
||||
if(c>='A' && c<='F') return c-'A'+10;
|
||||
return -1;
|
||||
};
|
||||
for(size_t i=0;i<url.size();++i)
|
||||
{
|
||||
if(url[i]!='%') { decoded+=url[i]; continue; }
|
||||
if(i+2>=url.size()) return {};
|
||||
const auto high=hex(url[i+1]), low=hex(url[i+2]);
|
||||
if(high<0 || low<0) return {};
|
||||
decoded+=static_cast<char>(16*high+low);
|
||||
i+=2;
|
||||
}
|
||||
if(decoded.empty() || decoded.find_first_of(":\0",0,2)!=decoded.npos) return {};
|
||||
const std::filesystem::path relative(wide(decoded));
|
||||
if(relative.has_root_path()) return {};
|
||||
return (document.parent_path()/relative).lexically_normal();
|
||||
}
|
||||
|
||||
std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer *peer,
|
||||
const std::shared_ptr<std::atomic<bool>> &cancel)
|
||||
{
|
||||
auto extension=path.extension().wstring();
|
||||
std::transform(extension.begin(),extension.end(),extension.begin(),::towlower);
|
||||
const std::map<std::wstring,std::string> types{
|
||||
{L".png","png"},{L".jpg","jpeg"},{L".jpeg","jpeg"},{L".gif","gif"},
|
||||
{L".webp","webp"},{L".bmp","bmp"},{L".svg","svg+xml"},{L".avif","avif"}
|
||||
};
|
||||
const auto type=types.find(extension);
|
||||
if(type==types.end()) return {};
|
||||
constexpr uint64_t limit=16*1024*1024;
|
||||
auto source=path;
|
||||
std::optional<RemoteTextFile> fetched;
|
||||
if(peer)
|
||||
{
|
||||
if(*cancel) return {};
|
||||
fetched.emplace(RemoteTextFile{*peer,path});
|
||||
fetched->download(false,[&](uint64_t,uint64_t){return !*cancel;},limit);
|
||||
source=fetched->cache;
|
||||
}
|
||||
if(*cancel) return {};
|
||||
std::ifstream input(source,std::ios::binary|std::ios::ate);
|
||||
const auto size=input.tellg();
|
||||
if(size<=0 || static_cast<uint64_t>(size)>limit) return {};
|
||||
std::string bytes(static_cast<size_t>(size),'\0');
|
||||
if(!input.seekg(0).read(bytes.data(),bytes.size())) return {};
|
||||
constexpr auto flags=CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF;
|
||||
DWORD length{};
|
||||
const auto data=reinterpret_cast<const BYTE *>(bytes.data());
|
||||
if(!CryptBinaryToStringA(data,static_cast<DWORD>(bytes.size()),flags,nullptr,&length)) return {};
|
||||
std::string encoded(length,'\0');
|
||||
if(!CryptBinaryToStringA(data,static_cast<DWORD>(bytes.size()),flags,encoded.data(),&length)) return {};
|
||||
encoded.resize(length);
|
||||
return "data:image/"+type->second+";base64,"+encoded;
|
||||
}
|
||||
|
||||
class TextWindow
|
||||
{
|
||||
public:
|
||||
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer)
|
||||
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer,
|
||||
std::string_view fragment)
|
||||
: original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), search{dialogs}
|
||||
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
search{dialogs}, previewFragment(fragment)
|
||||
{
|
||||
if (peer) remote=std::make_unique<RemoteTextFile>(RemoteTextFile{*peer,original});
|
||||
else document=std::make_unique<TextDocument>(original,edit);
|
||||
@@ -651,7 +733,8 @@ public:
|
||||
static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam);
|
||||
HWND window{}, editor{};
|
||||
bool handleKey(const MSG &message);
|
||||
const std::filesystem::path original;
|
||||
void goToFragment(std::string_view fragment);
|
||||
std::filesystem::path original;
|
||||
const std::string peerId;
|
||||
|
||||
private:
|
||||
@@ -678,12 +761,60 @@ private:
|
||||
int pageEol = SC_EOL_CRLF;
|
||||
size_t undoBytes{};
|
||||
bool uploadPending{};
|
||||
bool switchAfterSave{};
|
||||
FilesTerminalView preview;
|
||||
bool previewWanted{}, previewVisible{};
|
||||
ULONGLONG previewDeadline{};
|
||||
ULONGLONG nextFileCheck{};
|
||||
struct FileStamp
|
||||
{
|
||||
uint64_t writeTime, fileIndex, size;
|
||||
DWORD volume;
|
||||
bool operator==(const FileStamp &) const = default;
|
||||
};
|
||||
std::optional<FileStamp> previewStamp;
|
||||
std::string previewFragment;
|
||||
struct PreviewLocation
|
||||
{
|
||||
std::filesystem::path path;
|
||||
std::string fragment;
|
||||
int scroll{};
|
||||
};
|
||||
struct PreviewLink
|
||||
{
|
||||
PreviewLocation target;
|
||||
int direction{}, scroll{};
|
||||
bool newWindow{};
|
||||
};
|
||||
std::vector<PreviewLocation> navigationHistory;
|
||||
size_t navigationIndex{};
|
||||
std::optional<size_t> destinationIndex;
|
||||
PreviewLocation destination;
|
||||
std::future<std::unique_ptr<RemoteTextFile>> navigation;
|
||||
std::shared_ptr<std::atomic<bool>> cancelNavigation;
|
||||
bool restoreScroll{};
|
||||
std::deque<PreviewLink> previewLinks;
|
||||
struct ImageRequest
|
||||
{
|
||||
std::filesystem::path path;
|
||||
uint64_t index{}, generation{};
|
||||
};
|
||||
std::deque<ImageRequest> imageQueue;
|
||||
std::future<std::string> image;
|
||||
ImageRequest activeImage;
|
||||
std::shared_ptr<std::atomic<bool>> cancelImages;
|
||||
std::atomic<bool> cancelOpen{};
|
||||
std::future<void> opening;
|
||||
std::future<bool> saving;
|
||||
static constexpr UINT_PTR saveTimer = 1;
|
||||
static constexpr UINT_PTR openTimer = 2;
|
||||
static constexpr UINT_PTR previewTimer = 3;
|
||||
static constexpr UINT_PTR navigationTimer = 4;
|
||||
static constexpr UINT trimUndo = WM_APP + 1;
|
||||
static constexpr UINT previewFailed = WM_APP + 2;
|
||||
static constexpr UINT openPreviewLink = WM_APP + 3;
|
||||
static constexpr UINT previewRendered = WM_APP + 4;
|
||||
static constexpr UINT cycleWindow = WM_APP + 5;
|
||||
|
||||
LRESULT send(UINT message, WPARAM wparam = 0, LPARAM lparam = 0) const
|
||||
{
|
||||
@@ -725,6 +856,24 @@ private:
|
||||
void saveFile(bool closeWhenDone);
|
||||
void finishSave();
|
||||
void requestClose();
|
||||
void toggleMode();
|
||||
void changeMode();
|
||||
bool needsSave() const;
|
||||
bool canPreview() const;
|
||||
void updatePreview();
|
||||
void stopPreview(bool refresh=true,bool keepBrowser=false);
|
||||
void renderPreview(bool keepPosition=false);
|
||||
std::optional<FileStamp> previewFileStamp() const;
|
||||
void refreshPreview();
|
||||
void cancelPreviewImages();
|
||||
void previewMessage(const std::wstring &value);
|
||||
void navigatePreview(PreviewLink request);
|
||||
void finishNavigation();
|
||||
void showLocation(std::unique_ptr<RemoteTextFile> fetched);
|
||||
void syncNavigation();
|
||||
void updateTitle();
|
||||
void pollImages();
|
||||
void focusContent();
|
||||
void layout();
|
||||
void paint();
|
||||
void command(UINT id);
|
||||
@@ -750,6 +899,7 @@ void TextWindow::createMenu()
|
||||
const auto menu = CreateMenu();
|
||||
const auto file = addGroup(menu, L"&File");
|
||||
if (edit) addItem(file, save, L"&Save\tF2");
|
||||
addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6");
|
||||
addItem(file, close, L"&Close\tF10");
|
||||
const auto actions = addGroup(menu, edit ? L"&Edit" : L"&Selection");
|
||||
if (edit)
|
||||
@@ -763,6 +913,12 @@ void TextWindow::createMenu()
|
||||
addItem(actions, copy, L"&Copy\tCtrl+C");
|
||||
addItem(actions, selectAll, L"Select &page\tCtrl+A");
|
||||
const auto navigation = addGroup(menu, L"&Navigate");
|
||||
if (!edit)
|
||||
{
|
||||
addItem(navigation, historyBack, L"&Back\tAlt+Left");
|
||||
addItem(navigation, historyForward, L"F&orward\tAlt+Right");
|
||||
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
|
||||
}
|
||||
addItem(navigation, findText, L"&Find on page…\tCtrl+F");
|
||||
addItem(navigation, findNext, L"Find &next\tF3");
|
||||
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
|
||||
@@ -950,6 +1106,8 @@ void TextWindow::updateMenus()
|
||||
for (const auto command : {previousPage, firstPage}) enable(command, !busy() && page > 0);
|
||||
for (const auto command : {nextPage, lastPage}) enable(command, !busy() && page + 1 < pageTotal);
|
||||
enable(goToPage, !busy() && pageTotal > 1);
|
||||
enable(historyBack, !navigation.valid() && navigationIndex>0);
|
||||
enable(historyForward, !navigation.valid() && navigationIndex+1<navigationHistory.size());
|
||||
}
|
||||
|
||||
void TextWindow::installLexer()
|
||||
@@ -1125,9 +1283,13 @@ void TextWindow::initializeDocument()
|
||||
{
|
||||
automatic=detectLanguage(original,document->readPage(0));
|
||||
language=automatic;
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
installLexer();
|
||||
loadPage(0);
|
||||
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
|
||||
updatePreview();
|
||||
}
|
||||
|
||||
void TextWindow::finishOpen()
|
||||
@@ -1156,6 +1318,7 @@ void TextWindow::saveFile(bool closeWhenDone)
|
||||
if (!stagedDirty && !uploadPending)
|
||||
{
|
||||
if (closeWhenDone) DestroyWindow(window);
|
||||
else if (std::exchange(switchAfterSave, false)) changeMode();
|
||||
return;
|
||||
}
|
||||
pendingCaret = send(SCI_GETCURRENTPOS);
|
||||
@@ -1190,6 +1353,7 @@ void TextWindow::finishSave()
|
||||
if (!busy() || saving.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready) return;
|
||||
KillTimer(window, saveTimer);
|
||||
send(SCI_SETREADONLY, !edit);
|
||||
const auto change = std::exchange(switchAfterSave, false);
|
||||
const auto reopened = saving.get();
|
||||
stagedDirty = false;
|
||||
if (!reopened)
|
||||
@@ -1199,6 +1363,7 @@ void TextWindow::finishSave()
|
||||
return;
|
||||
}
|
||||
if (closeAfterSave) { DestroyWindow(window); return; }
|
||||
if (change) { changeMode(); return; }
|
||||
if (pageTotal == 1 && document->pages() == 1)
|
||||
{
|
||||
fileSize = document->size();
|
||||
@@ -1213,7 +1378,7 @@ void TextWindow::requestClose()
|
||||
{
|
||||
if (opening.valid()) { cancelOpen=true; return; }
|
||||
if (busy()) return;
|
||||
if (uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty))
|
||||
if (needsSave())
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window);
|
||||
if (answer == IDCANCEL) return;
|
||||
@@ -1223,6 +1388,388 @@ void TextWindow::requestClose()
|
||||
DestroyWindow(window);
|
||||
}
|
||||
|
||||
bool TextWindow::needsSave() const
|
||||
{
|
||||
return uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty);
|
||||
}
|
||||
|
||||
void TextWindow::toggleMode()
|
||||
{
|
||||
if(navigation.valid()) return;
|
||||
if (edit && needsSave())
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window);
|
||||
if (answer == IDYES)
|
||||
{
|
||||
switchAfterSave = true;
|
||||
try { saveFile(false); }
|
||||
catch (...) { switchAfterSave = false; throw; }
|
||||
return;
|
||||
}
|
||||
if (answer != IDNO) return;
|
||||
// The local LAN cache may already contain changes from a failed upload.
|
||||
if (uploadPending)
|
||||
{
|
||||
auto refreshed = std::make_unique<RemoteTextFile>(RemoteTextFile{remote->peer,original});
|
||||
refreshed->download(false,{});
|
||||
auto replacement = std::make_unique<TextDocument>(refreshed->cache,false);
|
||||
document.reset();
|
||||
remote = std::move(refreshed);
|
||||
document = std::move(replacement);
|
||||
uploadPending = false;
|
||||
}
|
||||
}
|
||||
changeMode();
|
||||
}
|
||||
|
||||
void TextWindow::changeMode()
|
||||
{
|
||||
if (!edit && remote && !remote->editable)
|
||||
throw std::runtime_error("The remote file does not support editing.");
|
||||
auto replacement = std::make_unique<TextDocument>(remote ? remote->cache : original, !edit);
|
||||
const auto caret = send(SCI_GETCURRENTPOS);
|
||||
document = std::move(replacement);
|
||||
edit = !edit;
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
prefs = loadTextPreferences().profiles[edit];
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
installLexer();
|
||||
loadPage(std::min(page, document->pages() - 1));
|
||||
send(SCI_GOTOPOS, std::min(caret, send(SCI_GETLENGTH)));
|
||||
updateTitle();
|
||||
updatePreview();
|
||||
layout();
|
||||
focusContent();
|
||||
}
|
||||
|
||||
void TextWindow::updateTitle()
|
||||
{
|
||||
const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") +
|
||||
(remote ? remote->peer.name + L" · " : std::wstring{}) + original.wstring();
|
||||
SetWindowTextW(window,title.c_str());
|
||||
}
|
||||
|
||||
bool TextWindow::canPreview() const
|
||||
{
|
||||
return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit;
|
||||
}
|
||||
|
||||
void TextWindow::updatePreview()
|
||||
{
|
||||
if(!canPreview())
|
||||
{
|
||||
stopPreview(true,true);
|
||||
return;
|
||||
}
|
||||
previewWanted=true;
|
||||
previewDeadline=GetTickCount64()+8000;
|
||||
previewStamp=previewFileStamp();
|
||||
nextFileCheck=GetTickCount64()+350;
|
||||
cancelImages=std::make_shared<std::atomic<bool>>(false);
|
||||
if(!SetTimer(window,previewTimer,50,nullptr)) { stopPreview(); return; }
|
||||
if(preview.initialized()) renderPreview();
|
||||
else if(!preview.create(window,[this](const auto &value){previewMessage(value);},
|
||||
[this]{PostMessageW(window,previewFailed,0,0);},true,[this](UINT key)
|
||||
{
|
||||
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
|
||||
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
|
||||
if(ctrl && !alt && key==VK_TAB)
|
||||
{
|
||||
PostMessageW(window,cycleWindow,0,0);
|
||||
return true;
|
||||
}
|
||||
if(key==VK_BROWSER_BACK || key==VK_BROWSER_FORWARD || (alt && (key==VK_LEFT || key==VK_RIGHT)))
|
||||
{
|
||||
PostMessageW(window,WM_COMMAND,key==VK_LEFT || key==VK_BROWSER_BACK?historyBack:historyForward,0);
|
||||
return true;
|
||||
}
|
||||
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
|
||||
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:close,0);
|
||||
return true;
|
||||
}))
|
||||
stopPreview();
|
||||
layout();
|
||||
}
|
||||
|
||||
void TextWindow::stopPreview(bool refresh,bool keepBrowser)
|
||||
{
|
||||
KillTimer(window,previewTimer);
|
||||
previewWanted=previewVisible=false;
|
||||
previewStamp.reset();
|
||||
cancelPreviewImages();
|
||||
previewLinks.clear();
|
||||
if(keepBrowser && preview.initialized()) preview.post(L"{\"action\":\"clear\"}");
|
||||
else preview.close();
|
||||
if(refresh)
|
||||
{
|
||||
layout();
|
||||
if(GetForegroundWindow()==window) focusContent();
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::cancelPreviewImages()
|
||||
{
|
||||
if(cancelImages) *cancelImages=true;
|
||||
imageQueue.clear();
|
||||
image={};
|
||||
}
|
||||
|
||||
void TextWindow::focusContent()
|
||||
{
|
||||
if(previewVisible) preview.focus();
|
||||
else if(!previewWanted) SetFocus(editor);
|
||||
}
|
||||
|
||||
void TextWindow::goToFragment(std::string_view fragment)
|
||||
{
|
||||
if(fragment.empty()) return;
|
||||
if(previewVisible)
|
||||
preview.post(wide(nlohmann::json{{"action","anchor"},{"fragment",fragment}}.dump()));
|
||||
else previewFragment=fragment;
|
||||
}
|
||||
|
||||
std::optional<TextWindow::FileStamp> TextWindow::previewFileStamp() const
|
||||
{
|
||||
if(remote) return {};
|
||||
const auto file=CreateFileW(original.c_str(),FILE_READ_ATTRIBUTES,
|
||||
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(file==INVALID_HANDLE_VALUE) return {};
|
||||
BY_HANDLE_FILE_INFORMATION state{};
|
||||
const auto found=GetFileInformationByHandle(file,&state);
|
||||
CloseHandle(file);
|
||||
if(!found) return {};
|
||||
const auto combine=[](DWORD high,DWORD low){return (uint64_t{high}<<32)|low;};
|
||||
return FileStamp{combine(state.ftLastWriteTime.dwHighDateTime,state.ftLastWriteTime.dwLowDateTime),
|
||||
combine(state.nFileIndexHigh,state.nFileIndexLow),
|
||||
combine(state.nFileSizeHigh,state.nFileSizeLow),state.dwVolumeSerialNumber};
|
||||
}
|
||||
|
||||
void TextWindow::renderPreview(bool keepPosition)
|
||||
{
|
||||
previewDeadline=GetTickCount64()+30000;
|
||||
std::string text;
|
||||
for(uint64_t index=0;index<document->pages();++index)
|
||||
text+=document->readPage(index);
|
||||
if(!remote) document->releaseReadHandle();
|
||||
nlohmann::json message{{"action","render"},{"text",std::move(text)},
|
||||
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
|
||||
{"keepPosition",keepPosition}};
|
||||
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
|
||||
restoreScroll=false;
|
||||
preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace)));
|
||||
}
|
||||
|
||||
void TextWindow::refreshPreview()
|
||||
{
|
||||
if(remote || !previewVisible || navigation.valid() || GetTickCount64()<nextFileCheck) return;
|
||||
nextFileCheck=GetTickCount64()+350;
|
||||
const auto stamp=previewFileStamp();
|
||||
if(!stamp || stamp==previewStamp) return;
|
||||
try
|
||||
{
|
||||
auto reopened=std::make_unique<TextDocument>(original,false);
|
||||
if(!reopened->pages()) return;
|
||||
document=std::move(reopened);
|
||||
previewStamp=stamp;
|
||||
loadPage(std::min(page,document->pages()-1));
|
||||
if(!canPreview()) { stopPreview(); return; }
|
||||
cancelPreviewImages();
|
||||
cancelImages=std::make_shared<std::atomic<bool>>(false);
|
||||
previewVisible=false;
|
||||
renderPreview(true);
|
||||
}
|
||||
catch(const std::runtime_error &)
|
||||
{
|
||||
// The file may be locked or incomplete while another application saves it.
|
||||
previewStamp.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::previewMessage(const std::wstring &value)
|
||||
{
|
||||
if(!previewWanted) return;
|
||||
try
|
||||
{
|
||||
if(value==L"ready")
|
||||
{
|
||||
renderPreview();
|
||||
return;
|
||||
}
|
||||
const auto message=nlohmann::json::parse(utf8(value));
|
||||
const auto action=message.at("action").get<std::string>();
|
||||
if(action=="cycle")
|
||||
{
|
||||
PostMessageW(window,cycleWindow,0,0);
|
||||
return;
|
||||
}
|
||||
if(action=="failed")
|
||||
{
|
||||
PostMessageW(window,previewFailed,0,0);
|
||||
return;
|
||||
}
|
||||
if(action=="rendered")
|
||||
{
|
||||
PostMessageW(window,previewRendered,0,0);
|
||||
return;
|
||||
}
|
||||
// Defer transitions until WebView2 returns from its event callback.
|
||||
if(action=="edit" || action=="close")
|
||||
{
|
||||
PostMessageW(window,WM_COMMAND,action=="edit"?switchMode:close,0);
|
||||
return;
|
||||
}
|
||||
if(action=="back" || action=="forward")
|
||||
{
|
||||
previewLinks.push_back({{},action=="back"?-1:1,message.value("scroll",0),false});
|
||||
PostMessageW(window,openPreviewLink,0,0);
|
||||
return;
|
||||
}
|
||||
if(action!="image" && action!="link") return;
|
||||
const auto url=message.at("path").get<std::string>();
|
||||
if(action=="link" && (url.starts_with("https://") || url.starts_with("http://")))
|
||||
{
|
||||
ShellExecuteW(window,L"open",wide(url).c_str(),nullptr,nullptr,SW_SHOWNORMAL);
|
||||
return;
|
||||
}
|
||||
const auto target=action=="link" && url.starts_with('#') ? original : markdownTarget(original,url);
|
||||
if(action=="link")
|
||||
{
|
||||
if(!target.empty())
|
||||
{
|
||||
const auto hash=url.find('#');
|
||||
previewLinks.push_back({{target,hash==url.npos?std::string{}:url.substr(hash+1)},
|
||||
0,message.value("scroll",0),message.value("newWindow",false)});
|
||||
PostMessageW(window,openPreviewLink,0,0);
|
||||
}
|
||||
}
|
||||
else if(imageQueue.size()<256)
|
||||
{
|
||||
imageQueue.push_back({target,message.at("index").get<uint64_t>(),message.at("generation").get<uint64_t>()});
|
||||
}
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(!previewVisible) PostMessageW(window,previewFailed,0,0);
|
||||
else log(L"Markdown preview message: "+wide(error.what()));
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::syncNavigation()
|
||||
{
|
||||
preview.post(wide(nlohmann::json{{"action","history"},{"back",navigationIndex>0},
|
||||
{"forward",navigationIndex+1<navigationHistory.size()}}.dump()));
|
||||
}
|
||||
|
||||
void TextWindow::navigatePreview(PreviewLink request)
|
||||
{
|
||||
if(edit || navigation.valid() || navigationHistory.empty()) return;
|
||||
if(request.newWindow)
|
||||
{
|
||||
openTextWindow(window,request.target.path,false,search.style,remote?&remote->peer:nullptr,
|
||||
request.target.fragment,true);
|
||||
return;
|
||||
}
|
||||
if((request.direction<0 && navigationIndex==0) ||
|
||||
(request.direction>0 && navigationIndex+1==navigationHistory.size())) return;
|
||||
navigationHistory[navigationIndex].scroll=request.scroll;
|
||||
destinationIndex.reset();
|
||||
if(request.direction)
|
||||
{
|
||||
destinationIndex=request.direction<0 ? navigationIndex-1 : navigationIndex+1;
|
||||
destination=navigationHistory[*destinationIndex];
|
||||
}
|
||||
else destination=std::move(request.target);
|
||||
if(destination.path==original || !remote) { showLocation(nullptr); return; }
|
||||
auto cancel=std::make_shared<std::atomic<bool>>(false);
|
||||
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task(
|
||||
[peer=remote->peer,path=destination.path,cancel] {
|
||||
auto file=std::make_unique<RemoteTextFile>(RemoteTextFile{peer,path});
|
||||
file->download(false,[cancel](uint64_t,uint64_t){return !*cancel;});
|
||||
return file;
|
||||
});
|
||||
if(!SetTimer(window,navigationTimer,75,nullptr))
|
||||
throw std::runtime_error("Cannot start the LAN navigation timer.");
|
||||
try
|
||||
{
|
||||
auto result=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
navigation=std::move(result);
|
||||
cancelNavigation=std::move(cancel);
|
||||
}
|
||||
catch(...) { KillTimer(window,navigationTimer); throw; }
|
||||
}
|
||||
|
||||
void TextWindow::finishNavigation()
|
||||
{
|
||||
if(!navigation.valid() || navigation.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
KillTimer(window,navigationTimer);
|
||||
showLocation(navigation.get());
|
||||
}
|
||||
|
||||
void TextWindow::showLocation(std::unique_ptr<RemoteTextFile> fetched)
|
||||
{
|
||||
const bool sameDocument=destination.path==original;
|
||||
std::unique_ptr<TextDocument> next;
|
||||
if(!sameDocument) next=std::make_unique<TextDocument>(fetched?fetched->cache:destination.path,false);
|
||||
|
||||
if(destinationIndex) navigationIndex=*destinationIndex;
|
||||
else if(!sameDocument || navigationHistory[navigationIndex].fragment!=destination.fragment)
|
||||
{
|
||||
navigationHistory.resize(navigationIndex+1);
|
||||
navigationHistory.push_back(destination);
|
||||
++navigationIndex;
|
||||
}
|
||||
if(sameDocument)
|
||||
{
|
||||
nlohmann::json message{{"action","anchor"},{"fragment",destination.fragment}};
|
||||
if(destinationIndex) message["scroll"]=destination.scroll;
|
||||
preview.post(wide(message.dump()));
|
||||
syncNavigation();
|
||||
return;
|
||||
}
|
||||
|
||||
stopPreview(false,true);
|
||||
document=std::move(next);
|
||||
if(fetched) remote=std::move(fetched);
|
||||
original=destination.path;
|
||||
filename=original.filename().wstring();
|
||||
previewFragment=destination.fragment;
|
||||
restoreScroll=destinationIndex.has_value();
|
||||
initializeDocument();
|
||||
updateTitle();
|
||||
layout();
|
||||
focusContent();
|
||||
}
|
||||
|
||||
void TextWindow::pollImages()
|
||||
{
|
||||
refreshPreview();
|
||||
if(!previewVisible && GetTickCount64()>=previewDeadline)
|
||||
{
|
||||
stopPreview();
|
||||
return;
|
||||
}
|
||||
if(image.valid())
|
||||
{
|
||||
if(image.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
std::string source;
|
||||
try { source=image.get(); } catch(const std::exception &) {}
|
||||
const nlohmann::json message{{"action","image"},{"index",activeImage.index},
|
||||
{"generation",activeImage.generation},{"source",std::move(source)}};
|
||||
preview.post(wide(message.dump()));
|
||||
}
|
||||
if(imageQueue.empty()) return;
|
||||
activeImage=std::move(imageQueue.front());
|
||||
imageQueue.pop_front();
|
||||
std::packaged_task<std::string()> task(
|
||||
[path=activeImage.path,peer=remote?std::optional(remote->peer):std::nullopt,cancel=cancelImages] {
|
||||
return markdownImage(path,peer?&*peer:nullptr,cancel);
|
||||
});
|
||||
image=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
}
|
||||
|
||||
void TextWindow::layout()
|
||||
{
|
||||
if (!editor) return;
|
||||
@@ -1230,6 +1777,8 @@ void TextWindow::layout()
|
||||
GetClientRect(window, &area);
|
||||
const auto row = chromeHeight();
|
||||
MoveWindow(editor, 0, 2 * row, area.right, std::max(0L, area.bottom - 3 * row), TRUE);
|
||||
preview.layout({0,2*row,area.right,std::max<LONG>(2*row,area.bottom-row)},previewWanted);
|
||||
ShowWindow(editor,document && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
invalidate();
|
||||
}
|
||||
|
||||
@@ -1288,8 +1837,10 @@ void TextWindow::paint()
|
||||
L" @ " + std::to_wstring(pageOffset);
|
||||
status += L" │ " + std::to_wstring(fileSize) + L" B";
|
||||
const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" :
|
||||
edit ? L"F2 Save F3 Find next F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close" :
|
||||
L"F3 Find next F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close";
|
||||
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
|
||||
previewVisible ? L"F6 Edit Ctrl+W Close" :
|
||||
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
|
||||
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
|
||||
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
|
||||
top.left += scale(12);
|
||||
top.right -= scale(12);
|
||||
@@ -1348,6 +1899,13 @@ void TextWindow::command(UINT id)
|
||||
{
|
||||
case save: saveFile(false); return;
|
||||
case close: requestClose(); return;
|
||||
case switchMode: toggleMode(); return;
|
||||
case historyBack:
|
||||
case historyForward:
|
||||
if(previewVisible)
|
||||
preview.post(wide(nlohmann::json{{"action",id==historyBack?"back":"forward"}}.dump()));
|
||||
else navigatePreview({{},id==historyBack?-1:1,0,false});
|
||||
return;
|
||||
case previousPage: if (page) go(page - 1); return;
|
||||
case nextPage: go(page + 1); return;
|
||||
case firstPage: go(0); return;
|
||||
@@ -1441,6 +1999,11 @@ bool TextWindow::handleKey(const MSG &message)
|
||||
if (message.hwnd != editor) return false;
|
||||
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
|
||||
{
|
||||
if (!edit && (key==VK_LEFT || key==VK_RIGHT))
|
||||
{
|
||||
SendMessageW(window,WM_COMMAND,key==VK_LEFT?historyBack:historyForward,0);
|
||||
return true;
|
||||
}
|
||||
for (size_t index = 0; index < menuBarLabels.size(); ++index)
|
||||
if (menuBarLabels[index].matches(static_cast<wchar_t>(key)))
|
||||
{
|
||||
@@ -1457,8 +2020,11 @@ bool TextWindow::handleKey(const MSG &message)
|
||||
if (key == VK_F2 || (ctrl && key == 'S')) id = save;
|
||||
if (key == VK_F3) id = findNext;
|
||||
if (key == VK_F5 || (ctrl && key == 'G')) id = goToPage;
|
||||
if (key == VK_F6) id = switchMode;
|
||||
if (key == VK_F9) id = 600;
|
||||
if (key == VK_ESCAPE || key == VK_F10) id = close;
|
||||
if (key == VK_ESCAPE || key == VK_F10 || (!edit && ctrl && key=='W')) id = close;
|
||||
if (!edit && key==VK_BROWSER_BACK) id=historyBack;
|
||||
if (!edit && key==VK_BROWSER_FORWARD) id=historyForward;
|
||||
if (ctrl && key == 'F') id = findText;
|
||||
if (ctrl && key == VK_PRIOR) id = previousPage;
|
||||
if (ctrl && key == VK_NEXT) id = nextPage;
|
||||
@@ -1477,6 +2043,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
const auto &state=*static_cast<const std::shared_ptr<TextWindow> *>(create->lpCreateParams);
|
||||
state->window=window;
|
||||
textWindows.emplace(window,state);
|
||||
textWindowOrder.push_back(window);
|
||||
}
|
||||
const auto found=textWindows.find(window);
|
||||
if(found==textWindows.end()) return DefWindowProcW(window,message,wparam,lparam);
|
||||
@@ -1517,6 +2084,12 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
MSG key{child,msg,wp,lp};
|
||||
if(state->handleKey(key)) return 0;
|
||||
}
|
||||
if(msg==WM_XBUTTONUP && !state->edit)
|
||||
{
|
||||
SendMessageW(state->window,WM_COMMAND,
|
||||
GET_XBUTTON_WPARAM(wp)==XBUTTON1?historyBack:historyForward,0);
|
||||
return TRUE;
|
||||
}
|
||||
return DefSubclassProc(child,msg,wp,lp);
|
||||
},1,reinterpret_cast<DWORD_PTR>(self.get()));
|
||||
if(self->remote)
|
||||
@@ -1532,7 +2105,6 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
}
|
||||
else self->initializeDocument();
|
||||
self->layout();
|
||||
ShowWindow(self->editor,SW_SHOWNA);
|
||||
return 0;
|
||||
case WM_ERASEBKGND: return 1;
|
||||
case WM_PAINT: self->paint(); return 0;
|
||||
@@ -1546,7 +2118,35 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
self->layout();
|
||||
return 0;
|
||||
}
|
||||
case WM_SETFOCUS: SetFocus(self->editor); return 0;
|
||||
case WM_SETFOCUS: self->focusContent(); return 0;
|
||||
case cycleWindow: cycleTextWindows(window); return 0;
|
||||
case WM_KEYDOWN:
|
||||
if(self->previewWanted && !self->previewVisible)
|
||||
{
|
||||
if(wparam==VK_F6) self->toggleMode();
|
||||
if(wparam==VK_ESCAPE || wparam==VK_F10 ||
|
||||
(wparam=='W' && (GetKeyState(VK_CONTROL)&0x8000))) self->requestClose();
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case previewFailed: self->stopPreview(); return 0;
|
||||
case previewRendered:
|
||||
if(self->previewWanted)
|
||||
{
|
||||
self->previewVisible=true;
|
||||
self->syncNavigation();
|
||||
self->layout();
|
||||
if(GetForegroundWindow()==window) self->focusContent();
|
||||
}
|
||||
return 0;
|
||||
case openPreviewLink:
|
||||
if(!self->previewLinks.empty())
|
||||
{
|
||||
const auto target=std::move(self->previewLinks.front());
|
||||
self->previewLinks.pop_front();
|
||||
self->navigatePreview(std::move(target));
|
||||
}
|
||||
return 0;
|
||||
case WM_INITMENU: self->updateMenus(); return 0;
|
||||
case WM_MENUCHAR: return self->menuKey(reinterpret_cast<HMENU>(lparam), LOWORD(wparam));
|
||||
case WM_MEASUREITEM:
|
||||
@@ -1576,6 +2176,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
case WM_TIMER:
|
||||
if (wparam == saveTimer) self->finishSave();
|
||||
if (wparam == openTimer) self->finishOpen();
|
||||
if (wparam == previewTimer) self->pollImages();
|
||||
if (wparam == navigationTimer) self->finishNavigation();
|
||||
return 0;
|
||||
case trimUndo:
|
||||
if (self->undoBytes >= 32 * TextDocument::pageBytes)
|
||||
@@ -1587,11 +2189,14 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
}
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
if(self->cancelNavigation) *self->cancelNavigation=true;
|
||||
self->stopPreview(false);
|
||||
self->releaseMenu();
|
||||
return 0;
|
||||
case WM_NCDESTROY:
|
||||
self->window=nullptr;
|
||||
textWindows.erase(window);
|
||||
std::erase(textWindowOrder,window);
|
||||
if(textOwnerClosed && textWindows.empty()) PostQuitMessage(0);
|
||||
break;
|
||||
}
|
||||
@@ -1707,10 +2312,29 @@ void showFarHistory(HWND dialog,int fieldId,const std::vector<FarHistoryEntry> &
|
||||
|
||||
void textWindowOwnerClosed()
|
||||
{
|
||||
filesOwner=nullptr;
|
||||
textOwnerClosed=true;
|
||||
if(textWindows.empty()) PostQuitMessage(0);
|
||||
}
|
||||
|
||||
bool cycleTextWindows(HWND current)
|
||||
{
|
||||
if(!current || (current!=filesOwner && !textWindows.contains(current))) return false;
|
||||
std::vector<HWND> windows;
|
||||
if(filesOwner && IsWindowVisible(filesOwner)) windows.push_back(filesOwner);
|
||||
for(const auto window:textWindowOrder)
|
||||
if(IsWindowVisible(window)) windows.push_back(window);
|
||||
if(windows.size()<2) return false;
|
||||
const auto from=std::find(windows.begin(),windows.end(),current);
|
||||
if(from==windows.end()) return false;
|
||||
auto to=std::next(from);
|
||||
if(to==windows.end()) to=windows.begin();
|
||||
if(IsIconic(*to)) ShowWindow(*to,SW_RESTORE);
|
||||
SetForegroundWindow(*to);
|
||||
if(*to!=filesOwner) SendMessageW(*to,WM_SETFOCUS,0,0);
|
||||
return true;
|
||||
}
|
||||
|
||||
HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *peer)
|
||||
{
|
||||
const auto identity=documentIdentity(path,peer?peer->id:"");
|
||||
@@ -1738,19 +2362,22 @@ HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *pe
|
||||
}
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer)
|
||||
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(!textWindows.contains(owner)) filesOwner=owner;
|
||||
std::error_code error;
|
||||
const auto identity=peer?path.lexically_normal():std::filesystem::weakly_canonical(path,error);
|
||||
const auto &original=error?path:identity;
|
||||
if(const auto existing=findOpenDocument(original,peer))
|
||||
if(const auto existing=newWindow?nullptr:findOpenDocument(original,peer))
|
||||
{
|
||||
if(dialogs.confirmExisting(owner) && IsWindow(existing))
|
||||
{
|
||||
if(IsIconic(existing)) ShowWindowAsync(existing,SW_RESTORE);
|
||||
SetForegroundWindow(existing);
|
||||
if(const auto open=textWindows.find(existing); open!=textWindows.end())
|
||||
open->second->goToFragment(fragment);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1767,7 +2394,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
|
||||
}();
|
||||
if(!registered) throw std::runtime_error("Cannot register the text window.");
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer);
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment);
|
||||
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
|
||||
(peer?peer->name+L" · ":std::wstring{})+path.wstring();
|
||||
RECT bounds{};
|
||||
@@ -1790,7 +2417,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
properties->Release();
|
||||
}
|
||||
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
SetFocus(state->editor);
|
||||
SendMessageW(window,WM_SETFOCUS,0,0);
|
||||
}
|
||||
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+7
-3
@@ -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){
|
||||
|
||||
+27
-13
@@ -1031,30 +1031,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 +1102,7 @@ struct FilesListener::Impl
|
||||
void poll()
|
||||
{
|
||||
std::erase_if(clients,[](const auto &client){return client->done.load();});
|
||||
if(listener.value==INVALID_SOCKET && GetTickCount64()>=nextBind) bindListener();
|
||||
if(listener.value==INVALID_SOCKET || clients.size()>=16) return;
|
||||
sockaddr_in address{};
|
||||
int size=sizeof(address);
|
||||
|
||||
+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.89";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.96";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
@@ -270,6 +270,79 @@ try {
|
||||
}
|
||||
if ([FilesActivationUi]::Focus($window) -ne $inputBox) { throw 'Deletion moved focus.' }
|
||||
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
|
||||
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$savedClipboard=[Windows.Forms.Clipboard]::GetDataObject()
|
||||
$programName=[IO.Path]::GetFileName($program)
|
||||
$expectedNames="Test folder`r`n$programName"
|
||||
try {
|
||||
Select-Row $left '[Test folder]'
|
||||
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
Select-Row $left $programName
|
||||
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
Wait-Until 'Files activation for Ctrl+Insert' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $expectedNames
|
||||
}
|
||||
Select-Row $right $fileName
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $fileName
|
||||
}
|
||||
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
|
||||
} finally {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
}
|
||||
}
|
||||
|
||||
$sizeA=Join-Path $rightDir 'Size A'
|
||||
$sizeB=Join-Path $rightDir 'Size B'
|
||||
$sizeC=Join-Path $rightDir 'Size C'
|
||||
New-Item -ItemType Directory -Path "$sizeA\nested", $sizeB, $sizeC | Out-Null
|
||||
[IO.File]::WriteAllBytes("$sizeA\file.bin",[byte[]]::new(4))
|
||||
[IO.File]::WriteAllBytes("$sizeA\nested\file.bin",[byte[]]::new(7))
|
||||
[IO.File]::WriteAllBytes("$sizeB\file.bin",[byte[]]::new(23))
|
||||
[IO.File]::WriteAllBytes("$sizeC\file.bin",[byte[]]::new(31))
|
||||
Select-Row $right '[Size A]'
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
Wait-Until 'F3 recursive size for the current folder' { (Read-Text $status) -ceq 'Size A 11 B' }
|
||||
foreach($name in 'Size A','Size B'){
|
||||
Select-Row $right "[$name]"
|
||||
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
}
|
||||
Select-Row $right '[Size C]'
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
Wait-Until 'completion of the marked size batch' { (Read-Text $status) -ceq 'Size C Folder' }
|
||||
Select-Row $right '[Size B]'
|
||||
Wait-Until 'F3 size for a marked folder' { (Read-Text $status) -ceq 'Size B 23 B' }
|
||||
Select-Row $right '[Size C]'
|
||||
if ((Read-Text $status) -cne 'Size C Folder') { throw 'F3 measured the unmarked cursor folder.' }
|
||||
Select-Row $right $fileName
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
$viewerTitle='Viewer '+[char]0x2014+" $document"
|
||||
Wait-Until 'F3 opening a file when folders are marked' {
|
||||
[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle) -ne [IntPtr]::Zero
|
||||
}
|
||||
$viewer=[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle)
|
||||
[void][FilesActivationUi]::PostMessage($viewer,0x10,[IntPtr]::Zero,[IntPtr]::Zero)
|
||||
Write-Output 'F3 measured the current folder recursively and measured marked folders without measuring the unmarked cursor folder.'
|
||||
|
||||
Select-Row $right '[Size B]'
|
||||
Wait-Until 'Files activation for Ctrl+R' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$shell.SendKeys('^r')
|
||||
Wait-Until 'Ctrl+R clearing the measured size and retaining the current folder' {
|
||||
(Read-Text $status) -ceq 'Size B Folder' -and
|
||||
[FilesActivationUi]::Send($right,0x188,[IntPtr]::Zero,[IntPtr]::Zero).ToInt32() -eq
|
||||
(Find-Row $right '[Size B]')
|
||||
}
|
||||
Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Executable,
|
||||
[string]$Screenshot,
|
||||
[string]$Node = 'node',
|
||||
[string]$LanFixture
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type @"
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class MarkdownUi {
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
public static void Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return;
|
||||
keybd_event(0x12,0,0,UIntPtr.Zero);
|
||||
keybd_event(0x12,0,2,UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
}
|
||||
public static void CycleWindow() {
|
||||
keybd_event(0x11,0,0,UIntPtr.Zero);
|
||||
keybd_event(0x09,0,0,UIntPtr.Zero);
|
||||
keybd_event(0x09,0,2,UIntPtr.Zero);
|
||||
keybd_event(0x11,0,2,UIntPtr.Zero);
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr window, StringBuilder title, int capacity);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SendText(IntPtr window, uint msg, IntPtr w, string l);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
}
|
||||
"@
|
||||
|
||||
function Wait-For([string]$Name, [scriptblock]$Check) {
|
||||
for ($i=0; $i -lt 150; $i++) {
|
||||
$value = & $Check
|
||||
if ($value) { return $value }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
throw "Timed out waiting for $Name"
|
||||
}
|
||||
|
||||
function Find-Window([string]$Class, [string]$Title = '', [IntPtr]$Except = 0) {
|
||||
$window = [IntPtr]::Zero
|
||||
while (($window = [MarkdownUi]::FindWindowEx(0,$window,$Class,[NullString]::Value)) -ne [IntPtr]::Zero) {
|
||||
[uint32]$pidFound = 0
|
||||
[void][MarkdownUi]::GetWindowThreadProcessId($window,[ref]$pidFound)
|
||||
if ($pidFound -ne $process.Id -or $window -eq $Except -or ![MarkdownUi]::IsWindowVisible($window)) { continue }
|
||||
$buffer = [Text.StringBuilder]::new(2048)
|
||||
[void][MarkdownUi]::GetWindowText($window,$buffer,$buffer.Capacity)
|
||||
if ($buffer.ToString() -like "*$Title*") { return $window }
|
||||
}
|
||||
}
|
||||
|
||||
function Post($Window, $Message, $Key) {
|
||||
if (![MarkdownUi]::PostMessage($Window,$Message,$Key,0)) { throw 'Could not drive the Files window.' }
|
||||
}
|
||||
|
||||
function Open-File($File, $Key) {
|
||||
$row = [MarkdownUi]::SendText($panel,0x1A2,-1,$File)
|
||||
if ($row.ToInt64() -lt 0) { throw "Missing row $File" }
|
||||
[void][MarkdownUi]::Send($panel,0x186,$row,0)
|
||||
Post $panel 0x100 $Key
|
||||
}
|
||||
|
||||
function Browser($Scenario, $Image = '', $Title = '') {
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port $Scenario $Image $Title
|
||||
if ($LASTEXITCODE) { throw "WebView2 verification failed for $Scenario" }
|
||||
}
|
||||
|
||||
function Wait-Foreground($Window) {
|
||||
$buffer = [Text.StringBuilder]::new(2048)
|
||||
[void][MarkdownUi]::GetWindowText($Window,$buffer,$buffer.Capacity)
|
||||
[void](Wait-For "foreground window $buffer" { [MarkdownUi]::GetForegroundWindow() -eq $Window })
|
||||
}
|
||||
|
||||
function Scintilla($Window) {
|
||||
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
|
||||
}
|
||||
|
||||
function Append-Character($Control, [char]$Character) {
|
||||
[void][MarkdownUi]::Send($Control,2318,0,0)
|
||||
[void][MarkdownUi]::Send($Control,0x102,[int]$Character,0)
|
||||
}
|
||||
|
||||
function Answer-Save($Button) {
|
||||
$dialog = Wait-For 'the save confirmation' {
|
||||
$candidate = Find-Window '#32770'
|
||||
if ($candidate -and [MarkdownUi]::GetDlgItem($candidate,7) -ne [IntPtr]::Zero) { $candidate }
|
||||
}
|
||||
Post $dialog 0x111 $Button
|
||||
[void](Wait-For 'the save confirmation to close' { ![MarkdownUi]::IsWindowVisible($dialog) })
|
||||
}
|
||||
|
||||
$source = Split-Path (Resolve-Path -LiteralPath $Executable)
|
||||
$root = Join-Path ([IO.Path]::GetTempPath()) ('ks-markdown-test-' + [Guid]::NewGuid().ToString('N'))
|
||||
$app = Join-Path $root 'app'
|
||||
$docs = Join-Path $root 'docs'
|
||||
$profileCaptured = $false
|
||||
$profile = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$saved = @{}
|
||||
$profileValues = 'LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
|
||||
$process = $null
|
||||
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
$data = $env:WEBVIEW2_USER_DATA_FOLDER
|
||||
try {
|
||||
New-Item -ItemType Directory -Path $app,$docs,"$docs\child","$docs\images" | Out-Null
|
||||
Copy-Item -LiteralPath $Executable,"$source\WebView2Loader.dll","$source\terminal" -Destination $app -Recurse
|
||||
$fixture = @'
|
||||
# Перегляд Markdown
|
||||
|
||||
| Header |
|
||||
| ------ |
|
||||
| Cell |
|
||||
|
||||
- [ ] Pending
|
||||
- [x] Complete
|
||||
|
||||

|
||||

|
||||
[Child](child/Other.md#target-heading)
|
||||
|
||||
~~~mermaid
|
||||
flowchart TD
|
||||
A[Render target] --> B[Result]
|
||||
~~~
|
||||
|
||||
~~~mermaid
|
||||
this is not a diagram
|
||||
~~~
|
||||
|
||||
~~~js
|
||||
const value = 42;
|
||||
~~~
|
||||
|
||||
<iframe src="https://example.invalid">Raw HTML</iframe>
|
||||
'@
|
||||
$original = Join-Path $docs 'Preview.md'
|
||||
[IO.File]::WriteAllText($original,$fixture)
|
||||
$childText = '# Linked Markdown' + "`n`n" + (("Filler paragraph.`n`n") * 60) + '## Target heading'
|
||||
[IO.File]::WriteAllText("$docs\child\Other.md",$childText)
|
||||
[IO.File]::WriteAllText("$docs\Plain.txt",'Plain text')
|
||||
$largeFile = [IO.File]::Create("$docs\Large.md")
|
||||
try {
|
||||
$line = [Text.Encoding]::UTF8.GetBytes(("# Large Markdown file`n" * 1024))
|
||||
while ($largeFile.Length -le 8MB) { $largeFile.Write($line,0,$line.Length) }
|
||||
} finally { $largeFile.Dispose() }
|
||||
[IO.File]::WriteAllBytes("$docs\images\tiny image.png",[Convert]::FromBase64String(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jBo0AAAAASUVORK5CYII='))
|
||||
foreach ($name in $profileValues) {
|
||||
if ($name -in $profile.GetValueNames()) {
|
||||
$saved[$name] = @($profile.GetValue($name),$profile.GetValueKind($name))
|
||||
}
|
||||
}
|
||||
$profileCaptured = $true
|
||||
$profile.SetValue('LeftPath',$docs)
|
||||
$profile.SetValue('RightPath',$docs)
|
||||
foreach ($name in 'LeftCursor','RightCursor','WindowPlacement') { $profile.DeleteValue($name,$false) }
|
||||
|
||||
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$listener.Start()
|
||||
$port = $listener.LocalEndpoint.Port
|
||||
$listener.Stop()
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = "--remote-debugging-port=$port --disable-background-networking"
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'webview'
|
||||
$process = Start-Process -FilePath (Join-Path $app (Split-Path -Leaf $Executable)) -PassThru -WindowStyle Normal
|
||||
$main = Wait-For 'Files' { Find-Window 'KSwitcher.Files' }
|
||||
[MarkdownUi]::Activate($main)
|
||||
$panel = [MarkdownUi]::GetDlgItem($main,102)
|
||||
|
||||
Open-File 'Preview.md' 0x72
|
||||
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
|
||||
if ([MarkdownUi]::IsWindowVisible((Scintilla $window))) {
|
||||
throw 'F3 showed the source text while starting the Markdown preview.'
|
||||
}
|
||||
Browser 'render' $Screenshot
|
||||
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Checking a task modified the read-only file.' }
|
||||
[IO.File]::WriteAllText($original,($fixture.Replace('Перегляд Markdown','Зміна на диску')))
|
||||
Browser 'Зміна на диску' '' 'Preview.md'
|
||||
$replacement = Join-Path $docs 'Preview-replacement.md'
|
||||
[IO.File]::WriteAllText($replacement,$fixture)
|
||||
[IO.File]::Move($replacement,$original,$true)
|
||||
Browser 'Перегляд Markdown' '' 'Preview.md'
|
||||
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window) { throw 'Reload changed windows.' }
|
||||
Browser 'edit'
|
||||
$editor = Wait-For 'F6 in WebView2 to open the editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
|
||||
if ($editor -ne $window) { throw 'F6 changed windows.' }
|
||||
[MarkdownUi]::Activate($window)
|
||||
Wait-Foreground $window
|
||||
[MarkdownUi]::CycleWindow()
|
||||
Wait-Foreground $main
|
||||
[MarkdownUi]::CycleWindow()
|
||||
Wait-Foreground $window
|
||||
$control = Scintilla $window
|
||||
if ([MarkdownUi]::Send($control,2140,0,0).ToInt64()) { throw 'The editor is read-only.' }
|
||||
Append-Character $control 'X'
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 2
|
||||
if ((Find-Window 'KSwitcher.Files.Text' 'Editor') -ne $window -or ![MarkdownUi]::Send($control,2159,0,0).ToInt64()) {
|
||||
throw 'Cancel lost unsaved changes.'
|
||||
}
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 7
|
||||
Browser 'Перегляд Markdown'
|
||||
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Discard changed the Markdown file.' }
|
||||
Browser 'ctrl-follow'
|
||||
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window -or (Find-Window 'KSwitcher.Files.Text' 'Other.md')) {
|
||||
throw 'Ctrl+click navigated without tabs.'
|
||||
}
|
||||
Browser 'shift-follow'
|
||||
$child = Wait-For 'the Shift+click Markdown window' { Find-Window 'KSwitcher.Files.Text' 'Other.md' $window }
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
[MarkdownUi]::Activate($child)
|
||||
Browser 'cycle' '' 'Other.md'
|
||||
Wait-Foreground $main
|
||||
[MarkdownUi]::CycleWindow()
|
||||
Wait-Foreground $window
|
||||
Browser 'cycle' '' 'Preview.md'
|
||||
Wait-Foreground $child
|
||||
Browser 'close' '' 'Other.md'
|
||||
[void](Wait-For 'Ctrl+W to close the Shift+click window' { ![MarkdownUi]::IsWindowVisible($child) })
|
||||
Browser 'follow'
|
||||
if ((Wait-For 'the in-place Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
|
||||
throw 'A normal click did not stay in the same window.'
|
||||
}
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'mouse-back' '' 'Other.md'
|
||||
Browser 'Перегляд Markdown' '' 'Preview.md'
|
||||
Browser 'mouse-forward' '' 'Preview.md'
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'back' '' 'Other.md'
|
||||
Browser 'Перегляд Markdown' '' 'Preview.md'
|
||||
Browser 'forward' '' 'Preview.md'
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'close' '' 'Other.md'
|
||||
[void](Wait-For 'the Markdown viewers to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
|
||||
Open-File 'Preview.md' 0x73
|
||||
$window = Wait-For 'F4 to open the Markdown editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
|
||||
$control = Scintilla $window
|
||||
Append-Character $control 'Y'
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 6
|
||||
Browser 'Перегляд Markdown'
|
||||
if (![IO.File]::ReadAllText($original).EndsWith('Y')) { throw 'F6 rendered before saving.' }
|
||||
Post $window 0x10 0
|
||||
[void](Wait-For 'the saved Markdown viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
|
||||
Open-File 'Preview.md' 0x73
|
||||
$window = Wait-For 'the editor before a save conflict' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
|
||||
$control = Scintilla $window
|
||||
Append-Character $control 'Z'
|
||||
[IO.File]::Move($original,"$docs\replaced.md")
|
||||
[IO.File]::WriteAllText($original,'An external replacement')
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 6
|
||||
$errorDialog = Wait-For 'a save conflict error' {
|
||||
$candidate = Find-Window '#32770'
|
||||
if ($candidate -and [MarkdownUi]::GetDlgItem($candidate,1) -ne [IntPtr]::Zero) { $candidate }
|
||||
}
|
||||
Post $errorDialog 0x111 1
|
||||
if ((Find-Window 'KSwitcher.Files.Text' 'Editor') -ne $window -or
|
||||
[MarkdownUi]::Send($control,2140,0,0).ToInt64() -or
|
||||
[IO.File]::ReadAllText($original) -cne 'An external replacement') {
|
||||
throw 'The failed save left editing mode or overwrote an externally replaced file.'
|
||||
}
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 7
|
||||
Post $window 0x10 0
|
||||
[void](Wait-For 'the conflict fixture to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
|
||||
Open-File 'Plain.txt' 0x72
|
||||
$window = Wait-For 'plain-text viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
|
||||
$control = Scintilla $window
|
||||
[void](Wait-For 'plain-text read-only view' { [MarkdownUi]::Send($control,2140,0,0).ToInt64() })
|
||||
Post $control 0x100 0x75
|
||||
[void](Wait-For 'F6 plain-text editor' { !( [MarkdownUi]::Send($control,2140,0,0).ToInt64() ) })
|
||||
Post $control 0x100 0x75
|
||||
[void](Wait-For 'F6 plain-text viewer' { [MarkdownUi]::Send($control,2140,0,0).ToInt64() })
|
||||
Post $window 0x10 0
|
||||
[void](Wait-For 'plain-text viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
Open-File 'Large.md' 0x72
|
||||
$window = Wait-For 'large Markdown text fallback' { Find-Window 'KSwitcher.Files.Text' 'Large.md' }
|
||||
$control = Scintilla $window
|
||||
if (![MarkdownUi]::IsWindowVisible($control) -or ![MarkdownUi]::Send($control,2140,0,0).ToInt64()) {
|
||||
throw 'Large Markdown did not open in the text viewer.'
|
||||
}
|
||||
Post $window 0x10 0
|
||||
[void](Wait-For 'large-file viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
$previewPage = Join-Path $app 'terminal\markdown.html'
|
||||
[IO.File]::Move($previewPage,"$previewPage.disabled")
|
||||
try {
|
||||
Open-File 'Preview.md' 0x72
|
||||
$window = Wait-For 'text fallback without preview assets' { Find-Window 'KSwitcher.Files.Text' 'Preview.md' }
|
||||
$control = Scintilla $window
|
||||
if (![MarkdownUi]::IsWindowVisible($control) -or ![MarkdownUi]::Send($control,2140,0,0).ToInt64()) {
|
||||
throw 'Markdown did not open in the text viewer when preview assets were missing.'
|
||||
}
|
||||
} finally { [IO.File]::Move("$previewPage.disabled",$previewPage) }
|
||||
Write-Output 'Verified Markdown rendering, Mermaid, task checkboxes, local relative resources, F3/F4, F6 Save/Discard/Cancel/save failure and text fallback.'
|
||||
if ($LanFixture) {
|
||||
Post $window 0x10 0
|
||||
Post $main 0x10 0
|
||||
if (!$process.WaitForExit(5000)) { throw 'Files did not close before the LAN check.' }
|
||||
[IO.File]::WriteAllText($original,$fixture)
|
||||
$lanExe = Join-Path $app 'KSwitcherFilesMarkdownLanFixture.exe'
|
||||
Copy-Item -LiteralPath $LanFixture -Destination $lanExe
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'lan-webview'
|
||||
$process = Start-Process -FilePath $lanExe -ArgumentList ('"{0}"' -f $original) -PassThru -WindowStyle Normal
|
||||
$window = Wait-For 'the LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Loopback peer' }
|
||||
Browser 'render'
|
||||
Browser 'edit'
|
||||
if ((Wait-For 'LAN F6 editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }) -ne $window) {
|
||||
throw 'LAN F6 changed windows.'
|
||||
}
|
||||
$control = Scintilla $window
|
||||
Append-Character $control 'L'
|
||||
Post $control 0x100 0x75
|
||||
Browser 'Перегляд Markdown'
|
||||
if (![IO.File]::ReadAllText($original).EndsWith('L')) { throw 'F6 rendered before uploading the LAN edit.' }
|
||||
Browser 'follow'
|
||||
if ((Wait-For 'the in-place LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
|
||||
throw 'A LAN link did not stay in the same window.'
|
||||
}
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'back' '' 'Other.md'
|
||||
Browser 'Перегляд Markdown' '' 'Preview.md'
|
||||
Browser 'forward' '' 'Preview.md'
|
||||
Browser 'Linked Markdown' '' 'Other.md'
|
||||
Browser 'close' '' 'Other.md'
|
||||
if (!$process.WaitForExit(5000) -or $process.ExitCode) { throw 'The LAN fixture did not close normally.' }
|
||||
Write-Output 'Verified Markdown, Mermaid, relative links/images and F6 saving through an authenticated loopback LAN connection.'
|
||||
}
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
Stop-Process -Id $process.Id
|
||||
[void]$process.WaitForExit(5000)
|
||||
}
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = $data
|
||||
if ($profileCaptured) {
|
||||
foreach ($name in $profileValues) {
|
||||
if ($saved.ContainsKey($name)) { $profile.SetValue($name,$saved[$name][0],$saved[$name][1]) }
|
||||
else { $profile.DeleteValue($name,$false) }
|
||||
}
|
||||
}
|
||||
$profile.Dispose()
|
||||
if (Test-Path -LiteralPath $root) {
|
||||
$resolved = (Resolve-Path -LiteralPath $root).Path
|
||||
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
|
||||
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-markdown-test-*') {
|
||||
for ($attempt=0; $attempt -lt 40 -and (Test-Path -LiteralPath $resolved); ++$attempt) {
|
||||
try { Remove-Item -LiteralPath $resolved -Recurse -Force }
|
||||
catch {
|
||||
if ($attempt -eq 39) { throw }
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
const [port, scenario, artifact, title] = process.argv.slice(2);
|
||||
let socket;
|
||||
const pending = new Map();
|
||||
let sequence = 0;
|
||||
|
||||
async function waitFor(callback, label) {
|
||||
for (let i = 0; i < 150; ++i) {
|
||||
const result = await callback();
|
||||
if (result) return result;
|
||||
await delay(100);
|
||||
}
|
||||
throw new Error('Timed out waiting for ' + label);
|
||||
}
|
||||
|
||||
function command(method, params = {}) {
|
||||
const id = ++sequence;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
reject(new Error('DevTools timed out on ' + method));
|
||||
}, 5000);
|
||||
pending.set(id, reply => {
|
||||
clearTimeout(timer);
|
||||
if (reply.error) reject(new Error(reply.error.message));
|
||||
else resolve(reply.result);
|
||||
});
|
||||
socket.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
}
|
||||
|
||||
async function evaluate(expression) {
|
||||
const reply = await command('Runtime.evaluate', { expression, returnByValue: true });
|
||||
if (reply.exceptionDetails) throw new Error(reply.exceptionDetails.exception.description);
|
||||
return reply.result.value;
|
||||
}
|
||||
|
||||
const target = await waitFor(async () => {
|
||||
const response = await fetch('http://127.0.0.1:' + port + '/json/list').catch(() => null);
|
||||
if (!response?.ok) return;
|
||||
return (await response.json()).find(item => item.url === 'https://kswitcher-markdown.invalid/markdown.html' &&
|
||||
(!title || item.title === title));
|
||||
}, 'the Markdown page in WebView2');
|
||||
socket = new WebSocket(target.webSocketDebuggerUrl);
|
||||
socket.addEventListener('message', event => {
|
||||
const reply = JSON.parse(event.data);
|
||||
const callback = pending.get(reply.id);
|
||||
if (callback) {
|
||||
pending.delete(reply.id);
|
||||
callback(reply);
|
||||
}
|
||||
});
|
||||
await new Promise((resolve, reject) => {
|
||||
socket.addEventListener('open', resolve, { once: true });
|
||||
socket.addEventListener('error', reject, { once: true });
|
||||
});
|
||||
|
||||
try {
|
||||
if (scenario === 'render') {
|
||||
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
|
||||
!!document.querySelector('figure svg') &&
|
||||
document.querySelector('img')?.naturalWidth === 1`), 'rendered Mermaid SVG and relative image');
|
||||
assert.equal(await evaluate(`document.querySelector('h1').textContent`), 'Перегляд Markdown');
|
||||
assert.equal(await evaluate(`[...document.querySelectorAll('nav button')].every(button => {
|
||||
const style = getComputedStyle(button);
|
||||
return style.borderTopWidth === '0px' && style.backgroundColor === 'rgba(0, 0, 0, 0)';
|
||||
})`), true);
|
||||
assert.equal(await evaluate(`document.querySelector('td').textContent`), 'Cell');
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').getBoundingClientRect().height > 0`), true);
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').textContent.includes('Render target')`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
|
||||
document.querySelector('main').textContent.includes('Invalid Mermaid diagram')`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-js') && !document.querySelector('iframe')`), true);
|
||||
assert.equal(await evaluate(`performance.getEntriesByType('resource')
|
||||
.every(entry => entry.name.startsWith(location.origin + '/') || entry.name.startsWith('data:'))`), true);
|
||||
await waitFor(() => evaluate(`document.querySelector('img[alt="Missing image"]')?.title === 'Image unavailable'`),
|
||||
'missing image feedback');
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => box.checked)`), [false, true]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => { box.click(); return box.checked; })`), [true, false]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => { box.click(); return box.checked; })`), [false, true]);
|
||||
if (artifact) {
|
||||
const { data } = await command('Page.captureScreenshot');
|
||||
await writeFile(artifact, Buffer.from(data, 'base64'));
|
||||
}
|
||||
} else if (scenario === 'edit') {
|
||||
await command('Input.dispatchKeyEvent', { type: 'keyDown', key: 'F6', code: 'F6', windowsVirtualKeyCode: 117 });
|
||||
} else if (['follow', 'shift-follow', 'ctrl-follow'].includes(scenario)) {
|
||||
await evaluate(`document.querySelector('a[href^="child/"]').dispatchEvent(new MouseEvent('click', {
|
||||
bubbles: true, cancelable: true, shiftKey: ${scenario === 'shift-follow'}, ctrlKey: ${scenario === 'ctrl-follow'}
|
||||
}))`);
|
||||
} else if (scenario === 'mouse-back' || scenario === 'mouse-forward') {
|
||||
const button = scenario === 'mouse-back' ? 'back' : 'forward';
|
||||
await waitFor(() => evaluate(`!document.getElementById('${button}').disabled`), button);
|
||||
await command('Input.dispatchMouseEvent', {type:'mousePressed', x:15, y:80, button, buttons:button === 'back' ? 8 : 16});
|
||||
await command('Input.dispatchMouseEvent', {type:'mouseReleased', x:15, y:80, button, buttons:0});
|
||||
} else if (scenario === 'back' || scenario === 'forward') {
|
||||
await waitFor(() => evaluate(`!document.getElementById('${scenario}').disabled`), scenario);
|
||||
await evaluate(`document.getElementById('${scenario}').click()`);
|
||||
} else if (scenario === 'cycle') {
|
||||
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers:2, windowsVirtualKeyCode:9});
|
||||
} else if (scenario === 'close') {
|
||||
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'w', code:'KeyW', modifiers:2, windowsVirtualKeyCode:87});
|
||||
} else {
|
||||
await waitFor(() => evaluate('document.documentElement?.classList.contains("rendered") && ' +
|
||||
'document.querySelector("h1")?.textContent === ' + JSON.stringify(scenario)), scenario);
|
||||
if (scenario === 'Linked Markdown') {
|
||||
await waitFor(() => evaluate('scrollY > 0 && document.getElementById("target-heading").getBoundingClientRect().top < innerHeight'),
|
||||
'the relative heading fragment to scroll into view');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
socket.close();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,15 @@ 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 Assert-FarCheckbox($Dialog, [int]$Id, $NextControl) {
|
||||
$checkbox=[SearchArrowTest]::GetDlgItem($Dialog,$Id)
|
||||
Post $Dialog 0x28 $checkbox 1
|
||||
@@ -113,6 +123,28 @@ function Read-Bounds($Window) {
|
||||
if (![SearchArrowTest]::GetWindowRect($Window,[ref]$bounds)) { throw 'Missing window bounds' }
|
||||
$bounds
|
||||
}
|
||||
function Assert-CompactNotice($Dialog, [int]$DefaultButton) {
|
||||
$text=[SearchArrowTest]::GetDlgItem($Dialog,100)
|
||||
if (([SearchArrowTest]::GetWindowStyle($text,-16).ToInt64() -band 0x00200000) -ne 0) {
|
||||
throw 'A short Files notice has a vertical scrollbar.'
|
||||
}
|
||||
$lines=[SearchArrowTest]::Send($text,0xBA,0,0).ToInt32()
|
||||
$body=Read-Bounds $text
|
||||
$button=[SearchArrowTest]::GetDlgItem($Dialog,$DefaultButton)
|
||||
$footer=Read-Bounds $button
|
||||
$lineHeight=($body.Bottom-$body.Top)/$lines
|
||||
$frame=Read-Bounds $Dialog
|
||||
if (($body.Top-$frame.Top) -gt 2*$lineHeight -or
|
||||
($frame.Bottom-$footer.Bottom) -gt $lineHeight) {
|
||||
throw 'A short Files notice has excess space between its content and frame.'
|
||||
}
|
||||
if (($footer.Top-$body.Bottom) -gt $lineHeight -or $footer.Top -le $body.Bottom) {
|
||||
throw 'A short Files notice has incorrect spacing between the text and the buttons.'
|
||||
}
|
||||
if ([SearchArrowTest]::FocusedControl($Dialog) -ne $button) {
|
||||
throw 'A Files notice has the wrong starting focus.'
|
||||
}
|
||||
}
|
||||
function Assert-FarFieldHeight($Dialog, [int[]]$Ids) {
|
||||
$heights=@(foreach ($id in $Ids) {
|
||||
$bounds=Read-Bounds ([SearchArrowTest]::GetDlgItem($Dialog,$id))
|
||||
@@ -193,10 +225,64 @@ $fixture = Join-Path $scratch ('files-editor-ui-' + [Guid]::NewGuid().ToString('
|
||||
[IO.File]::WriteAllText($fixture, "public class Test {`r`n}`r`n")
|
||||
$copy=Join-Path $scratch 'KSwitcher.Files.search-arrow-test.exe'
|
||||
Copy-Item -LiteralPath $Executable -Destination $copy
|
||||
$process = Start-Process -FilePath $copy -PassThru -WindowStyle Hidden
|
||||
$process = Start-Process -FilePath $copy -ArgumentList '--terminal-trace' -PassThru -WindowStyle Normal
|
||||
$paintTrace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
|
||||
try {
|
||||
$previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$main = Wait-Until { Find-Window 'KSwitcher.Files' $process.Id }
|
||||
$leftPanel=[SearchArrowTest]::GetDlgItem($main,102)
|
||||
$rightPanel=[SearchArrowTest]::GetDlgItem($main,103)
|
||||
foreach($check in @(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1})) {
|
||||
$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
|
||||
$draws=@(Get-Content -LiteralPath $paintTrace | Select-Object -Skip $lineCount |
|
||||
ForEach-Object { if($_ -match '^\d+ panel-draw ([01]) (\d+) '){ "$($Matches[1])/$($Matches[2])" } } |
|
||||
Select-Object -Unique)
|
||||
if("$($check.Index)/$row" -notin $draws -or $draws.Count -gt 3){
|
||||
throw "Clicking a row repainted unrelated file rows. Drawn rows: $draws"
|
||||
}
|
||||
}
|
||||
Write-Output 'Verified file clicks repaint only cursor rows in the active pane and when changing panes.'
|
||||
Post $main 0x111 132
|
||||
$commandMenu=Wait-Until {
|
||||
$list=[SearchArrowTest]::GetDlgItem($main,121)
|
||||
if ([SearchArrowTest]::IsWindowVisible($list)) { $list }
|
||||
}
|
||||
$count=[SearchArrowTest]::Send($commandMenu,0x18B,0,0).ToInt32()
|
||||
$rows=@(for ($i=0; $i -lt $count; $i++) {
|
||||
$label=[Text.StringBuilder]::new(128)
|
||||
[void][SearchArrowTest]::GetText($commandMenu,0x189,$i,$label)
|
||||
$label.ToString()
|
||||
})
|
||||
if (($rows -join '|') -cne "Refresh panel`tCtrl+R|Folder shortcuts||View`tF3|Edit`tF4|View externally`tAlt+F3|Edit externally`tAlt+F4") {
|
||||
throw 'Commands did not group local actions or showed a LAN-only section.'
|
||||
}
|
||||
Post $commandMenu 0x100 38
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq ($count-1) })
|
||||
Post $commandMenu 0x100 40
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 0 })
|
||||
Post $commandMenu 0x100 40
|
||||
Post $commandMenu 0x100 40
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 3 })
|
||||
Post $commandMenu 0x100 38
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 1 })
|
||||
$rowHeight=[SearchArrowTest]::Send($commandMenu,0x1A1,0,0).ToInt32()
|
||||
$separatorPoint=((2*$rowHeight+1) -shl 16) -bor 4
|
||||
[void][SearchArrowTest]::Send($commandMenu,0x201,1,$separatorPoint)
|
||||
[void][SearchArrowTest]::Send($commandMenu,0x202,0,$separatorPoint)
|
||||
if ([SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -ne 1) {
|
||||
throw 'A click selected the Commands separator.'
|
||||
}
|
||||
Post $commandMenu 0x100 27
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindowVisible($commandMenu) })
|
||||
Write-Output 'Verified Commands grouping, arrow navigation, and inert separators.'
|
||||
$panel = Wait-Until { $handle = [SearchArrowTest]::GetDlgItem($main,102); if ($handle -ne [IntPtr]::Zero) { $handle } }
|
||||
$pathControl = [SearchArrowTest]::GetDlgItem($main,142)
|
||||
$pathText = [Text.StringBuilder]::new(1024)
|
||||
@@ -213,6 +299,18 @@ 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
|
||||
$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.'}
|
||||
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 }
|
||||
@@ -244,6 +342,7 @@ try {
|
||||
[void][SearchArrowTest]::SendText($nameField,0xC,0,$newFolder)
|
||||
Post $makeDialog 0x111 1
|
||||
$folderError=Wait-Until { Find-Window '#32770' $process.Id 100 }
|
||||
Assert-CompactNotice $folderError 1
|
||||
Post $folderError 0x111 1
|
||||
[void](Wait-Until {
|
||||
![SearchArrowTest]::IsWindow($folderError) -and
|
||||
@@ -296,7 +395,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) })
|
||||
@@ -477,6 +580,7 @@ try {
|
||||
$notice=[Text.StringBuilder]::new(256)
|
||||
[void][SearchArrowTest]::GetText([SearchArrowTest]::GetDlgItem($existing,100),0xD,$notice.Capacity,$notice)
|
||||
if (!$notice.ToString().Contains('already open')) { throw 'Reopening did not offer to switch to the editor.' }
|
||||
Assert-CompactNotice $existing 7
|
||||
Post $existing 0x111 6
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindow($existing) })
|
||||
if (Find-Window 'KSwitcher.Files.Text' $process.Id 0 $editor) { throw 'Duplicate editor opened.' }
|
||||
@@ -631,6 +735,7 @@ finally {
|
||||
[void]$process.WaitForExit(5000)
|
||||
}
|
||||
if ($previousDpi) { [void][SearchArrowTest]::SetThreadDpiAwarenessContext($previousDpi) }
|
||||
if(Test-Path -LiteralPath $paintTrace){Remove-Item -LiteralPath $paintTrace -Force}
|
||||
$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-*') {
|
||||
|
||||
@@ -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{};
|
||||
|
||||
+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() }
|
||||
|
||||
@@ -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