Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90c93fba8c | ||
|
|
a09d5e72d1 | ||
|
|
c0bca1b4a2 | ||
|
|
d5ee6ee024 | ||
|
|
5cf0ff5140 | ||
|
|
9c3de731ec | ||
|
|
3b487d0af4 | ||
|
|
9c935fe4da | ||
|
|
4f0a1b5f27 | ||
|
|
524a2d4329 | ||
|
|
5bca97f864 | ||
|
|
0d714147ea | ||
|
|
a0aeb62270 | ||
|
|
4be9b24c4b | ||
|
|
9c30dd91b4 | ||
|
|
5ba51ebb00 | ||
|
|
2bc6eb60c9 | ||
|
|
9c1badcb45 | ||
|
|
9dcc20673a | ||
|
|
ec4079b346 | ||
|
|
41cef4d4f3 | ||
|
|
b53b5715ab |
No files matched your search
+10
-3
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.112 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.119 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
@@ -10,7 +10,8 @@ add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
|
||||
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico")
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-compare.ico")
|
||||
include(cmake/FilesTextLibraries.cmake)
|
||||
set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files")
|
||||
target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
|
||||
@@ -26,7 +27,7 @@ add_custom_target(check-files-search-arrow
|
||||
DEPENDS KSwitcherFiles
|
||||
VERBATIM)
|
||||
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid)
|
||||
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
|
||||
else()
|
||||
@@ -160,6 +161,11 @@ add_test(NAME files-system-open
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
|
||||
-SystemOpenOnly)
|
||||
set_tests_properties(files-system-open PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
|
||||
add_test(NAME files-comparison-splitter
|
||||
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
|
||||
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>")
|
||||
set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
|
||||
find_program(KSWITCHER_NODE NAMES node)
|
||||
if(KSWITCHER_NODE)
|
||||
add_test(NAME files-terminal-enter
|
||||
@@ -207,6 +213,7 @@ add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests)
|
||||
add_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout)
|
||||
set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
|
||||
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
|
||||
target_include_directories(KSwitcherHistoryHostTests PRIVATE vendor)
|
||||
target_link_libraries(KSwitcherHistoryHostTests PRIVATE kscore psapi)
|
||||
set_target_properties(KSwitcherHistoryHostTests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/history-host-fixture-$<CONFIG>")
|
||||
add_dependencies(KSwitcherHistoryHostTests KSwitcher KSwitcherScreenshot)
|
||||
|
||||
+122
-14
@@ -29,14 +29,81 @@ Warning і початковий фокус на No.
|
||||
|
||||
## Скорочення
|
||||
|
||||
- **FTP** у меню джерел (Alt+F1 для лівої панелі, Alt+F2 для правої)
|
||||
відкриває список збережених підключень у вибраній панелі. Shift+F4
|
||||
додає підключення, F4 редагує виділене, Enter відкриває його.
|
||||
У формі вкажи назву, сервер, порт (типово 21), ім’я користувача й пароль.
|
||||
Порожнє ім’я означає анонімний вхід. Паролі зберігаються локально
|
||||
із захистом Windows DPAPI. Звичайний FTP передає дані без шифрування.
|
||||
Після підключення панель показує справжній шлях початкового каталогу
|
||||
сервера. Enter або подвійний клік на `..` відкриває батьківську папку.
|
||||
У корені рядка `..` немає. Щоб повернутися до списку підключень,
|
||||
вибери FTP в меню джерел панелі.
|
||||
Назви файлів і папок передаються в UTF-8. Для старого сервера, який
|
||||
використовує системну кодову сторінку Windows, увімкни в профілі
|
||||
**Use Windows encoding for file names** і підключися знову.
|
||||
- F5 копіює поточний або позначені файли й папки між локальною та
|
||||
підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої
|
||||
панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі.
|
||||
Використовуються спільні діалоги Copy, прогресу та конфлікту імен.
|
||||
Поточний файл записується під тимчасовим ім’ям до завершення передачі.
|
||||
Для заміни файла FTP-сервер має приймати перейменування поверх нього.
|
||||
- У підключеній FTP-панелі F3 та Enter відкривають файл у Viewer, а F4
|
||||
відкриває Editor. Файл завантажується у тимчасову копію у фоні.
|
||||
F2 в Editor передає зміни назад на FTP. Якщо сервер повідомляє інший
|
||||
розмір або час зміни файла, запис скасовується, а правки лишаються в редакторі.
|
||||
- У підключеній FTP-панелі F6 перейменовує один файл або папку в поточному
|
||||
каталозі. Якщо нове ім’я зайняте, Files показує помилку. F8 запитує
|
||||
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
|
||||
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
|
||||
|
||||
- **F9 → Commands → Compare files** порівнює два позначені текстові файли
|
||||
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
|
||||
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
|
||||
FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
|
||||
рядків і підсвічуванням вставок, видалень і замін. У замінених рядках
|
||||
виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8)
|
||||
переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків.
|
||||
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
|
||||
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
|
||||
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
|
||||
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
|
||||
Текст файлів і порожня область під ним мають білий фон, рядки
|
||||
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
|
||||
Центральний розділювач можна перетягнути мишею. Під час зміни розміру
|
||||
вікна пропорція колонок зберігається.
|
||||
Ctrl+колесо змінює масштаб тексту в поточному вікні.
|
||||
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
|
||||
на панелі завдань. У **Options → File comparison → Font and colors**
|
||||
можна окремо налаштувати шрифт, тло, текст і кольори змін.
|
||||
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
|
||||
і меню Commands показує поточне призначення.
|
||||
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
|
||||
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
|
||||
Вставлені й видалені порожні рядки враховуються завжди.
|
||||
Кнопка розгортання в системному заголовку збільшує вікно порівняння
|
||||
до робочої області екрана. Повторне натискання відновлює попередній розмір.
|
||||
Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM,
|
||||
до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються
|
||||
як рівнозначні.
|
||||
|
||||
- У меню Files і його списках, що випадають, стрілки вгору й вниз
|
||||
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
|
||||
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
|
||||
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP.
|
||||
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
|
||||
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
|
||||
до закриття меню, навіть коли оновлюється список LAN.
|
||||
|
||||
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
|
||||
документ — у програмі, призначеній для його типу у Windows. EXE запускається
|
||||
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
|
||||
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
|
||||
панелі LAN, спочатку скопіюй його до локальної папки.
|
||||
Після успішного відкриття локального файла через Windows його шлях
|
||||
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
|
||||
його курсор приховано. При виборі
|
||||
з історії у командний рядок підставляється команда, яка повторює відкриття.
|
||||
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
|
||||
елемент через Windows.
|
||||
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
|
||||
@@ -49,7 +116,11 @@ Warning і початковий фокус на No.
|
||||
керують панеллю, коли список підказок закритий.
|
||||
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
|
||||
командний рядок порожній.
|
||||
Ctrl+← і Ctrl+→ зміщують розділювач видимих панелей на ширину одного символу.
|
||||
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
|
||||
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
|
||||
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
|
||||
курсора він мав інше оформлення.
|
||||
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
|
||||
текст із буфера обміну в позицію курсора або замінюють виділення.
|
||||
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
|
||||
@@ -58,12 +129,19 @@ Warning і початковий фокус на No.
|
||||
Enter передає порожній рядок у термінал.
|
||||
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
|
||||
командного рядка й виконують відповідну дію за тими самими правилами.
|
||||
Локальна команда запускається в папці активної панелі, яку показано
|
||||
перед командним рядком. Після перемикання панелі або переходу до іншої
|
||||
папки наступна команда використовує нову папку навіть у вже відкритому
|
||||
PowerShell. Якщо команда змінює папку (наприклад, через `cd`), панель
|
||||
переходить до неї, якщо користувач за цей час не змінив її розташування.
|
||||
Під час запуску термінала область виводу має темне тло, поки WebView2
|
||||
готує сторінку.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
- Під час набору локальної команди над полем з’являються підказки PowerShell.
|
||||
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
|
||||
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
|
||||
та шляхи відносно робочої папки термінала або активної панелі до запуску
|
||||
термінала. Після `cd ` список пропонує папки,
|
||||
та шляхи відносно робочої папки активної панелі.
|
||||
Після `cd ` список пропонує папки,
|
||||
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
|
||||
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
|
||||
Enter вставляє виділену, а клік вставляє підказку під вказівником.
|
||||
@@ -128,16 +206,26 @@ Warning і початковий фокус на No.
|
||||
|
||||
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
|
||||
курсора командного рядка або замінює виділення. Подвійні лапки додаються
|
||||
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
|
||||
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
|
||||
відкритої в активній панелі.
|
||||
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
|
||||
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Під час переходу
|
||||
активна панель показує «Loading folder…» і зберігає попередній список до
|
||||
завершення сканування. Після переходу оновлюються шлях і список цієї панелі
|
||||
та командний рядок. Сусідня панель не перемальовується через цей перехід.
|
||||
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
|
||||
панелі показує «Reading» з лічильником прочитаних файлів і папок та
|
||||
підказкою [Esc].
|
||||
До завершення читання панель зберігає попередній список. Escape зупиняє
|
||||
сканування активної панелі й відкриває прочитану частину папки. Якщо
|
||||
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
|
||||
повторює сканування, щоб отримати повний список. Після переходу
|
||||
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
|
||||
панель не перемальовується через цей перехід.
|
||||
Якщо надійшов новіший запит, результат попереднього
|
||||
сканування пропускається. Після підтвердження UAC очікування списку
|
||||
від підвищеного процесу теж відбувається у фоні.
|
||||
- Якщо Windows відмовляє у правах для F5, F6, F7 або F8 на локальних
|
||||
дисках, Files пропонує повторити операцію з правами адміністратора.
|
||||
Після підтвердження UAC допоміжний процес обробляє захищені елементи
|
||||
поточної операції. Відмова в діалозі або в UAC зупиняє операцію.
|
||||
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
|
||||
зберігаються для наявних елементів, а підраховані через F3 розміри папок
|
||||
скидаються. F2 також виконує цю дію.
|
||||
@@ -217,10 +305,16 @@ Warning і початковий фокус на No.
|
||||
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
|
||||
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
|
||||
порядку. Коли відкрито лише Files, активна панель не змінюється.
|
||||
- Shift+F4 у локальній панелі відкриває Editor для наявного або нового файла.
|
||||
Порожнє ім’я підставляє `New_File_<дата>_<час>.txt`. Новий файл з’являється
|
||||
на диску після збереження. Esc після змін пропонує Save, Discard або Cancel.
|
||||
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
|
||||
рядків. Скасування параметрів залишає текст у редакторі.
|
||||
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
|
||||
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
|
||||
із підсвічуванням Markdown.
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Клік по чекбоксу
|
||||
одразу записує позначку у вихідний Markdown. У разі помилки збереження
|
||||
попередній стан відновлюється. Підписи з'єднань малюються поверх стрілок.
|
||||
F4 відкриває текст із підсвічуванням Markdown.
|
||||
HTML усередині Markdown підтримує таблиці, текстове форматування, посилання,
|
||||
відносні зображення й окремі стилі, зокрема `white-space: nowrap` у клітинках.
|
||||
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
|
||||
@@ -239,11 +333,24 @@ Warning і початковий фокус на No.
|
||||
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
|
||||
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
|
||||
8 МіБ, F3 відкриває текстовий перегляд.
|
||||
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
|
||||
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
|
||||
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
|
||||
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
|
||||
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
|
||||
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
|
||||
позначених папок в інших рядках рахує позначені папки. Без позначок
|
||||
F3 рахує папку під курсором або відкриває файл. Папки обробляються по черзі,
|
||||
і результат кожної видно в колонці Size у широкому режимі та в рядку
|
||||
стану, коли там увімкнено розмір. Це працює і в LAN- та FTP-панелях. Посилання й
|
||||
junction не обходяться. Недоступний вміст позначається як частковий результат.
|
||||
Папки, які чекають на підрахунок, мають позначку Queued. Через дві секунди
|
||||
підрахунку в рядку поточної папки з’являється спінер.
|
||||
Пересування курсора в списку залишає спінер у рядку папки, яку ще рахують.
|
||||
Esc скасовує поточний підрахунок і чергу активної панелі, залишаючи
|
||||
вже обчислені розміри та поточний каталог.
|
||||
Перехід до іншого каталогу чи джерела панелі скасовує підрахунок.
|
||||
- Під списком кожної панелі з позначками показано кількість позначених
|
||||
елементів і їхній сумарний розмір. Файли враховуються одразу, папки — у
|
||||
міру завершення підрахунку через F3. Позначка ≥ означає, що сума
|
||||
неповна, а число біля «to measure» показує, скільки позначених папок
|
||||
ще без розміру.
|
||||
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
|
||||
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
|
||||
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
|
||||
@@ -355,6 +462,7 @@ Warning і початковий фокус на No.
|
||||
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
|
||||
|
||||
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
|
||||
Розділювач Size проходить по одній вертикалі в заголовку та списку, а праві краї підпису й значень вирівняні.
|
||||
|
||||
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
@@ -999,8 +999,7 @@ Keep `v0.4.2` as the last legacy `vX.Y.Z` release. Publish full packages as
|
||||
`release-vX.Y.Z` (stable, not prerelease), including `release-files.json`,
|
||||
`KSwitcher-win-x64.zip` and `SHA256SUMS.txt`. Never publish a manifest package under a
|
||||
legacy version tag: clients that have not installed the bridge would select it.
|
||||
Keep the compatibility bridge in the first 100 releases returned by Gitea while
|
||||
supporting old clients; their immutable update code only reads that page.
|
||||
Legacy clients only read the first 100 releases returned by Gitea. The bridge is now outside that page. For v0.3.x–v0.4.1, follow the manual bridge installation instructions above.
|
||||
|
||||
### Editors that omit copied trailing spaces
|
||||
|
||||
|
||||
+75
-1
@@ -1,5 +1,79 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.6.119 — 2026-11-18
|
||||
|
||||
KSwitcher Files runs local commands in the folder shown at the command prompt. After switching panes or opening a different folder, commands such as `git clone` and relative path suggestions use that folder in the same PowerShell session.
|
||||
|
||||
**Українською.**
|
||||
|
||||
KSwitcher Files запускає локальні команди в папці, показаній перед командним рядком. Після перемикання панелі або переходу до іншої папки команди на кшталт `git clone` і підказки відносних шляхів використовують цю папку в тій самій сесії PowerShell.
|
||||
|
||||
## v0.6.118 — 2026-11-18
|
||||
|
||||
- **Shift+F11** opens a side-by-side comparison of two selected text files from local, LAN or FTP panes. The comparison has its own taskbar button, a movable divider, a native toolbar, **F7/F8** change navigation, and **Ctrl+wheel** text zoom. The shortcut, font and colors are configurable in **Options → File comparison**.
|
||||
- The footer of each file pane shows the number and combined size of marked items, including folders measured by **F3**. **Ctrl+Left/Right** resize the file panes.
|
||||
- When Windows denies access during a supported local **F5–F8** operation, Files offers to retry with administrator rights through UAC.
|
||||
- Markdown task checkboxes save their state to the source file. Mermaid flowchart labels appear above the connecting lines.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Shift+F11** відкриває двостороннє порівняння двох вибраних текстових файлів із локальних, LAN- або FTP-панелей. Вікно має власну кнопку на панелі завдань, рухомий розділювач і системний тулбар. **F7/F8** переходять між змінами, **Ctrl+колесо** змінює масштаб тексту. Комбінація, шрифт і кольори налаштовуються в **Options → File comparison**.
|
||||
- Унизу кожної панелі видно кількість і сумарний розмір позначених елементів, зокрема папок, виміряних через **F3**. **Ctrl+←/→** змінюють ширину панелей.
|
||||
- Якщо Windows відмовляє в доступі під час підтримуваної локальної операції **F5–F8**, Files пропонує повторити її з правами адміністратора через UAC.
|
||||
- Чекбокси Markdown зберігають стан у вихідному файлі. Підписи з’єднань у блок-схемах Mermaid відображаються поверх ліній.
|
||||
|
||||
## v0.6.117 — 2026-11-18
|
||||
|
||||
- KSwitcher Files supports saved FTP connections in both panes. Browse UTF-8 file names, open or edit remote files with **F3/F4**, save with **F2**, copy between a local and FTP pane with **F5**, rename with **F6**, and permanently delete with **F8**.
|
||||
- **F3** measures folders on local, LAN and FTP panes. On `..` it queues every folder in the current list. Waiting folders show **Queued** and the active folder shows a spinner after two seconds. **Esc** cancels the active pane’s calculation and queue.
|
||||
- The source menu separates local drives, FTP and KSwitcher LAN. **1** opens FTP and the remaining displayed digits select LAN actions. Wide pane **Size** dividers align, and **Ctrl+F** on `..` inserts the open folder’s path.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- KSwitcher Files підтримує збережені FTP-підключення в обох панелях. Назви файлів читаються в UTF-8. **F3/F4** відкривають перегляд і редактор, **F2** зберігає зміни, **F5** копіює між локальною та FTP-панелями, **F6** перейменовує, **F8** видаляє без кошика.
|
||||
- **F3** рахує розмір локальних, LAN- і FTP-папок. На `..` до черги додаються всі папки списку. Папки в черзі мають позначку **Queued**, а біля поточної через дві секунди з’являється спінер. **Esc** скасовує підрахунок і чергу активної панелі.
|
||||
- Меню джерел розділяє локальні диски, FTP і KSwitcher LAN. **1** відкриває FTP, решта показаних цифр вибирають LAN-дії. Розділювачі колонки **Size** вирівняні, а **Ctrl+F** на `..` вставляє шлях відкритої папки.
|
||||
|
||||
## v0.6.116 — 2026-11-17
|
||||
|
||||
- Files displays a live count while reading a folder. **Esc** stops the scan and shows the entries already read. **Ctrl+R** reads the folder again. Mouse selection works beyond the first 65,536 rows.
|
||||
- Files shows the path of files opened through Windows in the terminal and command history. Choosing a history entry still inserts the command that reopens the file. The embedded terminal hides its inactive cursor.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- Files показує лічильник під час читання папки. **Esc** зупиняє читання й показує вже прочитані записи. **Ctrl+R** перечитує папку. Вибір мишею працює після перших 65 536 рядків.
|
||||
- Files показує шлях до файла, відкритого через Windows, у терміналі й історії команд. Вибір запису історії підставляє команду для повторного відкриття. Вбудований термінал приховує курсор, коли він неактивний.
|
||||
|
||||
## v0.6.115 — 2026-11-17
|
||||
|
||||
- **Shift+F4** opens or creates a file in the active local panel. Leave the name blank for a generated `New_File_…txt` name. After editing a draft, **Esc → Save** opens options for the file name, encoding, BOM, and line endings.
|
||||
- Typing updates the editor status line without repainting the menu or flashing the editor window.
|
||||
- When **Enter** opens a local file through Windows, Files displays `start 'path'` in the terminal and saves it in command history.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- **Shift+F4** відкриває або створює файл в активній локальній панелі. Якщо залишити ім’я порожнім, Files підставить `New_File_…txt`. Після редагування чернетки **Esc → Save** відкриває параметри імені, кодування, BOM і кінців рядків.
|
||||
- Під час набору редактор оновлює рядок стану без перемальовування меню й миготіння вікна.
|
||||
- Коли **Enter** відкриває локальний файл через Windows, Files показує `start 'шлях'` у терміналі й додає команду до історії.
|
||||
|
||||
## v0.6.114 — 2026-11-17
|
||||
|
||||
In KSwitcher Files, clicking a row in the inactive pane highlights that row immediately. The previous cursor row in that pane no longer flashes with the active highlight. If it had a custom unfocused cursor color, it returns directly to its normal style.
|
||||
|
||||
**Українською.**
|
||||
|
||||
У KSwitcher Files клік по рядку неактивної панелі одразу підсвічує вибраний рядок. Попередній рядок курсора цієї панелі більше не блимає активним підсвічуванням. Якщо він мав окремий колір неактивного курсора, рядок одразу повертається до звичайного оформлення.
|
||||
|
||||
## v0.6.113 — 2026-11-17
|
||||
|
||||
- KSwitcher Files keeps the terminal output area dark while WebView2 initializes. This fixes the white flash during startup.
|
||||
- The terminal copy regression test checks for a new clipboard write and verifies its contents without first taking clipboard ownership.
|
||||
|
||||
**Українською.**
|
||||
|
||||
- Під час запуску термінала область виводу KSwitcher Files залишається темною, поки WebView2 готує сторінку. Це усуває білий спалах під час відкриття термінала.
|
||||
- Тест копіювання з термінала перевіряє новий запис і його вміст без попереднього захоплення буфера обміну.
|
||||
|
||||
## v0.6.112 — 2026-11-17
|
||||
|
||||
In KSwitcher Files, **Ctrl+Shift+Tab** cycles backward through Files, Editor, and Viewer windows. **Ctrl+Tab** cycles forward. Both shortcuts wrap at the ends of the window list, including in the Markdown preview.
|
||||
@@ -458,7 +532,7 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
|
||||
|
||||
## Upgrade
|
||||
|
||||
Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
|
||||
Choose **Update** in the tray menu. For v0.3.x–v0.4.1, install the [v0.4.2 bridge](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2) manually first. Close KSwitcher and its editors, extract the bridge ZIP into the installation folder while keeping personal data, dictionaries, and tools, then start v0.4.2 and choose **Update**. v0.2.3 and earlier require manual installation.
|
||||
|
||||
For a manual upgrade, exit KSwitcher and its configurator and screenshot editors, then extract the entire **KSwitcher-win-x64.zip** into its installation folder. Verify it with **SHA256SUMS.txt**. Keep personal data, customized dictionaries and tools. Keep the three KSwitcher executables together.
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
8ac71477b90b4a8893c43e000d77d53df57db63c07f0d4784820c5563b106218 KSwitcher-win-x64.zip
|
||||
566cda1b26bbc5980e3e19f804ae500bf029fe6f5a503cfd609be6f6ad4409ea KSwitcher-win-x64.zip
|
||||
+65
-65
@@ -1,166 +1,166 @@
|
||||
{
|
||||
"version": "0.6.112",
|
||||
"version": "0.6.119",
|
||||
"schema": 1,
|
||||
"files": [
|
||||
{
|
||||
"sha256": "53c3f9aeca02136acbd2ec3c187ee858cb5f60a2f1bf5641ee264e062f73653f",
|
||||
"size": 2479104,
|
||||
"path": "KSwitcher.exe",
|
||||
"size": 2479104
|
||||
"sha256": "e6b98679ac0a460e42ec9f593e88cc802cedaaaf887bce79c3f8577419143aa1"
|
||||
},
|
||||
{
|
||||
"sha256": "c4dbd247e48fd1d37744d280c2fd948c3355eb3507324ae79adc0dcd24ef5469",
|
||||
"size": 2458112,
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"size": 2458112
|
||||
"sha256": "43e4ea0d087d70658fd2cca47b2f06b919eb86acc65dce1afa7db1e02cbdcded"
|
||||
},
|
||||
{
|
||||
"sha256": "30e8dbe575b3705ae379fda30174e0a486ef5605ec582dd81e01b121180c127b",
|
||||
"size": 3060224,
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"size": 3060224
|
||||
"sha256": "9b791b2dbf623f50ab92cde4017b07c9f8df4bbb7ac3526d0d18e0d770061f43"
|
||||
},
|
||||
{
|
||||
"sha256": "b45ff37c0f279dcf142606c282b73cf3403cb026c4800beea216fd532bc5993f",
|
||||
"size": 4370944,
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"size": 4214272
|
||||
"sha256": "e44a923d3e686e0e273e6dd167f6bd66dafd66e2870b4950fcbd8824d286a61d"
|
||||
},
|
||||
{
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"size": 194912,
|
||||
"path": "WebView2Loader.dll",
|
||||
"size": 194912
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
|
||||
},
|
||||
{
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"size": 1103,
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"size": 1103
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
|
||||
},
|
||||
{
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"size": 1521,
|
||||
"path": "terminal/addon-fit.js",
|
||||
"size": 1521
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
|
||||
},
|
||||
{
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"size": 527,
|
||||
"path": "terminal/index.html",
|
||||
"size": 527
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
|
||||
},
|
||||
{
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"size": 1073,
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"size": 1073
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
|
||||
},
|
||||
{
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"size": 100786,
|
||||
"path": "terminal/markdown-it.js",
|
||||
"size": 100786
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
|
||||
},
|
||||
{
|
||||
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c",
|
||||
"size": 3635,
|
||||
"path": "terminal/markdown.html",
|
||||
"size": 3530
|
||||
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79"
|
||||
},
|
||||
{
|
||||
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763",
|
||||
"size": 16944,
|
||||
"path": "terminal/markdown.js",
|
||||
"size": 15014
|
||||
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8"
|
||||
},
|
||||
{
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"size": 1089,
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"size": 1089
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
|
||||
},
|
||||
{
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"size": 5537838,
|
||||
"path": "terminal/mermaid.js",
|
||||
"size": 5537838
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
|
||||
},
|
||||
{
|
||||
"sha256": "0557d251962301940785690a3fc49475dd166bb7d0bd0417dc3279d1f1b3a98a",
|
||||
"size": 5065,
|
||||
"path": "terminal/terminal.js",
|
||||
"size": 5033
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
|
||||
},
|
||||
{
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"size": 1261,
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"size": 1261
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
|
||||
},
|
||||
{
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"size": 7112,
|
||||
"path": "terminal/xterm.css",
|
||||
"size": 7112
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
|
||||
},
|
||||
{
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"size": 488663,
|
||||
"path": "terminal/xterm.js",
|
||||
"size": 488663
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
|
||||
},
|
||||
{
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"size": 4401,
|
||||
"path": "LICENSE",
|
||||
"size": 4401
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
|
||||
},
|
||||
{
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"size": 1096,
|
||||
"path": "json-LICENSE.txt",
|
||||
"size": 1096
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
|
||||
},
|
||||
{
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"size": 883,
|
||||
"path": "files-text-license.txt",
|
||||
"size": 883
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
|
||||
},
|
||||
{
|
||||
"sha256": "fcbd14b6190dc2a3575a4bc4be7229540c647022cb038d33ec4ac22176c67a9e",
|
||||
"size": 95317,
|
||||
"path": "README.md",
|
||||
"size": 95289
|
||||
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8"
|
||||
},
|
||||
{
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
|
||||
"size": 11577,
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"size": 11577
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
|
||||
},
|
||||
{
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"size": 732485,
|
||||
"path": "dictionaries/en.txt",
|
||||
"size": 732485
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
|
||||
},
|
||||
{
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"size": 20566,
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"size": 20566
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
|
||||
},
|
||||
{
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"size": 2265,
|
||||
"path": "dictionaries/README.md",
|
||||
"size": 2265
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
|
||||
},
|
||||
{
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"size": 1109134,
|
||||
"path": "dictionaries/ru.txt",
|
||||
"size": 1109134
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
|
||||
},
|
||||
{
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"size": 1280,
|
||||
"path": "dictionaries/sources.json",
|
||||
"size": 1280
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
|
||||
},
|
||||
{
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"size": 940799,
|
||||
"path": "dictionaries/uk.txt",
|
||||
"size": 940799
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
|
||||
},
|
||||
{
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"size": 993,
|
||||
"path": "tools/README.txt",
|
||||
"size": 993
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
|
||||
},
|
||||
{
|
||||
"sha256": "f1cd3477fc3e64ed26986b86d85472ca0780963b225231ab575489d4fa82e01b",
|
||||
"size": 133120,
|
||||
"path": "tools/StayHere.exe",
|
||||
"size": 133120
|
||||
"sha256": "d689b74a0c5ba018d3f26eb32c4fab88a8404627ee69be1e326d60b1167b5667"
|
||||
},
|
||||
{
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"size": 2796,
|
||||
"path": "tools/StayHere-README.md",
|
||||
"size": 2796
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
|
||||
}
|
||||
]
|
||||
}
|
||||
+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,112,0
|
||||
PRODUCTVERSION 0,6,112,0
|
||||
FILEVERSION 0,6,119,0
|
||||
PRODUCTVERSION 0,6,119,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.112"
|
||||
VALUE "FileVersion", "0.6.119"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
1 ICON "kswitcher-files.ico"
|
||||
IDI_FILES_VIEWER ICON "kswitcher-files-viewer.ico"
|
||||
IDI_FILES_EDITOR ICON "kswitcher-files-editor.ico"
|
||||
IDI_FILES_COMPARE ICON "kswitcher-files-compare.ico"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
601 RCDATA "files-text-license.txt"
|
||||
|
||||
@@ -50,6 +51,41 @@ BEGIN
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
|
||||
END
|
||||
|
||||
611 DIALOGEX 0, 0, 332, 96
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Open/create file:", 460, 14, 16, 304, 12
|
||||
FAR_EDIT(461, 0, 14, 29, 304, 14)
|
||||
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
|
||||
LTEXT "&Code page:", 462, 14, 53, 94, 12
|
||||
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
|
||||
CONTROL "", 467, "Static", NOT WS_VISIBLE, 14, 72, 1, 1
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 76, 60, 16
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 76, 60, 16
|
||||
END
|
||||
|
||||
612 DIALOGEX 0, 0, 332, 184
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Save file &as:", 460, 14, 16, 304, 12
|
||||
FAR_EDIT(461, 0, 14, 29, 304, 14)
|
||||
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
|
||||
LTEXT "&Code page:", 462, 14, 53, 94, 12
|
||||
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
|
||||
AUTOCHECKBOX "Add signature (&BOM)", 464, 14, 66, 304, 12
|
||||
CONTROL "", 468, "Static", NOT WS_VISIBLE, 14, 86, 1, 1
|
||||
LTEXT "Change line breaks to:", 469, 14, 87, 304, 12
|
||||
AUTORADIOBUTTON "Do ¬ change", 470, 14, 100, 304, 12, WS_GROUP | WS_TABSTOP
|
||||
AUTORADIOBUTTON "&Windows (CR LF)", 471, 14, 112, 304, 12
|
||||
AUTORADIOBUTTON "&Unix (LF)", 472, 14, 124, 304, 12
|
||||
AUTORADIOBUTTON "&Mac (CR)", 473, 14, 136, 304, 12
|
||||
CONTROL "", 467, "Static", NOT WS_VISIBLE | WS_GROUP, 14, 155, 1, 1
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 157, 60, 16
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 157, 60, 16
|
||||
END
|
||||
|
||||
607 DIALOGEX 0, 0, 185, 57
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
@@ -60,6 +96,7 @@ BEGIN
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
|
||||
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
|
||||
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 129, 38, 51, 15
|
||||
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
|
||||
END
|
||||
|
||||
@@ -167,6 +204,14 @@ BEGIN
|
||||
PUSHBUTTON "Choose &font…", 377, 306, 68, 76, 14
|
||||
LTEXT "Font &size (8–72 pt)", 378, 131, 99, 184, 12
|
||||
EDITTEXT 379, 318, 96, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
LTEXT "", 408, 131, 30, 254, 14
|
||||
PUSHBUTTON "Change &font…", 409, 131, 49, 82, 15
|
||||
LTEXT "Comparison &color", 410, 131, 79, 117, 12
|
||||
COMBOBOX 411, 250, 76, 132, 126, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "Change color…", 412, 250, 97, 82, 15
|
||||
LTEXT "", 413, 338, 100, 45, 12
|
||||
LTEXT "Compare files &shortcut", 414, 131, 130, 117, 12
|
||||
CONTROL "", 415, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 250, 127, 132, 15
|
||||
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
|
||||
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
|
||||
@@ -307,3 +352,58 @@ BEGIN
|
||||
FAR_EDIT(325, 0, 12, 28, 361, 16)
|
||||
LISTBOX 324, 12, 49, 361, 155, LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
END
|
||||
|
||||
112 DIALOGEX 0, 0, 360, 186
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "FTP connection"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Name", 381, 16, 18, 328, 12
|
||||
FAR_EDIT(382, ES_LEFT, 16, 31, 328, 15)
|
||||
LTEXT "&Server", 383, 16, 49, 250, 12
|
||||
LTEXT "Por&t", 384, 278, 49, 66, 12
|
||||
FAR_EDIT(385, ES_LEFT, 16, 62, 250, 15)
|
||||
FAR_EDIT(386, ES_LEFT | ES_NUMBER, 278, 62, 66, 15)
|
||||
LTEXT "&User name (blank for anonymous)", 387, 16, 80, 328, 12
|
||||
FAR_EDIT(388, ES_LEFT, 16, 93, 328, 15)
|
||||
LTEXT "&Password", 389, 16, 111, 328, 12
|
||||
EDITTEXT 390, 16, 124, 328, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
|
||||
AUTOCHECKBOX "Use &Windows encoding for file names", 392, 16, 144, 328, 14
|
||||
LTEXT "", 391, 10, 161, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 164, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 164, 86, 18
|
||||
END
|
||||
|
||||
113 DIALOGEX 0, 0, 350, 73
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Rename"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "New name in the current FTP folder:", 210, 14, 15, 322, 12
|
||||
FAR_EDIT(211, 0, 14, 29, 322, 18)
|
||||
LTEXT "", 217, 10, 49, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Rename", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 51, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 51, 86, 18
|
||||
END
|
||||
|
||||
114 DIALOGEX 0, 0, 510, 252
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_CLIPCHILDREN
|
||||
EXSTYLE WS_EX_APPWINDOW
|
||||
CAPTION "Compare files"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "", 400, 4, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 401, 259, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 45, 510, 207
|
||||
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
|
||||
LTEXT "", 403, 216, 12, 98, 14
|
||||
END
|
||||
|
||||
115 DIALOGEX 0, 0, 290, 58
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Compare files"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
|
||||
END
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
@@ -3,4 +3,5 @@
|
||||
#define IDI_SCREENSHOT_QUESTION 102
|
||||
#define IDI_FILES_VIEWER 103
|
||||
#define IDI_FILES_EDITOR 104
|
||||
#define IDI_FILES_COMPARE 105
|
||||
#define IDC_SCREENSHOT_PENCIL 500
|
||||
@@ -34,6 +34,7 @@ table { display: block; border-collapse: collapse; }
|
||||
th, td { border: 1px solid GrayText; padding: .3em .65em; }
|
||||
img, svg { max-width: 100%; height: auto; }
|
||||
figure { margin: 1em 0; }
|
||||
figure svg .edgeLabel rect { fill: Canvas !important; opacity: 1 !important; stroke: none !important; }
|
||||
.task { list-style: none; }
|
||||
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
|
||||
</style>
|
||||
|
||||
@@ -15,6 +15,9 @@ let generation = 0;
|
||||
let images = [];
|
||||
let matches = [];
|
||||
let activeMatch = -1;
|
||||
let taskMarkers = new WeakMap();
|
||||
let pendingTask;
|
||||
let previewRevision = 0;
|
||||
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
@@ -24,7 +27,8 @@ mermaid.initialize({
|
||||
flowchart: { htmlLabels: false }
|
||||
});
|
||||
|
||||
markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
|
||||
markdown.core.ruler.after('inline', 'task_lists', ({ tokens, src, env }) => {
|
||||
const lines = src.split('\n');
|
||||
for (let i = 2; i < tokens.length; ++i) {
|
||||
const token = tokens[i];
|
||||
if (token.type !== 'inline' || tokens[i - 1].type !== 'paragraph_open' ||
|
||||
@@ -36,13 +40,16 @@ markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
|
||||
const box = new text.constructor('task_checkbox', '', 0);
|
||||
box.checked = marker[1] !== ' ';
|
||||
box.content = token.content.slice(marker[0].length);
|
||||
const line = tokens[i - 1].map?.[0];
|
||||
const sourceMarker = /^[ \t]*(?:>[ \t]*)*(?:[-+*]|\d{1,9}[.)])[ \t]+\[([ xX])\][ \t]+/.exec(lines[line]);
|
||||
if (sourceMarker) box.source = env.taskKey + ':' + line + ':' + (sourceMarker[0].lastIndexOf('[') + 1);
|
||||
token.children.unshift(box);
|
||||
tokens[i - 2].attrJoin('class', 'task');
|
||||
}
|
||||
});
|
||||
markdown.renderer.rules.task_checkbox = (tokens, i) =>
|
||||
'<input type="checkbox" aria-label="' + markdown.utils.escapeHtml(tokens[i].content) + '"' +
|
||||
(tokens[i].checked ? ' checked' : '') + '>';
|
||||
(tokens[i].checked ? ' checked' : '') + (tokens[i].source ? ' data-task="' + tokens[i].source + '"' : '') + '>';
|
||||
markdown.renderer.rules.image = (tokens, i) => {
|
||||
const token = tokens[i];
|
||||
const alt = markdown.renderer.renderInlineAsText(token.children, markdown.options, {});
|
||||
@@ -67,10 +74,13 @@ function relativeResource(path) {
|
||||
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
|
||||
}
|
||||
|
||||
function renderContent(text) {
|
||||
function renderContent(text, canSave) {
|
||||
// Parse in an inert template and allow only document markup before attaching it to the preview.
|
||||
const template = document.createElement('template');
|
||||
template.innerHTML = markdown.render(text);
|
||||
const taskKey = [...crypto.getRandomValues(new Uint32Array(4))].join('-');
|
||||
taskMarkers = new WeakMap();
|
||||
pendingTask = undefined;
|
||||
template.innerHTML = markdown.render(text, { taskKey });
|
||||
for (const element of template.content.querySelectorAll('*')) {
|
||||
const tag = element.localName;
|
||||
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
|
||||
@@ -79,6 +89,12 @@ function renderContent(text) {
|
||||
continue;
|
||||
}
|
||||
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
|
||||
const task = tag === 'input' && element.getAttribute('data-task');
|
||||
if (task && task.startsWith(taskKey + ':')) {
|
||||
const [, line, column] = task.split(':');
|
||||
taskMarkers.set(element, { line: Number(line), column: Number(column) });
|
||||
element.disabled = !canSave;
|
||||
}
|
||||
const styles = element.hasAttribute('style')
|
||||
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
|
||||
for (const { name } of [...element.attributes]) {
|
||||
@@ -217,13 +233,14 @@ searchPrevious.addEventListener('click', () => stepSearch(-1));
|
||||
searchNext.addEventListener('click', () => stepSearch(1));
|
||||
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
|
||||
|
||||
async function render({ text, fragment, scroll, title, keepPosition }) {
|
||||
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave }) {
|
||||
const current = ++generation;
|
||||
if (keepPosition) scroll = window.scrollY;
|
||||
else closeSearch();
|
||||
document.documentElement.classList.remove('rendered');
|
||||
document.title = title;
|
||||
renderContent(text);
|
||||
previewRevision = revision;
|
||||
renderContent(text, canSave);
|
||||
const headings = new Set();
|
||||
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
|
||||
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
||||
@@ -241,11 +258,15 @@ async function render({ text, fragment, scroll, title, keepPosition }) {
|
||||
if (current !== generation) return;
|
||||
const figure = document.createElement('figure');
|
||||
figure.innerHTML = svg;
|
||||
const paths = figure.querySelector('g.edgePaths');
|
||||
const labels = figure.querySelector('g.edgeLabels');
|
||||
if (paths && labels && paths.parentNode === labels.parentNode) paths.after(labels);
|
||||
block.parentElement.replaceWith(figure);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (current !== generation) return;
|
||||
const caption = document.createElement('div');
|
||||
caption.textContent = 'Invalid Mermaid diagram';
|
||||
caption.title = error instanceof Error ? error.message : String(error);
|
||||
block.parentElement.before(caption);
|
||||
}
|
||||
}
|
||||
@@ -255,6 +276,17 @@ async function render({ text, fragment, scroll, title, keepPosition }) {
|
||||
send('rendered');
|
||||
}
|
||||
|
||||
content.addEventListener('change', ({ target }) => {
|
||||
const marker = taskMarkers.get(target);
|
||||
if (!marker) return;
|
||||
if (pendingTask) {
|
||||
target.checked = !target.checked;
|
||||
return;
|
||||
}
|
||||
pendingTask = { target, checked: target.checked };
|
||||
send('save-task', { ...marker, revision: previewRevision, checked: target.checked });
|
||||
});
|
||||
|
||||
content.addEventListener('click', event => {
|
||||
const link = event.target.closest('a');
|
||||
if (!link) return;
|
||||
@@ -303,6 +335,10 @@ bridge.addEventListener('message', ({ data }) => {
|
||||
content.replaceChildren();
|
||||
}
|
||||
if (message.action === 'render') void render(message).catch(() => send('failed'));
|
||||
if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) {
|
||||
if (!message.saved) pendingTask.target.checked = !pendingTask.checked;
|
||||
pendingTask = undefined;
|
||||
}
|
||||
if (message.action === 'appearance') {
|
||||
const style = document.documentElement.style;
|
||||
style.setProperty('--markdown-width', message.width ? message.width + 'px' : 'none');
|
||||
|
||||
@@ -3,6 +3,7 @@ const terminal = new Terminal({
|
||||
fontFamily: 'Consolas, monospace',
|
||||
fontSize: 16,
|
||||
cursorBlink: false,
|
||||
cursorInactiveStyle: 'none',
|
||||
disableStdin: true,
|
||||
theme: { background: '#181818', foreground: '#e8e8e8' },
|
||||
});
|
||||
|
||||
@@ -2,6 +2,23 @@ constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MA
|
||||
auto commandHistoryKeys=defaultHistoryKeys;
|
||||
constexpr size_t commandHistoryLimit=1000;
|
||||
|
||||
std::wstring commandHistoryLabel(const std::wstring &command)
|
||||
{
|
||||
constexpr std::wstring_view prefix=L"start '";
|
||||
if(!command.starts_with(prefix) || command.size()<=prefix.size() || command.back()!=L'\'')
|
||||
return command;
|
||||
const std::wstring_view literal(command.data()+prefix.size(),command.size()-prefix.size()-1);
|
||||
std::wstring path;
|
||||
for(size_t i=0;i<literal.size();++i)
|
||||
{
|
||||
const auto character=literal[i];
|
||||
if(character==L'\'' || character==L'\u2018' || character==L'\u2019')
|
||||
if(++i==literal.size() || literal[i]!=character) return command;
|
||||
path+=character;
|
||||
}
|
||||
return fs::path(path).is_absolute()?path:command;
|
||||
}
|
||||
|
||||
bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
{
|
||||
if(keys[0]==keys[1]) return false;
|
||||
|
||||
@@ -69,7 +69,7 @@ void populateCommandHistory(HWND dialog)
|
||||
{
|
||||
return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;});
|
||||
};
|
||||
if(containsAll(command+L" "+entry.date))
|
||||
if(containsAll(command+L" "+historyLower(commandHistoryLabel(entry.command))+L" "+entry.date))
|
||||
{
|
||||
matches[0].push_back(index);
|
||||
continue;
|
||||
@@ -91,7 +91,7 @@ void populateCommandHistory(HWND dialog)
|
||||
if(first || date!=lastDate) add(date,-1);
|
||||
first=false;
|
||||
lastDate=date;
|
||||
const auto row=add(entry.command,index);
|
||||
const auto row=add(commandHistoryLabel(entry.command),index);
|
||||
if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row;
|
||||
}
|
||||
}
|
||||
@@ -159,8 +159,9 @@ void sizeCommandHistory(HWND dialog,HWND list)
|
||||
LONG longest{};
|
||||
for(const auto &entry:terminalHistory)
|
||||
{
|
||||
const auto label=commandHistoryLabel(entry.command);
|
||||
SIZE size{};
|
||||
if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast<int>(entry.command.size()),&size))
|
||||
if(GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.size()),&size))
|
||||
longest=std::max(longest,size.cx);
|
||||
}
|
||||
SelectObject(dc,previous);
|
||||
|
||||
@@ -0,0 +1,868 @@
|
||||
constexpr uint64_t compareFileLimit=2*ks::files::TextDocument::pageBytes;
|
||||
enum ComparisonColor { CompareBackground, CompareText, CompareInsert, CompareDelete, CompareReplace,
|
||||
CompareInline, ComparePadding, CompareDivider, CompareChangedText, CompareColorCount };
|
||||
constexpr const wchar_t *comparisonColorNames[]{L"Background",L"Text",L"Insertion",L"Deletion",L"Replacement",
|
||||
L"Changed fragment",L"Alignment padding",L"Divider",L"Text on changed lines"};
|
||||
constexpr wchar_t comparisonAppearanceKey[]=L"ComparisonAppearance";
|
||||
constexpr wchar_t comparisonShortcutKey[]=L"ComparisonShortcut";
|
||||
constexpr WORD defaultComparisonShortcut=MAKEWORD(VK_F11,HOTKEYF_SHIFT);
|
||||
WORD comparisonShortcut=defaultComparisonShortcut;
|
||||
constexpr int comparisonSplitScale=10000;
|
||||
|
||||
bool validComparisonShortcut(WORD shortcut)
|
||||
{
|
||||
const auto key=LOBYTE(shortcut),modifiers=HIBYTE(shortcut);
|
||||
return key>=VK_F1 && key<=VK_F12 &&
|
||||
(modifiers==(HOTKEYF_CONTROL|HOTKEYF_SHIFT) ||
|
||||
(modifiers==HOTKEYF_SHIFT && key!=VK_F4 && key!=VK_F8));
|
||||
}
|
||||
|
||||
void loadComparisonShortcut()
|
||||
{
|
||||
const auto shortcut=static_cast<WORD>(preference(comparisonShortcutKey,defaultComparisonShortcut));
|
||||
comparisonShortcut=validComparisonShortcut(shortcut)?shortcut:defaultComparisonShortcut;
|
||||
}
|
||||
|
||||
std::wstring comparisonShortcutLabel()
|
||||
{
|
||||
return std::wstring(HIBYTE(comparisonShortcut)&HOTKEYF_CONTROL?L"Ctrl+Shift+F":L"Shift+F")+
|
||||
std::to_wstring(LOBYTE(comparisonShortcut)-VK_F1+1);
|
||||
}
|
||||
|
||||
struct ComparisonAppearance
|
||||
{
|
||||
LOGFONTW font=defaultFilesFont();
|
||||
int points=defaultFontPoints;
|
||||
std::array<COLORREF,CompareColorCount> palette{RGB(255,255,255),RGB(24,24,24),RGB(177,226,184),
|
||||
RGB(249,194,194),RGB(251,224,154),RGB(245,170,90),RGB(230,230,230),RGB(160,160,160),RGB(24,24,24)};
|
||||
|
||||
bool operator==(const ComparisonAppearance &other) const
|
||||
{
|
||||
return points==other.points && palette==other.palette && !memcmp(&font,&other.font,sizeof(font));
|
||||
}
|
||||
};
|
||||
|
||||
ComparisonAppearance readComparisonAppearance()
|
||||
{
|
||||
ComparisonAppearance appearance;
|
||||
DWORD bytes=sizeof(appearance);
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,comparisonAppearanceKey,RRF_RT_REG_BINARY,nullptr,
|
||||
&appearance,&bytes)!=ERROR_SUCCESS || bytes!=sizeof(appearance) ||
|
||||
appearance.points<80 || appearance.points>240 ||
|
||||
std::any_of(appearance.palette.begin(),appearance.palette.end(),[](auto color){return color>0xffffff;}))
|
||||
return {};
|
||||
appearance.font.lfFaceName[LF_FACESIZE-1]=0;
|
||||
return appearance;
|
||||
}
|
||||
|
||||
bool saveComparisonAppearance(const ComparisonAppearance &appearance)
|
||||
{
|
||||
return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,comparisonAppearanceKey,REG_BINARY,
|
||||
&appearance,sizeof(appearance))==ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
struct CompareFile
|
||||
{
|
||||
fs::path path;
|
||||
std::wstring label;
|
||||
std::optional<FilesPeer> peer;
|
||||
std::optional<FtpProfile> ftp;
|
||||
};
|
||||
|
||||
struct CompareRow
|
||||
{
|
||||
int left=-1,right=-1;
|
||||
bool changed{};
|
||||
size_t commonStart{},commonEnd{};
|
||||
bool whitespaceOnly{};
|
||||
|
||||
bool hasChange(bool showWhitespace) const {return changed && (showWhitespace || !whitespaceOnly);}
|
||||
};
|
||||
|
||||
struct FileComparison
|
||||
{
|
||||
static constexpr std::array controls{400,401,402,403,407};
|
||||
CompareFile files[2];
|
||||
std::vector<std::wstring> lines[2];
|
||||
std::vector<CompareRow> rows;
|
||||
std::vector<int> changes,allChanges;
|
||||
bool showWhitespace{};
|
||||
RECT initialClient{};
|
||||
std::array<RECT,controls.size()> initialControls{};
|
||||
SIZE minimumWindow{};
|
||||
ComparisonAppearance appearance;
|
||||
HFONT font{};
|
||||
HBRUSH background{};
|
||||
int characterWidth=1;
|
||||
int split=comparisonSplitScale/2;
|
||||
std::optional<int> splitDragOffset;
|
||||
int zoom{},wheelRemainder{};
|
||||
|
||||
~FileComparison()
|
||||
{
|
||||
if(font) DeleteObject(font);
|
||||
if(background) DeleteObject(background);
|
||||
}
|
||||
};
|
||||
|
||||
std::map<HWND,std::unique_ptr<FileComparison>> comparisonWindows;
|
||||
|
||||
LONG comparisonSplitX(const FileComparison &comparison,LONG width)
|
||||
{
|
||||
return MulDiv(width,comparison.split,comparisonSplitScale);
|
||||
}
|
||||
|
||||
void layoutComparisonHeaders(HWND dialog,const FileComparison &comparison)
|
||||
{
|
||||
const auto list=GetDlgItem(dialog,402);
|
||||
RECT bounds{};
|
||||
GetClientRect(list,&bounds);
|
||||
MapWindowPoints(list,dialog,reinterpret_cast<POINT*>(&bounds),2);
|
||||
const auto middle=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
|
||||
const auto inset=comparison.initialControls[0].left;
|
||||
for(int side=0;side<2;++side)
|
||||
{
|
||||
const auto &initial=comparison.initialControls[side];
|
||||
const auto left=(side?middle:bounds.left)+inset;
|
||||
const auto right=(side?bounds.right:middle)-inset;
|
||||
SetWindowPos(GetDlgItem(dialog,400+side),nullptr,left,initial.top,std::max(0L,right-left),
|
||||
initial.bottom-initial.top,SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
|
||||
}
|
||||
}
|
||||
|
||||
void applyComparisonFont(HWND dialog,FileComparison &comparison)
|
||||
{
|
||||
auto font=comparison.appearance.font;
|
||||
const auto dpi=GetDpiForWindow(dialog);
|
||||
const auto points=std::clamp(comparison.appearance.points+comparison.zoom,80,240);
|
||||
comparison.zoom=points-comparison.appearance.points;
|
||||
font.lfHeight=-MulDiv(points,dpi,720);
|
||||
font.lfWidth=0;
|
||||
if(const auto next=CreateFontIndirectW(&font))
|
||||
{
|
||||
if(comparison.font) DeleteObject(comparison.font);
|
||||
comparison.font=next;
|
||||
}
|
||||
const auto list=GetDlgItem(dialog,402);
|
||||
if(const auto dc=GetDC(list))
|
||||
{
|
||||
const auto previous=SelectObject(dc,comparison.font?comparison.font:mono);
|
||||
TEXTMETRICW metrics{};
|
||||
if(GetTextMetricsW(dc,&metrics))
|
||||
{
|
||||
comparison.characterWidth=std::max(1L,metrics.tmAveCharWidth);
|
||||
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
|
||||
SendMessageW(list,LB_SETITEMHEIGHT,0,metrics.tmHeight+MulDiv(6,dpi,96));
|
||||
SendMessageW(list,LB_SETTOPINDEX,top,0);
|
||||
}
|
||||
SelectObject(dc,previous);
|
||||
ReleaseDC(list,dc);
|
||||
}
|
||||
InvalidateRect(list,nullptr,TRUE);
|
||||
}
|
||||
|
||||
void applyComparisonAppearance(HWND dialog,FileComparison &comparison)
|
||||
{
|
||||
comparison.appearance=readComparisonAppearance();
|
||||
if(const auto next=CreateSolidBrush(comparison.appearance.palette[CompareBackground]))
|
||||
{
|
||||
if(comparison.background) DeleteObject(comparison.background);
|
||||
comparison.background=next;
|
||||
}
|
||||
applyComparisonFont(dialog,comparison);
|
||||
}
|
||||
|
||||
bool zoomComparison(HWND dialog,FileComparison &comparison,WPARAM wheel)
|
||||
{
|
||||
if(!(GET_KEYSTATE_WPARAM(wheel)&MK_CONTROL)) return false;
|
||||
comparison.wheelRemainder+=GET_WHEEL_DELTA_WPARAM(wheel);
|
||||
const auto steps=comparison.wheelRemainder/WHEEL_DELTA;
|
||||
comparison.wheelRemainder%=WHEEL_DELTA;
|
||||
const auto base=comparison.appearance.points;
|
||||
const auto zoom=std::clamp(base+comparison.zoom+10*steps,80,240)-base;
|
||||
if(zoom!=comparison.zoom)
|
||||
{
|
||||
comparison.zoom=zoom;
|
||||
applyComparisonFont(dialog,comparison);
|
||||
layoutComparisonHeaders(dialog,comparison);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool handleComparisonMessage(MSG &message)
|
||||
{
|
||||
if(!message.hwnd) return false;
|
||||
const auto window=GetAncestor(message.hwnd,GA_ROOT);
|
||||
if(!comparisonWindows.contains(window)) return false;
|
||||
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
|
||||
{
|
||||
SendMessageW(window,WM_CLOSE,0,0);
|
||||
return true;
|
||||
}
|
||||
if(!IsDialogMessageW(window,&message))
|
||||
{
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::vector<std::wstring> readComparisonLines(const CompareFile &input,const std::atomic_bool &canceled)
|
||||
{
|
||||
struct TemporaryDirectory
|
||||
{
|
||||
fs::path path;
|
||||
~TemporaryDirectory()
|
||||
{
|
||||
if(path.empty()) return;
|
||||
std::error_code ignored;
|
||||
fs::remove_all(path,ignored);
|
||||
}
|
||||
} temporary;
|
||||
auto path=input.path;
|
||||
if(input.ftp || input.peer)
|
||||
{
|
||||
const auto directory=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
|
||||
requireFileOperation(fs::create_directory(directory),ERROR_ALREADY_EXISTS);
|
||||
temporary.path=directory;
|
||||
path=directory/L"file";
|
||||
CopyHost source(input.peer?&*input.peer:nullptr,input.ftp);
|
||||
const auto info=source.stat(input.path,canceled);
|
||||
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
|
||||
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
|
||||
ERROR_NOT_SUPPORTED);
|
||||
requireFileOperation(info->size<=compareFileLimit,ERROR_FILE_TOO_LARGE);
|
||||
FilesConnection local;
|
||||
const auto progress=[&](uint64_t,uint64_t){return !canceled;};
|
||||
if(source.ftp) downloadFtpFile(*source.ftp,local,input.path,path,*info,false,progress);
|
||||
else ks::lan::streamFile(*source.files,local,input.peer->id,input.path,path,info->size,
|
||||
info->modified,false,false,progress);
|
||||
}
|
||||
ks::files::TextDocument document(path,false);
|
||||
requireFileOperation(document.size()<=compareFileLimit,ERROR_FILE_TOO_LARGE);
|
||||
std::string text;
|
||||
for(uint64_t page=0;page<document.pages() && !canceled;++page) text+=document.readPage(page);
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
if(std::any_of(text.begin(),text.end(),[](unsigned char ch){
|
||||
return ch<32 && ch!='\t' && ch!='\r' && ch!='\n' && ch!='\f';
|
||||
})) throw std::runtime_error("Select two text files.");
|
||||
if(text.empty()) return {};
|
||||
const auto bytes=static_cast<int>(text.size());
|
||||
const auto count=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,nullptr,0);
|
||||
if(!count) throw std::runtime_error("Compare files supports UTF-8 and UTF-16 text.");
|
||||
std::wstring decoded(count,L'\0');
|
||||
checkFileOperation(MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,decoded.data(),count)!=0);
|
||||
std::vector<std::wstring> lines;
|
||||
size_t start=0;
|
||||
while(true)
|
||||
{
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
if(lines.size()==100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
|
||||
const auto end=decoded.find_first_of(L"\r\n",start);
|
||||
lines.push_back(decoded.substr(start,end==decoded.npos?end:end-start));
|
||||
if(end==decoded.npos) break;
|
||||
start=end+((decoded[end]==L'\r' && end+1<decoded.size() && decoded[end+1]==L'\n')?2:1);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
std::wstring_view comparisonContent(std::wstring_view line)
|
||||
{
|
||||
const auto start=line.find_first_not_of(L" \t");
|
||||
if(start==line.npos) return {};
|
||||
return line.substr(start,line.find_last_not_of(L" \t")-start+1);
|
||||
}
|
||||
|
||||
void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
|
||||
{
|
||||
const auto &left=result.lines[0],&right=result.lines[1];
|
||||
std::map<std::wstring_view,unsigned> ids;
|
||||
std::map<unsigned,unsigned> blankIds;
|
||||
unsigned nextId=1;
|
||||
const auto encode=[&](const auto &lines)
|
||||
{
|
||||
std::vector<unsigned> values;
|
||||
values.reserve(lines.size());
|
||||
unsigned previousContent=0;
|
||||
for(const auto &line:lines)
|
||||
{
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
const auto content=comparisonContent(line);
|
||||
// Blank lines can anchor alignment alongside the preceding content.
|
||||
if(content.empty())
|
||||
{
|
||||
const auto [entry,inserted]=blankIds.try_emplace(previousContent,nextId);
|
||||
nextId+=inserted;
|
||||
values.push_back(entry->second);
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto [entry,inserted]=ids.try_emplace(content,nextId);
|
||||
nextId+=inserted;
|
||||
previousContent=entry->second;
|
||||
values.push_back(previousContent);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
};
|
||||
const auto a=encode(left),b=encode(right);
|
||||
size_t prefix=0, suffix=0;
|
||||
while(prefix<a.size() && prefix<b.size() && a[prefix]==b[prefix]) ++prefix;
|
||||
while(suffix<a.size()-prefix && suffix<b.size()-prefix &&
|
||||
a[a.size()-1-suffix]==b[b.size()-1-suffix]) ++suffix;
|
||||
const auto n=static_cast<int>(a.size()-prefix-suffix),m=static_cast<int>(b.size()-prefix-suffix);
|
||||
const auto append=[&](int x,int y)
|
||||
{
|
||||
CompareRow row{x,y,x<0 || y<0 || left[x]!=right[y]};
|
||||
if(row.changed && (result.rows.empty() || !result.rows.back().changed))
|
||||
result.allChanges.push_back(static_cast<int>(result.rows.size()));
|
||||
if(row.changed && x>=0 && y>=0)
|
||||
{
|
||||
const auto &l=left[x],&r=right[y];
|
||||
row.whitespaceOnly=comparisonContent(l)==comparisonContent(r);
|
||||
const size_t length=std::min(l.size(),r.size());
|
||||
while(row.commonStart<length && l[row.commonStart]==r[row.commonStart]) ++row.commonStart;
|
||||
if(row.commonStart && l[row.commonStart-1]>=0xd800 && l[row.commonStart-1]<=0xdbff)
|
||||
--row.commonStart;
|
||||
while(row.commonEnd<length-row.commonStart &&
|
||||
l[l.size()-1-row.commonEnd]==r[r.size()-1-row.commonEnd]) ++row.commonEnd;
|
||||
if(row.commonEnd && l[l.size()-row.commonEnd]>=0xdc00 && l[l.size()-row.commonEnd]<=0xdfff)
|
||||
--row.commonEnd;
|
||||
}
|
||||
if(row.hasChange(false) && (result.rows.empty() || !result.rows.back().hasChange(false)))
|
||||
result.changes.push_back(static_cast<int>(result.rows.size()));
|
||||
result.rows.push_back(row);
|
||||
};
|
||||
const auto change=[&](size_t x,size_t y,size_t countLeft,size_t countRight)
|
||||
{
|
||||
// Prefer pairing structurally similar lines, leaving unmatched lines on their own side.
|
||||
const auto score=[](std::wstring_view l,std::wstring_view r)
|
||||
{
|
||||
if(l.empty() || r.empty()) return l.empty() && r.empty()?1u:0u;
|
||||
const auto cap=std::min({l.size(),r.size(),size_t{64}});
|
||||
size_t start=0,end=0;
|
||||
while(start<cap && l[start]==r[start]) ++start;
|
||||
while(end<cap-start && l[l.size()-1-end]==r[r.size()-1-end]) ++end;
|
||||
return 1u+static_cast<unsigned>(4*(start+end));
|
||||
};
|
||||
if(!countLeft || !countRight || countLeft>160'000/countRight)
|
||||
{
|
||||
for(size_t i=0;i<std::max(countLeft,countRight);++i)
|
||||
append(i<countLeft?static_cast<int>(x+i):-1,i<countRight?static_cast<int>(y+i):-1);
|
||||
return;
|
||||
}
|
||||
const auto stride=countRight+1;
|
||||
std::vector<std::wstring_view> l,r;
|
||||
for(size_t i=0;i<countLeft;++i) l.push_back(comparisonContent(left[x+i]));
|
||||
for(size_t j=0;j<countRight;++j) r.push_back(comparisonContent(right[y+j]));
|
||||
std::vector<unsigned> best((countLeft+1)*stride);
|
||||
for(size_t i=countLeft;i-->0;)
|
||||
for(size_t j=countRight;j-->0;)
|
||||
best[i*stride+j]=std::max({best[(i+1)*stride+j],best[i*stride+j+1],
|
||||
best[(i+1)*stride+j+1]+score(l[i],r[j])});
|
||||
size_t i=0,j=0;
|
||||
while(i<countLeft && j<countRight)
|
||||
{
|
||||
const auto pairScore=score(l[i],r[j]);
|
||||
if(pairScore && best[i*stride+j]==best[(i+1)*stride+j+1]+pairScore)
|
||||
{
|
||||
append(static_cast<int>(x+i),static_cast<int>(y+j));
|
||||
++i;
|
||||
++j;
|
||||
}
|
||||
else if(best[(i+1)*stride+j]>=best[i*stride+j+1]) append(static_cast<int>(x+i++),-1);
|
||||
else append(-1,static_cast<int>(y+j++));
|
||||
}
|
||||
while(i<countLeft) append(static_cast<int>(x+i++),-1);
|
||||
while(j<countRight) append(-1,static_cast<int>(y+j++));
|
||||
};
|
||||
for(size_t i=0;i<prefix;++i) append(static_cast<int>(i),static_cast<int>(i));
|
||||
if(n && m)
|
||||
{
|
||||
// Myers alignment. Each pass records the farthest left index per edit diagonal.
|
||||
std::vector<std::vector<int>> trace;
|
||||
const auto previousDiagonal=[](const std::vector<int> &prior,int d,int k)
|
||||
{
|
||||
if(k==-d || (k!=d && prior[(d+k-2)/2]<prior[(d+k)/2])) return k+1;
|
||||
return k-1;
|
||||
};
|
||||
bool complete=false;
|
||||
for(int d=0;!complete;++d)
|
||||
{
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
if(d>2'500) throw std::runtime_error("Too many differing lines to align in this comparison.");
|
||||
std::vector<int> level;
|
||||
level.reserve(d+1);
|
||||
for(int k=-d;k<=d;k+=2)
|
||||
{
|
||||
int x=0;
|
||||
if(d)
|
||||
{
|
||||
const auto &prior=trace.back();
|
||||
const auto previous=previousDiagonal(prior,d,k);
|
||||
x=prior[(d-1+previous)/2]+(previous<k);
|
||||
}
|
||||
int y=x-k;
|
||||
while(x<n && y<m && a[prefix+x]==b[prefix+y]) {++x;++y;}
|
||||
level.push_back(x);
|
||||
if(x>=n && y>=m) {complete=true;break;}
|
||||
}
|
||||
trace.push_back(std::move(level));
|
||||
}
|
||||
std::vector<std::pair<int,int>> matches;
|
||||
int x=n,y=m;
|
||||
for(int d=static_cast<int>(trace.size())-1;d>0;--d)
|
||||
{
|
||||
const auto &prior=trace[d-1];
|
||||
const auto previous=previousDiagonal(prior,d,x-y);
|
||||
const int startX=prior[(d-1+previous)/2],startY=startX-previous;
|
||||
while(x>startX && y>startY) {--x;--y;matches.emplace_back(x,y);}
|
||||
x=startX;
|
||||
y=startY;
|
||||
}
|
||||
while(x>0 && y>0) {--x;--y;matches.emplace_back(x,y);}
|
||||
int fromLeft=0,fromRight=0;
|
||||
for(auto it=matches.rbegin();it!=matches.rend();++it)
|
||||
{
|
||||
const auto [leftLine,rightLine]=*it;
|
||||
change(prefix+fromLeft,prefix+fromRight,leftLine-fromLeft,rightLine-fromRight);
|
||||
append(static_cast<int>(prefix+leftLine),static_cast<int>(prefix+rightLine));
|
||||
fromLeft=leftLine+1;
|
||||
fromRight=rightLine+1;
|
||||
}
|
||||
change(prefix+fromLeft,prefix+fromRight,n-fromLeft,m-fromRight);
|
||||
}
|
||||
else change(prefix,prefix,n,m);
|
||||
for(size_t i=0;i<suffix;++i)
|
||||
append(static_cast<int>(a.size()-suffix+i),static_cast<int>(b.size()-suffix+i));
|
||||
}
|
||||
|
||||
void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &item)
|
||||
{
|
||||
const auto dc=item.hDC;
|
||||
const auto bounds=item.rcItem;
|
||||
const auto fill=[&](const RECT &area,COLORREF color)
|
||||
{
|
||||
SetDCBrushColor(dc,color);
|
||||
FillRect(dc,&area,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
};
|
||||
const auto &palette=comparison.appearance.palette;
|
||||
const auto cell=comparison.characterWidth;
|
||||
fill(bounds,palette[CompareBackground]);
|
||||
if(item.itemID>=comparison.rows.size()) return;
|
||||
const auto &row=comparison.rows[item.itemID];
|
||||
const bool changed=row.hasChange(comparison.showWhitespace);
|
||||
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
|
||||
const LONG gutter=std::max(4,cell);
|
||||
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
|
||||
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
|
||||
if(changed) fill(link,highlight);
|
||||
else
|
||||
{
|
||||
const RECT divider{center,bounds.top,center+1,bounds.bottom};
|
||||
fill(divider,palette[CompareDivider]);
|
||||
}
|
||||
if(changed)
|
||||
{
|
||||
const LONG middle=(bounds.top+bounds.bottom)/2;
|
||||
const LONG start=row.left<0?bounds.top:middle,end=row.right<0?bounds.top:middle;
|
||||
SetDCPenColor(dc,palette[CompareChangedText]);
|
||||
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
|
||||
MoveToEx(dc,link.left,start,nullptr);
|
||||
LineTo(dc,link.right,end);
|
||||
SelectObject(dc,pen);
|
||||
}
|
||||
SelectObject(dc,comparison.font?comparison.font:mono);
|
||||
SetBkMode(dc,TRANSPARENT);
|
||||
const auto ink=palette[changed?CompareChangedText:CompareText];
|
||||
SetTextColor(dc,ink);
|
||||
const auto drawSide=[&](int side,int number,RECT area)
|
||||
{
|
||||
if(number<0)
|
||||
{
|
||||
fill(area,palette[ComparePadding]);
|
||||
return;
|
||||
}
|
||||
if(changed) fill(area,highlight);
|
||||
const auto numberText=std::to_wstring(number+1);
|
||||
RECT numberArea=area;
|
||||
numberArea.right=std::min(area.right,area.left+7*cell);
|
||||
DrawTextW(dc,numberText.c_str(),-1,&numberArea,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
|
||||
area.left=std::min(area.right,numberArea.right+cell);
|
||||
const auto &line=comparison.lines[side][number];
|
||||
const auto paneWidth=area.right-area.left;
|
||||
if(paneWidth<=0) return;
|
||||
const auto limit=static_cast<size_t>(paneWidth/cell+2)*4;
|
||||
auto visible=std::wstring_view(line).substr(0,limit);
|
||||
const bool clipped=visible.size()<line.size();
|
||||
if(clipped && visible.back()>=0xd800 && visible.back()<=0xdbff)
|
||||
visible.remove_suffix(1);
|
||||
if(changed && row.left>=0 && row.right>=0)
|
||||
{
|
||||
const auto width=[&](size_t chars)->LONG
|
||||
{
|
||||
if(chars>visible.size()) return paneWidth;
|
||||
RECT measured{};
|
||||
if(chars) DrawTextW(dc,visible.data(),static_cast<int>(chars),&measured,
|
||||
DT_CALCRECT|DT_SINGLELINE|DT_EXPANDTABS|DT_NOPREFIX);
|
||||
return std::min(paneWidth,measured.right);
|
||||
};
|
||||
const auto start=std::min(area.right,area.left+width(row.commonStart));
|
||||
const auto end=std::min(area.right,area.left+width(line.size()-row.commonEnd));
|
||||
const RECT changed{start,area.top,std::min(area.right,std::max(start+2,end)),area.bottom};
|
||||
fill(changed,palette[CompareInline]);
|
||||
}
|
||||
constexpr UINT flags=DT_SINGLELINE|DT_VCENTER|DT_EXPANDTABS|DT_NOPREFIX|DT_END_ELLIPSIS;
|
||||
if(clipped)
|
||||
{
|
||||
auto text=std::wstring(visible)+L"…";
|
||||
DrawTextW(dc,text.c_str(),static_cast<int>(text.size()),&area,flags);
|
||||
}
|
||||
else if(!visible.empty()) DrawTextW(dc,visible.data(),static_cast<int>(visible.size()),&area,flags);
|
||||
};
|
||||
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
|
||||
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
|
||||
if(item.itemState&ODS_SELECTED)
|
||||
{
|
||||
SetDCBrushColor(dc,ink);
|
||||
FrameRect(dc,&bounds,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
}
|
||||
|
||||
LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_KEYDOWN && (wp==VK_F7 || wp==VK_F8))
|
||||
{
|
||||
SendMessageW(GetParent(control),WM_COMMAND,wp==VK_F7?404:405,0);
|
||||
return 0;
|
||||
}
|
||||
if(GetDlgCtrlID(control)!=402) return DefSubclassProc(control,message,wp,lp);
|
||||
const auto dialog=GetParent(control);
|
||||
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!comparison) return DefSubclassProc(control,message,wp,lp);
|
||||
if(message==WM_MOUSEWHEEL && zoomComparison(dialog,*comparison,wp)) return 0;
|
||||
if(message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(control,&client);
|
||||
const auto middle=comparisonSplitX(*comparison,client.right);
|
||||
POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
if(message==WM_SETCURSOR)
|
||||
{
|
||||
if(LOWORD(lp)!=HTCLIENT) return DefSubclassProc(control,message,wp,lp);
|
||||
GetCursorPos(&point);
|
||||
ScreenToClient(control,&point);
|
||||
}
|
||||
const auto grip=MulDiv(5,GetDpiForWindow(control),96);
|
||||
if(comparison->splitDragOffset || std::abs(point.x-middle)<=grip)
|
||||
{
|
||||
SetCursor(LoadCursorW(nullptr,IDC_SIZEWE));
|
||||
if(message!=WM_SETCURSOR)
|
||||
{
|
||||
comparison->splitDragOffset=point.x-middle;
|
||||
SetCapture(control);
|
||||
if(GetCapture()!=control) comparison->splitDragOffset.reset();
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if(comparison->splitDragOffset && (message==WM_MOUSEMOVE || message==WM_LBUTTONUP))
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(control,&client);
|
||||
if(client.right>0)
|
||||
{
|
||||
constexpr int minimumShare=1500;
|
||||
const auto position=GET_X_LPARAM(lp)-*comparison->splitDragOffset;
|
||||
const auto split=std::clamp(MulDiv(position,comparisonSplitScale,client.right),
|
||||
minimumShare,comparisonSplitScale-minimumShare);
|
||||
if(split!=comparison->split)
|
||||
{
|
||||
comparison->split=split;
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
InvalidateRect(control,nullptr,FALSE);
|
||||
}
|
||||
}
|
||||
if(message==WM_LBUTTONUP) ReleaseCapture();
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_CAPTURECHANGED) comparison->splitDragOffset.reset();
|
||||
const auto result=DefSubclassProc(control,message,wp,lp);
|
||||
if(message==WM_PAINT)
|
||||
{
|
||||
RECT client{},last{};
|
||||
GetClientRect(control,&client);
|
||||
const auto count=SendMessageW(control,LB_GETCOUNT,0,0);
|
||||
if(count>0 && SendMessageW(control,LB_GETITEMRECT,count-1,reinterpret_cast<LPARAM>(&last))==LB_ERR)
|
||||
return result;
|
||||
const auto middle=comparisonSplitX(*comparison,client.right);
|
||||
const RECT blank{client.left,std::max(client.top,last.bottom),client.right,client.bottom};
|
||||
if(blank.top<blank.bottom)
|
||||
{
|
||||
const auto dc=GetDC(control);
|
||||
if(dc)
|
||||
{
|
||||
// The list box repaints its rows but can leave earlier divider marks below them.
|
||||
FillRect(dc,&blank,comparison->background?comparison->background:
|
||||
static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
|
||||
const RECT divider{middle,blank.top,middle+1,blank.bottom};
|
||||
SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]);
|
||||
FillRect(dc,÷r,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
ReleaseDC(control,dc);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void layoutComparison(HWND dialog)
|
||||
{
|
||||
const auto *comparison=reinterpret_cast<const FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!comparison || comparison->initialClient.right<=0) return;
|
||||
RECT client{};
|
||||
GetClientRect(dialog,&client);
|
||||
for(size_t i=0;i<FileComparison::controls.size();++i)
|
||||
{
|
||||
const auto id=FileComparison::controls[i];
|
||||
if(id==400 || id==401) continue;
|
||||
auto bounds=comparison->initialControls[i];
|
||||
if(id==402) bounds={0,bounds.top,client.right,client.bottom};
|
||||
SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,bounds.top,
|
||||
bounds.right-bounds.left,std::max(0L,bounds.bottom-bounds.top),
|
||||
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
|
||||
}
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
InvalidateRect(dialog,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void updateComparisonSummary(HWND dialog,const FileComparison &comparison)
|
||||
{
|
||||
const auto blocks=(comparison.showWhitespace?comparison.allChanges:comparison.changes).size();
|
||||
const auto summary=blocks==0?L"Text is identical":blocks==1?L"1 change block":
|
||||
std::to_wstring(blocks)+L" change blocks";
|
||||
SetDlgItemTextW(dialog,403,summary.c_str());
|
||||
const auto toolbar=GetDlgItem(dialog,407);
|
||||
for(const auto id:{404,405}) SendMessageW(toolbar,TB_ENABLEBUTTON,id,MAKELONG(blocks!=0,0));
|
||||
}
|
||||
|
||||
void initializeComparisonToolbar(HWND toolbar)
|
||||
{
|
||||
SendMessageW(toolbar,TB_BUTTONSTRUCTSIZE,sizeof(TBBUTTON),0);
|
||||
SendMessageW(toolbar,TB_SETEXTENDEDSTYLE,0,TBSTYLE_EX_MIXEDBUTTONS);
|
||||
SendMessageW(toolbar,TB_SETMAXTEXTROWS,1,0);
|
||||
const auto first=SendMessageW(toolbar,TB_LOADIMAGES,IDB_HIST_SMALL_COLOR,reinterpret_cast<LPARAM>(HINST_COMMCTRL));
|
||||
const auto icon=[&](int index){return first<0?I_IMAGENONE:static_cast<int>(first)+index;};
|
||||
constexpr BYTE text=BTNS_AUTOSIZE|BTNS_SHOWTEXT;
|
||||
const auto separator=MulDiv(8,GetDpiForWindow(toolbar),96);
|
||||
const TBBUTTON buttons[]{
|
||||
{icon(HIST_BACK),404,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Previous")},
|
||||
{icon(HIST_FORWARD),405,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Next")},
|
||||
{separator,0,0,BTNS_SEP,{},0,0},
|
||||
{I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Show whitespace changes")}
|
||||
};
|
||||
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
const auto list=GetDlgItem(dialog,402);
|
||||
const auto toolbar=GetDlgItem(dialog,407);
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
comparison=reinterpret_cast<FileComparison*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
GetClientRect(dialog,&comparison->initialClient);
|
||||
for(size_t i=0;i<FileComparison::controls.size();++i)
|
||||
comparison->initialControls[i]=dialogControlBounds(dialog,FileComparison::controls[i]);
|
||||
RECT window{};
|
||||
GetWindowRect(dialog,&window);
|
||||
comparison->minimumWindow={MulDiv(window.right-window.left,3,4),(window.bottom-window.top)/2};
|
||||
const auto resource=MAKEINTRESOURCEW(IDI_FILES_COMPARE);
|
||||
const auto dpi=GetDpiForWindow(dialog);
|
||||
const auto small=LoadImageW(GetModuleHandleW(nullptr),resource,IMAGE_ICON,
|
||||
GetSystemMetricsForDpi(SM_CXSMICON,dpi),GetSystemMetricsForDpi(SM_CYSMICON,dpi),LR_SHARED);
|
||||
const auto large=LoadIconW(GetModuleHandleW(nullptr),resource);
|
||||
SendMessageW(dialog,WM_SETICON,ICON_SMALL,reinterpret_cast<LPARAM>(small));
|
||||
SendMessageW(dialog,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(large));
|
||||
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,L"HrynCo.KSwitcher.Files.Compare");
|
||||
for(int side=0;side<2;++side) SetDlgItemTextW(dialog,400+side,comparison->files[side].label.c_str());
|
||||
initializeComparisonToolbar(toolbar);
|
||||
updateComparisonSummary(dialog,*comparison);
|
||||
SetWindowSubclass(list,comparisonKeys,1,0);
|
||||
SetWindowSubclass(toolbar,comparisonKeys,1,0);
|
||||
applyComparisonAppearance(dialog,*comparison);
|
||||
SendMessageW(list,LB_SETCOUNT,comparison->rows.size(),0);
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
if(!comparison->changes.empty()) SendMessageW(list,LB_SETCURSEL,comparison->changes.front(),0);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==filesPreferencesChanged && comparison)
|
||||
{
|
||||
applyComparisonAppearance(dialog,*comparison);
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE)
|
||||
{
|
||||
DestroyWindow(dialog);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_MOUSEWHEEL && comparison && zoomComparison(dialog,*comparison,wp)) return TRUE;
|
||||
if(message==WM_NCDESTROY)
|
||||
{
|
||||
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,nullptr);
|
||||
comparisonWindows.erase(dialog);
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_GETMINMAXINFO && comparison && comparison->minimumWindow.cx)
|
||||
{
|
||||
auto &size=reinterpret_cast<MINMAXINFO*>(lp)->ptMinTrackSize;
|
||||
size.x=comparison->minimumWindow.cx;
|
||||
size.y=comparison->minimumWindow.cy;
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_SIZE && wp!=SIZE_MINIMIZED)
|
||||
{
|
||||
layoutComparison(dialog);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_DRAWITEM && wp==402 && comparison)
|
||||
{
|
||||
drawComparisonRow(*comparison,*reinterpret_cast<const DRAWITEMSTRUCT*>(lp));
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CTLCOLORLISTBOX)
|
||||
return reinterpret_cast<INT_PTR>(comparison && comparison->background?comparison->background:
|
||||
GetStockObject(WHITE_BRUSH));
|
||||
if(message==WM_COMMAND && comparison)
|
||||
{
|
||||
const auto id=LOWORD(wp);
|
||||
if(id==IDCANCEL) {DestroyWindow(dialog);return TRUE;}
|
||||
if(id==406 && HIWORD(wp)==BN_CLICKED)
|
||||
{
|
||||
comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0;
|
||||
updateComparisonSummary(dialog,*comparison);
|
||||
InvalidateRect(list,nullptr,FALSE);
|
||||
return TRUE;
|
||||
}
|
||||
const auto &changes=comparison->showWhitespace?comparison->allChanges:comparison->changes;
|
||||
if((id==404 || id==405) && !changes.empty())
|
||||
{
|
||||
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
|
||||
if(id==404)
|
||||
{
|
||||
const auto previous=std::lower_bound(changes.begin(),changes.end(),current);
|
||||
if(previous!=changes.begin()) SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
|
||||
if(next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(id==402 && HIWORD(wp)==LBN_DBLCLK)
|
||||
{
|
||||
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
|
||||
if(current>=0 && static_cast<size_t>(current)<comparison->rows.size())
|
||||
{
|
||||
const auto &row=comparison->rows[current];
|
||||
const auto side=[&](int file,int line)
|
||||
{
|
||||
return line<0?std::wstring(L"—"):comparison->lines[file][line];
|
||||
};
|
||||
const auto detail=L"Left\n"+side(0,row.left)+L"\n\nRight\n"+side(1,row.right);
|
||||
showFilesNotice(dialog,detail.c_str(),L"Line details");
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDCANCEL)
|
||||
{
|
||||
*reinterpret_cast<std::atomic_bool*>(GetWindowLongPtrW(dialog,DWLP_USER))=true;
|
||||
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
|
||||
return TRUE;
|
||||
}
|
||||
return paintTextDialog(dialog,message,wp,lp,L" Compare files ");
|
||||
}
|
||||
|
||||
void compareSelectedFiles(HWND owner)
|
||||
{
|
||||
auto ¤t=panels[active],&other=panels[1-active];
|
||||
const auto selected=selectedPanelPaths(current);
|
||||
const auto opposite=selectedPanelPaths(other);
|
||||
auto state=std::make_unique<FileComparison>();
|
||||
auto &comparison=*state;
|
||||
const auto pick=[](const Panel &panel,const fs::path &path,CompareFile &file)
|
||||
{
|
||||
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
|
||||
if(ftpProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder")
|
||||
return false;
|
||||
const auto directory=path.parent_path();
|
||||
const auto tail=(directory.filename()/path.filename()).native();
|
||||
const auto location=panelLocation(panel);
|
||||
const auto label=tail+L" · "+location;
|
||||
file={path,label,panel.peer,panel.ftp};
|
||||
return true;
|
||||
};
|
||||
bool valid=false;
|
||||
if(selected.size()==2)
|
||||
valid=pick(current,selected[0],comparison.files[0]) && pick(current,selected[1],comparison.files[1]);
|
||||
else if(selected.size()==1 && opposite.size()==1)
|
||||
valid=pick(current,selected.front(),comparison.files[active]) &&
|
||||
pick(other,opposite.front(),comparison.files[1-active]);
|
||||
if(!valid)
|
||||
{
|
||||
showFilesNotice(owner,L"Mark two text files in the active panel or select one text file in each panel.",
|
||||
L"Compare files");
|
||||
return;
|
||||
}
|
||||
std::atomic_bool canceled{};
|
||||
try
|
||||
{
|
||||
{
|
||||
FileOperationUi worker;
|
||||
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
|
||||
comparisonProgressDialog,reinterpret_cast<LPARAM>(&canceled),false);
|
||||
if(!progress.window()) throw std::runtime_error("Could not open the progress dialog.");
|
||||
progress.show();
|
||||
worker.run(progress.window(),canceled,[&]
|
||||
{
|
||||
for(int side=0;side<2;++side)
|
||||
comparison.lines[side]=readComparisonLines(comparison.files[side],canceled);
|
||||
alignComparison(comparison,canceled);
|
||||
});
|
||||
}
|
||||
if(!canceled)
|
||||
{
|
||||
const auto window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(114),nullptr,
|
||||
comparisonDialog,reinterpret_cast<LPARAM>(&comparison));
|
||||
if(!window) throw std::runtime_error("Could not open the comparison window.");
|
||||
comparisonWindows.emplace(window,std::move(state));
|
||||
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
SetFocus(GetDlgItem(window,402));
|
||||
}
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(canceled || error.code().value()==ERROR_CANCELLED) return;
|
||||
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":
|
||||
fileError(error);
|
||||
showFileOperationError(owner,L"Comparison failed",detail);
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(!canceled) showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
|
||||
}
|
||||
}
|
||||
+34
-16
@@ -52,8 +52,10 @@ LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data)
|
||||
class FilesModalDialog
|
||||
{
|
||||
public:
|
||||
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
|
||||
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument)
|
||||
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument,
|
||||
bool watchOutsideClicks=true)
|
||||
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
|
||||
watchOutsideClicks_(watchOutsideClicks)
|
||||
{
|
||||
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
|
||||
}
|
||||
@@ -108,8 +110,7 @@ public:
|
||||
previous_=activeFilesDialog;
|
||||
activeFilesDialog=window_;
|
||||
entered_=true;
|
||||
if(!filesDialogMouseHook)
|
||||
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
|
||||
refreshMouseHook();
|
||||
if(GetWindowRect(owner_,&ownerBounds_))
|
||||
{
|
||||
if(!layout_) captureLayout();
|
||||
@@ -132,11 +133,7 @@ public:
|
||||
if(!entered_) return;
|
||||
entered_=false;
|
||||
activeFilesDialog=previous_;
|
||||
if(!previous_ && filesDialogMouseHook)
|
||||
{
|
||||
UnhookWindowsHookEx(filesDialogMouseHook);
|
||||
filesDialogMouseHook=nullptr;
|
||||
}
|
||||
refreshMouseHook();
|
||||
if(IsWindow(owner_) && !IsIconic(GetAncestor(owner_,GA_ROOTOWNER)))
|
||||
{
|
||||
SetActiveWindow(owner_);
|
||||
@@ -179,10 +176,15 @@ public:
|
||||
static INT_PTR run(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
|
||||
{
|
||||
FilesModalDialog dialog(instance,resource,owner,procedure,argument);
|
||||
if(!dialog.window()) return -1;
|
||||
dialog.show();
|
||||
return dialog.runModal();
|
||||
}
|
||||
|
||||
INT_PTR runModal()
|
||||
{
|
||||
if(!window_) return -1;
|
||||
show();
|
||||
MSG message{};
|
||||
while(!dialog.finished_ && IsWindow(dialog.window()))
|
||||
while(!finished_ && IsWindow(window_))
|
||||
{
|
||||
const auto status=GetMessageW(&message,nullptr,0,0);
|
||||
if(status<=0)
|
||||
@@ -190,11 +192,11 @@ public:
|
||||
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
|
||||
break;
|
||||
}
|
||||
if(handleMessage(dialog.window(),message)) continue;
|
||||
if(handleMessage(window_,message)) continue;
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
return dialog.result_;
|
||||
return result_;
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -207,7 +209,23 @@ private:
|
||||
DLGPROC procedure_;
|
||||
LPARAM argument_;
|
||||
INT_PTR result_=IDCANCEL;
|
||||
bool entered_{},finished_{};
|
||||
bool entered_{},finished_{},watchOutsideClicks_;
|
||||
|
||||
static void refreshMouseHook()
|
||||
{
|
||||
const auto *active=activeFilesDialog?
|
||||
reinterpret_cast<const FilesModalDialog*>(GetPropW(activeFilesDialog,stateProperty_)):nullptr;
|
||||
if(active && active->watchOutsideClicks_)
|
||||
{
|
||||
if(!filesDialogMouseHook)
|
||||
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
|
||||
}
|
||||
else if(filesDialogMouseHook)
|
||||
{
|
||||
UnhookWindowsHookEx(filesDialogMouseHook);
|
||||
filesDialogMouseHook=nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void captureLayout()
|
||||
{
|
||||
@@ -260,7 +278,7 @@ private:
|
||||
void fitWidth(HWND window,const RECT &owner,bool initial=false)
|
||||
{
|
||||
RECT bounds{};
|
||||
if(!GetWindowRect(window,&bounds)) return;
|
||||
if(IsZoomed(window) || !GetWindowRect(window,&bounds)) return;
|
||||
const int width=std::clamp(static_cast<int>(owner.right-owner.left)-2*ownerMargin(),
|
||||
minimumWidth_,std::max(minimumWidth_,preferredWidth_));
|
||||
const int height=bounds.bottom-bounds.top;
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
constexpr wchar_t operationPipePrefix[]=L"\\\\.\\pipe\\KSwitcher.Files.Operation.";
|
||||
constexpr DWORD operationMessageLimit=256*1024;
|
||||
|
||||
void writeElevationMessage(HANDLE pipe,const Json &message)
|
||||
{
|
||||
const auto bytes=message.dump();
|
||||
requireFileOperation(bytes.size()<=operationMessageLimit,ERROR_BUFFER_OVERFLOW);
|
||||
DWORD written{};
|
||||
checkFileOperation(WriteFile(pipe,bytes.data(),static_cast<DWORD>(bytes.size()),&written,nullptr));
|
||||
requireFileOperation(written==bytes.size(),ERROR_WRITE_FAULT);
|
||||
}
|
||||
|
||||
Json readElevationMessage(HANDLE pipe)
|
||||
{
|
||||
std::array<char,operationMessageLimit> bytes;
|
||||
DWORD read{};
|
||||
checkFileOperation(ReadFile(pipe,bytes.data(),operationMessageLimit,&read,nullptr));
|
||||
return Json::parse(bytes.data(),bytes.data()+read);
|
||||
}
|
||||
|
||||
bool localElevationPath(const fs::path &path)
|
||||
{
|
||||
const auto root=path.root_name().native();
|
||||
return path.is_absolute() && root.size()==2 && root[1]==L':' &&
|
||||
path.native().find(L'\0')==std::wstring::npos && path.has_relative_path() &&
|
||||
GetDriveTypeW(path.root_path().c_str())!=DRIVE_REMOTE;
|
||||
}
|
||||
|
||||
bool allowedElevationRequest(const Json &request)
|
||||
{
|
||||
const auto action=request.at("action").get<std::string>();
|
||||
if(action!="copy" && action!="move" && action!="mkdir" && action!="mkdir-link" &&
|
||||
action!="remove" && action!="recycle" && action!="rmdir" && action!="stat" &&
|
||||
action!="canonical" && action!="list") return false;
|
||||
if(!localElevationPath(filePath(request.at("path")))) return false;
|
||||
if(action=="copy" || action=="move" || action=="mkdir-link")
|
||||
return localElevationPath(filePath(request.at("target")));
|
||||
return true;
|
||||
}
|
||||
|
||||
DWORD serveElevatedFileOperations(const std::wstring &parent,const std::wstring &pipeName)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(!IsUserAnAdmin() || !pipeName.starts_with(operationPipePrefix)) return ERROR_ACCESS_DENIED;
|
||||
DWORD expected{};
|
||||
for(const auto ch:parent)
|
||||
{
|
||||
if(ch<L'0' || ch>L'9' || expected>(MAXDWORD-(ch-L'0'))/10) return ERROR_INVALID_PARAMETER;
|
||||
expected=expected*10+(ch-L'0');
|
||||
}
|
||||
Handle pipe{CreateFileW(pipeName.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
|
||||
SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr)};
|
||||
checkFileOperation(pipe.value!=INVALID_HANDLE_VALUE);
|
||||
ULONG server{};
|
||||
checkFileOperation(GetNamedPipeServerProcessId(pipe.value,&server));
|
||||
requireFileOperation(server==expected,ERROR_ACCESS_DENIED);
|
||||
DWORD mode=PIPE_READMODE_MESSAGE;
|
||||
checkFileOperation(SetNamedPipeHandleState(pipe.value,&mode,nullptr,nullptr));
|
||||
FilesConnection listing;
|
||||
bool more=false;
|
||||
while(true)
|
||||
{
|
||||
const auto request=readElevationMessage(pipe.value);
|
||||
Json reply;
|
||||
try
|
||||
{
|
||||
const auto action=request.at("action").get<std::string>();
|
||||
if(action=="listNext" || action=="list")
|
||||
{
|
||||
requireFileOperation(action=="listNext"?more:allowedElevationRequest(request),ERROR_ACCESS_DENIED);
|
||||
more=false;
|
||||
reply=listing.call(request);
|
||||
more=reply.value("more",false);
|
||||
}
|
||||
else
|
||||
{
|
||||
requireFileOperation(allowedElevationRequest(request),ERROR_ACCESS_DENIED);
|
||||
FilesConnection local;
|
||||
ULONGLONG lastUpdate{};
|
||||
reply=local.call(request,[&](uint64_t done,uint64_t total)
|
||||
{
|
||||
const auto now=GetTickCount64();
|
||||
if(lastUpdate && now-lastUpdate<100 && done!=total) return true;
|
||||
lastUpdate=now;
|
||||
writeElevationMessage(pipe.value,{{"progress",{done,total}}});
|
||||
return readElevationMessage(pipe.value).at("continue").get<bool>();
|
||||
});
|
||||
}
|
||||
}
|
||||
catch(const std::system_error &error) {reply={{"error",error.code().value()}};}
|
||||
catch(const std::exception &) {reply={{"error",ERROR_INVALID_DATA}};}
|
||||
writeElevationMessage(pipe.value,reply);
|
||||
}
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
const auto code=error.code().value();
|
||||
return code==ERROR_BROKEN_PIPE || code==ERROR_NO_DATA?ERROR_SUCCESS:static_cast<DWORD>(code);
|
||||
}
|
||||
catch(const std::exception &) {return ERROR_INVALID_DATA;}
|
||||
}
|
||||
|
||||
class FileOperationElevation
|
||||
{
|
||||
HWND owner_;
|
||||
FileOperationUi *ui_;
|
||||
std::atomic_bool &canceled_;
|
||||
ElevatedHelper helper_;
|
||||
bool connected_{};
|
||||
|
||||
DWORD connect()
|
||||
{
|
||||
const auto deadline=GetTickCount64()+10000;
|
||||
while(!canceled_ && GetTickCount64()<deadline)
|
||||
{
|
||||
if(ConnectNamedPipe(helper_.pipe.value,nullptr) || GetLastError()==ERROR_PIPE_CONNECTED)
|
||||
{
|
||||
ULONG client{};
|
||||
if(!GetNamedPipeClientProcessId(helper_.pipe.value,&client)) return GetLastError();
|
||||
if(client!=GetProcessId(helper_.process.value)) return ERROR_ACCESS_DENIED;
|
||||
DWORD mode=PIPE_READMODE_MESSAGE;
|
||||
if(!SetNamedPipeHandleState(helper_.pipe.value,&mode,nullptr,nullptr)) return GetLastError();
|
||||
connected_=true;
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
if(WaitForSingleObject(helper_.process.value,20)==WAIT_OBJECT_0)
|
||||
{
|
||||
DWORD result{};
|
||||
if(!GetExitCodeProcess(helper_.process.value,&result)) return GetLastError();
|
||||
return result?result:ERROR_PIPE_NOT_CONNECTED;
|
||||
}
|
||||
}
|
||||
return canceled_?ERROR_CANCELLED:ERROR_TIMEOUT;
|
||||
}
|
||||
|
||||
DWORD requestConsent(const Json &request)
|
||||
{
|
||||
if(canceled_) return ERROR_CANCELLED;
|
||||
auto paths=filePath(request.at("path")).wstring();
|
||||
if(request.contains("target")) paths+=L"\r\n"+filePath(request.at("target")).wstring();
|
||||
const auto question=L"Windows denied access to the following path:\r\n"+paths+
|
||||
L"\r\n\r\nRetry with administrator rights for the current operation?";
|
||||
if(showFilesNotice(owner_,question.c_str(),L"Access denied",{.confirm=true})!=IDYES)
|
||||
return ERROR_CANCELLED;
|
||||
const auto error=launchElevatedHelper(owner_,operationPipePrefix,L"--elevated-file-operation",
|
||||
std::to_wstring(GetCurrentProcessId()),helper_);
|
||||
SetForegroundWindow(owner_);
|
||||
return error;
|
||||
}
|
||||
|
||||
Json send(const Json &request,const ks::lan::FileProgress &progress={})
|
||||
{
|
||||
if(canceled_) return {{"error",ERROR_CANCELLED}};
|
||||
writeElevationMessage(helper_.pipe.value,request);
|
||||
for(;;)
|
||||
{
|
||||
auto message=readElevationMessage(helper_.pipe.value);
|
||||
if(!message.contains("progress")) return message;
|
||||
const auto &value=message.at("progress");
|
||||
writeElevationMessage(helper_.pipe.value,{{"continue",!canceled_ &&
|
||||
(!progress || progress(value.at(0).get<uint64_t>(),value.at(1).get<uint64_t>()))}});
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
FileOperationElevation(HWND owner,std::atomic_bool &canceled,FileOperationUi *ui=nullptr):
|
||||
owner_(owner),ui_(ui),canceled_(canceled){}
|
||||
|
||||
Json retry(const Json &request,Json reply,const ks::lan::FileProgress &progress={})
|
||||
{
|
||||
const auto failure=reply.at("error").get<DWORD>();
|
||||
if((failure!=ERROR_ACCESS_DENIED && failure!=ERROR_PRIVILEGE_NOT_HELD && failure!=ERROR_ELEVATION_REQUIRED) ||
|
||||
IsUserAnAdmin() || !allowedElevationRequest(request))
|
||||
return reply;
|
||||
if(!connected_)
|
||||
{
|
||||
auto error=ui_?ui_->invoke([&]{return requestConsent(request);}):requestConsent(request);
|
||||
if(error==ERROR_SUCCESS) error=connect();
|
||||
if(error==ERROR_CANCELLED) canceled_=true;
|
||||
if(error!=ERROR_SUCCESS) return {{"error",error}};
|
||||
}
|
||||
return send(request,progress);
|
||||
}
|
||||
|
||||
Json call(FilesConnection &local,const Json &request,const ks::lan::FileProgress &progress={})
|
||||
{
|
||||
return retry(request,local.call(request,progress),progress);
|
||||
}
|
||||
|
||||
void list(FilesConnection &local,const fs::path &path,const FileVisitor &visit)
|
||||
{
|
||||
const auto request=fileRequest("list",path);
|
||||
auto reply=local.call(request);
|
||||
const bool elevated=reply.at("error")==ERROR_ACCESS_DENIED;
|
||||
if(elevated) reply=retry(request,std::move(reply));
|
||||
listFilePages(std::move(reply),path,visit,[&]{
|
||||
const Json next{{"action","listNext"}};
|
||||
return elevated?send(next):local.call(next);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -152,7 +152,7 @@ bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
|
||||
|
||||
void addFolderShortcut(const Panel &panel,int digit)
|
||||
{
|
||||
if(panel.directory.empty()) return;
|
||||
if(panel.directory.empty() || panel.ftp) return;
|
||||
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
|
||||
panel.peer?panel.peer->name:L""},digit,{}};
|
||||
if(editFolderShortcut(GetParent(panel.list),edit))
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
struct FtpProfile
|
||||
{
|
||||
std::wstring name, host, user;
|
||||
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
|
||||
ks::Bytes secret;
|
||||
bool legacyNames{};
|
||||
};
|
||||
|
||||
std::vector<FtpProfile> ftpProfiles;
|
||||
bool ftpProfilesLoaded{};
|
||||
constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles";
|
||||
constexpr DWORD ftpProfilesMaxBytes=1024*1024;
|
||||
const fs::path ftpRoot=L"\\";
|
||||
|
||||
std::wstring ftpPath(const fs::path &path)
|
||||
{
|
||||
auto value=path.native();
|
||||
std::replace(value.begin(),value.end(),L'\\',L'/');
|
||||
return value;
|
||||
}
|
||||
|
||||
bool saveFtpProfiles(const std::vector<FtpProfile> &profiles)
|
||||
{
|
||||
auto rows=Json::array();
|
||||
for(const auto &profile:profiles)
|
||||
rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
|
||||
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
|
||||
{"legacyNames",profile.legacyNames}});
|
||||
const auto data=rows.dump();
|
||||
return data.size()<=ftpProfilesMaxBytes &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
bool loadFtpProfiles()
|
||||
{
|
||||
if(ftpProfilesLoaded) return true;
|
||||
DWORD bytes{};
|
||||
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,
|
||||
RRF_RT_REG_BINARY,nullptr,nullptr,&bytes);
|
||||
if(query==ERROR_FILE_NOT_FOUND)
|
||||
{
|
||||
ftpProfilesLoaded=true;
|
||||
return true;
|
||||
}
|
||||
if(query!=ERROR_SUCCESS || !bytes || bytes>ftpProfilesMaxBytes) return false;
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,RRF_RT_REG_BINARY,
|
||||
nullptr,data.data(),&bytes)!=ERROR_SUCCESS) return false;
|
||||
try
|
||||
{
|
||||
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
|
||||
if(!rows.is_array()) return false;
|
||||
std::vector<FtpProfile> profiles;
|
||||
for(const auto &row:rows)
|
||||
{
|
||||
const auto port=row.at("port").get<unsigned>();
|
||||
if(!port || port>65535) return false;
|
||||
FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
|
||||
ks::wide(row.at("user")),static_cast<INTERNET_PORT>(port),row.at("secret").get<ks::Bytes>(),
|
||||
row.value("legacyNames",false)};
|
||||
if(profile.name.empty() || profile.host.empty()) return false;
|
||||
profiles.push_back(std::move(profile));
|
||||
}
|
||||
ftpProfiles=std::move(profiles);
|
||||
ftpProfilesLoaded=true;
|
||||
return true;
|
||||
}
|
||||
catch(const std::exception &) {return false;}
|
||||
}
|
||||
|
||||
std::wstring ftpPassword(const FtpProfile &profile)
|
||||
{
|
||||
if(profile.secret.empty()) return {};
|
||||
auto bytes=ks::unprotect(profile.secret);
|
||||
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid FTP password");
|
||||
std::wstring password(bytes.size()/sizeof(wchar_t),L'\0');
|
||||
std::copy(bytes.begin(),bytes.end(),reinterpret_cast<unsigned char*>(password.data()));
|
||||
SecureZeroMemory(bytes.data(),bytes.size());
|
||||
return password;
|
||||
}
|
||||
|
||||
struct FtpHandle
|
||||
{
|
||||
HINTERNET value{};
|
||||
~FtpHandle() {if(value) InternetCloseHandle(value);}
|
||||
explicit FtpHandle(HINTERNET handle=nullptr):value(handle) {}
|
||||
FtpHandle(const FtpHandle &)=delete;
|
||||
FtpHandle &operator=(const FtpHandle &)=delete;
|
||||
};
|
||||
|
||||
void requireFileOperation(bool success,DWORD error)
|
||||
{
|
||||
if(!success) throw std::system_error(error,std::system_category());
|
||||
}
|
||||
|
||||
void checkFileOperation(bool success)
|
||||
{
|
||||
if(!success) requireFileOperation(false,GetLastError());
|
||||
}
|
||||
|
||||
class FtpSession
|
||||
{
|
||||
FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)};
|
||||
FtpHandle connection_;
|
||||
fs::path current_;
|
||||
UINT nameCodePage_;
|
||||
|
||||
public:
|
||||
explicit FtpSession(const FtpProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8)
|
||||
{
|
||||
checkFileOperation(internet_.value!=nullptr);
|
||||
DWORD timeout=10000, retries=1;
|
||||
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_TIMEOUT,&timeout,sizeof(timeout));
|
||||
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_RETRIES,&retries,sizeof(retries));
|
||||
InternetSetOptionW(internet_.value,INTERNET_OPTION_RECEIVE_TIMEOUT,&timeout,sizeof(timeout));
|
||||
InternetSetOptionW(internet_.value,INTERNET_OPTION_SEND_TIMEOUT,&timeout,sizeof(timeout));
|
||||
auto password=ftpPassword(profile);
|
||||
const auto user=profile.user.empty()?(password.empty()?nullptr:L"anonymous"):profile.user.c_str();
|
||||
connection_.value=InternetConnectW(internet_.value,profile.host.c_str(),profile.port,
|
||||
user,password.empty()?nullptr:password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
|
||||
const auto error=GetLastError();
|
||||
SecureZeroMemory(password.data(),password.size()*sizeof(wchar_t));
|
||||
requireFileOperation(connection_.value!=nullptr,error);
|
||||
if(!profile.legacyNames)
|
||||
FtpCommandA(handle(),FALSE,0,"OPTS UTF8 ON",0,nullptr);
|
||||
}
|
||||
|
||||
HINTERNET handle() const {return connection_.value;}
|
||||
|
||||
// WinINet's A entry points transfer FTP pathname bytes without a Unicode conversion.
|
||||
std::wstring decodeName(std::string_view bytes) const
|
||||
{
|
||||
if(bytes.empty()) return {};
|
||||
const auto length=static_cast<int>(bytes.size());
|
||||
const auto count=MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,nullptr,0);
|
||||
if(!count)
|
||||
throw std::runtime_error("The FTP server returned a name in another encoding. Check the FTP connection's file name encoding.");
|
||||
std::wstring name(count,L'\0');
|
||||
checkFileOperation(MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,name.data(),count)>0);
|
||||
return name;
|
||||
}
|
||||
|
||||
std::string encodeName(const fs::path &path) const
|
||||
{
|
||||
const auto name=ftpPath(path);
|
||||
if(name.empty()) return {};
|
||||
const auto length=static_cast<int>(name.size());
|
||||
BOOL substituted=FALSE;
|
||||
const auto legacy=nameCodePage_!=CP_UTF8;
|
||||
const auto flags=legacy?WC_NO_BEST_FIT_CHARS:WC_ERR_INVALID_CHARS;
|
||||
const auto replacement=legacy?&substituted:nullptr;
|
||||
const auto count=WideCharToMultiByte(nameCodePage_,flags,name.data(),length,nullptr,0,nullptr,replacement);
|
||||
requireFileOperation(count>0 && !substituted,ERROR_NO_UNICODE_TRANSLATION);
|
||||
std::string bytes(count,'\0');
|
||||
checkFileOperation(WideCharToMultiByte(nameCodePage_,flags,name.data(),length,bytes.data(),count,nullptr,replacement)>0);
|
||||
requireFileOperation(!substituted,ERROR_NO_UNICODE_TRANSLATION);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const fs::path &initialDirectory()
|
||||
{
|
||||
std::string bytes(32768,'\0');
|
||||
DWORD length=static_cast<DWORD>(bytes.size());
|
||||
checkFileOperation(FtpGetCurrentDirectoryA(handle(),bytes.data(),&length));
|
||||
auto initial=decodeName(bytes.c_str());
|
||||
if(initial.empty() || initial.front()!=L'/' || initial.find_first_of(L"\\\r\n")!=initial.npos)
|
||||
throw std::system_error(ERROR_BAD_PATHNAME,std::system_category());
|
||||
const auto first=initial.find_first_not_of(L'/');
|
||||
if(first==initial.npos) current_=ftpRoot;
|
||||
else
|
||||
{
|
||||
initial.erase(1,first-1);
|
||||
std::replace(initial.begin(),initial.end(),L'/',L'\\');
|
||||
current_=fs::path(initial).lexically_normal();
|
||||
if(current_.has_relative_path() && !current_.has_filename()) current_=current_.parent_path();
|
||||
}
|
||||
return current_;
|
||||
}
|
||||
|
||||
void setDirectory(const fs::path &path)
|
||||
{
|
||||
if(current_==path) return;
|
||||
checkFileOperation(FtpSetCurrentDirectoryA(handle(),encodeName(path).c_str()));
|
||||
current_=path;
|
||||
}
|
||||
};
|
||||
|
||||
DWORD listFtpDirectory(FtpSession &session,const fs::path &directory,const FileVisitor &visit,
|
||||
std::stop_token stop={})
|
||||
{
|
||||
if(stop.stop_requested()) return ERROR_CANCELLED;
|
||||
session.setDirectory(directory);
|
||||
if(stop.stop_requested()) return ERROR_CANCELLED;
|
||||
WIN32_FIND_DATAA entry{};
|
||||
const FtpHandle search{FtpFindFirstFileA(session.handle(),nullptr,&entry,
|
||||
INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE,0)};
|
||||
if(!search.value) return GetLastError();
|
||||
do
|
||||
{
|
||||
const auto name=session.decodeName(entry.cFileName);
|
||||
if(name.empty() || name==L"." || name==L".." || name.find_first_of(L"/\\:\r\n")!=name.npos)
|
||||
continue;
|
||||
ULARGE_INTEGER modified{}, size{};
|
||||
FILETIME utc{};
|
||||
if(LocalFileTimeToFileTime(&entry.ftLastWriteTime,&utc))
|
||||
{
|
||||
modified.HighPart=utc.dwHighDateTime;
|
||||
modified.LowPart=utc.dwLowDateTime;
|
||||
}
|
||||
size.HighPart=entry.nFileSizeHigh;
|
||||
size.LowPart=entry.nFileSizeLow;
|
||||
if(!visit(directory/name,{entry.dwFileAttributes,size.QuadPart,modified.QuadPart}))
|
||||
return ERROR_CANCELLED;
|
||||
} while(!stop.stop_requested() && InternetFindNextFileA(search.value,&entry));
|
||||
return stop.stop_requested()?ERROR_CANCELLED:GetLastError();
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr)
|
||||
{
|
||||
FileEntries entries;
|
||||
const auto error=listFtpDirectory(session,directory,[&](const fs::path &path,const FileInfo &info)
|
||||
{
|
||||
if(canceled && *canceled) return false;
|
||||
entries.emplace_back(path,info);
|
||||
return true;
|
||||
});
|
||||
requireFileOperation(error==ERROR_NO_MORE_FILES,error);
|
||||
return entries;
|
||||
}
|
||||
|
||||
std::optional<FileInfo> ftpEntry(const FileEntries &entries,const fs::path &path)
|
||||
{
|
||||
const auto entry=std::find_if(entries.begin(),entries.end(),
|
||||
[&](const auto &item){return item.first==path;});
|
||||
return entry==entries.end()?std::nullopt:std::optional<FileInfo>(entry->second);
|
||||
}
|
||||
|
||||
void renameFtpEntry(FtpSession &ftp,const fs::path &source,const fs::path &target)
|
||||
{
|
||||
ftp.setDirectory(source.parent_path());
|
||||
const auto oldName=ftp.encodeName(source.filename());
|
||||
const auto newName=ftp.encodeName(target.filename());
|
||||
checkFileOperation(FtpRenameFileA(ftp.handle(),oldName.c_str(),newName.c_str()));
|
||||
}
|
||||
|
||||
struct CopyHost
|
||||
{
|
||||
std::optional<FilesConnection> files;
|
||||
std::optional<FtpSession> ftp;
|
||||
FileOperationElevation *elevation{};
|
||||
fs::path listedDirectory;
|
||||
FileEntries listedEntries;
|
||||
|
||||
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile,FileOperationElevation *admin=nullptr)
|
||||
{
|
||||
if(profile) ftp.emplace(*profile);
|
||||
else files.emplace(peer);
|
||||
if(!peer && !profile) elevation=admin;
|
||||
}
|
||||
|
||||
Json request(const Json &message,const ks::lan::FileProgress &progress={})
|
||||
{
|
||||
return elevation?elevation->call(*files,message,progress):files->call(message,progress);
|
||||
}
|
||||
|
||||
const FileEntries &ftpListing(const fs::path &path,const std::atomic_bool &canceled)
|
||||
{
|
||||
if(path!=listedDirectory)
|
||||
{
|
||||
listedEntries=ftpChildren(*ftp,path,&canceled);
|
||||
listedDirectory=path;
|
||||
}
|
||||
return listedEntries;
|
||||
}
|
||||
|
||||
std::optional<FileInfo> stat(const fs::path &path,const std::atomic_bool &canceled)
|
||||
{
|
||||
return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path)));
|
||||
}
|
||||
|
||||
FileEntries children(const fs::path &path,const std::atomic_bool &canceled)
|
||||
{
|
||||
if(ftp) return ftpListing(path,canceled);
|
||||
if(!elevation) return childrenOf(*files,path);
|
||||
FileEntries entries;
|
||||
elevation->list(*files,path,[&](const fs::path &child,const FileInfo &info)
|
||||
{
|
||||
if(canceled) return false;
|
||||
entries.emplace_back(child,info);
|
||||
return true;
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
void makeDirectory(const fs::path &path)
|
||||
{
|
||||
if(!ftp)
|
||||
{
|
||||
checkFileReply(request(fileRequest("mkdir",path)));
|
||||
return;
|
||||
}
|
||||
ftp->setDirectory(path.parent_path());
|
||||
checkFileOperation(FtpCreateDirectoryA(ftp->handle(),ftp->encodeName(path.filename()).c_str()));
|
||||
listedDirectory.clear();
|
||||
}
|
||||
|
||||
void remove(const fs::path &path,bool permanent,DWORD attributes,bool readOnly)
|
||||
{
|
||||
if(ftp)
|
||||
{
|
||||
ftp->setDirectory(path.parent_path());
|
||||
const auto name=ftp->encodeName(path.filename());
|
||||
checkFileOperation(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)?
|
||||
FtpRemoveDirectoryA(ftp->handle(),name.c_str()):FtpDeleteFileA(ftp->handle(),name.c_str()));
|
||||
return;
|
||||
}
|
||||
auto message=fileRequest(permanent?"remove":"recycle",path);
|
||||
message["readOnly"]=readOnly;
|
||||
checkFileReply(request(message));
|
||||
}
|
||||
};
|
||||
|
||||
constexpr DWORD ftpCopyFlags=INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE;
|
||||
|
||||
void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &source,const fs::path &target,
|
||||
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress)
|
||||
{
|
||||
ftp.setDirectory(source.parent_path());
|
||||
const FtpHandle input{FtpOpenFileA(ftp.handle(),ftp.encodeName(source.filename()).c_str(),GENERIC_READ,ftpCopyFlags,0)};
|
||||
checkFileOperation(input.value!=nullptr);
|
||||
auto upload=fileRequest("openWrite",target);
|
||||
upload["transfer"]=ks::lan::randomHex(32);
|
||||
upload["size"]=info.size;
|
||||
try
|
||||
{
|
||||
const auto output=local.call(upload);
|
||||
checkFileReply(output);
|
||||
requireFileOperation(output.value("offset",uint64_t{1})==0,ERROR_FILE_INVALID);
|
||||
uint64_t done=0;
|
||||
ks::Bytes bytes(ks::lan::FileChunk);
|
||||
while(!progress || progress(done,info.size))
|
||||
{
|
||||
DWORD read{};
|
||||
checkFileOperation(InternetReadFile(input.value,bytes.data(),static_cast<DWORD>(bytes.size()),&read));
|
||||
if(!read)
|
||||
{
|
||||
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
|
||||
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
|
||||
checkFileReply(local.call({{"action","commit"},{"replace",replace},{"modified",info.modified}}));
|
||||
return;
|
||||
}
|
||||
requireFileOperation(read<=info.size-done,ERROR_FILE_INVALID);
|
||||
checkFileReply(local.call({{"action","write"},
|
||||
{"data",Json::binary(ks::Bytes(bytes.begin(),bytes.begin()+read))}}));
|
||||
done+=read;
|
||||
}
|
||||
requireFileOperation(false,ERROR_CANCELLED);
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
local.call({{"action","abort"}});
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &source,const fs::path &target,
|
||||
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress,
|
||||
const ks::files::RemoteTextRevision *expected=nullptr)
|
||||
{
|
||||
const auto directory=target.parent_path();
|
||||
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
|
||||
auto open=fileRequest("openRead",source);
|
||||
open["size"]=info.size;
|
||||
open["modified"]=info.modified;
|
||||
checkFileReply(local.call(open));
|
||||
ftp.setDirectory(directory);
|
||||
const auto stage=ftp.encodeName(temporary.filename());
|
||||
bool staged=false;
|
||||
try
|
||||
{
|
||||
uint64_t done=0;
|
||||
{
|
||||
FtpHandle output{FtpOpenFileA(ftp.handle(),stage.c_str(),GENERIC_WRITE,ftpCopyFlags,0)};
|
||||
checkFileOperation(output.value!=nullptr);
|
||||
staged=true;
|
||||
for(;;)
|
||||
{
|
||||
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
|
||||
const auto packet=local.call({{"action","read"}});
|
||||
checkFileReply(packet);
|
||||
const auto &bytes=packet.at("data").get_binary();
|
||||
if(bytes.empty()) break;
|
||||
requireFileOperation(bytes.size()<=info.size-done,ERROR_FILE_INVALID);
|
||||
for(DWORD offset=0;offset<bytes.size();)
|
||||
{
|
||||
DWORD written{};
|
||||
checkFileOperation(InternetWriteFile(output.value,bytes.data()+offset,
|
||||
static_cast<DWORD>(bytes.size()-offset),&written));
|
||||
requireFileOperation(written!=0,ERROR_WRITE_FAULT);
|
||||
offset+=written;
|
||||
}
|
||||
done+=bytes.size();
|
||||
}
|
||||
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
|
||||
checkFileOperation(InternetCloseHandle(output.value));
|
||||
output.value=nullptr;
|
||||
}
|
||||
checkFileReply(local.call({{"action","closeRead"}}));
|
||||
const auto entries=ftpChildren(ftp,directory);
|
||||
const auto uploaded=ftpEntry(entries,temporary);
|
||||
requireFileOperation(uploaded && uploaded->size==done,ERROR_WRITE_FAULT);
|
||||
const auto existing=ftpEntry(entries,target);
|
||||
if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified))
|
||||
throw std::runtime_error("The FTP file changed since it was opened. Your edits are still in the editor.");
|
||||
if(existing)
|
||||
requireFileOperation(replace && !(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
|
||||
ERROR_ALREADY_EXISTS);
|
||||
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
|
||||
renameFtpEntry(ftp,temporary,target);
|
||||
return *uploaded;
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
if(staged) FtpDeleteFileA(ftp.handle(),stage.c_str());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
namespace ftpDialog
|
||||
{
|
||||
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
|
||||
|
||||
std::wstring trim(std::wstring value)
|
||||
{
|
||||
const auto first=value.find_first_not_of(L" \t\r\n");
|
||||
if(first==value.npos) return {};
|
||||
return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1);
|
||||
}
|
||||
|
||||
struct Edit
|
||||
{
|
||||
FtpProfile profile;
|
||||
std::optional<size_t> index;
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" FTP connection ",false,{footer}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
auto &profile=reinterpret_cast<Edit*>(lp)->profile;
|
||||
prepareCopyDialog(dialog);
|
||||
layoutDialogContent(dialog,381);
|
||||
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL})
|
||||
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
for(const auto id:{name,host,user,password})
|
||||
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
|
||||
SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0);
|
||||
SetDlgItemTextW(dialog,name,profile.name.c_str());
|
||||
SetDlgItemTextW(dialog,host,profile.host.c_str());
|
||||
SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str());
|
||||
SetDlgItemTextW(dialog,user,profile.user.c_str());
|
||||
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
|
||||
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
|
||||
try
|
||||
{
|
||||
auto secret=ftpPassword(profile);
|
||||
SetDlgItemTextW(dialog,password,secret.c_str());
|
||||
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetWindowTextW(GetDlgItem(dialog,389),L"&Password (re-enter to replace saved password)");
|
||||
}
|
||||
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
|
||||
auto &edit=*reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
const auto invalid=[&](int field,const wchar_t *message)
|
||||
{
|
||||
showFilesNotice(dialog,message,L"FTP connection");
|
||||
SetFocus(GetDlgItem(dialog,field));
|
||||
return TRUE;
|
||||
};
|
||||
FtpProfile profile;
|
||||
profile.legacyNames=IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
|
||||
profile.name=trim(shortcutField(dialog,name));
|
||||
if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos)
|
||||
return invalid(name,L"Enter a name for this connection.");
|
||||
for(size_t i=0;i<ftpProfiles.size();++i)
|
||||
if(edit.index!=i && CompareStringOrdinal(ftpProfiles[i].name.c_str(),-1,profile.name.c_str(),-1,TRUE)==CSTR_EQUAL)
|
||||
return invalid(name,L"A connection with this name already exists.");
|
||||
profile.host=trim(shortcutField(dialog,host));
|
||||
if(profile.host.empty() || profile.host.find_first_of(L" /\\@\t\r\n")!=profile.host.npos)
|
||||
return invalid(host,L"Enter the server host name or IP address.");
|
||||
const auto value=shortcutField(dialog,port);
|
||||
const auto number=value.empty() || value.find_first_not_of(L"0123456789")!=value.npos?0:std::stoul(value);
|
||||
if(!number || number>65535) return invalid(port,L"Enter a port from 1 to 65535.");
|
||||
profile.port=static_cast<INTERNET_PORT>(number);
|
||||
profile.user=shortcutField(dialog,user);
|
||||
if(profile.user.find_first_of(L"\r\n")!=profile.user.npos)
|
||||
return invalid(user,L"Enter the user name on one line.");
|
||||
try
|
||||
{
|
||||
auto plain=shortcutField(dialog,password);
|
||||
if(!plain.empty())
|
||||
{
|
||||
const auto start=reinterpret_cast<const unsigned char*>(plain.data());
|
||||
ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t));
|
||||
SecureZeroMemory(plain.data(),plain.size()*sizeof(wchar_t));
|
||||
profile.secret=ks::protect(bytes);
|
||||
SecureZeroMemory(bytes.data(),bytes.size());
|
||||
}
|
||||
auto updated=ftpProfiles;
|
||||
if(edit.index) updated[*edit.index]=std::move(profile);
|
||||
else updated.push_back(std::move(profile));
|
||||
if(saveFtpProfiles(updated))
|
||||
{
|
||||
ftpProfiles=std::move(updated);
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
showFilesNotice(dialog,L"Could not save the FTP connection.",L"FTP connection");
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
void editFtpProfile(Panel &panel,bool create)
|
||||
{
|
||||
ftpDialog::Edit edit;
|
||||
if(!create)
|
||||
{
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(row<0 || static_cast<size_t>(row)>=ftpProfiles.size()) return;
|
||||
edit.index=static_cast<size_t>(row);
|
||||
edit.profile=ftpProfiles[*edit.index];
|
||||
}
|
||||
const auto owner=GetParent(panel.list);
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(112),owner,
|
||||
ftpDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
|
||||
for(auto &other:panels)
|
||||
{
|
||||
if(!ftpProfileList(other) || other.scan.valid()) continue;
|
||||
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(ftpProfiles.size()-1)):fs::path{};
|
||||
showFtpProfiles(other,selection);
|
||||
}
|
||||
}
|
||||
+1300
-331
File diff suppressed because it is too large.
Load diff
+97
-7
@@ -1,7 +1,12 @@
|
||||
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
|
||||
optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372;
|
||||
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions };
|
||||
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",L"Viewer",L"Editor"};
|
||||
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions, CompareFiles };
|
||||
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",
|
||||
L"Viewer",L"Editor",L"All settings",L"File comparison"};
|
||||
constexpr int comparisonFontLabel=408,comparisonChooseFont=409,comparisonColorCombo=411,
|
||||
comparisonChooseColor=412,comparisonColorValue=413,comparisonShortcutControl=415;
|
||||
constexpr int comparisonControls[]{comparisonFontLabel,comparisonChooseFont,410,comparisonColorCombo,
|
||||
comparisonChooseColor,comparisonColorValue,414,comparisonShortcutControl};
|
||||
constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background",
|
||||
L"Menu selection",L"Command bar",L"File cursor"};
|
||||
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
|
||||
@@ -89,12 +94,15 @@ struct OptionsBaseline
|
||||
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
|
||||
std::array<bool,2> wide{panels[0].wide,panels[1].wide};
|
||||
ks::files::TextSettings text=ks::files::loadTextPreferences();
|
||||
ComparisonAppearance comparison=readComparisonAppearance();
|
||||
WORD compareShortcut=comparisonShortcut;
|
||||
};
|
||||
|
||||
struct OptionsDraft
|
||||
{
|
||||
OptionsBaseline baseline;
|
||||
ks::files::TextSettings text=baseline.text;
|
||||
ComparisonAppearance comparison=baseline.comparison;
|
||||
HWND filesWindow{};
|
||||
LOGFONTW font=displayFont;
|
||||
int points=fontPoints;
|
||||
@@ -163,7 +171,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
|
||||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
|
||||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
|
||||
draft.text!=base.text;
|
||||
draft.text!=base.text || draft.comparison!=base.comparison ||
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0)!=base.compareShortcut;
|
||||
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
|
||||
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
|
||||
}
|
||||
@@ -409,6 +418,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
|
||||
return true;
|
||||
}
|
||||
|
||||
void showComparisonOptions(HWND dialog,const ComparisonAppearance &appearance)
|
||||
{
|
||||
const auto points=appearance.points;
|
||||
const auto description=std::wstring(appearance.font.lfFaceName)+L" · "+std::to_wstring(points/10)+
|
||||
(points%10?L"."+std::to_wstring(points%10):L"")+L" pt";
|
||||
SetDlgItemTextW(dialog,comparisonFontLabel,description.c_str());
|
||||
const auto index=SendDlgItemMessageW(dialog,comparisonColorCombo,CB_GETCURSEL,0,0);
|
||||
if(index<0 || index>=CompareColorCount) return;
|
||||
const auto color=appearance.palette[index];
|
||||
wchar_t hex[8]{};
|
||||
swprintf_s(hex,L"#%02X%02X%02X",unsigned(GetRValue(color)),unsigned(GetGValue(color)),unsigned(GetBValue(color)));
|
||||
SetDlgItemTextW(dialog,comparisonColorValue,hex);
|
||||
}
|
||||
|
||||
void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
{
|
||||
draft.page=page;
|
||||
@@ -420,7 +443,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
{
|
||||
title=optionsTitles[page];
|
||||
if(markdown) title=L"Markdown";
|
||||
else if(section>=0 && !textOptionsPage(page))
|
||||
else if(section>=0 && !textOptionsPage(page) && page!=CompareFiles)
|
||||
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
|
||||
(section==fileStyleSection?L"File type styles":colorNames[section]):
|
||||
page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font";
|
||||
@@ -451,6 +474,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
show(wideColumnControls,page==PanelModes && section==WideColumns);
|
||||
show(statusColumnControls,page==PanelModes && section==StatusColumns);
|
||||
show(appearanceControls,page==Appearance && section==Font);
|
||||
show(comparisonControls,page==CompareFiles);
|
||||
if(page==CompareFiles) showComparisonOptions(dialog,draft.comparison);
|
||||
show(dialogFrameControls,page==Appearance && section==DialogFrame);
|
||||
if(page==Appearance && section==DialogFrame)
|
||||
{
|
||||
@@ -524,8 +549,9 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
draft.markdownNode=nullptr;
|
||||
const auto root=add(L"All settings",allOptions,-1,TVI_ROOT);
|
||||
HTREEITEM first{},selected{};
|
||||
for(int page=PanelModes;page<allOptions;++page)
|
||||
for(int page=PanelModes;page<=CompareFiles;++page)
|
||||
{
|
||||
if(page==allOptions) continue;
|
||||
HTREEITEM category{};
|
||||
const bool wholeCategory=matches(optionsTitles[page]) || (!query.empty() && matches(L"All settings"));
|
||||
const auto addSection=[&](const wchar_t *label,int section,bool aliasMatches=false)
|
||||
@@ -562,6 +588,9 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
else if(page==CommandLine) addSection(L"Command history",0,
|
||||
matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here") ||
|
||||
matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here"));
|
||||
else if(page==CompareFiles)
|
||||
addSection(L"Font and colors",0,matches(L"Compare files shortcut") || std::any_of(std::begin(comparisonColorNames),
|
||||
std::end(comparisonColorNames),matches));
|
||||
else if(textOptionsPage(page))
|
||||
{
|
||||
const bool propertyMatches=matches(L"Tab width") ||
|
||||
@@ -611,6 +640,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
|
||||
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
|
||||
showMarkdownOptions(dialog,draft.text.markdown);
|
||||
for(const auto label:comparisonColorNames)
|
||||
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
|
||||
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_SETCURSEL,0,0);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETRULES,HKCOMB_NONE,HOTKEYF_SHIFT);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
|
||||
SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0);
|
||||
for(const auto &option:frameOptions)
|
||||
for(DWORD value=0;value<=option.maximum;++value)
|
||||
@@ -701,6 +735,28 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
showOptionsPage(dialog,*draft,Appearance,Font);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case comparisonChooseFont:
|
||||
if(chooseDisplayFont(dialog,draft->comparison.font,draft->comparison.points))
|
||||
{
|
||||
draft->comparison.font.lfHeight=draft->comparison.font.lfWidth=0;
|
||||
showComparisonOptions(dialog,draft->comparison);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
case comparisonColorCombo:
|
||||
if(HIWORD(wp)==CBN_SELCHANGE) showComparisonOptions(dialog,draft->comparison);
|
||||
return TRUE;
|
||||
case comparisonChooseColor:
|
||||
{
|
||||
const auto index=SendDlgItemMessageW(dialog,comparisonColorCombo,CB_GETCURSEL,0,0);
|
||||
if(index>=0 && index<CompareColorCount &&
|
||||
choosePanelColor(dialog,draft->comparison.palette[index],draft->custom.data()))
|
||||
{
|
||||
showComparisonOptions(dialog,draft->comparison);
|
||||
updateOptionsApply(dialog,*draft);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
case markdownWidth: case markdownSize: case markdownFamily:
|
||||
if(HIWORD(wp)==EN_CHANGE)
|
||||
{
|
||||
@@ -773,6 +829,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
return TRUE;
|
||||
case optionsReset:
|
||||
if(draft->page==allOptions || draft->page==CompareFiles)
|
||||
{
|
||||
draft->comparison=ComparisonAppearance{};
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,defaultComparisonShortcut,0);
|
||||
}
|
||||
if(draft->page==allOptions || draft->page==CommandLine)
|
||||
{
|
||||
setOptionHistoryKeys(dialog,defaultHistoryKeys);
|
||||
@@ -823,12 +884,22 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case 321: case 323:
|
||||
case 321: case 323: case comparisonShortcutControl:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case optionsApply:
|
||||
case IDOK:
|
||||
{
|
||||
const auto compareShortcut=static_cast<WORD>(
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0));
|
||||
if(!validComparisonShortcut(compareShortcut))
|
||||
{
|
||||
showFilesNotice(dialog,L"Choose Shift or Ctrl+Shift with a function key. Shift+F4 and Shift+F8 are reserved.",
|
||||
optionsTitles[CompareFiles]);
|
||||
if(IsWindowVisible(GetDlgItem(dialog,comparisonShortcutControl)))
|
||||
SetFocus(GetDlgItem(dialog,comparisonShortcutControl));
|
||||
return TRUE;
|
||||
}
|
||||
if(draft->markdownError)
|
||||
{
|
||||
if(!draft->markdownNode) SetDlgItemTextW(dialog,optionsSearch,L"");
|
||||
@@ -856,6 +927,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
const auto &base=draft->baseline;
|
||||
const auto storedComparison=readComparisonAppearance();
|
||||
const bool comparisonChanged=draft->comparison!=base.comparison;
|
||||
if(comparisonChanged && storedComparison!=base.comparison && storedComparison!=draft->comparison)
|
||||
{
|
||||
showFilesNotice(dialog,L"Comparison settings changed in another window. Reopen Options before editing them again.",
|
||||
optionsTitles[CompareFiles]);
|
||||
return TRUE;
|
||||
}
|
||||
const bool textChanged=draft->text!=base.text;
|
||||
auto textSettings=ks::files::loadTextPreferences();
|
||||
if(draft->text.markdown!=base.text.markdown)
|
||||
@@ -918,11 +997,19 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
showFilesNotice(dialog,L"Could not apply the selected font.",optionsTitles[Appearance]);
|
||||
return TRUE;
|
||||
}
|
||||
if(comparisonChanged && !saveComparisonAppearance(draft->comparison))
|
||||
{
|
||||
if(fontChanged) applyFont(owner,base.font,base.points);
|
||||
if(stylesChanged) saveFileStyles(fileStyles);
|
||||
showFilesNotice(dialog,L"Could not save comparison settings.",optionsTitles[CompareFiles]);
|
||||
return TRUE;
|
||||
}
|
||||
if(textChanged)
|
||||
{
|
||||
try { ks::files::saveTextPreferences(textSettings); }
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(comparisonChanged) saveComparisonAppearance(storedComparison);
|
||||
if(fontChanged) applyFont(owner,base.font,base.points);
|
||||
if(stylesChanged) saveFileStyles(fileStyles);
|
||||
const auto message=L"Could not save text settings. "+ks::wide(error.what());
|
||||
@@ -938,6 +1025,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto inputKeys=optionHistoryKeys(dialog);
|
||||
saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]);
|
||||
saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]);
|
||||
saveChanged(comparisonShortcutKey,compareShortcut,base.compareShortcut);
|
||||
saveChanged(ks::lan::remoteTerminalPreference,checked(optionsRemoteTerminal),base.remoteTerminal);
|
||||
saveChanged(ks::lan::remoteHibernatePreference,checked(optionsRemoteHibernate),base.remoteHibernate);
|
||||
saveChanged(ks::lan::remoteUpdatePreference,checked(optionsRemoteUpdate),base.remoteUpdate);
|
||||
@@ -972,6 +1060,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
SendMessageW(dialogOwner,filesPreferencesChanged,reinterpret_cast<WPARAM>(owner),0);
|
||||
draft->baseline=OptionsBaseline{};
|
||||
draft->text=draft->baseline.text;
|
||||
draft->comparison=draft->baseline.comparison;
|
||||
showMarkdownOptions(dialog,draft->text.markdown);
|
||||
populateTextSchemes(dialog,draft->text);
|
||||
draft->font=displayFont;
|
||||
@@ -987,6 +1076,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,274,panels[1].wide);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
|
||||
@@ -1010,7 +1100,7 @@ void runOptions(HWND owner,int page)
|
||||
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
|
||||
const DWORD initial=static_cast<DWORD>((page<<8)|1);
|
||||
const auto saved=preference(optionsLocationKey,initial);
|
||||
draft.location=(saved>>8)<=allOptions?saved:initial;
|
||||
draft.location=(saved>>8)<=CompareFiles?saved:initial;
|
||||
draft.page=static_cast<int>(draft.location>>8);
|
||||
draft.section=static_cast<int>(draft.location&255)-1;
|
||||
std::copy(std::begin(colors),std::end(colors),draft.palette.begin());
|
||||
|
||||
@@ -128,6 +128,7 @@ struct FileRowStyle
|
||||
{
|
||||
COLORREF foreground,background;
|
||||
unsigned decorations{};
|
||||
bool operator==(const FileRowStyle &) const = default;
|
||||
};
|
||||
FileRowStyle resolveFileStyle(std::wstring_view extension,bool file,bool dimmed,bool protectedRow,
|
||||
COLORREF foreground,COLORREF background,const std::vector<FileStyle> &styles=fileStyles,
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
#ifdef __MINGW32__
|
||||
__CRT_UUID_DECL(ICoreWebView2_3, 0xA0D6DF20, 0x3B92, 0x416D, 0xAA, 0x0C, 0x43, 0x7A, 0x9C, 0x72, 0x78, 0x57)
|
||||
__CRT_UUID_DECL(ICoreWebView2Controller2, 0xc979903e, 0xd4ca, 0x4228, 0x92, 0xeb, 0x47, 0xee, 0x3f, 0xa9, 0x6e, 0xab)
|
||||
__CRT_UUID_DECL(ICoreWebView2ControllerOptions3, 0xb32b191a, 0x8998, 0x57ca, 0xb7, 0xcb, 0xe0, 0x46, 0x17, 0xe4, 0xce, 0x4a)
|
||||
__CRT_UUID_DECL(ICoreWebView2Environment10, 0xee0eb9df, 0x6f12, 0x46ce, 0xb5, 0x3f, 0x3f, 0x47, 0xb9, 0xc9, 0x28, 0xe0)
|
||||
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler, 0x4e8a3389, 0xc9d8, 0x4bd2, 0xb6, 0xb5, 0x12, 0x4f, 0xee, 0x6c, 0xc1, 0x4d)
|
||||
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4819f3, 0xc9b7, 0x4260, 0x81, 0x27, 0xc9, 0xf5, 0xbd, 0xe7, 0xf6, 0x8c)
|
||||
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
|
||||
@@ -16,6 +19,8 @@ __CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
inline constexpr COLORREF terminalSurface=RGB(24,24,24);
|
||||
|
||||
template<class Interface, class... Args>
|
||||
class TerminalCallback final : public Interface
|
||||
{
|
||||
@@ -56,6 +61,7 @@ class FilesTerminalView
|
||||
RECT bounds{};
|
||||
bool ready{};
|
||||
bool visible{};
|
||||
bool waitForReady{};
|
||||
public:
|
||||
~FilesTerminalView() { close(); }
|
||||
void focus()
|
||||
@@ -94,9 +100,10 @@ public:
|
||||
RECT current{};
|
||||
if(FAILED(controller->get_Bounds(¤t)) || !EqualRect(¤t,&bounds))
|
||||
controller->put_Bounds(bounds);
|
||||
const bool showController=show && (!waitForReady || ready);
|
||||
BOOL currentVisibility{};
|
||||
if(FAILED(controller->get_IsVisible(¤tVisibility)) || !!currentVisibility!=show)
|
||||
controller->put_IsVisible(show);
|
||||
if(FAILED(controller->get_IsVisible(¤tVisibility)) || !!currentVisibility!=showController)
|
||||
controller->put_IsVisible(showController);
|
||||
}
|
||||
void close()
|
||||
{
|
||||
@@ -140,6 +147,9 @@ public:
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
|
||||
const auto assets=folder/L"terminal";
|
||||
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
|
||||
waitForReady=!markdown;
|
||||
constexpr COREWEBVIEW2_COLOR background{
|
||||
255,GetRValue(terminalSurface),GetGValue(terminalSurface),GetBValue(terminalSurface)};
|
||||
lifetime=std::make_shared<int>(0);
|
||||
const std::weak_ptr<int> alive=lifetime;
|
||||
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
|
||||
@@ -153,6 +163,12 @@ public:
|
||||
if(alive.expired()) return S_OK;
|
||||
if(FAILED(result) || !view) { failed(); return S_OK; }
|
||||
controller=view;
|
||||
if(!markdown)
|
||||
{
|
||||
view->put_IsVisible(FALSE);
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2Controller2> colors;
|
||||
if(SUCCEEDED(controller.As(&colors))) colors->put_DefaultBackgroundColor(background);
|
||||
}
|
||||
view->get_CoreWebView2(&web);
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
|
||||
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
|
||||
@@ -207,7 +223,11 @@ public:
|
||||
uri==source &&
|
||||
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
|
||||
{
|
||||
if(wcscmp(value,L"ready")==0) ready=true;
|
||||
if(!ready && wcscmp(value,L"ready")==0)
|
||||
{
|
||||
ready=true;
|
||||
if(waitForReady) layout(bounds,visible);
|
||||
}
|
||||
if(ready) receive(value);
|
||||
}
|
||||
CoTaskMemFree(value);
|
||||
@@ -222,6 +242,18 @@ public:
|
||||
layout(bounds,visible);
|
||||
return S_OK;
|
||||
});
|
||||
if(!markdown)
|
||||
{
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2Environment10> configurable;
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions> options;
|
||||
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions3> colors;
|
||||
if(SUCCEEDED(env->QueryInterface(IID_PPV_ARGS(&configurable))) &&
|
||||
SUCCEEDED(configurable->CreateCoreWebView2ControllerOptions(&options)) &&
|
||||
SUCCEEDED(options.As(&colors)) &&
|
||||
SUCCEEDED(colors->put_DefaultBackgroundColor(background)) &&
|
||||
SUCCEEDED(configurable->CreateCoreWebView2ControllerWithOptions(host,options.Get(),completed.Get())))
|
||||
return S_OK;
|
||||
}
|
||||
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
|
||||
return S_OK;
|
||||
});
|
||||
|
||||
+142
-42
@@ -38,6 +38,15 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
|
||||
return result;
|
||||
}
|
||||
|
||||
HANDLE trackReplacement(const std::filesystem::path &path)
|
||||
{
|
||||
// A metadata-only handle survives the rename without blocking ReplaceFile.
|
||||
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
|
||||
return handle;
|
||||
}
|
||||
|
||||
uint64_t fileSize(HANDLE file)
|
||||
{
|
||||
LARGE_INTEGER size{};
|
||||
@@ -97,10 +106,87 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
|
||||
if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file");
|
||||
return path;
|
||||
}
|
||||
|
||||
bool isUtf16(TextEncoding encoding)
|
||||
{
|
||||
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
|
||||
}
|
||||
|
||||
TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(std::move(path)), editable_(editable)
|
||||
std::string_view signature(TextEncoding encoding)
|
||||
{
|
||||
switch(encoding)
|
||||
{
|
||||
case TextEncoding::utf16le: return "\xff\xfe";
|
||||
case TextEncoding::utf16be: return "\xfe\xff";
|
||||
case TextEncoding::utf8: return "\xef\xbb\xbf";
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
|
||||
{
|
||||
const int length=static_cast<int>(bytes.size());
|
||||
const auto required=MultiByteToWideChar(codePage,flags,bytes.data(),length,nullptr,0);
|
||||
if(!required) fail("Decode text");
|
||||
std::wstring units(required,L'\0');
|
||||
if(!MultiByteToWideChar(codePage,flags,bytes.data(),length,units.data(),required)) fail("Decode text");
|
||||
return units;
|
||||
}
|
||||
|
||||
std::string encode(std::string_view utf8,TextEncoding encoding)
|
||||
{
|
||||
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
|
||||
const auto units=decodeMultibyte(utf8,CP_UTF8,MB_ERR_INVALID_CHARS);
|
||||
if(encoding==TextEncoding::windows1252)
|
||||
{
|
||||
BOOL substituted{};
|
||||
const int length=static_cast<int>(units.size());
|
||||
const auto required=WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,
|
||||
nullptr,0,nullptr,&substituted);
|
||||
if(!required) fail("Encode Windows-1252");
|
||||
if(substituted) throw std::runtime_error("Some characters cannot be saved as Windows-1252. Choose a Unicode encoding.");
|
||||
std::string bytes(required,'\0');
|
||||
if(!WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,bytes.data(),required,nullptr,&substituted))
|
||||
fail("Encode Windows-1252");
|
||||
return bytes;
|
||||
}
|
||||
std::string bytes(units.size()*2,'\0');
|
||||
const size_t low=encoding==TextEncoding::utf16le?0:1;
|
||||
for(size_t i=0;i<units.size();++i)
|
||||
{
|
||||
bytes[2*i+low]=static_cast<char>(units[i]&0xff);
|
||||
bytes[2*i+1-low]=static_cast<char>(units[i]>>8);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
std::string convertLineEndings(std::string_view text,TextLineEnding ending)
|
||||
{
|
||||
if(ending==TextLineEnding::preserve) return std::string(text);
|
||||
const std::string_view replacement=ending==TextLineEnding::crlf?"\r\n":ending==TextLineEnding::lf?"\n":"\r";
|
||||
std::string result;
|
||||
result.reserve(text.size());
|
||||
for(size_t start=0;start<text.size();)
|
||||
{
|
||||
const auto next=text.find_first_of("\r\n",start);
|
||||
result.append(text.substr(start,next==text.npos?text.npos:next-start));
|
||||
if(next==text.npos) break;
|
||||
result.append(replacement);
|
||||
start=next+1;
|
||||
if(text[next]=='\r' && start<text.size() && text[start]=='\n') ++start;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
|
||||
: path_(std::move(path)), editable_(editable)
|
||||
{
|
||||
if(path_.empty())
|
||||
{
|
||||
if(encoding!=TextEncoding::automatic) encoding_=encoding;
|
||||
return;
|
||||
}
|
||||
File source{openSource(path_, editable)};
|
||||
if (editable)
|
||||
{
|
||||
@@ -115,13 +201,15 @@ TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(st
|
||||
}
|
||||
size_ = fileSize(source.handle);
|
||||
const auto prefix = read(source.handle, 0, static_cast<size_t>(std::min<uint64_t>(3, size_)));
|
||||
if (prefix.starts_with("\xef\xbb\xbf")) bom_ = 3;
|
||||
else if (prefix.starts_with("\xff\xfe") || prefix.starts_with("\xfe\xff"))
|
||||
if(encoding==TextEncoding::automatic)
|
||||
{
|
||||
encoding_ = prefix.starts_with("\xff") ? Encoding::utf16le : Encoding::utf16be;
|
||||
bom_ = 2;
|
||||
if (size_ % 2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
|
||||
encoding=TextEncoding::utf8;
|
||||
for(const auto candidate:{TextEncoding::utf16le,TextEncoding::utf16be})
|
||||
if(prefix.starts_with(signature(candidate))) encoding=candidate;
|
||||
}
|
||||
encoding_=encoding;
|
||||
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
|
||||
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
|
||||
source_ = source.release();
|
||||
}
|
||||
|
||||
@@ -135,8 +223,9 @@ const wchar_t *TextDocument::encodingName() const
|
||||
{
|
||||
switch (encoding_)
|
||||
{
|
||||
case Encoding::utf16le: return L"UTF-16 LE";
|
||||
case Encoding::utf16be: return L"UTF-16 BE";
|
||||
case TextEncoding::utf16le: return L"UTF-16 LE";
|
||||
case TextEncoding::utf16be: return L"UTF-16 BE";
|
||||
case TextEncoding::windows1252: return L"Windows-1252";
|
||||
default: return bom_ ? L"UTF-8 BOM" : L"UTF-8";
|
||||
}
|
||||
}
|
||||
@@ -160,40 +249,45 @@ uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
|
||||
if (page >= pages()) return size_;
|
||||
|
||||
const auto offset = bom_ + page * pageBytes;
|
||||
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
|
||||
const auto unit = isUtf16(encoding_) ? 2u : 1u;
|
||||
const auto sample = read(source, offset - unit,
|
||||
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
|
||||
const auto getUnit = [&](size_t i) -> unsigned {
|
||||
const auto first = static_cast<unsigned char>(sample[i]);
|
||||
if (unit == 1) return first;
|
||||
const auto second = static_cast<unsigned char>(sample[i + 1]);
|
||||
return encoding_ == Encoding::utf16le ? first | (second << 8) : (first << 8) | second;
|
||||
return encoding_ == TextEncoding::utf16le ? first | (second << 8) : (first << 8) | second;
|
||||
};
|
||||
if (getUnit(0) == '\n') return offset;
|
||||
for (size_t i = unit; i + unit < sample.size(); i += unit)
|
||||
if (getUnit(i) == '\n') return offset + i;
|
||||
|
||||
size_t i = unit;
|
||||
if (unit == 1)
|
||||
if (encoding_ == TextEncoding::utf8)
|
||||
{
|
||||
// Advance past at most one UTF-8 code point, even on malformed input.
|
||||
while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i;
|
||||
}
|
||||
else if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
|
||||
else if (isUtf16(encoding_))
|
||||
if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
|
||||
if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit;
|
||||
return offset + i - unit;
|
||||
}
|
||||
|
||||
std::string TextDocument::decode(std::string bytes) const
|
||||
{
|
||||
if (encoding_ == Encoding::utf8 || bytes.empty()) return bytes;
|
||||
if (encoding_ == TextEncoding::utf8 || bytes.empty()) return bytes;
|
||||
std::wstring units;
|
||||
units.resize(bytes.size() / 2);
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
if(encoding_==TextEncoding::windows1252) units=decodeMultibyte(bytes,1252,0);
|
||||
else
|
||||
{
|
||||
const auto a = static_cast<unsigned char>(bytes[2 * i]);
|
||||
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
|
||||
units[i] = static_cast<wchar_t>(encoding_ == Encoding::utf16le ? a | (b << 8) : (a << 8) | b);
|
||||
units.resize(bytes.size() / 2);
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
{
|
||||
const auto a = static_cast<unsigned char>(bytes[2 * i]);
|
||||
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
|
||||
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
|
||||
}
|
||||
}
|
||||
const auto length = static_cast<int>(units.size());
|
||||
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
|
||||
@@ -204,25 +298,6 @@ std::string TextDocument::decode(std::string bytes) const
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string TextDocument::encode(std::string_view utf8) const
|
||||
{
|
||||
if (encoding_ == Encoding::utf8 || utf8.empty()) return std::string(utf8);
|
||||
const auto length = static_cast<int>(utf8.size());
|
||||
const int required = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, nullptr, 0);
|
||||
if (!required) fail("Encode UTF-16");
|
||||
std::wstring units(required, L'\0');
|
||||
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, units.data(), required))
|
||||
fail("Encode UTF-16");
|
||||
std::string bytes(units.size() * 2, '\0');
|
||||
const int low = encoding_ == Encoding::utf16le ? 0 : 1;
|
||||
for (size_t i = 0; i < units.size(); ++i)
|
||||
{
|
||||
bytes[2 * i + low] = static_cast<char>(units[i] & 0xff);
|
||||
bytes[2 * i + 1 - low] = static_cast<char>(units[i] >> 8);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
std::string TextDocument::readPage(uint64_t page) const
|
||||
{
|
||||
if (const auto it = changes_.find(page); it != changes_.end())
|
||||
@@ -232,6 +307,7 @@ std::string TextDocument::readPage(uint64_t page) const
|
||||
|
||||
std::string TextDocument::readOriginal(uint64_t page) const
|
||||
{
|
||||
if(path_.empty()) return {};
|
||||
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
|
||||
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
|
||||
const auto start = boundary(page,source);
|
||||
@@ -298,17 +374,14 @@ bool TextDocument::save()
|
||||
for (const auto &[page, change] : changes_)
|
||||
{
|
||||
copyUntil(offset, boundary(page));
|
||||
append(encode(read(spool_, change.offset, change.size)));
|
||||
append(encode(read(spool_, change.offset, change.size),encoding_));
|
||||
offset = boundary(page + 1);
|
||||
}
|
||||
copyUntil(offset, size_);
|
||||
if (!FlushFileBuffers(output.handle)) fail("Flush saved file");
|
||||
CloseHandle(output.release());
|
||||
|
||||
// A metadata-only handle survives the rename without blocking ReplaceFile's exclusive open.
|
||||
File replacement{CreateFileW(pending.path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)};
|
||||
if (replacement.handle == INVALID_HANDLE_VALUE) fail("Track replacement file");
|
||||
File replacement{trackReplacement(pending.path)};
|
||||
File current{openSource(path_, true)};
|
||||
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
|
||||
const auto backup = temporaryPath(path_.parent_path());
|
||||
@@ -336,4 +409,31 @@ bool TextDocument::save()
|
||||
spoolSize_ = 0;
|
||||
return source_ != INVALID_HANDLE_VALUE;
|
||||
}
|
||||
|
||||
bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
|
||||
{
|
||||
if(!path_.empty() || !editable_) throw std::logic_error("The document is not a new editable file.");
|
||||
if(format.encoding==TextEncoding::automatic) format.encoding=TextEncoding::utf8;
|
||||
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
|
||||
const auto bom=format.bom?signature(format.encoding):std::string_view{};
|
||||
PendingSave pending;
|
||||
File output;
|
||||
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
|
||||
write(output.handle,bom);
|
||||
write(output.handle,bytes);
|
||||
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
|
||||
CloseHandle(output.release());
|
||||
File replacement{trackReplacement(pending.path)};
|
||||
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Create new file");
|
||||
pending.path.clear();
|
||||
path_=std::move(path);
|
||||
encoding_=format.encoding;
|
||||
bom_=bom.size();
|
||||
size_=bom_+bytes.size();
|
||||
changes_.clear();
|
||||
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
|
||||
spoolSize_=0;
|
||||
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
|
||||
return source_!=INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,24 @@
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 };
|
||||
enum class TextLineEnding { preserve, crlf, lf, cr };
|
||||
|
||||
struct TextSaveFormat
|
||||
{
|
||||
TextEncoding encoding=TextEncoding::utf8;
|
||||
bool bom{};
|
||||
TextLineEnding lineEnding=TextLineEnding::preserve;
|
||||
};
|
||||
|
||||
class TextDocument
|
||||
{
|
||||
public:
|
||||
static constexpr uint64_t pageBytes = 1024 * 1024;
|
||||
static constexpr size_t editLimit = 8 * pageBytes;
|
||||
|
||||
explicit TextDocument(std::filesystem::path path, bool editable = true);
|
||||
explicit TextDocument(std::filesystem::path path, bool editable = true,
|
||||
TextEncoding encoding=TextEncoding::automatic);
|
||||
~TextDocument();
|
||||
TextDocument(const TextDocument &) = delete;
|
||||
TextDocument &operator=(const TextDocument &) = delete;
|
||||
@@ -29,10 +40,11 @@ public:
|
||||
bool modified() const { return !changes_.empty(); }
|
||||
bool modifiedWith(uint64_t page, std::string_view current) const;
|
||||
bool save();
|
||||
bool saveNew(std::filesystem::path path, TextSaveFormat format);
|
||||
const wchar_t *encodingName() const;
|
||||
TextEncoding encoding() const { return encoding_; }
|
||||
|
||||
private:
|
||||
enum class Encoding { utf8, utf16le, utf16be };
|
||||
struct Change { uint64_t offset; size_t size; };
|
||||
|
||||
std::filesystem::path path_;
|
||||
@@ -40,13 +52,12 @@ private:
|
||||
HANDLE spool_ = INVALID_HANDLE_VALUE;
|
||||
uint64_t size_{}, spoolSize_{};
|
||||
size_t bom_{};
|
||||
Encoding encoding_ = Encoding::utf8;
|
||||
TextEncoding encoding_ = TextEncoding::utf8;
|
||||
bool editable_;
|
||||
std::map<uint64_t, Change> changes_;
|
||||
|
||||
std::string decode(std::string bytes) const;
|
||||
uint64_t boundary(uint64_t page,HANDLE source) const;
|
||||
std::string readOriginal(uint64_t page) const;
|
||||
std::string encode(std::string_view utf8) const;
|
||||
};
|
||||
}
|
||||
+376
-107
@@ -582,12 +582,59 @@ INT_PTR CALLBACK searchDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM l
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
RemoteTextSource lanTextSource(const lan::FilesPeer &peer)
|
||||
{
|
||||
return {peer.id,peer.name,
|
||||
[peer](const std::filesystem::path &original,const std::filesystem::path &cache,
|
||||
bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit)
|
||||
{
|
||||
lan::FilesConnection source(&peer),target;
|
||||
const auto info=source.call(lan::fileRequest("stat",original));
|
||||
lan::checkFileReply(info);
|
||||
const bool canCommit=info.value("editCommit",false);
|
||||
const bool readOnly=info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY;
|
||||
if(edit && !canCommit)
|
||||
throw std::runtime_error("Update KSwitcher on the remote computer to edit this file.");
|
||||
if(edit && readOnly) throw std::runtime_error("The remote file is read-only.");
|
||||
const RemoteTextRevision revision{info.at("size"),info.at("modified"),canCommit && !readOnly};
|
||||
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);
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
target.call({{"action","abort"}});
|
||||
throw;
|
||||
}
|
||||
return revision;
|
||||
},
|
||||
[peer](const std::filesystem::path &original,const std::filesystem::path &cache,
|
||||
const RemoteTextRevision &revision)
|
||||
{
|
||||
lan::FilesConnection source,target(&peer);
|
||||
const auto info=source.call(lan::fileRequest("stat",cache));
|
||||
lan::checkFileReply(info);
|
||||
const RemoteTextRevision local{info.at("size"),info.at("modified"),revision.editable};
|
||||
const lan::FileRevision expected{revision.size,revision.modified};
|
||||
try { lan::streamFile(source,target,"Files editor",cache,original,local.size,local.modified,true,false,{},&expected); }
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(error.code().value()==ERROR_FILE_INVALID)
|
||||
throw std::runtime_error("The remote file changed since it was opened. Your edits are still in the editor.");
|
||||
throw;
|
||||
}
|
||||
return local;
|
||||
}};
|
||||
}
|
||||
|
||||
struct RemoteTextFile
|
||||
{
|
||||
lan::FilesPeer peer;
|
||||
RemoteTextSource source;
|
||||
std::filesystem::path original,cache;
|
||||
lan::FileRevision revision{};
|
||||
bool editable{};
|
||||
RemoteTextRevision revision{};
|
||||
|
||||
RemoteTextFile(const RemoteTextSource &backend,const std::filesystem::path &path):source(backend),original(path) {}
|
||||
|
||||
~RemoteTextFile()
|
||||
{
|
||||
@@ -597,57 +644,22 @@ struct RemoteTextFile
|
||||
std::filesystem::remove(cache.parent_path(),ignored);
|
||||
}
|
||||
|
||||
static lan::FileRevision stat(lan::FilesConnection &host,const std::filesystem::path &path)
|
||||
{
|
||||
const auto reply=host.call(lan::fileRequest("stat",path));
|
||||
lan::checkFileReply(reply);
|
||||
return {reply.at("size").get<uint64_t>(),reply.at("modified").get<uint64_t>()};
|
||||
}
|
||||
|
||||
void download(bool edit,const lan::FileProgress &progress,uint64_t sizeLimit=UINT64_MAX)
|
||||
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
|
||||
throw std::runtime_error("Cannot create a temporary directory for the LAN file.");
|
||||
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
|
||||
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
|
||||
if(!std::filesystem::create_directory(directory))
|
||||
throw std::runtime_error("Cannot create a temporary directory for the LAN file.");
|
||||
cache=directory/original.filename();
|
||||
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);
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
target.call({{"action","abort"}});
|
||||
throw;
|
||||
}
|
||||
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
|
||||
cache=directory/L"content";
|
||||
revision=source.download(original,cache,edit,progress,sizeLimit);
|
||||
}
|
||||
|
||||
void upload()
|
||||
{
|
||||
lan::FilesConnection source,target(&peer);
|
||||
const auto local=stat(source,cache);
|
||||
try { lan::streamFile(source,target,"Files editor",cache,original,local.size,local.modified,true,false,{},&revision); }
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(error.code().value()==ERROR_FILE_INVALID)
|
||||
throw std::runtime_error("The remote file changed since it was opened. Your edits are still in the editor.");
|
||||
throw;
|
||||
}
|
||||
revision=local;
|
||||
revision=source.upload(original,cache,revision);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -688,7 +700,7 @@ std::filesystem::path markdownTarget(const std::filesystem::path &document,std::
|
||||
return (document.parent_path()/relative).lexically_normal();
|
||||
}
|
||||
|
||||
std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer *peer,
|
||||
std::string markdownImage(const std::filesystem::path &path,const RemoteTextSource *backend,
|
||||
const std::shared_ptr<std::atomic<bool>> &cancel)
|
||||
{
|
||||
auto extension=path.extension().wstring();
|
||||
@@ -702,10 +714,10 @@ std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer
|
||||
constexpr uint64_t limit=16*1024*1024;
|
||||
auto source=path;
|
||||
std::optional<RemoteTextFile> fetched;
|
||||
if(peer)
|
||||
if(backend)
|
||||
{
|
||||
if(*cancel) return {};
|
||||
fetched.emplace(RemoteTextFile{*peer,path});
|
||||
fetched.emplace(*backend,path);
|
||||
fetched->download(false,[&](uint64_t,uint64_t){return !*cancel;},limit);
|
||||
source=fetched->cache;
|
||||
}
|
||||
@@ -728,14 +740,19 @@ std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer
|
||||
class TextWindow
|
||||
{
|
||||
public:
|
||||
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()),
|
||||
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend,
|
||||
std::string_view fragment,TextOpenOptions options)
|
||||
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
search{dialogs}, previewFragment(fragment)
|
||||
{
|
||||
if (peer) remote=std::make_unique<RemoteTextFile>(RemoteTextFile{*peer,original});
|
||||
else document=std::make_unique<TextDocument>(original,edit);
|
||||
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
|
||||
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
|
||||
if(options.encoding!=TextEncoding::automatic)
|
||||
{
|
||||
newFormat.encoding=options.encoding;
|
||||
newFormat.bom=options.encoding==TextEncoding::utf16le || options.encoding==TextEncoding::utf16be;
|
||||
}
|
||||
for (int index = 0; index < GetLexerCount(); ++index)
|
||||
{
|
||||
char name[128]{};
|
||||
@@ -764,6 +781,9 @@ private:
|
||||
std::unique_ptr<TextDocument> document;
|
||||
std::wstring filename;
|
||||
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
|
||||
bool draft{};
|
||||
TextSaveFormat newFormat;
|
||||
std::filesystem::path pendingSavePath;
|
||||
HICON smallIcon{},largeIcon{};
|
||||
TextPreferences prefs;
|
||||
TextWindowFont filesFont;
|
||||
@@ -796,6 +816,16 @@ private:
|
||||
bool operator==(const FileStamp &) const = default;
|
||||
};
|
||||
std::optional<FileStamp> previewStamp;
|
||||
struct MarkdownTask
|
||||
{
|
||||
uint64_t revision;
|
||||
size_t line,column;
|
||||
bool checked;
|
||||
};
|
||||
std::string previewText;
|
||||
uint64_t previewRevision{};
|
||||
std::optional<MarkdownTask> pendingTask;
|
||||
std::optional<size_t> taskOffset;
|
||||
std::string previewFragment;
|
||||
struct PreviewLocation
|
||||
{
|
||||
@@ -838,6 +868,7 @@ private:
|
||||
static constexpr UINT openPreviewLink = WM_APP + 3;
|
||||
static constexpr UINT previewRendered = WM_APP + 4;
|
||||
static constexpr UINT cycleWindow = WM_APP + 5;
|
||||
static constexpr UINT savePreviewTask = WM_APP + 6;
|
||||
|
||||
LRESULT send(UINT message, WPARAM wparam = 0, LPARAM lparam = 0) const
|
||||
{
|
||||
@@ -856,6 +887,9 @@ private:
|
||||
bool dirty() const { return stagedDirty || (!busy() && uploadPending) || currentChanged(); }
|
||||
bool busy() const { return saving.valid(); }
|
||||
void invalidate() const { InvalidateRect(window, nullptr, FALSE); }
|
||||
RECT statusBounds() const;
|
||||
void invalidateStatus() const;
|
||||
void invalidateHints() const;
|
||||
|
||||
void initializeDocument();
|
||||
void finishOpen();
|
||||
@@ -889,6 +923,9 @@ private:
|
||||
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
|
||||
std::optional<FileStamp> previewFileStamp() const;
|
||||
void refreshPreview();
|
||||
void startMarkdownTask();
|
||||
void finishMarkdownTask();
|
||||
void reportMarkdownTask(uint64_t revision,bool saved);
|
||||
void cancelPreviewImages();
|
||||
void previewMessage(const std::wstring &value);
|
||||
void navigatePreview(PreviewLink request);
|
||||
@@ -1342,22 +1379,25 @@ void TextWindow::finishOpen()
|
||||
void TextWindow::saveFile(bool closeWhenDone)
|
||||
{
|
||||
if (busy() || !edit) return;
|
||||
auto destination=original;
|
||||
if(draft && !search.style.saveOptions(window,destination,newFormat)) return;
|
||||
stagePage();
|
||||
if (!stagedDirty && !uploadPending)
|
||||
if (!draft && !stagedDirty && !uploadPending)
|
||||
{
|
||||
if (closeWhenDone) DestroyWindow(window);
|
||||
else if (std::exchange(switchAfterSave, false)) changeMode();
|
||||
return;
|
||||
}
|
||||
pendingCaret = send(SCI_GETCURRENTPOS);
|
||||
if(draft) pendingSavePath=destination;
|
||||
closeAfterSave = closeWhenDone;
|
||||
if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer.");
|
||||
send(SCI_SETREADONLY, TRUE);
|
||||
try
|
||||
{
|
||||
saving=std::async(std::launch::async,[this]
|
||||
saving=std::async(std::launch::async,[this,destination=std::move(destination)]
|
||||
{
|
||||
const auto reopened=document->save();
|
||||
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
|
||||
if(remote)
|
||||
{
|
||||
uploadPending=true;
|
||||
@@ -1380,10 +1420,23 @@ void TextWindow::finishSave()
|
||||
{
|
||||
if (!busy() || saving.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready) return;
|
||||
KillTimer(window, saveTimer);
|
||||
if(taskOffset)
|
||||
{
|
||||
finishMarkdownTask();
|
||||
return;
|
||||
}
|
||||
send(SCI_SETREADONLY, !edit);
|
||||
const auto change = std::exchange(switchAfterSave, false);
|
||||
const auto reopened = saving.get();
|
||||
stagedDirty = false;
|
||||
const bool created=std::exchange(draft,false);
|
||||
if(created)
|
||||
{
|
||||
original=std::move(pendingSavePath);
|
||||
filename=original.filename().wstring();
|
||||
navigationHistory.clear();
|
||||
updateTitle();
|
||||
}
|
||||
if (!reopened)
|
||||
{
|
||||
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
|
||||
@@ -1392,6 +1445,12 @@ void TextWindow::finishSave()
|
||||
}
|
||||
if (closeAfterSave) { DestroyWindow(window); return; }
|
||||
if (change) { changeMode(); return; }
|
||||
if(created)
|
||||
{
|
||||
initializeDocument();
|
||||
send(SCI_GOTOPOS,std::min<LRESULT>(pendingCaret,send(SCI_GETLENGTH)));
|
||||
return;
|
||||
}
|
||||
if (pageTotal == 1 && document->pages() == 1)
|
||||
{
|
||||
fileSize = document->size();
|
||||
@@ -1408,7 +1467,7 @@ void TextWindow::requestClose()
|
||||
if (busy()) return;
|
||||
if (needsSave())
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window);
|
||||
const auto answer = search.style.confirmSave(window,draft);
|
||||
if (answer == IDCANCEL) return;
|
||||
if (answer == IDYES) { saveFile(true); return; }
|
||||
if (answer != IDNO) return;
|
||||
@@ -1424,9 +1483,10 @@ bool TextWindow::needsSave() const
|
||||
void TextWindow::toggleMode()
|
||||
{
|
||||
if (busy() || navigation.valid()) return;
|
||||
if(draft) return;
|
||||
if (edit && needsSave())
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window);
|
||||
const auto answer = search.style.confirmSave(window,false);
|
||||
if (answer == IDYES)
|
||||
{
|
||||
switchAfterSave = true;
|
||||
@@ -1438,7 +1498,7 @@ void TextWindow::toggleMode()
|
||||
// The local LAN cache may already contain changes from a failed upload.
|
||||
if (uploadPending)
|
||||
{
|
||||
auto refreshed = std::make_unique<RemoteTextFile>(RemoteTextFile{remote->peer,original});
|
||||
auto refreshed = std::make_unique<RemoteTextFile>(remote->source,original);
|
||||
refreshed->download(false,{});
|
||||
auto replacement = std::make_unique<TextDocument>(refreshed->cache,false);
|
||||
document.reset();
|
||||
@@ -1452,7 +1512,7 @@ void TextWindow::toggleMode()
|
||||
|
||||
void TextWindow::changeMode()
|
||||
{
|
||||
if (!edit && remote && !remote->editable)
|
||||
if (!edit && remote && !remote->revision.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);
|
||||
@@ -1476,7 +1536,7 @@ void TextWindow::changeMode()
|
||||
void TextWindow::updateTitle()
|
||||
{
|
||||
const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") +
|
||||
(remote ? remote->peer.name + L" · " : std::wstring{}) + original.wstring();
|
||||
(remote ? remote->source.name + L" · " : std::wstring{}) + original.wstring();
|
||||
SetWindowTextW(window,title.c_str());
|
||||
}
|
||||
|
||||
@@ -1496,25 +1556,35 @@ void TextWindow::updateIcons(UINT dpi)
|
||||
set(largeIcon,ICON_BIG,SM_CXICON,SM_CYICON);
|
||||
}
|
||||
|
||||
void TextWindow::updateTaskbarGroup(bool closing)
|
||||
}
|
||||
|
||||
void setFileWindowTaskbar(HWND window,int iconResource,const wchar_t *identity)
|
||||
{
|
||||
auto icon=closing?std::wstring{}:executable()+L",-"+std::to_wstring(edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER);
|
||||
auto identity=std::wstring(edit?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
|
||||
auto icon=identity?executable()+L",-"+std::to_wstring(iconResource):std::wstring{};
|
||||
auto group=identity?std::wstring(identity):std::wstring{};
|
||||
IPropertyStore *properties{};
|
||||
if(FAILED(SHGetPropertyStoreForWindow(window,IID_PPV_ARGS(&properties)))) return;
|
||||
PROPVARIANT value{};
|
||||
if(!closing)
|
||||
if(identity)
|
||||
{
|
||||
value.vt=VT_LPWSTR;
|
||||
value.pwszVal=icon.data();
|
||||
}
|
||||
properties->SetValue(PKEY_AppUserModel_RelaunchIconResource,value);
|
||||
if(!closing) value.pwszVal=identity.data();
|
||||
if(identity) value.pwszVal=group.data();
|
||||
// Setting the group ID tells Explorer to refresh the taskbar button.
|
||||
properties->SetValue(PKEY_AppUserModel_ID,value);
|
||||
properties->Release();
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
void TextWindow::updateTaskbarGroup(bool closing)
|
||||
{
|
||||
setFileWindowTaskbar(window,edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER,closing?nullptr:
|
||||
edit?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
|
||||
}
|
||||
|
||||
bool TextWindow::canPreview() const
|
||||
{
|
||||
return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit;
|
||||
@@ -1568,6 +1638,9 @@ void TextWindow::stopPreview(bool refresh,bool keepBrowser)
|
||||
KillTimer(window,previewTimer);
|
||||
previewWanted=previewVisible=false;
|
||||
previewStamp.reset();
|
||||
++previewRevision;
|
||||
previewText.clear();
|
||||
pendingTask.reset();
|
||||
cancelPreviewImages();
|
||||
previewLinks.clear();
|
||||
if(keepBrowser && preview.initialized()) preview.post(L"{\"action\":\"clear\"}");
|
||||
@@ -1620,11 +1693,12 @@ void TextWindow::renderPreview(bool keepPosition)
|
||||
{
|
||||
applyMarkdownPreferences(loadTextPreferences().markdown);
|
||||
previewDeadline=GetTickCount64()+30000;
|
||||
std::string text;
|
||||
previewText.clear();
|
||||
for(uint64_t index=0;index<document->pages();++index)
|
||||
text+=document->readPage(index);
|
||||
previewText+=document->readPage(index);
|
||||
if(!remote) document->releaseReadHandle();
|
||||
nlohmann::json message{{"action","render"},{"text",std::move(text)},
|
||||
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
|
||||
{"canSave",!remote || remote->revision.editable},
|
||||
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
|
||||
{"keepPosition",keepPosition}};
|
||||
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
|
||||
@@ -1641,7 +1715,7 @@ void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences
|
||||
|
||||
void TextWindow::refreshPreview()
|
||||
{
|
||||
if(remote || !previewVisible || navigation.valid() || GetTickCount64()<nextFileCheck) return;
|
||||
if(remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
|
||||
nextFileCheck=GetTickCount64()+350;
|
||||
const auto stamp=previewFileStamp();
|
||||
if(!stamp || stamp==previewStamp) return;
|
||||
@@ -1665,6 +1739,121 @@ void TextWindow::refreshPreview()
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::reportMarkdownTask(uint64_t revision,bool saved)
|
||||
{
|
||||
preview.post(wide(nlohmann::json{{"action","task-result"},{"revision",revision},{"saved",saved}}.dump()));
|
||||
}
|
||||
|
||||
void TextWindow::startMarkdownTask()
|
||||
{
|
||||
const auto task=std::exchange(pendingTask,{});
|
||||
if(!task) return;
|
||||
if(!previewVisible || edit || busy() || navigation.valid() || task->revision!=previewRevision ||
|
||||
(remote && !remote->revision.editable))
|
||||
{
|
||||
reportMarkdownTask(task->revision,false);
|
||||
return;
|
||||
}
|
||||
size_t lineStart=0;
|
||||
const auto reject=[&]{reportMarkdownTask(task->revision,false);};
|
||||
for(size_t line=0;line<task->line;++line)
|
||||
{
|
||||
const auto end=previewText.find_first_of("\r\n",lineStart);
|
||||
if(end==previewText.npos) { reject(); return; }
|
||||
lineStart=end+1;
|
||||
if(previewText[end]=='\r' && lineStart<previewText.size() && previewText[lineStart]=='\n') ++lineStart;
|
||||
}
|
||||
if(!task->column || task->column>=previewText.size()-lineStart) { reject(); return; }
|
||||
const auto offset=lineStart+task->column;
|
||||
const auto lineEnd=previewText.find_first_of("\r\n",lineStart);
|
||||
if((lineEnd!=previewText.npos && offset>=lineEnd) || offset+1>=previewText.size() ||
|
||||
previewText[offset-1]!='[' || previewText[offset+1]!=']' ||
|
||||
(previewText[offset]!=' ' && previewText[offset]!='x' && previewText[offset]!='X'))
|
||||
{
|
||||
reject();
|
||||
return;
|
||||
}
|
||||
const auto next=task->checked?'x':' ';
|
||||
if((previewText[offset]!=' ')==task->checked) { reportMarkdownTask(task->revision,true); return; }
|
||||
if(!SetTimer(window,saveTimer,75,nullptr)) { reject(); return; }
|
||||
const auto encoding=document->encoding();
|
||||
try
|
||||
{
|
||||
saving=std::async(std::launch::async,[this,expected=previewText,offset,next,encoding]
|
||||
{
|
||||
const auto path=remote?remote->cache:original;
|
||||
std::filesystem::path candidate;
|
||||
struct RemoveCandidate
|
||||
{
|
||||
std::filesystem::path &path;
|
||||
~RemoveCandidate(){if(!path.empty()){std::error_code ec;std::filesystem::remove(path,ec);}}
|
||||
} cleanup{candidate};
|
||||
if(remote)
|
||||
{
|
||||
const auto stage=path.parent_path()/(path.filename()==L"content"?L"task-update":L"content");
|
||||
std::filesystem::copy_file(path,stage);
|
||||
candidate=stage;
|
||||
}
|
||||
TextDocument fresh(remote?candidate:path,true,encoding);
|
||||
if(fresh.size()>TextDocument::editLimit)
|
||||
throw std::runtime_error("The Markdown file grew outside KSwitcher.");
|
||||
size_t start=0;
|
||||
for(uint64_t index=0;index<fresh.pages();++index)
|
||||
{
|
||||
auto text=fresh.readPage(index);
|
||||
if(std::string_view(expected).substr(start,text.size())!=text)
|
||||
throw std::runtime_error("The Markdown text changed outside KSwitcher.");
|
||||
const auto end=start+text.size();
|
||||
if(offset>=start && offset<end)
|
||||
{
|
||||
text[offset-start]=next;
|
||||
fresh.stage(index,text);
|
||||
}
|
||||
start=end;
|
||||
}
|
||||
if(start!=expected.size()) throw std::runtime_error("The Markdown text changed outside KSwitcher.");
|
||||
fresh.save();
|
||||
if(remote)
|
||||
{
|
||||
remote->revision=remote->source.upload(original,candidate,remote->revision);
|
||||
remote->cache.swap(candidate);
|
||||
}
|
||||
return next=='x';
|
||||
});
|
||||
taskOffset=offset;
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
KillTimer(window,saveTimer);
|
||||
reject();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::finishMarkdownTask()
|
||||
{
|
||||
const auto offset=*std::exchange(taskOffset,{});
|
||||
const auto revision=previewRevision;
|
||||
bool checked{};
|
||||
try {checked=saving.get();}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
reportMarkdownTask(revision,false);
|
||||
search.style.message(window,(L"Could not save the Markdown checkbox. "+wide(error.what())).c_str());
|
||||
return;
|
||||
}
|
||||
if(offset<previewText.size()) previewText[offset]=checked?'x':' ';
|
||||
reportMarkdownTask(revision,true);
|
||||
const auto encoding=document->encoding();
|
||||
document=std::make_unique<TextDocument>(remote?remote->cache:original,false,encoding);
|
||||
loadPage(std::min(page,document->pages()-1));
|
||||
if(!remote)
|
||||
{
|
||||
previewStamp=previewFileStamp();
|
||||
document->releaseReadHandle();
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::previewMessage(const std::wstring &value)
|
||||
{
|
||||
if(!previewWanted) return;
|
||||
@@ -1692,6 +1881,16 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
PostMessageW(window,previewRendered,0,0);
|
||||
return;
|
||||
}
|
||||
if(action=="save-task")
|
||||
{
|
||||
if(!pendingTask && !busy())
|
||||
{
|
||||
pendingTask=MarkdownTask{message.at("revision"),message.at("line"),message.at("column"),
|
||||
message.at("checked")};
|
||||
PostMessageW(window,savePreviewTask,0,0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Defer transitions until WebView2 returns from its event callback.
|
||||
if(action=="edit" || action=="close")
|
||||
{
|
||||
@@ -1742,11 +1941,13 @@ void TextWindow::syncNavigation()
|
||||
|
||||
void TextWindow::navigatePreview(PreviewLink request)
|
||||
{
|
||||
if(edit || navigation.valid() || navigationHistory.empty()) return;
|
||||
if(edit || busy() || pendingTask || navigation.valid() || navigationHistory.empty()) return;
|
||||
if(request.newWindow)
|
||||
{
|
||||
openTextWindow(window,request.target.path,false,search.style,remote?&remote->peer:nullptr,
|
||||
request.target.fragment,true);
|
||||
if(remote)
|
||||
openRemoteTextWindow(window,request.target.path,false,search.style,remote->source,request.target.fragment,true);
|
||||
else
|
||||
openTextWindow(window,request.target.path,false,search.style,nullptr,request.target.fragment,true);
|
||||
return;
|
||||
}
|
||||
if((request.direction<0 && navigationIndex==0) ||
|
||||
@@ -1762,13 +1963,13 @@ void TextWindow::navigatePreview(PreviewLink request)
|
||||
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});
|
||||
[backend=remote->source,path=destination.path,cancel] {
|
||||
auto file=std::make_unique<RemoteTextFile>(backend,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.");
|
||||
throw std::runtime_error("Cannot start the remote navigation timer.");
|
||||
try
|
||||
{
|
||||
auto result=task.get_future();
|
||||
@@ -1842,8 +2043,8 @@ void TextWindow::pollImages()
|
||||
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);
|
||||
[path=activeImage.path,backend=remote?std::optional(remote->source):std::nullopt,cancel=cancelImages] {
|
||||
return markdownImage(path,backend?&*backend:nullptr,cancel);
|
||||
});
|
||||
image=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
@@ -1861,6 +2062,58 @@ void TextWindow::layout()
|
||||
invalidate();
|
||||
}
|
||||
|
||||
RECT TextWindow::statusBounds() const
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
bounds.top=chromeHeight();
|
||||
bounds.bottom=2*bounds.top;
|
||||
return bounds;
|
||||
}
|
||||
|
||||
void TextWindow::invalidateStatus() const
|
||||
{
|
||||
const auto bounds=statusBounds();
|
||||
InvalidateRect(window,&bounds,FALSE);
|
||||
}
|
||||
|
||||
void TextWindow::invalidateHints() const
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
bounds.top=std::max(0L,bounds.bottom-chromeHeight());
|
||||
InvalidateRect(window,&bounds,FALSE);
|
||||
}
|
||||
|
||||
void drawEditorStatus(HDC dc,RECT bounds,HFONT font,COLORREF background,COLORREF foreground,
|
||||
int inset,const std::wstring &status)
|
||||
{
|
||||
const auto width=bounds.right-bounds.left,height=bounds.bottom-bounds.top;
|
||||
if(width<=0 || height<=0) return;
|
||||
const auto memory=CreateCompatibleDC(dc);
|
||||
const auto bitmap=memory?CreateCompatibleBitmap(dc,width,height):nullptr;
|
||||
const auto target=bitmap?memory:dc;
|
||||
const auto oldBitmap=bitmap?SelectObject(memory,bitmap):nullptr;
|
||||
const auto oldFont=SelectObject(target,font);
|
||||
auto row=bitmap?RECT{0,0,width,height}:bounds;
|
||||
SetDCBrushColor(target,background);
|
||||
FillRect(target,&row,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
SetBkMode(target,TRANSPARENT);
|
||||
SetTextColor(target,foreground);
|
||||
row.left+=inset;
|
||||
row.right-=inset;
|
||||
if(row.left<row.right)
|
||||
DrawTextW(target,status.c_str(),-1,&row,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
SelectObject(target,oldFont);
|
||||
if(bitmap)
|
||||
{
|
||||
BitBlt(dc,bounds.left,bounds.top,width,height,memory,0,0,SRCCOPY);
|
||||
SelectObject(memory,oldBitmap);
|
||||
DeleteObject(bitmap);
|
||||
}
|
||||
if(memory) DeleteDC(memory);
|
||||
}
|
||||
|
||||
void TextWindow::paint()
|
||||
{
|
||||
PAINTSTRUCT paint{};
|
||||
@@ -1870,12 +2123,12 @@ void TextWindow::paint()
|
||||
const auto row = chromeHeight();
|
||||
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
SetDCBrushColor(dc, color(TextColor::background));
|
||||
FillRect(dc, &client, brush);
|
||||
const RECT body{0,2*row,client.right,std::max<LONG>(2*row,client.bottom-row)};
|
||||
FillRect(dc, &body, brush);
|
||||
SetDCBrushColor(dc, color(TextColor::chromebg));
|
||||
RECT menuBar{0, 0, client.right, row};
|
||||
RECT top{0, row, client.right, 2 * row};
|
||||
const RECT top=statusBounds();
|
||||
RECT bottom{0, client.bottom - row, client.right, client.bottom};
|
||||
FillRect(dc, &top, brush);
|
||||
FillRect(dc, &bottom, brush);
|
||||
FillRect(dc, &menuBar, brush);
|
||||
const auto chromeFont = createChromeFont();
|
||||
@@ -1904,27 +2157,27 @@ void TextWindow::paint()
|
||||
}
|
||||
SetTextColor(dc, color(TextColor::chrome));
|
||||
bottom.left += scale(7);
|
||||
const auto position = send(SCI_GETCURRENTPOS);
|
||||
const auto line = send(SCI_LINEFROMPOSITION, position) + 1;
|
||||
const auto column = send(SCI_GETCOLUMN, position) + 1;
|
||||
const auto displayLanguage = textLanguageLabel(language);
|
||||
auto status = filename + (edit ? L" (Edit)" : L" (View)") + (dirty() ? L" *" : L"") +
|
||||
L" │ " + (document?document->encodingName():L"Loading…") + L" │ " + displayLanguage +
|
||||
L" │ Ln " + std::to_wstring(line) + L":" + std::to_wstring(column);
|
||||
if (pageTotal > 1)
|
||||
status += L" │ Page " + std::to_wstring(page + 1) + L"/" + std::to_wstring(pageTotal) +
|
||||
L" @ " + std::to_wstring(pageOffset);
|
||||
status += L" │ " + std::to_wstring(fileSize) + L" B";
|
||||
RECT statusPaint{};
|
||||
if(IntersectRect(&statusPaint,&top,&paint.rcPaint))
|
||||
{
|
||||
const auto position=send(SCI_GETCURRENTPOS);
|
||||
const auto line=send(SCI_LINEFROMPOSITION,position)+1;
|
||||
const auto column=send(SCI_GETCOLUMN,position)+1;
|
||||
auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+
|
||||
L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+
|
||||
L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column);
|
||||
if(pageTotal>1)
|
||||
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
|
||||
L" @ "+std::to_wstring(pageOffset);
|
||||
status+=L" │ "+std::to_wstring(fileSize)+L" B";
|
||||
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
|
||||
}
|
||||
const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" :
|
||||
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
|
||||
previewVisible ? L"F6 Edit Ctrl+W Close" :
|
||||
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
|
||||
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
|
||||
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
|
||||
top.left += scale(12);
|
||||
top.right -= scale(12);
|
||||
if (top.left < top.right)
|
||||
DrawTextW(dc, status.c_str(), -1, &top, format | DT_RIGHT);
|
||||
DrawTextW(dc, hints, -1, &bottom, format);
|
||||
SelectObject(dc, previous);
|
||||
DeleteObject(chromeFont);
|
||||
@@ -2044,6 +2297,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
case SCN_MODIFIED:
|
||||
if (notice.modificationType & SC_MOD_INSERTCHECK)
|
||||
{
|
||||
const auto hadWarning=insertRejected;
|
||||
if (send(SCI_GETLENGTH) + notice.length > static_cast<LRESULT>(TextDocument::editLimit))
|
||||
{
|
||||
send(SCI_CHANGEINSERTION, 0, reinterpret_cast<LPARAM>(""));
|
||||
@@ -2051,6 +2305,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
MessageBeep(MB_ICONWARNING);
|
||||
}
|
||||
else insertRejected = false;
|
||||
if(hadWarning!=insertRejected) invalidateHints();
|
||||
}
|
||||
if (notice.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
|
||||
{
|
||||
@@ -2058,8 +2313,8 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
undoBytes += static_cast<size_t>(notice.length) + 64;
|
||||
if (undoBytes >= 32 * TextDocument::pageBytes)
|
||||
PostMessageW(window, trimUndo, 0, 0);
|
||||
invalidateStatus();
|
||||
}
|
||||
invalidate();
|
||||
break;
|
||||
case SCN_CHARADDED:
|
||||
if (edit && prefs.autoIndent && (notice.ch == '\n' || (notice.ch == '\r' && send(SCI_GETEOLMODE) == SC_EOL_CR)))
|
||||
@@ -2079,7 +2334,7 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
case SCN_UPDATEUI:
|
||||
case SCN_SAVEPOINTREACHED:
|
||||
case SCN_SAVEPOINTLEFT:
|
||||
invalidate();
|
||||
invalidateStatus();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -2188,7 +2443,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
self->applyPreferences();
|
||||
self->send(SCI_SETREADONLY,TRUE);
|
||||
if(!SetTimer(window,openTimer,75,nullptr))
|
||||
throw std::runtime_error("Cannot start the LAN file timer.");
|
||||
throw std::runtime_error("Cannot start the remote file timer.");
|
||||
self->opening=std::async(std::launch::async,[state=self.get()]
|
||||
{
|
||||
state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;});
|
||||
@@ -2224,6 +2479,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
}
|
||||
break;
|
||||
case previewFailed: self->stopPreview(); return 0;
|
||||
case savePreviewTask: self->startMarkdownTask(); return 0;
|
||||
case previewRendered:
|
||||
if(self->previewWanted)
|
||||
{
|
||||
@@ -2431,9 +2687,9 @@ bool cycleTextWindows(HWND current,bool reverse)
|
||||
return true;
|
||||
}
|
||||
|
||||
HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *peer)
|
||||
HWND findOpenDocument(const std::filesystem::path &path,std::string_view id)
|
||||
{
|
||||
const auto identity=documentIdentity(path,peer?peer->id:"");
|
||||
const auto identity=documentIdentity(path,id);
|
||||
struct Search
|
||||
{
|
||||
COPYDATASTRUCT query;
|
||||
@@ -2457,16 +2713,16 @@ HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *pe
|
||||
return search.match;
|
||||
}
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow)
|
||||
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options)
|
||||
{
|
||||
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 identity=backend?path.lexically_normal():std::filesystem::weakly_canonical(path,error);
|
||||
const auto &original=error?path:identity;
|
||||
if(const auto existing=newWindow?nullptr:findOpenDocument(original,peer))
|
||||
if(const auto existing=newWindow?nullptr:findOpenDocument(original,backend?backend->id:""))
|
||||
{
|
||||
if(dialogs.confirmExisting(owner) && IsWindow(existing))
|
||||
{
|
||||
@@ -2490,9 +2746,9 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
|
||||
}();
|
||||
if(!registered) throw std::runtime_error("Cannot register the text window.");
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment);
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,backend,fragment,options);
|
||||
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
|
||||
(peer?peer->name+L" · ":std::wstring{})+path.wstring();
|
||||
(backend?backend->name+L" · ":std::wstring{})+path.wstring();
|
||||
RECT bounds{};
|
||||
GetWindowRect(owner,&bounds);
|
||||
const auto window=CreateWindowExW(WS_EX_APPWINDOW,windowClass,title.c_str(),
|
||||
@@ -2504,4 +2760,17 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
}
|
||||
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
|
||||
}
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow,TextOpenOptions options)
|
||||
{
|
||||
const auto backend=peer?std::optional(lanTextSource(*peer)):std::nullopt;
|
||||
openTextWindowImpl(owner,path,edit,dialogs,backend?&*backend:nullptr,fragment,newWindow,options);
|
||||
}
|
||||
|
||||
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource &source,std::string_view fragment,bool newWindow)
|
||||
{
|
||||
openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,{});
|
||||
}
|
||||
}
|
||||
+34
-2
@@ -2,8 +2,11 @@
|
||||
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <cstdint>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include "files_text_document.h"
|
||||
|
||||
namespace ks::lan { struct FilesPeer; }
|
||||
|
||||
@@ -20,6 +23,8 @@ struct TextWindowFont
|
||||
int tenthsOfPoint;
|
||||
};
|
||||
|
||||
void setFileWindowTaskbar(HWND window,int iconResource,const wchar_t *identity);
|
||||
|
||||
struct FarDropDownPalette
|
||||
{
|
||||
COLORREF surface, text, selection;
|
||||
@@ -37,7 +42,7 @@ void installFarHistoryKey(HWND field,int arrowId);
|
||||
|
||||
struct TextDialogs
|
||||
{
|
||||
INT_PTR (*confirmSave)(HWND);
|
||||
INT_PTR (*confirmSave)(HWND,bool draft);
|
||||
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
|
||||
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
|
||||
void (*prepare)(HWND);
|
||||
@@ -49,10 +54,37 @@ struct TextDialogs
|
||||
void (*finish)(HWND,INT_PTR);
|
||||
bool (*dismissOwned)(HWND);
|
||||
bool (*confirmExisting)(HWND);
|
||||
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
|
||||
};
|
||||
|
||||
struct TextOpenOptions
|
||||
{
|
||||
TextEncoding encoding=TextEncoding::automatic;
|
||||
bool draft{};
|
||||
};
|
||||
|
||||
struct RemoteTextRevision
|
||||
{
|
||||
uint64_t size{}, modified{};
|
||||
bool editable{};
|
||||
};
|
||||
|
||||
struct RemoteTextSource
|
||||
{
|
||||
using Progress=std::function<bool(uint64_t,uint64_t)>;
|
||||
std::string id;
|
||||
std::wstring name;
|
||||
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
bool,const Progress &,uint64_t)> download;
|
||||
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
const RemoteTextRevision &)> upload;
|
||||
};
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false);
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
|
||||
TextOpenOptions options={});
|
||||
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false);
|
||||
void textWindowOwnerClosed();
|
||||
bool cycleTextWindows(HWND current,bool reverse);
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.112";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.119";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
+220
-21
@@ -3,6 +3,7 @@ param(
|
||||
[Parameter(Mandatory)][string]$Fixture,
|
||||
[switch]$SystemOpenOnly,
|
||||
[switch]$TerminalOnly,
|
||||
[int]$ScanEntries = 0,
|
||||
[string]$Node='node'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -12,6 +13,10 @@ using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class FilesActivationUi {
|
||||
public static void CreateScanFiles(string directory, int count) {
|
||||
for (int i = 0; i < count; i++)
|
||||
using (System.IO.File.Create(System.IO.Path.Combine(directory, i.ToString("D6") + ".txt"))) {}
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
@@ -27,6 +32,22 @@ public static class FilesActivationUi {
|
||||
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr window, IntPtr dc);
|
||||
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
|
||||
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
|
||||
public static uint ReadScreenCenter(IntPtr window) {
|
||||
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
|
||||
try {
|
||||
Rect bounds;
|
||||
if (!GetWindowRect(window, out bounds)) throw new InvalidOperationException("Missing terminal output.");
|
||||
var dc = GetDC(IntPtr.Zero);
|
||||
if (dc == IntPtr.Zero) throw new InvalidOperationException("Could not read the screen.");
|
||||
try { return GetPixel(dc, (bounds.Left + bounds.Right) / 2, (bounds.Top + bounds.Bottom) / 2); }
|
||||
finally { ReleaseDC(IntPtr.Zero, dc); }
|
||||
} finally {
|
||||
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool HasWarningBackground(IntPtr window) {
|
||||
var dc = GetDC(window);
|
||||
@@ -35,6 +56,7 @@ public static class FilesActivationUi {
|
||||
finally { ReleaseDC(window, dc); }
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
@@ -86,6 +108,19 @@ function Wait-Until([string]$Description, [scriptblock]$Condition) {
|
||||
throw "Timed out waiting for $Description"
|
||||
}
|
||||
|
||||
function Invoke-ClipboardOperation([scriptblock]$Operation) {
|
||||
for ($attempt = 1; $attempt -le 3; $attempt++) {
|
||||
try { return (& $Operation) }
|
||||
catch {
|
||||
# CLIPBRD_E_CANT_OPEN means another process is using the shared clipboard.
|
||||
if ($_.Exception.GetBaseException().HResult -ne 0x800401D0 -or
|
||||
$attempt -eq 3) { throw }
|
||||
[Windows.Forms.Application]::DoEvents()
|
||||
Start-Sleep -Milliseconds 25
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Find-OperationDialog($Owner, [int]$Control) {
|
||||
$candidate = [IntPtr]::Zero
|
||||
while ($true) {
|
||||
@@ -172,7 +207,7 @@ $extension = ".ksfiles$unique"
|
||||
$progId = "KSwitcher.Files.Test.$unique"
|
||||
$saved = @{}
|
||||
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
|
||||
'ShowDetails', 'StatusFields', 'CommandHistory', 'WindowPlacement'
|
||||
'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement'
|
||||
$process = $null
|
||||
$trace = $null
|
||||
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
@@ -214,6 +249,18 @@ try {
|
||||
$profile.SetValue('StatusFields', 3)
|
||||
|
||||
if($TerminalOnly){
|
||||
$terminalPage = Join-Path $app 'terminal/index.html'
|
||||
$page = Get-Content -Raw -LiteralPath $terminalPage
|
||||
$page = $page.Replace('<style>','<style media="not all">').Replace('src="terminal.js"','src="startup-fixture.js"')
|
||||
[IO.File]::WriteAllText($terminalPage,$page)
|
||||
[IO.File]::WriteAllText((Join-Path $app 'terminal/startup-fixture.js'), @'
|
||||
function startTerminalFixture() {
|
||||
document.querySelector('style').media = 'all';
|
||||
const script = document.createElement('script');
|
||||
script.src = 'terminal.js';
|
||||
document.body.append(script);
|
||||
}
|
||||
'@)
|
||||
$listener=[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$listener.Start()
|
||||
$port=$listener.LocalEndpoint.Port
|
||||
@@ -221,6 +268,13 @@ try {
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=$port"
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $root 'webview'
|
||||
}
|
||||
if($SystemOpenOnly) {
|
||||
$profile.SetValue('PreviousCommandKey',0x0245,'DWord')
|
||||
$profile.SetValue('CommandHistoryKey',0x0477,'DWord')
|
||||
}
|
||||
if ($ScanEntries) {
|
||||
[FilesActivationUi]::CreateScanFiles("$leftDir\Test folder", $ScanEntries)
|
||||
}
|
||||
$process = Start-Process -FilePath $testExe -ArgumentList '--terminal-output-trace' -PassThru
|
||||
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
|
||||
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
@@ -231,6 +285,49 @@ try {
|
||||
$output = [FilesActivationUi]::GetDlgItem($window, 145)
|
||||
$inputBox = [FilesActivationUi]::FindWindowEx($window, [IntPtr]::Zero, 'Edit', $null)
|
||||
|
||||
if ($ScanEntries) {
|
||||
Wait-Until 'visible Files window' { [FilesActivationUi]::Activate($window) }
|
||||
Wait-Until 'folder fixture row' { (Find-Row $left '[Test folder]') -ge 0 }
|
||||
$folderRow = Find-Row $left '[Test folder]'
|
||||
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
|
||||
Press-Enter $inputBox
|
||||
Wait-Until 'nonzero folder scan progress' {
|
||||
[FilesActivationUi]::IsWindowVisible($status) -and
|
||||
(Read-Text $status) -match '^Reading ([1-9][0-9]*) \[Esc\]$'
|
||||
}
|
||||
$progress = Read-Text $status
|
||||
[void][FilesActivationUi]::PostMessage($inputBox, 0x100, [IntPtr]27, [IntPtr]::Zero)
|
||||
Wait-Until 'partial folder result' { (Read-Text $status) -match '^Partial: \d+$' }
|
||||
$partial = [FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() - 1
|
||||
$partialStatus = Read-Text $status
|
||||
if ($partial -le 0 -or $partial -ge $ScanEntries -or
|
||||
$partialStatus -ne "Partial: $partial" -or
|
||||
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -ne "$leftDir\Test folder") {
|
||||
throw "Unexpected partial listing of $partial entries."
|
||||
}
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
$fullScan = [Diagnostics.Stopwatch]::StartNew()
|
||||
$keys.SendKeys('^r')
|
||||
Wait-Until 'complete folder result after Ctrl+R' {
|
||||
[FilesActivationUi]::Send($left, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $ScanEntries + 1
|
||||
}
|
||||
$fullScan.Stop()
|
||||
Write-Output "$progress. $partialStatus. Full scan: $ScanEntries files in $($fullScan.ElapsedMilliseconds) ms."
|
||||
$target = 65536
|
||||
[void][FilesActivationUi]::Send($left, 0x197, [IntPtr]$target, [IntPtr]::Zero)
|
||||
if ([FilesActivationUi]::Send($left, 0x18E, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $target) {
|
||||
throw "Could not scroll row $target to the top."
|
||||
}
|
||||
$point = [IntPtr]((2 -shl 16) -bor 6)
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x201, [IntPtr]1, $point)
|
||||
[void][FilesActivationUi]::PostMessage($left, 0x202, [IntPtr]::Zero, $point)
|
||||
Wait-Until 'mouse selection past the 16-bit row limit' {
|
||||
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq $target
|
||||
}
|
||||
Write-Output "Clicked row $target after scrolling it to the top."
|
||||
return
|
||||
}
|
||||
|
||||
if($SystemOpenOnly) {
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
$explorer = New-Object -ComObject Shell.Application
|
||||
@@ -271,11 +368,55 @@ try {
|
||||
Wait-Until 'plain Enter invoking the default Windows file association' {
|
||||
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
|
||||
}
|
||||
$command="start '$($document.Replace("'","''"))'"
|
||||
Wait-Until 'the system open action in terminal output and command history' {
|
||||
$history=$profile.GetValue('CommandHistory')
|
||||
[FilesActivationUi]::IsWindowVisible($output) -and $history -and
|
||||
([Text.Encoding]::Unicode.GetString($history).Split([char]0) -ccontains $command) -and
|
||||
(Select-String -LiteralPath $trace -Pattern ('^'+[regex]::Escape($document.Substring(0,24))) -Quiet)
|
||||
}
|
||||
Wait-Until 'Files active for command history' { [FilesActivationUi]::Activate($window) }
|
||||
$keys.SendKeys('%{F8}')
|
||||
$historyDialog=[IntPtr]::Zero
|
||||
Wait-Until 'command history showing only the opened file path' {
|
||||
$script:historyDialog=[FilesActivationUi]::GetForegroundWindow()
|
||||
$list=[FilesActivationUi]::GetDlgItem($historyDialog,324)
|
||||
$list -ne [IntPtr]::Zero -and (Find-Row $list $document) -ge 0
|
||||
}
|
||||
$historyList=[FilesActivationUi]::GetDlgItem($historyDialog,324)
|
||||
$historyRow=Find-Row $historyList $document
|
||||
[void][FilesActivationUi]::Send($historyList,0x186,[IntPtr]$historyRow,[IntPtr]::Zero)
|
||||
[void][FilesActivationUi]::PostMessage($historyDialog,0x111,[IntPtr]1,[IntPtr]::Zero)
|
||||
Wait-Until 'selecting the history path restoring a runnable command' { (Read-Text $inputBox) -ceq $command }
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
|
||||
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
|
||||
Remove-Item -LiteralPath "$document.opened"
|
||||
}
|
||||
if($SystemOpenOnly -or $TerminalOnly){
|
||||
$keys = New-Object -ComObject WScript.Shell
|
||||
if ($TerminalOnly) {
|
||||
Wait-Until 'Files active for the terminal startup check' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$keys.SendKeys('^o')
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-pause'
|
||||
if ($LASTEXITCODE) { throw 'Could not pause terminal page initialization.' }
|
||||
foreach ($frame in 1..10) {
|
||||
if ([FilesActivationUi]::GetForegroundWindow() -ne $window -or
|
||||
![FilesActivationUi]::IsWindowVisible($output)) { throw 'The terminal must be visible for the startup check.' }
|
||||
$pixel = [FilesActivationUi]::ReadScreenCenter($output)
|
||||
if ($pixel -ne 0x181818) { throw ('Unexpected terminal startup background 0x{0:X6}.' -f $pixel) }
|
||||
Start-Sleep -Milliseconds 30
|
||||
}
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-resume'
|
||||
if ($LASTEXITCODE) { throw 'Could not resume terminal page initialization.' }
|
||||
Wait-Until 'the terminal rendering after startup' {
|
||||
Select-String -LiteralPath $trace -SimpleMatch ' web-anchor ' -Quiet -ErrorAction SilentlyContinue
|
||||
}
|
||||
$keys.SendKeys('^o')
|
||||
Wait-Until 'file panes restored after the startup check' { [FilesActivationUi]::IsWindowVisible($left) }
|
||||
Write-Output 'Verified the dark terminal background before WebView initialization completes.'
|
||||
}
|
||||
foreach($case in @(
|
||||
@{Name='enter-panes'; Keys='{ENTER}'},
|
||||
@{Name='shift-enter-panes'; Keys='+{ENTER}'},
|
||||
@@ -319,6 +460,34 @@ try {
|
||||
([IO.File]::ReadAllLines($listing) -ccontains 'zzzz-dir-second')
|
||||
}
|
||||
Write-Output 'Verified repeated dir commands in the same terminal with file panes hidden and visible.'
|
||||
$rightChild = Join-Path $rightDir "Command's [folder]"
|
||||
[void][IO.Directory]::CreateDirectory($rightChild)
|
||||
$childRow = "[$([IO.Path]::GetFileName($rightChild))]"
|
||||
Wait-Until 'new folder in the right panel' { (Find-Row $right $childRow) -ge 0 }
|
||||
$keys.SendKeys('{TAB}')
|
||||
Send-InteractiveTerminal 'cmd /d /c "cd > panel-cwd.txt"'
|
||||
Wait-Until 'native command running in the newly active right panel' {
|
||||
(Test-Path -LiteralPath (Join-Path $rightDir 'panel-cwd.txt')) -and
|
||||
(Find-Row $right 'panel-cwd.txt') -ge 0
|
||||
}
|
||||
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr](Find-Row $right $childRow), [IntPtr]::Zero)
|
||||
Press-Enter $inputBox
|
||||
$rightPath = [FilesActivationUi]::GetDlgItem($window, 143)
|
||||
Wait-Until 'navigation to the right panel subfolder' { (Read-Text $rightPath) -ceq $rightChild }
|
||||
Send-InteractiveTerminal 'cmd /d /c "cd > child-cwd.txt"'
|
||||
Wait-Until 'native command running in the navigated folder' {
|
||||
(Test-Path -LiteralPath (Join-Path $rightChild 'child-cwd.txt')) -and
|
||||
(Find-Row $right 'child-cwd.txt') -ge 0
|
||||
}
|
||||
Send-InteractiveTerminal 'cd ..'
|
||||
Wait-Until 'PowerShell cd navigating the right panel' { (Find-Row $right 'panel-cwd.txt') -ge 0 }
|
||||
$keys.SendKeys('{TAB}')
|
||||
Send-InteractiveTerminal 'cmd /d /c "cd > left-cwd.txt"'
|
||||
Wait-Until 'native command running back in the left panel' {
|
||||
(Test-Path -LiteralPath (Join-Path $leftDir 'left-cwd.txt')) -and
|
||||
(Find-Row $left 'left-cwd.txt') -ge 0
|
||||
}
|
||||
Write-Output 'Verified native commands follow panel switches and folder navigation in the same PowerShell session.'
|
||||
$marker=Join-Path $root 'webview-enter.txt'
|
||||
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$command)
|
||||
@@ -329,26 +498,29 @@ try {
|
||||
!(Read-Text $inputBox)
|
||||
}
|
||||
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
|
||||
Select-Row $left '[Test folder]'
|
||||
# The left panel is already active after the working-directory check.
|
||||
$folderRow = Find-Row $left '[Test folder]'
|
||||
if ($folderRow -lt 0) { throw 'Missing folder for the terminal clipboard check.' }
|
||||
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
|
||||
$outputSelection = 'terminal-output-copy-fixture'
|
||||
Send-InteractiveTerminal "Write-Output '$outputSelection'"
|
||||
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$savedClipboard = [Windows.Forms.Clipboard]::GetDataObject()
|
||||
$savedClipboard = Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
|
||||
try {
|
||||
$nativeDraft = "Get-Item -LiteralPath '$leftDir'"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$nativeDraft)
|
||||
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]0,[IntPtr]4)
|
||||
$keys.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the full command line with a partial selection' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $nativeDraft
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $nativeDraft
|
||||
}
|
||||
$webviewDraft = "Get-Item -LiteralPath '$rightDir'"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$webviewDraft)
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-copy'
|
||||
if($LASTEXITCODE){throw 'Could not send Ctrl+Insert through the terminal WebView.'}
|
||||
Wait-Until 'Ctrl+Insert copying the command line with focus in the terminal WebView' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $webviewDraft
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $webviewDraft
|
||||
}
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-select-output'
|
||||
if($LASTEXITCODE){throw 'Could not select the terminal output fixture.'}
|
||||
@@ -356,22 +528,26 @@ try {
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
foreach($key in '^c','^{INSERT}') {
|
||||
[Windows.Forms.Clipboard]::SetText($webviewDraft)
|
||||
# Require a new clipboard write without making the test process the clipboard owner.
|
||||
$beforeCopy = [FilesActivationUi]::GetClipboardSequenceNumber()
|
||||
$keys.SendKeys($key)
|
||||
Wait-Until "$key copying only the selected terminal output with a command present" {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $outputSelection
|
||||
[FilesActivationUi]::GetClipboardSequenceNumber() -ne $beforeCopy -and
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $outputSelection
|
||||
}
|
||||
if ((Read-Text $inputBox) -cne $webviewDraft) { throw 'Copying output changed the command line.' }
|
||||
}
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
|
||||
$keys.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the selected folder name when the command line is empty' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq 'Test folder'
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq 'Test folder'
|
||||
}
|
||||
} finally {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
Invoke-ClipboardOperation {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
}
|
||||
}
|
||||
}
|
||||
Write-Output 'Verified Ctrl+C and Ctrl+Insert copy the selected output, then fall back to the command line or panel.'
|
||||
@@ -396,6 +572,20 @@ try {
|
||||
}
|
||||
if ((Read-Text $inputBox) -cne 'draft command') { throw 'Pane navigation changed the command line.' }
|
||||
$shell = New-Object -ComObject WScript.Shell
|
||||
Wait-Until 'Files activation for Ctrl+F' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
foreach ($case in @(
|
||||
@{ Row = '..'; Path = $rightDir },
|
||||
@{ Row = '[Test folder]'; Path = (Join-Path $rightDir 'Test folder') }
|
||||
)) {
|
||||
Select-Row $right $case.Row
|
||||
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
|
||||
[void][FilesActivationUi]::Send($inputBox, 0xB1, [IntPtr]6, [IntPtr]13)
|
||||
$shell.SendKeys('^f')
|
||||
$path = if ($case.Path.Contains(' ')) { '"{0}"' -f $case.Path } else { $case.Path }
|
||||
Wait-Until "Ctrl+F inserting the path for $($case.Row)" { (Read-Text $inputBox) -ceq "draft $path" }
|
||||
}
|
||||
$fileName = [IO.Path]::GetFileName($document)
|
||||
foreach ($name in $fileName, 'Test folder') {
|
||||
$label = if ($name -eq $fileName) { $name } else { "[$name]" }
|
||||
@@ -477,7 +667,7 @@ try {
|
||||
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
|
||||
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$savedClipboard=[Windows.Forms.Clipboard]::GetDataObject()
|
||||
$savedClipboard=Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
|
||||
$programName=[IO.Path]::GetFileName($program)
|
||||
$expectedNames="Test folder`r`n$programName"
|
||||
try {
|
||||
@@ -490,18 +680,20 @@ try {
|
||||
}
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $expectedNames
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $expectedNames
|
||||
}
|
||||
Select-Row $right $fileName
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $fileName
|
||||
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $fileName
|
||||
}
|
||||
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
|
||||
} finally {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
Invoke-ClipboardOperation {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,17 +712,24 @@ try {
|
||||
Select-Row $right "[$name]"
|
||||
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
}
|
||||
Select-Row $right '[Size C]'
|
||||
Select-Row $right $fileName
|
||||
[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' }
|
||||
Wait-Until 'F3 on a file measuring 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 '..'
|
||||
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
Select-Row $right '[Size C]'
|
||||
Wait-Until 'F3 on the parent row measuring all folders' { (Read-Text $status) -ceq 'Size C 31 B' }
|
||||
foreach($name in 'Size A','Size B'){
|
||||
Select-Row $right "[$name]"
|
||||
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
}
|
||||
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' {
|
||||
Wait-Until 'F3 opening a file with no marked folders' {
|
||||
[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle) -ne [IntPtr]::Zero
|
||||
}
|
||||
$viewer=[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle)
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
param([Parameter(Mandatory)][string]$Executable)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class ComparisonSplitterUi {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Point { public int X, Y; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point);
|
||||
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
|
||||
[DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(18, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(18, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-For([string]$Name, [scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 50; ++$attempt) {
|
||||
$value = & $Condition
|
||||
if ($value) { return $value }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
throw "Timed out waiting for $Name."
|
||||
}
|
||||
|
||||
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance'
|
||||
$saved = @{}
|
||||
foreach ($name in $names) {
|
||||
if ($name -in $preferences.GetValueNames()) {
|
||||
$saved[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
|
||||
}
|
||||
}
|
||||
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
|
||||
$root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N'))
|
||||
$dpi = [ComparisonSplitterUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$process = $null
|
||||
try {
|
||||
$left = Join-Path $root 'left'
|
||||
$right = Join-Path $root 'right'
|
||||
[void][IO.Directory]::CreateDirectory($left)
|
||||
[void][IO.Directory]::CreateDirectory($right)
|
||||
[IO.File]::WriteAllText((Join-Path $left 'sample.txt'), "one`ntwo")
|
||||
[IO.File]::WriteAllText((Join-Path $right 'sample.txt'), "one`nthree")
|
||||
$preferences.SetValue('LeftPath', $left)
|
||||
$preferences.SetValue('RightPath', $right)
|
||||
foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance') {
|
||||
$preferences.DeleteValue($name, $false)
|
||||
}
|
||||
|
||||
$process = Start-Process -FilePath (Resolve-Path -LiteralPath $Executable) -PassThru
|
||||
$main = Wait-For 'the Files window' {
|
||||
$process.Refresh()
|
||||
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
|
||||
}
|
||||
foreach ($id in 102, 103) {
|
||||
$panel = [ComparisonSplitterUi]::GetDlgItem($main, $id)
|
||||
[void](Wait-For 'the test file in the panel' {
|
||||
[ComparisonSplitterUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2
|
||||
})
|
||||
[void][ComparisonSplitterUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
|
||||
}
|
||||
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr]132, [IntPtr]::Zero)
|
||||
$picker = [ComparisonSplitterUi]::GetDlgItem($main, 121)
|
||||
[void](Wait-For 'the Commands menu' { [ComparisonSplitterUi]::IsWindowVisible($picker) })
|
||||
$row = -1
|
||||
$count = [ComparisonSplitterUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
|
||||
for ($i = 0; $i -lt $count; ++$i) {
|
||||
$label = [Text.StringBuilder]::new(128)
|
||||
[void][ComparisonSplitterUi]::Read($picker, 393, [IntPtr]$i, $label)
|
||||
if ($label.ToString() -like 'Compare files*') { $row = $i; break }
|
||||
}
|
||||
if ($row -lt 0) { throw 'Missing Compare files command.' }
|
||||
[void][ComparisonSplitterUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero)
|
||||
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr](0x20000 + 121), $picker)
|
||||
$list = Wait-For 'the foreground comparison list' {
|
||||
$dialog = [IntPtr]::Zero
|
||||
while (($dialog = [ComparisonSplitterUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
|
||||
[uint32]$ownerPid = 0
|
||||
[void][ComparisonSplitterUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
|
||||
if ($ownerPid -ne $process.Id) { continue }
|
||||
$control = [ComparisonSplitterUi]::GetDlgItem($dialog, 402)
|
||||
if ([ComparisonSplitterUi]::IsWindowVisible($control) -and [ComparisonSplitterUi]::Activate($dialog)) {
|
||||
return $control
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$bounds = [ComparisonSplitterUi+Rect]::new()
|
||||
[void][ComparisonSplitterUi]::GetClientRect($list, [ref]$bounds)
|
||||
$middle = [int]($bounds.Right / 2)
|
||||
$destination = [int]($bounds.Right * 0.65)
|
||||
$mouseY = 30 -shl 16
|
||||
[void][ComparisonSplitterUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
|
||||
for ($x = $middle + 5; $x -lt $destination; $x += 5) {
|
||||
[void][ComparisonSplitterUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
|
||||
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
}
|
||||
[void][ComparisonSplitterUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
|
||||
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
$origin = [ComparisonSplitterUi+Point]::new()
|
||||
[void][ComparisonSplitterUi]::ClientToScreen($list, [ref]$origin)
|
||||
$bitmap = [Drawing.Bitmap]::new($bounds.Right, 1)
|
||||
try {
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try { $graphics.CopyFromScreen($origin.X, ($origin.Y + $bounds.Bottom - 10), 0, 0, $bitmap.Size) }
|
||||
finally { $graphics.Dispose() }
|
||||
$ink = @(for ($x = $middle - 4; $x -le $destination + 4; ++$x) {
|
||||
if ($bitmap.GetPixel($x, 0).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x }
|
||||
})
|
||||
# Desktop scaling can spread the single-pixel divider across two adjacent screen pixels.
|
||||
if (!$ink.Count -or $ink.Count -gt 2 -or [Math]::Abs($ink[0] - $destination) -gt 1 -or
|
||||
($ink.Count -eq 2 -and $ink[1] - $ink[0] -ne 1)) {
|
||||
throw "Expected one divider under the last row at $destination. Found $($ink.Count) marked pixels, starting at $($ink | Select-Object -First 8)."
|
||||
}
|
||||
} finally { $bitmap.Dispose() }
|
||||
'Verified that dragging leaves exactly one divider below the file contents.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
|
||||
foreach ($name in $names) {
|
||||
if ($saved.ContainsKey($name)) { $preferences.SetValue($name, $saved[$name][0], $saved[$name][1]) }
|
||||
else { $preferences.DeleteValue($name, $false) }
|
||||
}
|
||||
$preferences.Dispose()
|
||||
if ($dpi) { [void][ComparisonSplitterUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
if (Test-Path -LiteralPath $root) {
|
||||
$resolved = (Resolve-Path -LiteralPath $root).Path
|
||||
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-files-splitter-*') {
|
||||
Remove-Item -LiteralPath $resolved -Recurse -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
+108
-16
@@ -1,6 +1,7 @@
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-dev/KSwitcher.Files.exe",
|
||||
[switch]$OfflineWake,
|
||||
[switch]$FtpProfiles,
|
||||
[string]$Screenshot
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -21,6 +22,7 @@ public static class FilesDriveShortcutTest {
|
||||
public static extern IntPtr SendRect(IntPtr window, uint msg, IntPtr w, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
}
|
||||
'@
|
||||
function Wait-Until([scriptblock]$Condition) {
|
||||
@@ -35,38 +37,116 @@ function Read-Text($Control, $Message = 13, $Parameter = 32768) {
|
||||
[void][FilesDriveShortcutTest]::SendMessage($Control, $Message, [IntPtr]$Parameter, $buffer)
|
||||
$buffer.ToString()
|
||||
}
|
||||
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
|
||||
$preferences = $null
|
||||
$savedPreferences = @{}
|
||||
$process = $null
|
||||
$previousDpi = [FilesDriveShortcutTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
try {
|
||||
if ($FtpProfiles) {
|
||||
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$preferenceNames = 'FtpProfiles', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
|
||||
foreach ($name in $preferenceNames) {
|
||||
if ($name -in $preferences.GetValueNames()) {
|
||||
$savedPreferences[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
|
||||
}
|
||||
}
|
||||
$profile = '[{"name":"Test FTP profile","host":"localhost","user":"","port":21,"secret":[]}]'
|
||||
$preferences.SetValue('FtpProfiles', [Text.Encoding]::UTF8.GetBytes($profile), 'Binary')
|
||||
foreach ($name in 'LeftWide', 'RightWide') { $preferences.SetValue($name, 1, 'DWord') }
|
||||
}
|
||||
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
|
||||
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
$window = $process.MainWindowHandle
|
||||
$picker = [FilesDriveShortcutTest]::GetDlgItem($window, 121)
|
||||
$path = [FilesDriveShortcutTest]::GetDlgItem($window, 142)
|
||||
function Open-Picker {
|
||||
[void][FilesDriveShortcutTest]::PostMessage($window, 260, [IntPtr]112, [IntPtr]::Zero)
|
||||
function Open-Picker([int]$Side = 0) {
|
||||
[void][FilesDriveShortcutTest]::PostMessage($window, 260, [IntPtr](112 + $Side), [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::IsWindowVisible($picker) }
|
||||
}
|
||||
function Read-Picker {
|
||||
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
|
||||
for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i }
|
||||
}
|
||||
function Render-Picker {
|
||||
$client = [FilesDriveShortcutTest+Rect]::new()
|
||||
[void][FilesDriveShortcutTest]::GetClientRect($picker, [ref]$client)
|
||||
$bitmap = [Drawing.Bitmap]::new($client.Right, $client.Bottom)
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
$dc = $graphics.GetHdc()
|
||||
try {
|
||||
if (![FilesDriveShortcutTest]::PrintWindow($picker, $dc, 2)) { throw 'Could not render drive picker.' }
|
||||
} finally { $graphics.ReleaseHdc($dc) }
|
||||
return $bitmap
|
||||
} finally { $graphics.Dispose() }
|
||||
}
|
||||
function Press-Shortcut([char]$Key) {
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 258, [IntPtr][int]$Key, [IntPtr]::Zero)
|
||||
Wait-Until { ![FilesDriveShortcutTest]::IsWindowVisible($picker) }
|
||||
}
|
||||
if ($OfflineWake) {
|
||||
function Read-Picker {
|
||||
$count = [FilesDriveShortcutTest]::SendMessage($picker, 395, [IntPtr]::Zero, $null).ToInt32()
|
||||
for ($i = 0; $i -lt $count; $i++) { Read-Text $picker 393 $i }
|
||||
}
|
||||
function Render-Picker {
|
||||
$client = [FilesDriveShortcutTest+Rect]::new()
|
||||
[void][FilesDriveShortcutTest]::GetClientRect($picker, [ref]$client)
|
||||
$bitmap = [Drawing.Bitmap]::new($client.Right, $client.Bottom)
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
if ($FtpProfiles) {
|
||||
foreach ($side in 0, 1) {
|
||||
Open-Picker $side
|
||||
$rows = @(Read-Picker)
|
||||
$row = [Array]::IndexOf($rows, 'FTP')
|
||||
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'KSwitcher LAN') {
|
||||
throw "Source groups are missing separators in panel $side."
|
||||
}
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$row, $null)
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row - 2 }
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
|
||||
Wait-Until {
|
||||
$selected = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32()
|
||||
$selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 1)
|
||||
}
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
|
||||
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row }
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 407, [IntPtr]($row - 2), $null)
|
||||
$bitmap = Render-Picker
|
||||
try {
|
||||
$divider = [FilesDriveShortcutTest+Rect]::new()
|
||||
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]($row - 1), [ref]$divider)
|
||||
$y = $divider.Top + [int][Math]::Floor(($divider.Bottom - $divider.Top) / 2)
|
||||
if ($y -le 0 -or $y -ge $bitmap.Height) { throw "Group divider is outside the rendered menu in panel $side (row $row, y $y, height $($bitmap.Height), top $([FilesDriveShortcutTest]::SendMessage($picker,398,[IntPtr]::Zero,$null)))." }
|
||||
$line = $bitmap.GetPixel(4, $y).ToArgb()
|
||||
if ($line -eq $bitmap.GetPixel(4, $y - 1).ToArgb() -or
|
||||
$line -ne $bitmap.GetPixel($bitmap.Width - 5, $y).ToArgb()) {
|
||||
throw "The local disks and FTP divider did not render in panel $side."
|
||||
}
|
||||
$ftpBounds = [FilesDriveShortcutTest+Rect]::new()
|
||||
[void][FilesDriveShortcutTest]::SendRect($picker, 408, [IntPtr]$row, [ref]$ftpBounds)
|
||||
$yellow = [Drawing.Color]::Yellow.ToArgb()
|
||||
$hasDigit = $false
|
||||
for ($lineY = $ftpBounds.Top; $lineY -lt $ftpBounds.Bottom -and $lineY -lt $bitmap.Height -and !$hasDigit; $lineY++) {
|
||||
for ($x = 0; $x -lt [Math]::Min(128,$bitmap.Width); $x++) {
|
||||
if ($bitmap.GetPixel($x,$lineY).ToArgb() -eq $yellow) { $hasDigit = $true; break }
|
||||
}
|
||||
}
|
||||
if (!$hasDigit) { throw "The FTP shortcut digit did not render in panel $side." }
|
||||
if ($Screenshot -and $side -eq 0) { $bitmap.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png) }
|
||||
} finally { $bitmap.Dispose() }
|
||||
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]($row - 2), $null)
|
||||
Press-Shortcut '1'
|
||||
$panelPath = [FilesDriveShortcutTest]::GetDlgItem($window, 142 + $side)
|
||||
$list = [FilesDriveShortcutTest]::GetDlgItem($window, 102 + $side)
|
||||
Wait-Until { (Read-Text $panelPath) -ceq 'FTP' }
|
||||
if ((Read-Text $list 393 0) -cne 'Test FTP profile') { throw "Saved FTP profile missing from panel $side." }
|
||||
$graphics = [Drawing.Graphics]::FromHwnd($list)
|
||||
try {
|
||||
$dc = $graphics.GetHdc()
|
||||
try {
|
||||
if (![FilesDriveShortcutTest]::PrintWindow($picker, $dc, 2)) { throw 'Could not render drive picker.' }
|
||||
if (![FilesDriveShortcutTest]::PrintWindow($list, $dc, 2)) { throw "FTP rows failed to render in panel $side." }
|
||||
} finally { $graphics.ReleaseHdc($dc) }
|
||||
return $bitmap
|
||||
} finally { $graphics.Dispose() }
|
||||
if ($process.HasExited) { throw "Files exited while rendering the FTP profile in panel $side." }
|
||||
}
|
||||
Write-Output 'Both source menus rendered the FTP shortcut, skipped group dividers, and opened FTP with 1.'
|
||||
return
|
||||
}
|
||||
if ($OfflineWake) {
|
||||
function Click-Picker([int]$X, [int]$Y) {
|
||||
$point = [IntPtr](($Y -shl 16) -bor $X)
|
||||
[void][FilesDriveShortcutTest]::PostMessage($picker, 513, [IntPtr]1, $point)
|
||||
@@ -137,5 +217,17 @@ try {
|
||||
}
|
||||
Write-Output 'Remote drives appeared automatically on both opens.'
|
||||
} finally {
|
||||
if (!$process.HasExited) { [void]$process.CloseMainWindow() }
|
||||
if ($previousDpi) { [void][FilesDriveShortcutTest]::SetThreadDpiAwarenessContext($previousDpi) }
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
if ($preferences -and !$process.WaitForExit(3000)) { Stop-Process -Id $process.Id; $process.WaitForExit() }
|
||||
}
|
||||
if ($preferences) {
|
||||
foreach ($name in $preferenceNames) {
|
||||
if ($savedPreferences.ContainsKey($name)) {
|
||||
$preferences.SetValue($name, $savedPreferences[$name][0], $savedPreferences[$name][1])
|
||||
} else { $preferences.DeleteValue($name, $false) }
|
||||
}
|
||||
$preferences.Close()
|
||||
}
|
||||
}
|
||||
@@ -189,7 +189,7 @@ try {
|
||||
|
||||
~~~mermaid
|
||||
flowchart TD
|
||||
A[Render target] --> B[Result]
|
||||
A[Render target] -->|Transition| B[Result]
|
||||
~~~
|
||||
|
||||
~~~mermaid
|
||||
@@ -276,7 +276,18 @@ const value = 42;
|
||||
[void](Wait-For 'Options to close after saving full width' { ![MarkdownUi]::IsWindowVisible($options) })
|
||||
Browser 'appearance-full'
|
||||
Write-Output 'Verified live Markdown width and font settings, Cancel and reopening the last Options section.'
|
||||
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Checking a task modified the read-only file.' }
|
||||
Browser 'toggle-first-task'
|
||||
$checkedFixture=$fixture.Replace('- [ ] Pending','- [x] Pending')
|
||||
[void](Wait-For 'Markdown checkbox saved to the source file' { [IO.File]::ReadAllText($original) -ceq $checkedFixture })
|
||||
Browser 'close'
|
||||
[void](Wait-For 'the initial preview to close' { ![MarkdownUi]::IsWindowVisible($window) })
|
||||
[MarkdownUi]::Activate($main)
|
||||
Wait-Foreground $main
|
||||
Open-File 'Preview.md' 0x72
|
||||
$window=Wait-For 'the reopened Markdown preview' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
|
||||
Browser 'first-task-checked'
|
||||
Browser 'toggle-first-task'
|
||||
[void](Wait-For 'the unchecked Markdown marker to save' { [IO.File]::ReadAllText($original) -ceq $fixture })
|
||||
[IO.File]::WriteAllText($original,($fixture.Replace('Перегляд Markdown','Зміна на диску')))
|
||||
Browser 'Зміна на диску' '' 'Preview.md'
|
||||
$replacement = Join-Path $docs 'Preview-replacement.md'
|
||||
@@ -393,7 +404,8 @@ const value = 42;
|
||||
}
|
||||
Post $control 0x100 0x75
|
||||
Answer-Save 7
|
||||
Post $window 0x10 0
|
||||
Browser 'external-replacement'
|
||||
Browser 'close'
|
||||
[void](Wait-For 'the conflict fixture to close' { !(Find-Window 'KSwitcher.Files.Text') })
|
||||
|
||||
Open-File 'Plain.txt' 0x72
|
||||
@@ -437,6 +449,8 @@ const value = 42;
|
||||
$window = Wait-For 'the LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Loopback peer' }
|
||||
[void](Assert-TextWindowAppearance $window 'Viewer')
|
||||
Browser 'render'
|
||||
Browser 'toggle-first-task'
|
||||
[void](Wait-For 'Markdown checkbox uploaded to the LAN peer' { [IO.File]::ReadAllText($original) -ceq $checkedFixture })
|
||||
Browser 'search'
|
||||
Browser 'edit'
|
||||
if ((Wait-For 'LAN F6 editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }) -ne $window) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { writeFile } from 'node:fs/promises';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
const [port, scenario, artifact, title] = process.argv.slice(2);
|
||||
const terminalScenario = ['terminal-enter', 'terminal-copy', 'terminal-select-output'].includes(scenario);
|
||||
const terminalScenario = scenario.startsWith('terminal-');
|
||||
let socket;
|
||||
const pending = new Map();
|
||||
let sequence = 0;
|
||||
@@ -69,7 +69,10 @@ await new Promise((resolve, reject) => {
|
||||
});
|
||||
|
||||
try {
|
||||
if (scenario === 'terminal-select-output') {
|
||||
if (scenario === 'terminal-startup-pause' || scenario === 'terminal-startup-resume') {
|
||||
await waitFor(() => evaluate('typeof startTerminalFixture === "function"'), 'the delayed terminal page');
|
||||
if (scenario === 'terminal-startup-resume') await evaluate('startTerminalFixture()');
|
||||
} else if (scenario === 'terminal-select-output') {
|
||||
const selection = await waitFor(() => evaluate(`(() => {
|
||||
const marker = 'terminal-output-copy-fixture';
|
||||
const buffer = terminal.buffer.active;
|
||||
@@ -82,6 +85,8 @@ try {
|
||||
})()`), 'the terminal output fixture');
|
||||
assert.equal(selection, 'terminal-output-copy-fixture');
|
||||
} else if (terminalScenario) {
|
||||
assert.equal(await evaluate('terminal.options.cursorInactiveStyle'), 'none');
|
||||
assert.equal(await evaluate('document.querySelectorAll(".xterm-cursor-outline").length'), 0);
|
||||
await evaluate('document.querySelector(".xterm-helper-textarea").focus()');
|
||||
const key = scenario === 'terminal-copy'
|
||||
? { key:'Insert', code:'Insert', modifiers:2, windowsVirtualKeyCode:45 }
|
||||
@@ -112,6 +117,14 @@ try {
|
||||
'the relative image in HTML');
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').getBoundingClientRect().height > 0`), true);
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').textContent.includes('Render target')`), true);
|
||||
assert.equal(await evaluate(`(() => {
|
||||
const paths = document.querySelector('figure svg g.edgePaths');
|
||||
const labels = document.querySelector('figure svg g.edgeLabels');
|
||||
const background = labels?.querySelector('.edgeLabel rect');
|
||||
return !!(paths && labels && background && labels.textContent.includes('Transition') &&
|
||||
(paths.compareDocumentPosition(labels) & Node.DOCUMENT_POSITION_FOLLOWING) &&
|
||||
getComputedStyle(background).opacity === '1');
|
||||
})()`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
|
||||
document.querySelector('main').textContent.includes('Invalid Mermaid diagram')`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-js') && !document.querySelector('iframe')`), true);
|
||||
@@ -120,14 +133,50 @@ try {
|
||||
await waitFor(() => evaluate(`document.querySelector('img[alt="Missing image"]')?.title === 'Image unavailable'`),
|
||||
'missing image feedback');
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => box.checked)`), [false, true]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [true, false]);
|
||||
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => { box.click(); return box.checked; })`), [false, true]);
|
||||
if (artifact) {
|
||||
const { cssContentSize } = await command('Page.getLayoutMetrics');
|
||||
const { data } = await command('Page.captureScreenshot', { captureBeyondViewport: true,
|
||||
clip: { x:0, y:0, width:cssContentSize.width, height:Math.min(cssContentSize.height, 620), scale:1 } });
|
||||
await writeFile(artifact, Buffer.from(data, 'base64'));
|
||||
}
|
||||
} else if (scenario === 'external-replacement') {
|
||||
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
|
||||
document.querySelector('main').textContent.trim() === 'An external replacement'`),
|
||||
'the replacement file rendered after discarding edits');
|
||||
} else if (scenario === 'diagram-reference') {
|
||||
await waitFor(() => evaluate("document.documentElement.classList.contains('rendered')"), 'rendered diagram page');
|
||||
const diagram = await evaluate(`(() => {
|
||||
const svg = document.querySelector('figure svg');
|
||||
const paths = svg?.querySelector('g.edgePaths');
|
||||
const labels = svg?.querySelector('g.edgeLabels');
|
||||
return {
|
||||
error: document.querySelector('pre code.language-mermaid')?.parentElement.previousElementSibling?.title,
|
||||
labels: [...(labels?.querySelectorAll('.edgeLabel') ?? [])]
|
||||
.map(label => label.textContent.trim()).filter(Boolean),
|
||||
paintedAbove: !!(paths && labels &&
|
||||
(paths.compareDocumentPosition(labels) & Node.DOCUMENT_POSITION_FOLLOWING)),
|
||||
opaque: [...(labels?.querySelectorAll('.edgeLabel rect') ?? [])].every(rect =>
|
||||
getComputedStyle(rect).opacity === '1'),
|
||||
};
|
||||
})()`);
|
||||
assert.equal(diagram.error, undefined, diagram.error);
|
||||
assert.deepEqual(diagram.labels.sort(), ['F3', 'F6', 'F6']);
|
||||
assert.equal(diagram.paintedAbove && diagram.opaque, true);
|
||||
if (artifact) {
|
||||
const { data } = await command('Page.captureScreenshot');
|
||||
await writeFile(artifact, Buffer.from(data, 'base64'));
|
||||
}
|
||||
} else if (scenario === 'toggle-first-task' || scenario === 'first-task-checked') {
|
||||
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
|
||||
!!document.querySelector('main li.task input')`), 'rendered Markdown task');
|
||||
if (scenario === 'toggle-first-task') {
|
||||
const target = "document.querySelector('main li.task input')";
|
||||
const before = await evaluate(target + '.checked');
|
||||
await evaluate(target + '.click()');
|
||||
await waitFor(() => evaluate(`!pendingTask && ${target}.checked !== ${before}`), 'saved Markdown task');
|
||||
}
|
||||
else
|
||||
assert.equal(await evaluate(`document.querySelector('main li.task input').checked`), true);
|
||||
} else if (scenario === 'search-menu' || scenario === 'search') {
|
||||
const searchFocused = 'document.activeElement === document.getElementById("search-query")';
|
||||
const searchClosed = 'document.getElementById("search").hidden';
|
||||
|
||||
@@ -57,7 +57,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
||||
return font;
|
||||
};
|
||||
dialogs.confirmExisting=[](HWND){return true;};
|
||||
dialogs.confirmSave=[](HWND)->INT_PTR {return IDYES;};
|
||||
dialogs.confirmSave=[](HWND,bool)->INT_PTR {return IDYES;};
|
||||
dialogs.message=[](HWND,const wchar_t *message){log(message);};
|
||||
dialogs.dismissOwned=[](HWND){return false;};
|
||||
files::openTextWindow(owner,document,false,dialogs,&peer);
|
||||
|
||||
@@ -11,7 +11,16 @@ public static class PanelFrameWindow {
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
@@ -38,11 +47,10 @@ function Read-Strip($X, $Y, $Width, $Height) {
|
||||
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
|
||||
$previousDpi = [PanelFrameWindow]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
try {
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
for ($attempt = 0; $attempt -lt 50; $attempt++) {
|
||||
$process.Refresh()
|
||||
$window = $process.MainWindowHandle
|
||||
if ($window -and $keyboard.AppActivate($process.Id)) { break }
|
||||
if ($window -and [PanelFrameWindow]::Activate($window)) { break }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
Start-Sleep -Milliseconds 300
|
||||
@@ -67,10 +75,19 @@ try {
|
||||
$x = $list.Left + 16
|
||||
$top = @(Read-Strip $x ($path.Top + [Math]::Floor(($path.Bottom - $path.Top) / 2) - 2) 1 4)
|
||||
if (($top -join ',') -ne ($side -join ',')) { throw "Panel $panel has an inconsistent top frame." }
|
||||
$start = $list.Left + [int](($list.Right - $list.Left) / 2)
|
||||
$width = $list.Right - $start
|
||||
$bodyPixels = @(Read-Strip $start ($list.Top + 2) $width 1)
|
||||
$headerPixels = @(Read-Strip $start ($header.Top + 2) $width 1)
|
||||
$bodyDivider = [Array]::IndexOf($bodyPixels, $side[0])
|
||||
$headerDivider = [Array]::IndexOf($headerPixels, $side[0])
|
||||
if ($bodyDivider -lt 0 -or $headerDivider -ne $bodyDivider) {
|
||||
throw "Panel $panel Size column divider is misaligned. Header offset: $headerDivider. Body offset: $bodyDivider."
|
||||
}
|
||||
$bottom = @(Read-Strip $x ($list.Bottom + 4) 1 ($header.Bottom - $header.Top + 6))
|
||||
$bottom = $bottom[($bottom.Count - 4)..($bottom.Count - 1)]
|
||||
if (($bottom -join ',') -ne ($side -join ',')) { throw "Panel $panel has an inconsistent bottom frame." }
|
||||
Write-Output "Panel $panel double frame verified on screen."
|
||||
Write-Output "Panel $panel double frame and Size column divider verified on screen."
|
||||
}
|
||||
} finally {
|
||||
if ($previousDpi) { [void][PanelFrameWindow]::SetThreadDpiAwarenessContext($previousDpi) }
|
||||
|
||||
+110
-10
@@ -1,4 +1,4 @@
|
||||
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly)
|
||||
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly,[switch]$CreateFileOnly)
|
||||
$ErrorActionPreference='Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @"
|
||||
@@ -19,6 +19,21 @@ public static class SearchArrowTest {
|
||||
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags);
|
||||
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hwnd);
|
||||
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
|
||||
[DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr hwnd, IntPtr rect, bool erase);
|
||||
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
|
||||
[DllImport("gdi32.dll")] static extern bool SetPixelV(IntPtr dc, int x, int y, uint color);
|
||||
public static bool EditorMenuProbe(IntPtr window, bool write) {
|
||||
const uint color = 0x00ff00ff;
|
||||
var dc = GetDC(window);
|
||||
if (dc == IntPtr.Zero) throw new InvalidOperationException("Cannot sample the editor.");
|
||||
try {
|
||||
if (write && !SetPixelV(dc, 4, 4, color))
|
||||
throw new InvalidOperationException("Cannot mark the editor menu.");
|
||||
return GetPixel(dc, 4, 4) == color;
|
||||
} finally { ReleaseDC(window, dc); }
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
|
||||
@@ -242,7 +257,7 @@ foreach($name in 'A.txt','B.txt','C.txt','D.txt'){
|
||||
$copy=Join-Path $scratch 'KSwitcher.Files.search-arrow-test.exe'
|
||||
Copy-Item -LiteralPath $Executable -Destination $copy
|
||||
$profile=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
|
||||
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement','FileStyles'
|
||||
$saved=@{}
|
||||
foreach($name in $keysToRestore){
|
||||
if($name -in $profile.GetValueNames()){
|
||||
@@ -256,6 +271,8 @@ try {
|
||||
$profile.SetValue('RightPath',$rightFixture)
|
||||
$profile.DeleteValue('LeftCursor',$false)
|
||||
$profile.DeleteValue('RightCursor',$false)
|
||||
$styles='[{"extension":".txt","background":3158064,"states":[{},{},{"background":3166352}]}]'
|
||||
$profile.SetValue('FileStyles',[Text.Encoding]::UTF8.GetBytes($styles),'Binary')
|
||||
$process=Start-Process -FilePath $copy -ArgumentList '--terminal-trace' -PassThru -WindowStyle Normal
|
||||
$paintTrace=Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
|
||||
$previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
@@ -267,6 +284,73 @@ try {
|
||||
[SearchArrowTest]::SendText($leftPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0 -and
|
||||
[SearchArrowTest]::SendText($rightPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0
|
||||
})
|
||||
if ($CreateFileOnly) {
|
||||
function Assert-DialogSurface($Dialog, [int]$Red, [int]$Green) {
|
||||
$bounds=Read-Bounds $Dialog
|
||||
$bitmap=[Drawing.Bitmap]::new(1,1)
|
||||
try {
|
||||
$graphics=[Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
[void](Wait-Until {
|
||||
$graphics.CopyFromScreen(($bounds.Left+4),($bounds.Top+4),0,0,$bitmap.Size)
|
||||
$pixel=$bitmap.GetPixel(0,0)
|
||||
$pixel.R -eq $Red -and $pixel.G -eq $Green -and $pixel.B -eq $Green
|
||||
})
|
||||
} finally { $graphics.Dispose() }
|
||||
} finally { $bitmap.Dispose() }
|
||||
}
|
||||
$keyboard=New-Object -ComObject WScript.Shell
|
||||
[void](Wait-Until { $keyboard.AppActivate($process.Id) })
|
||||
$keyboard.SendKeys('+{F4}')
|
||||
$open=Wait-Until { Find-Window '#32770' $process.Id 461 }
|
||||
Assert-DialogSurface $open 192 192
|
||||
Post $open 0x111 1
|
||||
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
|
||||
$title=[Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($editor,0xD,$title.Capacity,$title)
|
||||
if ($title.ToString() -notmatch '(New_File_[0-9-]+_[0-9.]+\.txt)$') { throw "Missing generated name in $title." }
|
||||
$generated=$Matches[1]
|
||||
if (Test-Path -LiteralPath (Join-Path $scratch $generated)) { throw 'Opening a draft created a file.' }
|
||||
$control=Wait-Until { [SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[NullString]::Value) }
|
||||
Start-Sleep -Milliseconds 150
|
||||
if (![SearchArrowTest]::EditorMenuProbe($editor,$true)) { throw 'Cannot mark the editor menu for the repaint check.' }
|
||||
foreach($ch in 'First'.ToCharArray()){Post $control 0x102 ([int]$ch)}
|
||||
Post $control 0x100 13
|
||||
foreach($ch in 'Second'.ToCharArray()){Post $control 0x102 ([int]$ch)}
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($control,2159,0,0).ToInt64() })
|
||||
Start-Sleep -Milliseconds 150
|
||||
$menuWasPreserved=[SearchArrowTest]::EditorMenuProbe($editor,$false)
|
||||
[void][SearchArrowTest]::InvalidateRect($editor,0,$false)
|
||||
if (!$menuWasPreserved) { throw 'Typing in a draft repainted the unchanged editor menu.' }
|
||||
foreach($cancel in $true,$false) {
|
||||
Post $control 0x100 27
|
||||
$confirm=Wait-Until { Find-Window '#32770' $process.Id 6 }
|
||||
Assert-DialogSurface $confirm 128 0
|
||||
Post $confirm 0x111 6
|
||||
$save=Wait-Until { Find-Window '#32770' $process.Id 464 }
|
||||
Assert-DialogSurface $save 192 192
|
||||
$name=[SearchArrowTest]::GetDlgItem($save,461)
|
||||
$current=[Text.StringBuilder]::new(1024)
|
||||
[void][SearchArrowTest]::GetText($name,0xD,$current.Capacity,$current)
|
||||
if ($current.ToString() -ne $generated) { throw 'Save options did not carry the generated name.' }
|
||||
if ($cancel) {
|
||||
Post $save 0x111 2
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindow($save) -and [SearchArrowTest]::IsWindow($editor) })
|
||||
continue
|
||||
}
|
||||
[void][SearchArrowTest]::SendText($name,0x0C,0,'created.txt')
|
||||
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,464),0xF1,1,0)
|
||||
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,472),0xF5,0,0)
|
||||
Post $save 0x111 1
|
||||
}
|
||||
$result=Join-Path $scratch 'created.txt'
|
||||
[void](Wait-Until { (Test-Path -LiteralPath $result) -and ![SearchArrowTest]::IsWindow($editor) })
|
||||
if ([Convert]::ToHexString([IO.File]::ReadAllBytes($result)) -ne 'EFBBBF46697273740A5365636F6E64') {
|
||||
throw 'The saved bytes must contain a UTF-8 BOM and LF line endings.'
|
||||
}
|
||||
Write-Output 'Verified Shift+F4, the generated name, Escape confirmation, cancellation, and Save options.'
|
||||
return
|
||||
}
|
||||
if (!$KeyboardCursorOnly) {
|
||||
$leftPath = [SearchArrowTest]::GetDlgItem($main,142)
|
||||
foreach ($step in @(@{ Row='[Right fixture]'; Path=$rightFixture }, @{ Row='..'; Path=$scratch })) {
|
||||
@@ -290,12 +374,27 @@ try {
|
||||
Write-Output 'Verified folder navigation repaints only the panel that changes directories.'
|
||||
}
|
||||
$clicks=if(!$KeyboardCursorOnly){
|
||||
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
|
||||
@(@{Panel=$leftPanel; Index=0},
|
||||
@{Panel=$rightPanel; Index=1; Label='A.txt'},
|
||||
@{Panel=$leftPanel; Index=0; Label='A.txt'},
|
||||
@{Panel=$rightPanel; Index=1; Label='..'; UnfocusedStyle=$true},
|
||||
@{Panel=$rightPanel; Index=1; Label='A.txt'})
|
||||
}
|
||||
$activeIndex=0
|
||||
foreach($check in $clicks) {
|
||||
$before=[SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32()
|
||||
$top=[SearchArrowTest]::Send($check.Panel,0x18E,0,0).ToInt32()
|
||||
$row=if($before -eq $top){$top+1}else{$top}
|
||||
$row=if($check.Label){[SearchArrowTest]::SendText($check.Panel,0x1A2,-1,$check.Label).ToInt32()}
|
||||
elseif($before -eq $top){$top+1}else{$top}
|
||||
if($row -lt 0 -or $row -eq $before){throw 'The click fixture must move the cursor.'}
|
||||
$previousKey="$($check.Index)/$before"
|
||||
$expected=@{"$($check.Index)/$row"='1'}
|
||||
if($check.Index -ne $activeIndex){
|
||||
$source=if($activeIndex -eq 0){$leftPanel}else{$rightPanel}
|
||||
$sourceRow=[SearchArrowTest]::Send($source,0x188,0,0).ToInt32()
|
||||
$expected["$activeIndex/$sourceRow"]='0'
|
||||
}
|
||||
if($check.Index -eq $activeIndex -or $check.UnfocusedStyle){$expected[$previousKey]='0'}
|
||||
[void](Wait-Until { Test-Path -LiteralPath $paintTrace })
|
||||
Start-Sleep -Milliseconds 150
|
||||
$lineCount=@(Get-Content -LiteralPath $paintTrace).Count
|
||||
@@ -303,14 +402,15 @@ try {
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32() -eq $row })
|
||||
Start-Sleep -Milliseconds 150
|
||||
$highlight=Read-PanelHighlights $paintTrace $lineCount
|
||||
$draws=@($highlight.Keys)
|
||||
if("$($check.Index)/$row" -notin $draws -or $draws.Count -gt 3){
|
||||
throw "Clicking a row repainted unrelated file rows. Drawn rows: $draws"
|
||||
if($highlight.Count -ne $expected.Count -or
|
||||
@($expected.Keys | Where-Object {$highlight[$_] -ne $expected[$_]}).Count){
|
||||
throw "Unexpected cursor redraw. Expected rows: $($expected.Keys -join ', '). Drawn rows: $($highlight.Keys -join ', ')."
|
||||
}
|
||||
if($highlight["$($check.Index)/$row"] -ne '1' -or
|
||||
($before -ge $top -and $highlight["$($check.Index)/$before"] -ne '0')){
|
||||
throw 'The new row must be painted active and the previous visible row must lose its highlight.'
|
||||
if($check.Index -ne $activeIndex -and (Get-Content -LiteralPath $paintTrace | Select-Object -Skip $lineCount |
|
||||
Where-Object {$_ -match "^\d+ panel-draw $($check.Index) $before 1 "})){
|
||||
throw 'The old row in the destination panel flashed as the active cursor.'
|
||||
}
|
||||
$activeIndex=$check.Index
|
||||
}
|
||||
if($clicks){Write-Output 'Verified file clicks repaint only cursor rows in the active pane and when changing panes.'}
|
||||
Post $main 0x111 132
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using ks::files::TextDocument;
|
||||
using ks::files::TextEncoding;
|
||||
using ks::files::TextLineEnding;
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -141,6 +143,43 @@ void sparseFile(const fs::path &file)
|
||||
document.stage(index, "edited");
|
||||
check(document.readPage(index) == "edited", "Stage an edit past 4 GiB");
|
||||
}
|
||||
|
||||
void saveDraft(const fs::path &file)
|
||||
{
|
||||
TextDocument draft({});
|
||||
check(draft.readPage(0).empty() && draft.pages()==1, "Start with an empty draft");
|
||||
draft.stage(0,"one\r\ntwo\rthree\n");
|
||||
writeFile(file,"existing");
|
||||
bool rejected{};
|
||||
try {draft.saveNew(file,{});}
|
||||
catch(const std::exception &) {rejected=true;}
|
||||
check(rejected && draft.modified() && readFile(file)=="existing", "Preserve a conflicting file and the draft");
|
||||
fs::remove(file);
|
||||
check(draft.saveNew(file,{TextEncoding::utf8,true,TextLineEnding::lf}), "Save a draft as a new file");
|
||||
check(readFile(file)=="\xef\xbb\xbfone\ntwo\nthree\n" && draft.readPage(0)=="one\ntwo\nthree\n",
|
||||
"Save a UTF-8 signature and normalize mixed line endings");
|
||||
draft.stage(0,"after");
|
||||
check(draft.save() && readFile(file)=="\xef\xbb\xbf" "after", "Edit normally after the first save");
|
||||
|
||||
const auto ansiFile=file.parent_path()/L"windows1252.txt";
|
||||
TextDocument ansiDraft({});
|
||||
ansiDraft.stage(0,"caf\xc3\xa9\n");
|
||||
check(ansiDraft.saveNew(ansiFile,{TextEncoding::windows1252,false,TextLineEnding::crlf}),
|
||||
"Save a draft in Windows-1252");
|
||||
check(readFile(ansiFile)=="caf\xe9\r\n" && ansiDraft.readPage(0)=="caf\xc3\xa9\r\n",
|
||||
"Round-trip Windows-1252 text and CRLF");
|
||||
TextDocument ansiReader(ansiFile,false,TextEncoding::windows1252);
|
||||
check(ansiReader.readPage(0)=="caf\xc3\xa9\r\n", "Open an existing file with an explicit code page");
|
||||
|
||||
const auto unicodeFile=file.parent_path()/L"utf16be.txt";
|
||||
TextDocument unicodeDraft({});
|
||||
unicodeDraft.stage(0,"a\n");
|
||||
check(unicodeDraft.saveNew(unicodeFile,{TextEncoding::utf16be,true,TextLineEnding::cr}),
|
||||
"Save a UTF-16 draft with a signature");
|
||||
TextDocument unicodeReader(unicodeFile,false);
|
||||
check(readFile(unicodeFile)==std::string("\xfe\xff\0a\0\r",6) && unicodeReader.readPage(0)=="a\r",
|
||||
"Detect the UTF-16 signature and read CR line endings");
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
@@ -151,6 +190,7 @@ int main()
|
||||
editsAcrossPages(fixture.directory / L"pages.txt");
|
||||
unicodeBoundaries(fixture.directory / L"unicode.txt");
|
||||
rejectExternalReplacement(fixture.directory / L"external.txt");
|
||||
saveDraft(fixture.directory / L"created.txt");
|
||||
sparseFile(fixture.directory / L"5gib.log");
|
||||
std::cout << "Files text document regressions passed.\n";
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user