Compare commits

...
Author SHA1 Message Date
agrynco e852fde4f4 Open recent Files diagnostics in a safe native viewer
Refs #132
2026-11-25 23:35:15 +02:00
agrynco e421c17f2a Merge pull request 'KSwitcher.Files: Add contextual offline help' (#189) from codex/issue-131-context-help into prerelease
Refs #131
2026-11-25 23:29:45 +02:00
agrynco f4dcd0efd9 Add contextual offline help to Files
Refs #131
2026-11-25 23:29:30 +02:00
agrynco a5a5724513 Merge pull request 'KSwitcher.Files: Add independent area scales and system themes' (#188) from codex/issue-130-themes-scale into prerelease
Refs #130
2026-11-25 23:21:17 +02:00
agrynco 040658f350 Add independent Files scales and Windows theme palettes
Refs #130
2026-11-25 23:21:06 +02:00
agrynco 0ac6501b21 Merge pull request 'KSwitcher.Files: Add selective settings import and export' (#187) from codex/issue-129-settings-portability into prerelease
Refs #129
2026-11-25 23:06:54 +02:00
agrynco b6b7164742 Add selective Files settings JSON import and export
Refs #129
2026-11-25 23:06:45 +02:00
agrynco 8870d8c3d9 Merge pull request 'KSwitcher.Files: Add named keyboard schemes' (#185) from codex/issue-128-key-schemes into prerelease
Refs #128
2026-11-25 22:54:36 +02:00
agrynco eb0f6ead72 Add named keyboard schemes for Files commands
Refs #128
2026-11-25 22:54:25 +02:00
agrynco d26eec3c98 Merge pull request 'KSwitcher.Files: Restore local documents and guard external edits' (#183) from codex/issue-127-document-session into prerelease
Refs #127
2026-11-25 22:42:00 +02:00
agrynco 1757450833 Restore local Files documents and guard external edits
Refs #127
2026-11-25 22:41:48 +02:00
agrynco 1066fbeab8 Merge pull request 'KSwitcher.Files: local PNG and JPEG editor' (#182) from codex/issue-126-image-editor into prerelease
Refs #126
2026-11-25 22:25:56 +02:00
agrynco f2dc1f0c78 Add image rotation crop and undo to Files
Refs #126
2026-11-25 22:25:47 +02:00
agrynco 64e741f778 Merge pull request 'KSwitcher.Files: offline HTML and binary Quick View' (#180) from codex/issue-125-quick-preview into prerelease
Refs #125
2026-11-25 22:10:59 +02:00
agrynco 1edd0343ef Add offline HTML and binary Quick View
Refs #125
2026-11-25 22:10:49 +02:00
agrynco 6c0e8f0736 Merge pull request 'KSwitcher.Files: panel swap, marks and layout options' (#179) from codex/issue-124-panel-layout into prerelease
Refs #124
2026-11-25 21:51:08 +02:00
agrynco 934521f404 Add Files panel layout and mouse options
Refs #124
2026-11-25 21:51:02 +02:00
agrynco 2db50fcd0e Merge pull request 'KSwitcher.Files: Copy/Move options and time estimate' (#178) from codex/issue-123-copy-options into prerelease
Refs #123
2026-11-25 21:43:00 +02:00
agrynco dbbc5c138e Add advanced Files copy and move options
Refs #123
2026-11-25 21:42:50 +02:00
agrynco 84385a1eca Merge pull request 'KSwitcher.Files: file operations for trusted LAN clients' (#177) from codex/issue-122-lan-capabilities into prerelease
Refs #122
2026-11-25 21:27:08 +02:00
agrynco f5b7ddfb53 Expose file operations to trusted LAN clients
Refs #122
2026-11-25 21:26:55 +02:00
agrynco 93e672c71d Merge pull request 'KSwitcher.Files: Windows environment variables' (#176) from codex/issue-121-environment-panel into prerelease
Refs #121
2026-11-25 21:08:57 +02:00
agrynco cc6199e9be Inspect and edit Windows environment definitions
Refs #121
2026-11-25 21:08:51 +02:00
agrynco a27ae96842 Merge pull request 'KSwitcher.Files: Stage, Unstage and reviewed local commits' (#175) from codex/issue-120-git-mutations into prerelease
Refs #120
2026-11-25 20:59:44 +02:00
agrynco 9158bf95a6 Stage and commit a reviewed Git index snapshot
Refs #120
2026-11-25 20:59:30 +02:00
agrynco 159b776199 Merge pull request 'KSwitcher.Files: Git branches and commit history' (#174) from codex/issue-119-git-history into prerelease
Refs #119
2026-11-25 20:37:56 +02:00
agrynco ada198db24 Browse Git branches and paged commit history
Refs #119
2026-11-25 20:37:46 +02:00
agrynco fe1f818582 Merge pull request 'KSwitcher.Files: Git Changes and side-by-side diff' (#173) from codex/issue-118-git-changes into prerelease
Refs #118
2026-11-25 20:27:30 +02:00
57 changed files with 6564 additions and 893 deletions

No files matched your search

+2 -2
View File
@@ -35,7 +35,7 @@ add_custom_target(check-files-quick-view
DEPENDS KSwitcherFiles
VERBATIM)
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr KSwitcherFilesImage libssh2::libssh2)
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr userenv KSwitcherFilesImage libssh2::libssh2)
if(MSVC)
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
else()
@@ -55,7 +55,7 @@ foreach(utilityTarget StayHere StayHereTest)
target_link_options(${utilityTarget} PRIVATE -municode -static -static-libgcc -static-libstdc++)
endif()
endforeach()
add_library(kscore src/lan_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp)
add_library(kscore src/lan_files.cpp src/lan_client_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp)
target_sources(kscore PRIVATE src/drive_snapshot.cpp src/google_drive.cpp)
foreach(field IN ITEMS ID SECRET)
set(KS_GOOGLE_CLIENT_${field} "$ENV{KSWITCHER_GOOGLE_CLIENT_${field}}")
+55 -2
View File
@@ -635,7 +635,7 @@ Warning і початковий фокус на No.
розміру, а список має однаковий внутрішній відступ зліва і справа.
- Тайм-аут запиту дисків відображається як Connection timed out. Якщо
ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows.
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. Commands → Files log відкриває до 200 останніх записів поточного або попереднього журналу. Refresh оновлює список. Copy selected або Ctrl+C копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано.
- Застосовані налаштування Files одразу підхоплюють інші відкриті вікна.
Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
@@ -686,13 +686,19 @@ Warning і початковий фокус на No.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
тексту, Markdown і зображень у сусідній панелі. Перегляд слідує за курсором активної
тексту, Markdown, HTML, зображень і двійкових файлів у сусідній панелі. Перегляд слідує за курсором активної
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
Під час перегляду файлові операції з призначенням у сусідній панелі
пропонують спершу закрити Quick View.
- Для локальних HTML-файлів до 8 МіБ Quick View відкриває **Rendered**. **Show Source** показує початковий текст, **Show Rendered** повертає форматований вигляд. F6 перемикає режими, коли фокус у самому перегляді. Quick View відображає статичне форматування й текст локально. Виконання скриптів, перехід за посиланнями і завантаження ресурсів заблоковані. Для зображень HTML показує їхній альтернативний текст. Більші HTML-файли починаються з першої сторінки вихідного тексту.
- Двійковий режим показує до 4096 початкових байтів, зі звичайними символами для друкованих байтів та позначенням `\xNN` для контрольних кодів. Рядки переносяться за шириною панелі. Shift+F3 відкриває повний Hex Viewer.
- **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й
вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі
зображення в порядку вихідної панелі на момент відкриття Viewer.
- **Options → Viewer → Restore local Viewer and Editor windows after restart** зберігає відкриті локальні вікна під час закриття Files. Під час наступного запуску наявні документи відкриваються в попередньому режимі й положенні. Текст відновлює сторінку, курсор і прокручування, а зображення — масштаб. Відновлення читає збережені файли з диска.
- Локальний Viewer оновлює вміст після зміни файла. Активний Editor пропонує **Reload** або **Keep buffer**. Reload відкриває актуальну версію з диска, Keep buffer залишає відкриті редагування. Збереження після Keep buffer перевіряє початкову версію й зберігає чернетку, якщо файл уже змінився.
- **F4** на локальному PNG або JPEG відкриває редактор зображень. Rotate left і Rotate right повертають зображення на 90°. Crop приймає цілі координати X і Y від нуля, ширину й висоту в пікселях поточного зображення. Undo або Ctrl+Z послідовно скасовує зміни.
- **Save copy** або Ctrl+Shift+S створює окремий PNG чи JPEG. PNG зберігає прозорість, а JPEG використовує біле тло. **Replace** або Ctrl+S просить підтвердження й звіряє версію оригіналу. Якщо зовнішня зміна або помилка заважає запису, редактор зберігає чернетку. Закриття незбереженої чернетки просить підтвердження.
- У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб,
перетягування мишею панорамує збільшене зображення, Fit підганяє його
під область перегляду, а 100% повертає вихідний масштаб. Клавіші 0 і 1
@@ -735,6 +741,11 @@ Warning і початковий фокус на No.
- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання.
- Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку.
- F1 відкриває вбудовану офлайн-довідку для панелі, вибраного пункту меню чи поточного діалогу. Пошук фільтрує теми за назвою й текстом. Esc закриває довідку та повертає фокус. У командному рядку з назвою команди F1 зберігає перехід до її довідки Windows. Загальна довідка також доступна через Commands → Help.
- Options → Import JSON / Export JSON переносить вибрані групи збережених параметрів Files. Окремо доступні кольори панелей і порівняння разом зі стилями файлів, режими й компонування панелей та іменовані схеми клавіш. Перед заміною відмінних схем з однаковою назвою Files запитує підтвердження. Імпорт спочатку оновлює чернетку Options. Apply або OK зберігає зміни, Cancel відкидає їх. Формат містить лише ці параметри. Невідомі поля і групи пропускаються.
- Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings.
- Масштаб панелей, текстового Viewer, Editor, Markdown, термінала й порівняння зберігається окремо. У Commands є Panel appearance або Terminal appearance залежно від видимої області. Options у Viewer, Editor та Markdown і кнопка Appearance у порівнянні відкривають відповідну сторінку. Значення 100% використовує обраний базовий розмір шрифту.
- Viewer і Editor підтримують колірну схему System (Windows). У Appearance → System themes можна призначити окремі палітри світлому й темному режимам Windows, включно із власними схемами. Rename scheme змінює назву власної схеми у списку, Viewer, Editor і призначеннях світлого та темного режимів.
- Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення.
- У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок.
- Модальні діалоги редактора й переглядача використовують той самий шрифт, що й діалоги операцій Files. Розміри полів і кнопок враховують метрики цього шрифту.
@@ -766,6 +777,35 @@ Warning і початковий фокус на No.
робочий файл у Viewer, **F4** відкриває його в Editor, якщо файл існує.
**Ctrl+R** перечитує Git, **Esc** повертає обидві панелі. Для цього
режиму потрібен Git for Windows. Перегляд залишає Git index без змін.
- У Git Changes кнопка **History** або **F6** відкриває історію. **Branch**
вибирає локальну чи remote-tracking гілку для перегляду. Зірочка
позначає поточну гілку або detached HEAD. Вибір не змінює checkout.
Сусідня панель показує повідомлення коміту та змінені шляхи.
Для merge-коміту список шляхів відповідає різниці з першим батьком.
**More** або **F7** додає наступні 50 комітів, **Ctrl+R** перечитує гілки,
**F6** повертає до Git Changes, а **Esc** повертає до файлових панелей.
- У Git Changes **Stage** та **Unstage** діють на вибраний запис.
Unstage перейменування відновлює обидва індексні шляхи. Якщо шлях уже
має staged-версію, Stage запитує підтвердження заміни.
- **Commit** показує checkout-гілку й усі staged-шляхи, включно з
прихованими фільтром. Якщо гілка, HEAD або staged-вміст змінилися
після перегляду, Files зберігає повідомлення й вимагає нового перегляду.
Після коміту показує хеш і перечитує Git Changes. Для detached HEAD,
розв’язання конфліктів або продовження активної операції використовуй
Git у терміналі.
- Stage використовує clean-фільтри Git. Локальний Commit враховує
**commit.gpgSign** і налаштований засіб підписування. Git hooks для
цих операцій Files вимкнено. Для комітів із hooks або інтерактивним
підписуванням використовуй Git у терміналі.
- **F9 → Commands → Environment Variables** показує області **User**,
**System** і **Process**, джерело, сире та розгорнуте значення.
Process показує середовище поточного процесу Files лише для читання.
**Edit** зберігає тип реєстрового значення. **Copy to User** і
**Copy to System** переносять сире значення та його тип і запитують
підтвердження, якщо визначення існує. Якщо значення змінилося після
відкриття діалогу або Windows відмовила в доступі, Files показує причину.
Запущені сеанси PowerShell зберігають своє середовище. Після зміни
перезапусти Files, щоб вбудований PowerShell успадкував нові значення.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
@@ -807,6 +847,11 @@ Warning і початковий фокус на No.
- Секції поточного файла й загального прогресу мають однаковий вертикальний відступ від вмісту до верхньої та нижньої ліній. Cancel стоїть по центру спільної нижньої секції.
- Обидві шкали займають усю ширину вмісту. Відсотки показуються по центру шкали, а її висота враховує поточний шрифт.
- **Options** у Copy/Move задає маску імен файлів із символами `*` і `?`. Порожня маска або `*` копіює всі файли й порожні папки. З іншою маскою Files зберігає структуру папок із відповідними файлами. У Move файли поза маскою залишаються в джерелі.
- Додаткові папки вводяться абсолютними шляхами, по одному на рядок, на тому самому комп’ютері або підключенні, що й основне призначення. Однакові папки обробляються один раз. У Move джерело видаляється після успішного копіювання елемента в усі вибрані папки. У разі пропуску або збою вже записані копії зберігаються. Підсумок показує кількість повністю скопійованих елементів по всіх призначеннях і загальну кількість записаних файлів.
- **Preserve modification time** зберігає час зміни там, де ціль підтримує його встановлення. Збереження часу підтримують Windows і SFTP. FTP-призначення використовує час сервера. **Preserve Windows permissions** переносить DACL між файловими системами Windows, які підтримують цей тип прав. Наявні папки, у які додаються файли, зберігають власні права й час.
- Оцінка залишку часу в прогресі з’являється після кількох вимірювань швидкості. Довга пауза скидає оцінку. Скасування й конфлікти використовують спільні діалоги.
## Попередження про конфлікт
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
@@ -824,6 +869,14 @@ Warning і початковий фокус на No.
- F8 переміщує підтверджені елементи в кошик Windows. Shift+Delete видаляє підтверджене дерево від вкладених елементів до батьківської папки. Прогрес і підсумок окремо показують успішні, пропущені й невдалі дії.
- Cancel і Esc у вікні прогресу відкривають спільне червоне підтвердження скасування. Yes зупиняє операцію, а No або Esc у підтвердженні повертає до прогресу. Початковий фокус стоїть на No.
## Обмін і компонування панелей
- **Commands → Swap panels** або **Ctrl+U** міняє панелі місцями. Активна панель, шлях, курсор, прокручування, позначки, поточний режим і Quick View переходять разом.
- **Options → File panel modes → Panel layout** містить незалежні параметри для правої кнопки, кнопок дисків і компактного компонування. За замовчуванням ці параметри вимкнені.
- **Mark items with the right mouse button** перемикає позначку рядка. **Shift+права кнопка**, **Shift+F10** і клавіша **Menu** відкривають контекстне меню. Права кнопка на порожньому місці також відкриває контекстне меню панелі.
- **Show drive buttons** додає наявні локальні диски над панелями. Кнопка відкриває корінь диска в активній панелі. Якщо всі диски не поміщаються, **…** відкриває Change drive.
- **Compact commander layout** скорочує проміжки між шляхом, рядками та станом, зберігаючи розмір шрифту, командний рядок і клавіші дій.
## Перевірка змін
Відкрий Copy і Warning в одній збірці та порівняй висоту нижніх секцій, центрування, повноту підписів і видимість фокуса. Перевір Tab, стрілки й Esc. Після узгодження нового правила онови відповідний розділ цього документа.
+65 -2
View File
@@ -9,9 +9,72 @@ with all online paired computers: history and the active clipboard.
## Trusted LAN clients
Open **Settings → Computers → Manage computers → Trusted clients** and choose **Add client…**. Select the Dirlume executable, confirm, then click **Save** in Settings. Dirlume can list existing LAN pairs, browse their drives, and download regular files using each remote computer’s file-access permissions. Pairing credentials stay in the resident KSwitcher process.
Open **Settings → Computers → Manage computers → Trusted clients** and choose
**Add client…**. Select the executable, confirm, and click **Save** in Settings.
A newly approved or previously enrolled executable can list pairs, browse
drives and download regular files. For each executable you can separately
enable **Allow write** for creating, editing, renaming, and copying, and
**Allow delete** for the recycle bin and permanent deletion. Move needs both
permissions. The paired computer's Windows access and file-sharing settings
still apply. KSwitcher retains the pairing credentials.
Select an executable, choose **Remove**, then click **Save** to revoke access. Add the executable again after updating it, since KSwitcher checks the approved path and SHA-256 fingerprint.
Select an executable and choose **Remove**, or turn off an individual grant,
then click **Save** to revoke access. KSwitcher checks grants again during
streaming and before publication or source removal. Add an updated executable
again because approval covers its path and SHA-256 fingerprint.
### Local trusted-client protocol
The Windows pipe is `\\.\pipe\KSwitcher.LAN.Clients.v1.<session>` and accepts
one request per connection from the resident's user. Send a JSON object in an
unsigned 32-bit little-endian length frame (maximum 16 KiB for the request).
Replies have the same length prefix. After the last reply, send one raw
acknowledgement byte and close. An error reply is a JSON object containing
a string `error`. Existing `peers`, `drives`, `list` and `download` requests
retain their original reply formats.
- `capabilities` optionally takes a `peer`. It returns the broker `protocol`
(2), `hostRevision`, and boolean `write`, `delete`, `move`,
`revisionRead`, `onHostTransfer`, and `localEndpoint` fields. With no peer,
the fields describe the local broker and its grants. With a peer, the flags
also account for its supported protocol. A peer with revision 0 still
supports legacy browsing and downloading.
- `stat` takes `peer` and an absolute `path`. It returns Windows attributes,
byte `size` and `modified` (Windows FILETIME). Preserve 64-bit integers
without rounding. `readFile` takes the same arguments plus an optional
`expected` object with `size` and `modified`. It returns metadata followed
by raw frames up to 64 KiB and a zero-length frame. Require the declared
byte count and the zero-length frame before accepting the download.
- `writeFile` takes `peer`, `path`, and the incoming byte `size`. Omit
`expected` for an exclusive create. Include the original `size` and
`modified` in `expected` for an edit. After the `ready` JSON reply, send
raw frames up to 64 KiB followed by a zero-length frame. The final reply
contains the saved metadata or an error. The host stages bytes until
the upload is complete and checks the revision when publishing an edit.
- `mkdir`, `rename`, `recycle`, and `delete` take `peer` and `path`.
Rename also takes a single new `name` and fails if the destination exists.
Permanent deletion of nonempty directories requires `recursive: true`.
The recycle bin is subject to Windows availability on the paired host.
- `transfer` takes `source` and `target` objects with a `peer` and `path`
each, optional `move` (default false), and a `conflict` policy of `fail`
(default), `skip`, or `replace`. Replace merges directories and replaces
regular files after validating the destination revision. The broker
allows at most one local endpoint, represented by `"peer": null`. For a
local endpoint the client must open the pipe with Windows impersonation
enabled, and local files are accessed using the caller's token.
- Transfer replies are JSON progress frames containing `type: "progress"`,
`phase` (`copy` or `remove`), source `path`, byte `done` and `total` for the current file, and
`completed` and `skipped` item counts. Reply to each progress frame with
a JSON frame containing `continue: true` or `continue: false`. The
final frame has `type: "complete"` and counts, or an error. Transfers
on one paired computer use its own file service even across drives. The
local pipe exchanges only control and status for transfers.
- For a move, the copy phase finishes before source deletion begins.
Skipped items remain at the source. Cancellation or failure can leave
previously completed destination items. Failure during source cleanup
can leave a partially removed source tree. Unpublished file uploads are
discarded. File-tree transfer does not follow junctions or symbolic
links within the tree.
## Remote files and diagnostic logs
+1 -1
View File
@@ -16,7 +16,7 @@ function(build_files_webp)
endfunction()
build_files_webp()
add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_view.cpp)
add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_edit.cpp src/files_image_view.cpp)
target_compile_definitions(KSwitcherFilesImage PRIVATE NOMINMAX UNICODE _UNICODE _WIN32_WINNT=0x0A00)
target_link_libraries(KSwitcherFilesImage PRIVATE webpdemux windowscodecs msimg32 ole32)
if(MSVC)
+180 -8
View File
@@ -156,6 +156,78 @@ BEGIN
PUSHBUTTON "Cancel", IDCANCEL, 162, 44, 50, 14
END
615 DIALOGEX 0, 0, 371, 214
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Keyboard shortcuts"
FONT 9, "Segoe UI"
BEGIN
LTEXT "Active &scheme", -1, 9, 9, 160, 11
COMBOBOX 610, 9, 22, 194, 120, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
PUSHBUTTON "&Copy as…", 611, 211, 22, 69, 15
PUSHBUTTON "Rese&t scheme", 612, 288, 22, 74, 15
LTEXT "&Command", -1, 9, 49, 166, 11
LISTBOX 613, 9, 63, 166, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
LTEXT "", 614, 184, 49, 178, 11
LISTBOX 615, 184, 63, 178, 80, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
CONTROL "", 616, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 184, 152, 74, 15
PUSHBUTTON "&Add", 617, 264, 152, 44, 15
PUSHBUTTON "&Remove", 618, 314, 152, 48, 15
PUSHBUTTON "Make &primary", 619, 184, 172, 75, 15
DEFPUSHBUTTON "OK", IDOK, 250, 192, 52, 15
PUSHBUTTON "Cancel", IDCANCEL, 310, 192, 52, 15
END
616 DIALOGEX 0, 0, 233, 73
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Copy keyboard scheme"
FONT 9, "Segoe UI"
BEGIN
LTEXT "Scheme &name", -1, 9, 9, 214, 11
EDITTEXT 620, 9, 23, 215, 15, ES_AUTOHSCROLL
DEFPUSHBUTTON "Copy", IDOK, 112, 49, 52, 15
PUSHBUTTON "Cancel", IDCANCEL, 172, 49, 52, 15
END
617 DIALOGEX 0, 0, 240, 124
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Files settings"
FONT 9, "Segoe UI"
BEGIN
LTEXT "", 624, 9, 9, 222, 24
AUTOCHECKBOX "Colors and file styles", 621, 9, 39, 222, 13
AUTOCHECKBOX "Panel modes and layout", 622, 9, 55, 222, 13
AUTOCHECKBOX "Keyboard schemes", 623, 9, 71, 222, 13
DEFPUSHBUTTON "Load", IDOK, 118, 99, 52, 15
PUSHBUTTON "Cancel", IDCANCEL, 179, 99, 52, 15
END
618 DIALOGEX 0, 0, 468, 242
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "KSwitcher Files Help"
FONT 9, "Segoe UI"
BEGIN
LTEXT "&Search help", -1, 9, 9, 112, 11
EDITTEXT 670, 9, 23, 145, 15, ES_AUTOHSCROLL
LISTBOX 671, 9, 45, 145, 160, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
LTEXT "", 672, 165, 23, 294, 15
EDITTEXT 673, 165, 45, 294, 160, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL
DEFPUSHBUTTON "&Close", IDOK, 403, 216, 56, 16
END
619 DIALOGEX 0, 0, 435, 211
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Files log"
FONT 9, "Segoe UI"
BEGIN
LTEXT "&Log", -1, 9, 12, 40, 11
COMBOBOX 680, 51, 9, 115, 70, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "", 681, 9, 31, 415, 28
LISTBOX 682, 9, 62, 417, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP
PUSHBUTTON "&Copy selected", 683, 9, 187, 90, 15
PUSHBUTTON "&Refresh", 684, 107, 187, 66, 15
DEFPUSHBUTTON "Close", IDOK, 370, 187, 56, 15
END
101 DIALOGEX 0, 0, 397, 310
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN
CAPTION "KSwitcher Files Options"
@@ -169,6 +241,10 @@ BEGIN
COMBOBOX 273, 132, 40, 108, 74, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "&Right panel", 507, 251, 27, 117, 11
COMBOBOX 274, 251, 40, 117, 74, CBS_DROPDOWNLIST | WS_TABSTOP
AUTOCHECKBOX "Mark items with the right mouse button", 520, 132, 64, 245, 13
AUTOCHECKBOX "Show drive buttons", 521, 132, 81, 245, 13
AUTOCHECKBOX "Compact commander layout", 522, 132, 98, 245, 13
LTEXT "Shift+right-click opens the Windows context menu.", 523, 132, 115, 245, 13
GROUPBOX "Wide panel columns", 275, 129, 27, 259, 59
LTEXT "Size column &width (6–16 characters)", 276, 138, 44, 175, 10
EDITTEXT 201, 335, 41, 43, 14, ES_NUMBER | ES_AUTOHSCROLL
@@ -190,10 +266,7 @@ BEGIN
COMBOBOX 305, 311, 51, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "&Row text padding (characters)", 306, 131, 77, 173, 12
COMBOBOX 307, 311, 74, 56, 76, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "Previous command", 320, 131, 30, 120, 12
CONTROL "", 321, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 27, 110, 15
LTEXT "Open command history", 322, 131, 53, 120, 12
CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15
PUSHBUTTON "&Keyboard shortcuts…", 321, 131, 30, 127, 15
AUTOCHECKBOX "Allow &paired PCs to run PowerShell commands here", 370, 131, 79, 250, 14
AUTOCHECKBOX "Allow paired PCs to &hibernate this PC", 371, 131, 95, 250, 14
AUTOCHECKBOX "Allow paired PCs to &update KSwitcher here", 372, 131, 111, 250, 14
@@ -232,6 +305,8 @@ BEGIN
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
LTEXT "", 367, 345, 184, 45, 12
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
PUSHBUTTON "Re&name scheme…", 534, 257, 163, 125, 15
AUTOCHECKBOX "Restore local Viewer and Editor windows after restart", 524, 131, 210, 250, 13
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12
@@ -245,8 +320,16 @@ BEGIN
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
PUSHBUTTON "&Keyboard shortcuts…", 415, 131, 127, 127, 15
LTEXT "&Scale", 528, 131, 235, 118, 12
COMBOBOX 529, 257, 232, 125, 98, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "&Light mode palette", 530, 131, 32, 118, 12
COMBOBOX 531, 250, 29, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "&Dark mode palette", 532, 131, 56, 118, 12
COMBOBOX 533, 250, 53, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "Viewer and Editor use these palettes when Color scheme is set to System (Windows).", 535, 131, 80, 250, 28
PUSHBUTTON "&Import JSON…", 525, 8, 289, 70, 14
PUSHBUTTON "&Export JSON…", 526, 84, 289, 70, 14
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
@@ -262,8 +345,9 @@ BEGIN
LTEXT "Existing files:", 212, 14, 57, 122, 14, SS_CENTERIMAGE
COMBOBOX 213, 140, 57, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
AUTOCHECKBOX "Also ask on read-only files", 214, 14, 77, 322, 14
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 92, 86, 18
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 92, 86, 18
CONTROL "&Options...", 215, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 222, 92, 86, 18
END
103 DIALOGEX 0, 0, 460, 126
@@ -619,3 +703,91 @@ BEGIN
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 95, 153, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 185, 153, 80, 17
END
126 DIALOGEX 0, 0, 420, 213
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Commit staged changes"
FONT 10, "Consolas"
BEGIN
LTEXT "", 594, 16, 15, 388, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 595, 16, 31, 388, 13, SS_NOPREFIX
LISTBOX 596, 16, 45, 388, 61, LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "Commit &message", 597, 16, 112, 388, 13
EDITTEXT 598, 16, 127, 388, 39, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN
LTEXT "", 599, 16, 170, 388, 13, SS_ENDELLIPSIS | SS_NOPREFIX | NOT WS_VISIBLE
LTEXT "", 600, 10, 186, 1, 1, NOT WS_VISIBLE
CONTROL "&Commit", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 125, 193, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 215, 193, 80, 17
END
127 DIALOGEX 0, 0, 458, 224
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Environment Variables"
FONT 10, "Consolas"
BEGIN
LTEXT "&Scope", 610, 16, 16, 58, 13
COMBOBOX 611, 77, 15, 120, 75, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
LTEXT "", 613, 16, 34, 426, 13, SS_PATHELLIPSIS | SS_NOPREFIX
LISTBOX 612, 16, 50, 172, 119, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "", 614, 197, 50, 245, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "Ra&w value", 620, 197, 66, 245, 13
EDITTEXT 615, 197, 80, 245, 30, ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY
LTEXT "E&xpanded value", 621, 197, 115, 245, 13
EDITTEXT 616, 197, 129, 245, 39, ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY
LTEXT "", 617, 16, 174, 426, 24, SS_NOPREFIX
LTEXT "", 618, 10, 199, 1, 1, NOT WS_VISIBLE
CONTROL "&Edit", 622, "Button", BS_OWNERDRAW | WS_TABSTOP, 27, 204, 59, 15
CONTROL "Copy to &User", 623, "Button", BS_OWNERDRAW | WS_TABSTOP, 89, 204, 89, 15
CONTROL "Cop&y to System", 624, "Button", BS_OWNERDRAW | WS_TABSTOP, 181, 204, 100, 15
CONTROL "&Refresh", 625, "Button", BS_OWNERDRAW | WS_TABSTOP, 285, 204, 66, 15
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 354, 204, 65, 15
END
128 DIALOGEX 0, 0, 366, 122
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Edit environment definition"
FONT 10, "Consolas"
BEGIN
LTEXT "", 630, 16, 16, 334, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "Ra&w value", 631, 16, 33, 334, 13
EDITTEXT 632, 16, 47, 334, 42, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN
LTEXT "", 633, 10, 94, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 100, 78, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 186, 100, 78, 16
END
129 DIALOGEX 0, 0, 388, 177
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Copy/Move options"
FONT 10, "Consolas"
BEGIN
LTEXT "File &mask", 645, 14, 15, 360, 13
FAR_EDIT(640, 0, 14, 28, 360, 17)
LTEXT "Additional &folders on this computer (one absolute path per line)", 646, 14, 53, 360, 13
EDITTEXT 641, 14, 67, 360, 40, ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL | WS_VSCROLL
AUTOCHECKBOX "Preserve modification &time", 642, 14, 112, 360, 14
AUTOCHECKBOX "Preserve Windows &permissions", 643, 14, 127, 360, 14
LTEXT "Extra folders use the same destination computer or connection.", 647, 14, 143, 360, 13
LTEXT "", 644, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 161, 86, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 200, 161, 86, 16
END
130 DIALOGEX 0, 0, 329, 119
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Crop image"
FONT 10, "Consolas"
BEGIN
LTEXT "", 650, 14, 15, 301, 12
LTEXT "&X", 656, 14, 35, 58, 14, SS_CENTERIMAGE
FAR_EDIT(651, ES_NUMBER, 75, 33, 70, 18)
LTEXT "&Y", 657, 173, 35, 58, 14, SS_CENTERIMAGE
FAR_EDIT(652, ES_NUMBER, 244, 33, 70, 18)
LTEXT "&Width", 658, 14, 60, 58, 14, SS_CENTERIMAGE
FAR_EDIT(653, ES_NUMBER, 75, 58, 70, 18)
LTEXT "&Height", 659, 173, 60, 62, 14, SS_CENTERIMAGE
FAR_EDIT(654, ES_NUMBER, 244, 58, 70, 18)
LTEXT "", 655, 10, 86, 1, 1, NOT WS_VISIBLE
CONTROL "&Crop", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 78, 94, 83, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 168, 94, 83, 17
END
+1 -1
View File
@@ -27,7 +27,7 @@ nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px;
::highlight(markdown-search-active) { background: #ffab45; color: #171717; }
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
a { color: LinkText; }
a[href] { color: LinkText; }
pre, table, figure { overflow: auto; }
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
pre { padding: .75em; }
+31 -8
View File
@@ -73,7 +73,7 @@ markdown.renderer.rules.image = (tokens, i) => {
const htmlTags = new Set(`a abbr address article aside b blockquote br caption code col colgroup dd del
details div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hr i img input ins kbd li
mark ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
main mark nav ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
tr u ul var wbr`.split(/\s+/));
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
const tagAttributes = {
@@ -88,21 +88,25 @@ function relativeResource(path) {
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
}
function renderContent(text, canSave) {
function renderContent(text, canSave, html) {
// Parse in an inert template and allow only document markup before attaching it to the preview.
const template = document.createElement('template');
const taskKey = [...crypto.getRandomValues(new Uint32Array(4))].join('-');
taskMarkers = new WeakMap();
pendingTask = undefined;
template.innerHTML = markdown.render(text, { taskKey });
template.innerHTML = html ? text : 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) ||
(tag === 'input' && element.type !== 'checkbox')) {
(tag === 'input' && (html || element.type !== 'checkbox'))) {
element.remove();
continue;
}
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
const imagePath = !html && tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
if (html && tag === 'img') {
element.replaceWith(document.createTextNode(element.getAttribute('alt') ?? ''));
continue;
}
const task = tag === 'input' && element.getAttribute('data-task');
if (task && task.startsWith(taskKey + ':')) {
const [, line, column] = task.split(':');
@@ -112,7 +116,8 @@ function renderContent(text, canSave) {
const styles = element.hasAttribute('style')
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
for (const { name } of [...element.attributes]) {
if (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name)) element.removeAttribute(name);
const blockedInHtml = html && (name === 'id' || name === 'class' || name === 'href');
if (blockedInHtml || (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name))) element.removeAttribute(name);
}
for (const [name, value] of styles) {
if (value) element.style.setProperty(name, value);
@@ -247,7 +252,7 @@ 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, revision, canSave, compact }) {
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact, html }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
else closeSearch();
@@ -255,7 +260,14 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
document.title = title;
document.documentElement.classList.toggle('quick-view', Boolean(compact));
previewRevision = revision;
renderContent(text, canSave);
renderContent(text, canSave, html);
images = [];
if (html) {
window.scrollTo(0, 0);
document.documentElement.classList.add('rendered');
send('rendered', { revision });
return;
}
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, '-');
@@ -343,6 +355,17 @@ document.addEventListener('keydown', event => {
}
});
let scrollTimer;
window.addEventListener('scroll', () => {
if (document.documentElement.classList.contains('quick-view')) return;
clearTimeout(scrollTimer);
const revision = previewRevision;
scrollTimer = setTimeout(() => {
if (revision === previewRevision && document.documentElement.classList.contains('rendered'))
send('scroll', { revision, top: Math.round(window.scrollY) });
}, 120);
}, { passive: true });
bridge.addEventListener('message', ({ data }) => {
const message = JSON.parse(data);
if (message.action === 'clear') {
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include <windows.h>
#include <array>
#include <cstddef>
#include <cwchar>
namespace ks::files
{
enum class AppearanceArea { panels, viewer, editor, markdown, terminal, comparison, count };
inline constexpr size_t appearanceIndex(AppearanceArea area) { return static_cast<size_t>(area); }
using AppearanceScales=std::array<unsigned,appearanceIndex(AppearanceArea::count)>;
inline constexpr AppearanceScales defaultAppearanceScales{100,100,100,100,100,100};
inline constexpr unsigned minAppearanceScale=75,maxAppearanceScale=200;
inline int scaledAppearanceSize(int size,unsigned percent)
{
return MulDiv(size,static_cast<int>(percent),100);
}
inline bool windowsAppThemeChanged(UINT message,LPARAM parameter)
{
return message==WM_THEMECHANGED || (message==WM_SETTINGCHANGE && parameter &&
std::wcscmp(reinterpret_cast<const wchar_t*>(parameter),L"ImmersiveColorSet")==0);
}
inline bool windowsUsesDarkApps()
{
DWORD light=1,bytes=sizeof(light);
return RegGetValueW(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
L"AppsUseLightTheme",RRF_RT_REG_DWORD,nullptr,&light,&bytes)==ERROR_SUCCESS && !light;
}
}
-57
View File
@@ -1,5 +1,3 @@
constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)};
auto commandHistoryKeys=defaultHistoryKeys;
constexpr size_t commandHistoryLimit=1000;
std::wstring commandHistoryLabel(const std::wstring &command)
@@ -19,41 +17,6 @@ std::wstring commandHistoryLabel(const std::wstring &command)
return fs::path(path).is_absolute()?path:command;
}
bool validHistoryKeys(const std::array<WORD,2> &keys)
{
if(keys[0]==keys[1]) return false;
return std::all_of(keys.begin(),keys.end(),[](WORD binding)
{
const auto key=LOBYTE(binding), modifiers=HIBYTE(binding);
const bool letter=key>='A' && key<='Z';
const bool function=key>=VK_F1 && key<=VK_F12;
if(!letter && !function) return false;
if(modifiers==HOTKEYF_CONTROL)
return letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y';
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
return false;
});
}
std::array<WORD,2> optionHistoryKeys(HWND dialog)
{
return {static_cast<WORD>(SendDlgItemMessageW(dialog,321,HKM_GETHOTKEY,0,0)),
static_cast<WORD>(SendDlgItemMessageW(dialog,323,HKM_GETHOTKEY,0,0))};
}
void setOptionHistoryKeys(HWND dialog,const std::array<WORD,2> &keys)
{
SendDlgItemMessageW(dialog,321,HKM_SETHOTKEY,keys[0],0);
SendDlgItemMessageW(dialog,323,HKM_SETHOTKEY,keys[1],0);
}
void loadCommandHistoryKeys()
{
const std::array<WORD,2> keys{static_cast<WORD>(preference(L"PreviousCommandKey",defaultHistoryKeys[0])),
static_cast<WORD>(preference(L"CommandHistoryKey",defaultHistoryKeys[1]))};
commandHistoryKeys=validHistoryKeys(keys)?keys:defaultHistoryKeys;
}
void loadCommandHistory()
{
@@ -107,23 +70,3 @@ void recallPreviousCommand()
if(terminalHistoryIndex==terminalHistory.size()) terminalHistoryDraft=terminalInputText();
recallCommand(terminalHistoryIndex-1);
}
void showCommandHistory(HWND owner);
bool handleCommandHistoryKey(HWND window,const MSG &message)
{
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
if((GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000)) return false;
const BYTE modifiers=((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0) |
((GetKeyState(VK_MENU)&0x8000)?HOTKEYF_ALT:0) | ((GetKeyState(VK_SHIFT)&0x8000)?HOTKEYF_SHIFT:0);
const auto binding=MAKEWORD(message.wParam,modifiers);
if(binding==commandHistoryKeys[0] && (message.hwnd==terminalInput ||
message.hwnd==panels[0].list || message.hwnd==panels[1].list))
{
recallPreviousCommand();
return true;
}
if(binding!=commandHistoryKeys[1]) return false;
if(!(message.lParam&(1LL<<30))) showCommandHistory(window);
return true;
}
+8 -28
View File
@@ -4,31 +4,8 @@ enum ComparisonColor { CompareBackground, CompareText, CompareInsert, CompareDel
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();
@@ -157,8 +134,9 @@ 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;
const auto base=areaFontPoints(comparison.appearance.points,AppearanceArea::comparison);
const auto points=std::clamp(base+comparison.zoom,60,480);
comparison.zoom=points-base;
font.lfHeight=-MulDiv(points,dpi,720);
font.lfWidth=0;
if(const auto next=CreateFontIndirectW(&font))
@@ -201,8 +179,8 @@ bool zoomComparison(HWND dialog,FileComparison &comparison,WPARAM wheel)
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;
const auto base=areaFontPoints(comparison.appearance.points,AppearanceArea::comparison);
const auto zoom=std::clamp(base+comparison.zoom+10*steps,60,480)-base;
if(zoom!=comparison.zoom)
{
comparison.zoom=zoom;
@@ -1023,7 +1001,8 @@ void initializeComparisonToolbar(HWND toolbar)
{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")}
{I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Show whitespace changes")},
{I_IMAGENONE,527,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Appearance…")}
};
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
}
@@ -1130,6 +1109,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto id=LOWORD(wp);
if(comparison->working) return TRUE;
if(id==IDCANCEL) {closeComparison(dialog,*comparison);return TRUE;}
if(id==527) {editFilesAppearance(dialog,AppearanceArea::comparison);return TRUE;}
if(id==applyLeft || id==applyRight)
{
const auto side=id-applyLeft;
+97
View File
@@ -0,0 +1,97 @@
struct CopyOptionsPrompt
{
CopyOptions value;
bool permissions{}, move{}, unixDest{};
};
INT_PTR CALLBACK copyOptionsDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int mask=640, paths=641, time=642, permissions=643, footer=644, folderLabel=646, hint=647;
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT*>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Copy/Move options ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
const auto &prompt=*reinterpret_cast<const CopyOptionsPrompt*>(lp);
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
layoutDialogContent(window,645);
fitFarEditToLine(GetDlgItem(window,mask));
installFarCheckbox(GetDlgItem(window,time),FarCheckboxSurface::gray);
installFarCheckbox(GetDlgItem(window,permissions),FarCheckboxSurface::gray);
for(const auto id:{time,permissions})
SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
layoutDialogButtons(window,footer,{IDOK,IDCANCEL});
CheckDlgButton(window,time,prompt.value.preserveTime?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(window,permissions,prompt.value.preservePermissions?BST_CHECKED:BST_UNCHECKED);
EnableWindow(GetDlgItem(window,permissions),prompt.permissions);
SetDlgItemTextW(window,mask,prompt.value.mask.c_str());
SendDlgItemMessageW(window,mask,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(window,paths,EM_SETLIMITTEXT,32767,0);
std::wstring lines;
for(const auto &path:prompt.value.additional)
{
if(!lines.empty()) lines+=L"\r\n";
lines+=path.native();
}
SetDlgItemTextW(window,paths,lines.c_str());
if(prompt.unixDest) SetDlgItemTextW(window,folderLabel,L"Additional &folders on this server (one absolute path per line)");
if(prompt.move) SetDlgItemTextW(window,hint,L"Move keeps the source until every requested copy succeeds.");
SetFocus(GetDlgItem(window,mask));
SendDlgItemMessageW(window,mask,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &prompt=*reinterpret_cast<CopyOptionsPrompt*>(GetWindowLongPtrW(window,DWLP_USER));
const auto text=[&](int id) {
auto control=GetDlgItem(window,id);
std::wstring value(GetWindowTextLengthW(control)+1,L'\0');
value.resize(GetWindowTextW(control,value.data(),static_cast<int>(value.size())));
return value;
};
auto pattern=text(mask);
if(pattern.find_first_of(L"/\\:")!=pattern.npos)
{
showFilesNotice(window,L"Enter a file name or mask without a path.",L"Copy/Move options");
SetFocus(GetDlgItem(window,mask));
return TRUE;
}
const auto entered=text(paths);
std::vector<fs::path> folders;
for(size_t start=0;start<entered.size();)
{
const auto end=entered.find(L'\n',start);
auto line=std::wstring_view(entered).substr(start,end==entered.npos?end:end-start);
if(!line.empty() && line.back()==L'\r') line.remove_suffix(1);
if(!line.empty())
{
auto path=fs::path(line);
const bool unc=!prompt.unixDest && (line.starts_with(L"\\\\") || line.starts_with(L"//"));
const bool absolute=prompt.unixDest?line.front()==L'/':path.is_absolute() || unc;
if(!absolute || line.find_first_of(L"<>|?*")!=line.npos || line.starts_with(L"\\\\.\\"))
{
showFilesNotice(window,L"Enter one absolute destination folder per line.",L"Copy/Move options");
SetFocus(GetDlgItem(window,paths));
return TRUE;
}
if(!unc) path=path.lexically_normal();
folders.push_back(folderPathWithoutSeparator(std::move(path)));
}
if(end==entered.npos) break;
start=end+1;
}
prompt.value={pattern.empty()?L"*":std::move(pattern),std::move(folders),
IsDlgButtonChecked(window,time)==BST_CHECKED,
prompt.permissions && IsDlgButtonChecked(window,permissions)==BST_CHECKED};
FilesModalDialog::finish(window,IDOK);
return TRUE;
}
+15 -4
View File
@@ -1,3 +1,5 @@
bool handleFilesHelpMessage(const MSG &message);
HWND activeFilesDialog{};
HHOOK filesDialogMouseHook{};
@@ -53,9 +55,10 @@ class FilesModalDialog
{
public:
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument,
bool watchOutsideClicks=true)
bool watchOutsideClicks=true,bool fitToOwner=true)
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
watchOutsideClicks_(watchOutsideClicks)
resource_(IS_INTRESOURCE(resource)?static_cast<unsigned>(reinterpret_cast<ULONG_PTR>(resource)):0),
watchOutsideClicks_(watchOutsideClicks),fitToOwner_(fitToOwner)
{
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
}
@@ -66,6 +69,12 @@ public:
HWND window() const { return window_; }
static unsigned resourceFor(HWND window)
{
const auto *state=reinterpret_cast<const FilesModalDialog*>(GetPropW(window,stateProperty_));
return state?state->resource_:0;
}
static HWND activeFor(HWND owner)
{
const auto root=GetAncestor(owner,GA_ROOTOWNER);
@@ -111,7 +120,7 @@ public:
activeFilesDialog=window_;
entered_=true;
refreshMouseHook();
if(GetWindowRect(owner_,&ownerBounds_))
if(fitToOwner_ && GetWindowRect(owner_,&ownerBounds_))
{
if(!layout_) captureLayout();
SetWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this),reinterpret_cast<DWORD_PTR>(this));
@@ -146,6 +155,7 @@ public:
{
if(message.hwnd==dialog || IsChild(dialog,message.hwnd))
{
if(handleFilesHelpMessage(message)) return true;
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
{
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
@@ -209,7 +219,8 @@ private:
DLGPROC procedure_;
LPARAM argument_;
INT_PTR result_=IDCANCEL;
bool entered_{},finished_{},watchOutsideClicks_;
unsigned resource_{};
bool entered_{},finished_{},watchOutsideClicks_,fitToOwner_;
static void refreshMouseHook()
{
+418
View File
@@ -0,0 +1,418 @@
enum class EnvironmentScope { user, system, process };
constexpr wchar_t userEnvironmentPath[]=L"Environment";
constexpr wchar_t systemEnvironmentPath[]=L"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
constexpr unsigned environmentValueLimit=32767;
const wchar_t *environmentScopeName(EnvironmentScope scope)
{
switch(scope)
{
case EnvironmentScope::user: return L"User";
case EnvironmentScope::system: return L"System";
case EnvironmentScope::process: return L"Process";
}
return L"";
}
std::wstring environmentSource(EnvironmentScope scope)
{
if(scope==EnvironmentScope::process) return L"Current KSwitcher.Files process";
return scope==EnvironmentScope::user?L"HKCU\\"+std::wstring(userEnvironmentPath):
L"HKLM\\"+std::wstring(systemEnvironmentPath);
}
struct EnvironmentKey
{
HKEY value{};
explicit EnvironmentKey(EnvironmentScope scope,bool write=false)
{
const bool user=scope==EnvironmentScope::user;
const auto root=user?HKEY_CURRENT_USER:HKEY_LOCAL_MACHINE;
const auto path=user?userEnvironmentPath:systemEnvironmentPath;
const auto access=KEY_QUERY_VALUE|(write?KEY_SET_VALUE:0);
const auto result=user && write?
RegCreateKeyExW(root,path,0,nullptr,0,access,nullptr,&value,nullptr):
RegOpenKeyExW(root,path,0,access,&value);
if(result!=ERROR_SUCCESS && (result!=ERROR_FILE_NOT_FOUND || !user || write))
throw std::system_error(result,std::system_category(),"Open the environment registry key");
}
EnvironmentKey(const EnvironmentKey &)=delete;
~EnvironmentKey(){if(value) RegCloseKey(value);}
};
struct EnvironmentValue
{
DWORD type{};
std::wstring text;
bool supported{};
bool operator==(const EnvironmentValue &) const = default;
};
struct EnvironmentVariable
{
std::wstring name;
EnvironmentValue value;
};
std::optional<EnvironmentValue> readEnvironmentValue(HKEY key,const std::wstring &name)
{
if(!key) return {};
DWORD size{},type{};
auto result=RegQueryValueExW(key,name.c_str(),nullptr,&type,nullptr,&size);
if(result==ERROR_FILE_NOT_FOUND) return {};
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Read the environment definition");
for(int attempt=0;attempt<4;++attempt)
{
if(type!=REG_SZ && type!=REG_EXPAND_SZ) return EnvironmentValue{type,{},false};
if(size%sizeof(wchar_t) || size>2*(environmentValueLimit+1))
return EnvironmentValue{type,{},false};
std::wstring text(size/sizeof(wchar_t)+1,L'\0');
result=RegQueryValueExW(key,name.c_str(),nullptr,&type,reinterpret_cast<BYTE*>(text.data()),&size);
if(result==ERROR_FILE_NOT_FOUND) return {};
if(result==ERROR_MORE_DATA) continue;
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Read the environment definition");
if((type!=REG_SZ && type!=REG_EXPAND_SZ) || size%sizeof(wchar_t))
return EnvironmentValue{type,{},false};
text.resize(size/sizeof(wchar_t));
while(!text.empty() && text.back()==L'\0') text.pop_back();
if(text.find(L'\0')!=text.npos) return EnvironmentValue{type,{},false};
return EnvironmentValue{type,std::move(text),true};
}
throw std::runtime_error("The environment definition changed while Windows was reading it.");
}
std::vector<EnvironmentVariable> readEnvironmentScope(EnvironmentScope scope)
{
std::vector<EnvironmentVariable> entries;
if(scope==EnvironmentScope::process)
{
const auto block=GetEnvironmentStringsW();
if(!block) throw std::system_error(GetLastError(),std::system_category(),"Read the current process environment");
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> owned(block,FreeEnvironmentStringsW);
for(auto offset=block;*offset;)
{
const std::wstring_view line=offset;
const auto equals=line.find(L'=');
if(equals!=line.npos && equals>0)
entries.push_back({std::wstring(line.substr(0,equals)),{REG_SZ,std::wstring(line.substr(equals+1)),true}});
offset+=line.size()+1;
}
}
else
{
const EnvironmentKey key(scope);
if(!key.value) return {};
std::vector<wchar_t> name(16384);
for(DWORD index=0;;++index)
{
DWORD length=static_cast<DWORD>(name.size());
const auto result=RegEnumValueW(key.value,index,name.data(),&length,nullptr,nullptr,nullptr,nullptr);
if(result==ERROR_NO_MORE_ITEMS) break;
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"List environment definitions");
if(!length) continue;
std::wstring label(name.data(),length);
if(label.find(L'=')!=label.npos) continue;
if(auto value=readEnvironmentValue(key.value,label);value && value->supported)
entries.push_back({std::move(label),std::move(*value)});
}
}
std::sort(entries.begin(),entries.end(),[](const auto &left,const auto &right) {
return CompareStringOrdinal(left.name.c_str(),-1,right.name.c_str(),-1,TRUE)==CSTR_LESS_THAN;
});
return entries;
}
std::wstring expandedEnvironmentValue(EnvironmentScope scope,const EnvironmentValue &value)
{
if(value.type!=REG_EXPAND_SZ) return value.text;
Handle token{};
if(scope==EnvironmentScope::user &&
!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_IMPERSONATE|TOKEN_DUPLICATE,&token.value))
throw std::system_error(GetLastError(),std::system_category(),"Open the current user's environment");
std::wstring expanded(environmentValueLimit+1,L'\0');
if(!ExpandEnvironmentStringsForUserW(token.value,value.text.c_str(),expanded.data(),static_cast<DWORD>(expanded.size())))
throw std::system_error(GetLastError(),std::system_category(),"Expand the environment definition");
expanded.resize(wcslen(expanded.c_str()));
return expanded;
}
void writeEnvironmentValue(EnvironmentScope scope,const std::wstring &name,const EnvironmentValue &replacement,
const std::optional<EnvironmentValue> &expected)
{
if(scope==EnvironmentScope::process) throw std::runtime_error("The current process environment is read-only here.");
if(replacement.text.size()>environmentValueLimit) throw std::runtime_error("The value exceeds the Windows environment limit.");
const EnvironmentKey key(scope,true);
if(readEnvironmentValue(key.value,name)!=expected)
throw std::runtime_error("Windows changed this definition while it was open. Reload and review the current value.");
if(expected==replacement) return;
const auto bytes=static_cast<DWORD>((replacement.text.size()+1)*sizeof(wchar_t));
const auto result=RegSetValueExW(key.value,name.c_str(),0,replacement.type,
reinterpret_cast<const BYTE*>(replacement.text.c_str()),bytes);
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Save the environment definition");
try
{
std::thread([] {
DWORD_PTR reply{};
SendMessageTimeoutW(HWND_BROADCAST,WM_SETTINGCHANGE,0,reinterpret_cast<LPARAM>(L"Environment"),
SMTO_ABORTIFHUNG,250,&reply);
}).detach();
}
catch(const std::exception &) {}
}
const wchar_t *environmentValueType(const EnvironmentValue &value)
{
return value.type==REG_EXPAND_SZ?L"REG_EXPAND_SZ":L"REG_SZ";
}
struct EnvironmentEdit
{
EnvironmentScope scope;
EnvironmentVariable original;
std::wstring replacement;
};
INT_PTR CALLBACK environmentEditDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int label=630,body=632,footer=633;
if(message==WM_INITDIALOG)
{
const auto &editor=*reinterpret_cast<const EnvironmentEdit *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,label);
const auto title=editor.original.name+L" · "+environmentScopeName(editor.scope)+L" · "+
environmentValueType(editor.original.value);
SetDlgItemTextW(dialog,label,title.c_str());
SendDlgItemMessageW(dialog,body,EM_SETLIMITTEXT,environmentValueLimit,0);
SetDlgItemTextW(dialog,body,editor.original.value.text.c_str());
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(dialog,body));
return FALSE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &editor=*reinterpret_cast<EnvironmentEdit *>(GetWindowLongPtrW(dialog,DWLP_USER));
editor.replacement=dialogFieldText(GetDlgItem(dialog,body));
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Edit environment definition ",false,{footer});
}
constexpr int envScope=611,envList=612,envSource=613,envSelected=614,envRaw=615,envExpanded=616,
envStatus=617,envFooter=618,envEdit=622,envCopyUser=623,envCopySystem=624,envRefresh=625;
struct EnvironmentPanel
{
EnvironmentScope scope=EnvironmentScope::user;
std::vector<EnvironmentVariable> entries;
std::wstring readFailure,notice;
};
std::wstring environmentErrorText(const std::exception &error)
{
if(const auto *system=dynamic_cast<const std::system_error *>(&error)) return fileError(*system);
return ks::wide(error.what());
}
const EnvironmentVariable *selectedEnvironmentVariable(HWND dialog,const EnvironmentPanel &panel)
{
const auto row=SendDlgItemMessageW(dialog,envList,LB_GETCURSEL,0,0);
if(row<0) return nullptr;
const auto index=SendDlgItemMessageW(dialog,envList,LB_GETITEMDATA,row,0);
return index>=0 && static_cast<size_t>(index)<panel.entries.size()?&panel.entries[index]:nullptr;
}
void setEnvironmentDetails(HWND dialog,const EnvironmentPanel &panel)
{
const auto *entry=selectedEnvironmentVariable(dialog,panel);
const bool registry=panel.scope!=EnvironmentScope::process;
SetDlgItemTextW(dialog,envSource,environmentSource(panel.scope).c_str());
SetDlgItemTextW(dialog,envSelected,entry?(entry->name+L" · "+
(registry?environmentValueType(entry->value):L"Read-only")).c_str():L"");
SetDlgItemTextW(dialog,envRaw,entry?entry->value.text.c_str():L"");
std::wstring expanded;
if(entry)
{
try {expanded=expandedEnvironmentValue(panel.scope,entry->value);}
catch(const std::exception &error) {expanded=L"Unavailable · "+environmentErrorText(error);}
}
SetDlgItemTextW(dialog,envExpanded,expanded.c_str());
EnableWindow(GetDlgItem(dialog,envEdit),entry && registry);
EnableWindow(GetDlgItem(dialog,envCopyUser),entry && panel.scope!=EnvironmentScope::user);
EnableWindow(GetDlgItem(dialog,envCopySystem),entry && panel.scope!=EnvironmentScope::system);
const auto status=!panel.readFailure.empty()?panel.readFailure:!panel.notice.empty()?panel.notice:
!entry?std::wstring(L"No environment variables in this scope."):
registry?L"Existing PowerShell sessions keep their environment. Restart Files for embedded PowerShell.":
L"These values belong to the running Files process.";
SetDlgItemTextW(dialog,envStatus,status.c_str());
}
void reloadEnvironmentPanel(HWND dialog,EnvironmentPanel &panel,const std::wstring &preferred={})
{
panel.readFailure.clear();
try {panel.entries=readEnvironmentScope(panel.scope);}
catch(const std::exception &error)
{
panel.entries.clear();
panel.readFailure=environmentErrorText(error);
}
const auto list=GetDlgItem(dialog,envList);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(size_t index=0;index<panel.entries.size();++index)
{
const auto &name=panel.entries[index].name;
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));
if(row<0) continue;
SendMessageW(list,LB_SETITEMDATA,row,index);
if(CompareStringOrdinal(name.c_str(),-1,preferred.c_str(),-1,TRUE)==CSTR_EQUAL) selected=row;
}
if(!panel.entries.empty()) SendMessageW(list,LB_SETCURSEL,selected,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,TRUE);
setEnvironmentDetails(dialog,panel);
}
void saveEnvironmentDefinition(HWND dialog,EnvironmentPanel &panel,const EnvironmentVariable &entry,
std::optional<EnvironmentScope> copyTo={})
{
try
{
if(copyTo)
{
const EnvironmentKey key(*copyTo);
const auto previous=readEnvironmentValue(key.value,entry.name);
if(previous && !previous->supported)
throw std::runtime_error("The destination already has a registry value of an unsupported type.");
const auto question=previous?L"Replace "+entry.name+L" in "+environmentScopeName(*copyTo)+L"?":
L"Copy "+entry.name+L" to "+environmentScopeName(*copyTo)+L"?";
if(showFilesNotice(dialog,question.c_str(),L"Copy environment definition",
{.confirm=true,.tone=previous?FilesNoticeTone::warning:FilesNoticeTone::dialog})!=IDYES) return;
if(panel.scope!=EnvironmentScope::process)
{
const EnvironmentKey source(panel.scope);
if(readEnvironmentValue(source.value,entry.name)!=entry.value)
throw std::runtime_error("The source definition changed. Reload and review it before copying.");
}
writeEnvironmentValue(*copyTo,entry.name,entry.value,previous);
panel.scope=*copyTo;
SendDlgItemMessageW(dialog,envScope,CB_SETCURSEL,static_cast<WPARAM>(panel.scope),0);
}
else
{
if(panel.scope==EnvironmentScope::process) return;
EnvironmentEdit editor{panel.scope,entry};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(128),dialog,environmentEditDialog,
reinterpret_cast<LPARAM>(&editor))!=IDOK || editor.replacement==entry.value.text) return;
writeEnvironmentValue(panel.scope,entry.name,{entry.value.type,editor.replacement,true},entry.value);
}
panel.notice=L"Saved. Restart Files for embedded PowerShell to inherit the new value.";
}
catch(const std::exception &error)
{
panel.notice.clear();
const auto details=environmentErrorText(error);
showFilesNotice(dialog,details.c_str(),L"Could not save environment definition",{.tone=FilesNoticeTone::warning});
}
reloadEnvironmentPanel(dialog,panel,entry.name);
}
INT_PTR CALLBACK environmentPanelDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &panel=*reinterpret_cast<EnvironmentPanel *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,610);
const auto scope=GetDlgItem(dialog,envScope);
for(const auto item:{EnvironmentScope::user,EnvironmentScope::system,EnvironmentScope::process})
SendMessageW(scope,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(environmentScopeName(item)));
SendMessageW(scope,CB_SETCURSEL,0,0);
installFarCombo(scope,GetDlgItem(dialog,610));
const auto list=GetDlgItem(dialog,envList);
const auto bounds=dialogControlBounds(dialog,envList);
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
installScrollBar(list,dialog);
layoutDialogButtons(dialog,envFooter,{envEdit,envCopyUser,envCopySystem,envRefresh,IDOK});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
reloadEnvironmentPanel(dialog,panel);
SetFocus(scope);
return FALSE;
}
auto *panel=reinterpret_cast<EnvironmentPanel *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!panel) return FALSE;
if(message==WM_DRAWITEM && wp==envScope)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=GetDlgItem(dialog,envList))
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
if(message==WM_COMMAND)
{
const auto id=LOWORD(wp),notification=HIWORD(wp);
if(id==envScope && (notification==CBN_SELENDOK ||
(notification==CBN_SELCHANGE && !SendDlgItemMessageW(dialog,envScope,CB_GETDROPPEDSTATE,0,0))))
{
const auto scope=SendDlgItemMessageW(dialog,envScope,CB_GETCURSEL,0,0);
if(scope>=0 && scope<=static_cast<LRESULT>(EnvironmentScope::process) &&
static_cast<EnvironmentScope>(scope)!=panel->scope)
{
const auto *entry=selectedEnvironmentVariable(dialog,*panel);
const auto selected=entry?entry->name:std::wstring{};
panel->scope=static_cast<EnvironmentScope>(scope);
reloadEnvironmentPanel(dialog,*panel,selected);
}
return TRUE;
}
if(id==envRefresh || (id==envList && notification==LBN_SELCHANGE))
{
if(id==envRefresh)
{
const auto *entry=selectedEnvironmentVariable(dialog,*panel);
const auto name=entry?entry->name:std::wstring{};
reloadEnvironmentPanel(dialog,*panel,name);
}
else setEnvironmentDetails(dialog,*panel);
return TRUE;
}
if(id==envEdit || id==envCopyUser || id==envCopySystem)
{
if(const auto *entry=selectedEnvironmentVariable(dialog,*panel))
saveEnvironmentDefinition(dialog,*panel,EnvironmentVariable(*entry),id==envEdit?std::nullopt:
std::optional(id==envCopyUser?EnvironmentScope::user:EnvironmentScope::system));
return TRUE;
}
if(id==IDOK || id==IDCANCEL)
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
}
if(message==WM_CLOSE) {FilesModalDialog::finish(dialog,IDCANCEL);return TRUE;}
return paintCopyDialog(dialog,message,wp,lp,L" Environment Variables ",false,{envFooter},false,GetDlgItem(dialog,envList));
}
void showEnvironmentPanel(HWND owner)
{
EnvironmentPanel panel;
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(127),owner,environmentPanelDialog,
reinterpret_cast<LPARAM>(&panel));
}
+14 -1
View File
@@ -25,6 +25,7 @@ struct CopyHost
FileOperationElevation *elevation{};
fs::path listedDirectory;
FileEntries listedEntries;
std::optional<bool> copyMetadataSupport;
CopyHost(const FilesPeer *peer,const std::optional<TransferProfile> &profile,FileOperationElevation *admin=nullptr)
{
@@ -67,6 +68,17 @@ struct CopyHost
return entries;
}
bool supportsCopyMetadata()
{
if(!copyMetadataSupport)
{
const auto reply=request(fileRequest("fileCapabilities",L"C:\\"));
if(reply.at("error")!=ERROR_INVALID_FUNCTION) checkFileReply(reply);
copyMetadataSupport=reply.value("copyMetadata",false);
}
return *copyMetadataSupport;
}
void makeDirectory(const fs::path &path)
{
if(!ftp)
@@ -131,7 +143,7 @@ void downloadTransferFile(TransferSession &ftp,FilesConnection &local,const fs::
FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress,
const ks::files::RemoteTextRevision *expected=nullptr)
const ks::files::RemoteTextRevision *expected=nullptr,bool preserveTime=false)
{
const auto directory=target.parent_path();
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
@@ -179,6 +191,7 @@ FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs
ERROR_ALREADY_EXISTS);
ftp.prepareReplacement(temporary,target);
}
if(preserveTime) ftp.preserveModificationTime(temporary,info.modified);
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
ftp.rename(temporary,target,existing.has_value());
return *uploaded;
+451 -18
View File
@@ -4,6 +4,8 @@
#include <algorithm>
#include <cstddef>
#include <memory>
#include <objbase.h>
#include <optional>
#include <stdexcept>
#include <system_error>
#include <tuple>
@@ -76,15 +78,16 @@ fs::path locateGit()
throw std::runtime_error("Git for Windows was not found. Install it or add git.exe to PATH.");
}
std::vector<wchar_t> gitEnvironment()
std::vector<wchar_t> gitEnvironment(const fs::path &alternateIndex)
{
const auto environment=GetEnvironmentStringsW();
if(!environment) gitWindowsError("Could not read the environment for Git");
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> owned(environment,FreeEnvironmentStringsW);
constexpr std::wstring_view overrides[]{
L"GIT_DIR",L"GIT_WORK_TREE",L"GIT_COMMON_DIR",L"GIT_INDEX_FILE",L"GIT_PREFIX",
L"GIT_OBJECT_DIRECTORY",L"GIT_ALTERNATE_OBJECT_DIRECTORIES",L"GIT_NAMESPACE",L"GIT_QUARANTINE_PATH",
L"GIT_CEILING_DIRECTORIES",L"GIT_GLOB_PATHSPECS",L"GIT_NOGLOB_PATHSPECS",L"GIT_ICASE_PATHSPECS"};
std::vector<wchar_t> result;
std::vector<std::wstring> settings;
for(auto entry=environment;*entry;)
{
const std::wstring_view setting=entry;
@@ -94,9 +97,15 @@ std::vector<wchar_t> gitEnvironment()
CompareStringOrdinal(name.data(),static_cast<int>(name.size()),key.data(),static_cast<int>(key.size()),TRUE)
==CSTR_EQUAL;
}))
result.insert(result.end(),entry,entry+setting.size()+1);
settings.emplace_back(setting);
entry+=setting.size()+1;
}
if(!alternateIndex.empty()) settings.push_back(L"GIT_INDEX_FILE="+alternateIndex.native());
std::sort(settings.begin(),settings.end(),[](const auto &left,const auto &right) {
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)==CSTR_LESS_THAN;
});
std::vector<wchar_t> result;
for(const auto &setting:settings) result.insert(result.end(),setting.c_str(),setting.c_str()+setting.size()+1);
result.push_back(L'\0');
if(result.size()==1) result.push_back(L'\0');
return result;
@@ -131,18 +140,33 @@ struct GitOutput
DWORD exitCode{};
};
struct GitCommandOptions
{
fs::path index;
std::string_view input;
std::function<void()> afterPrepare;
ULONGLONG timeout=15000;
};
GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector<std::wstring> &arguments,
size_t maximum,std::stop_token stop)
size_t maximum,std::stop_token stop,const GitCommandOptions &options={})
{
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
auto command=quoteWindowsArgument(git.native())+
L" --no-pager --no-optional-locks --literal-pathspecs -c core.fsmonitor=false -c core.quotePath=false -C "+
quoteWindowsArgument(directory.native());
for(const auto &argument:arguments) command+=L' '+quoteWindowsArgument(argument);
auto environment=gitEnvironment();
auto environment=gitEnvironment(options.index);
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
const GitHandle input{CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr)};
if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input");
GitHandle input,writeInput;
if(options.input.empty())
{
input.value=CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr);
if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input");
}
else if(!CreatePipe(&input.value,&writeInput.value,&inheritable,65536) ||
!SetHandleInformation(writeInput.value,HANDLE_FLAG_INHERIT,0))
gitWindowsError("Could not open Git input");
GitHandle out,childOut,error,childError;
makeGitPipe(out,childOut,inheritable);
makeGitPipe(error,childError,inheritable);
@@ -169,10 +193,20 @@ GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector
try
{
if(ResumeThread(thread.value)==DWORD(-1)) gitWindowsError("Could not resume Git");
input.close();
childOut.close();
childError.close();
const auto write=[&](std::string_view payload)
{
DWORD written{};
if(payload.size()>65536 || !WriteFile(writeInput.value,payload.data(),
static_cast<DWORD>(payload.size()),&written,nullptr) || written!=payload.size())
gitWindowsError("Could not send input to Git");
};
if(writeInput.value) write(options.input);
if(!options.afterPrepare) writeInput.close();
GitOutput result;
const auto deadline=GetTickCount64()+15000;
auto deadline=GetTickCount64()+options.timeout;
const auto read=[&](HANDLE pipe,std::string &data,size_t limit)
{
DWORD waiting{},readBytes{};
@@ -195,6 +229,14 @@ GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector
if(GetTickCount64()>=deadline) throw std::runtime_error("Git did not respond in time.");
const bool readOutput=read(out.value,result.output,maximum);
const bool readErrors=read(error.value,result.error,256*1024);
if(writeInput.value && (result.output.find("prepare: ok\n")!=std::string::npos ||
result.output.find("prepare: ok\r\n")!=std::string::npos))
{
options.afterPrepare();
write("commit\n");
writeInput.close();
deadline=GetTickCount64()+options.timeout;
}
const auto state=WaitForSingleObject(process.value,readOutput || readErrors?0:20);
if(state==WAIT_FAILED) gitWindowsError("Could not wait for Git");
if(state==WAIT_OBJECT_0 && !readOutput && !readErrors)
@@ -208,7 +250,10 @@ GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector
}
catch(...)
{
TerminateProcess(process.value,ERROR_CANCELLED);
const bool wasWaitingForInput=writeInput.value!=nullptr;
writeInput.close(); // EOF aborts a prepared Git reference transaction.
if(!wasWaitingForInput || WaitForSingleObject(process.value,2000)!=WAIT_OBJECT_0)
TerminateProcess(process.value,ERROR_CANCELLED);
throw;
}
}
@@ -221,10 +266,10 @@ void checkGit(const GitOutput &result,const char *operation,bool allowDifference
throw std::runtime_error(detail.empty()?std::string(operation):std::string(operation)+"\r\n"+detail);
}
std::string_view statusField(std::string_view &input)
std::string_view nulField(std::string_view &input)
{
const auto separator=input.find('\0');
if(separator==input.npos) throw std::runtime_error("Git returned incomplete status output.");
if(separator==input.npos) throw std::runtime_error("Git returned incomplete output.");
const auto field=input.substr(0,separator);
input.remove_prefix(separator+1);
return field;
@@ -251,12 +296,12 @@ std::vector<GitChange> parseGitStatus(std::string_view output)
std::vector<GitChange> result;
while(!output.empty())
{
const auto row=statusField(output);
const auto row=nulField(output);
if(row.size()<4 || row[2]!=' ') throw std::runtime_error("Git returned an invalid status record.");
const auto code=row.substr(0,2);
const auto path=statusPath(row.substr(3));
std::wstring origin;
if(code.find_first_of("RC")!=code.npos) origin=statusPath(statusField(output));
if(code.find_first_of("RC")!=code.npos) origin=statusPath(nulField(output));
if(code=="??") result.push_back({GitChangeKind::untracked,path,{},L"?"});
else if(code=="DD" || code=="AA" || code.find('U')!=code.npos)
result.push_back({GitChangeKind::unstaged,path,{},wide(std::string(code))});
@@ -271,6 +316,175 @@ std::vector<GitChange> parseGitStatus(std::string_view output)
});
return result;
}
std::wstring gitRevision(std::string_view value)
{
if((value.size()!=40 && value.size()!=64) || value.find_first_not_of("0123456789abcdef")!=value.npos)
throw std::runtime_error("Git returned an invalid object ID.");
return {value.begin(),value.end()};
}
void trimGitLine(std::string &line)
{
while(!line.empty() && (line.back()=='\n' || line.back()=='\r')) line.pop_back();
}
GitCheckout readCheckout(const fs::path &git,const fs::path &root,std::stop_token stop)
{
auto branch=runGit(git,root,{L"symbolic-ref",L"--quiet",L"HEAD"},64*1024,stop);
checkGit(branch,"Could not read the checked-out branch.",true);
auto head=runGit(git,root,{L"rev-parse",L"--verify",L"--quiet",L"HEAD"},64*1024,stop);
checkGit(head,"Could not read Git HEAD.",true);
trimGitLine(branch.output);
trimGitLine(head.output);
return {branch.exitCode?std::wstring{}:wide(branch.output),
head.exitCode?std::wstring{}:gitRevision(head.output)};
}
std::vector<GitChange> readStatus(const fs::path &git,const fs::path &root,std::stop_token stop)
{
const auto status=runGit(git,root,{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"},
8*1024*1024,stop);
checkGit(status,"Could not read Git worktree status.");
return parseGitStatus(status.output);
}
struct GitWorktreeFiles
{
fs::path index;
std::vector<std::pair<fs::path,const char *>> operations;
};
GitWorktreeFiles findWorktreeFiles(const GitChanges &worktree,std::stop_token stop)
{
constexpr std::pair<const wchar_t *,const char *> markers[]{
{L"MERGE_HEAD","merge"},{L"CHERRY_PICK_HEAD","cherry-pick"},{L"REVERT_HEAD","revert"},
{L"rebase-merge","rebase"},{L"rebase-apply","rebase or am"},{L"sequencer","sequencer"},
{L"BISECT_START","bisect"}};
std::vector<std::wstring> args{L"rev-parse",L"--path-format=absolute",L"--git-path",L"index"};
for(const auto &[name,operation]:markers)
{
args.push_back(L"--git-path");
args.push_back(name);
}
const auto paths=runGit(worktree.executable,worktree.root,args,256*1024,stop);
checkGit(paths,"Could not find the worktree index.");
std::string_view lines=paths.output;
const auto next=[&]
{
if(lines.empty()) throw std::runtime_error("Git returned incomplete worktree metadata.");
const auto separator=lines.find('\n');
auto line=lines.substr(0,separator);
lines.remove_prefix(separator==lines.npos?lines.size():separator+1);
if(line.ends_with('\r')) line.remove_suffix(1);
auto path=fs::path(wide(std::string(line))).make_preferred();
if(!path.is_absolute()) throw std::runtime_error("Git returned an invalid worktree path.");
return path;
};
GitWorktreeFiles result{next(),{}};
for(const auto &[name,operation]:markers) result.operations.emplace_back(next(),operation);
return result;
}
struct WorktreeIndexLock
{
GitHandle file;
explicit WorktreeIndexLock(const fs::path &index)
{
auto name=index;
name+=L".lock";
file.value=CreateFileW(name.c_str(),GENERIC_WRITE|DELETE,0,nullptr,CREATE_NEW,
FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr);
if(file.value!=INVALID_HANDLE_VALUE) return;
const auto error=GetLastError();
if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS || error==ERROR_SHARING_VIOLATION)
throw std::runtime_error("Git index is locked. Finish the other Git operation, then refresh.");
throw std::system_error(error,std::system_category(),"Could not lock the Git index");
}
WorktreeIndexLock(const WorktreeIndexLock &)=delete;
};
struct WorktreeIndexCopy
{
fs::path path;
explicit WorktreeIndexCopy(const fs::path &index)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,static_cast<int>(std::size(name))))
throw std::runtime_error("Could not name the temporary Git index.");
path=index;
path+=std::wstring(L".kswitcher-")+name;
if(CopyFileW(index.c_str(),path.c_str(),TRUE)) return;
const auto error=GetLastError();
if(error!=ERROR_FILE_NOT_FOUND)
throw std::system_error(error,std::system_category(),"Could not copy the worktree index");
}
WorktreeIndexCopy(const WorktreeIndexCopy &)=delete;
~WorktreeIndexCopy()
{
DeleteFileW(path.c_str());
const auto lock=path.native()+L".lock";
DeleteFileW(lock.c_str());
}
void publish(const fs::path &index) const
{
if(!MoveFileExW(path.c_str(),index.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
gitWindowsError("Could not replace the Git index");
}
};
void requireWritableWorktree(const GitChanges &worktree,const GitWorktreeFiles &paths,
const GitCheckout &checkout,std::stop_token stop)
{
if(!checkout.ref.starts_with(L"refs/heads/"))
throw std::runtime_error("This worktree has detached HEAD. Check out a branch before writing Git changes.");
for(const auto &[path,operation]:paths.operations)
{
if(GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES)
throw std::runtime_error(std::string("A Git ")+operation+" is in progress. Finish it before writing changes.");
const auto error=GetLastError();
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND)
throw std::system_error(error,std::system_category(),"Could not check for active Git operations");
}
const auto conflicts=runGit(worktree.executable,worktree.root,{L"ls-files",L"--unmerged",L"-z"},2*1024*1024,stop);
checkGit(conflicts,"Could not check Git index conflicts.");
if(!conflicts.output.empty()) throw std::runtime_error("The Git index contains conflicts. Resolve them before writing changes.");
}
GitCommitReview captureGitReview(const GitChanges &worktree,const GitCheckout &checkout,std::stop_token stop,
bool listPaths)
{
GitCommitReview review{worktree.root,checkout,{},{}};
std::vector<std::wstring> args{L"diff",L"--cached",L"--no-color",L"--no-ext-diff",L"--no-textconv",
L"--ita-invisible-in-index",L"-z"};
if(!checkout.revision.empty()) args.push_back(checkout.revision);
args.push_back(L"--");
auto identityArgs=args;
identityArgs.insert(identityArgs.begin()+1,{L"--raw",L"--no-renames",L"--abbrev=64"});
auto identity=runGit(worktree.executable,worktree.root,identityArgs,16*1024*1024,stop);
checkGit(identity,"Could not read the staged snapshot.");
review.stagedIdentity=std::move(identity.output);
if(!listPaths || review.stagedIdentity.empty()) return review;
args.insert(args.begin()+1,{L"--name-status",L"--find-renames"});
const auto changed=runGit(worktree.executable,worktree.root,args,8*1024*1024,stop);
checkGit(changed,"Could not list all staged paths.");
std::string_view records=changed.output;
while(!records.empty())
{
const auto flags=nulField(records);
if(flags.empty()) throw std::runtime_error("Git returned an invalid staged-path record.");
auto path=statusPath(nulField(records));
std::wstring old;
if(flags.front()=='R' || flags.front()=='C')
{
old=std::move(path);
path=statusPath(nulField(records));
}
review.staged.push_back({GitChangeKind::staged,std::move(path),std::move(old),wide(std::string(flags))});
}
return review;
}
}
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop)
@@ -279,13 +493,11 @@ GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token
result.executable=locateGit();
auto root=runGit(result.executable,directory,{L"rev-parse",L"--show-toplevel"},64*1024,stop);
checkGit(root,"This folder is not inside a Git worktree.");
while(!root.output.empty() && (root.output.back()=='\r' || root.output.back()=='\n')) root.output.pop_back();
trimGitLine(root.output);
result.root=fs::path(wide(root.output)).make_preferred();
if(!result.root.is_absolute()) throw std::runtime_error("Git returned an invalid worktree root.");
const auto status=runGit(result.executable,result.root,
{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"},8*1024*1024,stop);
checkGit(status,"Could not read Git worktree status.");
result.entries=parseGitStatus(status.output);
result.checkout=readCheckout(result.executable,result.root,stop);
result.entries=readStatus(result.executable,result.root,stop);
return result;
}
@@ -304,4 +516,225 @@ std::string readGitPatch(const std::filesystem::path &git,const std::filesystem:
checkGit(patch,"Could not read this Git diff.",untracked);
return std::move(patch.output);
}
std::vector<GitBranch> readGitBranches(const std::filesystem::path &git,const std::filesystem::path &root,
std::stop_token stop)
{
const auto refs=runGit(git,root,{L"for-each-ref",L"--sort=refname",
L"--format=%(objectname)%00%(refname)%00%(HEAD)%00%(symref)",L"refs/heads",L"refs/remotes"},
4*1024*1024,stop);
checkGit(refs,"Could not read Git branches.");
constexpr std::string_view localPrefix="refs/heads/",remotePrefix="refs/remotes/";
std::vector<GitBranch> branches;
bool foundHead=false;
for(std::string_view remaining=refs.output;!remaining.empty();)
{
const auto newline=remaining.find('\n');
auto line=remaining.substr(0,newline);
remaining.remove_prefix(newline==remaining.npos?remaining.size():newline+1);
if(line.ends_with('\r')) line.remove_suffix(1);
if(line.empty()) continue;
const auto revision=gitRevision(nulField(line));
const auto ref=nulField(line);
const bool current=nulField(line)=="*";
if(!line.empty()) continue; // Skip aliases such as origin/HEAD.
const bool remote=ref.starts_with(remotePrefix);
if(!remote && !ref.starts_with(localPrefix)) continue;
const auto branch=wide(std::string(ref.substr(remote?remotePrefix.size():localPrefix.size())));
branches.push_back({wide(std::string(ref)),(current?L"* ":remote?L"Tracking · ":L"Local · ")+branch,
revision,current});
foundHead|=current;
}
if(!foundHead)
{
auto head=runGit(git,root,{L"rev-parse",L"--verify",L"--quiet",L"HEAD"},64*1024,stop);
checkGit(head,"Could not read Git HEAD.",true);
if(!head.exitCode)
{
while(!head.output.empty() && (head.output.back()=='\n' || head.output.back()=='\r')) head.output.pop_back();
branches.insert(branches.begin(),{L"HEAD",L"* Detached HEAD",gitRevision(head.output),true});
}
}
return branches;
}
GitHistoryPage readGitHistory(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,size_t offset,std::stop_token stop)
{
constexpr size_t pageSize=50;
const auto log=runGit(git,root,{L"log",L"--no-decorate",L"--no-notes",L"--no-show-signature",
L"--encoding=UTF-8",L"--date=short",L"--format=%H%x00%h%x00%ad%x00%s",L"-z",
L"--max-count="+std::to_wstring(pageSize+1),L"--skip="+std::to_wstring(offset),revision,L"--"},
2*1024*1024,stop);
checkGit(log,"Could not read Git history.");
GitHistoryPage page;
std::string_view records=log.output;
while(!records.empty() && page.commits.size()<pageSize)
page.commits.push_back({gitRevision(nulField(records)),wide(std::string(nulField(records))),
wide(std::string(nulField(records))),wide(std::string(nulField(records)))});
page.more=!records.empty();
return page;
}
std::string readGitCommit(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,std::stop_token stop)
{
const auto metadata=runGit(git,root,{L"log",L"-1",L"--no-decorate",L"--no-notes",L"--no-show-signature",
L"--encoding=UTF-8",L"--format=%H%x00%an%x00%ae%x00%aI%x00%B",L"-z",revision,L"--"},2*1024*1024,stop);
checkGit(metadata,"Could not read the Git commit.");
std::string_view parts=metadata.output;
const auto id=nulField(parts);
const auto author=nulField(parts);
const auto email=nulField(parts);
const auto date=nulField(parts);
const auto message=nulField(parts);
std::string text="Commit ";
text.append(id).append("\nAuthor ").append(author);
if(!email.empty()) text.append(" <").append(email).push_back('>');
text.append("\nDate ").append(date).append("\n\n").append(message);
while(!text.empty() && (text.back()=='\r' || text.back()=='\n')) text.pop_back();
const auto changes=runGit(git,root,{L"show",L"--no-notes",L"--no-show-signature",L"--format=",L"--name-status",
L"-z",L"--root",L"--diff-merges=first-parent",L"--find-renames",L"--no-ext-diff",L"--no-textconv",
revision,L"--"},2*1024*1024,stop);
checkGit(changes,"Could not read changed paths.");
text+="\n\nChanged paths\n";
if(changes.output.empty()) text+="No changed paths.\n";
std::string_view records=changes.output;
while(!records.empty())
{
const auto code=nulField(records);
if(code.empty()) throw std::runtime_error("Git returned an invalid changed-path record.");
text.append(code).append(" ").append(nulField(records));
if(code.front()=='R' || code.front()=='C')
text.append(" → ").append(nulField(records));
text.push_back('\n');
}
return text;
}
void changeGitIndex(const GitChanges &worktree,const GitChange &entry,bool replaceStaged,std::stop_token stop)
{
const auto paths=findWorktreeFiles(worktree,stop);
const WorktreeIndexLock lock(paths.index);
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
requireWritableWorktree(worktree,paths,checkout,stop);
if(checkout!=worktree.checkout)
throw std::runtime_error("The checked-out branch or commit changed. Review the refreshed Git changes.");
const auto entries=readStatus(worktree.executable,worktree.root,stop);
if(std::find(entries.begin(),entries.end(),entry)==entries.end())
throw std::runtime_error("The selected change is no longer current. Review the refreshed Git changes.");
const bool stage=entry.kind!=GitChangeKind::staged;
const bool rename=entry.flags.starts_with(L"R") || entry.flags.starts_with(L"C");
const auto overlaps=[&](const GitChange &other)
{
return other.kind==GitChangeKind::staged && (other.path==entry.path || other.oldPath==entry.path ||
(rename && !entry.oldPath.empty() && (other.path==entry.oldPath || other.oldPath==entry.oldPath)));
};
if(stage && !replaceStaged && std::any_of(entries.begin(),entries.end(),overlaps))
throw std::runtime_error("The selected path already has staged changes. Review and confirm the replacement.");
if(stage)
{
const auto attributes=GetFileAttributesW((worktree.root/fs::path(entry.path)).c_str());
if(entry.path.ends_with(L'/') || (attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)))
{
const auto indexed=runGit(worktree.executable,worktree.root,{L"ls-files",L"--stage",L"--",entry.path},
256*1024,stop);
checkGit(indexed,"Could not identify the selected directory.");
if(!indexed.output.starts_with("160000 "))
throw std::runtime_error("This entry is a directory. Stage individual files or an existing submodule.");
}
}
const WorktreeIndexCopy pending(paths.index);
std::vector<std::wstring> args;
if(stage) args={L"add",L"-A",L"--"};
else if(checkout.revision.empty()) args={L"rm",L"--cached",L"-f",L"--ignore-unmatch",L"--"};
else args={L"restore",L"--staged",L"--source="+checkout.revision,L"--"};
if(rename && !entry.oldPath.empty()) args.push_back(entry.oldPath);
args.push_back(entry.path);
const auto result=runGit(worktree.executable,worktree.root,args,1024*1024,stop,{.index=pending.path});
checkGit(result,stage?"Could not stage the selected path.":"Could not unstage the selected path.");
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout || stop.stop_requested())
throw std::runtime_error("The checkout changed while Git was working. Review the refreshed Git changes.");
requireWritableWorktree(worktree,paths,checkout,stop);
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
pending.publish(paths.index);
}
GitCommitReview reviewGitCommit(const GitChanges &worktree,std::stop_token stop)
{
const auto paths=findWorktreeFiles(worktree,stop);
const WorktreeIndexLock lock(paths.index);
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
requireWritableWorktree(worktree,paths,checkout,stop);
auto review=captureGitReview(worktree,checkout,stop,true);
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout)
throw std::runtime_error("The checkout changed while reading the staged paths. Open a new review.");
if(review.staged.empty()) throw std::runtime_error("Stage at least one change before committing.");
return review;
}
std::wstring createGitCommit(const GitChanges &worktree,const GitCommitReview &review,
const std::wstring &message,std::stop_token stop)
{
if(message.find_first_not_of(L" \t\r\n")==message.npos)
throw std::runtime_error("Enter a commit message.");
if(worktree.root!=review.root || review.stagedIdentity.empty())
throw std::runtime_error("The reviewed worktree changed. Open a new review.");
const auto paths=findWorktreeFiles(worktree,stop);
const WorktreeIndexLock lock(paths.index);
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
requireWritableWorktree(worktree,paths,checkout,stop);
if(checkout!=review.checkout || captureGitReview(worktree,checkout,stop,false).stagedIdentity!=review.stagedIdentity)
throw std::runtime_error("The checkout or staged changes changed after review. Review them again. The message was kept.");
const WorktreeIndexCopy pending(paths.index);
auto tree=runGit(worktree.executable,worktree.root,{L"write-tree"},64*1024,stop,{.index=pending.path});
checkGit(tree,"Could not write the reviewed Git tree.");
trimGitLine(tree.output);
const auto treeId=gitRevision(tree.output);
auto signing=runGit(worktree.executable,worktree.root,{L"config",L"--type=bool",L"--get",L"commit.gpgSign"},64*1024,stop);
checkGit(signing,"Could not read Git signing settings.",true);
trimGitLine(signing.output);
std::vector<std::wstring> args{L"commit-tree",treeId,L"-F",L"-"};
if(!checkout.revision.empty()) args.insert(args.end(),{L"-p",checkout.revision});
if(signing.output=="true") args.push_back(L"-S");
auto contents=utf8(message);
for(size_t pos=0;(pos=contents.find('\r',pos))!=contents.npos;)
{
if(pos+1<contents.size() && contents[pos+1]=='\n') contents.erase(pos,1);
else contents[pos++]='\n';
}
auto created=runGit(worktree.executable,worktree.root,args,64*1024,stop,{.input=contents,.timeout=120000});
checkGit(created,"Could not create the commit. Check your Git author identity and signing settings.");
trimGitLine(created.output);
const auto commit=gitRevision(created.output);
const auto expected=checkout.revision.empty()?std::string(commit.size(),'0'):utf8(checkout.revision);
const std::string transaction="start\nupdate HEAD "+created.output+" "+expected+"\nprepare\n";
try
{
const auto update=runGit(worktree.executable,worktree.root,
{L"-c",L"core.hooksPath=NUL",L"update-ref",L"-m",L"KSwitcher Files: local commit",L"--stdin"},
64*1024,stop,{.input=transaction,.afterPrepare=[&] {
// Git holds HEAD and its referent after prepare, while the index remains locked by Files.
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout)
throw std::runtime_error("The checkout changed after review. Review it again. The message was kept.");
requireWritableWorktree(worktree,paths,checkout,stop);
}});
checkGit(update,"Could not update the checked-out branch. Refresh and review the staged changes.");
if(update.output.find("commit: ok")==std::string::npos)
throw std::runtime_error("Git did not confirm the branch update.");
}
catch(...)
{
try
{
if(readCheckout(worktree.executable,worktree.root,{})==GitCheckout{checkout.ref,commit}) return commit;
}
catch(const std::exception &) {}
throw;
}
return commit;
}
}
+42
View File
@@ -17,13 +17,55 @@ struct GitChange
bool operator==(const GitChange &) const = default;
};
struct GitCheckout
{
std::wstring ref, revision;
bool operator==(const GitCheckout &) const = default;
};
struct GitChanges
{
std::filesystem::path executable, root;
std::vector<GitChange> entries;
GitCheckout checkout;
};
struct GitBranch
{
std::wstring ref, label, revision;
bool current{};
};
struct GitCommit
{
std::wstring revision, abbreviated, date, subject;
};
struct GitHistoryPage
{
std::vector<GitCommit> commits;
bool more{};
};
struct GitCommitReview
{
std::filesystem::path root;
GitCheckout checkout;
std::vector<GitChange> staged;
std::string stagedIdentity;
};
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop);
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
const GitChange &change,std::stop_token stop);
std::vector<GitBranch> readGitBranches(const std::filesystem::path &git,const std::filesystem::path &root,
std::stop_token stop);
GitHistoryPage readGitHistory(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,size_t offset,std::stop_token stop);
std::string readGitCommit(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,std::stop_token stop);
void changeGitIndex(const GitChanges &worktree,const GitChange &entry,bool replaceStaged,std::stop_token stop);
GitCommitReview reviewGitCommit(const GitChanges &worktree,std::stop_token stop);
std::wstring createGitCommit(const GitChanges &worktree,const GitCommitReview &review,
const std::wstring &message,std::stop_token stop);
}
+547 -55
View File
@@ -1,24 +1,55 @@
using ks::files::GitChange;
using ks::files::GitChangeKind;
using ks::files::GitChanges;
using ks::files::GitBranch;
using ks::files::GitCommit;
using ks::files::GitCommitReview;
using ks::files::GitHistoryPage;
struct GitPreview
{
std::wstring heading;
std::variant<GitChange,std::wstring> item;
};
struct GitHistoryUpdate
{
std::optional<std::vector<GitBranch>> branches;
GitHistoryPage page;
size_t branch=0;
};
struct GitChangesView
{
HWND host{},heading{},filterLabel{},filter{},list{},status{},hints{},preview{};
HWND host{},heading{},switchView{},filterLabel{},filter{},branchPicker{},list{},status{},hints{},preview{},moreButton{};
HWND indexButton{},commitButton{};
fs::path folder;
GitChanges data;
std::future<GitChanges> refresh;
std::future<std::string> diff;
std::stop_source stopRefresh,stopDiff;
ULONGLONG diffAt{};
std::optional<GitChange> requested;
std::future<std::string> previewTask;
std::stop_source stopRefresh,stopPreview;
ULONGLONG previewAt{};
std::optional<GitPreview> requested;
std::string failure;
bool historyMode{},moreHistory{};
std::vector<GitBranch> branches;
std::vector<GitCommit> commits;
size_t branchIndex{};
std::future<GitHistoryUpdate> historyTask;
std::stop_source stopHistory;
std::string historyFailure;
std::future<GitCommitReview> commitReview;
std::future<std::wstring> mutation;
std::stop_source stopMutation;
std::wstring commitDraft,operation,writeStatus;
bool promptingWrite{};
};
std::unique_ptr<GitChangesView> gitChangesView;
constexpr wchar_t gitChangesClass[]=L"KSwitcher.Files.GitChanges";
constexpr UINT_PTR gitChangesTimer=1;
constexpr int gitHeading=570,gitFilter=571,gitList=572,gitStatus=573;
constexpr int gitHeading=570,gitFilter=571,gitList=572,gitStatus=573,gitSwitch=574,gitBranch=575,gitMore=576;
constexpr int gitIndexAction=577,gitCommitAction=578;
const wchar_t *gitChangeKindName(GitChangeKind kind)
{
@@ -39,34 +70,98 @@ const GitChange *selectedGitChange(const GitChangesView &view)
return index>=0 && size_t(index)<view.data.entries.size()?&view.data.entries[index]:nullptr;
}
const GitCommit *selectedGitCommit(const GitChangesView &view)
{
const auto row=SendMessageW(view.list,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendMessageW(view.list,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<view.commits.size()?&view.commits[index]:nullptr;
}
std::wstring gitChangePathLabel(const GitChange &entry)
{
return entry.oldPath.empty()?entry.path:entry.path+L" ← "+entry.oldPath;
}
std::wstring gitCheckoutLabel(const ks::files::GitCheckout &checkout)
{
constexpr std::wstring_view prefix=L"refs/heads/";
if(!checkout.ref.starts_with(prefix)) return L"Detached HEAD";
auto label=checkout.ref.substr(prefix.size());
if(checkout.revision.empty()) label+=L" (first commit)";
return label;
}
bool gitActionPending(const GitChangesView &view)
{
return view.commitReview.valid() || view.mutation.valid() || view.promptingWrite;
}
void updateGitActionButtons(GitChangesView &view)
{
const bool ready=!view.historyMode && !view.data.root.empty() && !view.refresh.valid() && !gitActionPending(view);
const auto *entry=view.historyMode?nullptr:selectedGitChange(view);
SetWindowTextW(view.indexButton,entry && entry->kind==GitChangeKind::staged?L"Unstage":L"Stage");
EnableWindow(view.indexButton,ready && entry);
EnableWindow(view.commitButton,ready);
EnableWindow(view.switchView,!view.data.root.empty() && !view.refresh.valid() && !gitActionPending(view));
}
void updateGitChangesStatus(GitChangesView &view,LRESULT shown=-1)
{
if(gitActionPending(view)) {SetWindowTextW(view.status,view.operation.c_str());return;}
if(view.refresh.valid()) {SetWindowTextW(view.status,L"Reading Git changes…");return;}
if(!view.failure.empty()) {SetWindowTextW(view.status,L"Could not read Git changes.");return;}
if(shown<0) shown=SendMessageW(view.list,LB_GETCOUNT,0,0);
const auto count=view.data.entries.size();
const std::wstring summary=!count?L"No Git changes.":shown<=0?L"No paths match the filter.":
std::to_wstring(shown)+(static_cast<size_t>(shown)==count?L"":L" of "+std::to_wstring(count))+L" changes";
SetWindowTextW(view.status,(view.writeStatus.empty()?summary:view.writeStatus+L" · "+summary).c_str());
}
std::wstring gitDiffHeading(const GitChange &entry)
{
return std::wstring(gitChangeKindName(entry.kind))+L" diff · "+entry.path;
}
void queueGitDiff(GitChangesView &view)
void queueGitPreview(GitChangesView &view)
{
view.stopDiff.request_stop();
view.diff={};
view.diffAt=0;
updateGitActionButtons(view);
view.stopPreview.request_stop();
view.previewTask={};
view.previewAt=0;
view.requested.reset();
if(view.historyMode)
{
if(const auto *commit=selectedGitCommit(view))
{
view.requested=GitPreview{L"Commit · "+commit->abbreviated,commit->revision};
view.previewAt=GetTickCount64()+100;
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
}
else if(!view.historyFailure.empty())
ks::files::previewQuickViewText(view.preview,L"Git history failed",view.historyFailure);
else ks::files::previewQuickViewText(view.preview,
view.historyTask.valid()?L"Commit · Reading history…":L"Commit · Select a commit",{});
return;
}
if(view.refresh.valid())
{
ks::files::previewQuickViewDiff(view.preview,L"Diff · Reading Git changes…",{});
ks::files::previewQuickViewText(view.preview,L"Diff · Reading Git changes…",{});
return;
}
if(!view.failure.empty())
{
ks::files::previewQuickViewDiff(view.preview,L"Git status failed",view.failure);
ks::files::previewQuickViewText(view.preview,L"Git status failed",view.failure);
return;
}
if(const auto *entry=selectedGitChange(view))
{
view.requested=*entry;
view.diffAt=GetTickCount64()+100;
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*entry)+L" · Loading…",{});
view.requested=GitPreview{gitDiffHeading(*entry),*entry};
view.previewAt=GetTickCount64()+100;
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
}
else ks::files::previewQuickViewDiff(view.preview,L"Diff · Select a change",{});
else ks::files::previewQuickViewText(view.preview,L"Diff · Select a change",{});
}
void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
@@ -90,7 +185,7 @@ void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
state.resize(10,L' ');
state+=entry.flags;
state.resize(13,L' ');
const auto label=state+(entry.oldPath.empty()?entry.path:entry.path+L" ← "+entry.oldPath);
const auto label=state+gitChangePathLabel(entry);
const auto row=SendMessageW(view.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row<0) continue;
++count;
@@ -101,18 +196,13 @@ void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(view.list,nullptr,TRUE);
InvalidateRect(view.host,nullptr,FALSE);
const auto total=view.data.entries.size();
const auto status=view.refresh.valid()?std::wstring(L"Reading Git changes…"):
!view.failure.empty()?L"Could not read Git changes.":
!total?L"No Git changes.":!count?L"No paths match the filter.":
std::to_wstring(count)+(query.empty()?L"":L" of "+std::to_wstring(total))+L" changes";
SetWindowTextW(view.status,status.c_str());
queueGitDiff(view);
updateGitChangesStatus(view,count);
queueGitPreview(view);
}
void refreshGitChanges(GitChangesView &view)
{
if(view.refresh.valid()) return;
if(view.refresh.valid() || gitActionPending(view)) return;
view.failure.clear();
view.stopRefresh=std::stop_source{};
try
@@ -123,8 +213,8 @@ void refreshGitChanges(GitChangesView &view)
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.refresh=std::move(pending);
SetWindowTextW(view.status,L"Reading Git changes…");
queueGitDiff(view);
updateGitChangesStatus(view);
queueGitPreview(view);
}
catch(const std::exception &)
{
@@ -133,9 +223,313 @@ void refreshGitChanges(GitChangesView &view)
}
}
struct GitCommitPrompt
{
const GitCommitReview &review;
std::wstring message;
};
INT_PTR CALLBACK gitCommitDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int branch=594,summary=595,staged=596,body=598,feedback=599,footer=600;
if(message==WM_INITDIALOG)
{
auto &prompt=*reinterpret_cast<GitCommitPrompt *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,branch);
SetDlgItemTextW(dialog,branch,(L"Branch "+gitCheckoutLabel(prompt.review.checkout)).c_str());
SetDlgItemTextW(dialog,summary,(std::to_wstring(prompt.review.staged.size())+L" staged changes · all paths").c_str());
const auto list=GetDlgItem(dialog,staged);
for(const auto &entry:prompt.review.staged)
{
const auto label=entry.flags+L" "+gitChangePathLabel(entry);
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
const auto bounds=dialogControlBounds(dialog,staged);
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
installScrollBar(list,dialog);
SendDlgItemMessageW(dialog,body,EM_SETLIMITTEXT,16000,0);
SetDlgItemTextW(dialog,body,prompt.message.c_str());
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(dialog,body));
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDCANCEL || LOWORD(wp)==IDOK)))
{
auto &prompt=*reinterpret_cast<GitCommitPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
prompt.message=dialogFieldText(GetDlgItem(dialog,body));
const bool submit=message==WM_COMMAND && LOWORD(wp)==IDOK;
if(submit && prompt.message.find_first_not_of(L" \t\r\n")==prompt.message.npos)
{
SetDlgItemTextW(dialog,feedback,L"Enter a commit message.");
ShowWindow(GetDlgItem(dialog,feedback),SW_SHOWNA);
SetFocus(GetDlgItem(dialog,body));
return TRUE;
}
FilesModalDialog::finish(dialog,submit?IDOK:IDCANCEL);
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==body && HIWORD(wp)==EN_CHANGE)
{
ShowWindow(GetDlgItem(dialog,feedback),SW_HIDE);
SetDlgItemTextW(dialog,feedback,L"");
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Commit staged changes ",false,{footer},false,GetDlgItem(dialog,staged));
}
GitChanges gitWorktreeTarget(const GitChangesView &view)
{
return {view.data.executable,view.data.root,{},view.data.checkout};
}
bool gitActionAvailable(const GitChangesView &view)
{
return !view.historyMode && !view.refresh.valid() && !gitActionPending(view) && !view.data.root.empty();
}
void showGitWriteError(GitChangesView &view,const std::exception &error)
{
std::wstring detail;
if(const auto *system=dynamic_cast<const std::system_error *>(&error)) detail=fileError(*system);
else
{
try {detail=ks::wide(error.what());}
catch(const std::exception &) {detail=L"Git returned an error in an unsupported encoding.";}
}
view.promptingWrite=true;
updateGitActionButtons(view);
showFilesNotice(GetParent(view.host),detail.c_str(),L"Git operation failed",{.tone=FilesNoticeTone::warning});
view.promptingWrite=false;
view.writeStatus=L"Git operation failed";
refreshGitChanges(view);
}
void runGitMutation(GitChangesView &view,std::wstring operation,
std::function<std::wstring(std::stop_token)> action)
{
view.stopMutation=std::stop_source{};
view.operation=std::move(operation);
try
{
std::packaged_task<std::wstring()> task([action=std::move(action),stop=view.stopMutation.get_token()] {
return action(stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.mutation=std::move(pending);
updateGitActionButtons(view);
updateGitChangesStatus(view);
}
catch(const std::exception &error) {showGitWriteError(view,error);}
}
void changeSelectedGitIndex(GitChangesView &view)
{
if(!gitActionAvailable(view)) return;
const auto *selected=selectedGitChange(view);
if(!selected) return;
const auto entry=*selected;
const bool stage=entry.kind!=GitChangeKind::staged;
const bool replace=stage && std::any_of(view.data.entries.begin(),view.data.entries.end(),[&](const auto &other) {
return other.kind==GitChangeKind::staged && (other.path==entry.path || other.oldPath==entry.path ||
(!entry.oldPath.empty() && (other.path==entry.oldPath || other.oldPath==entry.oldPath)));
});
if(replace)
{
view.promptingWrite=true;
updateGitActionButtons(view);
const auto message=L"Replace the staged version of "+entry.path+L" with the current working version?";
const auto answer=showFilesNotice(GetParent(view.host),message.c_str(),L"Replace staged changes",
{.confirm=true,.tone=FilesNoticeTone::warning});
view.promptingWrite=false;
updateGitActionButtons(view);
if(answer!=IDYES) return;
}
runGitMutation(view,stage?L"Staging the selected path…":L"Unstaging the selected path…",
[worktree=gitWorktreeTarget(view),entry,replace,stage](std::stop_token stop) {
ks::files::changeGitIndex(worktree,entry,replace,stop);
return stage?std::wstring(L"Path staged"):std::wstring(L"Path unstaged");
});
}
void openGitCommitReview(GitChangesView &view)
{
if(!gitActionAvailable(view)) return;
view.stopMutation=std::stop_source{};
view.operation=L"Reading all staged changes…";
try
{
std::packaged_task<GitCommitReview()> task([worktree=gitWorktreeTarget(view),stop=view.stopMutation.get_token()] {
return ks::files::reviewGitCommit(worktree,stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.commitReview=std::move(pending);
updateGitActionButtons(view);
updateGitChangesStatus(view);
}
catch(const std::exception &error) {showGitWriteError(view,error);}
}
void finishGitCommitReview(GitChangesView &view)
{
try
{
auto review=view.commitReview.get();
GitCommitPrompt prompt{review,view.commitDraft};
view.promptingWrite=true;
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(126),
GetParent(view.host),gitCommitDialog,reinterpret_cast<LPARAM>(&prompt));
view.promptingWrite=false;
view.commitDraft=std::move(prompt.message);
if(answer==IDOK)
runGitMutation(view,L"Creating the reviewed local commit…",
[worktree=gitWorktreeTarget(view),review=std::move(review),message=view.commitDraft](std::stop_token stop) {
return L"Commit "+ks::files::createGitCommit(worktree,review,message,stop).substr(0,12);
});
else
{
updateGitActionButtons(view);
updateGitChangesStatus(view);
}
}
catch(const std::exception &error)
{
view.promptingWrite=false;
showGitWriteError(view,error);
}
}
void finishGitMutation(GitChangesView &view)
{
try
{
view.writeStatus=view.mutation.get();
if(view.writeStatus.starts_with(L"Commit ")) view.commitDraft.clear();
refreshGitChanges(view);
}
catch(const std::exception &error) {showGitWriteError(view,error);}
}
void updateGitHistoryStatus(GitChangesView &view)
{
const auto status=view.historyTask.valid()?std::wstring(L"Reading Git history…"):
!view.historyFailure.empty()?L"Could not read Git history.":
view.commits.empty()?L"No commits yet.":std::to_wstring(view.commits.size())+L" commits";
SetWindowTextW(view.status,status.c_str());
EnableWindow(view.moreButton,view.moreHistory && !view.historyTask.valid());
}
void renderGitHistory(GitChangesView &view,std::wstring_view preserve={},LRESULT top=0)
{
SendMessageW(view.list,WM_SETREDRAW,FALSE,0);
SendMessageW(view.list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(size_t i=0;i<view.commits.size();++i)
{
const auto &commit=view.commits[i];
const auto label=commit.date+L" "+commit.abbreviated+L" "+commit.subject;
const auto row=SendMessageW(view.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row<0) continue;
SendMessageW(view.list,LB_SETITEMDATA,row,i);
if(preserve==commit.revision) selected=row;
}
if(!view.commits.empty())
{
SendMessageW(view.list,LB_SETCURSEL,selected,0);
if(top>0) SendMessageW(view.list,LB_SETTOPINDEX,top,0);
}
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(view.list,nullptr,TRUE);
InvalidateRect(view.host,nullptr,FALSE);
updateGitHistoryStatus(view);
queueGitPreview(view);
}
void loadGitHistory(GitChangesView &view,bool refreshBranches,bool append=false)
{
if(append && (view.historyTask.valid() || !view.moreHistory)) return;
view.stopHistory.request_stop();
view.historyTask={};
view.stopHistory=std::stop_source{};
view.historyFailure.clear();
const auto offset=append?view.commits.size():0;
const auto haveBranch=view.branchIndex<view.branches.size();
const auto branch=haveBranch?view.branches[view.branchIndex]:GitBranch{};
if(!append)
{
view.commits.clear();
view.moreHistory=false;
}
try
{
std::packaged_task<GitHistoryUpdate()> task([git=view.data.executable,root=view.data.root,
refreshBranches,offset,branch,index=view.branchIndex,stop=view.stopHistory.get_token()]
{
GitHistoryUpdate result;
result.branch=index;
auto revision=branch.revision;
if(refreshBranches)
{
result.branches=ks::files::readGitBranches(git,root,stop);
const auto &branches=*result.branches;
if(branches.empty()) return result;
auto chosen=std::find_if(branches.begin(),branches.end(),[&](const auto &entry){return entry.ref==branch.ref;});
if(chosen==branches.end())
chosen=std::find_if(branches.begin(),branches.end(),[](const auto &entry){return entry.current;});
if(chosen==branches.end()) chosen=branches.begin();
result.branch=static_cast<size_t>(chosen-branches.begin());
revision=chosen->revision;
}
if(!revision.empty()) result.page=ks::files::readGitHistory(git,root,revision,offset,stop);
return result;
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.historyTask=std::move(pending);
}
catch(const std::exception &error) {view.historyFailure=error.what();}
if(!append) renderGitHistory(view);
else updateGitHistoryStatus(view);
}
void finishGitHistory(GitChangesView &view)
{
const auto *entry=selectedGitCommit(view);
const auto selected=entry?entry->revision:std::wstring{};
const auto top=SendMessageW(view.list,LB_GETTOPINDEX,0,0);
try
{
auto result=view.historyTask.get();
view.branchIndex=result.branch;
if(result.branches)
{
view.branches=std::move(*result.branches);
SendMessageW(view.branchPicker,CB_RESETCONTENT,0,0);
for(const auto &branch:view.branches)
SendMessageW(view.branchPicker,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(branch.label.c_str()));
if(!view.branches.empty()) SendMessageW(view.branchPicker,CB_SETCURSEL,view.branchIndex,0);
EnableWindow(view.branchPicker,!view.branches.empty());
}
view.commits.insert(view.commits.end(),std::make_move_iterator(result.page.commits.begin()),
std::make_move_iterator(result.page.commits.end()));
view.moreHistory=result.page.more;
}
catch(const std::exception &error) {view.historyFailure=error.what();}
renderGitHistory(view,selected,top);
}
void pollGitChanges(GitChangesView &view)
{
using namespace std::chrono_literals;
if(view.commitReview.valid() && view.commitReview.wait_for(0ms)==std::future_status::ready)
finishGitCommitReview(view);
if(view.mutation.valid() && view.mutation.wait_for(0ms)==std::future_status::ready)
finishGitMutation(view);
if(view.refresh.valid() && view.refresh.wait_for(0ms)==std::future_status::ready)
{
const auto *entry=selectedGitChange(view);
@@ -153,36 +547,41 @@ void pollGitChanges(GitChangesView &view)
renderGitChanges(view);
}
}
if(view.diffAt && GetTickCount64()>=view.diffAt)
if(view.historyTask.valid() && view.historyTask.wait_for(0ms)==std::future_status::ready)
finishGitHistory(view);
if(view.previewAt && GetTickCount64()>=view.previewAt)
{
view.diffAt=0;
view.stopDiff=std::stop_source{};
view.previewAt=0;
view.stopPreview=std::stop_source{};
try
{
std::packaged_task<std::string()> task([git=view.data.executable,root=view.data.root,
entry=*view.requested,stop=view.stopDiff.get_token()] {
return ks::files::readGitPatch(git,root,entry,stop);
item=view.requested->item,stop=view.stopPreview.get_token()] {
if(const auto *change=std::get_if<GitChange>(&item))
return ks::files::readGitPatch(git,root,*change,stop);
return ks::files::readGitCommit(git,root,std::get<std::wstring>(item),stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.diff=std::move(pending);
view.previewTask=std::move(pending);
}
catch(const std::exception &)
{
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),"Could not start Git diff.");
ks::files::previewQuickViewText(view.preview,view.requested->heading,"Could not start the Git preview.");
}
}
if(view.diff.valid() && view.diff.wait_for(0ms)==std::future_status::ready)
if(view.previewTask.valid() && view.previewTask.wait_for(0ms)==std::future_status::ready)
{
try
{
const auto patch=view.diff.get();
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),
patch.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(patch));
const auto contents=view.previewTask.get();
ks::files::previewQuickViewText(view.preview,view.requested->heading,
contents.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(contents),
std::holds_alternative<GitChange>(view.requested->item));
}
catch(const std::exception &error)
{
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),error.what());
ks::files::previewQuickViewText(view.preview,view.requested->heading,error.what());
}
}
}
@@ -190,7 +589,7 @@ void pollGitChanges(GitChangesView &view)
void openGitWorkingFile(GitChangesView &view,bool edit)
{
const auto *entry=selectedGitChange(view);
if(!entry || view.refresh.valid() || !view.failure.empty()) return;
if(view.historyMode || !entry || view.refresh.valid() || !view.failure.empty() || gitActionPending(view)) return;
auto relative=fs::path(entry->path);
for(const auto &component:relative)
if(!validFileName(component.native()))
@@ -219,22 +618,58 @@ void layoutGitChildren(GitChangesView &view)
{
SetWindowPos(control,nullptr,x,y,std::max(0,width),std::max(0,height),SWP_NOZORDER|SWP_NOACTIVATE);
};
const int inset=6, top=4, filterLabel=8*cellWidth;
const int inset=6,top=4,filterLabel=8*cellWidth,buttonWidth=12*cellWidth;
const int filterTop=top+textHeight+6, listTop=filterTop+textHeight+6;
const int bottom=std::max(listTop,static_cast<int>(bounds.bottom)-textHeight-5);
const int leftWidth=std::max(0,middle-2*inset);
place(view.heading,inset,top,leftWidth,textHeight);
place(view.heading,inset,top,leftWidth-buttonWidth-4,textHeight);
place(view.switchView,inset+leftWidth-buttonWidth,top,buttonWidth,textHeight);
place(view.filterLabel,inset,filterTop,filterLabel,textHeight);
place(view.filter,inset+filterLabel,filterTop,leftWidth-filterLabel,textHeight);
place(view.branchPicker,inset+filterLabel,filterTop,leftWidth-filterLabel,11*textHeight);
place(view.list,inset,listTop,leftWidth-scrollBarWidth(view.list),bottom-listTop);
place(view.status,inset,bottom+3,leftWidth,textHeight);
place(view.status,inset,bottom+3,leftWidth-(view.historyMode?1:2)*(buttonWidth+4),textHeight);
place(view.moreButton,inset+leftWidth-buttonWidth,bottom+3,buttonWidth,textHeight);
place(view.indexButton,inset+leftWidth-2*buttonWidth-4,bottom+3,buttonWidth,textHeight);
place(view.commitButton,inset+leftWidth-buttonWidth,bottom+3,buttonWidth,textHeight);
place(view.preview,middle+inset,top,bounds.right-middle-2*inset,bottom-top);
place(view.hints,middle+inset,bottom+3,bounds.right-middle-2*inset,textHeight);
for(const auto control:{view.heading,view.filterLabel,view.filter,view.list,view.status,view.hints})
for(const auto control:{view.heading,view.switchView,view.filterLabel,view.filter,view.branchPicker,
view.list,view.status,view.hints,view.moreButton,view.indexButton,view.commitButton})
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendMessageW(view.list,LB_SETITEMHEIGHT,0,textHeight);
}
void switchGitView(GitChangesView &view)
{
if(view.data.root.empty() || view.refresh.valid() || gitActionPending(view)) return;
view.historyMode=!view.historyMode;
const auto title=view.historyMode?L"Git History · ":L"Git Changes · ";
SetWindowTextW(view.heading,(title+view.data.root.native()).c_str());
SetWindowTextW(view.switchView,view.historyMode?L"Changes":L"History");
SetWindowTextW(view.filterLabel,view.historyMode?L"Branch":L"Filter");
SetWindowTextW(view.hints,view.historyMode?L"F6 Changes F7 More Ctrl+R Refresh Esc Back":
L"F3 View F4 Edit F6 History Ctrl+R Refresh Esc Back");
ShowWindow(view.filter,view.historyMode?SW_HIDE:SW_SHOWNA);
ShowWindow(view.branchPicker,view.historyMode?SW_SHOWNA:SW_HIDE);
ShowWindow(view.moreButton,view.historyMode?SW_SHOWNA:SW_HIDE);
ShowWindow(view.indexButton,view.historyMode?SW_HIDE:SW_SHOWNA);
ShowWindow(view.commitButton,view.historyMode?SW_HIDE:SW_SHOWNA);
layoutGitChildren(view);
if(view.historyMode)
{
EnableWindow(view.branchPicker,FALSE);
loadGitHistory(view,true);
}
else
{
view.stopHistory.request_stop();
view.historyTask={};
renderGitChanges(view);
}
SetFocus(view.list);
}
LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_NCCREATE)
@@ -255,17 +690,29 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l
reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
};
view->heading=make(L"STATIC",L"Git Changes",SS_PATHELLIPSIS|SS_NOPREFIX,gitHeading);
view->switchView=make(L"BUTTON",L"History",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitSwitch);
view->filterLabel=make(L"STATIC",L"Filter",SS_NOPREFIX);
view->filter=make(farEditClass,L"",ES_MULTILINE|ES_AUTOHSCROLL|WS_TABSTOP,gitFilter);
view->branchPicker=make(L"COMBOBOX",L"",CBS_DROPDOWNLIST|CBS_OWNERDRAWFIXED|CBS_HASSTRINGS|WS_TABSTOP|WS_VSCROLL,
gitBranch);
view->list=make(L"LISTBOX",L"",LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT|LBS_NOTIFY|WS_TABSTOP,gitList);
view->status=make(L"STATIC",L"",SS_ENDELLIPSIS|SS_NOPREFIX,gitStatus);
view->hints=make(L"STATIC",L"F3 View F4 Edit Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX);
view->hints=make(L"STATIC",L"F3 View F4 Edit F6 History Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX);
view->moreButton=make(L"BUTTON",L"More",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitMore);
view->indexButton=make(L"BUTTON",L"Stage",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitIndexAction);
view->commitButton=make(L"BUTTON",L"Commit",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitCommitAction);
try {view->preview=ks::files::createQuickView(window,textWindowDialogs());}
catch(const std::exception &) {}
if(!view->heading || !view->filterLabel || !view->filter || !view->list || !view->status ||
!view->hints || !view->preview || !SetTimer(window,gitChangesTimer,35,nullptr)) return -1;
if(!view->heading || !view->switchView || !view->filterLabel || !view->filter || !view->branchPicker ||
!view->list || !view->status || !view->hints || !view->moreButton || !view->indexButton ||
!view->commitButton || !view->preview ||
!SetTimer(window,gitChangesTimer,35,nullptr)) return -1;
prepareDialogEdit(view->filter);
SendMessageW(view->filter,EM_SETLIMITTEXT,1024,0);
ShowWindow(view->branchPicker,SW_HIDE);
ShowWindow(view->moreButton,SW_HIDE);
layoutGitChildren(*view);
installFarCombo(view->branchPicker,view->filter);
installScrollBar(view->list,window);
return 0;
}
@@ -276,13 +723,28 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l
if(wp==gitChangesTimer) pollGitChanges(*view);
return 0;
case WM_COMMAND:
if(view->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE)
if(!view->historyMode && view->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE)
{
const auto *entry=selectedGitChange(*view);
renderGitChanges(*view,entry?std::optional(*entry):std::nullopt);
}
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitDiff(*view);
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitPreview(*view);
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_DBLCLK) openGitWorkingFile(*view,false);
else if(LOWORD(wp)==gitSwitch && HIWORD(wp)==BN_CLICKED) switchGitView(*view);
else if(view->historyMode && LOWORD(wp)==gitMore && HIWORD(wp)==BN_CLICKED) loadGitHistory(*view,false,true);
else if(LOWORD(wp)==gitIndexAction && HIWORD(wp)==BN_CLICKED) changeSelectedGitIndex(*view);
else if(LOWORD(wp)==gitCommitAction && HIWORD(wp)==BN_CLICKED) openGitCommitReview(*view);
else if(view->historyMode && LOWORD(wp)==gitBranch &&
(HIWORD(wp)==CBN_SELENDOK || (HIWORD(wp)==CBN_SELCHANGE &&
!SendMessageW(view->branchPicker,CB_GETDROPPEDSTATE,0,0))))
{
const auto index=SendMessageW(view->branchPicker,CB_GETCURSEL,0,0);
if(index>=0 && size_t(index)<view->branches.size() && size_t(index)!=view->branchIndex)
{
view->branchIndex=static_cast<size_t>(index);
loadGitHistory(*view,false);
}
}
return 0;
case WM_MEASUREITEM:
reinterpret_cast<MEASUREITEMSTRUCT *>(lp)->itemHeight=textHeight;
@@ -290,6 +752,8 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l
case WM_DRAWITEM:
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
if(item.CtlID==gitBranch) {drawFarComboRow(item);return TRUE;}
if(item.CtlType==ODT_BUTTON) {paintDialogButton(item,colors[Dialog],colors[Text]);return TRUE;}
if(item.itemID==static_cast<UINT>(-1)) return TRUE;
const auto count=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
if(count<0) return TRUE;
@@ -305,7 +769,8 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l
case WM_CTLCOLORLISTBOX:
{
const auto dc=reinterpret_cast<HDC>(wp);
const bool input=message==WM_CTLCOLOREDIT;
const bool input=message==WM_CTLCOLOREDIT ||
(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=view->list);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[input?Dialog:PanelBlue]);
return reinterpret_cast<LRESULT>(input?teal:blue);
@@ -339,10 +804,13 @@ bool showingGitChanges()
void closeGitChanges(HWND owner,bool restore=true)
{
if(restore && gitChangesView && gitActionPending(*gitChangesView)) return;
auto view=std::move(gitChangesView);
if(!view) return;
view->stopRefresh.request_stop();
view->stopDiff.request_stop();
view->stopPreview.request_stop();
view->stopHistory.request_stop();
view->stopMutation.request_stop();
if(IsWindow(view->host)) DestroyWindow(view->host);
if(restore)
{
@@ -398,11 +866,35 @@ bool handleGitChangesKey(HWND owner,const MSG &message)
const bool control=GetKeyState(VK_CONTROL)&0x8000;
const bool alt=GetKeyState(VK_MENU)&0x8000;
if(alt) return false;
const auto selector=view.historyMode?view.branchPicker:view.filter;
if(view.historyMode && SendMessageW(view.branchPicker,CB_GETDROPPEDSTATE,0,0)) return false;
if(!control && key==VK_ESCAPE) closeGitChanges(owner);
else if(control && key=='R') refreshGitChanges(view);
else if(control && key=='F') SetFocus(view.filter);
else if(!control && key==VK_TAB) SetFocus(GetFocus()==view.filter?view.list:view.filter);
else if(!control && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list)))
else if(control && key=='R')
{
if(view.historyMode) loadGitHistory(view,true);
else refreshGitChanges(view);
}
else if(control && key=='F') SetFocus(selector);
else if(!control && key==VK_TAB)
{
std::vector<HWND> focusOrder;
for(const auto controlWindow:{view.list,selector,view.indexButton,view.commitButton,view.switchView,view.moreButton})
if(IsWindowVisible(controlWindow) && IsWindowEnabled(controlWindow)) focusOrder.push_back(controlWindow);
const auto current=std::find(focusOrder.begin(),focusOrder.end(),GetFocus());
if(!focusOrder.empty())
{
const bool reverse=GetKeyState(VK_SHIFT)&0x8000;
const auto index=current==focusOrder.end()?0:static_cast<size_t>(current-focusOrder.begin());
const auto next=reverse?focusOrder.size()-1:1;
SetFocus(focusOrder[(index+next)%focusOrder.size()]);
}
}
else if(!control && key==VK_F6) switchGitView(view);
else if(!control && view.historyMode && key==VK_F7) loadGitHistory(view,false,true);
else if(!control && key==VK_RETURN &&
(GetFocus()==view.indexButton || GetFocus()==view.commitButton || GetFocus()==view.switchView || GetFocus()==view.moreButton))
SendMessageW(GetFocus(),BM_CLICK,0,0);
else if(!control && !view.historyMode && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list)))
openGitWorkingFile(view,key==VK_F4);
else if(!control && GetFocus()==view.filter &&
(key==VK_UP || key==VK_DOWN || key==VK_PRIOR || key==VK_NEXT))
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <windows.h>
namespace ks::files
{
inline constexpr UINT filesHelpRequest=WM_APP+273;
enum class FilesHelpTopic
{
panels, menus, navigation, find, transfer, deleteFiles, archive, space, properties, connections,
terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, log, count
};
}
+281
View File
@@ -0,0 +1,281 @@
using ks::files::FilesHelpTopic;
constexpr struct
{
const wchar_t *title,*keywords,*body;
} filesHelpTopics[]{
{L"File panels",L"commander left right selection tabs keyboard refresh",
L"Use Tab to switch panes. Enter opens the selected folder or file. Insert marks an item and advances to the next row. The selection summary counts marked items.\r\n\r\n"
L"The command bar shows the primary keys for common actions. The Left and Right menus switch modes, choose drives, sort items, and filter a pane."},
{L"Menus and shortcuts",L"f9 access keys commands actions configuration",
L"Press F9 to show the menu bar. Use the arrow keys to move between categories and entries. Press Enter to run the highlighted command.\r\n\r\n"
L"Press F1 on a menu item for its topic. Commands → Keyboard shortcuts lists the active scheme and lets you assign extra bindings."},
{L"Locations and navigation",L"folder path history breadcrumbs drives recent bookmark directory unc",
L"Use the breadcrumb in a local or remote pane to jump to an ancestor. The folder history keeps earlier locations for that pane. Recent folders are available from the drive picker.\r\n\r\n"
L"Folder shortcuts open frequently used locations. In the default scheme Ctrl+0–9 recalls a digit and Ctrl+Shift+0–9 adds the current folder."},
{L"Find files",L"search filter mask results alt f7 paths subfolders",
L"Find files searches from the active folder, including subfolders. Supply a filename mask such as *.md. The results show their locations and can be opened or used in file operations.\r\n\r\n"
L"Enter visits a result's folder. Esc stops an active search or returns from the results. Use Quick View for a preview of a local result."},
{L"Copy, move and rename",L"transfer destination mask overwrite permissions timestamps clipboard queue",
L"Copy and Move use the selection in the active pane. The destination starts with the other pane. Check the destination and the conflict policy before starting the operation.\r\n\r\n"
L"Copy/Move options can limit the selection by mask, target several folders, and preserve timestamps or supported permissions. The progress dialog shows the active file and an estimate when enough data has transferred."},
{L"Delete and Recycle Bin",L"permanent remove recovery confirmation shift delete",
L"Delete respects the selected items and shows a confirmation. Local files are sent to the Recycle Bin when supported. Check the notice for remote locations or permanent deletion.\r\n\r\n"
L"Shift+Delete requests permanent deletion. Cancel the confirmation to keep the selection without deleting it."},
{L"Archives",L"zip 7z pack extract compression update",
L"Open a ZIP or 7z archive from a local pane to browse its entries. Copy entries out to extract them. Back out through the parent entry or Esc.\r\n\r\n"
L"Use Pack files to create or update a ZIP or 7z archive. Review the destination, compression and conflict choices before saving."},
{L"Space Analyzer",L"storage folder size allocation disk tree treemap sunburst",
L"Open Space Analyzer from Commands for a local folder. The tree and charts show which folders consume space. Select an item to inspect its contribution and choose the display you need.\r\n\r\n"
L"Logical size describes file data. Allocated size describes disk allocation where it can be measured."},
{L"Properties and locking processes",L"context menu windows owner attributes filesystem locks handle",
L"Properties shows available file details and Windows attributes. The Windows context menu exposes actions supplied by the file type and the operating system.\r\n\r\n"
L"Use Locking processes for selected local items to see processes with open handles. Save any work in the owning program before closing it."},
{L"Network connections",L"ftp sftp smb lan ssh host authentication credentials password remote",
L"The drive picker opens FTP, SFTP and SMB connection profiles, as well as paired LAN computers. Create a profile with its protocol, host and starting folder.\r\n\r\n"
L"Check the remote server identity when connecting. If a listing is interrupted, use the Refresh command shown in the pane's status line to retry."},
{L"Command line and terminal",L"powershell ssh console history windows command f1",
L"Type a PowerShell command and press Enter to run it in the active pane's context. Ctrl+O switches between the file panes and terminal output. Previous command and Command history use the active keyboard scheme.\r\n\r\n"
L"With a command name at the caret, F1 can open its Windows command reference. With an empty command line F1 opens the Files guide."},
{L"Text Viewer and Quick View",L"preview read file html hex bookmark go to search",
L"View opens a separate window. Quick View previews the local selection alongside its pane. View as hex displays binary data. A local Viewer refreshes when its file is changed externally.\r\n\r\n"
L"Use the Viewer menus for Find, page navigation and bookmarks. Options opens the Viewer appearance page."},
{L"Text Editor",L"edit save encoding f2 f4 f6 external changes buffers",
L"Edit opens a text file for changes. The Editor menu provides Save, Find, undo and encoding controls. Switching to Viewer keeps a pending Editor buffer for the open document.\r\n\r\n"
L"When the disk version changes, choose Reload or Keep buffer. Saving checks the disk version again and reports a conflict if the file has changed."},
{L"Markdown preview",L"markdown rendered source local links images search",
L"Open a Markdown file in Viewer to read the rendered document. Use its navigation controls for local links and its search form to find rendered text. Switch back to source for editing.\r\n\r\n"
L"Options opens the Markdown page for width, font and scale. Markdown's scale is separate from the text Viewer and Editor."},
{L"Image Viewer and Editor",L"png jpeg image zoom rotate crop undo save copy",
L"View opens supported images with fit, zoom and navigation controls. Local PNG and JPEG files can be opened with Edit to rotate or crop them.\r\n\r\n"
L"Use Undo to reverse edits and Save Copy to create a new file. Replacing the original requires confirmation and checks for external changes."},
{L"File comparison",L"diff unified changes left right hunk apply undo whitespace",
L"Select the two files and choose Compare files. Previous and Next jump between change blocks. Unified changes the view, and Fold unchanged collapses matching context.\r\n\r\n"
L"Apply to left or right changes that side's draft. Use Undo or save the selected side when ready. Appearance opens the comparison font, colors and scale."},
{L"Git Changes",L"staged unstaged repository status commit branch diff",
L"Open Git Changes in a Git working tree to inspect changes, branches and history. Select an entry to review its diff.\r\n\r\n"
L"Stage the changes you want to include. Commit staged changes shows the items currently in the index before writing the commit."},
{L"Environment Variables",L"user system process path edit windows variables",
L"Environment Variables lists user, system and process scopes. Choose a scope, then review the selected name and value before editing.\r\n\r\n"
L"Changes to the system scope require the appropriate Windows permission. Existing applications may need to reopen before using updated values."},
{L"Files Options",L"preferences settings search apply reset cancel layout font",
L"Search settings by name or choose a section in the tree. Apply saves the draft and refreshes affected windows. Cancel discards the pending changes.\r\n\r\n"
L"Reset selected to defaults applies to the displayed section. Import JSON and Export JSON transfer supported settings groups between profiles."},
{L"Keyboard schemes",L"keys shortcuts multiple primary named duplicate context conflict",
L"Use Commands → Keyboard shortcuts to switch or copy a named scheme. Select a command, enter a key and choose Add. Make primary controls which binding appears in the command bar.\r\n\r\n"
L"Keys already assigned in an overlapping context cannot be added to another command in that context. F1 opens this guide."},
{L"Appearance and scale",L"theme light dark windows appearance font palette size",
L"Panels, Viewer, Editor, Markdown, terminal and comparison each have a saved scale. Use the visible area's Options or Appearance command to open its settings.\r\n\r\n"
L"Viewer and Editor can use System (Windows). Assign either a stock or named palette to each Windows mode under Appearance → System themes."},
{L"Import and export settings",L"json portable backup restore transfer option groups",
L"Select the saved settings groups to include in an export. The supported groups cover colors and file styles, panel layout and keyboard schemes.\r\n\r\n"
L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."},
{L"Files log",L"diagnostic journal error logging rotate copy record",
L"Open Files log from Commands to see recent entries. Switch between the current and previous rotated log, or use Refresh to read newer entries.\r\n\r\n"
L"Select an entry to copy its timestamp and summary. The viewer shows only supported diagnostic details."}
};
static_assert(std::size(filesHelpTopics)==static_cast<size_t>(FilesHelpTopic::count));
constexpr int helpSearch=670,helpTopics=671,helpTitle=672,helpBody=673;
void displayFilesHelpTopic(HWND dialog,int topic)
{
if(topic<0)
{
SetDlgItemTextW(dialog,helpTitle,L"No matching help topics");
SetDlgItemTextW(dialog,helpBody,L"");
return;
}
const auto &entry=filesHelpTopics[topic];
SetDlgItemTextW(dialog,helpTitle,entry.title);
SetDlgItemTextW(dialog,helpBody,entry.body);
SendDlgItemMessageW(dialog,helpBody,EM_SETSEL,0,0);
SendDlgItemMessageW(dialog,helpBody,EM_SCROLLCARET,0,0);
}
void filterFilesHelpTopics(HWND dialog,int previous)
{
wchar_t buffer[129]{};
GetDlgItemTextW(dialog,helpSearch,buffer,std::size(buffer));
std::wistringstream query(ks::lower(buffer));
std::vector<std::wstring> tokens;
for(std::wstring term;query>>term;) tokens.push_back(std::move(term));
const auto list=GetDlgItem(dialog,helpTopics);
SendMessageW(list,LB_RESETCONTENT,0,0);
int displayed=-1;
LRESULT selected=LB_ERR;
for(size_t i=0;i<std::size(filesHelpTopics);++i)
{
const auto &topic=filesHelpTopics[i];
const auto text=ks::lower(std::wstring(topic.title)+L" "+topic.keywords+L" "+topic.body);
if(!std::ranges::all_of(tokens,[&](const auto &word){return text.find(word)!=text.npos;})) continue;
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(topic.title));
if(row<0) continue;
SendMessageW(list,LB_SETITEMDATA,row,i);
if(selected==LB_ERR || static_cast<int>(i)==previous)
{
selected=row;
displayed=static_cast<int>(i);
}
}
if(selected!=LB_ERR) SendMessageW(list,LB_SETCURSEL,selected,0);
displayFilesHelpTopic(dialog,displayed);
}
int selectedFilesHelpTopic(HWND dialog)
{
const auto row=SendDlgItemMessageW(dialog,helpTopics,LB_GETCURSEL,0,0);
return row==LB_ERR?-1:static_cast<int>(SendDlgItemMessageW(dialog,helpTopics,LB_GETITEMDATA,row,0));
}
INT_PTR CALLBACK filesHelpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SendDlgItemMessageW(dialog,helpSearch,EM_SETLIMITTEXT,128,0);
filterFilesHelpTopics(dialog,static_cast<int>(lp));
SetFocus(GetDlgItem(dialog,helpSearch));
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(LOWORD(wp)==helpSearch && HIWORD(wp)==EN_CHANGE)
filterFilesHelpTopics(dialog,selectedFilesHelpTopic(dialog));
if(LOWORD(wp)==helpTopics && HIWORD(wp)==LBN_SELCHANGE)
displayFilesHelpTopic(dialog,selectedFilesHelpTopic(dialog));
return TRUE;
}
void showFilesHelp(HWND owner,FilesHelpTopic topic)
{
if(!owner || !IsWindow(owner) || FilesModalDialog::resourceFor(owner)==618) return;
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(618),owner,filesHelpDialog,
static_cast<LPARAM>(topic),false,false);
dialog.runModal();
}
FilesHelpTopic filesMenuHelpTopic()
{
if(folderPicker) return FilesHelpTopic::navigation;
if(!commandPicker) return IsWindowVisible(picker)?FilesHelpTopic::connections:FilesHelpTopic::menus;
const auto row=SendMessageW(picker,LB_GETCURSEL,0,0);
if(!selectablePickerRow(row)) return FilesHelpTopic::menus;
const int action=commandActions[row];
if(menuIndex==0 || menuIndex==4) return action==4?FilesHelpTopic::navigation:FilesHelpTopic::panels;
if(menuIndex==1)
{
if(action==4) return FilesHelpTopic::archive;
if(action==5 || action==6) return FilesHelpTopic::properties;
return action<=2?FilesHelpTopic::transfer:FilesHelpTopic::menus;
}
if(menuIndex!=2) return FilesHelpTopic::menus;
switch(action)
{
case 1: case 4: case 10: case 13: case 14: return FilesHelpTopic::viewer;
case 2: case 5: return FilesHelpTopic::editor;
case 3: case 11: return FilesHelpTopic::navigation;
case 6: case 7: return FilesHelpTopic::connections;
case 8: return FilesHelpTopic::comparison;
case 9: return FilesHelpTopic::find;
case 12: return FilesHelpTopic::space;
case 15: return FilesHelpTopic::properties;
case 16: return FilesHelpTopic::git;
case 17: return FilesHelpTopic::environment;
case 19: return FilesHelpTopic::terminal;
case 20: return FilesHelpTopic::keys;
case 21: return FilesHelpTopic::appearance;
case 23: return FilesHelpTopic::log;
default: return FilesHelpTopic::menus;
}
}
std::optional<FilesHelpTopic> filesHelpForWindow(HWND root,HWND target)
{
const auto resource=FilesModalDialog::resourceFor(root);
switch(resource)
{
case 618: return {};
case 101:
{
const auto control=GetDlgCtrlID(target);
if(control==optionsImport || control==optionsExport) return FilesHelpTopic::portability;
if(control==321 || control==comparisonKeySchemesButton) return FilesHelpTopic::keys;
if(const auto *option=reinterpret_cast<const OptionsDraft*>(GetWindowLongPtrW(root,DWLP_USER)))
{
if(option->page==Appearance || control==areaScaleControl) return FilesHelpTopic::appearance;
if(option->page==TextViewer && option->section==markdownSection) return FilesHelpTopic::markdown;
if(option->page==PanelModes) return FilesHelpTopic::panels;
if(option->page==CommandLine) return FilesHelpTopic::terminal;
if(option->page==CompareFiles) return FilesHelpTopic::comparison;
}
return FilesHelpTopic::options;
}
case 102: case 103: case 104: case 105: case 108: case 113: case 129: return FilesHelpTopic::transfer;
case 106: case 107: return FilesHelpTopic::deleteFiles;
case 109: case 110: case 117: return FilesHelpTopic::navigation;
case 111: return FilesHelpTopic::terminal;
case 112: case 121: case 122: case 123: case 124: return FilesHelpTopic::connections;
case 114: case 115: return FilesHelpTopic::comparison;
case 116: return FilesHelpTopic::find;
case 118: return FilesHelpTopic::space;
case 119: return FilesHelpTopic::panels;
case 120: return FilesHelpTopic::archive;
case 125: case 609: return FilesHelpTopic::properties;
case 126: return FilesHelpTopic::git;
case 127: case 128: return FilesHelpTopic::environment;
case 130: return FilesHelpTopic::images;
case 602: case 613: case 614: return FilesHelpTopic::viewer;
case 603: case 611: case 612: return FilesHelpTopic::editor;
case 608: return FilesHelpTopic::appearance;
case 615: case 616: return FilesHelpTopic::keys;
case 617: return FilesHelpTopic::portability;
case 619: return FilesHelpTopic::log;
case 604: case 607:
if(const auto owner=GetWindow(root,GW_OWNER);owner && owner!=root)
return filesHelpForWindow(owner,owner);
break;
}
if(comparisonWindows.contains(root)) return FilesHelpTopic::comparison;
if(const auto area=ks::files::textWindowAppearanceArea(root))
return *area==AppearanceArea::markdown?FilesHelpTopic::markdown:
*area==AppearanceArea::editor?FilesHelpTopic::editor:FilesHelpTopic::viewer;
wchar_t type[64]{};
GetClassNameW(root,type,std::size(type));
if(std::wstring_view(type)==L"KSwitcherFilesImageViewer") return FilesHelpTopic::images;
if(root!=GetParent(terminalInput)) return resource?std::optional(FilesHelpTopic::options):std::nullopt;
if(gitChangesView && (target==gitChangesView->host || IsChild(gitChangesView->host,target))) return FilesHelpTopic::git;
if(quickImageWindow && (target==quickImageWindow || IsChild(quickImageWindow,target))) return FilesHelpTopic::images;
if(quickViewWindow && (target==quickViewWindow || IsChild(quickViewWindow,target))) return FilesHelpTopic::viewer;
if(IsWindowVisible(menuBar) || IsWindowVisible(picker)) return filesMenuHelpTopic();
if(terminalVisible || target==terminalOutput || IsChild(terminalOutput,target)) return FilesHelpTopic::terminal;
if(target==panels[0].path || target==panels[1].path) return FilesHelpTopic::navigation;
return panels[active].findOrigin?FilesHelpTopic::find:FilesHelpTopic::panels;
}
bool handleFilesHelpMessage(const MSG &message)
{
const bool posted=message.message==ks::files::filesHelpRequest;
if(!message.hwnd || (!posted && (message.message!=WM_KEYDOWN || message.wParam!=VK_F1 ||
((GetKeyState(VK_CONTROL)|GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|
GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)))) return false;
const auto root=GetAncestor(message.hwnd,GA_ROOT);
auto target=message.hwnd;
if(root==target)
if(const auto focus=GetFocus();focus && IsChild(root,focus)) target=focus;
if(FilesModalDialog::resourceFor(root)==618) return true;
const auto topic=posted && message.hwnd==GetParent(terminalInput)?
std::optional(FilesHelpTopic::terminal):filesHelpForWindow(root,target);
if(!topic) return false;
if(!posted)
{
if(message.lParam&(1LL<<30)) return true;
if(target==terminalInput && commandLineAvailable(root) && handleCompletionKey(VK_F1,message.lParam))
return true;
}
showFilesHelp(root,*topic);
return true;
}
+79 -5
View File
@@ -3,6 +3,7 @@
#include <wincodec.h>
#include <webp/decode.h>
#include <webp/demux.h>
#include <algorithm>
#include <cstring>
#include <fstream>
#include <memory>
@@ -58,13 +59,14 @@ struct ImagingObject
T *operator->() const {return value;}
};
struct Apartment
{
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
};
ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop)
{
struct Apartment
{
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
};
const Apartment apartment;
if(apartment.initialized!=RPC_E_CHANGED_MODE) checkImage(apartment.initialized);
ImagingObject<IWICImagingFactory> factory;
@@ -141,6 +143,78 @@ bool isImagePath(const std::filesystem::path &path)
return imageFormat(path)!=ImageFormat::unknown;
}
bool isEditableImagePath(const std::filesystem::path &path)
{
const auto format=imageFormat(path);
return format==ImageFormat::png || format==ImageFormat::jpeg;
}
void encodeImage(const ImageRaster &raster,const fs::path &contents,const fs::path &name)
{
const auto format=imageFormat(name);
if(format!=ImageFormat::png && format!=ImageFormat::jpeg)
throw std::runtime_error("Choose a PNG or JPEG file.");
checkImageDimensions(raster.width,raster.height);
if(raster.pixels.size()!=size_t(raster.width)*raster.height) throw std::runtime_error(invalidImage);
const auto check=[](HRESULT result) {
if(FAILED(result)) throw std::system_error(static_cast<int>(result),std::system_category(),"Encode image");
};
const Apartment apartment;
if(apartment.initialized!=RPC_E_CHANGED_MODE) check(apartment.initialized);
ImagingObject<IWICImagingFactory> factory;
check(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
const bool png=format==ImageFormat::png;
ImagingObject<IWICStream> stream;
check(factory->CreateStream(&stream.value));
check(stream->InitializeFromFilename(contents.c_str(),GENERIC_WRITE));
ImagingObject<IWICBitmapEncoder> encoder;
check(factory->CreateEncoder(png?GUID_ContainerFormatPng:GUID_ContainerFormatJpeg,nullptr,&encoder.value));
check(encoder->Initialize(stream.value,WICBitmapEncoderNoCache));
ImagingObject<IWICBitmapFrameEncode> frame;
ImagingObject<IPropertyBag2> options;
check(encoder->CreateNewFrame(&frame.value,&options.value));
if(!png)
{
wchar_t qualityName[]=L"ImageQuality";
PROPBAG2 property{};
property.pstrName=qualityName;
VARIANT quality{};
quality.vt=VT_R4;
quality.fltVal=0.95f;
check(options->Write(1,&property,&quality));
}
check(frame->Initialize(options.value));
check(frame->SetSize(raster.width,raster.height));
auto pixelFormat=png?GUID_WICPixelFormat32bppBGRA:GUID_WICPixelFormat24bppBGR;
check(frame->SetPixelFormat(&pixelFormat));
auto *pixels=raster.pixels.data();
std::vector<uint32_t> opaque;
if(!png && std::any_of(raster.pixels.begin(),raster.pixels.end(),[](uint32_t pixel){return (pixel>>24)!=255;}))
{
opaque=raster.pixels;
for(auto &pixel:opaque)
{
const auto white=255-(pixel>>24);
const auto gray=white|(white<<8)|(white<<16);
pixel=0xff000000|((pixel&0x00ffffff)+gray);
}
pixels=opaque.data();
}
const auto stride=static_cast<UINT>(raster.width*sizeof(uint32_t));
ImagingObject<IWICBitmap> source;
check(factory->CreateBitmapFromMemory(raster.width,raster.height,GUID_WICPixelFormat32bppPBGRA,stride,
static_cast<UINT>(raster.pixels.size()*sizeof(uint32_t)),
reinterpret_cast<BYTE *>(const_cast<uint32_t *>(pixels)),&source.value));
ImagingObject<IWICFormatConverter> converter;
check(factory->CreateFormatConverter(&converter.value));
check(converter->Initialize(source.value,pixelFormat,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom));
check(frame->WriteSource(converter.value,nullptr));
check(frame->Commit());
check(encoder->Commit());
check(stream->Commit(STGC_DEFAULT));
}
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop)
{
const auto format=imageFormat(name);
+3 -1
View File
@@ -10,10 +10,12 @@ namespace ks::files
struct ImageRaster
{
unsigned width{}, height{};
std::vector<uint32_t> pixels;
std::vector<uint32_t> pixels; // Premultiplied BGRA.
};
inline constexpr uint64_t imageSourceLimit=96ULL*1024*1024;
bool isImagePath(const std::filesystem::path &path);
bool isEditableImagePath(const std::filesystem::path &path);
void encodeImage(const ImageRaster &raster,const std::filesystem::path &contents,const std::filesystem::path &name);
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop={});
}
+131
View File
@@ -0,0 +1,131 @@
#include "files_image_edit.h"
#include "files_win32_replace.h"
#include <system_error>
namespace ks::files
{
namespace
{
struct ImageFile
{
HANDLE handle=INVALID_HANDLE_VALUE;
~ImageFile() {if(handle!=INVALID_HANDLE_VALUE) CloseHandle(handle);}
};
struct StagedImage
{
std::filesystem::path path;
~StagedImage() {if(!path.empty()) DeleteFileW(path.c_str());}
};
[[noreturn]] void fail(const char *message,DWORD error=GetLastError())
{
throw std::system_error(static_cast<int>(error),std::system_category(),message);
}
ImageRevision readRevision(HANDLE handle)
{
const auto revision=fileVersion(handle);
if(revision.info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))
throw std::runtime_error("Choose a regular local image.");
return revision;
}
bool contains(unsigned width,unsigned height,const ImageRegion &area)
{
return area.width && area.height && area.x<width && area.y<height &&
area.width<=width-area.x && area.height<=height-area.y;
}
}
ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area)
{
auto &region=geometry.region;
const bool sideways=(geometry.turns&1)!=0;
if(geometry.turns>=4 || !contains(sideways?region.height:region.width,sideways?region.width:region.height,area))
throw std::runtime_error("The crop rectangle must fit inside the image.");
const auto width=region.width, height=region.height;
switch(geometry.turns)
{
case 0: region.x+=area.x; region.y+=area.y; break;
case 1: region.x+=area.y; region.y+=height-area.x-area.width; break;
case 2: region.x+=width-area.x-area.width; region.y+=height-area.y-area.height; break;
case 3: region.x+=width-area.y-area.height; region.y+=area.x; break;
}
region.width=sideways?area.height:area.width;
region.height=sideways?area.width:area.height;
return geometry;
}
ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry)
{
const auto &region=geometry.region;
if(geometry.turns>=4 || !contains(original.width,original.height,region) ||
original.pixels.size()!=size_t(original.width)*original.height)
throw std::runtime_error("The image edit exceeds the original bounds.");
const bool sideways=geometry.turns&1;
ImageRaster output{sideways?region.height:region.width,sideways?region.width:region.height,{}};
output.pixels.resize(size_t(output.width)*output.height);
for(unsigned y=0;y<output.height;++y)
{
for(unsigned x=0;x<output.width;++x)
{
unsigned fromX{},fromY{};
switch(geometry.turns)
{
case 0: fromX=x; fromY=y; break;
case 1: fromX=y; fromY=region.height-1-x; break;
case 2: fromX=region.width-1-x; fromY=region.height-1-y; break;
case 3: fromX=region.width-1-y; fromY=x; break;
}
output.pixels[size_t(y)*output.width+x]=original.pixels[size_t(region.y+fromY)*original.width+region.x+fromX];
}
}
return output;
}
ImageRevision imageRevision(const std::filesystem::path &path)
{
ImageFile file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.handle==INVALID_HANDLE_VALUE) fail("Open image revision");
return readRevision(file.handle);
}
bool sameImageRevision(const ImageRevision &first,const ImageRevision &second)
{
return first==second;
}
ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected)
{
const auto stagedPath=temporaryPath(path.parent_path());
{
ImageFile reserve{CreateFileW(stagedPath.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,nullptr)};
if(reserve.handle==INVALID_HANDLE_VALUE) fail("Create image staging file");
}
StagedImage pending{stagedPath};
encodeImage(raster,pending.path,path);
// Keep the saved file's identity through publication, even if the path changes again.
ImageFile saved{CreateFileW(pending.path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(saved.handle==INVALID_HANDLE_VALUE) fail("Track saved image");
if(!expected)
{
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Publish image copy");
pending.path.clear();
return readRevision(saved.handle);
}
ImageFile current{CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,nullptr,
OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(current.handle==INVALID_HANDLE_VALUE) fail("Verify original image");
if(!sameImageRevision(*expected,readRevision(current.handle)))
throw std::runtime_error("The original image changed outside Files. Your edits remain open.");
const auto backup=temporaryPath(path.parent_path());
if(const auto error=replaceFileWithBackup(path,pending.path,backup)) fail("Replace original image",error);
pending.path.clear();
DeleteFileW(backup.c_str());
return readRevision(saved.handle);
}
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include "files_image_decode.h"
#include "files_win32_replace.h"
namespace ks::files
{
struct ImageRegion
{
unsigned x{}, y{}, width{}, height{};
bool operator==(const ImageRegion &) const = default;
};
struct ImageGeometry
{
ImageRegion region;
unsigned turns{};
bool operator==(const ImageGeometry &) const = default;
};
using ImageRevision=LocalFileVersion;
ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area);
ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry);
ImageRevision imageRevision(const std::filesystem::path &path);
bool sameImageRevision(const ImageRevision &first,const ImageRevision &second);
ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected=nullptr);
}
+109
View File
@@ -0,0 +1,109 @@
struct ImageCropPrompt
{
unsigned width,height;
ks::files::ImageRegion result;
};
INT_PTR CALLBACK imageCropDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int hint=650, x=651, y=652, width=653, height=654, footer=655;
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Crop image ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
auto &prompt=*reinterpret_cast<ImageCropPrompt *>(lp);
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
layoutDialogContent(window,hint);
layoutDialogButtons(window,footer,{IDOK,IDCANCEL});
const auto description=L"Image: "+std::to_wstring(prompt.width)+L" × "+std::to_wstring(prompt.height)+
L" pixels. X and Y start at zero.";
SetDlgItemTextW(window,hint,description.c_str());
for(const auto id:{x,y,width,height})
{
fitFarEditToLine(GetDlgItem(window,id));
const auto value=id==width?prompt.width:id==height?prompt.height:0;
SetDlgItemInt(window,id,value,FALSE);
}
SetFocus(GetDlgItem(window,x));
SendDlgItemMessageW(window,x,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &prompt=*reinterpret_cast<ImageCropPrompt *>(GetWindowLongPtrW(window,DWLP_USER));
std::array<unsigned,4> fields{};
for(size_t i=0;i<fields.size();++i)
{
const int id=x+static_cast<int>(i);
BOOL valid{};
fields[i]=GetDlgItemInt(window,id,&valid,FALSE);
if(!valid)
{
showFilesNotice(window,L"Enter a whole number of pixels.",L"Crop image");
SetFocus(GetDlgItem(window,id));
return TRUE;
}
}
const auto [left,top,wide,high]=fields;
if(!wide || !high || left>=prompt.width || top>=prompt.height ||
wide>prompt.width-left || high>prompt.height-top)
{
showFilesNotice(window,L"The crop rectangle must fit inside the image.",L"Crop image");
return TRUE;
}
prompt.result={left,top,wide,high};
FilesModalDialog::finish(window,IDOK);
return TRUE;
}
ks::files::ImageEditDialogs imageEditDialogs()
{
return {
[](HWND owner,unsigned width,unsigned height) -> std::optional<ks::files::ImageRegion>
{
ImageCropPrompt crop{width,height,{}};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(130),owner,
imageCropDialog,reinterpret_cast<LPARAM>(&crop))==IDOK) return crop.result;
return {};
},
[](HWND owner,const fs::path &original) -> fs::path
{
const auto name=original.stem().native()+L" copy"+original.extension().native();
std::array<wchar_t,32768> file{};
wcsncpy_s(file.data(),file.size(),name.c_str(),_TRUNCATE);
auto initial=original.parent_path().native();
OPENFILENAMEW dialog{sizeof(dialog)};
dialog.hwndOwner=owner;
dialog.lpstrTitle=L"Save an image copy";
dialog.lpstrFilter=L"PNG (*.png)\0*.png\0JPEG (*.jpg, *.jpeg)\0*.jpg;*.jpeg\0";
dialog.nFilterIndex=ks::lower(original.extension().native())==L".png"?1:2;
dialog.lpstrFile=file.data();
dialog.nMaxFile=static_cast<DWORD>(file.size());
dialog.lpstrInitialDir=initial.c_str();
dialog.lpstrDefExt=dialog.nFilterIndex==1?L"png":L"jpg";
dialog.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST;
if(GetSaveFileNameW(&dialog)) return file.data();
if(CommDlgExtendedError()) throw std::runtime_error("Could not open the image save dialog.");
return {};
},
[](HWND owner,const std::wstring &text,const wchar_t *title)
{
return showFilesNotice(owner,text.c_str(),title,{.confirm=true,.tone=FilesNoticeTone::warning})==IDYES;
},
[](HWND owner,const wchar_t *text)
{
showFilesNotice(owner,text,L"Image editor",{.tone=FilesNoticeTone::warning});
},
FilesModalDialog::dismissOwned,textWindowDialogs().reloadChanged
};
}
+233 -35
View File
@@ -17,8 +17,9 @@ namespace
{
namespace fs=std::filesystem;
constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer";
constexpr UINT_PTR imageTimer=1;
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize };
constexpr UINT_PTR imageTimer=1, externalImageTimer=2;
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize,
rotateLeft, rotateRight, crop, undoEdit, saveCopy, replaceOriginal };
void fillImageView(HDC dc,const RECT &rect,COLORREF color)
{
@@ -37,14 +38,32 @@ struct ImageView
ImageLoadRetry retry;
bool retried{};
std::function<void(HWND)> onClose;
std::array<HWND,6> buttons{};
std::array<HWND,replaceOriginal> buttons{};
struct Draft
{
ImageEditDialogs dialogs;
ImageRaster original;
std::optional<ImageRevision> version;
ImageGeometry geometry{}, saved{};
std::vector<ImageGeometry> undo;
bool dirty() const {return geometry!=saved;}
};
std::optional<Draft> draft;
struct Loaded
{
ImageRaster raster;
std::optional<ImageRevision> revision;
};
bool confirmingClose{};
std::optional<ImageRevision> observedVersion;
HFONT font{};
UINT fontDpi{};
int toolbarHeight{};
HBITMAP bitmap{};
unsigned width{},height{};
fs::path requested;
std::wstring error;
std::future<ImageRaster> reading;
std::future<Loaded> reading;
std::stop_source stop;
uint64_t revision{}, started{};
double zoom=1, x{}, y{};
@@ -64,7 +83,7 @@ struct ImageView
{
RECT area{};
GetClientRect(window,&area);
area.top=std::min(area.bottom,static_cast<LONG>(scale(35)));
area.top=std::min(area.bottom,static_cast<LONG>(toolbarHeight));
area.bottom=std::max(area.top,area.bottom-scale(27));
return area;
}
@@ -86,45 +105,83 @@ struct ImageView
RECT bounds{};
GetClientRect(window,&bounds);
const int left=scale(4), gap=scale(3), height=scale(27);
const int count=embedded?4:6;
const int available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
const int unit=std::min(scale(80),available/count);
int x=left;
for(auto button:buttons)
const auto place=[&](unsigned first,unsigned last,int y,int preferred) {
const auto count=static_cast<int>(last-first+1);
const auto available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
const auto unit=std::min(scale(preferred),available/count);
int x=left;
for(unsigned id=first;id<=last;++id)
{
SetWindowPos(buttons[id-1],nullptr,x,scale(y),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
x+=unit+gap;
}
};
place(embedded || draft?zoomOut:previous,actualSize,4,80);
int rows=0;
if(draft)
{
if(!button) continue;
SetWindowPos(button,nullptr,x,scale(4),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
x+=unit+gap;
int buttonWidth=scale(80);
if(const auto dc=GetDC(window))
{
const auto previousFont=font?SelectObject(dc,font):nullptr;
for(unsigned id=rotateLeft;id<=replaceOriginal;++id)
{
wchar_t label[32]{};
const auto length=GetWindowTextW(buttons[id-1],label,static_cast<int>(std::size(label)));
SIZE extent{};
if(GetTextExtentPoint32W(dc,label,length,&extent))
buttonWidth=std::max(buttonWidth,static_cast<int>(extent.cx)+scale(8));
}
if(previousFont) SelectObject(dc,previousFont);
ReleaseDC(window,dc);
}
const auto perRow=static_cast<unsigned>(std::max(1,(static_cast<int>(bounds.right)-left*2+gap)/(buttonWidth+gap)));
for(unsigned first=rotateLeft;first<=replaceOriginal;first+=perRow)
place(first,std::min<unsigned>(replaceOriginal,first+perRow-1),35+31*rows++,130);
}
toolbarHeight=scale(35+31*rows);
clampOffset();
InvalidateRect(window,nullptr,FALSE);
}
void updateButtons() const
{
if(!embedded)
if(!embedded && !draft)
{
EnableWindow(buttons[previous-1],position>0);
EnableWindow(buttons[following-1],position+1<images.size());
}
for(unsigned id=zoomOut;id<=actualSize;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
if(draft)
{
for(unsigned id=rotateLeft;id<=crop;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
EnableWindow(buttons[undoEdit-1],!draft->undo.empty());
EnableWindow(buttons[saveCopy-1],bitmap!=nullptr);
EnableWindow(buttons[replaceOriginal-1],draft->version && draft->dirty());
const auto title=L"Editor — "+requested.filename().wstring()+(draft->dirty()?L" *":L"");
SetWindowTextW(window,title.c_str());
}
for(auto button:buttons)
if(button) InvalidateRect(button,nullptr,FALSE);
}
void request(const fs::path &path)
void request(const fs::path &path,bool reload=false)
{
if(requested==path) return;
if(requested==path && !reload) return;
requested=path;
++revision;
stop.request_stop();
retried=false;
error.clear();
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
width=height=0;
fit=true;
x=y=0;
if(!embedded)
if(!reload)
{
observedVersion.reset();
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
width=height=0;
fit=true;
x=y=0;
}
if(!embedded && !draft)
{
const auto label=L"Viewer — "+path.filename().wstring();
SetWindowTextW(window,label.c_str());
@@ -134,7 +191,7 @@ struct ImageView
InvalidateRect(window,nullptr,FALSE);
}
void show(ImageRaster image)
void show(const ImageRaster &image)
{
BITMAPINFO info{};
info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
@@ -144,12 +201,16 @@ struct ImageView
info.bmiHeader.biBitCount=32;
info.bmiHeader.biCompression=BI_RGB;
void *bits=nullptr;
bitmap=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
if(!bitmap || !bits) throw std::runtime_error("Could not display this image.");
const auto next=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
if(!next || !bits)
{
if(next) DeleteObject(next);
throw std::runtime_error("Could not display this image.");
}
std::memcpy(bits,image.pixels.data(),image.pixels.size()*sizeof(uint32_t));
if(const auto old=std::exchange(bitmap,next)) DeleteObject(old);
width=image.width;
height=image.height;
updateButtons();
}
void poll()
@@ -163,7 +224,20 @@ struct ImageView
try
{
auto image=reading.get();
if(current) show(std::move(image));
if(current)
{
show(image.raster);
observedVersion=image.revision;
if(draft)
{
draft->undo.clear();
draft->version=image.revision;
draft->original=std::move(image.raster);
draft->geometry=draft->saved={{0,0,width,height},0};
}
clampOffset();
updateButtons();
}
}
catch(const std::exception &failure)
{
@@ -191,9 +265,17 @@ struct ImageView
}
stop=std::stop_source{};
started=revision;
std::packaged_task<ImageRaster()> task([path=requested,decoder=retried?retry.load:load,token=stop.get_token()]
std::packaged_task<Loaded()> task([path=requested,decoder=retried?retry.load:load,
token=stop.get_token(),watch=!embedded && !load && isLocalDocumentPath(requested),editing=draft.has_value()]
{
return decoder?decoder(path,token):decodeImage(path,path,token);
if(!watch) return Loaded{decoder?decoder(path,token):decodeImage(path,path,token),{}};
std::optional<ImageRevision> before;
try {before=imageRevision(path);}
catch(const std::exception &) {if(editing) throw;}
auto raster=decodeImage(path,path,token);
if(before && *before!=imageRevision(path))
throw std::runtime_error("The image changed while it was opening. Open it again.");
return Loaded{std::move(raster),before};
});
reading=task.get_future();
try {std::thread(std::move(task)).detach();}
@@ -206,6 +288,18 @@ struct ImageView
}
}
void pollExternal()
{
if(!observedVersion || requested.empty() || reading.valid()) return;
std::optional<ImageRevision> revision;
try {revision=imageRevision(requested);}
catch(const std::exception &) {return;}
if(revision==observedVersion) return;
if(draft && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !draft->dialogs.reloadChanged)) return;
observedVersion=revision;
if(!draft || draft->dialogs.reloadChanged(window)) request(requested,true);
}
double factor() const
{
if(!fit || !width || !height) return zoom;
@@ -242,9 +336,70 @@ struct ImageView
InvalidateRect(window,nullptr,FALSE);
}
void applyEdit(ImageGeometry next,bool undo)
{
if(next==draft->geometry) return;
auto raster=transformImage(draft->original,next);
if(!undo) draft->undo.push_back(draft->geometry);
try {show(raster);}
catch(...)
{
if(!undo) draft->undo.pop_back();
throw;
}
if(undo) draft->undo.pop_back();
draft->geometry=next;
fit=true;
zoom=1;
x=y=0;
updateButtons();
InvalidateRect(window,nullptr,FALSE);
}
void editAction(UINT id)
{
if(!draft || !bitmap) return;
try
{
if(id==rotateLeft || id==rotateRight)
{
auto next=draft->geometry;
next.turns=(next.turns+(id==rotateLeft?3:1))%4;
applyEdit(next,false);
}
else if(id==crop)
{
if(const auto area=draft->dialogs.crop(window,width,height))
applyEdit(cropImage(draft->geometry,*area),false);
}
else if(id==undoEdit && !draft->undo.empty())
applyEdit(draft->undo.back(),true);
else if(id==saveCopy)
{
const auto destination=draft->dialogs.copyPath(window,requested);
if(destination.empty()) return;
saveImage(transformImage(draft->original,draft->geometry),destination);
}
else if(id==replaceOriginal && draft->dirty() && draft->version &&
draft->dialogs.confirm(window,L"Replace the original image?\r\n\r\n"+requested.native(),L"Replace original"))
{
draft->version=saveImage(transformImage(draft->original,draft->geometry),requested,&*draft->version);
observedVersion=draft->version;
draft->saved=draft->geometry;
updateButtons();
}
}
catch(const std::exception &failure)
{
updateButtons();
draft->dialogs.report(window,wide(failure.what()).c_str());
}
}
void action(UINT id)
{
if(id==previous && position>0) request(images[--position]);
if(id>=rotateLeft && id<=replaceOriginal) editAction(id);
else if(id==previous && position>0) request(images[--position]);
else if(id==following && position+1<images.size()) request(images[++position]);
else if(id==zoomOut || id==zoomIn) changeZoom(id==zoomIn?1.25:0.8);
else if(id==fitImage || id==actualSize)
@@ -354,12 +509,19 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
case WM_CREATE:
{
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%"};
for(unsigned id=view.embedded?zoomOut:previous;id<=actualSize;++id)
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%",
L"Rotate left",L"Rotate right",L"Crop…",L"Undo",L"Save copy…",L"Replace…"};
const unsigned first=view.embedded || view.draft?zoomOut:previous;
const unsigned last=view.draft?replaceOriginal:actualSize;
for(unsigned id=first;id<=last;++id)
{
view.buttons[id-1]=CreateWindowW(L"BUTTON",labels[id-1],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
if(!view.buttons[id-1]) return -1;
}
view.layout();
view.updateButtons();
if(!view.embedded && !view.load) SetTimer(window,externalImageTimer,500,nullptr);
return 0;
}
case WM_SIZE: view.layout(); return 0;
@@ -376,7 +538,10 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
case WM_ERASEBKGND: return 1;
case WM_PAINT: view.paint(); return 0;
case WM_DRAWITEM: view.paintButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp)); return TRUE;
case WM_TIMER: if(wp==imageTimer) view.poll(); return 0;
case WM_TIMER:
if(wp==imageTimer) view.poll();
if(wp==externalImageTimer) view.pollExternal();
return 0;
case WM_COMMAND:
if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);}
return 0;
@@ -416,15 +581,26 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
return 0;
}
case WM_KEYDOWN:
if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='Z') view.action(undoEdit);
else if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='S')
view.action((GetKeyState(VK_SHIFT)&0x8000)?saveCopy:replaceOriginal);
else if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
else if(wp==VK_SUBTRACT || wp==VK_OEM_MINUS) view.action(zoomOut);
else if(wp=='0') view.action(fitImage);
else if(wp=='1') view.action(actualSize);
else if(!view.embedded && (wp==VK_LEFT || wp==VK_PRIOR)) view.action(previous);
else if(!view.embedded && (wp==VK_RIGHT || wp==VK_NEXT)) view.action(following);
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) DestroyWindow(window);
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) SendMessageW(window,WM_CLOSE,0,0);
else break;
return 0;
case WM_CLOSE:
if(view.confirmingClose || (view.draft && view.draft->dialogs.dismissOwned(window))) return 0;
view.confirmingClose=true;
if(!view.draft || !view.draft->dirty() ||
view.draft->dialogs.confirm(window,L"Discard unsaved image edits?",L"Image editor"))
DestroyWindow(window);
view.confirmingClose=false;
return 0;
case WM_NCDESTROY:
imageViews.erase(found);
if(view.onClose) view.onClose(window);
@@ -435,7 +611,8 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
}
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry)
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry,
const ImageEditDialogs *editor)
{
const auto instance=GetModuleHandleW(nullptr);
static const bool registered=[instance]
@@ -450,6 +627,7 @@ HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<s
if(!registered) return nullptr;
auto state=std::make_shared<ImageView>();
state->embedded=embedded;
if(editor) state->draft.emplace(ImageView::Draft{*editor});
state->style=style;
state->images=std::move(images);
state->load=std::move(load);
@@ -471,4 +649,24 @@ void showImageViewFile(HWND window,const std::filesystem::path &path)
{
if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path);
}
std::optional<ImageWindowSession> imageWindowSession(HWND window)
{
const auto found=imageViews.find(window);
if(found==imageViews.end()) return {};
const auto &view=*found->second;
if(view.embedded || view.load || !isLocalDocumentPath(view.requested)) return {};
return ImageWindowSession{view.requested,view.draft.has_value(),view.fit,view.zoom,view.x,view.y};
}
void restoreImageWindowSession(HWND window,const ImageWindowSession &state)
{
const auto found=imageViews.find(window);
if(found==imageViews.end()) return;
auto &view=*found->second;
view.fit=state.fit;
view.zoom=std::isfinite(state.zoom)?std::clamp(state.zoom,0.05,32.0):1.0;
view.x=std::isfinite(state.x)?state.x:0;
view.y=std::isfinite(state.y)?state.y:0;
}
}
+25 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include "files_image_decode.h"
#include "files_image_edit.h"
#include <optional>
#include <windows.h>
#include <functional>
#include <exception>
@@ -22,7 +23,29 @@ struct ImageViewStyle
COLORREF background{}, text{}, toolbar{}, toolbarText{}, selection{};
};
struct ImageEditDialogs
{
std::function<std::optional<ImageRegion>(HWND,unsigned,unsigned)> crop;
std::function<std::filesystem::path(HWND,const std::filesystem::path &)> copyPath;
std::function<bool(HWND,const std::wstring &,const wchar_t *)> confirm;
std::function<void(HWND,const wchar_t *)> report;
std::function<bool(HWND)> dismissOwned;
std::function<bool(HWND)> reloadChanged;
};
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={});
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={},
const ImageEditDialogs *editor=nullptr);
void showImageViewFile(HWND window,const std::filesystem::path &path);
struct ImageWindowSession
{
std::filesystem::path path;
bool editor{}, fit=true;
double zoom=1, x{}, y{};
RECT bounds{};
bool maximized{};
};
std::optional<ImageWindowSession> imageWindowSession(HWND window);
void restoreImageWindowSession(HWND window,const ImageWindowSession &state);
}
+257
View File
@@ -0,0 +1,257 @@
enum KeyContext : unsigned { panelKeyContext=1, terminalKeyContext=2 };
enum class FilesKey
{
Refresh, View, Edit, Copy, Move, Mkdir, Delete, Exit, Compare, Previous, History,
Pack, Find, ExternalView, ExternalEdit, QuickView, FullPath, HexView, Swap, Properties, Next, Count
};
constexpr size_t keyIndex(FilesKey command) { return static_cast<size_t>(command); }
constexpr unsigned bothKeyContexts=panelKeyContext|terminalKeyContext;
constexpr WORD chord(BYTE key,BYTE modifiers=0) { return MAKEWORD(key,modifiers); }
constexpr BYTE keyCtrl=HOTKEYF_CONTROL,keyShift=HOTKEYF_SHIFT,keyAlt=HOTKEYF_ALT;
constexpr struct
{
const char *id;
const wchar_t *label;
unsigned contexts;
std::array<WORD,2> defaults;
} filesKeyCommands[]{
{"refresh",L"Refresh panel",bothKeyContexts,{chord('R',keyCtrl),chord(VK_F2)}},
{"view",L"View",panelKeyContext,{chord(VK_F3)}},
{"edit",L"Edit",panelKeyContext,{chord(VK_F4)}},
{"copy",L"Copy",panelKeyContext,{chord(VK_F5)}},
{"move",L"Move",panelKeyContext,{chord(VK_F6)}},
{"mkdir",L"Make folder",panelKeyContext,{chord(VK_F7)}},
{"delete",L"Delete to Recycle Bin",panelKeyContext,{chord(VK_F8)}},
{"exit",L"Exit",bothKeyContexts,{chord(VK_F10)}},
{"compare",L"Compare files",panelKeyContext,{chord(VK_F11,keyShift)}},
{"previous",L"Previous command",bothKeyContexts,{chord('E',keyCtrl)}},
{"history",L"Command history",bothKeyContexts,{chord(VK_F8,keyAlt)}},
{"pack",L"Pack files",panelKeyContext,{chord(VK_F5,keyAlt)}},
{"find",L"Find files",panelKeyContext,{chord(VK_F7,keyAlt)}},
{"externalView",L"View externally",panelKeyContext,{chord(VK_F3,keyAlt)}},
{"externalEdit",L"Edit externally",panelKeyContext,{chord(VK_F4,keyAlt)}},
{"quickView",L"Quick View",panelKeyContext,{chord('Q',keyCtrl)}},
{"fullPath",L"Copy full path",panelKeyContext,{chord('C',keyCtrl|keyShift)}},
{"hexView",L"View as hex",panelKeyContext,{chord(VK_F3,keyShift)}},
{"swap",L"Swap panels",panelKeyContext,{chord('U',keyCtrl)}},
{"properties",L"Properties",panelKeyContext,{chord('A',keyCtrl)}},
{"next",L"Next command",terminalKeyContext,{chord(VK_DOWN)}},
};
static_assert(std::size(filesKeyCommands)==keyIndex(FilesKey::Count));
constexpr size_t filesKeySchemeLimit=24,filesKeysPerCommand=8;
constexpr wchar_t filesKeySchemePreference[]=L"KeySchemesV1";
struct FilesKeyScheme
{
std::wstring name;
std::array<std::vector<WORD>,keyIndex(FilesKey::Count)> keys;
bool operator==(const FilesKeyScheme &) const=default;
};
struct FilesKeySettings
{
std::vector<FilesKeyScheme> schemes;
size_t active{};
bool operator==(const FilesKeySettings &) const=default;
};
std::wstring filesKeyLabel(WORD binding)
{
if(!binding) return {};
std::wstring label;
if(HIBYTE(binding)&keyCtrl) label+=L"Ctrl+";
if(HIBYTE(binding)&keyAlt) label+=L"Alt+";
if(HIBYTE(binding)&keyShift) label+=L"Shift+";
const auto key=LOBYTE(binding);
if(key>=VK_F1 && key<=VK_F24) label+=L"F"+std::to_wstring(key-VK_F1+1);
else if(key==VK_DOWN) label+=L"Down";
else label+=static_cast<wchar_t>(key);
return label;
}
FilesKeyScheme defaultFilesKeyScheme(std::wstring name=L"Default")
{
FilesKeyScheme scheme{std::move(name),{}};
for(size_t command=0;command<scheme.keys.size();++command)
for(const auto binding:filesKeyCommands[command].defaults)
if(binding) scheme.keys[command].push_back(binding);
return scheme;
}
FilesKeySettings filesKeySettings{{defaultFilesKeyScheme()},0};
bool sameFilesKeySchemeName(std::wstring_view first,std::wstring_view second)
{
return CompareStringOrdinal(first.data(),static_cast<int>(first.size()),
second.data(),static_cast<int>(second.size()),TRUE)==CSTR_EQUAL;
}
bool validFilesKeySchemeName(std::wstring_view name)
{
return !name.empty() && name.size()<=48 && !iswspace(name.front()) && !iswspace(name.back()) &&
std::ranges::none_of(name,[](wchar_t character){return iswcntrl(character);});
}
unsigned reservedFilesKeyContexts(WORD binding)
{
const auto key=LOBYTE(binding),mods=HIBYTE(binding);
if(key>=VK_F1 && key<=VK_F24)
{
if(mods==keyAlt && key==VK_F4) return terminalKeyContext;
if(!mods && key==VK_F1) return bothKeyContexts;
if((!mods && key==VK_F9) || (mods==keyAlt && (key==VK_F1 || key==VK_F2 || key==VK_F10)) ||
(mods==keyShift && key==VK_F4) || (mods==keyShift && key==VK_F10) ||
(mods==keyCtrl && key<=VK_F12))
return panelKeyContext;
return 0;
}
if(key==VK_DOWN && !mods) return panelKeyContext;
if(key>='A' && key<='Z' && (mods&keyCtrl) && !(mods&keyAlt))
{
constexpr std::wstring_view editing=L"CFOPVXYZ";
if(mods==keyCtrl && editing.find(key)!=editing.npos) return bothKeyContexts;
if((mods==keyCtrl && key=='A') || (mods==(keyCtrl|keyShift) && (key=='C' || key=='V')))
return terminalKeyContext;
return 0;
}
return bothKeyContexts;
}
std::wstring filesKeyConflict(const FilesKeyScheme &scheme,size_t command,WORD binding)
{
if(!binding || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt)))
return L"Use a function key or a letter with Ctrl.";
const auto contexts=filesKeyCommands[command].contexts;
if(reservedFilesKeyContexts(binding)&contexts)
return filesKeyLabel(binding)+L" is reserved or unavailable in this context.";
for(size_t i=0;i<scheme.keys.size();++i)
if((filesKeyCommands[i].contexts&contexts) && std::ranges::find(scheme.keys[i],binding)!=scheme.keys[i].end())
return filesKeyLabel(binding)+L" is already assigned to "+filesKeyCommands[i].label+L".";
return {};
}
std::optional<FilesKeySettings> parseFilesKeySettings(const Json &stored)
{
try
{
if(stored.at("version")!=1 || !stored.at("schemes").is_array()) return {};
const auto &rows=stored.at("schemes");
if(rows.empty() || rows.size()>filesKeySchemeLimit) return {};
FilesKeySettings settings;
const auto active=stored.at("active").get<std::string>();
for(const auto &row:rows)
{
auto name=ks::wide(row.at("name").get<std::string>());
if(!validFilesKeySchemeName(name) ||
std::ranges::any_of(settings.schemes,[&](const auto &other)
{ return sameFilesKeySchemeName(other.name,name); })) return {};
FilesKeyScheme scheme{std::move(name),{}};
const auto &commands=row.at("commands");
if(!commands.is_object()) return {};
for(size_t i=0;i<scheme.keys.size();++i)
{
const auto found=commands.find(filesKeyCommands[i].id);
if(found==commands.end()) continue;
if(!found->is_array() || found->size()>filesKeysPerCommand) return {};
for(const auto &entry:*found)
{
if(!entry.is_number_unsigned() || entry>0xffff) return {};
const auto binding=entry.get<WORD>();
if(binding==chord(VK_F1)) continue;
if(!filesKeyConflict(scheme,i,binding).empty()) return {};
scheme.keys[i].push_back(binding);
}
}
for(size_t i=0;i<scheme.keys.size();++i)
if(!commands.contains(filesKeyCommands[i].id))
for(const auto binding:filesKeyCommands[i].defaults)
if(binding && filesKeyConflict(scheme,i,binding).empty()) scheme.keys[i].push_back(binding);
if(active==ks::utf8(scheme.name)) settings.active=settings.schemes.size();
settings.schemes.push_back(std::move(scheme));
}
return settings;
}
catch(const std::exception &) { return {}; }
}
Json serializeFilesKeySettings(const FilesKeySettings &settings)
{
Json schemes=Json::array();
for(const auto &scheme:settings.schemes)
{
Json commands=Json::object();
for(size_t i=0;i<scheme.keys.size();++i) commands[filesKeyCommands[i].id]=scheme.keys[i];
schemes.push_back({{"name",ks::utf8(scheme.name)},{"commands",std::move(commands)}});
}
return {{"version",1},{"active",ks::utf8(settings.schemes[settings.active].name)},{"schemes",std::move(schemes)}};
}
void loadFilesKeySettings()
{
if(const auto json=readFilesJsonPreference(filesKeySchemePreference))
if(auto settings=parseFilesKeySettings(*json))
{
filesKeySettings=std::move(*settings);
return;
}
auto migrated=defaultFilesKeyScheme(L"Previous settings");
constexpr struct { FilesKey command; const wchar_t *name; } legacy[]{
{FilesKey::Previous,L"PreviousCommandKey"},{FilesKey::History,L"CommandHistoryKey"},
{FilesKey::Compare,L"ComparisonShortcut"},
};
for(const auto &item:legacy)
{
const auto index=keyIndex(item.command);
auto &keys=migrated.keys[index];
const auto fallback=filesKeyCommands[index].defaults.front();
const auto binding=static_cast<WORD>(preference(item.name,fallback));
const auto context=filesKeyCommands[index].contexts;
if(binding==fallback || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt)) ||
(reservedFilesKeyContexts(binding)&context)) continue;
for(size_t i=0;i<migrated.keys.size();++i)
if(filesKeyCommands[i].contexts&context) std::erase(migrated.keys[i],binding);
keys={binding};
}
filesKeySettings={{defaultFilesKeyScheme()},0};
if(migrated.keys!=filesKeySettings.schemes.front().keys)
{
filesKeySettings.schemes.push_back(std::move(migrated));
filesKeySettings.active=1;
}
}
WORD currentFilesChord(WPARAM key)
{
if(key>0xff || ((GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return 0;
return chord(static_cast<BYTE>(key),((GetKeyState(VK_CONTROL)&0x8000)?keyCtrl:0) |
((GetKeyState(VK_SHIFT)&0x8000)?keyShift:0) | ((GetKeyState(VK_MENU)&0x8000)?keyAlt:0));
}
std::optional<FilesKey> boundFilesCommand(WORD binding,unsigned context)
{
const auto &keys=filesKeySettings.schemes[filesKeySettings.active].keys;
for(size_t i=0;i<keys.size();++i)
if((filesKeyCommands[i].contexts&context) && std::ranges::find(keys[i],binding)!=keys[i].end())
return static_cast<FilesKey>(i);
return {};
}
std::wstring filesKeyHint(FilesKey command,bool all=false)
{
std::wstring text;
for(const auto binding:filesKeySettings.schemes[filesKeySettings.active].keys[keyIndex(command)])
{
if(!text.empty()) text+=L", ";
text+=filesKeyLabel(binding);
if(!all) break;
}
return text;
}
std::wstring filesKeyMenuLabel(FilesKey command,std::wstring label={})
{
if(label.empty()) label=filesKeyCommands[keyIndex(command)].label;
const auto keys=filesKeyHint(command,true);
if(!keys.empty()) label+=L"\t"+keys;
return label;
}
+228
View File
@@ -0,0 +1,228 @@
constexpr int keySchemeChoice=610,keySchemeCopy=611,keySchemeReset=612,keySchemeCommand=613,
keySchemeContext=614,keySchemeBindings=615,keySchemeCapture=616,keySchemeAdd=617,keySchemeRemove=618,
keySchemePrimary=619,keySchemeName=620;
struct FilesKeySchemeDraft
{
FilesKeySettings base=filesKeySettings,settings=base;
FilesKey initial;
FilesKeySettings *pending{};
};
INT_PTR CALLBACK copyKeySchemeDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
auto &name=*reinterpret_cast<std::wstring*>(lp);
SendDlgItemMessageW(dialog,keySchemeName,EM_SETLIMITTEXT,48,0);
SetDlgItemTextW(dialog,keySchemeName,name.c_str());
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &name=*reinterpret_cast<std::wstring*>(GetWindowLongPtrW(dialog,DWLP_USER));
wchar_t entry[49]{};
GetDlgItemTextW(dialog,keySchemeName,entry,std::size(entry));
name=entry;
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
void refreshFilesKeyBindings(HWND dialog,const FilesKeyScheme &scheme,size_t command,size_t selection=0)
{
const auto &descriptor=filesKeyCommands[command];
SetDlgItemTextW(dialog,keySchemeContext,
descriptor.contexts==bothKeyContexts?L"Keys · panels and command output":
descriptor.contexts==terminalKeyContext?L"Keys · command output":L"Keys · file panels");
const auto list=GetDlgItem(dialog,keySchemeBindings);
SendMessageW(list,LB_RESETCONTENT,0,0);
const auto &keys=scheme.keys[command];
for(size_t i=0;i<keys.size();++i)
{
auto label=filesKeyLabel(keys[i]);
if(!i) label+=L" (primary)";
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
if(!keys.empty()) SendMessageW(list,LB_SETCURSEL,std::min(selection,keys.size()-1),0);
EnableWindow(GetDlgItem(dialog,keySchemeRemove),!keys.empty());
EnableWindow(GetDlgItem(dialog,keySchemePrimary),keys.size()>1 && selection>0 && selection<keys.size());
EnableWindow(GetDlgItem(dialog,keySchemeAdd),keys.size()<filesKeysPerCommand);
}
void refreshFilesKeySchemes(HWND dialog,const FilesKeySettings &settings)
{
const auto choice=GetDlgItem(dialog,keySchemeChoice);
SendMessageW(choice,CB_RESETCONTENT,0,0);
for(const auto &scheme:settings.schemes)
SendMessageW(choice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(scheme.name.c_str()));
SendMessageW(choice,CB_SETCURSEL,settings.active,0);
EnableWindow(GetDlgItem(dialog,keySchemeCopy),settings.schemes.size()<filesKeySchemeLimit);
}
std::wstring filesKeyBarLabel(FilesKey command,const wchar_t *action)
{
return filesKeyHint(command)+L" "+action;
}
void refreshFilesKeyBar()
{
for(size_t i=0;i<std::size(keyBar);++i)
{
SetWindowTextW(commands[i],filesKeyBarLabel(keyBar[i].command,keyBar[i].label).c_str());
InvalidateRect(commands[i],nullptr,FALSE);
}
}
INT_PTR CALLBACK filesKeySchemesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &draft=*reinterpret_cast<FilesKeySchemeDraft*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
refreshFilesKeySchemes(dialog,draft.settings);
for(const auto &item:filesKeyCommands)
SendDlgItemMessageW(dialog,keySchemeCommand,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(item.label));
const auto index=keyIndex(draft.initial);
SendDlgItemMessageW(dialog,keySchemeCommand,LB_SETCURSEL,index,0);
refreshFilesKeyBindings(dialog,draft.settings.schemes[draft.settings.active],index);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
auto &draft=*reinterpret_cast<FilesKeySchemeDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
auto &settings=draft.settings;
auto &scheme=settings.schemes[settings.active];
const auto row=SendDlgItemMessageW(dialog,keySchemeCommand,LB_GETCURSEL,0,0);
if(row==LB_ERR) return FALSE;
const auto command=static_cast<size_t>(row);
const auto position=static_cast<size_t>(SendDlgItemMessageW(dialog,keySchemeBindings,LB_GETCURSEL,0,0));
auto &keys=scheme.keys[command];
switch(LOWORD(wp))
{
case keySchemeChoice:
if(HIWORD(wp)==CBN_SELCHANGE)
{
const auto chosen=SendDlgItemMessageW(dialog,keySchemeChoice,CB_GETCURSEL,0,0);
if(chosen!=CB_ERR) settings.active=static_cast<size_t>(chosen);
refreshFilesKeyBindings(dialog,settings.schemes[settings.active],command);
}
return TRUE;
case keySchemeCommand:
if(HIWORD(wp)==LBN_SELCHANGE) refreshFilesKeyBindings(dialog,scheme,command);
return TRUE;
case keySchemeBindings:
if(HIWORD(wp)==LBN_SELCHANGE)
EnableWindow(GetDlgItem(dialog,keySchemePrimary),position>0 && position<keys.size());
return TRUE;
case keySchemeCopy:
{
if(settings.schemes.size()>=filesKeySchemeLimit) return TRUE;
std::wstring name=scheme.name.substr(0,43)+L" copy";
FilesModalDialog copyName(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(616),dialog,
copyKeySchemeDialog,reinterpret_cast<LPARAM>(&name),false);
if(copyName.runModal()!=IDOK) return TRUE;
if(!validFilesKeySchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &other)
{ return sameFilesKeySchemeName(other.name,name); }))
{
showFilesNotice(dialog,L"Enter a unique name with no leading or trailing spaces.",L"Keyboard shortcuts");
return TRUE;
}
auto copy=scheme;
copy.name=std::move(name);
settings.schemes.push_back(std::move(copy));
settings.active=settings.schemes.size()-1;
refreshFilesKeySchemes(dialog,settings);
refreshFilesKeyBindings(dialog,settings.schemes.back(),command);
return TRUE;
}
case keySchemeReset:
{
FilesNoticeOptions notice;
notice.confirm=true;
notice.accept=L"&Reset";
const auto prompt=L"Reset all keys in “"+scheme.name+L"” to defaults?";
if(showFilesNotice(dialog,prompt.c_str(),L"Keyboard shortcuts",notice)!=IDYES) return TRUE;
scheme=defaultFilesKeyScheme(scheme.name);
refreshFilesKeyBindings(dialog,scheme,command);
return TRUE;
}
case keySchemeAdd:
{
if(keys.size()>=filesKeysPerCommand) return TRUE;
const auto binding=static_cast<WORD>(SendDlgItemMessageW(dialog,keySchemeCapture,HKM_GETHOTKEY,0,0));
if(const auto conflict=filesKeyConflict(scheme,command,binding);!conflict.empty())
{
showFilesNotice(dialog,conflict.c_str(),L"Keyboard shortcuts");
SetFocus(GetDlgItem(dialog,keySchemeCapture));
return TRUE;
}
keys.push_back(binding);
SendDlgItemMessageW(dialog,keySchemeCapture,HKM_SETHOTKEY,0,0);
refreshFilesKeyBindings(dialog,scheme,command,keys.size()-1);
return TRUE;
}
case keySchemeRemove:
if(position<keys.size())
{
keys.erase(keys.begin()+position);
refreshFilesKeyBindings(dialog,scheme,command,position<keys.size()?position:0);
}
return TRUE;
case keySchemePrimary:
if(position>0 && position<keys.size())
{
std::rotate(keys.begin(),keys.begin()+position,keys.begin()+position+1);
refreshFilesKeyBindings(dialog,scheme,command);
}
return TRUE;
case IDOK:
if(draft.pending) *draft.pending=settings;
else if(settings!=draft.base)
{
const OptionsWriteLock writeLock;
if(!writeLock.acquired())
{
showFilesNotice(dialog,L"Another window is saving Files settings. Try again.",L"Keyboard shortcuts");
return TRUE;
}
loadFilesKeySettings();
if(filesKeySettings!=draft.base && filesKeySettings!=settings)
{
showFilesNotice(dialog,L"Keyboard schemes were changed in another window. Reopen this dialog.",
L"Keyboard shortcuts");
return TRUE;
}
if(!writeFilesJsonPreference(filesKeySchemePreference,serializeFilesKeySettings(settings)))
{
showFilesNotice(dialog,L"Could not save the keyboard schemes.",L"Keyboard shortcuts");
return TRUE;
}
filesKeySettings=settings;
refreshFilesKeyBar();
showFileDetails(panels[active]);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
}
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
return FALSE;
}
void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending)
{
if(!pending) loadFilesKeySettings();
const auto &base=pending?*pending:filesKeySettings;
FilesKeySchemeDraft draft{base,base,initial,pending};
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(615),owner,
filesKeySchemesDialog,reinterpret_cast<LPARAM>(&draft),false);
dialog.runModal();
}
+177
View File
@@ -0,0 +1,177 @@
constexpr int filesLogSource=680,filesLogStatus=681,filesLogEntries=682,filesLogCopy=683,filesLogRefresh=684;
constexpr size_t filesLogEntryLimit=200,filesLogReadLimit=256*1024;
std::optional<unsigned> filesLogError(std::string_view message,std::string_view marker)
{
const auto last=message.rfind(marker);
if(last==message.npos) return {};
const auto value=message.substr(last+marker.size());
unsigned error{};
const auto parsed=std::from_chars(value.data(),value.data()+value.size(),error);
if(parsed.ec!=std::errc{} || parsed.ptr!=value.data()+value.size()) return {};
return error;
}
std::wstring safeFilesLogEntry(std::string_view line)
{
if(line.ends_with('\r')) line.remove_suffix(1);
std::wstring stamp;
constexpr std::string_view format="0000-00-00 00:00:00 ";
if(line.size()>=format.size())
{
bool valid=true;
for(size_t i=0;i<format.size();++i)
valid&=format[i]=='0'?(line[i]>='0' && line[i]<='9'):line[i]==format[i];
if(valid)
{
stamp=ks::wide(std::string(line.substr(0,format.size()-1)))+L" · ";
line.remove_prefix(format.size());
}
}
// Only fixed descriptions and numeric Windows result codes cross into the UI or clipboard.
std::wstring text;
std::optional<unsigned> error;
if(line=="LAN Files peer lookup failed: local KSwitcher window not found")
text=L"LAN peer lookup failed. KSwitcher is unavailable.";
else if(line.starts_with("LAN Files peer lookup failed: delivered="))
{
text=L"LAN peer lookup failed";
error=filesLogError(line,", Windows error=");
}
else if(line=="LAN Files drive query failed: unexpected error")
text=L"LAN drive query failed. Unexpected error.";
else if(line.starts_with("LAN Files drive query for "))
{
text=L"LAN drive query failed";
error=filesLogError(line,") failed: Windows error ");
if(error==WSAETIMEDOUT) text=L"LAN drive query timed out";
}
else text=L"Diagnostic entry · details hidden";
if(error && *error) text+=L" (Windows error "+std::to_wstring(*error)+L")";
return stamp+text;
}
std::vector<std::wstring> recentFilesLogEntries(const ks::Bytes &bytes)
{
std::vector<std::wstring> entries;
if(bytes.empty()) return entries;
const std::string_view text(reinterpret_cast<const char*>(bytes.data()),bytes.size());
auto end=text.size();
while(end && entries.size()<filesLogEntryLimit)
{
if(text[end-1]=='\n') --end;
const auto split=end?text.rfind('\n',end-1):text.npos;
const auto begin=split==text.npos?0:split+1;
const auto row=text.substr(begin,end-begin);
if(!row.empty() && row!="\r") entries.push_back(safeFilesLogEntry(row));
end=begin;
}
return entries;
}
struct FilesLogDraft
{
std::vector<std::wstring> entries;
};
void refreshFilesLog(HWND dialog,FilesLogDraft &draft)
{
const bool previous=SendDlgItemMessageW(dialog,filesLogSource,CB_GETCURSEL,0,0)==1;
const auto list=GetDlgItem(dialog,filesLogEntries);
SendMessageW(list,LB_RESETCONTENT,0,0);
SendMessageW(list,LB_SETHORIZONTALEXTENT,0,0);
draft.entries.clear();
try
{
if(const auto data=ks::readActiveLogTail(previous,filesLogReadLimit))
{
draft.entries=recentFilesLogEntries(*data);
SetDlgItemTextW(dialog,filesLogStatus,draft.entries.empty()?L"The Files log has no entries.":
L"Most recent first. Select an entry to copy its timestamp and description.");
}
else SetDlgItemTextW(dialog,filesLogStatus,previous?L"No previous Files log is available yet.":
L"No Files log yet. Entries appear when Write log is enabled and Files records a problem.");
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,filesLogStatus,L"Could not read the Files log. Use Refresh to try again.");
}
int width=0;
const auto dc=GetDC(list);
const auto font=reinterpret_cast<HFONT>(SendMessageW(list,WM_GETFONT,0,0));
const auto oldFont=dc && font?SelectObject(dc,font):nullptr;
for(const auto &entry:draft.entries)
{
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(entry.c_str()));
if(dc)
{
SIZE extent{};
GetTextExtentPoint32W(dc,entry.c_str(),static_cast<int>(entry.size()),&extent);
width=std::max(width,static_cast<int>(extent.cx)+12);
}
}
if(oldFont) SelectObject(dc,oldFont);
if(dc) ReleaseDC(list,dc);
if(width) SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0);
if(!draft.entries.empty()) SendMessageW(list,LB_SETCURSEL,0,0);
EnableWindow(GetDlgItem(dialog,filesLogCopy),!draft.entries.empty());
}
LRESULT CALLBACK filesLogListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_KEYDOWN && wp=='C' && (GetKeyState(VK_CONTROL)&0x8000) &&
!((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
{
if(!(lp&(1LL<<30))) SendMessageW(GetParent(list),WM_COMMAND,MAKEWPARAM(filesLogCopy,BN_CLICKED),0);
return 0;
}
return DefSubclassProc(list,message,wp,lp);
}
INT_PTR CALLBACK filesLogDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &draft=*reinterpret_cast<FilesLogDraft*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
for(const auto name:{L"Current",L"Previous"})
SendDlgItemMessageW(dialog,filesLogSource,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
SendDlgItemMessageW(dialog,filesLogSource,CB_SETCURSEL,0,0);
SetWindowSubclass(GetDlgItem(dialog,filesLogEntries),filesLogListKeys,1,0);
refreshFilesLog(dialog,draft);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
auto &draft=*reinterpret_cast<FilesLogDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(LOWORD(wp)==filesLogRefresh || (LOWORD(wp)==filesLogSource && HIWORD(wp)==CBN_SELCHANGE))
{
refreshFilesLog(dialog,draft);
return TRUE;
}
if(LOWORD(wp)==filesLogCopy)
{
const auto row=SendDlgItemMessageW(dialog,filesLogEntries,LB_GETCURSEL,0,0);
if(row>=0 && static_cast<size_t>(row)<draft.entries.size())
{
if(copyFilesText(dialog,draft.entries[row],L"Could not copy the Files log entry."))
SetDlgItemTextW(dialog,filesLogStatus,L"Entry copied.");
else SetDlgItemTextW(dialog,filesLogStatus,L"Could not copy the Files log entry.");
}
return TRUE;
}
return FALSE;
}
void showFilesLog(HWND owner)
{
FilesLogDraft draft;
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(619),owner,filesLogDialog,
reinterpret_cast<LPARAM>(&draft),false,false);
dialog.runModal();
}
+605 -229
View File
File diff suppressed because it is too large. Load diff
+283 -92
View File
@@ -1,28 +1,34 @@
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
optionsImport=525,optionsExport=526,
optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372;
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;
comparisonChooseColor=412,comparisonColorValue=413,comparisonKeySchemesButton=415;
constexpr int comparisonControls[]{comparisonFontLabel,comparisonChooseFont,410,comparisonColorCombo,
comparisonChooseColor,comparisonColorValue,414,comparisonShortcutControl};
comparisonChooseColor,comparisonColorValue,comparisonKeySchemesButton};
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 };
constexpr const wchar_t *panelSectionNames[]{L"Panel layout",L"Wide panel columns",L"Status line columns"};
constexpr int panelLayoutControls[]{506,273,507,274};
constexpr int rightClickMarksControl=520, driveButtonsControl=521, compactLayoutControl=522;
constexpr int panelLayoutControls[]{506,273,507,274,rightClickMarksControl,driveButtonsControl,compactLayoutControl,523};
constexpr int wideColumnControls[]{275,276,201,202,204};
constexpr int statusColumnControls[]{277,203,205,206,207,208};
constexpr int colorOptionControls[]{279,280};
constexpr int appearanceControls[]{281,282};
enum AppearanceSection { Font, DialogFrame };
enum AppearanceSection { Font, DialogFrame, SystemThemes };
constexpr int terminalScaleSection=1,areaScaleLabel=528,areaScaleControl=529;
constexpr int systemLightChoice=531,systemDarkChoice=533;
constexpr int systemThemeControls[]{530,systemLightChoice,532,systemDarkChoice,535};
constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307;
constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding};
constexpr int restoreDocumentsControl=524;
constexpr int textTabWidth=357,textLineEnding=359,
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368;
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368,textRenameScheme=534;
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme};
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme,textRenameScheme};
constexpr int editingControls[]{354,355,358,textLineEnding};
constexpr int markdownSection=1,markdownWidth=374,markdownFamily=376,markdownChoose=377,markdownSize=379;
constexpr int markdownControls[]{373,markdownWidth,375,markdownFamily,markdownChoose,378,markdownSize};
@@ -51,7 +57,7 @@ constexpr struct
{innerFramePadding,&DialogFramePadding::inner,maxDialogFramePadding},
{rowTextPadding,&DialogFramePadding::rowText,maxDialogRowTextPadding}};
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight };
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight, BottomLeft };
struct OptionsControl
{
int id;
@@ -67,6 +73,9 @@ struct PanelProperty
};
constexpr PanelProperty panelProperties[]{
{PanelLayout,273,L"Left panel mode",defaultWide?1u:0u},{PanelLayout,274,L"Right panel mode",defaultWide?1u:0u},
{PanelLayout,rightClickMarksControl,L"Mark items with the right mouse button",0},
{PanelLayout,driveButtonsControl,L"Show drive buttons",0},
{PanelLayout,compactLayoutControl,L"Compact commander layout",0},
{WideColumns,201,L"Size column width",defaultSizeWidth},
{WideColumns,202,L"Align file extensions",defaultAlignExtensions},
{WideColumns,204,L"Align folder extensions",defaultAlignFolders},
@@ -101,16 +110,18 @@ struct OptionsBaseline
DialogFramePadding padding=dialogFramePadding;
std::array<COLORREF,ColorCount> palette=colors;
std::vector<FileStyle> styles=fileStyles;
std::array<WORD,2> keys=commandHistoryKeys;
bool remoteTerminal=ks::lan::remoteTerminalAllowed();
bool remoteHibernate=ks::lan::remoteHibernateAllowed();
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
bool mouseMarks=rightClickMarks, drives=showDriveButtons, compact=compactLayout;
bool restoreLocal=restoreDocuments;
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
ks::files::TextSettings text=ks::files::loadTextPreferences();
ComparisonAppearance comparison=readComparisonAppearance();
WORD compareShortcut=comparisonShortcut;
FilesKeySettings keySettings=filesKeySettings;
ks::files::AppearanceScales scales=readAreaScales();
};
struct OptionsDraft
@@ -118,6 +129,8 @@ struct OptionsDraft
OptionsBaseline baseline;
ks::files::TextSettings text=baseline.text;
ComparisonAppearance comparison=baseline.comparison;
FilesKeySettings keySettings=baseline.keySettings;
ks::files::AppearanceScales scales=baseline.scales;
HWND filesWindow{};
LOGFONTW font=displayFont;
int points=fontPoints;
@@ -133,13 +146,14 @@ struct OptionsDraft
HTREEITEM wideColumnsNode{},markdownNode{};
RECT initialClient{};
UINT initialDpi=96;
OptionsControl controls[8]{
OptionsControl controls[10]{
{optionsTree,OptionsAnchor::StretchHeight},
{optionsTitle,OptionsAnchor::StretchWidth},
{275,OptionsAnchor::StretchWidth},{277,OptionsAnchor::StretchWidth},
{281,OptionsAnchor::StretchWidth},
{IDOK,OptionsAnchor::BottomRight},{IDCANCEL,OptionsAnchor::BottomRight},
{optionsApply,OptionsAnchor::BottomRight}};
{optionsApply,OptionsAnchor::BottomRight},
{optionsImport,OptionsAnchor::BottomLeft},{optionsExport,OptionsAnchor::BottomLeft}};
};
@@ -157,19 +171,6 @@ bool optionsFontChanged(const OptionsDraft &draft)
_wcsicmp(pending.lfFaceName,applied.lfFaceName)!=0;
}
struct OptionsWriteLock
{
HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite");
DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED;
bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; }
~OptionsWriteLock()
{
if(acquired()) ReleaseMutex(mutex);
if(mutex) CloseHandle(mutex);
}
};
void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
{
BOOL valid{};
@@ -181,13 +182,15 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
const bool dirty=!valid || draft.markdownError || width!=base.width ||
panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] ||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives ||
checked(compactLayoutControl)!=base.compact || checked(restoreDocumentsControl)!=base.restoreLocal ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
checked(optionsRemoteTerminal)!=base.remoteTerminal ||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
draft.text!=base.text || draft.comparison!=base.comparison ||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0)!=base.compareShortcut;
draft.text!=base.text || draft.comparison!=base.comparison || draft.keySettings!=base.keySettings ||
draft.scales!=base.scales;
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
}
@@ -245,6 +248,7 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft)
case OptionsAnchor::StretchWidth: width+=dx;break;
case OptionsAnchor::StretchHeight: height+=dy;break;
case OptionsAnchor::BottomRight: x+=dx;y+=dy;break;
case OptionsAnchor::BottomLeft: y+=dy;break;
}
SetWindowPos(GetDlgItem(dialog,control.id),nullptr,x,y,width,height,
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW);
@@ -280,19 +284,22 @@ void populateTextSchemes(HWND dialog,const ks::files::TextSettings &settings)
};
add(L"Custom");
for(const auto name:ks::files::textPaletteNames) add(name);
add(L"System (Windows)");
for(const auto &scheme:settings.schemes) add(scheme.name.c_str());
}
size_t currentTextScheme(const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
{
for(size_t index=0;index<std::size(ks::files::textPalettes);++index)
const auto presets=std::size(ks::files::textPalettes);
if(profile.scheme==ks::files::systemTextScheme) return presets+1;
for(size_t index=0;index<presets;++index)
if(profile.scheme==ks::files::textPaletteNames[index] && profile.colors==ks::files::textPalettes[index])
return index+1;
for(size_t index=0;index<settings.schemes.size();++index)
{
const auto &scheme=settings.schemes[index];
if(profile.scheme==scheme.name && profile.colors==scheme.colors)
return std::size(ks::files::textPalettes)+index+1;
return presets+index+2;
}
return 0;
}
@@ -303,6 +310,13 @@ INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
SendDlgItemMessageW(dialog,100,EM_SETLIMITTEXT,ks::files::maxTextPaletteName,0);
const auto &name=*reinterpret_cast<const std::wstring*>(lp);
if(!name.empty())
{
SetWindowTextW(dialog,L"Rename color scheme");
SetDlgItemTextW(dialog,100,name.c_str());
SetDlgItemTextW(dialog,IDOK,L"Rename");
}
groupDialogButtons(dialog,{IDOK,IDCANCEL},true);
return TRUE;
}
@@ -320,13 +334,22 @@ INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files::TextPreferences &profile)
bool reservedTextSchemeName(const std::wstring &name)
{
return sameSchemeName(name,L"Custom") || sameSchemeName(name,L"System (Windows)") ||
sameSchemeName(name,ks::files::systemTextScheme) ||
std::any_of(std::begin(ks::files::textPaletteNames),std::end(ks::files::textPaletteNames),
[&](const wchar_t *preset){return sameSchemeName(name,preset);});
}
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,bool edit)
{
auto &profile=settings.profiles[edit];
const auto palette=ks::files::resolvedTextProfile(settings,edit).colors;
std::wstring name;
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog,
reinterpret_cast<LPARAM>(&name))!=IDOK) return;
if(sameSchemeName(name,L"Custom") || std::any_of(std::begin(ks::files::textPaletteNames),
std::end(ks::files::textPaletteNames),[&](const wchar_t *preset){return sameSchemeName(name,preset);}))
if(reservedTextSchemeName(name))
{
showFilesNotice(dialog,L"Choose a different name for your color scheme.",L"Save color scheme");
return;
@@ -337,7 +360,7 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
{
if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",
{.confirm=true,.tone=FilesNoticeTone::neutral})!=IDYES) return;
existing->colors=profile.colors;
existing->colors=palette;
profile.scheme=existing->name;
}
else
@@ -347,18 +370,44 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
showFilesNotice(dialog,L"The color scheme list is full.",L"Save color scheme");
return;
}
settings.schemes.push_back({name,profile.colors});
settings.schemes.push_back({name,palette});
profile.scheme=std::move(name);
}
profile.colors=palette;
populateTextSchemes(dialog,settings);
}
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
void renameTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
{
const auto scheme=std::ranges::find_if(settings.schemes,[&](const auto &candidate)
{ return sameSchemeName(profile.scheme,candidate.name.c_str()); });
if(scheme==settings.schemes.end()) return;
auto name=scheme->name;
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog,
reinterpret_cast<LPARAM>(&name))!=IDOK || name==scheme->name) return;
if(reservedTextSchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &candidate)
{return &candidate!=&*scheme && sameSchemeName(name,candidate.name.c_str());}))
{
showFilesNotice(dialog,L"Choose a unique name for the color scheme.",L"Rename color scheme");
return;
}
for(auto &document:settings.profiles)
if(sameSchemeName(document.scheme,scheme->name.c_str())) document.scheme=name;
for(auto &role:settings.systemThemes)
if(sameSchemeName(role,scheme->name.c_str())) role=name;
scheme->name=std::move(name);
populateTextSchemes(dialog,settings);
}
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,bool edit)
{
const auto profile=ks::files::resolvedTextProfile(settings,edit);
for(const auto &check:textChecks) CheckDlgButton(dialog,check.id,profile.*check.value?BST_CHECKED:BST_UNCHECKED);
SendDlgItemMessageW(dialog,textTabWidth,CB_SETCURSEL,profile.tabWidth-1,0);
SendDlgItemMessageW(dialog,textLineEnding,CB_SETCURSEL,profile.lineEnding,0);
SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,currentTextScheme(settings,profile),0);
const auto selected=currentTextScheme(settings,profile);
SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,selected,0);
EnableWindow(GetDlgItem(dialog,textRenameScheme),selected>=std::size(ks::files::textPalettes)+2);
refreshTextColor(dialog,profile);
}
@@ -393,12 +442,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
if(const auto check=std::find_if(std::begin(textChecks),std::end(textChecks),
[id](const auto &entry){return entry.id==id;});check!=std::end(textChecks))
profile.*check->value=IsDlgButtonChecked(dialog,id)==BST_CHECKED;
else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,profile);
else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,draft.page==TextEditor);
else if(id==textRenameScheme) renameTextSchemeDraft(dialog,draft.text,profile);
else if(id==textChangeColor)
{
const auto index=row(textColor);
if(index>=0 && static_cast<size_t>(index)<profile.colors.size())
choosePanelColor(dialog,profile.colors[index],draft.custom.data());
{
auto palette=ks::files::resolvedTextProfile(draft.text,draft.page==TextEditor).colors;
if(choosePanelColor(dialog,palette[index],draft.custom.data()))
{
profile.colors=palette;
profile.scheme.clear();
}
}
}
else if(HIWORD(command)==CBN_SELCHANGE)
{
@@ -410,15 +467,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
case textTabWidth: profile.tabWidth=static_cast<int>(selected)+1; break;
case textLineEnding: profile.lineEnding=static_cast<int>(selected); break;
case textTheme:
if(selected==0) profile.scheme.clear();
if(selected==0)
{
profile.colors=ks::files::resolvedTextProfile(draft.text,draft.page==TextEditor).colors;
profile.scheme.clear();
}
else if(const auto scheme=static_cast<size_t>(selected-1);scheme<std::size(ks::files::textPalettes))
{
profile.scheme=ks::files::textPaletteNames[scheme];
profile.colors=ks::files::textPalettes[scheme];
}
else if(scheme==std::size(ks::files::textPalettes)) profile.scheme=ks::files::systemTextScheme;
else
{
const auto index=scheme-std::size(ks::files::textPalettes);
const auto index=scheme-std::size(ks::files::textPalettes)-1;
if(index>=draft.text.schemes.size()) return false;
profile.scheme=draft.text.schemes[index].name;
profile.colors=draft.text.schemes[index].colors;
@@ -428,7 +490,7 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
}
}
else return false;
showTextOptions(dialog,draft.text,profile);
showTextOptions(dialog,draft.text,draft.page==TextEditor);
updateOptionsApply(dialog,draft);
return true;
}
@@ -447,6 +509,65 @@ void showComparisonOptions(HWND dialog,const ComparisonAppearance &appearance)
SetDlgItemTextW(dialog,comparisonColorValue,hex);
}
std::optional<AppearanceArea> optionsScaleArea(int page,int section)
{
if(page==Appearance && section==Font) return AppearanceArea::panels;
if(page==CommandLine && section==terminalScaleSection) return AppearanceArea::terminal;
if(page==TextViewer) return section==markdownSection?AppearanceArea::markdown:AppearanceArea::viewer;
if(page==TextEditor) return AppearanceArea::editor;
if(page==CompareFiles) return AppearanceArea::comparison;
return {};
}
void showAreaScale(HWND dialog,const OptionsDraft &draft,std::optional<AppearanceArea> area)
{
const auto label=GetDlgItem(dialog,areaScaleLabel);
const auto field=GetDlgItem(dialog,areaScaleControl);
ShowWindow(label,area?SW_SHOW:SW_HIDE);
ShowWindow(field,area?SW_SHOW:SW_HIDE);
if(!area) return;
const auto index=ks::files::appearanceIndex(*area);
constexpr const wchar_t *labels[]{L"&Panel scale",L"&Viewer scale",L"&Editor scale",L"&Markdown scale",
L"&Terminal scale",L"&Comparison scale"};
constexpr int top[]{77,232,232,124,29,155};
SetWindowTextW(label,labels[index]);
RECT labelBox{131,top[index]+3,0,0},fieldBox{257,top[index],0,0};
MapDialogRect(dialog,&labelBox);
MapDialogRect(dialog,&fieldBox);
const auto flags=SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE;
SetWindowPos(label,nullptr,labelBox.left,labelBox.top,0,0,flags);
SetWindowPos(field,nullptr,fieldBox.left,fieldBox.top,0,0,flags);
SendMessageW(field,CB_RESETCONTENT,0,0);
const auto selected=draft.scales[index];
for(unsigned percent=ks::files::minAppearanceScale;percent<=ks::files::maxAppearanceScale;++percent)
{
if(percent%5 && percent!=selected) continue;
const auto caption=std::to_wstring(percent)+L"%";
const auto row=SendMessageW(field,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(caption.c_str()));
if(row<0) continue;
SendMessageW(field,CB_SETITEMDATA,row,percent);
if(percent==selected) SendMessageW(field,CB_SETCURSEL,row,0);
}
}
void showSystemThemeRoles(HWND dialog,const ks::files::TextSettings &settings)
{
constexpr int controls[]{systemLightChoice,systemDarkChoice};
for(size_t role=0;role<std::size(controls);++role)
{
const auto control=GetDlgItem(dialog,controls[role]);
SendMessageW(control,CB_RESETCONTENT,0,0);
const auto add=[&](const wchar_t *name)
{
const auto row=SendMessageW(control,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
if(row>=0 && sameSchemeName(settings.systemThemes[role],name))
SendMessageW(control,CB_SETCURSEL,row,0);
};
for(const auto name:ks::files::textPaletteNames) add(name);
for(const auto &scheme:settings.schemes) add(scheme.name.c_str());
}
}
void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
{
draft.page=page;
@@ -461,7 +582,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
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";
page==CommandLine?(section==terminalScaleSection?L"Terminal appearance":L"Command history"):
section==SystemThemes?L"System themes":section==DialogFrame?L"Dialog frame":L"Font";
}
SetDlgItemTextW(dialog,optionsTitle,title);
const auto show=[&](auto &controls,bool visible)
@@ -489,6 +611,9 @@ 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(systemThemeControls,page==Appearance && section==SystemThemes);
if(page==Appearance && section==SystemThemes) showSystemThemeRoles(dialog,draft.text);
showAreaScale(dialog,draft,optionsScaleArea(page,section));
show(comparisonControls,page==CompareFiles);
if(page==CompareFiles) showComparisonOptions(dialog,draft.comparison);
show(dialogFrameControls,page==Appearance && section==DialogFrame);
@@ -497,17 +622,19 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
for(const auto &option:frameOptions)
SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0);
}
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
constexpr int commandLineControls[]{321,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
show(commandLineControls,page==CommandLine && section==0);
show(markdownControls,markdown);
show(textControls,textOptionsPage(page) && !markdown);
ShowWindow(GetDlgItem(dialog,restoreDocumentsControl),page==TextViewer && !markdown?SW_SHOW:SW_HIDE);
show(editingControls,page==TextEditor);
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,page==TextEditor);
const bool fileTypes=page==PanelColors && section==fileStyleSection;
constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState};
show(fileStyleControls,fileTypes);
const auto preview=GetDlgItem(dialog,fileStylePreview);
ShowWindow(preview,page>=0 && page<CommandLine && section>=0?SW_SHOW:SW_HIDE);
const bool panelPreview=page>=0 && page<CommandLine && section>=0 && !(page==Appearance && section==SystemThemes);
ShowWindow(preview,panelPreview?SW_SHOW:SW_HIDE);
layoutOptionsPreview(dialog);
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
show(colorOptionControls,page==PanelColors && section>=0 && !fileTypes);
@@ -600,27 +727,35 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
addSection(L"File type styles",fileStyleSection,extensionMatches || matches(L"System and hidden") ||
matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground"));
}
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==CommandLine)
{
addSection(L"Command history",0,matches(L"Previous command") || matches(L"Keyboard shortcuts") ||
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"));
addSection(L"Terminal appearance",terminalScaleSection,matches(L"Terminal scale"));
}
else if(page==CompareFiles)
addSection(L"Font and colors",0,matches(L"Compare files shortcut") || std::any_of(std::begin(comparisonColorNames),
addSection(L"Font and colors",0,matches(L"Comparison scale") || matches(L"Compare files shortcut") || matches(L"Keyboard shortcuts") || std::any_of(std::begin(comparisonColorNames),
std::end(comparisonColorNames),matches));
else if(textOptionsPage(page))
{
const bool propertyMatches=matches(L"Tab width") ||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Customize colors") ||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Rename scheme") || matches(L"Customize colors") ||
matches(page==TextEditor?L"Editor scale":L"Viewer scale") ||
(page==TextEditor && matches(L"Line endings for new lines")) ||
(page==TextViewer && matches(L"Restore local Viewer and Editor windows after restart")) ||
std::any_of(std::begin(textChecks),std::end(textChecks),[&](const auto &check)
{return (page==TextEditor || check.id<354) && matches(check.name);}) ||
std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches);
addSection(page==TextEditor?L"Editing and appearance":L"Viewing and appearance",0,propertyMatches);
if(page==TextViewer) addSection(L"Markdown",markdownSection,
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size"));
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size") ||
matches(L"Markdown scale"));
}
else
{
addSection(L"Font",Font,matches(L"Display font"));
addSection(L"Font",Font,matches(L"Display font") || matches(L"Panel scale"));
addSection(L"System themes",SystemThemes,matches(L"Light mode palette") || matches(L"Dark mode palette"));
addSection(L"Dialog frame",DialogFrame,
matches(L"Outer padding") || matches(L"Inner padding") || matches(L"Row text padding"));
}
@@ -631,6 +766,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
if(!first) SetDlgItemTextW(dialog,optionsTitle,L"No matching settings");
}
#include "files_options_transfer.inl"
INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
@@ -661,8 +798,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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)
@@ -679,9 +814,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
showPanelModeOptions(dialog);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
@@ -739,6 +877,29 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
case optionsSearch:
if(HIWORD(wp)==EN_CHANGE) filterOptions(dialog,*draft);
return TRUE;
case areaScaleControl:
if(HIWORD(wp)==CBN_SELCHANGE)
if(const auto area=optionsScaleArea(draft->page,draft->section))
{
const auto row=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETCURSEL,0,0);
if(row>=0)
{
const auto percent=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETITEMDATA,row,0);
if(percent>=ks::files::minAppearanceScale && percent<=ks::files::maxAppearanceScale)
draft->scales[ks::files::appearanceIndex(*area)]=static_cast<unsigned>(percent);
}
updateOptionsApply(dialog,*draft);
}
return TRUE;
case systemLightChoice: case systemDarkChoice:
if(HIWORD(wp)==CBN_SELCHANGE)
{
wchar_t name[ks::files::maxTextPaletteName+1]{};
GetDlgItemTextW(dialog,LOWORD(wp),name,std::size(name));
if(ks::files::namedTextPalette(draft->text,name)) draft->text.systemThemes[LOWORD(wp)==systemDarkChoice]=name;
updateOptionsApply(dialog,*draft);
}
return TRUE;
case 279:
if(draft->page==PanelColors && draft->section>=0 && draft->section<ColorCount)
{
@@ -846,14 +1007,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
return TRUE;
case optionsReset:
if(draft->page==allOptions) draft->scales=ks::files::defaultAppearanceScales;
else if(const auto area=optionsScaleArea(draft->page,draft->section))
draft->scales[ks::files::appearanceIndex(*area)]=100;
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==SystemThemes)))
draft->text.systemThemes=ks::files::TextSettings{}.systemThemes;
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);
CheckDlgButton(dialog,optionsRemoteTerminal,BST_UNCHECKED);
CheckDlgButton(dialog,optionsRemoteHibernate,BST_UNCHECKED);
CheckDlgButton(dialog,optionsRemoteUpdate,BST_UNCHECKED);
@@ -868,13 +1030,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(draft->page==allOptions || (draft->page==PanelColors &&
(draft->section<0 || draft->section==fileStyleSection)))
draft->styles=defaultFileStyles;
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=DialogFrame))
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==Font)))
{
draft->font=defaultFilesFont();
draft->points=defaultFontPoints;
}
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font))
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==DialogFrame)))
draft->framePadding=defaultDialogFramePadding;
if(draft->page==allOptions || (draft->page==TextViewer && draft->section!=markdownSection))
CheckDlgButton(dialog,restoreDocumentsControl,BST_UNCHECKED);
if(draft->page==allOptions || textOptionsPage(draft->page))
for(int page=TextViewer;page<=TextEditor;++page)
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
@@ -898,25 +1062,21 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
case 201:
case 202: case 203: case 204: case 205: case 206: case 207: case 208:
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
case 273: case 274: case rightClickMarksControl: case driveButtonsControl: case compactLayoutControl:
case restoreDocumentsControl:
case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
updateOptionsApply(dialog,*draft);
return TRUE;
case 321: case 323: case comparisonShortcutControl:
case 321: case comparisonKeySchemesButton:
editFilesKeySchemes(dialog,LOWORD(wp)==321?FilesKey::Previous:FilesKey::Compare,&draft->keySettings);
updateOptionsApply(dialog,*draft);
return TRUE;
case optionsImport: case optionsExport:
transferFilesOptions(dialog,*draft,LOWORD(wp)==optionsImport);
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"");
@@ -944,6 +1104,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
const auto &base=draft->baseline;
const bool keysChanged=draft->keySettings!=base.keySettings;
loadFilesKeySettings();
if(keysChanged && filesKeySettings!=base.keySettings && filesKeySettings!=draft->keySettings)
{
showFilesNotice(dialog,L"Keyboard schemes changed in another window. Reopen Options before editing them again.",
L"Keyboard shortcuts");
return TRUE;
}
const auto storedComparison=readComparisonAppearance();
const bool comparisonChanged=draft->comparison!=base.comparison;
if(comparisonChanged && storedComparison!=base.comparison && storedComparison!=draft->comparison)
@@ -953,7 +1121,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
const bool textChanged=draft->text!=base.text;
auto textSettings=ks::files::loadTextPreferences();
const auto storedText=ks::files::loadTextPreferences();
auto textSettings=storedText;
if(draft->text.markdown!=base.text.markdown)
{
if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown)
@@ -985,14 +1154,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
textSettings.schemes=draft->text.schemes;
}
auto keys=optionHistoryKeys(dialog);
loadCommandHistoryKeys();
for(size_t i=0;i<keys.size();++i)
if(keys[i]==base.keys[i]) keys[i]=commandHistoryKeys[i];
if(!validHistoryKeys(keys))
if(draft->text.systemThemes!=base.text.systemThemes)
{
showFilesNotice(dialog,L"Choose distinct shortcuts using Ctrl or Alt that are free in Files.",L"Command history");
return TRUE;
if(textSettings.systemThemes!=base.text.systemThemes && textSettings.systemThemes!=draft->text.systemThemes)
{
showFilesNotice(dialog,L"System theme choices changed in another window. Reopen Options before editing them again.",
L"System themes");
return TRUE;
}
textSettings.systemThemes=draft->text.systemThemes;
}
const bool stylesChanged=draft->styles!=base.styles;
loadFileStyles();
@@ -1034,15 +1204,22 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
}
if(keysChanged && !writeFilesJsonPreference(filesKeySchemePreference,serializeFilesKeySettings(draft->keySettings)))
{
if(textChanged)
try {ks::files::saveTextPreferences(storedText);}
catch(const std::exception &) {setStatus(L"Could not restore earlier text settings.",true);}
if(comparisonChanged) saveComparisonAppearance(storedComparison);
if(fontChanged) applyFont(owner,base.font,base.points);
if(stylesChanged) saveFileStyles(fileStyles);
showFilesNotice(dialog,L"Could not save the keyboard schemes.",L"Keyboard shortcuts");
return TRUE;
}
const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial)
{
if(value!=initial) savePreference(name,value);
};
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
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);
@@ -1050,6 +1227,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
saveChanged(L"AlignExtensions",checked(202),base.extensions);
saveChanged(L"AlignFolders",checked(204),base.folders);
saveChanged(L"ShowDetails",checked(203),base.details);
saveChanged(rightClickMarksKey,checked(rightClickMarksControl),base.mouseMarks);
saveChanged(driveButtonsKey,checked(driveButtonsControl),base.drives);
saveChanged(compactLayoutKey,checked(compactLayoutControl),base.compact);
saveChanged(restoreDocumentsKey,checked(restoreDocumentsControl),base.restoreLocal);
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
const auto initialFields=fields;
for(int i=0;i<4;++i)
@@ -1063,6 +1244,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
saveChanged(dialogFrameOuterKey,draft->framePadding.outer,base.padding.outer);
saveChanged(dialogFrameInnerKey,draft->framePadding.inner,base.padding.inner);
saveChanged(dialogRowTextKey,draft->framePadding.rowText,base.padding.rowText);
for(size_t i=0;i<draft->scales.size();++i) saveChanged(areaScaleKeys[i],draft->scales[i],base.scales[i]);
if(fontChanged)
{
savePreference(L"FontPoints",fontPoints);
@@ -1074,6 +1256,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(mode!=base.modes[index]) savePanelMode(index,mode);
}
loadFilesPreferences(owner);
refreshFilesKeyBar();
notifyFilesPreferences(owner);
const auto dialogOwner=GetWindow(dialog,GW_OWNER);
if(dialogOwner!=owner)
@@ -1081,6 +1264,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
draft->baseline=OptionsBaseline{};
draft->text=draft->baseline.text;
draft->comparison=draft->baseline.comparison;
draft->keySettings=draft->baseline.keySettings;
draft->scales=draft->baseline.scales;
showMarkdownOptions(dialog,draft->text.markdown);
populateTextSchemes(dialog,draft->text);
draft->font=displayFont;
@@ -1092,10 +1277,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
showPanelModeOptions(dialog);
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());
@@ -1113,12 +1300,13 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return FALSE;
}
void runOptions(HWND owner,int page)
void runOptions(HWND owner,int page,int section=0,bool restoreLocation=true)
{
loadFilesKeySettings();
OptionsDraft draft;
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
const DWORD initial=static_cast<DWORD>((page<<8)|1);
const auto saved=preference(optionsLocationKey,initial);
const DWORD initial=static_cast<DWORD>((page<<8)|(section+1));
const auto saved=restoreLocation?preference(optionsLocationKey,initial):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;
@@ -1135,7 +1323,10 @@ void editOptions(HWND owner)
SetFocus(panels[active].list);
}
void editTextOptions(HWND owner,bool edit)
void editFilesAppearance(HWND owner,AppearanceArea area)
{
runOptions(owner,edit?TextEditor:TextViewer);
constexpr int pages[]{Appearance,TextViewer,TextEditor,TextViewer,CommandLine,CompareFiles};
constexpr int sections[]{Font,0,0,markdownSection,terminalScaleSection,0};
const auto index=ks::files::appearanceIndex(area);
runOptions(owner,pages[index],sections[index],false);
}
+2 -1
View File
@@ -7,7 +7,8 @@ void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDra
const auto dpi=GetDpiForWindow(item.hwndItem);
const auto px=[&](int value){return MulDiv(value,dpi,96);};
auto font=draft.font;
font.lfHeight=-MulDiv(draft.points,dpi,720);
const auto panelScale=draft.scales[ks::files::appearanceIndex(AppearanceArea::panels)];
font.lfHeight=-MulDiv(ks::files::scaledAppearanceSize(draft.points,panelScale),dpi,720);
font.lfWidth=0;
const auto previewFont=CreateFontIndirectW(&font);
SelectObject(dc,previewFont?previewFont:mono);
+275
View File
@@ -0,0 +1,275 @@
constexpr struct
{
const char *id;
const wchar_t *label;
int control;
} filesTransferGroups[]{
{"colors",L"&Colors and file styles",621},
{"panels",L"&Panel modes and layout",622},
{"keys",L"&Keyboard schemes",623},
};
constexpr struct
{
const char *id;
int control;
bool OptionsBaseline::*value;
} transferablePanelChecks[]{
{"alignFileExtensions",202,&OptionsBaseline::extensions},
{"alignFolderExtensions",204,&OptionsBaseline::folders},
{"showDetails",203,&OptionsBaseline::details},
{"rightClickMarks",rightClickMarksControl,&OptionsBaseline::mouseMarks},
{"driveButtons",driveButtonsControl,&OptionsBaseline::drives},
{"compactLayout",compactLayoutControl,&OptionsBaseline::compact},
};
struct FilesTransferDraft
{
bool importing{};
Json groups=Json::object();
std::array<bool,std::size(filesTransferGroups)> chosen{};
};
INT_PTR CALLBACK filesTransferDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &draft=*reinterpret_cast<FilesTransferDraft*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
SetWindowTextW(dialog,draft.importing?L"Import Files settings":L"Export Files settings");
SetDlgItemTextW(dialog,624,draft.importing?
L"Choose groups to load into Options. Apply saves the changes.":
L"Choose groups to export from your saved Files settings.");
SetDlgItemTextW(dialog,IDOK,draft.importing?L"&Load":L"&Export");
for(const auto &group:filesTransferGroups)
{
const bool available=draft.groups.contains(group.id);
const auto control=GetDlgItem(dialog,group.control);
SetWindowTextW(control,group.label);
ShowWindow(control,available?SW_SHOW:SW_HIDE);
CheckDlgButton(dialog,group.control,available?BST_CHECKED:BST_UNCHECKED);
}
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
auto &draft=*reinterpret_cast<FilesTransferDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
for(size_t i=0;i<draft.chosen.size();++i)
{
const auto &group=filesTransferGroups[i];
draft.chosen[i]=draft.groups.contains(group.id) && IsDlgButtonChecked(dialog,group.control)==BST_CHECKED;
}
const bool any=std::ranges::any_of(draft.chosen,[](bool chosen){return chosen;});
if(LOWORD(wp)==IDOK && any) FilesModalDialog::finish(dialog,IDOK);
else EnableWindow(GetDlgItem(dialog,IDOK),any);
return TRUE;
}
fs::path chooseFilesTransferPath(HWND owner,bool importing)
{
std::array<wchar_t,32768> file{};
if(!importing) wcscpy_s(file.data(),file.size(),L"KSwitcher.Files.settings.json");
OPENFILENAMEW pick{sizeof(pick)};
pick.hwndOwner=owner;
pick.lpstrTitle=importing?L"Open Files settings JSON":L"Save Files settings JSON";
pick.lpstrFilter=L"JSON files (*.json)\0*.json\0All files (*.*)\0*.*\0";
pick.lpstrFile=file.data();
pick.nMaxFile=static_cast<DWORD>(file.size());
pick.lpstrDefExt=L"json";
pick.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|
(importing?OFN_FILEMUSTEXIST:OFN_OVERWRITEPROMPT);
if(importing?GetOpenFileNameW(&pick):GetSaveFileNameW(&pick)) return file.data();
if(CommDlgExtendedError()) throw std::runtime_error("Could not open the file picker.");
return {};
}
Json exportFilesOptionGroups(const OptionsBaseline &saved)
{
Json colors{{"panels",saved.palette},{"comparison",saved.comparison.palette},{"fileStyles",serializeFileStyles(saved.styles)}};
Json panels{{"leftMode",static_cast<DWORD>(saved.modes[0])},
{"rightMode",static_cast<DWORD>(saved.modes[1])},{"sizeWidth",saved.width},{"statusFields",saved.fields}};
for(const auto &check:transferablePanelChecks) panels[check.id]=saved.*check.value;
return {{"colors",std::move(colors)},{"panels",std::move(panels)},{"keys",serializeFilesKeySettings(saved.keySettings)}};
}
template<typename Palette>
void importFilesColors(const Json &value,Palette &palette)
{
if(!value.is_array()) throw std::runtime_error("Expected an array of colors.");
for(size_t i=0;i<std::min(value.size(),palette.size());++i)
{
if(!value[i].is_number_unsigned() || value[i]>0xffffff)
throw std::runtime_error("A color is outside the RGB range.");
palette[i]=value[i].template get<COLORREF>();
}
}
DWORD importFilesOptionNumber(const Json &value,DWORD minimum,DWORD maximum)
{
if(!value.is_number_unsigned() || value<minimum || value>maximum)
throw std::runtime_error("A panel setting is outside its supported range.");
return value.get<DWORD>();
}
std::optional<FilesKeySettings> mergeImportedFilesKeySchemes(HWND owner,const FilesKeySettings &local,const Json &value)
{
const auto imported=parseFilesKeySettings(value);
if(!imported) throw std::runtime_error("The keyboard schemes contain invalid or conflicting bindings.");
auto result=local;
size_t replacements{};
for(size_t i=0;i<imported->schemes.size();++i)
{
const auto &scheme=imported->schemes[i];
const auto existing=std::ranges::find_if(result.schemes,[&](const auto &candidate)
{ return sameFilesKeySchemeName(candidate.name,scheme.name); });
const auto position=static_cast<size_t>(existing-result.schemes.begin());
if(i==imported->active) result.active=position;
if(existing==result.schemes.end()) result.schemes.push_back(scheme);
else if(existing->keys!=scheme.keys)
{
++replacements;
auto name=existing->name;
*existing=scheme;
existing->name=std::move(name);
}
}
if(result.schemes.size()>filesKeySchemeLimit)
throw std::runtime_error("The imported keyboard schemes exceed the number Files can store.");
if(replacements)
{
const auto prompt=L"Replace "+std::to_wstring(replacements)+
(replacements==1?L" keyboard scheme with the same name?":L" keyboard schemes with the same names?");
if(showFilesNotice(owner,prompt.c_str(),L"Import Files settings",
{.confirm=true,.accept=L"&Replace"})!=IDYES) return {};
}
return result;
}
void stageImportedFilesOptions(HWND dialog,OptionsDraft &draft,const Json &groups)
{
auto palette=draft.palette;
auto comparison=draft.comparison.palette;
auto styles=draft.styles;
auto options=OptionsBaseline{};
options.modes={panelModeOption(dialog,0),panelModeOption(dialog,1)};
options.width=GetDlgItemInt(dialog,201,nullptr,FALSE);
options.fields=0;
for(int i=0;i<4;++i)
if(IsDlgButtonChecked(dialog,205+i)==BST_CHECKED) options.fields|=1u<<i;
for(const auto &check:transferablePanelChecks)
options.*check.value=IsDlgButtonChecked(dialog,check.control)==BST_CHECKED;
const auto colorGroup=groups.find("colors");
if(colorGroup!=groups.end())
{
if(!colorGroup->is_object()) throw std::runtime_error("Invalid colors group.");
if(colorGroup->contains("panels")) importFilesColors(colorGroup->at("panels"),palette);
if(colorGroup->contains("comparison")) importFilesColors(colorGroup->at("comparison"),comparison);
if(colorGroup->contains("fileStyles"))
{
auto parsed=parseFileStyles(colorGroup->at("fileStyles"));
if(!parsed) throw std::runtime_error("Invalid file styles.");
styles=std::move(*parsed);
}
}
const auto panelGroup=groups.find("panels");
if(panelGroup!=groups.end())
{
if(!panelGroup->is_object()) throw std::runtime_error("Invalid panel modes and layout group.");
for(const auto &check:transferablePanelChecks)
if(panelGroup->contains(check.id)) options.*check.value=panelGroup->at(check.id).get<bool>();
constexpr const char *modeKeys[]{"leftMode","rightMode"};
for(size_t i=0;i<options.modes.size();++i)
if(panelGroup->contains(modeKeys[i]))
options.modes[i]=static_cast<PanelMode>(importFilesOptionNumber(
panelGroup->at(modeKeys[i]),0,std::size(panelModeNames)-1));
if(panelGroup->contains("sizeWidth"))
options.width=importFilesOptionNumber(panelGroup->at("sizeWidth"),6,16);
if(panelGroup->contains("statusFields"))
options.fields=importFilesOptionNumber(panelGroup->at("statusFields"),0,15);
}
if(groups.contains("keys"))
{
auto keys=mergeImportedFilesKeySchemes(dialog,draft.keySettings,groups.at("keys"));
if(!keys) return;
draft.keySettings=std::move(*keys);
}
if(colorGroup!=groups.end())
{
draft.palette=palette;
draft.comparison.palette=comparison;
draft.styles=std::move(styles);
}
if(panelGroup!=groups.end())
{
if(panelGroup->contains("sizeWidth")) SetDlgItemInt(dialog,201,options.width,FALSE);
for(int index=0;index<2;++index)
SendDlgItemMessageW(dialog,273+index,CB_SETCURSEL,static_cast<WPARAM>(options.modes[index]),0);
for(const auto &check:transferablePanelChecks)
CheckDlgButton(dialog,check.control,options.*check.value?BST_CHECKED:BST_UNCHECKED);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,options.fields&(1u<<i)?BST_CHECKED:BST_UNCHECKED);
}
if(draft.page==PanelColors && draft.section==fileStyleSection) updateFileStyleEditor(dialog,draft,true);
showOptionsPage(dialog,draft,draft.page,draft.section);
updateOptionsApply(dialog,draft);
}
void transferFilesOptions(HWND dialog,OptionsDraft &options,bool importing)
{
try
{
FilesTransferDraft transfer{.importing=importing};
if(importing)
{
const auto path=chooseFilesTransferPath(dialog,true);
if(path.empty()) return;
const auto data=ks::readFile(path,maxFilesJsonBytes);
const auto document=Json::parse(data,[](int depth,Json::parse_event_t,Json &)
{
if(depth>32) throw std::runtime_error("The JSON contains too many nested levels.");
return true;
});
if(document.value("format",std::string{})!="kswitcher-files-settings" || document.at("version")!=1)
throw std::runtime_error("This Files settings format or version is unsupported.");
const auto &groups=document.at("groups");
if(!groups.is_object()) throw std::runtime_error("The document does not contain settings groups.");
for(const auto &group:filesTransferGroups)
if(groups.contains(group.id)) transfer.groups[group.id]=groups.at(group.id);
if(transfer.groups.empty()) throw std::runtime_error("The file does not contain any supported settings groups.");
}
else transfer.groups=exportFilesOptionGroups(options.baseline);
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(617),dialog,filesTransferDialog,
reinterpret_cast<LPARAM>(&transfer))!=IDOK) return;
for(size_t i=0;i<transfer.chosen.size();++i)
if(!transfer.chosen[i]) transfer.groups.erase(filesTransferGroups[i].id);
if(importing) stageImportedFilesOptions(dialog,options,transfer.groups);
else
{
const auto path=chooseFilesTransferPath(dialog,false);
if(path.empty()) return;
const auto output=Json{{"format","kswitcher-files-settings"},{"version",1},
{"groups",std::move(transfer.groups)}}.dump(2)+"\n";
const auto temporary=ks::files::temporaryPath(path.parent_path());
const bool replace=GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES;
ks::atomicWrite(temporary,ks::Bytes(output.begin(),output.end()));
if(!MoveFileExW(temporary.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH|(replace?MOVEFILE_REPLACE_EXISTING:0)))
{
DeleteFileW(temporary.c_str());
throw std::runtime_error("Could not publish the settings file.");
}
}
}
catch(const Json::exception &)
{
showFilesNotice(dialog,L"The JSON is damaged or contains an invalid value.",L"Files settings");
}
catch(const std::exception &error)
{
const auto message=ks::wide(error.what());
showFilesNotice(dialog,message.c_str(),L"Files settings");
}
}
+18
View File
@@ -388,6 +388,24 @@ public:
if(libssh2_sftp_mkdir(sftp_.get(),name.c_str(),0755)) operationError("Could not create the SFTP folder");
}
void preserveModificationTime(const fs::path &path,uint64_t modified) const
{
constexpr uint64_t ticks=10000000, windowsEpoch=11644473600;
if(modified/ticks<windowsEpoch || modified/ticks-windowsEpoch>UINT32_MAX) return;
requireWriteAccess();
const auto name=encode(path);
LIBSSH2_SFTP_ATTRIBUTES attributes{};
if(libssh2_sftp_lstat(sftp_.get(),name.c_str(),&attributes))
operationError("Could not read the staged file timestamps");
const auto seconds=static_cast<unsigned long>(modified/ticks-windowsEpoch);
if(!(attributes.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)) attributes.atime=seconds;
attributes.flags=LIBSSH2_SFTP_ATTR_ACMODTIME;
attributes.mtime=seconds;
if(libssh2_sftp_setstat(sftp_.get(),name.c_str(),&attributes) &&
libssh2_sftp_last_error(sftp_.get())!=LIBSSH2_FX_OP_UNSUPPORTED)
operationError("Could not preserve the SFTP modification time");
}
void remove(const fs::path &path,bool directory) const
{
requireWriteAccess();
+31 -34
View File
@@ -48,60 +48,54 @@ bool sameFileExtension(std::wstring_view left,std::wstring_view right)
right.data(),static_cast<int>(right.size()),TRUE)==CSTR_EQUAL;
}
void loadFileStyles()
std::optional<std::vector<FileStyle>> parseFileStyles(const Json &rows)
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>256*1024) return;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
return;
try
{
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
if(!rows.is_array() || rows.size()>64) return;
if(!rows.is_array() || rows.size()>64) return {};
std::vector<FileStyle> parsed;
for(const auto &row:rows)
{
FileStyle style{ks::wide(row.at("extension").get<std::string>())};
if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return;
if(std::any_of(parsed.begin(),parsed.end(),[&](const auto &existing){return existing.extension==style.extension;}))
return;
const auto color=[&](const char *key)->std::optional<COLORREF>
if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return {};
if(std::ranges::any_of(parsed,[&](const auto &existing){return existing.extension==style.extension;}))
return {};
const auto color=[](const Json &entry,const char *key)->std::optional<COLORREF>
{
if(!row.contains(key)) return {};
const auto value=row.at(key).get<DWORD>();
if(value>0xffffff) throw std::runtime_error("Invalid file style color");
return value;
if(!entry.contains(key)) return {};
const auto &value=entry.at(key);
if(!value.is_number_unsigned() || value>0xffffff) throw std::runtime_error("Invalid file style color");
return value.get<DWORD>();
};
style.foreground=color("foreground");
style.background=color("background");
style.foreground=color(row,"foreground");
style.background=color(row,"background");
style.underline=row.value("underline",false);
style.strikeout=row.value("strikeout",false);
if(row.contains("states"))
{
const auto &states=row.at("states");
if(!states.is_array() || states.size()!=style.states.size()) return;
if(!states.is_array() || states.size()!=style.states.size()) return {};
for(size_t i=0;i<style.states.size();++i)
{
const auto read=[&](const char *key)->std::optional<COLORREF>
{
if(!states[i].contains(key)) return {};
const auto value=states[i].at(key).get<DWORD>();
if(value>0xffffff) throw std::runtime_error("Invalid state color");
return value;
};
style.states[i]={read("foreground"),read("background")};
if(!states[i].is_object()) return {};
style.states[i]={color(states[i],"foreground"),color(states[i],"background")};
}
}
parsed.push_back(std::move(style));
}
fileStyles=std::move(parsed);
return parsed;
}
catch(const std::exception &) {}
catch(const std::exception &) {return {};}
}
bool saveFileStyles(const std::vector<FileStyle> &styles)
void loadFileStyles()
{
fileStyles=defaultFileStyles;
if(const auto rows=readFilesJsonPreference(fileStyleKey))
if(auto parsed=parseFileStyles(*rows)) fileStyles=std::move(*parsed);
}
Json serializeFileStyles(const std::vector<FileStyle> &styles)
{
auto rows=Json::array();
for(const auto &style:styles)
@@ -119,9 +113,12 @@ bool saveFileStyles(const std::vector<FileStyle> &styles)
}
rows.push_back(std::move(row));
}
const auto data=rows.dump();
return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
return rows;
}
bool saveFileStyles(const std::vector<FileStyle> &styles)
{
return writeFilesJsonPreference(fileStyleKey,serializeFileStyles(styles));
}
struct FileRowStyle
+71 -25
View File
@@ -42,7 +42,7 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
HANDLE trackReplacement(const std::filesystem::path &path)
{
// A metadata-only handle survives the rename without blocking ReplaceFile.
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
const auto handle=CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
return handle;
@@ -90,15 +90,6 @@ bool sameFile(HANDLE a, HANDLE b)
return sameFileIdentity(first,second);
}
std::filesystem::path temporaryPath(const std::filesystem::path &directory)
{
GUID id{};
wchar_t name[40]{};
if (FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id, name, 40))
throw std::runtime_error("Cannot create a temporary file name.");
return directory / (std::wstring(L".kswitcher-") + name + L".tmp");
}
std::filesystem::path createTemporary(const std::filesystem::path &directory, File &file, DWORD flags)
{
auto path = temporaryPath(directory);
@@ -107,6 +98,11 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
return path;
}
void createEditorSnapshot(File &file)
{
createTemporary(std::filesystem::temp_directory_path(),file,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE);
}
bool isUtf16(TextEncoding encoding)
{
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
@@ -133,6 +129,18 @@ std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
return units;
}
std::string encodeUtf8(std::wstring_view units)
{
if(units.empty()) return {};
const auto length=static_cast<int>(units.size());
const int required=WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,units.data(),length,nullptr,0,nullptr,nullptr);
if(!required) fail("Decode UTF-16");
std::string result(required,'\0');
if(!WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,units.data(),length,result.data(),required,nullptr,nullptr))
fail("Decode UTF-16");
return result;
}
std::string encode(std::string_view utf8,TextEncoding encoding)
{
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
@@ -179,8 +187,8 @@ std::string convertLineEndings(std::string_view text,TextLineEnding ending)
}
}
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
: path_(std::move(path)), editable_(editable)
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding,bool snapshotEdits)
: path_(std::move(path)), editable_(editable),snapshotEdits_(snapshotEdits && editable)
{
if(path_.empty())
{
@@ -210,7 +218,20 @@ TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding
encoding_=encoding;
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
source_ = source.release();
if(snapshotEdits_)
{
version_=fileVersion(source.handle);
File snapshot;
createEditorSnapshot(snapshot);
for(uint64_t offset=0;offset<size_;)
{
const auto block=read(source.handle,offset,static_cast<size_t>(std::min(pageBytes,size_-offset)));
write(snapshot.handle,block);
offset+=block.size();
}
source_=snapshot.release();
}
else source_ = source.release();
}
TextDocument::~TextDocument()
@@ -289,13 +310,7 @@ std::string TextDocument::decode(std::string bytes) const
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
}
}
const auto length = static_cast<int>(units.size());
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
if (!required) fail("Decode UTF-16");
std::string result(required, '\0');
if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, result.data(), required, nullptr, nullptr))
fail("Decode UTF-16");
return result;
return encodeUtf8(units);
}
std::string TextDocument::readPage(uint64_t page) const
@@ -377,6 +392,15 @@ std::string formatHexAddress(uint64_t offset)
return address;
}
std::string formatBinarySymbols(std::string_view bytes)
{
if(bytes.empty()) return {};
auto symbols=decodeMultibyte(bytes,437,0);
for(size_t i=0;i<bytes.size();++i)
if(const auto marker=binarySymbolMarker(static_cast<unsigned char>(bytes[i]))) symbols[i]=marker;
return encodeUtf8(symbols);
}
std::string formatHexPage(std::string_view bytes,uint64_t offset)
{
constexpr char digits[]="0123456789ABCDEF";
@@ -461,13 +485,26 @@ void TextDocument::stage(uint64_t page, std::string_view utf8)
bool TextDocument::save()
{
if (!modified()) return true;
const auto verify=[&](HANDLE current) {
if(version_ && *version_!=fileVersion(current))
throw std::runtime_error("The file changed outside Files. Your editor buffer was kept.");
if(!version_ && !sameFile(source_,current))
throw std::runtime_error("The file was replaced outside KSwitcher.");
};
if(version_)
{
File current{openSource(path_,true)};
verify(current.handle);
}
PendingSave pending;
File output;
File output,snapshot;
if(snapshotEdits_) createEditorSnapshot(snapshot);
pending.path = createTemporary(path_.parent_path(), output, FILE_ATTRIBUTE_NORMAL);
uint64_t written{};
const auto append = [&](std::string_view bytes) {
write(output.handle, bytes);
if(snapshotEdits_) write(snapshot.handle,bytes);
written += bytes.size();
};
const auto copyUntil = [&](uint64_t &offset, uint64_t end) {
@@ -491,7 +528,7 @@ bool TextDocument::save()
File replacement{trackReplacement(pending.path)};
File current{openSource(path_, true)};
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
verify(current.handle);
const auto backup = temporaryPath(path_.parent_path());
if (const auto error=replaceFileWithBackup(path_,pending.path,backup))
{
@@ -499,7 +536,9 @@ bool TextDocument::save()
fail("Replace original file");
}
pending.path.clear();
const auto newSource = ReOpenFile(replacement.handle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, 0);
if(snapshotEdits_) version_=fileVersion(replacement.handle);
const auto newSource=snapshotEdits_?snapshot.release():
ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
DeleteFileW(backup.c_str());
CloseHandle(source_);
source_ = newSource;
@@ -517,10 +556,16 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
const auto bom=format.bom?signature(format.encoding):std::string_view{};
PendingSave pending;
File output;
File output,snapshot;
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
write(output.handle,bom);
write(output.handle,bytes);
if(snapshotEdits_)
{
createEditorSnapshot(snapshot);
write(snapshot.handle,bom);
write(snapshot.handle,bytes);
}
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
File replacement{trackReplacement(pending.path)};
@@ -533,7 +578,8 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
changes_.clear();
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
spoolSize_=0;
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
if(snapshotEdits_) version_=fileVersion(replacement.handle);
source_=snapshotEdits_?snapshot.release():ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
return source_!=INVALID_HANDLE_VALUE;
}
}
+10 -3
View File
@@ -1,6 +1,6 @@
#pragma once
#include <windows.h>
#include "files_win32_replace.h"
#include <cstdint>
#include <filesystem>
#include <map>
@@ -17,6 +17,11 @@ enum class TextLineEnding { preserve, crlf, lf, cr };
inline constexpr uint64_t hexPageBytes=64*1024;
std::string formatHexAddress(uint64_t offset);
std::string formatHexPage(std::string_view bytes,uint64_t offset);
constexpr wchar_t binarySymbolMarker(unsigned char byte)
{
return byte<0x20 || byte==0x7f || byte==0xff || byte=='\\' ? static_cast<wchar_t>(0xe000+byte) : 0;
}
std::string formatBinarySymbols(std::string_view bytes);
struct TextSaveFormat
{
@@ -38,7 +43,7 @@ public:
static constexpr size_t editLimit = 8 * pageBytes;
explicit TextDocument(std::filesystem::path path, bool editable = true,
TextEncoding encoding=TextEncoding::automatic);
TextEncoding encoding=TextEncoding::automatic,bool snapshotEdits=false);
~TextDocument();
TextDocument(const TextDocument &) = delete;
TextDocument &operator=(const TextDocument &) = delete;
@@ -58,6 +63,7 @@ public:
bool saveNew(std::filesystem::path path, TextSaveFormat format);
const wchar_t *encodingName() const;
TextEncoding encoding() const { return encoding_; }
const std::optional<LocalFileVersion> &expectedVersion() const {return version_;}
private:
struct Change { uint64_t offset; size_t size; };
@@ -68,7 +74,8 @@ private:
uint64_t size_{}, spoolSize_{};
size_t bom_{};
TextEncoding encoding_ = TextEncoding::utf8;
bool editable_;
bool editable_, snapshotEdits_;
std::optional<LocalFileVersion> version_;
std::map<uint64_t, Change> changes_;
std::string decode(std::string bytes) const;
+6
View File
@@ -2,12 +2,15 @@
#include <windows.h>
#include <array>
#include <optional>
#include <string_view>
#include <string>
#include <vector>
namespace ks::files
{
inline constexpr size_t documentColorCount = 10;
inline constexpr wchar_t systemTextScheme[]=L"@system";
using TextPalette = std::array<COLORREF, 14>;
inline constexpr const wchar_t *textPaletteNames[] = {L"FAR (blue)", L"Dark", L"Light"};
inline constexpr TextPalette textPalettes[] = {
@@ -56,8 +59,11 @@ struct TextSettings
TextPreferencesSet profiles;
std::vector<NamedTextPalette> schemes;
MarkdownPreferences markdown;
std::array<std::wstring,2> systemThemes{textPaletteNames[2],textPaletteNames[1]};
bool operator==(const TextSettings &) const = default;
};
std::optional<TextPalette> namedTextPalette(const TextSettings &settings,std::wstring_view name);
TextPreferences resolvedTextProfile(const TextSettings &settings,bool editor);
TextSettings loadTextPreferences();
void saveTextPreferences(const TextSettings &settings);
}
+452 -84
View File
@@ -1,4 +1,5 @@
#include "files_text_window.h"
#include "files_help.h"
#include "files_image_view.h"
#include "files_text_preferences.h"
#include "files_menu_paint.h"
@@ -73,6 +74,30 @@ void readTextProfile(TextPreferences &prefs, const nlohmann::json &data)
}
}
std::optional<TextPalette> namedTextPalette(const TextSettings &settings,std::wstring_view name)
{
const auto matches=[&](const wchar_t *other)
{
return !name.empty() && CompareStringOrdinal(name.data(),static_cast<int>(name.size()),other,-1,TRUE)==CSTR_EQUAL;
};
for(size_t i=0;i<std::size(textPalettes);++i)
if(matches(textPaletteNames[i])) return textPalettes[i];
for(const auto &scheme:settings.schemes)
if(matches(scheme.name.c_str())) return scheme.colors;
return {};
}
TextPreferences resolvedTextProfile(const TextSettings &settings,bool editor)
{
auto profile=settings.profiles[editor];
if(profile.scheme==systemTextScheme)
{
const bool dark=windowsUsesDarkApps();
profile.colors=namedTextPalette(settings,settings.systemThemes[dark]).value_or(textPalettes[dark?1:2]);
}
return profile;
}
TextSettings loadTextPreferences()
{
TextSettings settings{};
@@ -109,6 +134,17 @@ TextSettings loadTextPreferences()
}
catch (const std::exception &) {}
}
if(const auto system=data.find("systemThemes");system!=data.end() && system->is_object())
{
constexpr const char *roles[]{"light","dark"};
for(size_t i=0;i<settings.systemThemes.size();++i)
if(const auto name=system->find(roles[i]);name!=system->end() && name->is_string())
{
auto value=wide(name->get<std::string>());
if(value.size()<=maxTextPaletteName && namedTextPalette(settings,value))
settings.systemThemes[i]=std::move(value);
}
}
return settings;
}
const wchar_t *legacy[]{L"files-viewer.json", L"files-editor.json"};
@@ -140,6 +176,7 @@ void saveTextPreferences(const TextSettings &settings)
schemes.push_back({{"name", utf8(scheme.name)}, {"colors", scheme.colors}});
data["markdown"]={{"width",settings.markdown.width},{"fontSize",settings.markdown.fontSize},
{"font",utf8(settings.markdown.font)}};
data["systemThemes"]={{"light",utf8(settings.systemThemes[0])},{"dark",utf8(settings.systemThemes[1])}};
const auto json = data.dump(2);
atomicWrite(dataDirectory() / L"files-text.json", Bytes(json.begin(), json.end()));
}
@@ -683,6 +720,19 @@ std::future<std::unique_ptr<RemoteTextFile>> fetchRemoteText(const RemoteTextSou
return result;
}
unsigned textAreaScale(TextDialogs dialogs,AppearanceArea area)
{
return dialogs.readScale?dialogs.readScale(area):100;
}
TextWindowFont scaledDocumentFont(TextDialogs dialogs,bool editor)
{
auto font=dialogs.readFont();
font.tenthsOfPoint=scaledAppearanceSize(font.tenthsOfPoint,
textAreaScale(dialogs,editor?AppearanceArea::editor:AppearanceArea::viewer));
return font;
}
class TextWindow;
std::map<HWND,std::shared_ptr<TextWindow>> textWindows;
std::vector<HWND> textWindowOrder;
@@ -771,12 +821,12 @@ public:
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
edit(editable), draft(options.draft), embedded(quickView), hex(options.hex && !editable),
initialBookmark(options.line),
prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
prefs(resolvedTextProfile(loadTextPreferences(),editable)), filesFont(scaledDocumentFont(dialogs,editable)),
search{dialogs}, previewFragment(fragment)
{
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,
hex?TextEncoding::utf8:options.encoding);
hex?TextEncoding::utf8:options.encoding,isLocalDocumentPath(original));
if(options.encoding!=TextEncoding::automatic)
{
newFormat.encoding=options.encoding;
@@ -800,12 +850,18 @@ public:
if(smallIcon) DestroyIcon(smallIcon);
if(largeIcon) DestroyIcon(largeIcon);
}
HWND window{}, editor{};
HWND window{}, editor{}, quickModeButton{};
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
void previewFile(const std::filesystem::path &path);
void previewDiff(const std::wstring &title,std::string_view patch);
void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff);
bool openBookmark(const ViewerBookmark &bookmark);
nlohmann::json sessionState() const;
void restoreSession(const nlohmann::json &state);
AppearanceArea appearanceArea() const
{
return previewWanted?AppearanceArea::markdown:edit?AppearanceArea::editor:AppearanceArea::viewer;
}
std::filesystem::path original;
const std::string peerId;
@@ -860,13 +916,8 @@ private:
bool previewWanted{}, previewVisible{}, previewRetried{};
ULONGLONG previewDeadline{};
ULONGLONG nextFileCheck{};
struct FileStamp
{
uint64_t writeTime, fileIndex, size;
DWORD volume;
bool operator==(const FileStamp &) const = default;
};
std::optional<FileStamp> previewStamp;
std::optional<LocalFileVersion> previewStamp, observedVersion;
bool diskChanged{};
struct MarkdownTask
{
uint64_t revision;
@@ -875,6 +926,8 @@ private:
};
std::string previewText;
uint64_t previewRevision{};
int renderedScroll{};
std::optional<int> sessionScroll;
std::optional<MarkdownTask> pendingTask;
std::optional<size_t> taskOffset;
std::string previewFragment;
@@ -918,6 +971,7 @@ private:
static constexpr UINT_PTR quickViewTimer = 5;
static constexpr UINT_PTR bookmarkTimer = 6;
static constexpr UINT_PTR savedViewerTimer = 7;
static constexpr UINT_PTR externalChangeTimer = 8;
struct BookmarkLocation
{
std::filesystem::path path;
@@ -928,20 +982,29 @@ private:
};
std::future<BookmarkLocation> bookmarkTask;
std::stop_source bookmarkStop;
enum class QuickKind { text, html, binary };
struct QuickDocument
{
std::unique_ptr<TextDocument> document;
std::string firstPage;
std::optional<std::string> markdown;
std::optional<std::string> previewCode;
QuickKind kind{};
size_t binaryBytes{};
};
std::future<QuickDocument> quickLoading;
std::filesystem::path quickPath;
std::wstring quickDiffTitle;
bool quickDiffVisible{};
std::wstring quickTextTitle;
bool quickTextVisible{},quickTextDiff{};
uint64_t quickRequest{}, quickReading{};
ULONGLONG quickReadyAt{};
std::wstring quickError;
std::optional<std::string> quickMarkdown;
std::optional<std::string> quickPreviewCode;
QuickKind quickKind{};
bool quickHtmlRendered{}, binaryRepresentations{};
size_t quickBinaryBytes{};
static constexpr int quickModeControl=159;
void applySourceLayoutOptions();
void toggleQuickHtml();
void pollQuickView();
static constexpr UINT trimUndo = WM_APP + 1;
static constexpr UINT previewFailed = WM_APP + 2;
@@ -1003,7 +1066,7 @@ private:
void changeMode();
ViewerPosition currentPosition() const;
void restorePosition(const ViewerPosition &position);
void showTextMode(const ViewerPosition &position,std::string contents);
void showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus=true);
void suspendEditor(std::unique_ptr<RemoteTextFile> saved={});
void restoreEditor();
void finishSavedViewer();
@@ -1015,7 +1078,9 @@ private:
void stopPreview(bool refresh=true,bool keepBrowser=false);
void renderPreview(bool keepPosition=false);
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
std::optional<FileStamp> previewFileStamp() const;
std::optional<LocalFileVersion> previewFileStamp() const;
void rememberLocalVersion();
void pollExternalChanges();
void refreshPreview();
void startMarkdownTask();
void finishMarkdownTask();
@@ -1307,8 +1372,8 @@ void TextWindow::reloadPreferences()
pendingPreferences = false;
auto settings = loadTextPreferences();
applyMarkdownPreferences(settings.markdown);
auto &profile = settings.profiles[edit];
const auto font = search.style.readFont();
auto profile=resolvedTextProfile(settings,edit);
const auto font=scaledDocumentFont(search.style,edit);
const bool fontChanged = font.tenthsOfPoint != filesFont.tenthsOfPoint ||
std::memcmp(&font.font, &filesFont.font, sizeof(LOGFONTW)) != 0;
if (!fontChanged && profile == prefs) return;
@@ -1371,19 +1436,44 @@ void TextWindow::applyPreferences()
send(SCI_SETUSETABS, !prefs.tabsAsSpaces);
send(SCI_SETTABINDENTS, TRUE);
send(SCI_SETBACKSPACEUNINDENTS, TRUE);
send(SCI_SETWRAPMODE, !hex && prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE);
send(SCI_SETVIEWWS, !hex && prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE);
send(SCI_SETVIEWEOL, !hex && prefs.whitespace);
applySourceLayoutOptions();
applyLineEnding();
updateLineNumberMargin();
layout();
invalidate();
}
void TextWindow::applySourceLayoutOptions()
{
const bool binary=embedded && quickKind==QuickKind::binary;
if(std::exchange(binaryRepresentations,binary)!=binary)
{
constexpr char digits[]="0123456789ABCDEF";
for(int byte=0;byte<256;++byte)
{
const auto marker=binarySymbolMarker(static_cast<unsigned char>(byte));
if(!marker) continue;
const auto key=utf8(std::wstring(1,marker));
const auto index=reinterpret_cast<WPARAM>(key.c_str());
if(binary)
{
const char value[]{'\\','x',digits[byte>>4],digits[byte&15],0};
send(SCI_SETREPRESENTATION,index,reinterpret_cast<LPARAM>(byte=='\\'?"\\\\":value));
send(SCI_SETREPRESENTATIONAPPEARANCE,index,SC_REPRESENTATION_PLAIN);
}
else send(SCI_CLEARREPRESENTATION,index);
}
}
send(SCI_SETWRAPMODE,binary?SC_WRAP_CHAR:!hex && prefs.wrap?SC_WRAP_WORD:SC_WRAP_NONE);
send(SCI_SETHSCROLLBAR,!binary);
send(SCI_SETVIEWWS,!binary && !hex && prefs.whitespace?SCWS_VISIBLEALWAYS:SCWS_INVISIBLE);
send(SCI_SETVIEWEOL,!binary && !hex && prefs.whitespace);
}
void TextWindow::updateLineNumberMargin()
{
LRESULT width{};
if (prefs.numbers && !hex)
if (prefs.numbers && !hex && (!embedded || quickKind!=QuickKind::binary))
{
const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size();
const std::string sample(digits, '9');
@@ -1591,6 +1681,7 @@ void TextWindow::go(uint64_t index)
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
{
rememberLocalVersion();
if(hex)
{
releaseMenu();
@@ -1601,8 +1692,9 @@ void TextWindow::initializeDocument(std::optional<std::string> firstPage)
return;
}
if(!firstPage) firstPage=document->readPage(0);
automatic=detectLanguage(original,*firstPage);
automatic=embedded && quickKind==QuickKind::binary?TextLanguage{}:detectLanguage(original,*firstPage);
language=automatic;
if(embedded) applySourceLayoutOptions();
if(canPreview()) ShowWindow(editor,SW_HIDE);
if(!embedded)
{
@@ -1625,24 +1717,27 @@ std::string readMarkdownDocument(TextDocument &document)
void TextWindow::previewFile(const std::filesystem::path &path)
{
if(quickDiffTitle.empty() && path==quickPath) return;
quickDiffVisible=false;
quickDiffTitle.clear();
if(quickTextTitle.empty() && path==quickPath) return;
quickTextVisible=false;
quickTextTitle.clear();
quickPath=path;
++quickRequest;
quickReadyAt=GetTickCount64()+80;
stopPreview(false,true);
document.reset();
quickMarkdown.reset();
quickPreviewCode.reset();
quickKind=QuickKind::text;
quickHtmlRendered=false;
quickBinaryBytes=0;
quickError.clear();
layout();
SetTimer(window,quickViewTimer,30,nullptr);
}
void TextWindow::previewDiff(const std::wstring &title,std::string_view patch)
void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff)
{
if(!embedded) return;
if(quickDiffTitle.empty())
if(quickTextTitle.empty())
{
++quickRequest;
KillTimer(window,quickViewTimer);
@@ -1651,14 +1746,22 @@ void TextWindow::previewDiff(const std::wstring &title,std::string_view patch)
quickError.clear();
stopPreview(false,true);
document.reset();
quickMarkdown.reset();
language=automatic=detectLanguage(L"preview.diff",patch);
quickPreviewCode.reset();
quickKind=QuickKind::text;
quickHtmlRendered=false;
quickBinaryBytes=0;
applySourceLayoutOptions();
}
if(quickTextTitle.empty() || quickTextDiff!=diff)
{
language=automatic=diff?detectLanguage(L"preview.diff",contents):TextLanguage{};
installLexer();
}
quickDiffTitle=title;
quickDiffVisible=!patch.empty();
quickTextTitle=title;
quickTextVisible=!contents.empty();
quickTextDiff=diff;
pageEol=SC_EOL_LF;
replaceEditorText(patch);
replaceEditorText(contents);
send(SCI_COLOURISE,0,-1);
layout();
}
@@ -1677,7 +1780,10 @@ void TextWindow::pollQuickView()
original=quickPath;
filename=original.filename().wstring();
document=std::move(loaded.document);
quickMarkdown=std::move(loaded.markdown);
quickPreviewCode=std::move(loaded.previewCode);
quickKind=loaded.kind;
quickHtmlRendered=quickKind==QuickKind::html && quickPreviewCode.has_value();
quickBinaryBytes=loaded.binaryBytes;
initializeDocument(std::move(loaded.firstPage));
}
}
@@ -1706,13 +1812,23 @@ void TextWindow::pollQuickView()
std::packaged_task<QuickDocument()> task([path=quickPath] {
auto source=std::make_unique<TextDocument>(path,false);
auto first=source->readPage(0);
if(first.find('\0')!=std::string::npos)
throw std::runtime_error("Binary preview is unavailable.");
std::optional<std::string> markdown;
if(source->size()<=TextDocument::editLimit && detectLanguage(path,first).lexer=="markdown")
markdown=readMarkdownDocument(*source);
const auto extension=lower(path.extension().wstring());
const auto html=extension==L".html" || extension==L".htm" || extension==L".xhtml";
const auto binary=std::any_of(first.begin(),first.end(),[](unsigned char c) {
return (c<32 && c!='\t' && c!='\r' && c!='\n' && c!='\f') || c==127;
});
if(binary && !html)
{
constexpr size_t limit=4096;
const auto bytes=source->readBytes(0,limit);
source->releaseReadHandle();
return QuickDocument{std::move(source),formatBinarySymbols(bytes),{},QuickKind::binary,bytes.size()};
}
std::optional<std::string> markup;
if(source->size()<=TextDocument::editLimit && (html || detectLanguage(path,first).lexer=="markdown"))
markup=readMarkdownDocument(*source);
source->releaseReadHandle();
return QuickDocument{std::move(source),std::move(first),std::move(markdown)};
return QuickDocument{std::move(source),std::move(first),std::move(markup),html?QuickKind::html:QuickKind::text};
});
quickLoading=task.get_future();
std::thread(std::move(task)).detach();
@@ -1846,6 +1962,7 @@ void TextWindow::finishSave()
navigationHistory.clear();
updateTitle();
}
rememberLocalVersion();
if (!reopened)
{
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
@@ -1941,10 +2058,64 @@ void TextWindow::restorePosition(const ViewerPosition &position)
send(SCI_SETXOFFSET,position.horizontal);
}
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents)
void writeDocumentPlacement(nlohmann::json &state,HWND window)
{
WINDOWPLACEMENT placement{sizeof(placement)};
if(GetWindowPlacement(window,&placement))
{
const auto &rect=placement.rcNormalPosition;
state["rect"]={rect.left,rect.top,rect.right,rect.bottom};
state["maximized"]=placement.showCmd==SW_SHOWMAXIMIZED ||
(placement.flags&WPF_RESTORETOMAXIMIZED)!=0;
}
}
RECT readDocumentBounds(const nlohmann::json &state)
{
if(!state.contains("rect")) return {};
const auto rect=state.at("rect").get<std::array<LONG,4>>();
return {rect[0],rect[1],rect[2],rect[3]};
}
int restoreDocumentPlacement(HWND window,HWND owner,const RECT &bounds,bool maximized)
{
if(bounds.left>=bounds.right || bounds.top>=bounds.bottom || !MonitorFromRect(&bounds,MONITOR_DEFAULTTONULL))
return IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
WINDOWPLACEMENT placement{sizeof(placement)};
placement.rcNormalPosition=bounds;
placement.showCmd=maximized?SW_SHOWMAXIMIZED:SW_SHOWNORMAL;
SetWindowPlacement(window,&placement);
return maximized?SW_MAXIMIZE:SW_SHOWNORMAL;
}
nlohmann::json TextWindow::sessionState() const
{
if(embedded || remote || draft || !document || !isLocalDocumentPath(original)) return nullptr;
const auto position=currentPosition();
nlohmann::json state{{"path",utf8(original.native())},{"editor",edit},{"hex",hex},
{"page",position.page},{"anchor",position.anchor},{"caret",position.caret},
{"firstLine",position.firstLine},{"horizontal",position.horizontal}};
if(previewVisible) state["renderedScroll"]=renderedScroll;
writeDocumentPlacement(state,window);
return state;
}
void TextWindow::restoreSession(const nlohmann::json &state)
{
ViewerPosition position{std::min(state.value("page",uint64_t{}),pageTotal?pageTotal-1:0),
state.value("anchor",LRESULT{}),state.value("caret",LRESULT{}),
std::max<LRESULT>(0,state.value("firstLine",LRESULT{})),std::max<LRESULT>(0,state.value("horizontal",LRESULT{}))};
if(position.page!=page) loadPage(position.page);
restorePosition(position);
if(state.contains("renderedScroll")) sessionScroll=std::max(0,state.at("renderedScroll").get<int>());
}
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus)
{
rememberLocalVersion();
if(canPreview()) ShowWindow(editor,SW_HIDE);
prefs = loadTextPreferences().profiles[edit];
prefs=resolvedTextProfile(loadTextPreferences(),edit);
filesFont=scaledDocumentFont(search.style,edit);
releaseMenu();
createMenu();
installLexer();
@@ -1955,7 +2126,7 @@ void TextWindow::showTextMode(const ViewerPosition &position,std::string content
updateTaskbarGroup();
updatePreview();
layout();
focusContent();
if(takeFocus) focusContent();
}
void TextWindow::changeMode()
@@ -1963,7 +2134,8 @@ void TextWindow::changeMode()
if(!edit && remote && !remote->revision.editable)
throw std::runtime_error("The remote file does not support editing.");
auto position=currentPosition();
auto replacement=std::make_unique<TextDocument>(remote?remote->cache:original,!edit,document->encoding());
auto replacement=std::make_unique<TextDocument>(remote?remote->cache:original,!edit,document->encoding(),
!remote && isLocalDocumentPath(original));
position.page=std::min(position.page,replacement->pages()-1);
auto contents=replacement->readPage(position.page);
document=std::move(replacement);
@@ -2060,8 +2232,17 @@ void TextWindow::updateTaskbarGroup(bool closing)
bool TextWindow::canPreview() const
{
return !edit && !hex && !showBookmarkSource && automatic.lexer=="markdown" && document &&
document->size()<=TextDocument::editLimit;
if(edit || hex || showBookmarkSource || !document || document->size()>TextDocument::editLimit) return false;
if(embedded && quickKind==QuickKind::html) return quickHtmlRendered;
return automatic.lexer=="markdown";
}
void TextWindow::toggleQuickHtml()
{
if(!embedded || quickKind!=QuickKind::html || !document || !quickPreviewCode) return;
quickHtmlRendered=!quickHtmlRendered;
if(quickHtmlRendered) updatePreview();
else stopPreview(true,true);
}
void TextWindow::updatePreview()
@@ -2090,8 +2271,18 @@ bool TextWindow::startPreviewBrowser()
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
if(key==VK_F1 && !ctrl && !alt && !((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
{
PostMessageW(window,filesHelpRequest,0,0);
return true;
}
if(embedded)
{
if(!ctrl && !alt && !(GetKeyState(VK_SHIFT)&0x8000) && key==VK_F6 && quickKind==QuickKind::html)
{
PostMessageW(window,WM_COMMAND,quickModeControl,0);
return true;
}
if(!ctrl || alt || key!='Q') return false;
PostMessageW(GetParent(window),quickViewToggleMessage,0,0);
return true;
@@ -2127,6 +2318,7 @@ void TextWindow::stopPreview(bool refresh,bool keepBrowser)
{
KillTimer(window,previewTimer);
previewWanted=previewVisible=false;
if(embedded && refresh && quickKind==QuickKind::html) quickHtmlRendered=false;
previewStamp.reset();
++previewRevision;
previewText.clear();
@@ -2163,33 +2355,70 @@ void TextWindow::goToFragment(std::string_view fragment)
else previewFragment=fragment;
}
std::optional<TextWindow::FileStamp> TextWindow::previewFileStamp() const
std::optional<LocalFileVersion> TextWindow::previewFileStamp() const
{
if(remote) return {};
if(remote || !isLocalDocumentPath(original)) return {};
const auto file=CreateFileW(original.c_str(),FILE_READ_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(file==INVALID_HANDLE_VALUE) return {};
BY_HANDLE_FILE_INFORMATION state{};
const auto found=GetFileInformationByHandle(file,&state);
std::optional<LocalFileVersion> stamp;
try {stamp=fileVersion(file);} catch(const std::system_error &) {}
CloseHandle(file);
if(!found) return {};
const auto combine=[](DWORD high,DWORD low){return (uint64_t{high}<<32)|low;};
return FileStamp{combine(state.ftLastWriteTime.dwHighDateTime,state.ftLastWriteTime.dwLowDateTime),
combine(state.nFileIndexHigh,state.nFileIndexLow),
combine(state.nFileSizeHigh,state.nFileSizeLow),state.dwVolumeSerialNumber};
return stamp;
}
void TextWindow::rememberLocalVersion()
{
if(embedded || remote || !document) return;
observedVersion=edit?document->expectedVersion():previewFileStamp();
diskChanged=false;
}
void TextWindow::pollExternalChanges()
{
if(embedded || remote || draft || !document || busy() || previewWanted || navigation.valid() || !observedVersion)
return;
const auto stamp=previewFileStamp();
if(!stamp || stamp==observedVersion) return;
if(edit && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !search.style.reloadChanged)) return;
try
{
if(edit)
{
observedVersion=stamp;
diskChanged=true;
invalidate();
if(!search.style.reloadChanged(window)) return;
}
auto replacement=std::make_unique<TextDocument>(original,edit,hex?TextEncoding::utf8:TextEncoding::automatic,edit);
auto position=currentPosition();
const auto pages=hex?1+(replacement->size()?replacement->size()-1:0)/hexPageBytes:replacement->pages();
position.page=std::min(position.page,pages-1);
auto contents=hex?formatHexPage(replacement->readBytes(position.page*hexPageBytes,hexPageBytes),
position.page*hexPageBytes):replacement->readPage(position.page);
if(!hex) language=automatic=detectLanguage(original,contents);
document=std::move(replacement);
showTextMode(position,std::move(contents),edit);
}
catch(const std::exception &error)
{
if(edit) search.style.message(window,wide(error.what()).c_str());
}
}
void TextWindow::renderPreview(bool keepPosition)
{
applyMarkdownPreferences(loadTextPreferences().markdown);
previewDeadline=GetTickCount64()+30000;
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
previewText=quickPreviewCode?*quickPreviewCode:readMarkdownDocument(*document);
if(!remote) document->releaseReadHandle();
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
{"canSave",!embedded && !suspendedEditor && (!remote || remote->revision.editable)},{"compact",embedded},
{"html",embedded && quickKind==QuickKind::html},
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
{"keepPosition",keepPosition}};
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
if(sessionScroll) message["scroll"]=*std::exchange(sessionScroll,{});
restoreScroll=false;
preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace)));
}
@@ -2197,8 +2426,9 @@ void TextWindow::renderPreview(bool keepPosition)
void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences)
{
if(!preview.initialized()) return;
const auto scale=textAreaScale(search.style,AppearanceArea::markdown);
preview.post(wide(nlohmann::json{{"action","appearance"},{"width",preferences.width},
{"fontSize",preferences.fontSize},{"font",utf8(preferences.font)}}.dump()));
{"fontSize",preferences.fontSize*scale/100.0},{"font",utf8(preferences.font)}}.dump()));
}
void TextWindow::refreshPreview()
@@ -2354,6 +2584,7 @@ void TextWindow::previewMessage(const std::wstring &value)
}
const auto message=nlohmann::json::parse(utf8(value));
const auto action=message.at("action").get<std::string>();
if(embedded && quickKind==QuickKind::html && action!="rendered" && action!="failed") return;
if(action=="cycle")
{
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
@@ -2362,6 +2593,11 @@ void TextWindow::previewMessage(const std::wstring &value)
if(embedded && action!="image" && action!="rendered" && action!="failed") return;
const auto revision=message.value("revision",previewRevision);
if(embedded && revision!=previewRevision) return;
if(action=="scroll")
{
if(!embedded && revision==previewRevision) renderedScroll=std::max(0,message.at("top").get<int>());
return;
}
if(action=="failed")
{
PostMessageW(window,previewFailed,static_cast<WPARAM>(revision),0);
@@ -2554,8 +2790,15 @@ void TextWindow::layout()
const int top=embedded?row:2*row;
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
if(quickModeButton)
{
const int width=std::min(static_cast<int>(area.right),scale(108));
MoveWindow(quickModeButton,area.right-width,0,width,row,TRUE);
SetWindowTextW(quickModeButton,quickHtmlRendered?L"Show Source":L"Show Rendered");
ShowWindow(quickModeButton,quickKind==QuickKind::html && quickPreviewCode && document?SW_SHOWNA:SW_HIDE);
}
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
ShowWindow(editor,(document || quickDiffVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
invalidate();
}
@@ -2629,10 +2872,19 @@ void TextWindow::paint()
std::wstring label=L"Quick View";
if(!quickPath.empty()) label+=L" · "+quickPath.filename().native();
if(!quickError.empty()) label+=L" · "+quickError;
else if(quickPath.empty()) label+=L" · Select a local text file";
else if(quickPath.empty()) label+=L" · Select a local file";
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
else if(!previewVisible && pageTotal>1) label+=L" · First page";
if(!quickDiffTitle.empty()) label=quickDiffTitle;
else if(quickKind==QuickKind::binary)
label=L"Binary · "+std::to_wstring(quickBinaryBytes)+L" / "+std::to_wstring(fileSize)+L" B · "+
quickPath.filename().native();
else
{
if(quickKind==QuickKind::html) label+=previewVisible?L" · Rendered":L" · Source";
if(!previewVisible && pageTotal>1) label+=L" · First page";
}
if(quickModeButton && IsWindowVisible(quickModeButton))
client.right=std::max(0L,client.right-scale(108));
if(!quickTextTitle.empty()) label=quickTextTitle;
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
color(TextColor::chrome),scale(6),label);
if(chromeFont) DeleteObject(chromeFont);
@@ -2687,6 +2939,7 @@ void TextWindow::paint()
if(pageTotal>1)
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
L" @ "+std::to_wstring(pageOffset);
if(diskChanged && edit) status+=L" │ Disk changed";
status+=L" │ "+std::to_wstring(fileSize)+L" B";
if(bookmarkTask.valid()) status+=L" │ Locating line…";
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
@@ -2800,7 +3053,7 @@ void TextWindow::command(UINT id)
case lexerAuto: language = automatic; installLexer(); return;
case lexerPlain: language = {}; installLexer(); return;
case options:
search.style.options(window, edit);
search.style.options(window,appearanceArea());
SetFocus(editor);
return;
default:
@@ -2868,7 +3121,13 @@ void TextWindow::notify(const SCNotification &notice)
bool TextWindow::handleKey(const MSG &message)
{
if(embedded) return false;
if(embedded)
{
if(quickKind!=QuickKind::html || message.message!=WM_KEYDOWN || message.wParam!=VK_F6 ||
((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_MENU))&0x8000)) return false;
if(!(message.lParam&(1LL<<30))) toggleQuickHtml();
return true;
}
const auto key = message.wParam;
if (message.hwnd != editor) return false;
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
@@ -2927,7 +3186,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
const auto self=found->second;
try
{
if (message == preferencesChanged)
if(message==preferencesChanged || windowsAppThemeChanged(message,lparam))
{
self->reloadPreferences();
return 0;
@@ -2949,6 +3208,12 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
self->editor = CreateWindowExW(0, L"Scintilla", L"", WS_CHILD | WS_TABSTOP |
WS_VSCROLL | WS_HSCROLL, 0, 0, 0, 0, window, nullptr, GetModuleHandleW(nullptr), nullptr);
if (!self->editor) throw std::runtime_error("Cannot create the text control.");
if(self->embedded)
{
self->quickModeButton=CreateWindowW(L"BUTTON",L"Show Source",WS_CHILD|WS_TABSTOP|BS_PUSHBUTTON,
0,0,0,0,window,reinterpret_cast<HMENU>(quickModeControl),GetModuleHandleW(nullptr),nullptr);
if(!self->quickModeButton) throw std::runtime_error("Cannot create the Quick View mode button.");
}
self->send(SCI_SETCODEPAGE, SC_CP_UTF8);
self->send(SCI_SETMARGINS, 1);
self->send(SCI_SETMODEVENTMASK, SC_MOD_INSERTCHECK | SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT);
@@ -2979,6 +3244,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
else self->initializeDocument();
if(!self->embedded)
{
if(!self->remote) SetTimer(window,externalChangeTimer,500,nullptr);
self->updateIcons(GetDpiForWindow(window));
self->updateTaskbarGroup();
}
@@ -3046,7 +3312,11 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
return 0;
}
case WM_COMMAND:
if(self->embedded) return 0;
if(self->embedded)
{
if(LOWORD(wparam)==quickModeControl) self->toggleQuickHtml();
return 0;
}
if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600);
else self->command(LOWORD(wparam));
return 0;
@@ -3061,6 +3331,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
if (wparam == saveTimer) self->finishSave();
if (wparam == openTimer) self->finishOpen();
if (wparam == previewTimer) self->pollImages();
if (wparam == externalChangeTimer) self->pollExternalChanges();
if (wparam == navigationTimer) self->finishNavigation();
if (wparam == quickViewTimer) self->pollQuickView();
if (wparam == bookmarkTimer) self->finishBookmark();
@@ -3295,16 +3566,23 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
preview->second->previewFile(path);
}
void previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch)
std::optional<AppearanceArea> textWindowAppearanceArea(HWND window)
{
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
preview->second->previewDiff(title,patch);
const auto entry=textWindows.find(window);
if(entry==textWindows.end()) return {};
return entry->second->appearanceArea();
}
ImageViewStyle imageViewStyle(TextDialogs dialogs)
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff)
{
const auto font=dialogs.readFont();
const auto colors=loadTextPreferences().profiles[0].colors;
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
preview->second->previewEmbeddedText(title,contents,diff);
}
ImageViewStyle imageViewStyle(TextDialogs dialogs,bool edit=false)
{
const auto font=scaledDocumentFont(dialogs,edit);
const auto colors=resolvedTextProfile(loadTextPreferences(),edit).colors;
return {font.font,font.tenthsOfPoint,colors[0],colors[1],colors[2],colors[3],colors[4]};
}
@@ -3319,7 +3597,8 @@ void previewImageQuickViewFile(HWND window,const std::filesystem::path &path)
}
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source)
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source,const ImageEditDialogs *editor,
const ImageWindowSession *session)
{
try
{
@@ -3349,26 +3628,35 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
}
}
if(!textWindows.contains(owner)) filesOwner=owner;
const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load),
const auto window=createImageView(owner,false,imageViewStyle(dialogs,editor!=nullptr),std::move(images),path,std::move(load),
[](HWND closed) {
std::erase(textWindowOrder,closed);
quitWhenFilesWindowsClose();
},std::move(retry));
if(!window) throw std::runtime_error("Could not open the image viewer.");
},std::move(retry),editor);
if(!window) throw std::runtime_error(editor?"Could not open the image editor.":"Could not open the image viewer.");
textWindowOrder.push_back(window);
const auto instance=GetModuleHandleW(nullptr);
const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(IDI_FILES_VIEWER),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE);
const int iconId=editor?IDI_FILES_EDITOR:IDI_FILES_VIEWER;
const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(iconId),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE);
if(icon) SendMessageW(window,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(icon));
setFileWindowTaskbar(window,IDI_FILES_VIEWER,L"HrynCo.KSwitcher.Files.Viewer");
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
setFileWindowTaskbar(window,iconId,editor?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
if(session) restoreImageWindowSession(window,*session);
ShowWindow(window,session?restoreDocumentPlacement(window,owner,session->bounds,session->maximized):
IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
SetFocus(window);
}
catch(const std::exception &error) {dialogs.message(owner,wide(error.what()).c_str());}
catch(const std::exception &error)
{
if(!session) dialogs.message(owner,wide(error.what()).c_str());
else log(L"Restore Files image: "+wide(error.what()));
}
}
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options)
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options,
const nlohmann::json *session=nullptr)
{
HWND created{};
if(!edit && !options.draft && !options.hex && !options.line && isImagePath(path))
{
openImageWindow(owner,{path},path,dialogs,nullptr,backend);
@@ -3404,10 +3692,90 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,bounds.left,bounds.top,bounds.right-bounds.left,
bounds.bottom-bounds.top,nullptr,nullptr,instance,&state);
if(!window) return;
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
created=window;
int show=IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
if(session)
{
state->restoreSession(*session);
show=restoreDocumentPlacement(window,owner,readDocumentBounds(*session),session->value("maximized",false));
}
ShowWindow(window,show);
SendMessageW(window,WM_SETFOCUS,0,0);
}
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
catch(const std::exception &error)
{
if(!session) dialogs.message(owner,wide(error.what()).c_str());
else
{
if(created) DestroyWindow(created);
log(L"Restore Files document: "+wide(error.what()));
}
}
}
constexpr wchar_t localSessionKey[]=L"LocalDocumentsV1";
void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled)
{
if(!enabled)
{
RegDeleteKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey);
return;
}
auto session=nlohmann::json::array();
for(const auto window:textWindowOrder)
{
if(session.size()>=128) break;
if(const auto found=textWindows.find(window);found!=textWindows.end())
{
auto state=found->second->sessionState();
if(!state.is_null()) session.push_back(std::move(state));
}
else if(const auto image=imageWindowSession(window))
{
nlohmann::json state{{"path",utf8(image->path.native())},{"editor",image->editor},{"image",true},
{"fit",image->fit},{"zoom",image->zoom},{"x",image->x},{"y",image->y}};
writeDocumentPlacement(state,window);
session.push_back(std::move(state));
}
}
const auto text=session.dump();
if(text.size()<=1024*1024)
RegSetKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,REG_BINARY,text.data(),static_cast<DWORD>(text.size()));
}
void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,
const ImageEditDialogs &imageEditor)
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>1024*1024) return;
std::string text(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,text.data(),&bytes)!=ERROR_SUCCESS)
return;
const auto session=nlohmann::json::parse(text.begin(),text.begin()+bytes,nullptr,false);
if(!session.is_array()) return;
for(size_t i=0;i<std::min<size_t>(128,session.size());++i)
{
try
{
const auto &state=session[i];
const std::filesystem::path path=wide(state.at("path").get<std::string>());
if(!isLocalDocumentPath(path)) continue;
const auto attributes=GetFileAttributesW(path.c_str());
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY)) continue;
const bool editor=state.value("editor",false);
if(state.value("image",false))
{
if(!isImagePath(path) || (editor && !isEditableImagePath(path))) continue;
ImageWindowSession image{path,editor,state.value("fit",true),state.value("zoom",1.0),
state.value("x",0.0),state.value("y",0.0),readDocumentBounds(state),state.value("maximized",false)};
openImageWindow(owner,{path},path,dialogs,nullptr,nullptr,editor?&imageEditor:nullptr,&image);
}
else openTextWindowImpl(owner,path,editor,dialogs,nullptr,{},true,{.hex=state.value("hex",false)},&state);
}
catch(const std::exception &error) {log(L"Restore Files document: "+wide(error.what()));}
}
}
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
+12 -3
View File
@@ -1,6 +1,7 @@
#pragma once
#include <windows.h>
#include "files_appearance.h"
#include <filesystem>
#include <functional>
#include <optional>
@@ -48,7 +49,7 @@ struct TextDialogs
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
void (*prepare)(HWND);
void (*options)(HWND, bool);
void (*options)(HWND, AppearanceArea);
void (*message)(HWND, const wchar_t *);
TextWindowFont (*readFont)();
FarDropDownPalette (*dropDownPalette)();
@@ -57,6 +58,8 @@ struct TextDialogs
bool (*dismissOwned)(HWND);
bool (*confirmExisting)(HWND);
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
bool (*reloadChanged)(HWND){};
unsigned (*readScale)(AppearanceArea){};
};
struct TextOpenOptions
@@ -106,11 +109,14 @@ RemoteTextSource createLanTextSource(const lan::FilesPeer &peer);
inline constexpr UINT quickViewToggleMessage=WM_APP+31;
HWND createQuickView(HWND owner,TextDialogs dialogs);
void previewQuickViewFile(HWND window,const std::filesystem::path &path);
void previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch);
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff=false);
HWND createImageQuickView(HWND owner,TextDialogs dialogs);
void previewImageQuickViewFile(HWND window,const std::filesystem::path &path);
struct ImageEditDialogs;
struct ImageWindowSession;
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr);
TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr,
const ImageEditDialogs *editor=nullptr,const ImageWindowSession *session=nullptr);
void showAllViewerBookmarks(HWND owner,TextDialogs dialogs);
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
@@ -118,8 +124,11 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
TextOpenOptions options={});
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={});
void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled);
void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,const ImageEditDialogs &imageEditor);
void textWindowOwnerClosed();
void standaloneFilesWindowOpened();
void standaloneFilesWindowClosed();
bool cycleTextWindows(HWND current,bool reverse);
std::optional<AppearanceArea> textWindowAppearanceArea(HWND window);
}
+5
View File
@@ -102,6 +102,11 @@ public:
FtpDeleteFileA(ftp_->handle(),name.c_str()));
}
void preserveModificationTime(const fs::path &path,uint64_t modified)
{
if(sftp_ && modified) sftp_->preserveModificationTime(path,modified);
}
void prepareReplacement(const fs::path &staged,const fs::path &existing)
{
if(sftp_) sftp_->prepareReplacement(staged,existing);
+46
View File
@@ -1,18 +1,64 @@
#pragma once
#include <windows.h>
#include <objbase.h>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <string_view>
#include <system_error>
namespace ks::files
{
inline bool isLocalDocumentPath(const std::filesystem::path &path)
{
std::wstring_view name=path.native();
if(name.starts_with(L"\\\\?\\")) name.remove_prefix(4);
if(name.size()<3 || name[1]!=L':' || (name[2]!=L'\\' && name[2]!=L'/')) return false;
const auto type=GetDriveTypeW(std::wstring(name.substr(0,3)).c_str());
return type==DRIVE_FIXED || type==DRIVE_REMOVABLE || type==DRIVE_RAMDISK || type==DRIVE_CDROM;
}
inline std::filesystem::path temporaryPath(const std::filesystem::path &directory)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Cannot create a temporary file name.");
return directory/(std::wstring(L".kswitcher-")+name+L".tmp");
}
inline bool sameFileIdentity(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
{
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
left.nFileIndexLow==right.nFileIndexLow;
}
struct LocalFileVersion
{
BY_HANDLE_FILE_INFORMATION info{};
LONGLONG changeTime{};
bool operator==(const LocalFileVersion &other) const
{
return sameFileIdentity(info,other.info) && changeTime==other.changeTime &&
info.nFileSizeHigh==other.info.nFileSizeHigh && info.nFileSizeLow==other.info.nFileSizeLow &&
CompareFileTime(&info.ftLastWriteTime,&other.info.ftLastWriteTime)==0;
}
};
inline LocalFileVersion fileVersion(HANDLE file)
{
LocalFileVersion version;
if(!GetFileInformationByHandle(file,&version.info))
throw std::system_error(static_cast<int>(GetLastError()),std::system_category(),"Read file revision");
FILE_BASIC_INFO basics{};
if(GetFileInformationByHandleEx(file,FileBasicInfo,&basics,sizeof(basics)))
version.changeTime=basics.ChangeTime.QuadPart;
return version;
}
inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement,
const std::filesystem::path &backup)
{
+23 -82
View File
@@ -9,7 +9,7 @@
#include "lan_layout.h"
#include "lan_network.h"
#include "lan_wake.h"
#include "lan_clients.h"
#include "lan_client_files.h"
#include <atomic>
#include <mutex>
#include <thread>
@@ -183,24 +183,16 @@ struct LanService::Impl
~Impl() { clients.stop(); stop(); }
void startClients()
{
clients.start([this](const Json &request, const auto &allowed, const auto &send) {
const auto action = request.at("action").get<std::string>();
auto reply = [&](const Json &result) {
const auto text = result.dump();
send(text.data(), DWORD(text.size()));
clients.start([this](const Json &request, const auto &allowed, const auto &send, const auto &receive, const auto &asCaller) {
const auto reachable = [&](const Peer &peer) {
return enabled && peer.files && peer.verified && GetTickCount64() - peer.verified < lan::PeerLifetime;
};
lan::FilesPeer target;
std::string local, key;
auto machines = Json::array();
if (request.at("action") == "peers")
{
std::lock_guard gate(commandGate);
std::lock_guard lock(mutex);
const auto now = GetTickCount64();
const auto reachable = [&](const Peer &peer) {
return enabled && peer.files && peer.verified && now - peer.verified < lan::PeerLifetime;
};
if (action == "peers")
auto machines = Json::array();
{
std::lock_guard gate(commandGate);
std::lock_guard lock(mutex);
refreshFiles = true;
for (const auto &[peer, pair] : trusted.items())
{
@@ -209,74 +201,23 @@ struct LanService::Impl
{"online", found != peers.end() && reachable(found->second)}});
}
}
else
{
if (action != "drives" && action != "list" && action != "download")
throw std::runtime_error("Unsupported LAN client operation.");
const auto peer = request.at("peer").get<std::string>();
const auto found = peers.find(peer);
if (!trusted.contains(peer) || found == peers.end() || !reachable(found->second))
throw std::runtime_error("The paired computer is offline or file browsing is unavailable.");
char address[INET_ADDRSTRLEN]{};
auto ip = found->second.address.sin_addr;
if (!InetNtopA(AF_INET, &ip, address, sizeof(address)))
throw std::runtime_error("The paired computer has no usable address.");
target = {peer, address, wide(found->second.name), lan::FilesPort, true};
local = id;
key = trusted.at(peer).at("key").get<std::string>();
}
}
if (action == "peers")
{
reply(machines);
const auto result = machines.dump();
send(result.data(), DWORD(result.size()));
return;
}
lan::FilesConnection connection(target, local, key);
if (action == "drives")
{
const auto result = connection.call({{"action", "drives"}});
lan::checkFileReply(result);
reply(result.at("drives"));
return;
}
const auto path = lan::filePath(request.at("path"));
if (action == "list")
{
auto page = connection.call(lan::fileRequest("list", path));
auto entries = Json::array();
size_t bytes{};
for (;;)
{
lan::checkFileReply(page);
for (auto &entry : page.at("entries"))
{
bytes += entry.dump().size() + 1;
if (bytes > 8 * 1024 * 1024) throw std::runtime_error("The remote directory listing is too large.");
entries.push_back(std::move(entry));
}
if (!page.at("more").get<bool>()) break;
allowed();
page = connection.call({{"action", "listNext"}});
}
reply(entries);
return;
}
const auto file = connection.call(lan::fileRequest("stat", path));
lan::checkFileReply(file);
auto open = lan::fileRequest("openRead", path);
open["size"] = file.at("size");
open["modified"] = file.at("modified");
lan::checkFileReply(connection.call(open));
reply({{"size", file.at("size")}});
for (;;)
{
allowed();
const auto chunk = connection.call({{"action", "read"}});
lan::checkFileReply(chunk);
const auto &data = chunk.at("data").get_binary();
send(data.data(), DWORD(data.size()));
if (data.empty()) break;
}
lan::routeClientFiles(request, allowed, send, receive, asCaller, [&](const std::string &peer) {
std::lock_guard gate(commandGate);
std::lock_guard lock(mutex);
const auto found = peers.find(peer);
if (!trusted.contains(peer) || found == peers.end() || !reachable(found->second))
throw std::runtime_error("The paired computer is offline or file browsing is unavailable.");
char address[INET_ADDRSTRLEN]{};
auto ip = found->second.address.sin_addr;
if (!InetNtopA(AF_INET, &ip, address, sizeof(address)))
throw std::runtime_error("The paired computer has no usable address.");
return lan::ClientFilesPeer{{peer, address, wide(found->second.name), lan::FilesPort, true},
id, trusted.at(peer).at("key").get<std::string>()};
});
});
}
void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted},
+380
View File
@@ -0,0 +1,380 @@
#include "lan_client_files.h"
#include "files_win32_directory.h"
namespace ks::lan
{
namespace
{
namespace fs = std::filesystem;
using Access = ClientFilesAccess;
Json checked(FilesConnection &connection, const Json &request, const FileProgress &progress = {})
{
auto reply = connection.call(request, progress);
checkFileReply(reply);
return reply;
}
void sendJson(const ClientSend &send, const Json &reply)
{
const auto text = reply.dump();
send(text.data(), DWORD(text.size()));
}
void revision(Json &request, const Json &file)
{
request["size"] = file.at("size");
request["modified"] = file.at("modified");
}
Json stat(FilesConnection &host, const fs::path &path)
{
return checked(host, fileRequest("stat", path));
}
unsigned hostRevision(FilesConnection &host)
{
const auto result = host.call(fileRequest("fileCapabilities", L"C:\\"));
if (result.at("error") == ERROR_INVALID_FUNCTION) return 0;
checkFileReply(result);
return result.at("revision").get<unsigned>();
}
void requireCurrentHost(FilesConnection &host)
{
if (!hostRevision(host)) throw std::runtime_error("Update the paired computer to use this operation.");
}
bool granted(const ClientCheck &check, Access access)
{
try { check(access); return true; }
catch (const std::runtime_error &) { check(Access::Browse); return false; }
}
Json capabilities(bool write, bool erase, unsigned host)
{
return {{"protocol", 2}, {"hostRevision", host}, {"write", write && host},
{"delete", erase && host}, {"move", write && erase && host},
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0}};
}
fs::path itemPath(const Json &value)
{
auto path = filePath(value).lexically_normal();
// Only regular drive paths reach remote mutations; never allow operating on a drive root.
const auto root = path.root_name().native();
if (root.size() != 2 || root[1] != L':' || !path.is_absolute() || path.filename().empty())
throw std::runtime_error("Choose a file or folder below a drive root.");
for (const auto &part : path.relative_path())
if (!files::validWindowsFileName(part.native()))
throw std::runtime_error("Invalid Windows file name.");
return path;
}
bool directory(const Json &item) { return item.at("attributes").get<DWORD>() & FILE_ATTRIBUTE_DIRECTORY; }
bool reparse(const Json &item) { return item.at("attributes").get<DWORD>() & FILE_ATTRIBUTE_REPARSE_POINT; }
void requireRegular(const Json &item)
{
if (reparse(item)) throw std::runtime_error("A file tree cannot include a junction or symbolic link.");
}
Json list(FilesConnection &host, const fs::path &path, const std::function<void()> &guard)
{
auto page = host.call(fileRequest("list", path));
auto entries = Json::array();
size_t bytes{};
for (;;)
{
checkFileReply(page);
for (auto &entry : page.at("entries"))
{
bytes += entry.dump().size() + 1;
if (bytes > 8 * 1024 * 1024) throw std::runtime_error("The remote directory listing is too large.");
entries.push_back(std::move(entry));
}
if (!page.at("more").get<bool>()) return entries;
guard();
page = host.call({{"action", "listNext"}});
}
}
bool absent(const Json &result)
{
return result.at("error") == ERROR_FILE_NOT_FOUND || result.at("error") == ERROR_PATH_NOT_FOUND;
}
bool sameOrBelow(const fs::path &parent, const fs::path &candidate)
{
auto part = candidate.begin();
for (const auto &component : parent)
{
if (part == candidate.end() || CompareStringOrdinal(component.c_str(), -1, part->c_str(), -1, TRUE) != CSTR_EQUAL)
return false;
++part;
}
return true;
}
fs::path canonical(FilesConnection &host, const fs::path &path)
{
return filePath(checked(host, fileRequest("canonical", path)).at("path")).lexically_normal();
}
class ClientTransfer
{
FilesConnection &source, &target;
const bool sameHost, move;
const std::string sourceId, conflict;
const std::function<void()> guard;
const ClientSend &send;
const ClientReceive &receive;
uint64_t completed{}, skipped{};
struct Removal { fs::path path; Json metadata; };
std::vector<Removal> removals;
void progress(const fs::path &path, uint64_t done, uint64_t total, const char *phase = "copy")
{
guard();
sendJson(send, {{"type", "progress"}, {"phase", phase}, {"path", utf8(path.native())},
{"done", done}, {"total", total},
{"completed", completed}, {"skipped", skipped}});
const auto result = Json::parse(receive(256));
if (!result.at("continue").get<bool>()) throw std::system_error(ERROR_CANCELLED, std::system_category());
guard();
}
bool copy(const fs::path &from, const fs::path &to, unsigned depth)
{
if (depth > 256) throw std::runtime_error("The file tree is too deep.");
progress(from, 0, 0);
const auto original = stat(source, from);
requireRegular(original);
const auto existing = target.call(fileRequest("stat", to));
const bool found = !absent(existing);
if (found)
{
checkFileReply(existing);
if (conflict == "skip") { ++skipped; return false; }
if (conflict != "replace" || directory(original) != directory(existing))
throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
requireRegular(existing);
}
bool whole = true;
if (directory(original))
{
if (!found)
{
guard();
checked(target, fileRequest("mkdir", to));
}
for (const auto &entry : list(source, from, guard))
{
const auto child = wide(entry.at("name").get<std::string>());
if (!files::validWindowsFileName(child)) throw std::runtime_error("Invalid directory entry.");
if (!copy(from / child, to / child, depth + 1)) whole = false;
}
}
else
{
ULONGLONG last{};
const auto onProgress = [&](uint64_t done, uint64_t total) {
guard();
const auto now = GetTickCount64();
if (!last || now - last >= 200 || done == total)
{
progress(from, done, total);
last = now;
}
return true;
};
const FileRevision expected{existing.value("size", uint64_t{}), existing.value("modified", uint64_t{})};
if (sameHost)
{
auto request = fileRequest("copy", from);
request.update({{"target", utf8(to.native())}, {"replace", found}, {"append", false}, {"resume", false}});
revision(request, original);
if (found) request.update({{"expectedSize", expected.size}, {"expectedModified", expected.modified}});
checked(source, request, onProgress);
}
else streamFile(source, target, sourceId, from, to, original.at("size"), original.at("modified"),
found, false, onProgress, found ? &expected : nullptr, false);
}
++completed;
if (move && whole) removals.push_back({from, original});
return whole;
}
public:
ClientTransfer(FilesConnection &source, FilesConnection &target, bool sameHost, bool move,
const std::string &sourceId, const std::string &conflict, const std::function<void()> &guard,
const ClientSend &send, const ClientReceive &receive)
: source(source), target(target), sameHost(sameHost), move(move), sourceId(sourceId), conflict(conflict),
guard(guard), send(send), receive(receive) {}
void run(const fs::path &from, const fs::path &to)
{
if (conflict != "fail" && conflict != "skip" && conflict != "replace")
throw std::runtime_error("Unknown conflict policy.");
if (sameHost)
{
const auto sourcePath = canonical(source, from);
const auto targetPath = canonical(target, to);
if (sameOrBelow(sourcePath, targetPath) || sameOrBelow(targetPath, sourcePath))
throw std::runtime_error("Source and destination paths overlap.");
}
copy(from, to, 0);
if (!removals.empty()) progress(from, 0, 0, "remove");
for (const auto &entry : removals)
{
guard();
auto request = fileRequest(directory(entry.metadata) ? "rmdir" : "remove", entry.path);
if (!directory(entry.metadata)) revision(request, entry.metadata);
checked(source, request);
}
sendJson(send, {{"type", "complete"}, {"completed", completed}, {"skipped", skipped}});
}
};
void read(FilesConnection &host, const fs::path &path, const Json &request, bool legacy, const ClientSend &send,
const std::function<void()> &guard)
{
const auto file = stat(host, path);
auto open = fileRequest("openRead", path);
revision(open, file);
if (request.contains("expected") &&
(request.at("expected").at("size") != file.at("size") ||
request.at("expected").at("modified") != file.at("modified")))
throw std::system_error(ERROR_FILE_INVALID, std::system_category());
guard();
checked(host, open);
sendJson(send, legacy ? Json{{"size", file.at("size")}} : file);
for (;;)
{
guard();
const auto chunk = checked(host, {{"action", "read"}});
const auto &data = chunk.at("data").get_binary();
send(data.data(), DWORD(data.size()));
if (data.empty()) return;
}
}
void write(FilesConnection &host, const fs::path &path, const Json &request, const ClientSend &send,
const ClientReceive &receive, const std::function<void()> &guard)
{
const auto size = request.at("size").get<uint64_t>();
auto upload = fileRequest("openWrite", path);
upload.update({{"size", size}, {"transfer", randomHex(32)}, {"resume", false}});
guard();
checked(host, upload);
sendJson(send, {{"type", "ready"}});
uint64_t done{};
for (;;)
{
auto data = receive(DWORD(FileChunk));
guard();
if (data.empty()) break;
if (data.size() > size - done) throw std::runtime_error("The upload exceeds the declared size.");
done += data.size();
checked(host, {{"action", "write"}, {"data", Json::binary(std::move(data))}});
}
if (done != size) throw std::runtime_error("The upload ended before the declared size.");
FILETIME now{};
GetSystemTimeAsFileTime(&now);
Json commit{{"action", "commit"}, {"replace", false},
{"modified", uint64_t(now.dwLowDateTime) | (uint64_t(now.dwHighDateTime) << 32)}};
if (request.contains("expected"))
{
commit["action"] = "commitEdit";
commit["expectedSize"] = request.at("expected").at("size");
commit["expectedModified"] = request.at("expected").at("modified");
}
guard();
checked(host, commit);
sendJson(send, stat(host, path));
}
void removeTree(FilesConnection &host, const fs::path &path, bool recursive, unsigned depth,
const std::function<void()> &guard)
{
if (depth > 256) throw std::runtime_error("The file tree is too deep.");
guard();
const auto item = stat(host, path);
if (recursive && directory(item) && !reparse(item))
{
for (const auto &entry : list(host, path, guard))
{
const auto child = wide(entry.at("name").get<std::string>());
if (!files::validWindowsFileName(child)) throw std::runtime_error("Invalid directory entry.");
removeTree(host, path / child, true, depth + 1, guard);
}
}
auto request = fileRequest(directory(item) ? "rmdir" : "remove", path);
if (!directory(item) && !reparse(item)) revision(request, item);
guard();
checked(host, request);
}
}
void routeClientFiles(const Json &request, const ClientCheck &check, const ClientSend &send,
const ClientReceive &receive, const ClientAsCaller &asCaller, const ClientFilesResolve &resolve)
{
const auto action = request.at("action").get<std::string>();
if (action == "capabilities" && !request.contains("peer"))
{
sendJson(send, capabilities(granted(check, Access::Write), granted(check, Access::Delete), 1));
return;
}
if (action == "transfer")
{
const auto &from = request.at("source");
const auto &to = request.at("target");
const bool move = request.value("move", false);
const auto guard = [&] { check(move ? Access::Move : Access::Write); };
guard();
const bool fromLocal = from.at("peer").is_null(), toLocal = to.at("peer").is_null();
if (fromLocal && toLocal) throw std::runtime_error("At least one path must be on a paired computer.");
const auto first = fromLocal ? ClientFilesPeer{} : resolve(from.at("peer"));
const auto second = toLocal ? ClientFilesPeer{} : resolve(to.at("peer"));
const auto copy = [&] {
const auto open = [](const ClientFilesPeer &peer) {
if (peer.peer.id.empty()) return std::make_unique<FilesConnection>();
auto host = std::make_unique<FilesConnection>(peer.peer, peer.localId, peer.key);
requireCurrentHost(*host);
return host;
};
const auto source = open(first), target = open(second);
ClientTransfer(*source, *target, first.peer.id == second.peer.id, move, first.peer.id,
request.value("conflict", "fail"), guard, send, receive)
.run(itemPath(from.at("path")), itemPath(to.at("path")));
};
if (fromLocal || toLocal) asCaller(copy);
else copy();
return;
}
auto access = Access::Browse;
if (action == "mkdir" || action == "rename" || action == "writeFile") access = Access::Write;
else if (action == "recycle" || action == "delete") access = Access::Delete;
else if (action != "drives" && action != "list" && action != "download" && action != "stat" &&
action != "readFile" && action != "capabilities")
throw std::runtime_error("Unsupported LAN client operation.");
const auto guard = [&] { check(access); };
guard();
const auto resolved = resolve(request.at("peer"));
FilesConnection host(resolved.peer, resolved.localId, resolved.key);
if (action == "capabilities")
sendJson(send, capabilities(granted(check, Access::Write), granted(check, Access::Delete), hostRevision(host)));
else if (action == "drives") sendJson(send, checked(host, {{"action", "drives"}}).at("drives"));
else if (action == "list") sendJson(send, list(host, filePath(request.at("path")), guard));
else if (action == "download") read(host, filePath(request.at("path")), Json::object(), true, send, guard);
else if (action == "stat") sendJson(send, stat(host, filePath(request.at("path"))));
else
{
requireCurrentHost(host);
const auto path = itemPath(request.at("path"));
if (action == "readFile") read(host, path, request, false, send, guard);
else if (action == "writeFile") write(host, path, request, send, receive, guard);
else if (action == "delete")
{
removeTree(host, path, request.value("recursive", false), 0, guard);
sendJson(send, {{"error", 0}});
}
else
{
auto operation = fileRequest(action == "rename" ? "move" : action, path);
if (action == "rename")
{
const auto name = wide(request.at("name").get<std::string>());
if (!files::validWindowsFileName(name)) throw std::runtime_error("Invalid Windows file name.");
operation.update({{"target", utf8((path.parent_path() / name).native())}, {"replace", false}});
}
guard();
sendJson(send, checked(host, operation));
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include "lan_clients.h"
#include "lan_files.h"
namespace ks::lan
{
struct ClientFilesPeer
{
FilesPeer peer;
std::string localId, key;
};
using ClientFilesResolve = std::function<ClientFilesPeer(const std::string &)>;
void routeClientFiles(const Json &request, const ClientCheck &check, const ClientSend &send,
const ClientReceive &receive, const ClientAsCaller &asCaller, const ClientFilesResolve &resolve);
}
+47 -10
View File
@@ -9,6 +9,12 @@
namespace ks::lan
{
enum class ClientFilesAccess : unsigned { Browse = 0, Write = 1, Delete = 2, Move = 3 };
using ClientCheck = std::function<void(ClientFilesAccess)>;
using ClientSend = std::function<void(const void *, DWORD)>;
using ClientReceive = std::function<Bytes(DWORD)>;
using ClientAsCaller = std::function<void(const std::function<void()> &)>;
class LanClients
{
struct Handle
@@ -106,8 +112,7 @@ class LanClients
{
return std::filesystem::exists(store) ? Json::parse(unprotect(readFile(store, 256 * 1024))) : Json::array();
}
using Rule = std::function<void()>;
Rule authorize(HANDLE pipe) const
ClientCheck authorize(HANDLE pipe) const
{
ULONG pid{};
if (!GetNamedPipeClientProcessId(pipe, &pid))
@@ -123,17 +128,25 @@ class LanClients
auto image = std::make_shared<ClientImage>(std::wstring(filename, length));
if (CompareFileTime(&image->modified, &started) > 0)
throw std::runtime_error("Restart the client after replacing its executable.");
Rule check = [this, process, image] {
ClientCheck check = [this, pipe, process, image](ClientFilesAccess access) {
if (WaitForSingleObject(stopped.value, 0) != WAIT_TIMEOUT ||
WaitForSingleObject(process->value, 0) != WAIT_TIMEOUT)
WaitForSingleObject(process->value, 0) != WAIT_TIMEOUT ||
!PeekNamedPipe(pipe, nullptr, 0, nullptr, nullptr, nullptr))
throw std::runtime_error("The local client disconnected.");
std::lock_guard lock(storeMutex);
for (const auto &entry : clients())
if (!_wcsicmp(wide(entry.at("path").get<std::string>()).c_str(), image->path.c_str()) &&
entry.at("sha256") == image->digest) return;
entry.at("sha256") == image->digest)
{
const auto mask = static_cast<unsigned>(access);
if (((mask & 1) && !entry.value("writeFiles", false)) ||
((mask & 2) && !entry.value("deleteFiles", false)))
throw std::runtime_error("Grant the required file permission in Trusted clients.");
return;
}
throw std::runtime_error("Authorize this executable in KSwitcher → Computers → Trusted clients.");
};
check();
check(ClientFilesAccess::Browse);
return check;
}
struct LocalMemory
@@ -141,8 +154,7 @@ class LanClients
void *value{};
~LocalMemory() { if (value) LocalFree(value); }
};
using Send = std::function<void(const void *, DWORD)>;
using Route = std::function<void(const Json &, const Rule &, const Send &)>;
using Route = std::function<void(const Json &, const ClientCheck &, const ClientSend &, const ClientReceive &, const ClientAsCaller &)>;
void serve(const Route &route, const std::wstring &instance) const
{
HANDLE rawToken{};
@@ -194,8 +206,32 @@ class LanClients
{
auto check = authorize(pipe.value);
route(Json::parse(request), check, [&](const void *data, DWORD bytes) {
check();
check(ClientFilesAccess::Browse);
if (!writeFrame(pipe.value, data, bytes)) throw std::runtime_error("The local client disconnected.");
}, [&](DWORD maximum) {
check(ClientFilesAccess::Browse);
DWORD bytes{};
if (!io(pipe.value, &bytes, sizeof(bytes), false) || bytes > maximum)
throw std::runtime_error("The local client disconnected or sent an invalid frame.");
Bytes data(bytes);
if (bytes && !io(pipe.value, data.data(), bytes, false))
throw std::runtime_error("The local client disconnected.");
return data;
}, [&](const std::function<void()> &operation) {
if (!ImpersonateNamedPipeClient(pipe.value))
throw std::runtime_error("The pipe must allow Windows client impersonation for local paths.");
struct Revert
{
~Revert() { if (!RevertToSelf()) std::terminate(); }
} revert;
Handle caller;
SECURITY_IMPERSONATION_LEVEL level{};
DWORD length{};
if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &caller.value) ||
!GetTokenInformation(caller.value, TokenImpersonationLevel, &level, sizeof(level), &length) ||
level < SecurityImpersonation)
throw std::runtime_error("The pipe must allow Windows client impersonation for local paths.");
operation();
});
}
}
@@ -235,7 +271,8 @@ public:
return !_wcsicmp(wide(entry.at("path").template get<std::string>()).c_str(), image.path.c_str());
});
if (entries.size() >= 64) throw std::runtime_error("The trusted client list is full.");
entries.push_back({{"path", utf8(image.path)}, {"sha256", image.digest}});
entries.push_back({{"path", utf8(image.path)}, {"sha256", image.digest},
{"writeFiles", request.value("writeFiles", false)}, {"deleteFiles", request.value("deleteFiles", false)}});
}
else
{
+74 -6
View File
@@ -8,6 +8,7 @@
#include <bcrypt.h>
#include <wincrypt.h>
#include <sddl.h>
#include <aclapi.h>
#include <winsafer.h>
#include <cstring>
#include <mutex>
@@ -679,6 +680,7 @@ public:
}
return reply;
}
if(action=="fileCapabilities") return {{"error",0},{"revision",1},{"copyMetadata",true}};
if(action=="listNext") return listNext();
if(action=="read")
{
@@ -769,6 +771,67 @@ public:
const auto canonical=fs::weakly_canonical(name,error);
return error?failure(error.value()):Json{{"error",0},{"path",utf8(canonical.native())}};
}
if(action=="copyPermissions")
{
DWORD size{};
GetFileSecurityW(name.c_str(),DACL_SECURITY_INFORMATION,nullptr,0,&size);
if(!size || GetLastError()!=ERROR_INSUFFICIENT_BUFFER) return failure();
Bytes descriptor(size);
if(!GetFileSecurityW(name.c_str(),DACL_SECURITY_INFORMATION,descriptor.data(),size,&size)) return failure();
LPWSTR sddl{};
if(!ConvertSecurityDescriptorToStringSecurityDescriptorW(descriptor.data(),SDDL_REVISION_1,
DACL_SECURITY_INFORMATION,&sddl,nullptr)) return failure();
const auto value=utf8(sddl);
LocalFree(sddl);
return {{"error",0},{"permissions",value}};
}
if(action=="applyCopyMetadata")
{
if(request.contains("modified"))
{
FileHandle file{CreateFileW(name.c_str(),FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return failure();
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file.value,&info)) return failure();
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT) return failure(ERROR_NOT_SUPPORTED);
auto stamp=request.at("modified").get<uint64_t>();
FILETIME time{static_cast<DWORD>(stamp),static_cast<DWORD>(stamp>>32)};
if(!stamp) GetSystemTimeAsFileTime(&time);
if(!SetFileTime(file.value,nullptr,nullptr,&time)) return failure();
}
if(request.contains("permissions"))
{
FileHandle file{CreateFileW(name.c_str(),FILE_READ_ATTRIBUTES|READ_CONTROL|WRITE_DAC,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return failure();
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file.value,&info)) return failure();
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT) return failure(ERROR_NOT_SUPPORTED);
PSECURITY_DESCRIPTOR descriptor{};
const auto sddl=wide(request.at("permissions").get<std::string>());
if(!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(),SDDL_REVISION_1,
&descriptor,nullptr)) return failure();
SECURITY_DESCRIPTOR_CONTROL control{};
DWORD revision{};
BOOL present{}, defaulted{};
PACL acl{};
auto error=DWORD(ERROR_SUCCESS);
if(!GetSecurityDescriptorDacl(descriptor,&present,&acl,&defaulted) || !present ||
!GetSecurityDescriptorControl(descriptor,&control,&revision)) error=ERROR_INVALID_DATA;
else
{
auto security=DACL_SECURITY_INFORMATION|((control&SE_DACL_PROTECTED)?
PROTECTED_DACL_SECURITY_INFORMATION:UNPROTECTED_DACL_SECURITY_INFORMATION);
error=SetSecurityInfo(file.value,SE_FILE_OBJECT,security,nullptr,nullptr,acl,nullptr);
}
LocalFree(descriptor);
if(error) return failure(error);
}
return ok();
}
if(action=="mkdir") return CreateDirectoryW(name.c_str(),nullptr)?ok():failure();
if(action=="mkdir-link")
{
@@ -824,8 +887,11 @@ public:
{
// Both streams execute inside the serving process.
FilesConnection source,target;
const auto edit=request.contains("expectedSize");
const FileRevision expected{request.value("expectedSize",uint64_t{}),
request.value("expectedModified",uint64_t{})};
streamFile(source,target,"same host",name,destination,request.at("size"),request.at("modified"),
request.at("replace"),request.at("append"),progress);
request.at("replace"),request.at("append"),progress,edit?&expected:nullptr,request.value("resume",true));
return ok();
}
return copy(name,destination,request.at("replace"),request.at("append"),progress);
@@ -856,7 +922,8 @@ public:
expectedSize=request.at("size").get<uint64_t>();
const bool append=request.value("append",false);
appendBase=0;
auto staging=target.parent_path()/wide(".kswitcher-"+transfer+".partial");
const bool resume=request.value("resume",true);
const auto staging=target.parent_path()/wide(".kswitcher-"+transfer+".partial");
FileHandle original;
if(append)
{
@@ -866,7 +933,7 @@ public:
if(!GetFileInformationByHandle(original.value,&info)) return failure();
appendBase=fileSize(info.nFileSizeHigh,info.nFileSizeLow);
}
output.value=CreateFileW(staging.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_ALWAYS,
output.value=CreateFileW(staging.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,resume?OPEN_ALWAYS:CREATE_NEW,
FILE_ATTRIBUTE_HIDDEN|FILE_FLAG_OPEN_REPARSE_POINT,nullptr);
if(output.value==INVALID_HANDLE_VALUE) return failure();
const bool created=GetLastError()!=ERROR_ALREADY_EXISTS;
@@ -875,7 +942,7 @@ public:
if(info.nNumberOfLinks!=1 || (info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)))
return failure(ERROR_ACCESS_DENIED);
temporary=staging;
resumable=true;
resumable=resume;
if(created && appendBase)
{
Bytes buffer(FileChunk);
@@ -971,7 +1038,7 @@ Json FilesConnection::call(const Json &request,const FileProgress &progress)
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination)
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination,bool resumable)
{
auto openSource=fileRequest("openRead",from);
openSource["size"]=size;
@@ -982,7 +1049,8 @@ void streamFile(FilesConnection &source,FilesConnection &target,const std::strin
upload["size"]=size;
const auto identity=Json::array({sourceId,ks::utf8(from.native()),ks::utf8(to.native()),
size,modified,append});
upload["transfer"]=ks::lan::mac("KSwitcher partial v1",identity.dump());
upload["transfer"]=resumable?ks::lan::mac("KSwitcher partial v1",identity.dump()):randomHex(32);
upload["resume"]=resumable;
uint64_t done=0;
const auto resumeProgress=[&](uint64_t,uint64_t){return !progress || progress(done,size);};
try
+2 -1
View File
@@ -31,7 +31,8 @@ public:
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr);
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr,
bool resumable=true);
DWORD runRemoteCommand(FilesConnection &host,const std::filesystem::path &directory,std::wstring_view command,
const std::function<void(std::string_view)> &output,std::stop_token stop={});
+35
View File
@@ -899,6 +899,41 @@ void setLoggingEnabled(bool enabled)
if (!enabled)
diagnosticBuffer.clear();
}
std::optional<Bytes> readActiveLogTail(bool previous,size_t byteLimit)
{
std::lock_guard lock(logGate);
auto path=logDirectory()/logFilename;
if(previous) path+=L".1";
const auto raw=CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(raw==INVALID_HANDLE_VALUE)
{
const auto error=GetLastError();
if(error==ERROR_FILE_NOT_FOUND || error==ERROR_PATH_NOT_FOUND) return {};
throw std::runtime_error("Cannot open the diagnostic log");
}
const std::unique_ptr<void,decltype(&CloseHandle)> file(raw,CloseHandle);
LARGE_INTEGER size{};
if(!GetFileSizeEx(raw,&size) || size.QuadPart<0) throw std::runtime_error("Cannot measure the diagnostic log");
const auto limit=std::min<uint64_t>(byteLimit,2*1024*1024);
if(!limit || !size.QuadPart) return Bytes{};
const auto offset=std::max<int64_t>(0,size.QuadPart-static_cast<int64_t>(limit));
LARGE_INTEGER position{};
position.QuadPart=offset?offset-1:0;
if(!SetFilePointerEx(raw,position,nullptr,FILE_BEGIN)) throw std::runtime_error("Cannot seek in the diagnostic log");
Bytes contents(static_cast<size_t>(size.QuadPart-position.QuadPart));
DWORD read{};
if(!ReadFile(raw,contents.data(),static_cast<DWORD>(contents.size()),&read,nullptr))
throw std::runtime_error("Cannot read the diagnostic log");
contents.resize(read);
if(offset && !contents.empty())
{
const auto newline=std::find(contents.begin(),contents.end(),'\n');
contents.erase(contents.begin(),newline==contents.end()?newline:std::next(newline));
}
return contents;
}
std::wstring readDiagnosticLog(bool previous)
{
std::lock_guard lock(logGate);
+1
View File
@@ -107,5 +107,6 @@ void expireDiagnostics(ULONGLONG now);
void diagnosticEvent(const std::wstring &message, bool problem = false);
void diagnosticOperation(const std::string &json);
std::wstring readDiagnosticLog(bool previous);
std::optional<Bytes> readActiveLogTail(bool previous,size_t byteLimit);
void clearDiagnosticLog(bool previous);
} // namespace ks
+43 -8
View File
@@ -54,6 +54,16 @@ struct LanClientsView
LanView *lan{};
nlohmann::json entries, saved;
};
void selectLanClient(HWND window, const LanClientsView &view, LRESULT index)
{
const bool selected = index >= 0 && size_t(index) < view.entries.size();
EnableWindow(GetDlgItem(window, 734), selected);
EnableWindow(GetDlgItem(window, 736), selected);
EnableWindow(GetDlgItem(window, 737), selected);
for (const auto &[id, key] : {std::pair{736, "writeFiles"}, std::pair{737, "deleteFiles"}})
SendDlgItemMessageW(window, id, BM_SETCHECK,
selected && view.entries[size_t(index)].value(key, false) ? BST_CHECKED : BST_UNCHECKED, 0);
}
void refreshLanClients(HWND window, LanClientsView &view)
{
view.entries = view.saved;
@@ -75,7 +85,7 @@ void refreshLanClients(HWND window, LanClientsView &view)
if (width > SendDlgItemMessageW(window, 732, LB_GETHORIZONTALEXTENT, 0, 0))
SendDlgItemMessageW(window, 732, LB_SETHORIZONTALEXTENT, width, 0);
}
EnableWindow(GetDlgItem(window, 734), FALSE);
selectLanClient(window, view, LB_ERR);
}
LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
{
@@ -100,7 +110,7 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
const auto index = SendDlgItemMessageW(window, 732, LB_GETCURSEL, 0, 0);
if (id == 732 && HIWORD(wp) == LBN_SELCHANGE)
{
EnableWindow(GetDlgItem(window, 734), index != LB_ERR);
selectLanClient(window, *view, index);
return 0;
}
try
@@ -116,7 +126,9 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
const auto canonical = entry.at("path").get<std::string>();
const auto key = utf8(lower(wide(canonical)));
auto &changes = view->lan->draft["clients"];
if (std::find(view->saved.begin(), view->saved.end(), entry) == view->saved.end())
if (std::none_of(view->saved.begin(), view->saved.end(), [&](const auto &saved) {
return saved.at("path") == entry.at("path") && saved.at("sha256") == entry.at("sha256");
}))
changes[key] = {{"action", "trustClient"}, {"path", canonical}, {"sha256", entry.at("sha256")}};
else if (changes.is_object()) changes.erase(key);
if (changes.empty()) view->lan->draft.erase("clients");
@@ -125,6 +137,27 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
}
return 0;
}
if ((id == 736 || id == 737) && index >= 0 && size_t(index) < view->entries.size())
{
auto entry = view->entries[size_t(index)];
const auto *permission = id == 736 ? "writeFiles" : "deleteFiles";
const auto checked = SendDlgItemMessageW(window, id, BM_GETCHECK, 0, 0) == BST_CHECKED;
if (checked && MessageBoxW(window, id == 736 ?
L"Allow this executable to create, rename, copy and overwrite files on paired computers?" :
L"Allow this executable to recycle and permanently delete files on paired computers?",
L"Change trusted client permissions", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES)
{
selectLanClient(window, *view, index);
return 0;
}
entry["action"] = "trustClient";
entry[permission] = checked;
const auto key = utf8(lower(wide(entry.at("path").get<std::string>())));
view->lan->draft["clients"][key] = entry;
view->entries[size_t(index)] = std::move(entry);
refreshLanFooter(*view->lan);
return 0;
}
if (id == 734 && index >= 0 && size_t(index) < view->entries.size())
{
const auto path = view->entries[size_t(index)].at("path").get<std::string>();
@@ -149,17 +182,19 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
}
void showLanClients(HWND parent, LanView &lan)
{
auto window = makeWindow(*lan.app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 280, 0, false);
auto window = makeWindow(*lan.app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 318, 0, false);
SetWindowLongPtrW(window, GWLP_HWNDPARENT, reinterpret_cast<LONG_PTR>(parent));
auto view = new LanClientsView{&lan};
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(view));
label(window, L"Trusted executables can browse and download files from paired computers.", 16, 14, 578);
control(window, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | WS_BORDER | LBS_NOTIFY |
LBS_NOINTEGRALHEIGHT, 732, 16, 42, 578, 152);
label(window, L"After updating an executable, add it again and click Apply or Save in Settings.", 16, 202, 578);
button(window, L"&Add client…", 733, 16, 236, 126);
button(window, L"&Remove", 734, 150, 236, 110);
button(window, L"&Close", IDCANCEL, 494, 236, 100);
control(window, L"BUTTON", L"Allow &write", WS_TABSTOP | BS_AUTOCHECKBOX, 736, 16, 200, 150, 26);
control(window, L"BUTTON", L"Allow &delete", WS_TABSTOP | BS_AUTOCHECKBOX, 737, 182, 200, 150, 26);
label(window, L"Move requires both permissions. Click Apply or Save in Settings.", 16, 232, 578);
button(window, L"&Add client…", 733, 16, 271, 126);
button(window, L"&Remove", 734, 150, 271, 110);
button(window, L"&Close", IDCANCEL, 494, 271, 100);
try
{
view->saved = lanRequest(*lan.app, {{"action", "trustedClients"}});
+56 -1
View File
@@ -1,4 +1,4 @@
#include "files_image_decode.h"
#include "files_image_edit.h"
#include <windows.h>
#include <wincodec.h>
#include <webp/encode.h>
@@ -84,6 +84,60 @@ void expectDecodeFailure(const fs::path &file,std::string_view text)
throw std::runtime_error("invalid image was decoded");
}
void verifyImageEdits(const fs::path &root)
{
ImageRaster original{4,3,{0xff110001,0xff110002,0xff110003,0xff110004,
0xff110005,0x80402010,0xff110007,0xff110008,0xff110009,0xff11000a,0xff11000b,0xff11000c}};
const ImageGeometry initial{{0,0,4,3},0};
const ImageGeometry clockwise{initial.region,1};
const auto rotated=transformImage(original,clockwise);
expect(rotated.width==3 && rotated.height==4 && rotated.pixels[0]==original.pixels[8] &&
rotated.pixels[11]==original.pixels[3],"clockwise rotation changed pixel order");
const auto reversed=transformImage(original,{initial.region,3});
expect(reversed.pixels.front()==original.pixels[3] && reversed.pixels.back()==original.pixels[8],
"counterclockwise rotation changed pixel order");
const auto cropped=transformImage(original,cropImage(clockwise,{1,1,2,2}));
expect(cropped.width==2 && cropped.height==2 && cropped.pixels==std::vector<uint32_t>{
original.pixels[5],original.pixels[1],original.pixels[6],original.pixels[2]},
"crop used coordinates before rotation");
bool outside=false;
try {cropImage(clockwise,{2,1,2,2});}
catch(const std::runtime_error &) {outside=true;}
expect(outside,"out-of-bounds crop was accepted");
const auto png=root/L"Редагування.png";
saveImage(cropped,png);
const auto saved=decodeImage(png,png);
expect(saved.width==2 && saved.height==2 && saved.pixels==cropped.pixels,"PNG copy lost alpha or pixels");
const auto before=imageRevision(png);
bool collision=false;
try {saveImage(rotated,png);}
catch(const std::system_error &) {collision=true;}
expect(collision && sameImageRevision(before,imageRevision(png)), "Save Copy overwrote an existing image");
const auto incoming=root/L"external.png";
saveImage(original,incoming);
fs::rename(png,root/L"first.png");
fs::rename(incoming,png);
bool stale=false;
try {saveImage(cropped,png,&before);}
catch(const std::runtime_error &) {stale=true;}
expect(stale && decodeImage(png,png).pixels==original.pixels,"Replace overwrote an external revision");
const auto current=imageRevision(png);
const auto written=saveImage(cropped,png,&current);
expect(sameImageRevision(written,imageRevision(png)), "returned revision did not track the installed image");
expect(decodeImage(png,png).pixels==cropped.pixels,"confirmed replacement lost image data");
const auto jpeg=root/L"copy.jpg";
const ImageRaster transparent{8,8,std::vector<uint32_t>(64,0)};
saveImage(transparent,jpeg);
const auto lossy=decodeImage(jpeg,jpeg);
expect(lossy.width==8 && lossy.height==8 && lossy.pixels.front()>=0xfffefefe,
"JPEG copy failed to composite transparency on white");
for(const auto &entry:fs::directory_iterator(root))
expect(entry.path().extension()!=L".tmp","image operation left a staging file");
}
std::vector<uint8_t> animatedWebp(const uint8_t *encoded,size_t size)
{
expect(size>12,"WebP fixture RIFF body");
@@ -109,6 +163,7 @@ int main()
{
expect(SUCCEEDED(apartment),"initialize COM");
Temp temp;
verifyImageEdits(temp.path);
for(const auto &[name,container]:std::array{
std::pair{L"знімок.PNG",&GUID_ContainerFormatPng},
std::pair{L"picture.jpeg",&GUID_ContainerFormatJpeg},
+17
View File
@@ -99,6 +99,23 @@ try {
: { key:'Enter', code:'Enter', windowsVirtualKeyCode:13 };
await command('Input.dispatchKeyEvent', { type:'keyDown', ...key });
await command('Input.dispatchKeyEvent', { type:'keyUp', ...key });
} else if (scenario === 'html-quick') {
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
document.querySelector('main h1')?.textContent === 'Offline HTML fixture'`), 'rendered HTML');
assert.equal(await evaluate(`document.querySelector('main td strong')?.textContent`), 'Formatted table');
assert.equal(await evaluate(`document.querySelector('main h1').style.color`), 'teal');
assert.equal(await evaluate(`document.querySelector('main h1').style.position`), '');
assert.equal(await evaluate(`document.querySelectorAll(
'main :is(script, style, link, meta, iframe, object, img, input, [href], [src], [onload], [onclick])'
).length`), 0);
assert.equal(await evaluate(`document.querySelector('main').textContent.includes('Image description')`), true);
assert.equal(await evaluate(`window.documentScriptRan`), undefined);
await evaluate(`document.querySelector('main a').click()`);
assert.equal(await evaluate('location.href'), 'https://kswitcher-markdown.invalid/markdown.html');
if (artifact) {
const screenshot = await command('Page.captureScreenshot', { format: 'png' });
await writeFile(artifact, Buffer.from(screenshot.data, 'base64'));
}
} else if (scenario === 'render') {
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
!!document.querySelector('figure svg') &&
+173 -32
View File
@@ -1,60 +1,133 @@
param(
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe"
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe",
[string]$ProfileSubkey = 'Software\KSwitcher\Files',
[string]$Node = (Get-Command node -ErrorAction SilentlyContinue).Source,
[string]$RenderedImage = '',
[string]$BinaryImage = ''
)
$ErrorActionPreference = 'Stop'
. "$PSScriptRoot/files_commands_ui.ps1"
$browserProbe = $Node -and ((& $Node -p "typeof WebSocket === 'function'") -eq 'true')
if($RenderedImage -and !$browserProbe){throw 'A Node runtime with WebSocket is required for a rendered screenshot'}
Add-Type @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class FilesQuickViewProbe {
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr parent, int id);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(0x12, 0, 0, UIntPtr.Zero);
keybd_event(0x12, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x,
int y, int width, int height, uint flags);
[DllImport("user32.dll", EntryPoint="PostMessageW")]
public static extern bool Post(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
[DllImport("user32.dll", EntryPoint="SendMessageW")]
public static extern IntPtr Send(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
public static extern IntPtr FindRow(IntPtr window, uint msg, IntPtr wp, string name);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr wp, StringBuilder text);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
}
'@
function Wait-Until([scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 100; $attempt++) {
if (& $Condition) { return }
function Wait-Until([string]$Label,[scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 150; $attempt++) {
$result = & $Condition
if ($result) { return $result }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for: $Condition"
throw "Timed out waiting for $Label"
}
function Text([IntPtr]$Handle) {
$buffer = [Text.StringBuilder]::new(256)
[void][FilesQuickViewProbe]::Read($Handle, 13, [IntPtr]$buffer.Capacity, $buffer)
$buffer.ToString()
}
function Select-File([string]$Name) {
$row = [FilesQuickViewProbe]::FindRow($leftList, 0x1A2, [IntPtr](-1), $Name)
if ($row.ToInt64() -lt 0) { throw "Missing row $Name" }
[void][FilesQuickViewProbe]::Send($leftList, 0x186, $row, 0)
[void][FilesQuickViewProbe]::Post($window, 273, [IntPtr](0x10000+102), $leftList)
}
function Preview-Bytes([int]$Count) {
[byte[]]$bytes = @(
for($i=0; $i -lt $Count; ++$i) {
[byte]([FilesQuickViewProbe]::Send($editor, 2007, [IntPtr]$i, 0).ToInt32() -band 255)
}
)
[Text.Encoding]::UTF8.GetString($bytes)
}
function Browser {
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'html-quick' $RenderedImage 'preview.html'
if ($LASTEXITCODE) { throw 'WebView2 verification failed for rendered HTML' }
}
$exe = (Resolve-Path $Executable).Path
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
$source = Split-Path $exe
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ProfileSubkey)
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor',
'LeftPanelMode', 'RightPanelMode', 'WindowPlacement'
$saved = @{}
foreach ($name in $names) {
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
}
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$profile = $env:WEBVIEW2_USER_DATA_FOLDER
$fixture = [IO.Directory]::CreateTempSubdirectory('ks-files-quick-view-')
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
try {
$network = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$network.Start()
$probe = "http://127.0.0.1:$($network.LocalEndpoint.Port)/should-not-load"
$debug = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$debug.Start()
$port = $debug.LocalEndpoint.Port
$debug.Stop()
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = "--remote-debugging-port=$port --disable-background-networking"
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $fixture.FullName 'webview'
$app = $fixture.CreateSubdirectory('app')
Copy-Item -LiteralPath $exe,"$source\WebView2Loader.dll","$source\terminal" -Destination $app.FullName -Recurse
$left = $fixture.CreateSubdirectory('left')
$right = $fixture.CreateSubdirectory('right')
$document = Join-Path $left.FullName 'preview.txt'
[IO.File]::WriteAllText($document, 'Quick View fixture')
$key.SetValue('LeftWide', 1, 'DWord')
$key.SetValue('RightWide', 1, 'DWord')
[IO.File]::WriteAllText((Join-Path $left.FullName 'preview.html'), @"
<!doctype html>
<html><head><title>Document title</title>
<meta http-equiv="refresh" content="0;url=$probe">
<link rel="stylesheet" href="$probe">
<style>@import url('$probe');</style>
<script>window.documentScriptRan = true;</script></head>
<body onload="window.documentScriptRan = true;"><main>
<h1 style="color: teal; position: fixed" onclick="window.documentScriptRan = true;">Offline HTML fixture</h1>
<table><tr><td><strong>Formatted table</strong></td></tr></table>
<a href="$probe">External link</a>
<img src="$probe" alt="Image description"><iframe src="$probe"></iframe>
<form action="$probe"><input type="submit"></form>
</main></body></html>
"@)
$data = [byte[]]::new(5000)
[byte[]]$header = 0,1,9,10,13,27,31,32,65,127,128,255
$header.CopyTo($data,0)
for ($i=$header.Length; $i -lt $data.Length; ++$i) { $data[$i] = 66 }
[IO.File]::WriteAllBytes((Join-Path $left.FullName 'symbols.bin'), $data)
$expectedSymbols = -join ([char[]]@(0xe000,0xe001,0xe009,0xe00a,0xe00d,0xe01b,0xe01f,
0x20,0x41,0xe07f,0xC7,0xe0ff))
$key.SetValue('LeftPanelMode', 1, 'DWord')
$key.SetValue('RightPanelMode', 1, 'DWord')
$key.SetValue('LeftPath', $left.FullName, 'String')
$key.SetValue('RightPath', $right.FullName, 'String')
$key.SetValue('LeftCursor', $document, 'String')
$key.DeleteValue('RightCursor', $false)
$key.DeleteValue('WindowPlacement', $false)
$process = Start-Process -FilePath $exe -PassThru
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
$window = $process.MainWindowHandle
Wait-Until { [FilesQuickViewProbe]::Activate($window) }
$keyboard = New-Object -ComObject WScript.Shell
$process = Start-Process -FilePath (Join-Path $app.FullName (Split-Path -Leaf $exe)) -PassThru -WindowStyle Normal
$window = Wait-Until 'the Files window' {
$process.Refresh()
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
}
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,1500,920,20)
$leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102)
$rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103)
$rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141)
@@ -62,12 +135,16 @@ try {
if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) {
throw 'Expected both file panels in the test window.'
}
Wait-Until { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) }
$keyboard.SendKeys('^q')
Wait-Until {
[void](Wait-Until 'both panels' { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) })
Invoke-FilesCommand $window 'Quick View*'
$preview = Wait-Until 'Quick View' {
$hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158)
$hostWindow -ne [IntPtr]::Zero -and [FilesQuickViewProbe]::IsWindowVisible($hostWindow)
if ([FilesQuickViewProbe]::IsWindowVisible($hostWindow)) { $hostWindow }
}
$editor = [FilesQuickViewProbe]::FindWindowEx($preview,0,'Scintilla',[NullString]::Value)
[void](Wait-Until 'the text preview' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
$initialWrap = [FilesQuickViewProbe]::Send($editor,2269,0,0)
$initialScrollbar = [FilesQuickViewProbe]::Send($editor,2131,0,0)
foreach ($control in $rightList, $rightHeading, $rightPath) {
if ([FilesQuickViewProbe]::IsWindowVisible($control)) {
throw 'A file panel control can draw over the Quick View content.'
@@ -75,19 +152,75 @@ try {
}
if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' }
$keyboard.SendKeys('^q')
Wait-Until { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero }
Select-File 'preview.html'
$mode = [FilesQuickViewProbe]::GetDlgItem($preview,159)
[void](Wait-Until 'the HTML mode switch' { [FilesQuickViewProbe]::IsWindowVisible($mode) -and (Text $mode) -eq 'Show Source' })
if ($browserProbe) { Browser }
[void][FilesQuickViewProbe]::Post($preview,273,159,$mode)
[void](Wait-Until 'the HTML source' {
[FilesQuickViewProbe]::IsWindowVisible($editor) -and (Text $mode) -eq 'Show Rendered' -and
(Preview-Bytes 15) -eq '<!doctype html>'
})
[void][FilesQuickViewProbe]::Post($editor,0x100,117,0)
[void](Wait-Until 'keyboard switch back to Rendered' { (Text $mode) -eq 'Show Source' })
if ($browserProbe) { Browser }
if ($network.Pending()) { throw 'Rendering HTML attempted an outbound resource request' }
Select-File 'symbols.bin'
[void](Wait-Until 'binary glyphs in the embedded view' {
[FilesQuickViewProbe]::IsWindowVisible($editor) -and [FilesQuickViewProbe]::Send($editor,2269,0,0).ToInt32() -eq 2
})
if ((Preview-Bytes ([Text.Encoding]::UTF8.GetByteCount($expectedSymbols))) -cne $expectedSymbols) {
throw 'Binary control bytes were lost or decoded as text'
}
$expectedLength = [Text.Encoding]::UTF8.GetByteCount($expectedSymbols) + 4096 - $header.Length
if ([FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -ne $expectedLength -or
[FilesQuickViewProbe]::Send($editor,2131,0,0).ToInt32() -ne 0) {
throw 'Binary preview exceeded its byte limit or enabled horizontal scrolling'
}
$escapeWidth = [FilesQuickViewProbe]::Send($editor,2164,0,3).ToInt32() -
[FilesQuickViewProbe]::Send($editor,2164,0,0).ToInt32()
if($escapeWidth -le [FilesQuickViewProbe]::Send($editor,2279,0,0).ToInt32()){
throw 'The control byte did not render as a full visible escape'
}
if($BinaryImage){
Add-Type -AssemblyName System.Drawing
$bounds = [FilesCommandsUi+Rect]::new()
[void][FilesCommandsUi]::GetClientRect($preview,[ref]$bounds)
$bitmap = [Drawing.Bitmap]::new($bounds.Right,$bounds.Bottom)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try { if(![FilesCommandsUi]::PrintWindow($preview,$dc,3)){throw 'Could not render binary preview'} }
finally { $graphics.ReleaseHdc($dc) }
$bitmap.Save($BinaryImage,[Drawing.Imaging.ImageFormat]::Png)
} finally { $graphics.Dispose(); $bitmap.Dispose() }
}
$wideRows = [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32()
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,840,920,20)
[void](Wait-Until 'binary rows wrap in a narrower pane' { [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32() -gt $wideRows })
Select-File 'preview.txt'
[void](Wait-Until 'ordinary text preview restored' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
if ([FilesQuickViewProbe]::IsWindowVisible($mode) -or [FilesQuickViewProbe]::Send($editor,2269,0,0) -ne $initialWrap -or
[FilesQuickViewProbe]::Send($editor,2131,0,0) -ne $initialScrollbar) { throw 'Preview mode leaked into a text file' }
[void][FilesQuickViewProbe]::Post($window,0x801F,0,0)
[void](Wait-Until 'Quick View closed' { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero })
foreach ($control in $rightList, $rightHeading, $rightPath) {
if (![FilesQuickViewProbe]::IsWindowVisible($control)) {
throw 'A file panel control remained hidden after closing Quick View.'
}
}
'Quick View hides the covered list and chrome, then restores the same controls.'
'Quick View verified with offline HTML, source switching, bounded binary glyphs and restored file panels.'
} finally {
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() }
}
if ($network) { $network.Stop() }
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags
$env:WEBVIEW2_USER_DATA_FOLDER = $profile
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $key.DeleteValue($name, $false) }
@@ -96,6 +229,14 @@ try {
$path = [IO.Path]::GetFullPath($fixture.FullName)
if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and
[IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) {
[IO.Directory]::Delete($path, $true)
for($attempt=0; $attempt -lt 50; ++$attempt){
try {
[IO.Directory]::Delete($path, $true)
break
} catch [System.IO.IOException] {
if($attempt -eq 49){throw}
Start-Sleep -Milliseconds 100
}
}
}
}
+30
View File
@@ -160,11 +160,40 @@ void hexBytes(const fs::path &file)
const auto text=ks::files::formatHexPage(bytes,0);
check(text.starts_with("0000000000000000 EF BB BF 00 41 FF 7F 0D 0A") &&
text.ends_with("|....A.... |"),"Hex and ASCII columns retain unprintable bytes and alignment");
const std::string controls("\x00\x01\x09\x0A\x0D\x1B\x1F A\x7F\x80\xFF",12);
const std::string symbols(reinterpret_cast<const char *>(u8"\ue000\ue001\ue009\ue00a\ue00d\ue01b\ue01f A\ue07f\u00c7\ue0ff"));
check(ks::files::formatBinarySymbols(controls)==symbols,"Quick View displays all control and high bytes as glyphs");
const std::string slash(reinterpret_cast<const char *>(u8"\ue05c"));
check(ks::files::formatBinarySymbols("\\x00")==slash+"x00","Binary preview distinguishes literal escapes");
check(ks::files::formatBinarySymbols({}).empty(),"An empty symbol preview stays empty");
const std::string twoRows(17,'a');
check(ks::files::formatHexPage(twoRows,0).find("\r\n0000000000000010 61")!=std::string::npos,
"Hex offsets advance by the row width");
}
void watchedEditor(const fs::path &file)
{
writeFile(file,"original bytes");
TextDocument editor(file,true,TextEncoding::automatic,true);
check(editor.expectedVersion().has_value(),"local editor captured the original version");
writeFile(file,"external bytes");
check(editor.readPage(0)=="original bytes","external edit replaced the editor snapshot");
editor.stage(0,"editor buffer");
bool rejected=false;
try {editor.save();}
catch(const std::runtime_error &error)
{
rejected=std::string_view(error.what()).find("changed outside Files")!=std::string_view::npos;
}
check(rejected && editor.readPage(0)=="editor buffer","external edit was overwritten or the draft was cleared");
TextDocument reloaded(file,true,TextEncoding::automatic,true);
check(reloaded.readPage(0)=="external bytes","reload did not take the external version");
reloaded.stage(0,"confirmed write");
check(reloaded.save() && reloaded.readPage(0)=="confirmed write","local save lost the new snapshot");
writeFile(file,"next change");
check(reloaded.readPage(0)=="confirmed write","the post-save editor lost snapshot isolation");
}
void bookmarkedLines(const fs::path &file)
{
const auto longLine=std::string(TextDocument::pageBytes+32,'x');
@@ -256,6 +285,7 @@ int main()
rejectExternalReplacement(fixture.directory / L"external.txt");
saveDraft(fixture.directory / L"created.txt");
hexBytes(fixture.directory / L"raw.bin");
watchedEditor(fixture.directory / L"watched.txt");
bookmarkedLines(fixture.directory / L"bookmarks.txt");
comparisonEdits();
sparseFile(fixture.directory / L"5gib.log");
+297 -52
View File
@@ -1,90 +1,335 @@
#include "lan_clients.h"
#include <winsock2.h>
#include "lan_client_files.h"
#include "lan_network.h"
#include <atomic>
#include <fstream>
#include <iostream>
namespace
{
using ks::lan::Json;
using namespace ks;
using namespace ks::lan;
namespace fs = std::filesystem;
void require(bool value, const char *message)
{
if (!value) throw std::runtime_error(message);
}
Json request(const std::wstring &name)
class Pipe
{
require(WaitNamedPipeW(name.c_str(), 3000) != FALSE, "LAN client pipe did not start");
struct Pipe
HANDLE handle = INVALID_HANDLE_VALUE;
void io(void *buffer, DWORD length, bool write)
{
HANDLE value;
~Pipe() { if (value != INVALID_HANDLE_VALUE) CloseHandle(value); }
} pipe{CreateFileW(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, nullptr)};
require(pipe.value != INVALID_HANDLE_VALUE, "could not open LAN client pipe");
auto transfer = [&](void *buffer, DWORD length, bool write) {
auto *cursor = static_cast<char *>(buffer);
while (length)
{
DWORD count{};
require((write ? WriteFile(pipe.value, cursor, length, &count, nullptr) :
ReadFile(pipe.value, cursor, length, &count, nullptr)) && count, "pipe transfer failed");
require((write ? WriteFile(handle, cursor, length, &count, nullptr) :
ReadFile(handle, cursor, length, &count, nullptr)) && count, "pipe transfer failed");
cursor += count;
length -= count;
}
}
public:
Pipe(const std::wstring &name, const Json &request, bool impersonate = false)
{
const auto end = GetTickCount64() + 3000;
do
{
handle = CreateFileW(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING,
SECURITY_SQOS_PRESENT | (impersonate ? SECURITY_IMPERSONATION : SECURITY_IDENTIFICATION), nullptr);
if (handle != INVALID_HANDLE_VALUE) break;
Sleep(10);
} while (GetTickCount64() < end);
require(handle != INVALID_HANDLE_VALUE, "could not open LAN client pipe");
sendJson(request);
}
~Pipe() { if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); }
void send(std::string data)
{
DWORD length = DWORD(data.size());
io(&length, sizeof(length), true);
if (length) io(data.data(), length, true);
}
void sendJson(const Json &data) { send(data.dump()); }
std::string read()
{
DWORD length{};
io(&length, sizeof(length), false);
require(length <= 8 * 1024 * 1024, "unexpected reply size");
std::string payload(length, '\0');
if (length) io(payload.data(), length, false);
return payload;
}
Json reply() { return Json::parse(read()); }
void ack()
{
char ack{};
io(&ack, 1, true);
}
};
Json request(const std::wstring &name, const Json &body, bool impersonate = false)
{
Pipe pipe(name, body, impersonate);
auto reply = pipe.reply();
pipe.ack();
return reply;
}
void save(const fs::path &path, const std::string &content)
{
std::ofstream file(path, std::ios::binary | std::ios::trunc);
file << content;
require(bool(file), "could not write test file");
}
std::string read(const fs::path &path)
{
std::ifstream file(path, std::ios::binary);
require(bool(file), "could not read test file");
return {std::istreambuf_iterator<char>(file), {}};
}
Json endpoint(const Json &peer, const fs::path &path)
{
return {{"peer", peer}, {"path", utf8(path.native())}};
}
Json operation(const char *action, const Json &peer, const fs::path &path)
{
auto result = endpoint(peer, path);
result["action"] = action;
return result;
}
Json transfer(const Json &from, const Json &to, bool move, const char *conflict = "fail")
{
return {{"action", "transfer"}, {"source", from}, {"target", to}, {"move", move}, {"conflict", conflict}};
}
Json runTransfer(const std::wstring &name, const Json &job,
const std::function<bool(const Json &)> &progress = {}, bool impersonate = false)
{
Pipe pipe(name, job, impersonate);
for (;;)
{
auto result = pipe.reply();
if (result.value("type", "") != "progress")
{
pipe.ack();
return result;
}
pipe.sendJson({{"continue", !progress || progress(result)}});
}
}
void verifyFiles(LanClients &clients, const Json &trusted, const std::wstring &pipe,
const fs::path &root, const fs::path &secondVolume)
{
const auto caller = randomHex(16), a = randomHex(16), b = randomHex(16), key = randomHex(32);
std::atomic<bool> available{true};
const auto pair = [&](const std::string &id) { return id == caller && available.load() ? key : std::string{}; };
Network network;
FilesListener first(a, pair, 0), second(b, pair, 0);
require(first.port() && second.port(), "could not start paired file listeners");
std::jthread listeners([&](std::stop_token stop) {
while (!stop.stop_requested()) { first.poll(); second.poll(); Sleep(1); }
});
const auto running = [&](const std::string &peer) -> ClientFilesPeer {
require(peer == a || peer == b, "an unknown peer was routed");
return {{peer, "127.0.0.1", L"Fixture", peer == a ? first.port() : second.port(), true}, caller, key};
};
auto payload = Json{{"action", "peers"}}.dump();
DWORD length = DWORD(payload.size());
transfer(&length, sizeof(length), true);
transfer(payload.data(), length, true);
transfer(&length, sizeof(length), false);
require(length > 0 && length < 4096, "unexpected reply size");
payload.resize(length);
transfer(payload.data(), length, false);
char ack{};
transfer(&ack, 1, true);
return Json::parse(payload);
clients.start([&](const Json &body, const ClientCheck &check, const ClientSend &send,
const ClientReceive &receive, const ClientAsCaller &asCaller) {
if (body.at("action") == "peers")
{
constexpr std::string_view reply = R"([{"id":"fixture","name":"Paired PC","online":true}])";
send(reply.data(), DWORD(reply.size()));
}
else routeClientFiles(body, check, send, receive, asCaller, running);
}, pipe.substr(pipe.find(L".test.")));
struct Stop { LanClients &clients; ~Stop() { clients.stop(); } } stop{clients};
const auto path = utf8(executable());
const auto canonical = trusted.at("path");
const Json peers{{"action", "peers"}};
require(request(pipe, peers).contains("error"), "an untrusted executable was accepted");
const auto grant = [&](bool write, bool erase) {
clients.settings("trustClient", {{"path", path}, {"writeFiles", write}, {"deleteFiles", erase}});
};
grant(false, false);
require(request(pipe, peers).at(0).at("name") == "Paired PC", "the trusted executable was rejected");
const auto setCapabilities = [&](bool write, bool erase) {
const auto caps = request(pipe, {{"action", "capabilities"}, {"peer", a}});
require(caps.value("protocol", 0) == 2 && caps.value("hostRevision", 0) == 1 &&
caps.at("write") == write && caps.at("delete") == erase && caps.at("move") == (write && erase),
"wrong advertised capabilities");
};
setCapabilities(false, false);
const auto src = root / L"source", dst = root / L"target", file = src / L"content.txt";
const std::string content(FileChunk * 4 + 19, 'x');
fs::create_directory(src);
save(file, content);
const auto mkdir = operation("mkdir", b, dst);
require(request(pipe, mkdir).contains("error") && !fs::exists(dst), "browse grant allowed creation");
const auto legacy = request(pipe, operation("list", a, src));
require(legacy.at(0).at("name") == "content.txt", "legacy list schema changed");
{
Pipe download(pipe, operation("download", a, file));
const auto header = download.reply();
require(header.size() == 1 && header.at("size") == content.size(), "legacy download schema changed");
std::string downloaded;
for (auto chunk = download.read(); !chunk.empty(); chunk = download.read()) downloaded += chunk;
download.ack();
require(downloaded == content, "legacy download content changed");
}
const auto info = request(pipe, operation("stat", a, file));
auto readVersion = operation("readFile", a, file);
readVersion["expected"] = {{"size", info.at("size")}, {"modified", info.at("modified")}};
{
Pipe reader(pipe, readVersion);
require(reader.reply().at("modified") == info.at("modified"), "revision read omitted metadata");
std::string downloaded;
for (auto chunk = reader.read(); !chunk.empty(); chunk = reader.read()) downloaded += chunk;
reader.ack();
require(downloaded == content, "revision read had incorrect content");
}
readVersion["expected"]["size"] = 0;
require(request(pipe, readVersion).at("error").is_string(), "stale revision read was accepted");
grant(true, false);
setCapabilities(true, false);
require(request(pipe, mkdir).at("error") == 0, "mkdir failed");
require(request(pipe, operation("delete", a, file)).contains("error") && fs::exists(file),
"write grant allowed deletion");
auto up = operation("writeFile", b, dst / L"upload.txt");
up["size"] = 3;
const auto upload = [&](const std::string &value) {
Pipe writer(pipe, up);
require(writer.reply().value("type", "") == "ready", "upload did not open");
writer.send(value);
writer.send("");
const auto result = writer.reply();
writer.ack();
return result;
};
const auto original = upload("one");
require(original.at("error") == 0 && read(dst / L"upload.txt") == "one", "exclusive create failed");
const auto collision = upload("two");
require(collision.at("error").is_string() && read(dst / L"upload.txt") == "one",
"exclusive create overwrote existing file");
up["expected"] = {{"size", original.at("size")}, {"modified", original.at("modified")}};
require(upload("two").at("error") == 0 && read(dst / L"upload.txt") == "two", "revision save failed");
require(upload("bad").at("error").is_string() && read(dst / L"upload.txt") == "two", "stale save lost data");
auto rename = operation("rename", b, dst / L"upload.txt");
rename["name"] = "renamed.txt";
require(request(pipe, rename).at("error") == 0 && read(dst / L"renamed.txt") == "two", "rename failed");
const auto to = dst / L"copy";
const auto cross = transfer(endpoint(a, src), endpoint(b, to), false);
require(runTransfer(pipe, cross).at("type") == "complete" && read(to / L"content.txt") == content,
"cross-peer tree copy failed");
require(runTransfer(pipe, cross).contains("error"), "the fail conflict policy overwrote a directory");
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "skip")).at("skipped") == 1,
"skip conflict policy failed");
save(to / L"content.txt", "replace me");
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "replace")).at("type") == "complete" &&
read(to / L"content.txt") == content, "replace conflict policy failed");
const auto localCopy = root / L"local.txt";
const auto fromLocal = transfer(endpoint(nullptr, file), endpoint(b, dst / L"from-local.txt"), false);
require(runTransfer(pipe, fromLocal).contains("error"), "identification-only pipe accessed local files");
const auto localUpload = runTransfer(pipe, fromLocal, {}, true);
require(localUpload.value("type", "") == "complete" && read(dst / L"from-local.txt") == content,
localUpload.value("error", "local upload failed under the caller token").c_str());
require(runTransfer(pipe, transfer(endpoint(b, dst / L"from-local.txt"), endpoint(nullptr, localCopy), false),
{}, true).at("type") == "complete" && read(localCopy) == content, "local download failed under the caller token");
const auto remoteSide = secondVolume.empty() ? dst : secondVolume;
const auto sameCopy = remoteSide / L"same-host.txt";
unsigned progressFrames{};
require(runTransfer(pipe, transfer(endpoint(a, file), endpoint(a, sameCopy), false),
[&](const Json &) { ++progressFrames; return true; }).at("type") == "complete" &&
progressFrames > 1 && read(sameCopy) == content, "same-host transfer failed");
const auto cancelled = dst / L"cancelled.txt";
const auto cancellation = transfer(endpoint(a, file), endpoint(a, cancelled), false);
require(runTransfer(pipe, cancellation, [](const Json &progress) { return progress.at("total") == 0; })
.contains("error") && !fs::exists(cancelled) && read(file) == content, "same-host cancellation lost data");
{
Pipe disconnect(pipe, cancellation);
while (disconnect.reply().at("total") == 0) disconnect.sendJson({{"continue", true}});
}
require(request(pipe, peers).is_array() && !fs::exists(cancelled) && read(file) == content,
"pipe disconnect published an incomplete transfer");
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(a, src / L"inside"), false)).contains("error") &&
!fs::exists(src / L"inside"), "same-host transfer recursed into its source");
grant(true, true);
setCapabilities(true, true);
const auto moved = dst / L"moved.txt";
const auto move = transfer(endpoint(a, file), endpoint(b, moved), true);
require(runTransfer(pipe, move, [&](const Json &progress) {
if (progress.at("phase") == "remove") grant(true, false);
return true;
}).contains("error") && fs::exists(file) && read(moved) == content,
"revoked delete grant still removed the source or failed to publish the full destination");
fs::remove(moved);
grant(true, true);
require(runTransfer(pipe, move, [&](const Json &progress) {
if (progress.at("total") != 0) available = false;
return true;
}).contains("error") && fs::exists(file) && !fs::exists(moved), "connection loss published a partial move");
available = true;
const auto sameMove = remoteSide / L"same-move";
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(a, sameMove), true)).at("type") == "complete" &&
read(sameMove / L"content.txt") == content && !fs::exists(src), "same-host tree move failed");
const auto crossMove = dst / L"cross-move";
require(runTransfer(pipe, transfer(endpoint(a, sameMove), endpoint(b, crossMove), true)).at("type") == "complete" &&
read(crossMove / L"content.txt") == content && !fs::exists(sameMove), "cross-peer tree move failed");
auto erase = operation("delete", b, crossMove);
erase["recursive"] = true;
require(request(pipe, erase).at("error") == 0 && !fs::exists(crossMove), "recursive delete failed");
for (const auto &entry : fs::recursive_directory_iterator(root))
require(entry.path().extension() != L".partial", "an interrupted client operation left a partial upload");
auto changed = clients.settings("trustedClients", {});
changed.at(0)["sha256"] = std::string(64, '0');
const auto differentHash = changed.dump();
atomicWrite(root / L"lan-clients.bin", protect(Bytes(differentHash.begin(), differentHash.end())));
require(request(pipe, peers).contains("error"), "an executable with a different fingerprint was accepted");
grant(true, true);
clients.settings("removeClient", {{"path", canonical}});
require(request(pipe, peers).contains("error"), "revocation must reject the next request");
}
}
int main()
{
const auto suffix = L".test." + std::to_wstring(GetCurrentProcessId());
const auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-LAN" + suffix);
const auto root = fs::temp_directory_path() / (L"KSwitcher-LAN" + suffix);
fs::path secondVolume;
try
{
require(std::filesystem::create_directory(root), "could not create test directory");
require(fs::create_directory(root), "could not create test directory");
wchar_t other[512]{};
const auto length = GetEnvironmentVariableW(L"KSWITCHER_TEST_LAN_OTHER_VOLUME", other, DWORD(std::size(other)));
if (length && length < std::size(other))
{
secondVolume = fs::path(other) / root.filename();
require(fs::create_directory(secondVolume), "could not create other-volume fixture");
}
DWORD session{};
require(ProcessIdToSessionId(GetCurrentProcessId(), &session) != FALSE, "no Windows session");
const auto pipe = L"\\\\.\\pipe\\KSwitcher.LAN.Clients.v1." + std::to_wstring(session) + suffix;
{
ks::lan::LanClients clients(root);
clients.start([](const Json &request, const auto &, const auto &send) {
require(request.at("action") == "peers", "unexpected request");
constexpr std::string_view reply = R"([{"id":"fixture","name":"Paired PC","online":true}])";
send(reply.data(), DWORD(reply.size()));
}, suffix);
// WaitNamedPipe returns immediately if the instance has not been created yet.
for (int n = 0; n < 100 && !WaitNamedPipeW(pipe.c_str(), 20); ++n) Sleep(20);
require(request(pipe).contains("error"), "an untrusted executable was accepted");
const auto path = ks::utf8(ks::executable());
const auto trusted = clients.settings("trustClient", {{"path", path}});
require(trusted.size() == 1, "the program must be enrolled exactly once");
require(request(pipe).at(0).at("name") == "Paired PC", "the trusted program was rejected");
auto changed = trusted;
changed.at(0)["sha256"] = std::string(64, '0');
const auto store = root / L"lan-clients.bin";
const auto differentHash = changed.dump();
ks::atomicWrite(store, ks::protect(ks::Bytes(differentHash.begin(), differentHash.end())));
require(request(pipe).contains("error"), "an executable with a different fingerprint was accepted");
clients.settings("trustClient", {{"path", path}});
clients.settings("removeClient", {{"path", trusted.at(0).at("path")}});
require(request(pipe).contains("error"), "revocation must reject the next request");
LanClients clients(root);
const auto trusted = clients.settings("inspectClient", {{"path", utf8(executable())}});
verifyFiles(clients, trusted, pipe, root, secondVolume);
clients.stop();
}
std::filesystem::remove(root / L"lan-clients.bin");
std::filesystem::remove(root);
std::cout << "Verified executable approval, resident pipe access and revocation.\n";
if (!secondVolume.empty()) fs::remove_all(secondVolume);
fs::remove_all(root);
std::cout << "Verified approval, permissions, legacy discovery/download, revisions and transfers between paired hosts.\n";
return 0;
}
catch (const std::exception &error)
{
if (!secondVolume.empty()) { std::error_code ignored; fs::remove_all(secondVolume, ignored); }
{ std::error_code ignored; fs::remove_all(root, ignored); }
std::cerr << error.what() << '\n';
return 1;
}
+31
View File
@@ -200,6 +200,37 @@ int main()
catch(const std::system_error &){}
verifyConnectionCancellation(client,key);
FilesConnection host(one,client,key);
{
const auto source=root/L"acl-source.txt", copied=root/L"acl-target.txt";
save(source,"source");
save(copied,"target");
auto get=fileRequest("copyPermissions",source);
const auto inherited=host.call(get);
checkFileReply(inherited);
auto acl=inherited.at("permissions").get<std::string>();
if(!acl.starts_with("D:P")) acl.insert(2,"P");
auto protect=fileRequest("applyCopyMetadata",source);
protect["permissions"]=acl;
const auto protectedSource=host.call(protect);
require(protectedSource.at("error")==ERROR_SUCCESS, "could not set a protected source DACL");
const auto permissions=host.call(get);
checkFileReply(permissions);
require(permissions.at("permissions").get<std::string>().starts_with("D:P"),
"copy permission action did not protect the Windows DACL");
auto apply=fileRequest("applyCopyMetadata",copied);
constexpr uint64_t modified=132537600000000000ULL;
apply["permissions"]=permissions.at("permissions");
apply["modified"]=modified;
const auto applied=host.call(apply);
require(applied.at("error")==ERROR_SUCCESS, "could not copy Windows metadata to the target");
auto result=host.call(fileRequest("copyPermissions",copied));
checkFileReply(result);
require(result.at("permissions")==permissions.at("permissions"),
"Windows permissions did not survive LAN metadata copy");
result=host.call(fileRequest("stat",copied));
checkFileReply(result);
require(result.at("modified")==modified,"LAN copy metadata lost the file modification time");
}
{
const Json hibernate={{"action","hibernate"}};
FilesConnection target(two,client,key);