Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8c329c265 | ||
|
|
debd2b9cd9 | ||
|
|
90c93fba8c | ||
|
|
a09d5e72d1 | ||
|
|
c0bca1b4a2 | ||
|
|
d5ee6ee024 | ||
|
|
5cf0ff5140 |
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.120 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. Файл завантажується у тимчасову копію
|
||||
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
|
||||
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
|
||||
|
||||
@@ -1027,7 +1027,7 @@ History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc**
|
||||
|
||||
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels.
|
||||
History reuses separate helper processes for OCR and thumbnails so recognition can run alongside previews.
|
||||
Idle helpers exit after 30 seconds, and closing the history host stops its helpers. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
|
||||
Idle history helpers exit after 30 seconds, and closing the history host stops its helpers. During text conversion, a short-lived instance of **KSwitcher.Screenshot.exe** holds the image clipboard backup in memory and restores it only if the clipboard sequence still matches. Selection reads avoid loading image formats. Keep the executables from the same ZIP together. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
|
||||
|
||||
A live development-build test measured **4.37 MiB before history and 4.35 MiB after two open/Esc cycles**, compared with an earlier roughly 8–9 MiB plateau. A same-image clipboard-backup benchmark retained **12.78 MiB before versus 0.05 MiB after**. These measure private working set, not a guaranteed total footprint. Include all helpers when measuring active use: combined memory can be higher while history is open. No forced working-set trimming is used. Existing screenshots and shortcuts remain applicable. The v0.6.38 approach of retaining a hidden history window/RichEdit control is superseded by process termination.
|
||||
|
||||
|
||||
@@ -1,5 +1,35 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.6.120 — 2026-11-20
|
||||
|
||||
Layout conversion starts faster when the Windows clipboard contains an image. KSwitcher keeps the image and accompanying formats in memory for the duration of the operation. It restores them after conversion if the clipboard still belongs to the operation. A newer copy takes precedence.
|
||||
|
||||
**Українською.**
|
||||
|
||||
Перетворення розкладки починається швидше, коли в буфері обміну Windows є зображення. KSwitcher тримає зображення й супровідні формати в пам’яті до завершення операції. Копія відновлюється, якщо буфер усе ще належить операції. Новіше копіювання має пріоритет.
|
||||
|
||||
## 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
|
||||
53334ba83a44c69c3acd2aad297db177366fe553fae8813b88b81e0a215c860f KSwitcher-win-x64.zip
|
||||
+66
-66
@@ -1,166 +1,166 @@
|
||||
{
|
||||
"version": "0.6.117",
|
||||
"files": [
|
||||
{
|
||||
"size": 2479104,
|
||||
"path": "KSwitcher.exe",
|
||||
"sha256": "4ea5e71940d5cd1cbd062c6eead6a57d6c9a7b8a3884f2d8707267872643a55f"
|
||||
"sha256": "152b41278761439ce5ebe87bca3a4d8a96d89db82264ec0fbb2299e7c207dfb5",
|
||||
"size": 2372096
|
||||
},
|
||||
{
|
||||
"size": 2458112,
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"sha256": "3576d94c26dbed409dc12a13fb570d3dac5d35f8df1cf79761758a1e308e6b89"
|
||||
"sha256": "3d44721ba688a6916e393d2b9d9291e38ee063795b54cdae8e78cfd621835619",
|
||||
"size": 2369536
|
||||
},
|
||||
{
|
||||
"size": 3060224,
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"sha256": "738a6c42f56bd44d3cd871d53d51aa9580c3a20825c5407d2bb36ce512fe2103"
|
||||
"sha256": "81d9fbb770e876937310a0b483e11bd96cdb9e20b0f6baf0fa9927f24965aeeb",
|
||||
"size": 3348992
|
||||
},
|
||||
{
|
||||
"size": 4286976,
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"sha256": "f1231f85448b57771e6ce1f8e416282af8d9112f093bd05cb26881c79ccd5cc5"
|
||||
"sha256": "04c9af5324144a46a5f3cc0d8f2c6912745f8bbad7fbef0576bd52c88b5c5e03",
|
||||
"size": 4370944
|
||||
},
|
||||
{
|
||||
"size": 194912,
|
||||
"path": "WebView2Loader.dll",
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"size": 194912
|
||||
},
|
||||
{
|
||||
"size": 1103,
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"size": 1103
|
||||
},
|
||||
{
|
||||
"size": 1521,
|
||||
"path": "terminal/addon-fit.js",
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"size": 1521
|
||||
},
|
||||
{
|
||||
"size": 527,
|
||||
"path": "terminal/index.html",
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"size": 527
|
||||
},
|
||||
{
|
||||
"size": 1073,
|
||||
"path": "terminal/markdown-it-LICENSE.txt",
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
|
||||
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
|
||||
"size": 1073
|
||||
},
|
||||
{
|
||||
"size": 100786,
|
||||
"path": "terminal/markdown-it.js",
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
|
||||
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
|
||||
"size": 100786
|
||||
},
|
||||
{
|
||||
"size": 3530,
|
||||
"path": "terminal/markdown.html",
|
||||
"sha256": "e5381c35fb254b558c8b869746e2e575c8ed53600611ac90597ed2dd80fa321c"
|
||||
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79",
|
||||
"size": 3635
|
||||
},
|
||||
{
|
||||
"size": 15014,
|
||||
"path": "terminal/markdown.js",
|
||||
"sha256": "55c905afaf074e3253267a7c48a5ebca14edd7f15449fd85c0a884c34da22763"
|
||||
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8",
|
||||
"size": 16944
|
||||
},
|
||||
{
|
||||
"size": 1089,
|
||||
"path": "terminal/mermaid-LICENSE.txt",
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
|
||||
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
|
||||
"size": 1089
|
||||
},
|
||||
{
|
||||
"size": 5537838,
|
||||
"path": "terminal/mermaid.js",
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
|
||||
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
|
||||
"size": 5537838
|
||||
},
|
||||
{
|
||||
"size": 5065,
|
||||
"path": "terminal/terminal.js",
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b"
|
||||
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
|
||||
"size": 5065
|
||||
},
|
||||
{
|
||||
"size": 1261,
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"size": 1261
|
||||
},
|
||||
{
|
||||
"size": 7112,
|
||||
"path": "terminal/xterm.css",
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"size": 7112
|
||||
},
|
||||
{
|
||||
"size": 488663,
|
||||
"path": "terminal/xterm.js",
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"size": 488663
|
||||
},
|
||||
{
|
||||
"size": 4401,
|
||||
"path": "LICENSE",
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"size": 4401
|
||||
},
|
||||
{
|
||||
"size": 1096,
|
||||
"path": "json-LICENSE.txt",
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
|
||||
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
|
||||
"size": 1096
|
||||
},
|
||||
{
|
||||
"size": 883,
|
||||
"path": "files-text-license.txt",
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"size": 883
|
||||
},
|
||||
{
|
||||
"size": 95317,
|
||||
"path": "README.md",
|
||||
"sha256": "ea5016c6fa29a98bf9ebf103fcf27f1be091842ad3228b167d18b053fda767d8"
|
||||
"sha256": "afc7e78c4c3600888f642692423cd993b4aa431dfa54f752c7ac394de18186c6",
|
||||
"size": 95354
|
||||
},
|
||||
{
|
||||
"size": 11577,
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930"
|
||||
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
|
||||
"size": 11577
|
||||
},
|
||||
{
|
||||
"size": 732485,
|
||||
"path": "dictionaries/en.txt",
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
|
||||
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
|
||||
"size": 732485
|
||||
},
|
||||
{
|
||||
"size": 20566,
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
|
||||
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
|
||||
"size": 20566
|
||||
},
|
||||
{
|
||||
"size": 2265,
|
||||
"path": "dictionaries/README.md",
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"size": 2265
|
||||
},
|
||||
{
|
||||
"size": 1109134,
|
||||
"path": "dictionaries/ru.txt",
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
|
||||
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
|
||||
"size": 1109134
|
||||
},
|
||||
{
|
||||
"size": 1280,
|
||||
"path": "dictionaries/sources.json",
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"size": 1280
|
||||
},
|
||||
{
|
||||
"size": 940799,
|
||||
"path": "dictionaries/uk.txt",
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"size": 940799
|
||||
},
|
||||
{
|
||||
"size": 993,
|
||||
"path": "tools/README.txt",
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"size": 993
|
||||
},
|
||||
{
|
||||
"size": 133120,
|
||||
"path": "tools/StayHere.exe",
|
||||
"sha256": "ebe97d3b7f267632b90463358bcc2518cad12f43c1eb568d2749a08f88a4bd97"
|
||||
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
|
||||
"size": 134656
|
||||
},
|
||||
{
|
||||
"size": 2796,
|
||||
"path": "tools/StayHere-README.md",
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"size": 2796
|
||||
}
|
||||
],
|
||||
"schema": 1
|
||||
"schema": 1,
|
||||
"version": "0.6.120"
|
||||
}
|
||||
+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,120,0
|
||||
PRODUCTVERSION 0,6,120,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.120"
|
||||
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;
|
||||
|
||||
@@ -50,13 +50,12 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
||||
std::wstring token;
|
||||
bool autoOpenEditor=false, writeLog=false;
|
||||
int argc{}; auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
|
||||
if(argc==3 && std::wstring(argv[1])==L"--clipboard-snapshot") {
|
||||
std::filesystem::path request=argv[2]; LocalFree(argv);
|
||||
return ks::runClipboardSnapshot(request);
|
||||
}
|
||||
if(argc==5 && std::wstring_view(argv[1])==L"--history-image-worker") {
|
||||
HANDLE handles[3]{};
|
||||
for(int i=0;i<3;++i)
|
||||
const bool clipboardSnapshot = argc == 6 && std::wstring_view(argv[1]) == L"--clipboard-snapshot";
|
||||
const bool historyImageWorker = argc == 5 && std::wstring_view(argv[1]) == L"--history-image-worker";
|
||||
if (clipboardSnapshot || historyImageWorker)
|
||||
{
|
||||
HANDLE handles[4]{};
|
||||
for (int i = 0; i < argc - 2; ++i)
|
||||
{
|
||||
wchar_t *end{};
|
||||
const auto value=std::wcstoull(argv[i+2],&end,10);
|
||||
@@ -64,6 +63,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
|
||||
handles[i]=reinterpret_cast<HANDLE>(static_cast<uintptr_t>(value));
|
||||
}
|
||||
LocalFree(argv);
|
||||
if (clipboardSnapshot) return ks::runClipboardSnapshot(handles[0], handles[1], handles[2], handles[3]);
|
||||
const auto initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
if(FAILED(initialized)) return 1;
|
||||
const auto result=ks::runHistoryImageWorker(handles[0],handles[1],handles[2]);
|
||||
|
||||
+138
-134
@@ -703,26 +703,98 @@ struct ImageWorkerHandle
|
||||
if(value) CloseHandle(std::exchange(value,nullptr));
|
||||
}
|
||||
};
|
||||
template <typename Control>
|
||||
struct ImageWorkerView
|
||||
{
|
||||
ImageWorkerControl *control{};
|
||||
Control *control{};
|
||||
~ImageWorkerView() { reset(); }
|
||||
void reset()
|
||||
{
|
||||
if(control) UnmapViewOfFile(std::exchange(control,nullptr));
|
||||
}
|
||||
};
|
||||
template <typename Control>
|
||||
struct ImageWorkerChannel
|
||||
{
|
||||
ImageWorkerHandle mapping, requestReady, responseReady, process;
|
||||
ImageWorkerView<Control> view;
|
||||
|
||||
~ImageWorkerChannel() { stop(); }
|
||||
void stop() noexcept
|
||||
{
|
||||
if (process.value && WaitForSingleObject(process.value, 0) == WAIT_TIMEOUT)
|
||||
{
|
||||
TerminateProcess(process.value, ERROR_CANCELLED);
|
||||
WaitForSingleObject(process.value, INFINITE);
|
||||
}
|
||||
process.reset();
|
||||
view.reset();
|
||||
mapping.reset();
|
||||
requestReady.reset();
|
||||
responseReady.reset();
|
||||
}
|
||||
void open()
|
||||
{
|
||||
SECURITY_ATTRIBUTES security{sizeof(security), nullptr, TRUE};
|
||||
mapping.value = CreateFileMappingW(INVALID_HANDLE_VALUE, &security, PAGE_READWRITE, 0, sizeof(Control), nullptr);
|
||||
requestReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
|
||||
responseReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
|
||||
if (!mapping.value || !requestReady.value || !responseReady.value)
|
||||
throw std::runtime_error("Cannot create image helper channel");
|
||||
view.control = static_cast<Control *>(MapViewOfFile(mapping.value, FILE_MAP_WRITE, 0, 0, sizeof(Control)));
|
||||
if (!view.control) throw std::runtime_error("Cannot map image helper channel");
|
||||
}
|
||||
void start(std::wstring_view mode, HANDLE parent = nullptr)
|
||||
{
|
||||
std::vector<HANDLE> inherited{mapping.value, requestReady.value, responseReady.value};
|
||||
if (parent) inherited.push_back(parent);
|
||||
SIZE_T bytes{};
|
||||
InitializeProcThreadAttributeList(nullptr, 1, 0, &bytes);
|
||||
Bytes storage(bytes);
|
||||
auto attributes = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if (!InitializeProcThreadAttributeList(attributes, 1, 0, &bytes))
|
||||
throw std::runtime_error("Cannot initialize image helper startup");
|
||||
struct Attributes
|
||||
{
|
||||
LPPROC_THREAD_ATTRIBUTE_LIST value;
|
||||
~Attributes() { DeleteProcThreadAttributeList(value); }
|
||||
} cleanup{attributes};
|
||||
if (!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
inherited.data(), inherited.size() * sizeof(HANDLE), nullptr, nullptr))
|
||||
throw std::runtime_error("Cannot configure image helper startup");
|
||||
|
||||
const auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
|
||||
auto command = L"\"" + helper.wstring() + L"\" ";
|
||||
command += mode;
|
||||
for (auto handle : inherited) command += L" " + std::to_wstring(reinterpret_cast<uintptr_t>(handle));
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb = sizeof(startup);
|
||||
startup.lpAttributeList = attributes;
|
||||
PROCESS_INFORMATION child{};
|
||||
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, TRUE,
|
||||
CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, nullptr, helper.parent_path().c_str(),
|
||||
&startup.StartupInfo, &child))
|
||||
throw std::runtime_error(utf8(lastError(L"Cannot start image helper")));
|
||||
process.value = child.hProcess;
|
||||
CloseHandle(child.hThread);
|
||||
for (auto handle : inherited) SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
|
||||
}
|
||||
DWORD waitForResponse(DWORD timeout) const
|
||||
{
|
||||
HANDLE signals[]{responseReady.value, process.value};
|
||||
return WaitForMultipleObjects(2, signals, FALSE, timeout);
|
||||
}
|
||||
};
|
||||
struct HistoryImageWorker
|
||||
{
|
||||
std::timed_mutex mutex;
|
||||
ImageWorkerHandle mapping, requestReady, responseReady, process;
|
||||
ImageWorkerView view;
|
||||
|
||||
~HistoryImageWorker() { stop(); }
|
||||
void stop();
|
||||
void start();
|
||||
ImageWorkerChannel<ImageWorkerControl> channel;
|
||||
int perform(const std::filesystem::path &, const std::function<bool()> &);
|
||||
};
|
||||
struct ClipboardSnapshotControl
|
||||
{
|
||||
DWORD sequence;
|
||||
};
|
||||
}
|
||||
|
||||
struct HistoryImageWorkers
|
||||
@@ -778,42 +850,15 @@ void History::reload()
|
||||
std::lock_guard lock(mutex_);
|
||||
loadIndex();
|
||||
}
|
||||
void ClipboardSnapshot::cleanup() noexcept
|
||||
struct ClipboardSnapshot::Helper
|
||||
{
|
||||
if (request_.empty()) return;
|
||||
std::error_code ignored;
|
||||
for (const auto *suffix : {L"", L".snapshot", L".result"})
|
||||
std::filesystem::remove(std::filesystem::path(request_.wstring() + suffix), ignored);
|
||||
request_.clear();
|
||||
}
|
||||
ClipboardSnapshot::~ClipboardSnapshot() { cleanup(); }
|
||||
DWORD ClipboardSnapshot::run(bool restore, DWORD sequence)
|
||||
{
|
||||
atomicWrite(request_, protect(jsonBytes(Json{{"schema", 1}, {"restore", restore}, {"sequence", sequence}})));
|
||||
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
|
||||
auto command = L"\"" + helper.wstring() + L"\" --clipboard-snapshot \"" + request_.wstring() + L"\"";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
|
||||
PROCESS_INFORMATION process{};
|
||||
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
|
||||
nullptr, helper.parent_path().c_str(), &startup, &process))
|
||||
throw std::runtime_error("Cannot start clipboard snapshot helper");
|
||||
CloseHandle(process.hThread);
|
||||
auto wait = WaitForSingleObject(process.hProcess, 10000);
|
||||
DWORD result = ERROR_GEN_FAILURE;
|
||||
if (wait != WAIT_OBJECT_0)
|
||||
{
|
||||
TerminateProcess(process.hProcess, ERROR_TIMEOUT);
|
||||
WaitForSingleObject(process.hProcess, INFINITE);
|
||||
}
|
||||
GetExitCodeProcess(process.hProcess, &result);
|
||||
CloseHandle(process.hProcess);
|
||||
if (wait != WAIT_OBJECT_0 || result) throw std::runtime_error("Clipboard snapshot helper failed");
|
||||
return parse(unprotect(readFile(request_.wstring() + L".result", 4096))).at("sequence").get<DWORD>();
|
||||
}
|
||||
ImageWorkerChannel<ClipboardSnapshotControl> channel;
|
||||
};
|
||||
ClipboardSnapshot::ClipboardSnapshot() = default;
|
||||
ClipboardSnapshot::~ClipboardSnapshot() = default;
|
||||
void ClipboardSnapshot::capture(HWND window, DWORD sequence)
|
||||
{
|
||||
cleanup();
|
||||
helper_.reset();
|
||||
clip_ = {};
|
||||
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
|
||||
!IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")))
|
||||
@@ -821,39 +866,53 @@ void ClipboardSnapshot::capture(HWND window, DWORD sequence)
|
||||
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence);
|
||||
return;
|
||||
}
|
||||
request_ = std::filesystem::temp_directory_path() / (L"ks-clipboard-" + newSnippetId() + L".request");
|
||||
try { run(false, sequence); }
|
||||
catch (...) { cleanup(); throw; }
|
||||
auto helper = std::make_unique<Helper>();
|
||||
auto &channel = helper->channel;
|
||||
channel.open();
|
||||
channel.view.control->sequence = sequence;
|
||||
// Let the helper discard its private copy if the resident exits unexpectedly.
|
||||
ImageWorkerHandle parent;
|
||||
const auto self = GetCurrentProcess();
|
||||
if (!DuplicateHandle(self, self, self, &parent.value, SYNCHRONIZE, TRUE, 0))
|
||||
throw std::runtime_error("Cannot pass resident lifetime to clipboard helper");
|
||||
channel.start(L"--clipboard-snapshot", parent.value);
|
||||
if (channel.waitForResponse(10000) != WAIT_OBJECT_0)
|
||||
throw std::runtime_error("Clipboard snapshot helper failed to capture");
|
||||
helper_ = std::move(helper);
|
||||
}
|
||||
DWORD ClipboardSnapshot::restore(HWND window, DWORD sequence)
|
||||
{
|
||||
return request_.empty() ? writeClipboardGuarded(window, clip_, sequence) : run(true, sequence);
|
||||
if (!helper_) return writeClipboardGuarded(window, clip_, sequence);
|
||||
auto &channel = helper_->channel;
|
||||
if (!channel.process.value)
|
||||
throw std::runtime_error("Clipboard snapshot helper is unavailable");
|
||||
channel.view.control->sequence = sequence;
|
||||
DWORD result{};
|
||||
if (!SetEvent(channel.requestReady.value) || WaitForSingleObject(channel.process.value, 10000) != WAIT_OBJECT_0 ||
|
||||
!GetExitCodeProcess(channel.process.value, &result) || result != 0)
|
||||
{
|
||||
channel.stop();
|
||||
throw std::runtime_error("Clipboard snapshot helper failed to restore");
|
||||
}
|
||||
return channel.view.control->sequence;
|
||||
}
|
||||
int runClipboardSnapshot(const std::filesystem::path &request)
|
||||
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!request.is_absolute() || !request.filename().wstring().starts_with(L"ks-clipboard-") ||
|
||||
request.extension() != L".request") return 1;
|
||||
auto job = parse(unprotect(readFile(request, 4096)));
|
||||
if (job.at("schema") != 1) return 1;
|
||||
auto sequence = job.at("sequence").get<DWORD>();
|
||||
const auto snapshot = request.wstring() + L".snapshot";
|
||||
if (job.at("restore").get<bool>())
|
||||
{
|
||||
auto clip = decodeClip(unprotect(readFile(snapshot, 70 * 1024 * 1024)));
|
||||
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
|
||||
if (!window) return 1;
|
||||
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
|
||||
sequence = writeClipboardGuarded(window, clip, sequence);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
|
||||
if (sequence != GetClipboardSequenceNumber()) return 2;
|
||||
atomicWrite(snapshot, protect(encodeClip(clip)));
|
||||
}
|
||||
atomicWrite(request.wstring() + L".result", protect(jsonBytes(Json{{"sequence", sequence}})));
|
||||
ImageWorkerView<ClipboardSnapshotControl> view{static_cast<ClipboardSnapshotControl *>(
|
||||
MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(ClipboardSnapshotControl)))};
|
||||
if (!view.control) return 1;
|
||||
const auto sequence = view.control->sequence;
|
||||
const auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
|
||||
if (sequence != GetClipboardSequenceNumber() || !SetEvent(responseReady)) return 1;
|
||||
// Only the clipboard sequence crosses the channel. The captured formats stay in this process.
|
||||
HANDLE signals[]{parent, requestReady};
|
||||
if (WaitForMultipleObjects(2, signals, FALSE, INFINITE) != WAIT_OBJECT_0 + 1) return 1;
|
||||
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
|
||||
if (!window) return 1;
|
||||
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
|
||||
view.control->sequence = writeClipboardGuarded(window, clip, view.control->sequence);
|
||||
return 0;
|
||||
}
|
||||
catch (...) { return 1; }
|
||||
@@ -1163,61 +1222,6 @@ void History::clear()
|
||||
}
|
||||
namespace
|
||||
{
|
||||
void HistoryImageWorker::stop()
|
||||
{
|
||||
if(process.value && WaitForSingleObject(process.value,0)==WAIT_TIMEOUT)
|
||||
{
|
||||
TerminateProcess(process.value,ERROR_CANCELLED);
|
||||
WaitForSingleObject(process.value,INFINITE);
|
||||
}
|
||||
process.reset();
|
||||
view.reset();
|
||||
mapping.reset();
|
||||
requestReady.reset();
|
||||
responseReady.reset();
|
||||
}
|
||||
|
||||
void HistoryImageWorker::start()
|
||||
{
|
||||
SECURITY_ATTRIBUTES security{sizeof(security),nullptr,TRUE};
|
||||
mapping.value=CreateFileMappingW(INVALID_HANDLE_VALUE,&security,PAGE_READWRITE,0,sizeof(ImageWorkerControl),nullptr);
|
||||
requestReady.value=CreateEventW(&security,FALSE,FALSE,nullptr);
|
||||
responseReady.value=CreateEventW(&security,FALSE,FALSE,nullptr);
|
||||
if(!mapping.value || !requestReady.value || !responseReady.value)
|
||||
throw std::runtime_error("Cannot create history OCR worker channel");
|
||||
view.control=static_cast<ImageWorkerControl *>(MapViewOfFile(mapping.value,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)));
|
||||
if(!view.control) throw std::runtime_error("Cannot map history OCR worker channel");
|
||||
|
||||
SIZE_T bytes{};
|
||||
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
|
||||
Bytes storage(bytes);
|
||||
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes))
|
||||
throw std::runtime_error("Cannot initialize history OCR worker startup");
|
||||
struct Attributes
|
||||
{
|
||||
LPPROC_THREAD_ATTRIBUTE_LIST value;
|
||||
~Attributes() { DeleteProcThreadAttributeList(value); }
|
||||
} cleanup{attributes};
|
||||
HANDLE inherited[]{mapping.value,requestReady.value,responseReady.value};
|
||||
if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr))
|
||||
throw std::runtime_error("Cannot configure history OCR worker startup");
|
||||
|
||||
const auto helper=std::filesystem::path(executable()).parent_path()/L"KSwitcher.Screenshot.exe";
|
||||
auto command=L"\""+helper.wstring()+L"\" --history-image-worker";
|
||||
for(auto handle:inherited) command+=L" "+std::to_wstring(reinterpret_cast<uintptr_t>(handle));
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb=sizeof(startup);
|
||||
startup.lpAttributeList=attributes;
|
||||
PROCESS_INFORMATION child{};
|
||||
if(!CreateProcessW(helper.c_str(),command.data(),nullptr,nullptr,TRUE,
|
||||
CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,nullptr,helper.parent_path().c_str(),&startup.StartupInfo,&child))
|
||||
throw std::runtime_error(utf8(lastError(L"Cannot start history OCR helper")));
|
||||
process.value=child.hProcess;
|
||||
CloseHandle(child.hThread);
|
||||
for(const auto handle:inherited) SetHandleInformation(handle,HANDLE_FLAG_INHERIT,0);
|
||||
}
|
||||
|
||||
int HistoryImageWorker::perform(const std::filesystem::path &request,const std::function<bool()> &cancelled)
|
||||
{
|
||||
std::unique_lock lock(mutex,std::defer_lock);
|
||||
@@ -1234,42 +1238,42 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
|
||||
{
|
||||
for(int attempt=0;attempt<2;++attempt)
|
||||
{
|
||||
if(!process.value || WaitForSingleObject(process.value,0)!=WAIT_TIMEOUT)
|
||||
if(!channel.process.value || WaitForSingleObject(channel.process.value,0)!=WAIT_TIMEOUT)
|
||||
{
|
||||
stop();
|
||||
start();
|
||||
channel.stop();
|
||||
channel.open();
|
||||
channel.start(L"--history-image-worker");
|
||||
}
|
||||
checkCancelled();
|
||||
std::copy(path.begin(),path.end(),view.control->request);
|
||||
view.control->request[path.size()]=L'\0';
|
||||
if(!SetEvent(requestReady.value)) throw std::runtime_error("Cannot request history OCR");
|
||||
HANDLE signals[]{responseReady.value,process.value};
|
||||
std::copy(path.begin(),path.end(),channel.view.control->request);
|
||||
channel.view.control->request[path.size()]=L'\0';
|
||||
if(!SetEvent(channel.requestReady.value)) throw std::runtime_error("Cannot request history OCR");
|
||||
const auto deadline=GetTickCount64()+60000;
|
||||
for(;;)
|
||||
{
|
||||
const auto wait=WaitForMultipleObjects(2,signals,FALSE,100);
|
||||
const auto wait=channel.waitForResponse(100);
|
||||
if(wait==WAIT_OBJECT_0)
|
||||
{
|
||||
checkCancelled();
|
||||
return view.control->result;
|
||||
return channel.view.control->result;
|
||||
}
|
||||
if(wait==WAIT_OBJECT_0+1)
|
||||
{
|
||||
DWORD code{};
|
||||
if(GetExitCodeProcess(process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
|
||||
if(GetExitCodeProcess(channel.process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
|
||||
throw std::runtime_error("History OCR helper exited before responding");
|
||||
}
|
||||
if(wait!=WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper");
|
||||
checkCancelled();
|
||||
if(GetTickCount64()>=deadline) throw std::runtime_error("History OCR helper timed out");
|
||||
}
|
||||
stop();
|
||||
channel.stop();
|
||||
}
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
// The child must stop writing before the request and response files are cleaned up.
|
||||
stop();
|
||||
channel.stop();
|
||||
throw;
|
||||
}
|
||||
throw std::runtime_error("History OCR helper did not accept the request");
|
||||
@@ -1278,7 +1282,7 @@ int HistoryImageWorker::perform(const std::filesystem::path &request,const std::
|
||||
|
||||
int runHistoryImageWorker(HANDLE mapping,HANDLE requestReady,HANDLE responseReady)
|
||||
{
|
||||
ImageWorkerView view{static_cast<ImageWorkerControl *>(
|
||||
ImageWorkerView<ImageWorkerControl> view{static_cast<ImageWorkerControl *>(
|
||||
MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)))};
|
||||
if(!view.control) return 1;
|
||||
for(;;)
|
||||
|
||||
+5
-6
@@ -58,20 +58,19 @@ bool sameClipboardImage(const Clip &, const Clip &);
|
||||
int runImageHistoryCapture(const std::filesystem::path &request);
|
||||
int runHistoryOcr(const std::filesystem::path &request);
|
||||
int runHistoryImageWorker(HANDLE mapping, HANDLE requestReady, HANDLE responseReady);
|
||||
// Image backups stay encrypted on disk and are read/written only by a short-lived helper.
|
||||
// Image backups are held in memory by a helper for the lifetime of the transaction.
|
||||
class ClipboardSnapshot
|
||||
{
|
||||
struct Helper;
|
||||
Clip clip_;
|
||||
std::filesystem::path request_;
|
||||
void cleanup() noexcept;
|
||||
DWORD run(bool restore, DWORD sequence);
|
||||
std::unique_ptr<Helper> helper_;
|
||||
public:
|
||||
ClipboardSnapshot() = default;
|
||||
ClipboardSnapshot();
|
||||
ClipboardSnapshot(const ClipboardSnapshot &) = delete;
|
||||
ClipboardSnapshot &operator=(const ClipboardSnapshot &) = delete;
|
||||
~ClipboardSnapshot();
|
||||
void capture(HWND, DWORD sequence);
|
||||
DWORD restore(HWND, DWORD sequence);
|
||||
};
|
||||
int runClipboardSnapshot(const std::filesystem::path &request);
|
||||
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent);
|
||||
} // namespace ks
|
||||
+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.120";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
@@ -44,7 +44,9 @@ int main(int argc,char**argv) {
|
||||
HWND w=owner(); int result=0; ks::Clip original; bool saved=false;
|
||||
try {
|
||||
std::string mode=argc>1?argv[1]:"suite";
|
||||
if(mode=="publish") {
|
||||
if(mode=="temporary") {
|
||||
ks::writeClipboard(w,ks::textClip(L"temporary"));
|
||||
} else if(mode=="publish") {
|
||||
ks::Pixels p{1566,1068,ks::Bytes(1566*1068*4,255)}; p.bgra[0]=77;
|
||||
auto dib=ks::imageDib(p); auto v5=dib;
|
||||
BITMAPV5HEADER h{}; h.bV5Size=sizeof(h); h.bV5Width=p.width; h.bV5Height=-p.height;
|
||||
@@ -60,9 +62,17 @@ int main(int argc,char**argv) {
|
||||
auto clip=ks::readClipboard(w,64*1024*1024);
|
||||
ks::writeClipboard(w,ks::textClip(L"temporary")); ks::writeClipboard(w,clip);
|
||||
} else {
|
||||
ks::ClipboardSnapshot snapshot; snapshot.capture(w,GetClipboardSequenceNumber());
|
||||
auto seq=ks::writeClipboard(w,ks::textClip(L"temporary"));
|
||||
require(snapshot.restore(w,seq)==GetClipboardSequenceNumber(),"helper returns current sequence");
|
||||
ks::ClipboardSnapshot snapshot;
|
||||
auto started=GetTickCount64();
|
||||
snapshot.capture(w,GetClipboardSequenceNumber());
|
||||
std::cout<<"Image snapshot capture: "<<GetTickCount64()-started<<" ms\n";
|
||||
// A separate publisher avoids blocking clipboard notifications on this waiting test thread.
|
||||
child(L"temporary");
|
||||
const auto seq=GetClipboardSequenceNumber();
|
||||
started=GetTickCount64();
|
||||
const auto restored=snapshot.restore(w,seq);
|
||||
std::cout<<"Image snapshot restore: "<<GetTickCount64()-started<<" ms\n";
|
||||
require(restored==GetClipboardSequenceNumber(),"helper returns current sequence");
|
||||
}
|
||||
auto after=resident();
|
||||
auto report="baseline="+std::to_string(baseline)+" after="+std::to_string(after)+" delta="+std::to_string(int64_t(after)-int64_t(baseline))+"\n";
|
||||
@@ -78,6 +88,13 @@ int main(int argc,char**argv) {
|
||||
bool rejected=false;
|
||||
try {ks::readClipboard(w,32*1024*1024,ks::ClipboardRead::WithoutImages,seq);} catch(...) {rejected=true;}
|
||||
require(rejected,"resident rejects images before reading their data");
|
||||
{
|
||||
ks::ClipboardSnapshot snapshot;
|
||||
try {snapshot.capture(w,seq-1); rejected=false;} catch(...) {rejected=true;}
|
||||
require(rejected,"stale image snapshot is rejected");
|
||||
snapshot.capture(w,seq);
|
||||
}
|
||||
require(GetClipboardSequenceNumber()==seq,"discarding an image snapshot leaves the clipboard untouched");
|
||||
{
|
||||
ks::ClipboardSnapshot snapshot; snapshot.capture(w,seq);
|
||||
auto stale=ks::writeClipboard(w,ks::textClip(L"temporary"));
|
||||
|
||||
@@ -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