Compare commits
5
Commits
release-v0.6.117
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
debd2b9cd9 | ||
|
|
90c93fba8c | ||
|
|
a09d5e72d1 | ||
|
|
c0bca1b4a2 | ||
|
|
d5ee6ee024 |
No files matched your search
+8
-2
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.117 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)
|
||||
@@ -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
|
||||
|
||||
+51
-5
@@ -57,6 +57,36 @@ Warning і початковий фокус на No.
|
||||
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
|
||||
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
|
||||
|
||||
- **F9 → Commands → Compare files** порівнює два позначені текстові файли
|
||||
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
|
||||
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
|
||||
FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
|
||||
рядків і підсвічуванням вставок, видалень і замін. У замінених рядках
|
||||
виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8)
|
||||
переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків.
|
||||
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
|
||||
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
|
||||
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
|
||||
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
|
||||
Текст файлів і порожня область під ним мають білий фон, рядки
|
||||
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
|
||||
Центральний розділювач можна перетягнути мишею. Під час зміни розміру
|
||||
вікна пропорція колонок зберігається.
|
||||
Ctrl+колесо змінює масштаб тексту в поточному вікні.
|
||||
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
|
||||
на панелі завдань. У **Options → File comparison → Font and colors**
|
||||
можна окремо налаштувати шрифт, тло, текст і кольори змін.
|
||||
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
|
||||
і меню Commands показує поточне призначення.
|
||||
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
|
||||
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
|
||||
Вставлені й видалені порожні рядки враховуються завжди.
|
||||
Кнопка розгортання в системному заголовку збільшує вікно порівняння
|
||||
до робочої області екрана. Повторне натискання відновлює попередній розмір.
|
||||
Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM,
|
||||
до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються
|
||||
як рівнозначні.
|
||||
|
||||
- У меню Files і його списках, що випадають, стрілки вгору й вниз
|
||||
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
|
||||
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
|
||||
@@ -86,6 +116,7 @@ Warning і початковий фокус на No.
|
||||
керують панеллю, коли список підказок закритий.
|
||||
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
|
||||
командний рядок порожній.
|
||||
Ctrl+← і Ctrl+→ зміщують розділювач видимих панелей на ширину одного символу.
|
||||
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
|
||||
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
|
||||
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
|
||||
@@ -98,14 +129,19 @@ Warning і початковий фокус на No.
|
||||
Enter передає порожній рядок у термінал.
|
||||
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
|
||||
командного рядка й виконують відповідну дію за тими самими правилами.
|
||||
Локальна команда запускається в папці активної панелі, яку показано
|
||||
перед командним рядком. Після перемикання панелі або переходу до іншої
|
||||
папки наступна команда використовує нову папку навіть у вже відкритому
|
||||
PowerShell. Якщо команда змінює папку (наприклад, через `cd`), панель
|
||||
переходить до неї, якщо користувач за цей час не змінив її розташування.
|
||||
Під час запуску термінала область виводу має темне тло, поки WebView2
|
||||
готує сторінку.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
- Під час набору локальної команди над полем з’являються підказки PowerShell.
|
||||
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
|
||||
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
|
||||
та шляхи відносно робочої папки термінала або активної панелі до запуску
|
||||
термінала. Після `cd ` список пропонує папки,
|
||||
та шляхи відносно робочої папки активної панелі.
|
||||
Після `cd ` список пропонує папки,
|
||||
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
|
||||
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
|
||||
Enter вставляє виділену, а клік вставляє підказку під вказівником.
|
||||
@@ -186,6 +222,10 @@ Warning і початковий фокус на No.
|
||||
Якщо надійшов новіший запит, результат попереднього
|
||||
сканування пропускається. Після підтвердження UAC очікування списку
|
||||
від підвищеного процесу теж відбувається у фоні.
|
||||
- Якщо Windows відмовляє у правах для F5, F6, F7 або F8 на локальних
|
||||
дисках, Files пропонує повторити операцію з правами адміністратора.
|
||||
Після підтвердження UAC допоміжний процес обробляє захищені елементи
|
||||
поточної операції. Відмова в діалозі або в UAC зупиняє операцію.
|
||||
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
|
||||
зберігаються для наявних елементів, а підраховані через F3 розміри папок
|
||||
скидаються. F2 також виконує цю дію.
|
||||
@@ -271,9 +311,10 @@ Warning і початковий фокус на No.
|
||||
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
|
||||
рядків. Скасування параметрів залишає текст у редакторі.
|
||||
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
|
||||
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
|
||||
із підсвічуванням Markdown.
|
||||
інтерактивними чекбоксами списків і діаграмами Mermaid. Клік по чекбоксу
|
||||
одразу записує позначку у вихідний Markdown. У разі помилки збереження
|
||||
попередній стан відновлюється. Підписи з'єднань малюються поверх стрілок.
|
||||
F4 відкриває текст із підсвічуванням Markdown.
|
||||
HTML усередині Markdown підтримує таблиці, текстове форматування, посилання,
|
||||
відносні зображення й окремі стилі, зокрема `white-space: nowrap` у клітинках.
|
||||
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
|
||||
@@ -305,6 +346,11 @@ Warning і початковий фокус на No.
|
||||
Esc скасовує поточний підрахунок і чергу активної панелі, залишаючи
|
||||
вже обчислені розміри та поточний каталог.
|
||||
Перехід до іншого каталогу чи джерела панелі скасовує підрахунок.
|
||||
- Під списком кожної панелі з позначками показано кількість позначених
|
||||
елементів і їхній сумарний розмір. Файли враховуються одразу, папки — у
|
||||
міру завершення підрахунку через F3. Позначка ≥ означає, що сума
|
||||
неповна, а число біля «to measure» показує, скільки позначених папок
|
||||
ще без розміру.
|
||||
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
|
||||
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
|
||||
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
|
||||
|
||||
@@ -1,5 +1,27 @@
|
||||
# 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**.
|
||||
|
||||
@@ -1 +1 @@
|
||||
b11409bce6fcc98484107e6c56c13d3830b5c1c6d58515ab7f395ede30dc6d5b KSwitcher-win-x64.zip
|
||||
566cda1b26bbc5980e3e19f804ae500bf029fe6f5a503cfd609be6f6ad4409ea KSwitcher-win-x64.zip
|
||||
+13
-13
@@ -1,25 +1,26 @@
|
||||
{
|
||||
"version": "0.6.117",
|
||||
"version": "0.6.119",
|
||||
"schema": 1,
|
||||
"files": [
|
||||
{
|
||||
"size": 2479104,
|
||||
"path": "KSwitcher.exe",
|
||||
"sha256": "4ea5e71940d5cd1cbd062c6eead6a57d6c9a7b8a3884f2d8707267872643a55f"
|
||||
"sha256": "e6b98679ac0a460e42ec9f593e88cc802cedaaaf887bce79c3f8577419143aa1"
|
||||
},
|
||||
{
|
||||
"size": 2458112,
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"sha256": "3576d94c26dbed409dc12a13fb570d3dac5d35f8df1cf79761758a1e308e6b89"
|
||||
"sha256": "43e4ea0d087d70658fd2cca47b2f06b919eb86acc65dce1afa7db1e02cbdcded"
|
||||
},
|
||||
{
|
||||
"size": 3060224,
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"sha256": "738a6c42f56bd44d3cd871d53d51aa9580c3a20825c5407d2bb36ce512fe2103"
|
||||
"sha256": "9b791b2dbf623f50ab92cde4017b07c9f8df4bbb7ac3526d0d18e0d770061f43"
|
||||
},
|
||||
{
|
||||
"size": 4286976,
|
||||
"size": 4370944,
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"sha256": "f1231f85448b57771e6ce1f8e416282af8d9112f093bd05cb26881c79ccd5cc5"
|
||||
"sha256": "e44a923d3e686e0e273e6dd167f6bd66dafd66e2870b4950fcbd8824d286a61d"
|
||||
},
|
||||
{
|
||||
"size": 194912,
|
||||
@@ -52,14 +53,14 @@
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
|
||||
},
|
||||
{
|
||||
"size": 3530,
|
||||
"size": 3635,
|
||||
"path": "terminal/markdown.html",
|
||||
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
|
||||
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79"
|
||||
},
|
||||
{
|
||||
"size": 15014,
|
||||
"size": 16944,
|
||||
"path": "terminal/markdown.js",
|
||||
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763"
|
||||
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8"
|
||||
},
|
||||
{
|
||||
"size": 1089,
|
||||
@@ -154,13 +155,12 @@
|
||||
{
|
||||
"size": 133120,
|
||||
"path": "tools/StayHere.exe",
|
||||
"sha256": "ebe97d3b7f267632b90463358bcc2518cad12f43c1eb568d2749a08f88a4bd97"
|
||||
"sha256": "d689b74a0c5ba018d3f26eb32c4fab88a8404627ee69be1e326d60b1167b5667"
|
||||
},
|
||||
{
|
||||
"size": 2796,
|
||||
"path": "tools/StayHere-README.md",
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
|
||||
}
|
||||
],
|
||||
"schema": 1
|
||||
]
|
||||
}
|
||||
+3
-3
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
201 RCDATA "update.ps1"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 0,6,117,0
|
||||
PRODUCTVERSION 0,6,117,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.117"
|
||||
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"
|
||||
|
||||
@@ -203,6 +204,14 @@ BEGIN
|
||||
PUSHBUTTON "Choose &font…", 377, 306, 68, 76, 14
|
||||
LTEXT "Font &size (8–72 pt)", 378, 131, 99, 184, 12
|
||||
EDITTEXT 379, 318, 96, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
LTEXT "", 408, 131, 30, 254, 14
|
||||
PUSHBUTTON "Change &font…", 409, 131, 49, 82, 15
|
||||
LTEXT "Comparison &color", 410, 131, 79, 117, 12
|
||||
COMBOBOX 411, 250, 76, 132, 126, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "Change color…", 412, 250, 97, 82, 15
|
||||
LTEXT "", 413, 338, 100, 45, 12
|
||||
LTEXT "Compare files &shortcut", 414, 131, 130, 117, 12
|
||||
CONTROL "", 415, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 250, 127, 132, 15
|
||||
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
|
||||
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
|
||||
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
|
||||
@@ -376,3 +385,25 @@ BEGIN
|
||||
CONTROL "&Rename", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 51, 86, 18
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 51, 86, 18
|
||||
END
|
||||
|
||||
114 DIALOGEX 0, 0, 510, 252
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_CLIPCHILDREN
|
||||
EXSTYLE WS_EX_APPWINDOW
|
||||
CAPTION "Compare files"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "", 400, 4, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 401, 259, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 45, 510, 207
|
||||
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
|
||||
LTEXT "", 403, 216, 12, 98, 14
|
||||
END
|
||||
|
||||
115 DIALOGEX 0, 0, 290, 58
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Compare files"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
|
||||
END
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
@@ -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');
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
};
|
||||
+23
-7
@@ -30,13 +30,20 @@ struct CopyHost
|
||||
{
|
||||
std::optional<FilesConnection> files;
|
||||
std::optional<FtpSession> ftp;
|
||||
FileOperationElevation *elevation{};
|
||||
fs::path listedDirectory;
|
||||
FileEntries listedEntries;
|
||||
|
||||
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile)
|
||||
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile,FileOperationElevation *admin=nullptr)
|
||||
{
|
||||
if(profile) ftp.emplace(*profile);
|
||||
else files.emplace(peer);
|
||||
if(!peer && !profile) elevation=admin;
|
||||
}
|
||||
|
||||
Json request(const Json &message,const ks::lan::FileProgress &progress={})
|
||||
{
|
||||
return elevation?elevation->call(*files,message,progress):files->call(message,progress);
|
||||
}
|
||||
|
||||
const FileEntries &ftpListing(const fs::path &path,const std::atomic_bool &canceled)
|
||||
@@ -51,19 +58,28 @@ struct CopyHost
|
||||
|
||||
std::optional<FileInfo> stat(const fs::path &path,const std::atomic_bool &canceled)
|
||||
{
|
||||
return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(*files,path);
|
||||
return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path)));
|
||||
}
|
||||
|
||||
FileEntries children(const fs::path &path,const std::atomic_bool &canceled)
|
||||
{
|
||||
return ftp?ftpListing(path,canceled):childrenOf(*files,path);
|
||||
if(ftp) return ftpListing(path,canceled);
|
||||
if(!elevation) return childrenOf(*files,path);
|
||||
FileEntries entries;
|
||||
elevation->list(*files,path,[&](const fs::path &child,const FileInfo &info)
|
||||
{
|
||||
if(canceled) return false;
|
||||
entries.emplace_back(child,info);
|
||||
return true;
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
void makeDirectory(const fs::path &path)
|
||||
{
|
||||
if(!ftp)
|
||||
{
|
||||
checkFileReply(files->call(fileRequest("mkdir",path)));
|
||||
checkFileReply(request(fileRequest("mkdir",path)));
|
||||
return;
|
||||
}
|
||||
ftp->setDirectory(path.parent_path());
|
||||
@@ -81,9 +97,9 @@ struct CopyHost
|
||||
FtpRemoveDirectoryA(ftp->handle(),name.c_str()):FtpDeleteFileA(ftp->handle(),name.c_str()));
|
||||
return;
|
||||
}
|
||||
auto request=fileRequest(permanent?"remove":"recycle",path);
|
||||
request["readOnly"]=readOnly;
|
||||
checkFileReply(files->call(request));
|
||||
auto message=fileRequest(permanent?"remove":"recycle",path);
|
||||
message["readOnly"]=readOnly;
|
||||
checkFileReply(request(message));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+239
-66
@@ -36,6 +36,7 @@
|
||||
#include "lan_files.h"
|
||||
#include "lan_wake.h"
|
||||
#include "platform.h"
|
||||
#include "../resources/resource.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -52,27 +53,35 @@ FileInfo fileInfo(const Json &row)
|
||||
{
|
||||
return {row.at("attributes"),row.at("size"),row.at("modified")};
|
||||
}
|
||||
std::optional<FileInfo> statFile(FilesConnection &host,const fs::path &path)
|
||||
std::optional<FileInfo> statFile(const Json &reply)
|
||||
{
|
||||
const auto reply=host.call(fileRequest("stat",path));
|
||||
const auto error=reply.at("error").get<DWORD>();
|
||||
if(error==ERROR_FILE_NOT_FOUND || error==ERROR_PATH_NOT_FOUND) return {};
|
||||
checkFileReply(reply);
|
||||
return fileInfo(reply);
|
||||
}
|
||||
std::optional<FileInfo> statFile(FilesConnection &host,const fs::path &path)
|
||||
{
|
||||
return statFile(host.call(fileRequest("stat",path)));
|
||||
}
|
||||
using FileVisitor=std::function<bool(const fs::path &,const FileInfo &)>;
|
||||
bool listFiles(FilesConnection &host,const fs::path &directory,const FileVisitor &visit)
|
||||
template<class NextPage>
|
||||
bool listFilePages(Json page,const fs::path &directory,const FileVisitor &visit,NextPage next)
|
||||
{
|
||||
auto page=host.call(fileRequest("list",directory));
|
||||
for(;;)
|
||||
{
|
||||
checkFileReply(page);
|
||||
for(const auto &row:page.at("entries"))
|
||||
if(!visit(directory/filePath(row.at("name")),fileInfo(row))) return false;
|
||||
if(!page.at("more").get<bool>()) return true;
|
||||
page=host.call({{"action","listNext"}});
|
||||
page=next();
|
||||
}
|
||||
}
|
||||
bool listFiles(FilesConnection &host,const fs::path &directory,const FileVisitor &visit)
|
||||
{
|
||||
return listFilePages(host.call(fileRequest("list",directory)),directory,visit,
|
||||
[&]{return host.call({{"action","listNext"}});});
|
||||
}
|
||||
std::wstring fileError(const std::system_error &error)
|
||||
{
|
||||
wchar_t *message{};
|
||||
@@ -182,23 +191,24 @@ DWORD listElevatedFolder(const fs::path &directory, const std::wstring &pipeName
|
||||
return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error;
|
||||
}
|
||||
|
||||
struct ElevatedFolderListing
|
||||
struct ElevatedHelper
|
||||
{
|
||||
Handle pipe{}, process{};
|
||||
};
|
||||
|
||||
DWORD launchElevatedFolder(HWND owner,const fs::path &directory,ElevatedFolderListing &session)
|
||||
DWORD launchElevatedHelper(HWND owner,std::wstring_view prefix,const std::wstring &command,
|
||||
const std::wstring &arguments,ElevatedHelper &session)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t token[40]{}, executable[32768]{};
|
||||
auto length=GetModuleFileNameW(nullptr,executable,static_cast<DWORD>(std::size(executable)));
|
||||
if(!length || length>=std::size(executable) || FAILED(CoCreateGuid(&id)) ||
|
||||
!StringFromGUID2(id,token,static_cast<int>(std::size(token)))) return ERROR_GEN_FAILURE;
|
||||
auto name=std::wstring(folderPipePrefix)+token;
|
||||
auto name=std::wstring(prefix)+token;
|
||||
session.pipe.value=CreateNamedPipeW(name.c_str(),PIPE_ACCESS_DUPLEX|FILE_FLAG_FIRST_PIPE_INSTANCE,
|
||||
PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_NOWAIT|PIPE_REJECT_REMOTE_CLIENTS,1,0,4096,0,nullptr);
|
||||
if(session.pipe.value==INVALID_HANDLE_VALUE) return GetLastError();
|
||||
auto parameters=L"--list-folder \""+(directory/L".").wstring()+L"\" \""+name+L"\"";
|
||||
auto parameters=command+L" "+arguments+L" \""+name+L"\"";
|
||||
SHELLEXECUTEINFOW launch{};
|
||||
launch.cbSize=sizeof(launch);
|
||||
launch.fMask=SEE_MASK_NOCLOSEPROCESS|SEE_MASK_NOASYNC;
|
||||
@@ -212,8 +222,13 @@ DWORD launchElevatedFolder(HWND owner,const fs::path &directory,ElevatedFolderLi
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
DWORD launchElevatedFolder(HWND owner,const fs::path &directory,ElevatedHelper &session)
|
||||
{
|
||||
return launchElevatedHelper(owner,folderPipePrefix,L"--list-folder",
|
||||
L"\""+(directory/L".").wstring()+L"\"",session);
|
||||
}
|
||||
|
||||
DWORD readElevatedFolder(const ElevatedFolderListing &session,const fs::path &directory,
|
||||
DWORD readElevatedFolder(const ElevatedHelper &session,const fs::path &directory,
|
||||
std::vector<fs::path> &folders,std::vector<fs::path> &files,
|
||||
std::map<fs::path,FolderEntryMetadata> &metadata,
|
||||
std::atomic_size_t &entriesRead,std::stop_token stop)
|
||||
@@ -358,7 +373,7 @@ struct Panel
|
||||
std::optional<FilesPeer> peer;
|
||||
bool offerElevation{};
|
||||
uint64_t statusRevision{};
|
||||
std::shared_ptr<ElevatedFolderListing> elevated;
|
||||
std::shared_ptr<ElevatedHelper> elevated;
|
||||
std::optional<FtpProfile> ftp;
|
||||
};
|
||||
struct ScanResult
|
||||
@@ -382,6 +397,7 @@ struct Panel
|
||||
std::vector<std::wstring> sizes;
|
||||
std::vector<bool> dimmed;
|
||||
std::vector<bool> marked;
|
||||
HWND selectionSummary{};
|
||||
FolderSizes folderSizes;
|
||||
std::shared_ptr<FolderSizeJob> folderSizeJob;
|
||||
std::set<fs::path> folderSizeWaiting;
|
||||
@@ -425,7 +441,12 @@ HWND terminalInput{},terminalOutput{},terminalPrompt{};
|
||||
constexpr UINT_PTR terminalTimer=2;
|
||||
constexpr UINT_PTR directoryWatchTimer=4;
|
||||
bool terminalVisible{};
|
||||
std::deque<int> terminalCommandPanels;
|
||||
struct TerminalCommandContext
|
||||
{
|
||||
int panel=-1;
|
||||
fs::path directory;
|
||||
};
|
||||
std::deque<TerminalCommandContext> terminalCommands;
|
||||
std::wstring terminalDirectory;
|
||||
int terminalRows{};
|
||||
struct CommandEntry { std::wstring date, command; };
|
||||
@@ -533,6 +554,7 @@ struct FilesNoticeOptions
|
||||
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
|
||||
void openMenu(HWND window, int index);
|
||||
void showFileDetails(const Panel &panel);
|
||||
void updateSelectionSummary(const Panel &panel);
|
||||
void editOptions(HWND owner);
|
||||
void showFolderShortcuts(Panel &panel,int digit);
|
||||
void layout(HWND window,bool activeOnly=false);
|
||||
@@ -678,6 +700,7 @@ bool applyFont(HWND owner, LOGFONTW font, int points)
|
||||
for(auto &panel:panels)
|
||||
{
|
||||
if(panel.path) SendMessageW(panel.path,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
if(panel.selectionSummary) SendMessageW(panel.selectionSummary,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
if(panel.list) SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight);
|
||||
}
|
||||
if(picker) SendMessageW(picker,LB_SETITEMHEIGHT,0,textHeight);
|
||||
@@ -1043,20 +1066,44 @@ void swapPanels(HWND window)
|
||||
// Move the controls with their contents to retain the cursor and scroll position.
|
||||
std::swap(panels[0],panels[1]);
|
||||
active=1-active;
|
||||
for(auto &panel:terminalCommandPanels)
|
||||
if(panel>=0) panel=1-panel;
|
||||
for(auto &command:terminalCommands)
|
||||
if(command.panel>=0) command.panel=1-command.panel;
|
||||
for(int i=0;i<2;++i)
|
||||
{
|
||||
const auto &panel=panels[i];
|
||||
SetWindowLongPtrW(panel.list,GWLP_ID,102+i);
|
||||
SetWindowLongPtrW(panel.heading,GWLP_ID,140+i);
|
||||
SetWindowLongPtrW(panel.path,GWLP_ID,142+i);
|
||||
SetWindowLongPtrW(panel.selectionSummary,GWLP_ID,154+i);
|
||||
savePreference(panelModeKeys[i],panel.wide);
|
||||
}
|
||||
notifyFilesPreferences(window);
|
||||
layout(window);
|
||||
}
|
||||
|
||||
bool hasSelectionSummary()
|
||||
{
|
||||
return GetWindowTextLengthW(panels[0].selectionSummary) || GetWindowTextLengthW(panels[1].selectionSummary);
|
||||
}
|
||||
|
||||
int clampPanelDivider(int position,int width)
|
||||
{
|
||||
return std::clamp(position,120,std::max(120,width-120));
|
||||
}
|
||||
|
||||
int panelDivider(int width)
|
||||
{
|
||||
return clampPanelDivider(split?split:width/2,width);
|
||||
}
|
||||
|
||||
void setPanelDivider(HWND window,int width,int position)
|
||||
{
|
||||
const auto next=clampPanelDivider(position,width);
|
||||
if(next==panelDivider(width)) return;
|
||||
split=next;
|
||||
layout(window);
|
||||
}
|
||||
|
||||
void layout(HWND window,bool activeOnly)
|
||||
{
|
||||
RECT rect{};
|
||||
@@ -1064,13 +1111,14 @@ void layout(HWND window,bool activeOnly)
|
||||
int width = rect.right, height = rect.bottom;
|
||||
const int inputTop=height-2*textHeight;
|
||||
const int terminalBottom=std::max(4,inputTop);
|
||||
const int detailsHeight=terminalVisible?0:textHeight+12;
|
||||
const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0;
|
||||
const int detailsHeight=terminalVisible?0:textHeight+12+summaryHeight;
|
||||
const int terminalTop=terminalVisible?4:std::max(4,terminalBottom-
|
||||
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/textHeight-4))*textHeight);
|
||||
const int panelBottom=terminalTop-detailsHeight;
|
||||
const bool showOutput=terminalTop<terminalBottom;
|
||||
traceTerminal("layout",terminalRows,terminalTop,terminalBottom,showOutput,terminalVisible);
|
||||
int middle = std::clamp(split ? split : width / 2, 120, std::max(120, width - 120));
|
||||
const int middle=panelDivider(width);
|
||||
auto place=[](HWND control, int x, int y, int width, int height)
|
||||
{
|
||||
if(control) SetWindowPos(control,nullptr,x,y,width,height,
|
||||
@@ -1089,6 +1137,8 @@ void layout(HWND window,bool activeOnly)
|
||||
ShowWindow(panels[i].heading,!terminalVisible && panels[i].wide?SW_SHOWNA:SW_HIDE);
|
||||
place(panels[i].list, x + 5, textHeight+10+headingHeight,listWidth,
|
||||
std::max(0, panelBottom-textHeight-10-headingHeight));
|
||||
place(panels[i].selectionSummary,x+8,panelBottom+4,std::max(0,end-x-16),summaryHeight);
|
||||
ShowWindow(panels[i].selectionSummary,summaryHeight?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
place(menuBar,0,0,width,textHeight+4);
|
||||
const int menuEdges[]{0,7,15,27,38,46};
|
||||
@@ -1097,7 +1147,7 @@ void layout(HWND window,bool activeOnly)
|
||||
}
|
||||
const int detailsLeft=active?middle+2:0;
|
||||
const int detailsRight=active?width:middle-2;
|
||||
place(status,detailsLeft+8,panelBottom+4,std::max(0,detailsRight-detailsLeft-16),textHeight);
|
||||
place(status,detailsLeft+8,panelBottom+4+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
|
||||
const auto ¤t=panels[active];
|
||||
const auto prompt=panelLocation(current)+L">";
|
||||
SetWindowTextW(terminalPrompt,prompt.c_str());
|
||||
@@ -1114,7 +1164,7 @@ void layout(HWND window,bool activeOnly)
|
||||
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),textHeight);
|
||||
if(activeOnly)
|
||||
{
|
||||
const RECT details{0,panelBottom+4,width,panelBottom+4+textHeight};
|
||||
const RECT details{0,panelBottom+4+summaryHeight,width,panelBottom+4+summaryHeight+textHeight};
|
||||
const RECT commandLine{0,inputTop,width,inputTop+textHeight};
|
||||
if(!terminalVisible) RedrawWindow(window,&details,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
RedrawWindow(window,&commandLine,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
@@ -1301,7 +1351,7 @@ std::optional<CompletionQuery> currentCompletionQuery()
|
||||
if(!first || first!=last) return {};
|
||||
std::wstring directory;
|
||||
if(!panels[active].peer && !panels[active].ftp)
|
||||
directory=terminal.alive() && !terminalDirectory.empty()?terminalDirectory:panels[active].directory.native();
|
||||
directory=panels[active].directory.native();
|
||||
return CompletionQuery{std::move(line),std::move(directory),first};
|
||||
}
|
||||
|
||||
@@ -1560,6 +1610,7 @@ void refreshPanel(Panel &panel)
|
||||
{
|
||||
cancelFolderSizes(panel);
|
||||
panel.folderSizes.clear();
|
||||
updateSelectionSummary(panel);
|
||||
open(panel,panel.directory,false);
|
||||
}
|
||||
|
||||
@@ -1628,14 +1679,19 @@ bool ensureTerminalView(HWND owner)
|
||||
else if(message.starts_with(L"directory:"))
|
||||
{
|
||||
const auto directory=message.substr(10);
|
||||
if(!terminalCommandPanels.empty())
|
||||
if(!terminalCommands.empty())
|
||||
{
|
||||
const int panel=terminalCommandPanels.front();
|
||||
terminalCommandPanels.pop_front();
|
||||
std::error_code error;
|
||||
if(panel>=0 && !panels[panel].peer && directory!=terminalDirectory &&
|
||||
!directory.empty() && fs::is_directory(directory,error))
|
||||
open(panels[panel],directory,false);
|
||||
const auto command=std::move(terminalCommands.front());
|
||||
terminalCommands.pop_front();
|
||||
if(command.panel>=0 && !directory.empty() && directory!=command.directory.native())
|
||||
{
|
||||
auto &panel=panels[command.panel];
|
||||
std::error_code error;
|
||||
if(!panel.peer && !panel.ftp && panel.directory==command.directory &&
|
||||
(!panel.scanRequest || panel.scanRequest->directory==command.directory) &&
|
||||
fs::is_directory(directory,error))
|
||||
open(panel,directory,false);
|
||||
}
|
||||
}
|
||||
terminalDirectory=directory;
|
||||
}
|
||||
@@ -1687,8 +1743,8 @@ bool startTerminal(HWND owner,const fs::path &directory)
|
||||
if(!ensureTerminalView(owner)) return false;
|
||||
if(terminal.start(directory.c_str(),terminalSize))
|
||||
{
|
||||
terminalCommandPanels={-1};
|
||||
terminalDirectory.clear();
|
||||
terminalCommands={{}};
|
||||
terminalDirectory=directory.native();
|
||||
return true;
|
||||
}
|
||||
setStatus(L"Could not start PowerShell.");
|
||||
@@ -1789,12 +1845,21 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
|
||||
return true;
|
||||
}
|
||||
if(!startTerminal(owner,panel.directory)) return false;
|
||||
if(!terminal.write(value+L"\r"))
|
||||
// Use the directory displayed by the panel at submission time. A queued
|
||||
// command may change location before PowerShell gets to this input.
|
||||
const bool hasCommand=value.find_first_not_of(L" \t\r\n")!=value.npos;
|
||||
std::wstring input;
|
||||
if(hasCommand && (terminalDirectory!=panel.directory.native() ||
|
||||
std::any_of(terminalCommands.begin(),terminalCommands.end(),
|
||||
[](const auto &command){ return command.panel>=0; })))
|
||||
input=L"try { Microsoft.PowerShell.Management\\Set-Location -LiteralPath "+
|
||||
powerShellPath(panel.directory)+L" -ErrorAction Stop } catch { Write-Error $_; return }; ";
|
||||
if(!terminal.write(input+value+L"\r"))
|
||||
{
|
||||
setStatus(L"Could not send PowerShell input.");
|
||||
return false;
|
||||
}
|
||||
terminalCommandPanels.push_back(static_cast<int>(&panel-panels));
|
||||
terminalCommands.push_back({hasCommand?static_cast<int>(&panel-panels):-1,panel.directory});
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1885,6 +1950,52 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
|
||||
return DefSubclassProc(input,message,wp,lp);
|
||||
}
|
||||
|
||||
void updateSelectionSummary(const Panel &panel)
|
||||
{
|
||||
const bool hadSummary=hasSelectionSummary();
|
||||
size_t marked=0,unmeasured=0;
|
||||
uint64_t total=0;
|
||||
bool partial=false;
|
||||
if(!ftpProfileList(panel))
|
||||
{
|
||||
for(size_t row=0;row<panel.marked.size();++row)
|
||||
{
|
||||
if(!panel.marked[row] || panel.sizes[row]==L"Up") continue;
|
||||
++marked;
|
||||
uint64_t bytes;
|
||||
if(panel.sizes[row]==L"Folder")
|
||||
{
|
||||
const auto measured=panel.folderSizes.find(panel.rows[row]);
|
||||
if(measured==panel.folderSizes.end())
|
||||
{
|
||||
++unmeasured;
|
||||
continue;
|
||||
}
|
||||
bytes=measured->second.bytes;
|
||||
partial|=measured->second.partial;
|
||||
}
|
||||
else bytes=std::stoull(panel.sizes[row]);
|
||||
if(bytes>UINT64_MAX-total)
|
||||
{
|
||||
total=UINT64_MAX;
|
||||
partial=true;
|
||||
}
|
||||
else total+=bytes;
|
||||
}
|
||||
}
|
||||
std::wstring summary;
|
||||
if(marked)
|
||||
{
|
||||
summary=L"Selected: ";
|
||||
if(partial || unmeasured) summary+=L"≥ ";
|
||||
summary+=formatSize(total)+L" · "+std::to_wstring(marked)+(marked==1?L" item":L" items");
|
||||
if(unmeasured) summary+=L" · "+std::to_wstring(unmeasured)+L" to measure";
|
||||
if(partial) summary+=L" · partial";
|
||||
}
|
||||
SetWindowTextW(panel.selectionSummary,summary.c_str());
|
||||
if(hadSummary!=hasSelectionSummary()) layout(GetParent(panel.list));
|
||||
}
|
||||
|
||||
void showFileDetails(const Panel &panel)
|
||||
{
|
||||
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
|
||||
@@ -2096,7 +2207,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
if(rememberElevationApproval || showFilesNotice(owner,question.c_str(),
|
||||
L"KSwitcher Files",{.confirm=true,.remember=&remember})==IDYES)
|
||||
{
|
||||
auto elevated=std::make_shared<ElevatedFolderListing>();
|
||||
auto elevated=std::make_shared<ElevatedHelper>();
|
||||
const auto result=launchElevatedFolder(owner,directory,*elevated);
|
||||
SetForegroundWindow(owner);
|
||||
SetFocus(panel.list);
|
||||
@@ -2214,6 +2325,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
}
|
||||
if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(panel.list,nullptr,FALSE);
|
||||
updateSelectionSummary(panel);
|
||||
if(partial && &panel==&panels[active])
|
||||
setStatus(L"Partial: "+std::to_wstring(folders.size()+files.size()));
|
||||
else if(!partial && error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND)
|
||||
@@ -2478,10 +2590,12 @@ void collectFolderSizes(Panel &panel)
|
||||
invalidateFolderSizeRow(panel,path);
|
||||
}
|
||||
if(finished) cancelFolderSizes(panel);
|
||||
if(!completed.empty()) updateSelectionSummary(panel);
|
||||
if((finished || !completed.empty()) && &panel==&panels[active]) showFileDetails(panel);
|
||||
}
|
||||
|
||||
void openSelectedText(const Panel &panel, bool edit, bool external);
|
||||
void compareSelectedFiles(HWND owner);
|
||||
INT_PTR confirmTextSave(HWND owner,bool draft);
|
||||
bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format);
|
||||
INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption);
|
||||
@@ -2615,6 +2729,7 @@ void selectDrive()
|
||||
else if(menuIndex==2 && row==3) showFolderShortcuts(panels[active],-1);
|
||||
else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true);
|
||||
else if(menuIndex==2 && (row==6 || row==7)) runActivePeerAction(owner,row==7);
|
||||
else if(menuIndex==2 && row==8) compareSelectedFiles(owner);
|
||||
else
|
||||
{
|
||||
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
|
||||
@@ -3330,6 +3445,7 @@ void prepareCopyDialog(HWND dialog)
|
||||
return TRUE;
|
||||
},0);
|
||||
const auto style=GetWindowLongPtrW(dialog,GWL_STYLE);
|
||||
if(style&WS_MAXIMIZEBOX) return;
|
||||
SetWindowLongPtrW(dialog,GWL_STYLE,style&~(WS_CAPTION|WS_SYSMENU|WS_THICKFRAME));
|
||||
const auto extended=GetWindowLongPtrW(dialog,GWL_EXSTYLE);
|
||||
SetWindowLongPtrW(dialog,GWL_EXSTYLE,extended&~WS_EX_DLGMODALFRAME);
|
||||
@@ -4755,7 +4871,9 @@ FileEntries childrenOf(FilesConnection &host,const fs::path &path)
|
||||
return children;
|
||||
}
|
||||
|
||||
#include "files_elevation.inl"
|
||||
#include "files_ftp_copy.inl"
|
||||
#include "files_compare.inl"
|
||||
|
||||
ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile)
|
||||
{
|
||||
@@ -4843,7 +4961,7 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path
|
||||
request["append"]=append;
|
||||
request["size"]=info.size;
|
||||
request["modified"]=info.modified;
|
||||
checkFileReply(hosts.source.files->call(request,update));
|
||||
checkFileReply(hosts.source.request(request,update));
|
||||
return;
|
||||
}
|
||||
ks::lan::streamFile(*hosts.source.files,*hosts.target.files,hosts.sourceId,from,to,
|
||||
@@ -4868,7 +4986,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
|
||||
auto request=fileRequest("move",from);
|
||||
request["target"]=ks::utf8(target.native());
|
||||
request["replace"]=replace;
|
||||
const auto reply=hosts.source.files->call(request);
|
||||
const auto reply=hosts.source.request(request);
|
||||
if(reply.at("error")==ERROR_NOT_SAME_DEVICE) return false;
|
||||
checkFileReply(reply);
|
||||
return true;
|
||||
@@ -4897,7 +5015,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
|
||||
{
|
||||
progress.localLockSource=hosts.sourceLocal?from:fs::path{};
|
||||
progress.localLockTarget.clear();
|
||||
checkFileReply(hosts.source.files->call(fileRequest("rmdir",from)));
|
||||
checkFileReply(hosts.source.request(fileRequest("rmdir",from)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -4916,7 +5034,7 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
|
||||
auto remove=fileRequest("remove",from);
|
||||
remove["size"]=incoming->size;
|
||||
remove["modified"]=incoming->modified;
|
||||
checkFileReply(hosts.source.files->call(remove));
|
||||
checkFileReply(hosts.source.request(remove));
|
||||
}
|
||||
}
|
||||
progress.bytes+=fileSize;
|
||||
@@ -5055,7 +5173,9 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
|
||||
try
|
||||
{
|
||||
progress.ui.run(progress.window,progress.canceled,[&] {
|
||||
CopyHost sourceHost(request.sourcePeer,sourceFtp);
|
||||
FileOperationElevation elevation(progress.window,progress.canceled,&progress.ui);
|
||||
auto *admin=!ftp && !request.sourcePeer && !targetPeer?&elevation:nullptr;
|
||||
CopyHost sourceHost(request.sourcePeer,sourceFtp,admin);
|
||||
if(ftpRename)
|
||||
{
|
||||
const auto &path=request.sources.front();
|
||||
@@ -5076,7 +5196,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
|
||||
return;
|
||||
}
|
||||
std::unique_ptr<CopyHost> otherHost;
|
||||
if(!sameHost) otherHost=std::make_unique<CopyHost>(targetPeer,destinationFtp);
|
||||
if(!sameHost) otherHost=std::make_unique<CopyHost>(targetPeer,destinationFtp,admin);
|
||||
const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost,
|
||||
request.sourcePeer?request.sourcePeer->id:"local",!request.sourcePeer && !sourceFtp,
|
||||
!targetPeer && !destinationFtp};
|
||||
@@ -5091,7 +5211,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
|
||||
{
|
||||
const auto canonical=[&](const fs::path &name)
|
||||
{
|
||||
const auto reply=sourceHost.files->call(fileRequest("canonical",name));
|
||||
const auto reply=sourceHost.request(fileRequest("canonical",name));
|
||||
checkFileReply(reply);
|
||||
return filePath(reply.at("path"));
|
||||
};
|
||||
@@ -5140,6 +5260,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
|
||||
progressDialog.close();
|
||||
activeCopy=nullptr;
|
||||
copyInProgress=false;
|
||||
updateSelectionSummary(source);
|
||||
for(auto &panel:panels) EnableWindow(panel.list,TRUE);
|
||||
for(const auto command:commands) EnableWindow(command,TRUE);
|
||||
if(progress.closeOwner)
|
||||
@@ -5404,7 +5525,8 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
|
||||
try
|
||||
{
|
||||
ui.run(window,canceled,[&] {
|
||||
CopyHost host(panel.peer?&*panel.peer:nullptr,ftp);
|
||||
FileOperationElevation elevation(window,canceled,&ui);
|
||||
CopyHost host(panel.peer?&*panel.peer:nullptr,ftp,&elevation);
|
||||
const auto collect=[&](auto &&self,const fs::path &path,std::vector<fs::path> &group)->void
|
||||
{
|
||||
for(const auto &[child,info]:host.children(path,canceled))
|
||||
@@ -5515,7 +5637,9 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
|
||||
{
|
||||
const auto error=probeDeleteAccess(current);
|
||||
if(isSharingError(error)) throw std::system_error(error,std::system_category());
|
||||
if(!ks::lan::recycleFile(window,current))
|
||||
if(error==ERROR_ACCESS_DENIED)
|
||||
checkFileReply(elevation.retry(fileRequest("recycle",current),{{"error",error}}));
|
||||
else if(!ks::lan::recycleFile(window,current))
|
||||
{
|
||||
// The Shell can hide the error from an individual item in a folder.
|
||||
lockPaths.insert(current);
|
||||
@@ -5527,6 +5651,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
|
||||
}
|
||||
catch(const std::system_error &e)
|
||||
{
|
||||
if(canceled && e.code().value()==ERROR_CANCELLED) break;
|
||||
recordFailure(e,current);
|
||||
if(e.code().value()>=10000) break;
|
||||
}
|
||||
@@ -5714,6 +5839,8 @@ INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
return TRUE;
|
||||
}
|
||||
fs::path current;
|
||||
std::atomic_bool canceled{};
|
||||
FileOperationElevation elevation(dialog,canceled);
|
||||
try
|
||||
{
|
||||
FilesConnection host(request->peer);
|
||||
@@ -5727,14 +5854,17 @@ INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
operation["target"]=ks::utf8(resolved.lexically_normal().native());
|
||||
operation["kind"]=kind==1?"junction":"symlink";
|
||||
}
|
||||
checkFileReply(host.call(operation));
|
||||
checkFileReply(request->peer?host.call(operation):elevation.call(host,operation));
|
||||
request->created=current;
|
||||
}
|
||||
}
|
||||
catch(const std::system_error &failure)
|
||||
{
|
||||
const auto details=current.filename().wstring()+L": "+fileError(failure);
|
||||
error(details.c_str(),input);
|
||||
if(!canceled)
|
||||
{
|
||||
const auto details=current.filename().wstring()+L": "+fileError(failure);
|
||||
error(details.c_str(),input);
|
||||
}
|
||||
if(!request->created.empty()) FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
@@ -6034,6 +6164,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
if(panel.sizes[i]!=L"Up") panel.marked[i]=mark;
|
||||
SendMessageW(window,LB_SETCURSEL,target,0);
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
updateSelectionSummary(panel);
|
||||
showFileDetails(panel);
|
||||
return 0;
|
||||
}
|
||||
@@ -6139,6 +6270,7 @@ bool loadFilesPreferences(HWND window)
|
||||
alignFolders=preference(L"AlignFolders",defaultAlignFolders)!=0;
|
||||
statusFields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
loadCommandHistoryKeys();
|
||||
loadComparisonShortcut();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -6169,17 +6301,13 @@ void openMenu(HWND window, int index)
|
||||
else if(index==2)
|
||||
{
|
||||
rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
|
||||
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4"};
|
||||
if(panels[active].peer)
|
||||
{
|
||||
rows.push_back(L"Hibernate remote PC");
|
||||
rows.push_back(L"Update remote KSwitcher");
|
||||
}
|
||||
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
|
||||
L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel()};
|
||||
}
|
||||
commandActions.clear();
|
||||
if(index==2)
|
||||
{
|
||||
commandActions={0,3,-1,1,2,4,5};
|
||||
commandActions={0,3,-1,1,2,4,5,8};
|
||||
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
|
||||
}
|
||||
else
|
||||
@@ -6222,7 +6350,10 @@ void openMenu(HWND window, int index)
|
||||
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&anchor),2);
|
||||
GetClientRect(window,&client);
|
||||
const int inset=dialogFrameMetrics(GetDpiForWindow(window)).content();
|
||||
const int width=std::max(1,std::min(static_cast<int>(client.right)-2*inset,26*cellWidth+16));
|
||||
int columns=26;
|
||||
for(const auto action:commandActions)
|
||||
if(action>=0) columns=std::max(columns,static_cast<int>(rows[action].size())+3);
|
||||
const int width=std::max(1,std::min(static_cast<int>(client.right)-2*inset,columns*cellWidth+16));
|
||||
const int x=std::clamp(static_cast<int>(anchor.left)+inset,inset,
|
||||
std::max(inset,static_cast<int>(client.right)-width-inset));
|
||||
const int y=anchor.bottom+5;
|
||||
@@ -6524,8 +6655,10 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
0, 0, 0, 0, window, reinterpret_cast<HMENU>(102 + static_cast<INT_PTR>(i)), instance, nullptr);
|
||||
panel.heading=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(140+static_cast<INT_PTR>(i)),instance,nullptr);
|
||||
if (!panel.path || !panel.list || !panel.heading) return -1;
|
||||
for (auto child : {panel.path, panel.list})
|
||||
panel.selectionSummary=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_ENDELLIPSIS,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(154+static_cast<INT_PTR>(i)),instance,nullptr);
|
||||
if (!panel.path || !panel.list || !panel.heading || !panel.selectionSummary) return -1;
|
||||
for (auto child : {panel.path, panel.list, panel.selectionSummary})
|
||||
SendMessageW(child, WM_SETFONT, reinterpret_cast<WPARAM>(mono), FALSE);
|
||||
SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight);
|
||||
wchar_t system[MAX_PATH]{};
|
||||
@@ -6569,7 +6702,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
RECT rect{};
|
||||
GetClientRect(window, &rect);
|
||||
const int width = rect.right;
|
||||
int middle = std::clamp(split ? split : width / 2, 120, std::max(120, width - 120));
|
||||
const int middle=panelDivider(width);
|
||||
if (point.y >= 0 && point.y < rect.bottom-2*textHeight-14 && abs(point.x - middle) <= 4)
|
||||
{
|
||||
SetCursor(LoadCursorW(nullptr, IDC_SIZEWE));
|
||||
@@ -6593,7 +6726,12 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
break;
|
||||
}
|
||||
case WM_MOUSEMOVE:
|
||||
if (dragging) { split = std::max(1, GET_X_LPARAM(lp)); layout(window); }
|
||||
if(dragging)
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(window,&client);
|
||||
setPanelDivider(window,client.right,GET_X_LPARAM(lp));
|
||||
}
|
||||
return 0;
|
||||
case WM_LBUTTONUP:
|
||||
if (dragging) ReleaseCapture();
|
||||
@@ -7087,16 +7225,6 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
{
|
||||
bool writeLog=ks::Settings{}.writeLog;
|
||||
try
|
||||
{
|
||||
const auto settings=ks::dataDirectory()/L"settings.json";
|
||||
if(std::filesystem::exists(settings))
|
||||
writeLog=Json::parse(ks::readFile(settings,1024*1024)).value("writeLog",writeLog);
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
ks::setLogFilename(L"kswitcher-files.log");
|
||||
ks::setLoggingEnabled(writeLog);
|
||||
int count{};
|
||||
if(auto args=CommandLineToArgvW(GetCommandLineW(),&count))
|
||||
{
|
||||
@@ -7106,6 +7234,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
LocalFree(args);
|
||||
return static_cast<int>(result);
|
||||
}
|
||||
if(count==4 && std::wstring_view(args[1])==L"--elevated-file-operation")
|
||||
{
|
||||
const auto result=serveElevatedFileOperations(args[2],args[3]);
|
||||
LocalFree(args);
|
||||
return static_cast<int>(result);
|
||||
}
|
||||
for(int i=1;i<count;++i)
|
||||
if(std::wstring_view(args[i])==L"--terminal-trace" ||
|
||||
std::wstring_view(args[i])==L"--terminal-output-trace")
|
||||
@@ -7120,7 +7254,18 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
LocalFree(args);
|
||||
}
|
||||
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS|ICC_TREEVIEW_CLASSES|ICC_HOTKEY_CLASS};
|
||||
bool writeLog=ks::Settings{}.writeLog;
|
||||
try
|
||||
{
|
||||
const auto settings=ks::dataDirectory()/L"settings.json";
|
||||
if(std::filesystem::exists(settings))
|
||||
writeLog=Json::parse(ks::readFile(settings,1024*1024)).value("writeLog",writeLog);
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
ks::setLogFilename(L"kswitcher-files.log");
|
||||
ks::setLoggingEnabled(writeLog);
|
||||
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS|ICC_TREEVIEW_CLASSES|
|
||||
ICC_HOTKEY_CLASS|ICC_BAR_CLASSES};
|
||||
InitCommonControlsEx(&controls);
|
||||
loadCommandHistory();
|
||||
WNDCLASSW type{};
|
||||
@@ -7142,6 +7287,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
{
|
||||
if(GetForegroundWindow()==window || IsChild(window,GetFocus())) restoreCommandFocus();
|
||||
if(GetMessageW(&message,nullptr,0,0)<=0) break;
|
||||
if(handleComparisonMessage(message)) continue;
|
||||
if(message.message==WM_KEYDOWN && message.wParam==VK_TAB &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
|
||||
ks::files::cycleTextWindows(GetAncestor(message.hwnd,GA_ROOT),(GetKeyState(VK_SHIFT)&0x8000)!=0))
|
||||
@@ -7225,6 +7371,18 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
const bool panelFocused=message.hwnd==panels[0].list || message.hwnd==panels[1].list;
|
||||
const bool mainInput=panelFocused || message.hwnd==terminalInput;
|
||||
if(mainInput && !terminalVisible && !copyInProgress && !commandHistoryWindow &&
|
||||
!FilesModalDialog::activeFor(window) && message.message==WM_KEYDOWN &&
|
||||
(message.wParam==VK_LEFT || message.wParam==VK_RIGHT) &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) &&
|
||||
!((GetKeyState(VK_SHIFT)|GetKeyState(VK_MENU)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(window,&client);
|
||||
const int direction=message.wParam==VK_LEFT?-1:1;
|
||||
setPanelDivider(window,client.right,panelDivider(client.right)+direction*cellWidth);
|
||||
continue;
|
||||
}
|
||||
if(message.message==WM_KEYDOWN && mainInput && !terminalVisible &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
|
||||
!(GetKeyState(VK_LWIN)&0x8000) && !(GetKeyState(VK_RWIN)&0x8000) &&
|
||||
@@ -7242,6 +7400,21 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
continue;
|
||||
}
|
||||
const bool filesMessage=message.hwnd==window || IsChild(window,message.hwnd);
|
||||
if(filesMessage && !terminalVisible && !copyInProgress && !commandHistoryWindow &&
|
||||
!FilesModalDialog::activeFor(window) && message.message==WM_KEYDOWN &&
|
||||
!(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
|
||||
!(GetKeyState(VK_RWIN)&0x8000) && (GetKeyState(VK_SHIFT)&0x8000) &&
|
||||
MAKEWORD(message.wParam,HOTKEYF_SHIFT|((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0))==
|
||||
comparisonShortcut)
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)))
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
compareSelectedFiles(window);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(mainInput && !terminalVisible && !copyInProgress &&
|
||||
message.message==WM_KEYDOWN && message.wParam>=VK_F1 && message.wParam<=VK_F12 &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
|
||||
|
||||
+97
-7
@@ -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());
|
||||
|
||||
@@ -42,6 +42,7 @@ public:
|
||||
bool save();
|
||||
bool saveNew(std::filesystem::path path, TextSaveFormat format);
|
||||
const wchar_t *encodingName() const;
|
||||
TextEncoding encoding() const { return encoding_; }
|
||||
|
||||
private:
|
||||
struct Change { uint64_t offset; size_t size; };
|
||||
|
||||
+169
-10
@@ -816,6 +816,16 @@ private:
|
||||
bool operator==(const FileStamp &) const = default;
|
||||
};
|
||||
std::optional<FileStamp> previewStamp;
|
||||
struct MarkdownTask
|
||||
{
|
||||
uint64_t revision;
|
||||
size_t line,column;
|
||||
bool checked;
|
||||
};
|
||||
std::string previewText;
|
||||
uint64_t previewRevision{};
|
||||
std::optional<MarkdownTask> pendingTask;
|
||||
std::optional<size_t> taskOffset;
|
||||
std::string previewFragment;
|
||||
struct PreviewLocation
|
||||
{
|
||||
@@ -858,6 +868,7 @@ private:
|
||||
static constexpr UINT openPreviewLink = WM_APP + 3;
|
||||
static constexpr UINT previewRendered = WM_APP + 4;
|
||||
static constexpr UINT cycleWindow = WM_APP + 5;
|
||||
static constexpr UINT savePreviewTask = WM_APP + 6;
|
||||
|
||||
LRESULT send(UINT message, WPARAM wparam = 0, LPARAM lparam = 0) const
|
||||
{
|
||||
@@ -912,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);
|
||||
@@ -1406,6 +1420,11 @@ void TextWindow::finishSave()
|
||||
{
|
||||
if (!busy() || saving.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready) return;
|
||||
KillTimer(window, saveTimer);
|
||||
if(taskOffset)
|
||||
{
|
||||
finishMarkdownTask();
|
||||
return;
|
||||
}
|
||||
send(SCI_SETREADONLY, !edit);
|
||||
const auto change = std::exchange(switchAfterSave, false);
|
||||
const auto reopened = saving.get();
|
||||
@@ -1537,25 +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;
|
||||
@@ -1609,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\"}");
|
||||
@@ -1661,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;
|
||||
@@ -1682,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;
|
||||
@@ -1706,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;
|
||||
@@ -1733,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")
|
||||
{
|
||||
@@ -1783,7 +1941,7 @@ void TextWindow::syncNavigation()
|
||||
|
||||
void TextWindow::navigatePreview(PreviewLink request)
|
||||
{
|
||||
if(edit || navigation.valid() || navigationHistory.empty()) return;
|
||||
if(edit || busy() || pendingTask || navigation.valid() || navigationHistory.empty()) return;
|
||||
if(request.newWindow)
|
||||
{
|
||||
if(remote)
|
||||
@@ -2321,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)
|
||||
{
|
||||
|
||||
@@ -23,6 +23,8 @@ struct TextWindowFont
|
||||
int tenthsOfPoint;
|
||||
};
|
||||
|
||||
void setFileWindowTaskbar(HWND window,int iconResource,const wchar_t *identity);
|
||||
|
||||
struct FarDropDownPalette
|
||||
{
|
||||
COLORREF surface, text, selection;
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.117";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.119";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
@@ -460,6 +460,34 @@ function startTerminalFixture() {
|
||||
([IO.File]::ReadAllLines($listing) -ccontains 'zzzz-dir-second')
|
||||
}
|
||||
Write-Output 'Verified repeated dir commands in the same terminal with file panes hidden and visible.'
|
||||
$rightChild = Join-Path $rightDir "Command's [folder]"
|
||||
[void][IO.Directory]::CreateDirectory($rightChild)
|
||||
$childRow = "[$([IO.Path]::GetFileName($rightChild))]"
|
||||
Wait-Until 'new folder in the right panel' { (Find-Row $right $childRow) -ge 0 }
|
||||
$keys.SendKeys('{TAB}')
|
||||
Send-InteractiveTerminal 'cmd /d /c "cd > panel-cwd.txt"'
|
||||
Wait-Until 'native command running in the newly active right panel' {
|
||||
(Test-Path -LiteralPath (Join-Path $rightDir 'panel-cwd.txt')) -and
|
||||
(Find-Row $right 'panel-cwd.txt') -ge 0
|
||||
}
|
||||
[void][FilesActivationUi]::Send($right, 0x186, [IntPtr](Find-Row $right $childRow), [IntPtr]::Zero)
|
||||
Press-Enter $inputBox
|
||||
$rightPath = [FilesActivationUi]::GetDlgItem($window, 143)
|
||||
Wait-Until 'navigation to the right panel subfolder' { (Read-Text $rightPath) -ceq $rightChild }
|
||||
Send-InteractiveTerminal 'cmd /d /c "cd > child-cwd.txt"'
|
||||
Wait-Until 'native command running in the navigated folder' {
|
||||
(Test-Path -LiteralPath (Join-Path $rightChild 'child-cwd.txt')) -and
|
||||
(Find-Row $right 'child-cwd.txt') -ge 0
|
||||
}
|
||||
Send-InteractiveTerminal 'cd ..'
|
||||
Wait-Until 'PowerShell cd navigating the right panel' { (Find-Row $right 'panel-cwd.txt') -ge 0 }
|
||||
$keys.SendKeys('{TAB}')
|
||||
Send-InteractiveTerminal 'cmd /d /c "cd > left-cwd.txt"'
|
||||
Wait-Until 'native command running back in the left panel' {
|
||||
(Test-Path -LiteralPath (Join-Path $leftDir 'left-cwd.txt')) -and
|
||||
(Find-Row $left 'left-cwd.txt') -ge 0
|
||||
}
|
||||
Write-Output 'Verified native commands follow panel switches and folder navigation in the same PowerShell session.'
|
||||
$marker=Join-Path $root 'webview-enter.txt'
|
||||
$command="[IO.File]::AppendAllText('$($marker.Replace("'","''"))','executed')"
|
||||
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$command)
|
||||
@@ -470,7 +498,10 @@ function startTerminalFixture() {
|
||||
!(Read-Text $inputBox)
|
||||
}
|
||||
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
|
||||
Select-Row $left '[Test folder]'
|
||||
# The left panel is already active after the working-directory check.
|
||||
$folderRow = Find-Row $left '[Test folder]'
|
||||
if ($folderRow -lt 0) { throw 'Missing folder for the terminal clipboard check.' }
|
||||
[void][FilesActivationUi]::Send($left, 0x186, [IntPtr]$folderRow, [IntPtr]::Zero)
|
||||
$outputSelection = 'terminal-output-copy-fixture'
|
||||
Send-InteractiveTerminal "Write-Output '$outputSelection'"
|
||||
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -117,6 +117,14 @@ try {
|
||||
'the relative image in HTML');
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').getBoundingClientRect().height > 0`), true);
|
||||
assert.equal(await evaluate(`document.querySelector('figure svg').textContent.includes('Render target')`), true);
|
||||
assert.equal(await evaluate(`(() => {
|
||||
const paths = document.querySelector('figure svg g.edgePaths');
|
||||
const labels = document.querySelector('figure svg g.edgeLabels');
|
||||
const background = labels?.querySelector('.edgeLabel rect');
|
||||
return !!(paths && labels && background && labels.textContent.includes('Transition') &&
|
||||
(paths.compareDocumentPosition(labels) & Node.DOCUMENT_POSITION_FOLLOWING) &&
|
||||
getComputedStyle(background).opacity === '1');
|
||||
})()`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
|
||||
document.querySelector('main').textContent.includes('Invalid Mermaid diagram')`), true);
|
||||
assert.equal(await evaluate(`!!document.querySelector('pre code.language-js') && !document.querySelector('iframe')`), true);
|
||||
@@ -125,14 +133,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';
|
||||
|
||||
Reference in new issue
Block a user