Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c0e8f0736 | ||
|
|
934521f404 | ||
|
|
2db50fcd0e | ||
|
|
dbbc5c138e | ||
|
|
84385a1eca | ||
|
|
f5b7ddfb53 | ||
|
|
93e672c71d | ||
|
|
cc6199e9be | ||
|
|
a27ae96842 | ||
|
|
9158bf95a6 | ||
|
|
159b776199 | ||
|
|
ada198db24 | ||
|
|
fe1f818582 | ||
|
|
1217887e14 | ||
|
|
10847244f0 |
No files matched your search
+3
-3
@@ -6,7 +6,7 @@ endif()
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
|
||||
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp resources/files.rc)
|
||||
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp resources/files.rc)
|
||||
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
|
||||
@@ -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}}")
|
||||
|
||||
+49
@@ -759,6 +759,42 @@ Warning і початковий фокус на No.
|
||||
зі збереженням вихідного файла в першій. Після завершення процесу список
|
||||
перечитується. Якщо Windows обмежила доступ або перевірка великої папки
|
||||
завершилася частково, діалог повідомляє про це.
|
||||
- **F9 → Commands → Git Changes** відкриває зміни Git із кореня або
|
||||
вкладеної папки локального worktree. Список окремо показує **Staged**,
|
||||
**Unstaged** та **Untracked**, а сусідня панель відображає diff
|
||||
вибраного рядка. **Filter** шукає за шляхом. **F3** відкриває поточний
|
||||
робочий файл у 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 мають системне оформлення.
|
||||
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
|
||||
@@ -800,6 +836,11 @@ Warning і початковий фокус на No.
|
||||
- Секції поточного файла й загального прогресу мають однаковий вертикальний відступ від вмісту до верхньої та нижньої ліній. Cancel стоїть по центру спільної нижньої секції.
|
||||
- Обидві шкали займають усю ширину вмісту. Відсотки показуються по центру шкали, а її висота враховує поточний шрифт.
|
||||
|
||||
- **Options** у Copy/Move задає маску імен файлів із символами `*` і `?`. Порожня маска або `*` копіює всі файли й порожні папки. З іншою маскою Files зберігає структуру папок із відповідними файлами. У Move файли поза маскою залишаються в джерелі.
|
||||
- Додаткові папки вводяться абсолютними шляхами, по одному на рядок, на тому самому комп’ютері або підключенні, що й основне призначення. Однакові папки обробляються один раз. У Move джерело видаляється після успішного копіювання елемента в усі вибрані папки. У разі пропуску або збою вже записані копії зберігаються. Підсумок показує кількість повністю скопійованих елементів по всіх призначеннях і загальну кількість записаних файлів.
|
||||
- **Preserve modification time** зберігає час зміни там, де ціль підтримує його встановлення. Збереження часу підтримують Windows і SFTP. FTP-призначення використовує час сервера. **Preserve Windows permissions** переносить DACL між файловими системами Windows, які підтримують цей тип прав. Наявні папки, у які додаються файли, зберігають власні права й час.
|
||||
- Оцінка залишку часу в прогресі з’являється після кількох вимірювань швидкості. Довга пауза скидає оцінку. Скасування й конфлікти використовують спільні діалоги.
|
||||
|
||||
## Попередження про конфлікт
|
||||
|
||||
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
|
||||
@@ -817,6 +858,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
@@ -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
|
||||
|
||||
|
||||
+76
-2
@@ -169,6 +169,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
|
||||
@@ -262,8 +266,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 +624,72 @@ 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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
|
||||
@@ -0,0 +1,740 @@
|
||||
#include "files_git_changes.h"
|
||||
#include "core.h"
|
||||
#include "windows_command_line.h"
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <objbase.h>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace
|
||||
{
|
||||
namespace fs=std::filesystem;
|
||||
|
||||
struct GitHandle
|
||||
{
|
||||
HANDLE value{};
|
||||
void close()
|
||||
{
|
||||
if(value && value!=INVALID_HANDLE_VALUE) CloseHandle(value);
|
||||
value=nullptr;
|
||||
}
|
||||
~GitHandle(){close();}
|
||||
};
|
||||
|
||||
[[noreturn]] void gitWindowsError(const char *operation)
|
||||
{
|
||||
throw std::system_error(GetLastError(),std::system_category(),operation);
|
||||
}
|
||||
|
||||
void makeGitPipe(GitHandle &read,GitHandle &write,SECURITY_ATTRIBUTES &inheritable)
|
||||
{
|
||||
if(!CreatePipe(&read.value,&write.value,&inheritable,0) ||
|
||||
!SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0))
|
||||
gitWindowsError("Could not create the Git output pipe");
|
||||
}
|
||||
|
||||
fs::path locateGit()
|
||||
{
|
||||
const DWORD size=GetEnvironmentVariableW(L"PATH",nullptr,0);
|
||||
std::wstring paths(size,L'\0');
|
||||
if(size)
|
||||
{
|
||||
const auto count=GetEnvironmentVariableW(L"PATH",paths.data(),size);
|
||||
paths.resize(count<size?count:0);
|
||||
}
|
||||
std::wstring_view remaining=paths;
|
||||
while(!remaining.empty())
|
||||
{
|
||||
const auto end=remaining.find(L';');
|
||||
auto directory=remaining.substr(0,end);
|
||||
if(directory.size()>=2 && directory.front()==L'"' && directory.back()==L'"')
|
||||
directory=directory.substr(1,directory.size()-2);
|
||||
const auto path=fs::path(directory);
|
||||
if(path.is_absolute())
|
||||
{
|
||||
const auto candidate=path/L"git.exe";
|
||||
const auto attributes=GetFileAttributesW(candidate.c_str());
|
||||
if(attributes!=INVALID_FILE_ATTRIBUTES && !(attributes&FILE_ATTRIBUTE_DIRECTORY)) return candidate;
|
||||
}
|
||||
if(end==remaining.npos) break;
|
||||
remaining.remove_prefix(end+1);
|
||||
}
|
||||
for(const auto key:{HKEY_CURRENT_USER,HKEY_LOCAL_MACHINE})
|
||||
{
|
||||
wchar_t install[32768]{};
|
||||
DWORD bytes=sizeof(install);
|
||||
if(RegGetValueW(key,L"SOFTWARE\\GitForWindows",L"InstallPath",RRF_RT_REG_SZ,nullptr,install,&bytes)!=ERROR_SUCCESS)
|
||||
continue;
|
||||
const auto git=fs::path(install)/L"cmd"/L"git.exe";
|
||||
if(git.is_absolute() && GetFileAttributesW(git.c_str())!=INVALID_FILE_ATTRIBUTES) return git;
|
||||
}
|
||||
throw std::runtime_error("Git for Windows was not found. Install it or add git.exe to PATH.");
|
||||
}
|
||||
|
||||
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<std::wstring> settings;
|
||||
for(auto entry=environment;*entry;)
|
||||
{
|
||||
const std::wstring_view setting=entry;
|
||||
const auto name=setting.substr(0,setting.find(L'='));
|
||||
if(std::none_of(std::begin(overrides),std::end(overrides),[&](std::wstring_view key) {
|
||||
return name.size()==key.size() &&
|
||||
CompareStringOrdinal(name.data(),static_cast<int>(name.size()),key.data(),static_cast<int>(key.size()),TRUE)
|
||||
==CSTR_EQUAL;
|
||||
}))
|
||||
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;
|
||||
}
|
||||
|
||||
struct GitProcessAttributes
|
||||
{
|
||||
std::vector<std::byte> storage;
|
||||
LPPROC_THREAD_ATTRIBUTE_LIST list{};
|
||||
explicit GitProcessAttributes(HANDLE (&inherited)[3])
|
||||
{
|
||||
SIZE_T bytes{};
|
||||
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
|
||||
storage.resize(bytes);
|
||||
const auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes))
|
||||
gitWindowsError("Could not initialize the Git process");
|
||||
if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr))
|
||||
{
|
||||
const auto error=GetLastError();
|
||||
DeleteProcThreadAttributeList(attributes);
|
||||
throw std::system_error(error,std::system_category(),"Could not set Git process handles");
|
||||
}
|
||||
list=attributes;
|
||||
}
|
||||
~GitProcessAttributes(){DeleteProcThreadAttributeList(list);}
|
||||
};
|
||||
|
||||
struct GitOutput
|
||||
{
|
||||
std::string output, error;
|
||||
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,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(options.index);
|
||||
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
|
||||
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);
|
||||
HANDLE inherited[]{input.value,childOut.value,childError.value};
|
||||
GitProcessAttributes attributes(inherited);
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb=sizeof(startup);
|
||||
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
|
||||
startup.StartupInfo.hStdInput=input.value;
|
||||
startup.StartupInfo.hStdOutput=childOut.value;
|
||||
startup.StartupInfo.hStdError=childError.value;
|
||||
startup.lpAttributeList=attributes.list;
|
||||
PROCESS_INFORMATION child{};
|
||||
if(!CreateProcessW(git.c_str(),command.data(),nullptr,nullptr,TRUE,
|
||||
CREATE_NO_WINDOW|CREATE_SUSPENDED|CREATE_UNICODE_ENVIRONMENT|EXTENDED_STARTUPINFO_PRESENT,
|
||||
environment.data(),directory.c_str(),&startup.StartupInfo,&child))
|
||||
gitWindowsError("Could not start Git");
|
||||
const GitHandle process{child.hProcess},thread{child.hThread};
|
||||
const GitHandle job{CreateJobObjectW(nullptr,nullptr)};
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
|
||||
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if(job.value && SetInformationJobObject(job.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))
|
||||
AssignProcessToJobObject(job.value,process.value);
|
||||
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;
|
||||
auto deadline=GetTickCount64()+options.timeout;
|
||||
const auto read=[&](HANDLE pipe,std::string &data,size_t limit)
|
||||
{
|
||||
DWORD waiting{},readBytes{};
|
||||
char buffer[8192];
|
||||
if(!PeekNamedPipe(pipe,nullptr,0,nullptr,&waiting,nullptr))
|
||||
{
|
||||
if(GetLastError()==ERROR_BROKEN_PIPE) return false;
|
||||
gitWindowsError("Could not read Git output");
|
||||
}
|
||||
if(!waiting) return false;
|
||||
if(!ReadFile(pipe,buffer,std::min<DWORD>(waiting,sizeof(buffer)),&readBytes,nullptr))
|
||||
gitWindowsError("Could not read Git output");
|
||||
if(data.size()+readBytes>limit) throw std::runtime_error("Git output was too large to display.");
|
||||
data.append(buffer,readBytes);
|
||||
return readBytes!=0;
|
||||
};
|
||||
for(;;)
|
||||
{
|
||||
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
|
||||
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)
|
||||
{
|
||||
if(read(out.value,result.output,maximum) || read(error.value,result.error,256*1024))
|
||||
continue;
|
||||
if(!GetExitCodeProcess(process.value,&result.exitCode)) gitWindowsError("Could not read Git status");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
void checkGit(const GitOutput &result,const char *operation,bool allowDifference=false)
|
||||
{
|
||||
if(!result.exitCode || (allowDifference && result.exitCode==1)) return;
|
||||
auto detail=result.error;
|
||||
while(!detail.empty() && (detail.back()=='\r' || detail.back()=='\n')) detail.pop_back();
|
||||
throw std::runtime_error(detail.empty()?std::string(operation):std::string(operation)+"\r\n"+detail);
|
||||
}
|
||||
|
||||
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 output.");
|
||||
const auto field=input.substr(0,separator);
|
||||
input.remove_prefix(separator+1);
|
||||
return field;
|
||||
}
|
||||
|
||||
std::wstring statusPath(std::string_view value)
|
||||
{
|
||||
if(value.empty() || value.starts_with('/') || value.find_first_of("\\:")!=value.npos)
|
||||
throw std::runtime_error("Git returned an unsupported worktree path.");
|
||||
for(auto suffix=value;!suffix.empty();)
|
||||
{
|
||||
const auto slash=suffix.find('/');
|
||||
const auto part=suffix.substr(0,slash);
|
||||
if(part=="." || part==".." || part.empty())
|
||||
throw std::runtime_error("Git returned an unsupported worktree path.");
|
||||
if(slash==suffix.npos) break;
|
||||
suffix.remove_prefix(slash+1);
|
||||
}
|
||||
return wide(std::string(value));
|
||||
}
|
||||
|
||||
std::vector<GitChange> parseGitStatus(std::string_view output)
|
||||
{
|
||||
std::vector<GitChange> result;
|
||||
while(!output.empty())
|
||||
{
|
||||
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(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))});
|
||||
else
|
||||
{
|
||||
if(code[0]!=' ') result.push_back({GitChangeKind::staged,path,origin,std::wstring(1,code[0])});
|
||||
if(code[1]!=' ') result.push_back({GitChangeKind::unstaged,path,origin,std::wstring(1,code[1])});
|
||||
}
|
||||
}
|
||||
std::sort(result.begin(),result.end(),[](const auto &left,const auto &right) {
|
||||
return std::tie(left.kind,left.path)<std::tie(right.kind,right.path);
|
||||
});
|
||||
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)
|
||||
{
|
||||
GitChanges result;
|
||||
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.");
|
||||
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.");
|
||||
result.checkout=readCheckout(result.executable,result.root,stop);
|
||||
result.entries=readStatus(result.executable,result.root,stop);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
|
||||
const GitChange &change,std::stop_token stop)
|
||||
{
|
||||
std::vector<std::wstring> args{L"diff",L"--no-color",L"--no-ext-diff",L"--no-textconv",L"--find-renames"};
|
||||
const bool untracked=change.kind==GitChangeKind::untracked;
|
||||
if(untracked) args.push_back(L"--no-index");
|
||||
if(change.kind==GitChangeKind::staged) args.push_back(L"--cached");
|
||||
args.push_back(L"--");
|
||||
if(untracked) args.push_back(L"/dev/null");
|
||||
else if(!change.oldPath.empty()) args.push_back(change.oldPath);
|
||||
args.push_back(change.path);
|
||||
auto patch=runGit(git,root,args,2*1024*1024,stop);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
#include <filesystem>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
enum class GitChangeKind { staged, unstaged, untracked };
|
||||
|
||||
struct GitChange
|
||||
{
|
||||
GitChangeKind kind;
|
||||
std::wstring path;
|
||||
std::wstring oldPath;
|
||||
std::wstring flags;
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,904 @@
|
||||
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{},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> 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,gitSwitch=574,gitBranch=575,gitMore=576;
|
||||
constexpr int gitIndexAction=577,gitCommitAction=578;
|
||||
|
||||
const wchar_t *gitChangeKindName(GitChangeKind kind)
|
||||
{
|
||||
switch(kind)
|
||||
{
|
||||
case GitChangeKind::staged: return L"Staged";
|
||||
case GitChangeKind::unstaged: return L"Unstaged";
|
||||
case GitChangeKind::untracked: return L"Untracked";
|
||||
}
|
||||
return L"";
|
||||
}
|
||||
|
||||
const GitChange *selectedGitChange(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.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 queueGitPreview(GitChangesView &view)
|
||||
{
|
||||
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::previewQuickViewText(view.preview,L"Diff · Reading Git changes…",{});
|
||||
return;
|
||||
}
|
||||
if(!view.failure.empty())
|
||||
{
|
||||
ks::files::previewQuickViewText(view.preview,L"Git status failed",view.failure);
|
||||
return;
|
||||
}
|
||||
if(const auto *entry=selectedGitChange(view))
|
||||
{
|
||||
view.requested=GitPreview{gitDiffHeading(*entry),*entry};
|
||||
view.previewAt=GetTickCount64()+100;
|
||||
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
|
||||
}
|
||||
else ks::files::previewQuickViewText(view.preview,L"Diff · Select a change",{});
|
||||
}
|
||||
|
||||
void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
|
||||
{
|
||||
auto query=dialogFieldText(view.filter);
|
||||
std::replace(query.begin(),query.end(),L'\\',L'/');
|
||||
const auto matches=[&](std::wstring_view path)
|
||||
{
|
||||
return query.empty() || (!path.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
|
||||
path.data(),static_cast<int>(path.size()),query.data(),static_cast<int>(query.size()),
|
||||
nullptr,nullptr,nullptr,0)>=0);
|
||||
};
|
||||
SendMessageW(view.list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(view.list,LB_RESETCONTENT,0,0);
|
||||
LRESULT selected=0,count=0;
|
||||
for(size_t index=0;index<view.data.entries.size();++index)
|
||||
{
|
||||
const auto &entry=view.data.entries[index];
|
||||
if(!matches(entry.path) && !matches(entry.oldPath)) continue;
|
||||
auto state=std::wstring(gitChangeKindName(entry.kind));
|
||||
state.resize(10,L' ');
|
||||
state+=entry.flags;
|
||||
state.resize(13,L' ');
|
||||
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;
|
||||
SendMessageW(view.list,LB_SETITEMDATA,row,index);
|
||||
if(previous && previous->path==entry.path && previous->kind==entry.kind) selected=row;
|
||||
}
|
||||
if(count) SendMessageW(view.list,LB_SETCURSEL,selected,0);
|
||||
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(view.list,nullptr,TRUE);
|
||||
InvalidateRect(view.host,nullptr,FALSE);
|
||||
updateGitChangesStatus(view,count);
|
||||
queueGitPreview(view);
|
||||
}
|
||||
|
||||
void refreshGitChanges(GitChangesView &view)
|
||||
{
|
||||
if(view.refresh.valid() || gitActionPending(view)) return;
|
||||
view.failure.clear();
|
||||
view.stopRefresh=std::stop_source{};
|
||||
try
|
||||
{
|
||||
std::packaged_task<GitChanges()> task([folder=view.folder,stop=view.stopRefresh.get_token()] {
|
||||
return ks::files::readGitChanges(folder,stop);
|
||||
});
|
||||
auto pending=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
view.refresh=std::move(pending);
|
||||
updateGitChangesStatus(view);
|
||||
queueGitPreview(view);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
view.failure="Could not start Git.";
|
||||
renderGitChanges(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);
|
||||
const auto selected=entry?std::optional(*entry):std::nullopt;
|
||||
try
|
||||
{
|
||||
view.data=view.refresh.get();
|
||||
SetWindowTextW(view.heading,(L"Git Changes · "+view.data.root.native()).c_str());
|
||||
renderGitChanges(view,selected);
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
view.data={};
|
||||
view.failure=error.what();
|
||||
renderGitChanges(view);
|
||||
}
|
||||
}
|
||||
if(view.historyTask.valid() && view.historyTask.wait_for(0ms)==std::future_status::ready)
|
||||
finishGitHistory(view);
|
||||
if(view.previewAt && GetTickCount64()>=view.previewAt)
|
||||
{
|
||||
view.previewAt=0;
|
||||
view.stopPreview=std::stop_source{};
|
||||
try
|
||||
{
|
||||
std::packaged_task<std::string()> task([git=view.data.executable,root=view.data.root,
|
||||
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.previewTask=std::move(pending);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
ks::files::previewQuickViewText(view.preview,view.requested->heading,"Could not start the Git preview.");
|
||||
}
|
||||
}
|
||||
if(view.previewTask.valid() && view.previewTask.wait_for(0ms)==std::future_status::ready)
|
||||
{
|
||||
try
|
||||
{
|
||||
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::previewQuickViewText(view.preview,view.requested->heading,error.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void openGitWorkingFile(GitChangesView &view,bool edit)
|
||||
{
|
||||
const auto *entry=selectedGitChange(view);
|
||||
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()))
|
||||
{
|
||||
SetWindowTextW(view.status,L"This path cannot be opened as a Windows file.");
|
||||
return;
|
||||
}
|
||||
auto path=view.data.root/relative.make_preferred();
|
||||
const auto attributes=GetFileAttributesW(path.c_str());
|
||||
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY))
|
||||
{
|
||||
SetWindowTextW(view.status,L"No current working file for this change.");
|
||||
return;
|
||||
}
|
||||
const auto owner=GetParent(view.host);
|
||||
if(!edit && ks::files::isImagePath(path)) ks::files::openImageWindow(owner,{path},path,textWindowDialogs());
|
||||
else ks::files::openTextWindow(owner,path,edit,textWindowDialogs());
|
||||
}
|
||||
|
||||
void layoutGitChildren(GitChangesView &view)
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(view.host,&bounds);
|
||||
const int middle=panelDivider(bounds.right);
|
||||
const auto place=[](HWND control,int x,int y,int width,int height)
|
||||
{
|
||||
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,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-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-(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.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)
|
||||
{
|
||||
const auto *create=reinterpret_cast<const CREATESTRUCTW *>(lp);
|
||||
SetWindowLongPtrW(window,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(create->lpCreateParams));
|
||||
}
|
||||
const auto view=reinterpret_cast<GitChangesView *>(GetWindowLongPtrW(window,GWLP_USERDATA));
|
||||
if(!view) return DefWindowProcW(window,message,wp,lp);
|
||||
switch(message)
|
||||
{
|
||||
case WM_CREATE:
|
||||
{
|
||||
view->host=window;
|
||||
const auto make=[&](const wchar_t *type,const wchar_t *text,DWORD style,int id=0)
|
||||
{
|
||||
return CreateWindowW(type,text,WS_CHILD|WS_VISIBLE|style,0,0,0,0,window,
|
||||
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 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->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;
|
||||
}
|
||||
case WM_SIZE:
|
||||
if(view->preview) layoutGitChildren(*view);
|
||||
return 0;
|
||||
case WM_TIMER:
|
||||
if(wp==gitChangesTimer) pollGitChanges(*view);
|
||||
return 0;
|
||||
case WM_COMMAND:
|
||||
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) 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;
|
||||
return TRUE;
|
||||
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;
|
||||
std::wstring label(count+1,L'\0');
|
||||
if(SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()))==LB_ERR)
|
||||
return TRUE;
|
||||
const bool selected=item.itemState&ODS_SELECTED;
|
||||
paintText(item.hDC,item.rcItem,label.c_str(),colors[Text],colors[selected?PanelCursor:PanelBlue]);
|
||||
return TRUE;
|
||||
}
|
||||
case WM_CTLCOLORSTATIC:
|
||||
case WM_CTLCOLOREDIT:
|
||||
case WM_CTLCOLORLISTBOX:
|
||||
{
|
||||
const auto dc=reinterpret_cast<HDC>(wp);
|
||||
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);
|
||||
}
|
||||
case WM_PAINT:
|
||||
{
|
||||
PAINTSTRUCT paint{};
|
||||
const auto dc=BeginPaint(window,&paint);
|
||||
FillRect(dc,&paint.rcPaint,blue);
|
||||
if(view->list) paintScrollPosition(window,dc,view->list,colors[PanelBlue]);
|
||||
EndPaint(window,&paint);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return DefWindowProcW(window,message,wp,lp);
|
||||
}
|
||||
|
||||
void layoutGitChanges(HWND window)
|
||||
{
|
||||
if(!gitChangesView) return;
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
SetWindowPos(gitChangesView->host,HWND_TOP,0,0,bounds.right,bounds.bottom,SWP_NOACTIVATE|SWP_SHOWWINDOW);
|
||||
layoutGitChildren(*gitChangesView);
|
||||
}
|
||||
|
||||
bool showingGitChanges()
|
||||
{
|
||||
return static_cast<bool>(gitChangesView);
|
||||
}
|
||||
|
||||
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->stopPreview.request_stop();
|
||||
view->stopHistory.request_stop();
|
||||
view->stopMutation.request_stop();
|
||||
if(IsWindow(view->host)) DestroyWindow(view->host);
|
||||
if(restore)
|
||||
{
|
||||
layout(owner);
|
||||
restoreCommandFocus();
|
||||
showFileDetails(panels[active]);
|
||||
}
|
||||
}
|
||||
|
||||
bool gitChangesAvailable(const Panel &panel)
|
||||
{
|
||||
return !terminalVisible && !panel.directory.empty() && !panel.ftp && !panel.peer && !panel.archive &&
|
||||
!windowsNetworkPath(panel.directory);
|
||||
}
|
||||
|
||||
void openGitChanges(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(gitChangesView || !gitChangesAvailable(panel)) return;
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
static const bool registered=[instance]
|
||||
{
|
||||
WNDCLASSW type{};
|
||||
type.lpfnWndProc=gitChangesProcedure;
|
||||
type.hInstance=instance;
|
||||
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
|
||||
type.lpszClassName=gitChangesClass;
|
||||
return RegisterClassW(&type)!=0;
|
||||
}();
|
||||
if(!registered) return;
|
||||
auto view=std::make_unique<GitChangesView>();
|
||||
view->folder=panel.directory;
|
||||
if(!CreateWindowW(gitChangesClass,L"Git Changes",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
|
||||
0,0,0,0,owner,nullptr,instance,view.get()))
|
||||
{
|
||||
setStatus(L"Could not open Git Changes.");
|
||||
return;
|
||||
}
|
||||
gitChangesView=std::move(view);
|
||||
closePanelSearch();
|
||||
hideCompletion();
|
||||
layout(owner);
|
||||
ShowWindow(gitChangesView->preview,SW_SHOWNA);
|
||||
SetFocus(gitChangesView->list);
|
||||
refreshGitChanges(*gitChangesView);
|
||||
}
|
||||
|
||||
bool handleGitChangesKey(HWND owner,const MSG &message)
|
||||
{
|
||||
auto &view=*gitChangesView;
|
||||
if(message.message!=WM_KEYDOWN || FilesModalDialog::activeFor(owner) ||
|
||||
(message.hwnd!=owner && message.hwnd!=view.host && !IsChild(view.host,message.hwnd))) return false;
|
||||
const auto key=message.wParam;
|
||||
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')
|
||||
{
|
||||
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))
|
||||
SendMessageW(view.list,WM_KEYDOWN,key,message.lParam);
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
+419
-73
@@ -11,6 +11,7 @@
|
||||
#include <sddl.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <psapi.h>
|
||||
#include <userenv.h>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
#include <algorithm>
|
||||
@@ -38,6 +39,7 @@
|
||||
#include <libssh2_sftp.h>
|
||||
#include "files_terminal.h"
|
||||
#include "files_archive.h"
|
||||
#include "files_git_changes.h"
|
||||
#include "files_compare_text.h"
|
||||
#include "files_image_decode.h"
|
||||
#include "files_win32_directory.h"
|
||||
@@ -832,6 +834,11 @@ constexpr DWORD defaultStatusFields=15;
|
||||
int sizeWidth=defaultSizeWidth;
|
||||
bool alignExtensions=defaultAlignExtensions, showDetails=defaultShowDetails;
|
||||
bool alignFolders=defaultAlignFolders;
|
||||
bool rightClickMarks{}, showDriveButtons{}, compactLayout{};
|
||||
constexpr wchar_t rightClickMarksKey[]=L"RightClickMarks", driveButtonsKey[]=L"ShowDriveButtons",
|
||||
compactLayoutKey[]=L"CompactPanelLayout";
|
||||
constexpr int firstDriveButton=660, moreDriveButton=firstDriveButton+26;
|
||||
std::array<HWND,27> driveButtons{};
|
||||
DWORD statusFields=defaultStatusFields;
|
||||
std::vector<fs::path> drivePaths;
|
||||
bool lanDrivePicker{};
|
||||
@@ -1592,6 +1599,8 @@ void swapPanels(HWND window)
|
||||
}
|
||||
notifyFilesPreferences(window);
|
||||
layout(window);
|
||||
showFileDetails(panels[active]);
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
}
|
||||
|
||||
bool hasSelectionSummary()
|
||||
@@ -1617,19 +1626,28 @@ void setPanelDivider(HWND window,int width,int position)
|
||||
layout(window);
|
||||
}
|
||||
|
||||
void layoutGitChanges(HWND window);
|
||||
bool showingGitChanges();
|
||||
|
||||
void layout(HWND window,bool activeOnly)
|
||||
{
|
||||
RECT rect{};
|
||||
GetClientRect(window, &rect);
|
||||
int width = rect.right, height = rect.bottom;
|
||||
const int inputTop=height-2*textHeight;
|
||||
const bool gitMode=showingGitChanges();
|
||||
const int terminalBottom=std::max(4,inputTop);
|
||||
const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0;
|
||||
const int detailsHeight=terminalVisible?0:textHeight+12+summaryHeight;
|
||||
const int detailsInset=compactLayout?2:4;
|
||||
const int detailsHeight=terminalVisible?0:textHeight+(compactLayout?4:12)+summaryHeight;
|
||||
const DWORD driveMask=showDriveButtons && !terminalVisible && !gitMode?GetLogicalDrives():0;
|
||||
const int driveHeight=driveMask?textHeight+2:0;
|
||||
const int panelMargin=compactLayout?4:5;
|
||||
const int pathTop=driveHeight+(compactLayout?1:4);
|
||||
const int terminalTop=terminalVisible?4:std::max(4,terminalBottom-
|
||||
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/textHeight-4))*textHeight);
|
||||
const int panelBottom=terminalTop-detailsHeight;
|
||||
const bool showOutput=terminalTop<terminalBottom;
|
||||
const bool showOutput=!gitMode && terminalTop<terminalBottom;
|
||||
traceTerminal("layout",terminalRows,terminalTop,terminalBottom,showOutput,terminalVisible);
|
||||
const int middle=panelDivider(width);
|
||||
auto place=[](HWND control, int x, int y, int width, int height)
|
||||
@@ -1639,21 +1657,41 @@ void layout(HWND window,bool activeOnly)
|
||||
};
|
||||
if(!activeOnly)
|
||||
{
|
||||
const int buttonWidth=std::max(4*cellWidth,32);
|
||||
const int maxButtons=std::max(1,(width-8)/buttonWidth);
|
||||
int drives=0;
|
||||
for(int letter=0;letter<26;++letter) if(driveMask&(1UL<<letter)) ++drives;
|
||||
const int visibleDrives=drives>maxButtons?maxButtons-1:drives;
|
||||
int slot=0;
|
||||
for(int letter=0;letter<26;++letter)
|
||||
{
|
||||
const auto button=driveButtons[letter];
|
||||
if(!button) continue;
|
||||
const bool visible=(driveMask&(1UL<<letter)) && slot<visibleDrives;
|
||||
if(visible) place(button,4+slot++*buttonWidth,0,buttonWidth,textHeight);
|
||||
ShowWindow(button,visible?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
if(const auto more=driveButtons.back())
|
||||
{
|
||||
place(more,4+slot*buttonWidth,0,buttonWidth,textHeight);
|
||||
ShowWindow(more,drives>maxButtons?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
const int headingTop=pathTop+textHeight+(compactLayout?2:6);
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
int x = i ? middle + 2 : 0;
|
||||
int end = i ? width : middle - 2;
|
||||
place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight);
|
||||
place(panels[i].path, x+panelMargin,pathTop,std::max(0,end-x-2*panelMargin),textHeight);
|
||||
int headingHeight=detailedPanel(panels[i])?textHeight:0;
|
||||
const int listWidth=std::max(0,end-x-8-scrollBarWidth(panels[i].list));
|
||||
const bool panelVisible=!terminalVisible && (!quickViewWindow || i==quickViewSource);
|
||||
const int listWidth=std::max(0,end-x-panelMargin-3-scrollBarWidth(panels[i].list));
|
||||
const bool panelVisible=!gitMode && !terminalVisible && (!quickViewWindow || i==quickViewSource);
|
||||
ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE);
|
||||
place(panels[i].heading,x+5,textHeight+10,listWidth,headingHeight);
|
||||
place(panels[i].heading,x+panelMargin,headingTop,listWidth,headingHeight);
|
||||
ShowWindow(panels[i].heading,panelVisible && detailedPanel(panels[i])?SW_SHOWNA:SW_HIDE);
|
||||
place(panels[i].list, x + 5, textHeight+10+headingHeight,listWidth,
|
||||
std::max(0, panelBottom-textHeight-10-headingHeight));
|
||||
place(panels[i].selectionSummary,x+8,panelBottom+4,std::max(0,end-x-16),summaryHeight);
|
||||
place(panels[i].list,x+panelMargin,headingTop+headingHeight,listWidth,
|
||||
std::max(0,panelBottom-headingTop-headingHeight));
|
||||
place(panels[i].selectionSummary,x+8,panelBottom+detailsInset,std::max(0,end-x-16),summaryHeight);
|
||||
ShowWindow(panels[i].selectionSummary,panelVisible && summaryHeight?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
place(menuBar,0,0,width,textHeight+4);
|
||||
@@ -1663,7 +1701,7 @@ void layout(HWND window,bool activeOnly)
|
||||
}
|
||||
const int detailsLeft=active?middle+2:0;
|
||||
const int detailsRight=active?width:middle-2;
|
||||
place(status,detailsLeft+8,panelBottom+4+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
|
||||
place(status,detailsLeft+8,panelBottom+detailsInset+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
|
||||
const auto ¤t=panels[active];
|
||||
const auto prompt=panelLocation(current)+(terminalVisible?L"> ":L">");
|
||||
SetWindowTextW(terminalPrompt,prompt.c_str());
|
||||
@@ -1680,7 +1718,13 @@ void layout(HWND window,bool activeOnly)
|
||||
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),textHeight);
|
||||
if(activeOnly)
|
||||
{
|
||||
const RECT details{0,panelBottom+4+summaryHeight,width,panelBottom+4+summaryHeight+textHeight};
|
||||
const RECT details{0,panelBottom+detailsInset+summaryHeight,width,
|
||||
panelBottom+detailsInset+summaryHeight+textHeight};
|
||||
if(driveHeight)
|
||||
{
|
||||
const RECT drives{0,0,width,driveHeight};
|
||||
RedrawWindow(window,&drives,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
}
|
||||
const RECT commandLine{0,inputTop,width,inputTop+textHeight};
|
||||
if(!terminalVisible) RedrawWindow(window,&details,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
RedrawWindow(window,&commandLine,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
@@ -1695,7 +1739,9 @@ void layout(HWND window,bool activeOnly)
|
||||
}
|
||||
if(!showOutput) clearTerminalSelection();
|
||||
ShowWindow(terminalOutput,showOutput?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(status,terminalVisible?SW_HIDE:SW_SHOWNA);
|
||||
ShowWindow(status,terminalVisible || gitMode?SW_HIDE:SW_SHOWNA);
|
||||
ShowWindow(terminalPrompt,gitMode?SW_HIDE:SW_SHOWNA);
|
||||
ShowWindow(terminalInput,gitMode?SW_HIDE:SW_SHOWNA);
|
||||
terminalView.layout(terminalOutput,showOutput && !sshPrompt,terminalBottom-4);
|
||||
sshView.layout(terminalOutput,showOutput && sshPrompt.has_value(),terminalBottom-4);
|
||||
constexpr int refreshExtra=4;
|
||||
@@ -1706,6 +1752,7 @@ void layout(HWND window,bool activeOnly)
|
||||
const int left=i?(i*unit+refreshExtra)*width/total:0;
|
||||
const int right=((i+1)*unit+refreshExtra)*width/total;
|
||||
place(commands[i],left,height-textHeight,right-left,textHeight);
|
||||
ShowWindow(commands[i],gitMode?SW_HIDE:SW_SHOWNA);
|
||||
}
|
||||
if(quickViewWindow)
|
||||
{
|
||||
@@ -1714,13 +1761,15 @@ void layout(HWND window,bool activeOnly)
|
||||
for(const auto preview:{quickViewWindow,quickImageWindow})
|
||||
{
|
||||
if(!preview) continue;
|
||||
SetWindowPos(preview,nullptr,left+5,4,std::max(0,right-left-10),
|
||||
std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
const int bottom=panelBottom+summaryHeight+textHeight+detailsInset;
|
||||
SetWindowPos(preview,nullptr,left+panelMargin,pathTop,std::max(0,right-left-2*panelMargin),
|
||||
std::max(0,bottom-pathTop),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
const bool current=quickViewDisplaysImage==(preview==quickImageWindow);
|
||||
ShowWindow(preview,!terminalVisible && current?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(preview,!gitMode && !terminalVisible && current?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
}
|
||||
if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window);
|
||||
layoutGitChanges(window);
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
|
||||
}
|
||||
|
||||
@@ -3837,6 +3886,9 @@ void showPanelItemProperties(HWND owner,Panel &panel);
|
||||
bool panelLockSearchAvailable(const Panel &panel);
|
||||
void showPanelLockProcesses(HWND owner,Panel &panel);
|
||||
void showProcesses(HWND owner,std::vector<fs::path> paths={});
|
||||
bool gitChangesAvailable(const Panel &panel);
|
||||
void openGitChanges(HWND owner,const Panel &panel);
|
||||
void showEnvironmentPanel(HWND owner);
|
||||
|
||||
bool selectablePickerRow(LRESULT row)
|
||||
{
|
||||
@@ -3885,6 +3937,9 @@ void selectDrive()
|
||||
else if(menuIndex==2 && row==13) openSelectedText(panels[active],false,false,true);
|
||||
else if(menuIndex==2 && row==14) ks::files::showAllViewerBookmarks(owner,textWindowDialogs());
|
||||
else if(menuIndex==2 && row==15) showProcesses(owner);
|
||||
else if(menuIndex==2 && row==16) openGitChanges(owner,panels[active]);
|
||||
else if(menuIndex==2 && row==17) showEnvironmentPanel(owner);
|
||||
else if(menuIndex==2 && row==18) swapPanels(owner);
|
||||
else if(menuIndex==1 && row==4) createArchive(owner,panels[active]);
|
||||
else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]);
|
||||
else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]);
|
||||
@@ -4636,6 +4691,13 @@ struct CopyDestination
|
||||
bool useSourcePeer{};
|
||||
};
|
||||
|
||||
struct CopyOptions
|
||||
{
|
||||
std::wstring mask=L"*";
|
||||
std::vector<fs::path> additional;
|
||||
bool preserveTime=true, preservePermissions{};
|
||||
};
|
||||
|
||||
struct CopyRequest
|
||||
{
|
||||
std::vector<fs::path> sources;
|
||||
@@ -4650,6 +4712,7 @@ struct CopyRequest
|
||||
std::wstring ftpDestination;
|
||||
bool upload{};
|
||||
bool ftpRename{}, externalSources{}, archiveSource{};
|
||||
CopyOptions options;
|
||||
};
|
||||
|
||||
bool directoryExists(const FilesPeer *peer,const fs::path &path)
|
||||
@@ -5277,6 +5340,8 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring &
|
||||
return {std::move(request.destination),std::move(request.newName),useSourcePeer};
|
||||
}
|
||||
|
||||
#include "files_copy_options.inl"
|
||||
|
||||
INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
|
||||
{
|
||||
constexpr int summary=210, pathField=211, conflicts=212;
|
||||
@@ -5332,7 +5397,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
|
||||
SendDlgItemMessageW(dialog,pathField,EM_SETREADONLY,!single && !request.move,0);
|
||||
if(request.move) SetDlgItemTextW(dialog,IDOK,request.externalSources?L"&Move":L"&Rename");
|
||||
fitFarEditToLine(GetDlgItem(dialog,pathField));
|
||||
layoutDialogButtons(dialog,214,{IDOK,IDCANCEL});
|
||||
layoutDialogButtons(dialog,214,{IDOK,215,IDCANCEL});
|
||||
installFarCheckbox(GetDlgItem(dialog,214),FarCheckboxSurface::gray);
|
||||
CheckDlgButton(dialog,214,request.askReadOnly?BST_CHECKED:BST_UNCHECKED);
|
||||
SendDlgItemMessageW(dialog,summary,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
@@ -5370,7 +5435,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(!request.validation.valid() ||
|
||||
request.validation.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE;
|
||||
KillTimer(dialog,validationTimer);
|
||||
for(const auto control:{pathField,213,214,IDOK}) EnableWindow(GetDlgItem(dialog,control),TRUE);
|
||||
for(const auto control:{pathField,213,214,215,IDOK}) EnableWindow(GetDlgItem(dialog,control),TRUE);
|
||||
try
|
||||
{
|
||||
auto result=request.validation.get();
|
||||
@@ -5388,6 +5453,14 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
|
||||
InvalidateRect(GetDlgItem(dialog,213),nullptr,FALSE);
|
||||
return FALSE;
|
||||
}
|
||||
if(LOWORD(wp)==215)
|
||||
{
|
||||
CopyOptionsPrompt options{request.options, request.ftpDestination.empty() && !request.archiveSource, request.move,
|
||||
request.upload};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(129),dialog,copyOptionsDialog,
|
||||
reinterpret_cast<LPARAM>(&options))==IDOK) request.options=std::move(options.value);
|
||||
return TRUE;
|
||||
}
|
||||
if(LOWORD(wp)!=IDOK) return FALSE;
|
||||
if(request.validation.valid()) return TRUE;
|
||||
try
|
||||
@@ -5431,7 +5504,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
|
||||
std::thread(std::move(validation)).detach();
|
||||
request.validation=std::move(ready);
|
||||
SetFocus(GetDlgItem(dialog,IDCANCEL));
|
||||
for(const auto control:{pathField,213,214,IDOK}) EnableWindow(GetDlgItem(dialog,control),FALSE);
|
||||
for(const auto control:{pathField,213,214,215,IDOK}) EnableWindow(GetDlgItem(dialog,control),FALSE);
|
||||
}
|
||||
catch(const std::exception &e)
|
||||
{
|
||||
@@ -5511,14 +5584,17 @@ struct CopyProgress
|
||||
std::atomic_bool canceled{};
|
||||
bool closeOwner{};
|
||||
bool move{}, fileSourcesOnly{};
|
||||
bool writingArchive{};
|
||||
bool writingArchive{}, deferRemoval{};
|
||||
CopyOptions options;
|
||||
int conflictChoice{};
|
||||
ConflictMode conflictMode{};
|
||||
bool askReadOnly=true;
|
||||
uint64_t files{}, totalFiles{}, bytes{}, totalBytes{};
|
||||
uint64_t skippedFiles{}, skippedBytes{};
|
||||
const wchar_t *lastSkipReason=L"";
|
||||
ULONGLONG lastPaint{};
|
||||
ULONGLONG lastPaint{}, sampleStart{}, lastSample{};
|
||||
uint64_t sampleBytes{}, lastBytes{};
|
||||
unsigned samples{};
|
||||
fs::path from,to,renamedTarget;
|
||||
fs::path localLockSource,localLockTarget;
|
||||
};
|
||||
@@ -5584,8 +5660,30 @@ void updateCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSiz
|
||||
SetDlgItemTextW(progress.window,224,(L"Files: "+std::to_wstring(progress.files)+L" / "+
|
||||
std::to_wstring(progress.totalFiles)+(progress.skippedFiles?
|
||||
L" Skipped: "+std::to_wstring(progress.skippedFiles)+L" ("+progress.lastSkipReason+L")":L"")).c_str());
|
||||
SetDlgItemTextW(progress.window,225,(L"Size: "+formatSize(bytes)+L" / "+
|
||||
formatSize(progress.totalBytes)).c_str());
|
||||
auto sizeText=L"Size: "+formatSize(bytes)+L" / "+formatSize(progress.totalBytes);
|
||||
if(!progress.sampleStart || progress.lastPaint-progress.lastSample>1500 || bytes<progress.lastBytes)
|
||||
{
|
||||
progress.sampleStart=progress.lastSample=progress.lastPaint;
|
||||
progress.sampleBytes=progress.lastBytes=bytes;
|
||||
progress.samples=0;
|
||||
}
|
||||
else if(bytes>progress.lastBytes && progress.lastPaint-progress.lastSample>=200)
|
||||
{
|
||||
progress.lastSample=progress.lastPaint;
|
||||
progress.lastBytes=bytes;
|
||||
++progress.samples;
|
||||
}
|
||||
const auto elapsed=progress.lastSample-progress.sampleStart;
|
||||
const auto accounted=std::min(progress.totalBytes,bytes+progress.skippedBytes);
|
||||
if(progress.samples>=3 && elapsed>=1200 && bytes>progress.sampleBytes && accounted<progress.totalBytes)
|
||||
{
|
||||
const auto estimate=std::ceil((progress.totalBytes-accounted)*(elapsed/1000.0)/(bytes-progress.sampleBytes));
|
||||
const auto seconds=static_cast<uint64_t>(std::min(estimate,360000000.0));
|
||||
sizeText+=L" Remaining: "+std::to_wstring(seconds/3600)+L":"+
|
||||
(seconds%3600/60<10?L"0":L"")+std::to_wstring(seconds%3600/60)+L":"+
|
||||
(seconds%60<10?L"0":L"")+std::to_wstring(seconds%60);
|
||||
}
|
||||
SetDlgItemTextW(progress.window,225,sizeText.c_str());
|
||||
}
|
||||
|
||||
void reportCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSize,bool force=false)
|
||||
@@ -6284,23 +6382,69 @@ ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile)
|
||||
return source;
|
||||
}
|
||||
|
||||
bool countCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
|
||||
struct CopyNode
|
||||
{
|
||||
if(progress.canceled) return false;
|
||||
fs::path path;
|
||||
FileInfo info;
|
||||
std::vector<CopyNode> children;
|
||||
bool whole=true;
|
||||
};
|
||||
|
||||
std::optional<CopyNode> planCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
|
||||
{
|
||||
if(progress.canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
const auto info=host.stat(path,progress.canceled);
|
||||
if(!info || (info->attributes&FILE_ATTRIBUTE_REPARSE_POINT))
|
||||
throw std::system_error(info?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category());
|
||||
if(progress.fileSourcesOnly && (info->attributes&FILE_ATTRIBUTE_DIRECTORY))
|
||||
if(!info) throw std::system_error(ERROR_FILE_NOT_FOUND,std::system_category());
|
||||
const bool directory=info->attributes&FILE_ATTRIBUTE_DIRECTORY;
|
||||
if(!directory && !matchesFileMask(path.filename().native(),progress.options.mask)) return {};
|
||||
if(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)
|
||||
throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category());
|
||||
if(progress.fileSourcesOnly && directory)
|
||||
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
|
||||
if(!(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
|
||||
CopyNode node{path,*info,{}};
|
||||
if(!directory)
|
||||
{
|
||||
++progress.totalFiles;
|
||||
progress.totalBytes+=info->size;
|
||||
return true;
|
||||
}
|
||||
for(const auto &[child,entry]:host.children(path,progress.canceled))
|
||||
if(!countCopy(host,child,progress)) return false;
|
||||
return true;
|
||||
else
|
||||
{
|
||||
for(const auto &[child,entry]:host.children(path,progress.canceled))
|
||||
{
|
||||
auto item=planCopy(host,child,progress);
|
||||
node.whole=node.whole && item && item->whole;
|
||||
if(item) node.children.push_back(std::move(*item));
|
||||
}
|
||||
if(node.children.empty() && progress.options.mask!=L"*") return {};
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
void verifyCopyPlan(CopyHost &source,const CopyNode &node,const std::atomic_bool &canceled)
|
||||
{
|
||||
if(canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
const auto current=source.stat(node.path,canceled);
|
||||
if(!current || current->size!=node.info.size || current->modified!=node.info.modified ||
|
||||
((current->attributes^node.info.attributes)&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)))
|
||||
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
|
||||
for(const auto &child:node.children) verifyCopyPlan(source,child,canceled);
|
||||
}
|
||||
|
||||
void removeCopiedPlan(CopyHost &source,const CopyNode &node,CopyProgress &progress,bool local)
|
||||
{
|
||||
if(progress.canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
const bool directory=node.info.attributes&FILE_ATTRIBUTE_DIRECTORY;
|
||||
for(const auto &child:node.children) removeCopiedPlan(source,child,progress,local);
|
||||
if(directory && !node.whole) return;
|
||||
progress.localLockSource=local?node.path:fs::path{};
|
||||
progress.localLockTarget.clear();
|
||||
auto action=fileRequest(directory?"rmdir":"remove",node.path);
|
||||
if(!directory)
|
||||
{
|
||||
action["size"]=node.info.size;
|
||||
action["modified"]=node.info.modified;
|
||||
}
|
||||
checkFileReply(source.request(action));
|
||||
}
|
||||
|
||||
enum class CopyResult { complete, skipped, failed };
|
||||
@@ -6328,7 +6472,7 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path
|
||||
}
|
||||
if(hosts.target.ftp)
|
||||
{
|
||||
uploadTransferFile(*hosts.source.files,*hosts.target.ftp,from,to,info,replace,update);
|
||||
uploadTransferFile(*hosts.source.files,*hosts.target.ftp,from,to,info,replace,update,nullptr,progress.options.preserveTime);
|
||||
hosts.target.listedDirectory.clear();
|
||||
return;
|
||||
}
|
||||
@@ -6347,9 +6491,27 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path
|
||||
info.size,info.modified,replace,append,update);
|
||||
}
|
||||
|
||||
CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::path &to,CopyProgress &progress,
|
||||
void applyCopyMetadata(const CopyEndpoints &hosts,const fs::path &to,const FileInfo &info,
|
||||
const CopyOptions &options,const Json &permissions,bool directory)
|
||||
{
|
||||
if(hosts.target.ftp)
|
||||
{
|
||||
if(directory && options.preserveTime) hosts.target.ftp->preserveModificationTime(to,info.modified);
|
||||
return;
|
||||
}
|
||||
auto request=fileRequest("applyCopyMetadata",to);
|
||||
if(directory && options.preserveTime && info.modified && hosts.target.supportsCopyMetadata())
|
||||
request["modified"]=info.modified;
|
||||
else if(!directory && !options.preserveTime)
|
||||
request["modified"]=uint64_t{};
|
||||
if(!permissions.is_null()) request["permissions"]=permissions;
|
||||
if(request.size()>2) checkFileReply(hosts.target.request(request));
|
||||
}
|
||||
|
||||
CopyResult copyItem(const CopyEndpoints &hosts,const CopyNode &node,const fs::path &to,CopyProgress &progress,
|
||||
bool topLevel=false,bool singleItem=false)
|
||||
{
|
||||
const auto &from=node.path;
|
||||
if(progress.canceled) return CopyResult::failed;
|
||||
if((hosts.source.ftp || hosts.target.ftp) && !validFtpCopyName(to.filename().native(),hosts.target.ftp.has_value()))
|
||||
throw std::system_error(ERROR_INVALID_NAME,std::system_category());
|
||||
@@ -6358,12 +6520,21 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
|
||||
const auto incoming=hosts.source.stat(from,progress.canceled);
|
||||
if(!incoming || (incoming->attributes&FILE_ATTRIBUTE_REPARSE_POINT))
|
||||
throw std::system_error(incoming?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category());
|
||||
if(progress.fileSourcesOnly && (incoming->attributes&FILE_ATTRIBUTE_DIRECTORY))
|
||||
if(((incoming->attributes^node.info.attributes)&FILE_ATTRIBUTE_DIRECTORY) ||
|
||||
(!(incoming->attributes&FILE_ATTRIBUTE_DIRECTORY) &&
|
||||
(incoming->size!=node.info.size || incoming->modified!=node.info.modified)))
|
||||
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
|
||||
|
||||
const auto readPermissions=[&] {
|
||||
if(!progress.options.preservePermissions) return Json(nullptr);
|
||||
const auto reply=hosts.source.request(fileRequest("copyPermissions",from));
|
||||
checkFileReply(reply);
|
||||
return Json(reply.at("permissions"));
|
||||
};
|
||||
const auto removeImmediately=progress.move && !progress.deferRemoval;
|
||||
const auto moveOnHost=[&](const fs::path &target,bool replace)
|
||||
{
|
||||
if(!progress.move || !hosts.sameHost) return false;
|
||||
if(!removeImmediately || !hosts.sameHost) return false;
|
||||
auto request=fileRequest("move",from);
|
||||
request["target"]=ks::utf8(target.native());
|
||||
request["replace"]=replace;
|
||||
@@ -6384,15 +6555,17 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
|
||||
progress.bytes=progress.totalBytes;
|
||||
return CopyResult::complete;
|
||||
}
|
||||
const auto permissions=existing?Json(nullptr):readPermissions();
|
||||
if(!existing) hosts.target.makeDirectory(to);
|
||||
auto result=CopyResult::complete;
|
||||
for(const auto &[child,entry]:hosts.source.children(from,progress.canceled))
|
||||
for(const auto &child:node.children)
|
||||
{
|
||||
const auto outcome=copyItem(hosts,child,to/child.filename(),progress);
|
||||
const auto outcome=copyItem(hosts,child,to/child.path.filename(),progress);
|
||||
if(outcome==CopyResult::failed) return outcome;
|
||||
if(outcome==CopyResult::skipped) result=outcome;
|
||||
}
|
||||
if(progress.move && result==CopyResult::complete)
|
||||
if(!existing) applyCopyMetadata(hosts,to,*incoming,progress.options,permissions,true);
|
||||
if(removeImmediately && result==CopyResult::complete)
|
||||
{
|
||||
progress.localLockSource=hosts.sourceLocal?from:fs::path{};
|
||||
progress.localLockTarget.clear();
|
||||
@@ -6409,8 +6582,10 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
|
||||
if(hosts.targetLocal) progress.localLockTarget=target;
|
||||
if(!moveOnHost(target,replace))
|
||||
{
|
||||
const auto permissions=readPermissions();
|
||||
transferFile(hosts,from,target,*incoming,replace,append,progress);
|
||||
if(progress.move)
|
||||
applyCopyMetadata(hosts,target,*incoming,progress.options,permissions,false);
|
||||
if(removeImmediately)
|
||||
{
|
||||
auto remove=fileRequest("remove",from);
|
||||
remove["size"]=incoming->size;
|
||||
@@ -6623,6 +6798,9 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
progress.fileSourcesOnly=fromSearch;
|
||||
progress.conflictMode=request.conflictMode;
|
||||
progress.askReadOnly=request.askReadOnly;
|
||||
progress.options=std::move(request.options);
|
||||
progress.deferRemoval=move && (progress.options.mask!=L"*" || !progress.options.additional.empty() ||
|
||||
progress.options.preservePermissions || !progress.options.preserveTime);
|
||||
FilesModalDialog progressDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner,
|
||||
copyProgressDialog,reinterpret_cast<LPARAM>(&progress));
|
||||
progress.window=progressDialog.window();
|
||||
@@ -6637,8 +6815,11 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
for(const auto command:commands) EnableWindow(command,FALSE);
|
||||
progressDialog.show();
|
||||
bool failed=false, skipped=false;
|
||||
size_t copied=0;
|
||||
size_t copied=0, completedCopies=0, requestedCopies=0;
|
||||
const bool multiple=!progress.options.additional.empty();
|
||||
bool noMatchingFiles=false;
|
||||
std::set<fs::path> results, removed;
|
||||
fs::path failedDestination;
|
||||
std::wstring failure;
|
||||
std::vector<fs::path> lockPaths;
|
||||
try
|
||||
@@ -6691,43 +6872,103 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost,
|
||||
request.sourcePeer?request.sourcePeer->id:"local",!request.sourcePeer && !sourceFtp,
|
||||
!targetPeer && !destinationFtp};
|
||||
for(const auto &path:sources)
|
||||
if(!countCopy(sourceHost,path,progress)) { failed=true; break; }
|
||||
reportCopyProgress(progress,0,0,true);
|
||||
std::vector<std::pair<size_t,CopyNode>> plans;
|
||||
for(size_t i=0;i<sources.size();++i)
|
||||
if(auto plan=planCopy(sourceHost,sources[i],progress)) plans.emplace_back(i,std::move(*plan));
|
||||
if(plans.empty()) { noMatchingFiles=true; return; }
|
||||
|
||||
const auto canonical=[&](const fs::path &name) {
|
||||
const auto reply=hosts.target.request(fileRequest("canonical",name));
|
||||
checkFileReply(reply);
|
||||
return filePath(reply.at("path"));
|
||||
};
|
||||
const auto equalPath=[&](const fs::path &first,const fs::path &second) {
|
||||
return destinationFtp?first==second:
|
||||
CompareStringOrdinal(first.c_str(),-1,second.c_str(),-1,TRUE)==CSTR_EQUAL;
|
||||
};
|
||||
std::vector<fs::path> folders{targetDirectory};
|
||||
std::vector<fs::path> locations{destinationFtp?targetDirectory:canonical(targetDirectory)};
|
||||
for(const auto &folder:progress.options.additional)
|
||||
{
|
||||
if(failed) break;
|
||||
const auto &path=sources[i];
|
||||
const auto to=targetDirectory/(renamed?request.newName:path.filename());
|
||||
if(sameHost)
|
||||
const auto location=destinationFtp?folder:canonical(folder);
|
||||
if(std::any_of(locations.begin(),locations.end(),[&](const auto &known) {return equalPath(known,location);}))
|
||||
continue;
|
||||
const auto info=folder==folder.root_path() && destinationFtp?std::optional<FileInfo>{
|
||||
FileInfo{FILE_ATTRIBUTE_DIRECTORY,0,0}}:hosts.target.stat(folder,progress.canceled);
|
||||
if(!info || !(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
|
||||
{
|
||||
const auto canonical=[&](const fs::path &name)
|
||||
failedDestination=folder;
|
||||
throw std::system_error(ERROR_PATH_NOT_FOUND,std::system_category());
|
||||
}
|
||||
folders.push_back(folder);
|
||||
locations.push_back(location);
|
||||
}
|
||||
requestedCopies=plans.size()*folders.size();
|
||||
progress.totalFiles*=folders.size();
|
||||
progress.totalBytes*=folders.size();
|
||||
if(progress.options.preservePermissions &&
|
||||
(!hosts.source.supportsCopyMetadata() || !hosts.target.supportsCopyMetadata()))
|
||||
throw std::runtime_error("Update both KSwitcher computers to preserve Windows permissions.");
|
||||
if(!progress.options.preserveTime && !destinationFtp && !hosts.target.supportsCopyMetadata())
|
||||
throw std::runtime_error("Update KSwitcher on the destination to set a new modification time.");
|
||||
|
||||
if(sameHost)
|
||||
{
|
||||
for(const auto &[index,plan]:plans)
|
||||
{
|
||||
const auto canonicalSource=canonical(plan.path);
|
||||
for(const auto &folder:folders)
|
||||
{
|
||||
const auto reply=sourceHost.request(fileRequest("canonical",name));
|
||||
checkFileReply(reply);
|
||||
return filePath(reply.at("path"));
|
||||
};
|
||||
const auto canonicalSource=canonical(path);
|
||||
const auto canonicalTarget=canonical(to);
|
||||
for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path())
|
||||
{
|
||||
if(CompareStringOrdinal(ancestor.c_str(),-1,canonicalSource.c_str(),-1,TRUE)==CSTR_EQUAL)
|
||||
const auto target=folder/(renamed?request.newName:plan.path.filename());
|
||||
const auto canonicalTarget=canonical(target);
|
||||
for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path())
|
||||
{
|
||||
throw std::system_error(ERROR_INVALID_PARAMETER,std::system_category());
|
||||
if(equalPath(ancestor,canonicalSource))
|
||||
{
|
||||
failedDestination=target;
|
||||
throw std::system_error(ERROR_INVALID_PARAMETER,std::system_category());
|
||||
}
|
||||
if(!ancestor.has_relative_path()) break;
|
||||
}
|
||||
if(!ancestor.has_relative_path()) break;
|
||||
}
|
||||
}
|
||||
if(failed) break;
|
||||
progress.renamedTarget.clear();
|
||||
const auto outcome=copyItem(hosts,path,to,progress,true,sources.size()==1);
|
||||
if(outcome==CopyResult::failed) { failed=true; break; }
|
||||
if(outcome==CopyResult::skipped) { skipped=true; continue; }
|
||||
}
|
||||
reportCopyProgress(progress,0,0,true);
|
||||
for(const auto &[index,plan]:plans)
|
||||
{
|
||||
const auto &path=plan.path;
|
||||
bool allDestinations=true;
|
||||
fs::path primaryResult;
|
||||
for(size_t destinationIndex=0;destinationIndex<folders.size();++destinationIndex)
|
||||
{
|
||||
if(progress.canceled) return;
|
||||
const auto to=folders[destinationIndex]/(renamed?request.newName:path.filename());
|
||||
failedDestination=to;
|
||||
progress.renamedTarget.clear();
|
||||
const auto outcome=copyItem(hosts,plan,to,progress,true,plans.size()==1 && folders.size()==1);
|
||||
if(outcome==CopyResult::failed) { failed=true; return; }
|
||||
if(outcome==CopyResult::skipped) { skipped=true; allDestinations=false; continue; }
|
||||
++completedCopies;
|
||||
if(destinationIndex==0)
|
||||
{
|
||||
primaryResult=progress.renamedTarget.empty()?to:progress.renamedTarget;
|
||||
results.insert(primaryResult);
|
||||
}
|
||||
}
|
||||
if(!allDestinations) continue;
|
||||
failedDestination.clear();
|
||||
if(progress.deferRemoval)
|
||||
{
|
||||
verifyCopyPlan(sourceHost,plan,progress.canceled);
|
||||
removeCopiedPlan(sourceHost,plan,progress,hosts.sourceLocal);
|
||||
if(!plan.whole) skipped=true;
|
||||
}
|
||||
if(!primaryResult.empty() && primaryResult.filename()!=path.filename())
|
||||
progress.renamedTarget=primaryResult;
|
||||
++copied;
|
||||
if(move && fromSearch) removed.insert(path);
|
||||
results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget);
|
||||
if(!request.externalSources) progress.ui.invoke([&] {
|
||||
const auto row=std::find(source.rows.begin(),source.rows.end(),request.sources[i]);
|
||||
if(move && plan.whole && (fromSearch || treePanelActive(source))) removed.insert(path);
|
||||
if(!request.externalSources && plan.whole) progress.ui.invoke([&] {
|
||||
const auto row=std::find(source.rows.begin(),source.rows.end(),request.sources[index]);
|
||||
if(row!=source.rows.end()) markPanelRow(source,row-source.rows.begin(),false);
|
||||
else if(treePanelActive(source)) source.tree.marks.erase(path);
|
||||
InvalidateRect(source.list,nullptr,FALSE);
|
||||
@@ -6749,7 +6990,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
catch(const std::exception &e)
|
||||
{
|
||||
failed=true;
|
||||
failure=archive.empty()?L"File connection interrupted.":ks::wide(e.what());
|
||||
failure=ks::wide(e.what());
|
||||
}
|
||||
const auto targetId=peerId(targetPeer);
|
||||
const bool restoreFocus=GetForegroundWindow()==progress.window;
|
||||
@@ -6809,9 +7050,24 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
SetForegroundWindow(owner);
|
||||
SetFocus(panels[active].list);
|
||||
}
|
||||
const auto outcomeText=[&] {
|
||||
auto text=std::to_wstring(completedCopies)+L" of "+std::to_wstring(requestedCopies)+
|
||||
L" item copies completed across the requested folders. "+std::to_wstring(progress.files)+L" files copied.";
|
||||
if(move) text+=L" Sources were removed only after their requested copies completed.";
|
||||
return text;
|
||||
};
|
||||
if(failed && !progress.canceled)
|
||||
{
|
||||
if(failure.empty()) failure=L"Could not complete the operation.";
|
||||
if(!failedDestination.empty()) failure+=L"\r\n\r\nDestination: "+failedDestination.native();
|
||||
if(multiple && requestedCopies) failure+=L"\r\n\r\n"+outcomeText();
|
||||
showFileOperationError(owner,ftpRename?L"Rename failed":move?L"Move failed":L"Copy failed",
|
||||
failure.empty()?L"Could not complete the operation.":failure,std::move(lockPaths));
|
||||
failure,std::move(lockPaths));
|
||||
}
|
||||
else if(noMatchingFiles)
|
||||
setStatus(L"No files match the copy mask.");
|
||||
else if(multiple)
|
||||
setStatus((progress.canceled?L"Canceled. ":skipped?L"Finished with skipped copies. ":L"")+outcomeText());
|
||||
else if(ftpRename)
|
||||
setStatus(copied?L"Rename complete.":L"Rename canceled.");
|
||||
else if(move)
|
||||
@@ -7660,6 +7916,27 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
if(message==WM_RBUTTONUP)
|
||||
{
|
||||
POINT screen{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
if(rightClickMarks && !(wp&MK_SHIFT) && commandLineAvailable(GetParent(window)))
|
||||
{
|
||||
auto &panel=panels[index];
|
||||
const auto row=panelRowAt(window,screen,SendMessageW(window,LB_GETTOPINDEX,0,0),panel.rows.size());
|
||||
if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel))
|
||||
{
|
||||
closePanelSearch();
|
||||
SetFocus(window);
|
||||
activatePanel(index);
|
||||
panelClipboardContext=true;
|
||||
clearTerminalSelection();
|
||||
const auto previous=currentPanelRow(panel);
|
||||
SendMessageW(window,LB_SETCURSEL,row,0);
|
||||
markPanelRow(panel,row,!panel.marked[row]);
|
||||
invalidatePanelRow(window,row);
|
||||
if(previous!=row) invalidatePanelRow(window,previous);
|
||||
updateSelectionSummary(panel);
|
||||
showFileDetails(panel);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
ClientToScreen(window,&screen);
|
||||
showPanelContextMenu(window,MAKELPARAM(screen.x,screen.y));
|
||||
return 0;
|
||||
@@ -7882,6 +8159,9 @@ bool loadFilesPreferences(HWND window)
|
||||
alignExtensions=preference(L"AlignExtensions",defaultAlignExtensions)!=0;
|
||||
showDetails=preference(L"ShowDetails",defaultShowDetails)!=0;
|
||||
alignFolders=preference(L"AlignFolders",defaultAlignFolders)!=0;
|
||||
rightClickMarks=preference(rightClickMarksKey,0)!=0;
|
||||
showDriveButtons=preference(driveButtonsKey,0)!=0;
|
||||
compactLayout=preference(compactLayoutKey,0)!=0;
|
||||
statusFields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
loadCommandHistoryKeys();
|
||||
loadComparisonShortcut();
|
||||
@@ -7892,6 +8172,7 @@ bool loadFilesPreferences(HWND window)
|
||||
#include "files_options.inl"
|
||||
#include "files_panel_columns_dialog.inl"
|
||||
#include "files_space_analyzer.inl"
|
||||
#include "files_environment.inl"
|
||||
|
||||
void openMenu(HWND window, int index)
|
||||
{
|
||||
@@ -7945,7 +8226,8 @@ void openMenu(HWND window, int index)
|
||||
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
|
||||
L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(),
|
||||
L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q",
|
||||
L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…"};
|
||||
L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…",
|
||||
L"Git Changes…",L"Environment Variables…",L"Swap panels\tCtrl+U"};
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
const bool remoteResults=remoteSearchResults(panel);
|
||||
@@ -7971,7 +8253,10 @@ void openMenu(HWND window, int index)
|
||||
else if(index==2)
|
||||
{
|
||||
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
|
||||
if(!terminalVisible) commandActions.insert(commandActions.begin()+1,18);
|
||||
if(!terminalVisible) commandActions.push_back(15);
|
||||
if(gitChangesAvailable(panel)) commandActions.push_back(16);
|
||||
if(!terminalVisible) commandActions.push_back(17);
|
||||
if(!terminalVisible && canFindFiles(panels[active])) commandActions.insert(commandActions.begin()+1,9);
|
||||
if(!terminalVisible && !panels[active].peer && !panels[active].ftp)
|
||||
commandActions.insert(commandActions.begin()+2,12);
|
||||
@@ -8174,8 +8459,16 @@ bool commandLineAvailable(HWND owner)
|
||||
!IsWindowVisible(menuBar) && !IsWindowVisible(picker);
|
||||
}
|
||||
|
||||
#include "files_git_panel.inl"
|
||||
|
||||
void restoreCommandFocus()
|
||||
{
|
||||
if(gitChangesView)
|
||||
{
|
||||
const auto focus=GetFocus();
|
||||
if(focus==GetParent(terminalInput)) SetFocus(gitChangesView->list);
|
||||
return;
|
||||
}
|
||||
if(GetFocus()!=terminalInput && !GetCapture() && commandLineAvailable(GetParent(terminalInput)))
|
||||
SetFocus(terminalInput);
|
||||
}
|
||||
@@ -8196,6 +8489,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(message==filesPreferencesChanged)
|
||||
{
|
||||
if(quickViewWindow) SendNotifyMessageW(quickViewWindow,message,wp,lp);
|
||||
if(gitChangesView) SendNotifyMessageW(gitChangesView->preview,message,wp,lp);
|
||||
if(reinterpret_cast<HWND>(wp)!=window)
|
||||
{
|
||||
loadFilesPreferences(window);
|
||||
@@ -8338,6 +8632,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
|
||||
commands[i] = CreateWindowW(L"BUTTON", keyBar[i].label, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
|
||||
0, 0, 0, 0, window, reinterpret_cast<HMENU>(static_cast<INT_PTR>(keyBar[i].id)), instance, nullptr);
|
||||
for(int i=0;i<static_cast<int>(driveButtons.size());++i)
|
||||
{
|
||||
const wchar_t letter[]{static_cast<wchar_t>(L'A'+i),L':',0};
|
||||
driveButtons[i]=CreateWindowW(L"BUTTON",i==26?L"…":letter,WS_CHILD|BS_OWNERDRAW|WS_CLIPSIBLINGS,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(firstDriveButton+i)),instance,nullptr);
|
||||
if(!driveButtons[i]) return -1;
|
||||
}
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
auto &panel = panels[i];
|
||||
@@ -8381,6 +8682,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
return 0;
|
||||
}
|
||||
case WM_DEVICECHANGE:
|
||||
if(showDriveButtons)
|
||||
{
|
||||
layout(window);
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
}
|
||||
break;
|
||||
case WM_SIZE:
|
||||
hideCompletion();
|
||||
hidePicker();
|
||||
@@ -8461,7 +8769,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
GetWindowRect(status,&details);
|
||||
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&details),2);
|
||||
const RECT divider{box.left+1,box.bottom-2,box.right-1,box.bottom-1};
|
||||
box.bottom=std::max(box.bottom,details.bottom+6);
|
||||
box.bottom=std::max(box.bottom,details.bottom+(compactLayout?2:6));
|
||||
FrameRect(dc,&box,border);
|
||||
if(IsWindowVisible(panel.list)) paintScrollPosition(window,dc,panel.list,colors[PanelBlue]);
|
||||
InflateRect(&box,-3,-3);
|
||||
@@ -8633,6 +8941,21 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
GetWindowTextW(item.hwndItem,label,64);
|
||||
text=label;
|
||||
}
|
||||
if(item.CtlID>=firstDriveButton && item.CtlID<=moreDriveButton)
|
||||
{
|
||||
const auto &panel=panels[active];
|
||||
const auto drive=panel.directory.root_name().native();
|
||||
const bool selected=item.CtlID!=moreDriveButton && !panel.peer && !panel.ftp && !panel.archive &&
|
||||
drive.size()==2 && towupper(drive.front())==L'A'+item.CtlID-firstDriveButton;
|
||||
auto bounds=item.rcItem;
|
||||
FillRect(item.hDC,&bounds,selected?teal:blue);
|
||||
SelectObject(item.hDC,mono);
|
||||
SetBkMode(item.hDC,TRANSPARENT);
|
||||
SetTextColor(item.hDC,colors[selected?Text:Frame]);
|
||||
DrawTextW(item.hDC,text.c_str(),-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX);
|
||||
if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&bounds);
|
||||
return TRUE;
|
||||
}
|
||||
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
|
||||
{
|
||||
if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp)
|
||||
@@ -8922,6 +9245,18 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(HIWORD(wp)==BN_CLICKED && LOWORD(wp)>=firstDriveButton && LOWORD(wp)<=moreDriveButton)
|
||||
{
|
||||
const auto id=LOWORD(wp);
|
||||
if(id==moreDriveButton) chooseDrive(active);
|
||||
else
|
||||
{
|
||||
const wchar_t root[]{static_cast<wchar_t>(L'A'+id-firstDriveButton),L':',L'\\',0};
|
||||
openOn(panels[active],root,false,{});
|
||||
restoreCommandFocus();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive();
|
||||
if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED)
|
||||
{
|
||||
@@ -8944,6 +9279,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
return 0;
|
||||
case WM_CLOSE:
|
||||
if(!activeCopy && FilesModalDialog::dismissOwned(window)) return 0;
|
||||
if(gitChangesView && gitActionPending(*gitChangesView)) return 0;
|
||||
if(activeCopy)
|
||||
{
|
||||
if(FilesModalDialog::activeFor(window)!=activeCopy->window)
|
||||
@@ -8973,6 +9309,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
pendingPanelDrop.reset();
|
||||
closeGitChanges(window,false);
|
||||
for(auto &panel:panels)
|
||||
if(panel.folderSizeJob) panel.folderSizeJob->stop.request_stop();
|
||||
KillTimer(window,terminalTimer);
|
||||
@@ -9082,6 +9419,15 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST &&
|
||||
GetFocus()==terminalInput)
|
||||
message.hwnd=terminalInput;
|
||||
if(gitChangesView)
|
||||
{
|
||||
if(!handleGitChangesKey(window,message))
|
||||
{
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(handleQuickViewKey(window,message) || handlePanelPathKey(window,message)) continue;
|
||||
if((message.message==WM_KEYDOWN || message.message==WM_SYSKEYDOWN) &&
|
||||
!terminalVisible && commandLineAvailable(window) &&
|
||||
|
||||
+19
-2
@@ -11,7 +11,8 @@ constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Pop
|
||||
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};
|
||||
@@ -67,6 +68,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},
|
||||
@@ -107,6 +111,7 @@ struct OptionsBaseline
|
||||
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;
|
||||
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
|
||||
ks::files::TextSettings text=ks::files::loadTextPreferences();
|
||||
ComparisonAppearance comparison=readComparisonAppearance();
|
||||
@@ -181,6 +186,8 @@ 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 ||
|
||||
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 ||
|
||||
@@ -679,6 +686,9 @@ 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);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
@@ -898,7 +908,8 @@ 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 optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case 321: case 323: case comparisonShortcutControl:
|
||||
@@ -1050,6 +1061,9 @@ 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);
|
||||
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
const auto initialFields=fields;
|
||||
for(int i=0;i<4;++i)
|
||||
@@ -1092,6 +1106,9 @@ 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);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -804,6 +804,7 @@ public:
|
||||
bool handleKey(const MSG &message);
|
||||
void goToFragment(std::string_view fragment);
|
||||
void previewFile(const std::filesystem::path &path);
|
||||
void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff);
|
||||
bool openBookmark(const ViewerBookmark &bookmark);
|
||||
std::filesystem::path original;
|
||||
const std::string peerId;
|
||||
@@ -935,6 +936,8 @@ private:
|
||||
};
|
||||
std::future<QuickDocument> quickLoading;
|
||||
std::filesystem::path quickPath;
|
||||
std::wstring quickTextTitle;
|
||||
bool quickTextVisible{},quickTextDiff{};
|
||||
uint64_t quickRequest{}, quickReading{};
|
||||
ULONGLONG quickReadyAt{};
|
||||
std::wstring quickError;
|
||||
@@ -985,6 +988,7 @@ private:
|
||||
void updateLineNumberMargin();
|
||||
void applyLineEnding();
|
||||
void installLexer();
|
||||
void replaceEditorText(std::string_view data);
|
||||
void loadPage(uint64_t index,std::optional<std::string> cached={});
|
||||
void toggleHex();
|
||||
void locateBookmark(uint64_t line);
|
||||
@@ -1411,6 +1415,12 @@ void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
|
||||
const auto eol = data.find_first_of("\r\n");
|
||||
pageEol = eol == data.npos ? SC_EOL_CRLF : data[eol] == '\n' ? SC_EOL_LF :
|
||||
eol + 1 < data.size() && data[eol + 1] == '\n' ? SC_EOL_CRLF : SC_EOL_CR;
|
||||
replaceEditorText(data);
|
||||
cleanPage = std::move(data);
|
||||
}
|
||||
|
||||
void TextWindow::replaceEditorText(std::string_view data)
|
||||
{
|
||||
loading = true;
|
||||
send(SCI_SETREADONLY, FALSE);
|
||||
send(SCI_SETUNDOCOLLECTION, FALSE);
|
||||
@@ -1424,7 +1434,6 @@ void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
|
||||
send(SCI_GOTOPOS, 0);
|
||||
send(SCI_SETXOFFSET, 0);
|
||||
send(SCI_SETFIRSTVISIBLELINE, 0);
|
||||
cleanPage = std::move(data);
|
||||
loading = false;
|
||||
updateLineNumberMargin();
|
||||
undoBytes = 0;
|
||||
@@ -1616,7 +1625,9 @@ std::string readMarkdownDocument(TextDocument &document)
|
||||
|
||||
void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
{
|
||||
if(path==quickPath) return;
|
||||
if(quickTextTitle.empty() && path==quickPath) return;
|
||||
quickTextVisible=false;
|
||||
quickTextTitle.clear();
|
||||
quickPath=path;
|
||||
++quickRequest;
|
||||
quickReadyAt=GetTickCount64()+80;
|
||||
@@ -1628,6 +1639,34 @@ void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
SetTimer(window,quickViewTimer,30,nullptr);
|
||||
}
|
||||
|
||||
void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff)
|
||||
{
|
||||
if(!embedded) return;
|
||||
if(quickTextTitle.empty())
|
||||
{
|
||||
++quickRequest;
|
||||
KillTimer(window,quickViewTimer);
|
||||
quickLoading={};
|
||||
quickPath.clear();
|
||||
quickError.clear();
|
||||
stopPreview(false,true);
|
||||
document.reset();
|
||||
quickMarkdown.reset();
|
||||
}
|
||||
if(quickTextTitle.empty() || quickTextDiff!=diff)
|
||||
{
|
||||
language=automatic=diff?detectLanguage(L"preview.diff",contents):TextLanguage{};
|
||||
installLexer();
|
||||
}
|
||||
quickTextTitle=title;
|
||||
quickTextVisible=!contents.empty();
|
||||
quickTextDiff=diff;
|
||||
pageEol=SC_EOL_LF;
|
||||
replaceEditorText(contents);
|
||||
send(SCI_COLOURISE,0,-1);
|
||||
layout();
|
||||
}
|
||||
|
||||
void TextWindow::pollQuickView()
|
||||
{
|
||||
if(quickLoading.valid())
|
||||
@@ -2520,7 +2559,7 @@ void TextWindow::layout()
|
||||
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
|
||||
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
|
||||
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
|
||||
ShowWindow(editor,document && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
invalidate();
|
||||
}
|
||||
|
||||
@@ -2597,6 +2636,7 @@ void TextWindow::paint()
|
||||
else if(quickPath.empty()) label+=L" · Select a local text file";
|
||||
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
|
||||
else if(!previewVisible && pageTotal>1) label+=L" · First page";
|
||||
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);
|
||||
@@ -3259,6 +3299,12 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
preview->second->previewFile(path);
|
||||
}
|
||||
|
||||
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff)
|
||||
{
|
||||
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
|
||||
preview->second->previewEmbeddedText(title,contents,diff);
|
||||
}
|
||||
|
||||
ImageViewStyle imageViewStyle(TextDialogs dialogs)
|
||||
{
|
||||
const auto font=dialogs.readFont();
|
||||
|
||||
@@ -106,6 +106,7 @@ 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 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);
|
||||
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
|
||||
|
||||
@@ -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);
|
||||
|
||||
+23
-82
@@ -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},
|
||||
|
||||
@@ -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, ⌖
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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
@@ -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={});
|
||||
|
||||
|
||||
+43
-8
@@ -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"}});
|
||||
|
||||
+8
-22
@@ -1,5 +1,6 @@
|
||||
#include "update.h"
|
||||
#include "json.hpp"
|
||||
#include "windows_command_line.h"
|
||||
|
||||
namespace ks
|
||||
{
|
||||
@@ -10,21 +11,6 @@ struct Handle
|
||||
HANDLE value{};
|
||||
~Handle() { if (value) CloseHandle(value); }
|
||||
};
|
||||
std::wstring quoteArgument(const std::wstring &value)
|
||||
{
|
||||
// Windows argv escaping, including a path ending with a backslash.
|
||||
std::wstring out = L"\"";
|
||||
size_t slashes = 0;
|
||||
for (auto ch : value)
|
||||
{
|
||||
if (ch == L'\\') { ++slashes; continue; }
|
||||
out.append(ch == L'"' ? slashes * 2 + 1 : slashes, L'\\');
|
||||
slashes = 0;
|
||||
out += ch;
|
||||
}
|
||||
out.append(slashes * 2, L'\\');
|
||||
return out + L'"';
|
||||
}
|
||||
}
|
||||
UpdateResult runUpdate(bool install, const std::wstring &expectedVersion, bool showProgress)
|
||||
{
|
||||
@@ -50,16 +36,16 @@ UpdateResult runUpdate(bool install, const std::wstring &expectedVersion, bool s
|
||||
wchar_t system[MAX_PATH]{};
|
||||
if (!GetSystemDirectoryW(system, MAX_PATH)) throw std::runtime_error("Cannot locate Windows PowerShell");
|
||||
auto powershell = std::filesystem::path(system) / L"WindowsPowerShell/v1.0/powershell.exe";
|
||||
std::wstring command = quoteArgument(powershell.wstring()) + L" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File " +
|
||||
quoteArgument((work / L"update.ps1").wstring()) + L" -Mode " + (install ? L"Install" : L"Check") +
|
||||
L" -CurrentVersion " + quoteArgument(AppVersion) + L" -WorkDirectory " + quoteArgument(work.wstring()) +
|
||||
L" -InstallDirectory " + quoteArgument(std::filesystem::path(executable()).parent_path().wstring()) +
|
||||
L" -ParentProcessId " + std::to_wstring(GetCurrentProcessId()) + L" -ReadyEvent " + quoteArgument(readyName);
|
||||
std::wstring command = quoteWindowsArgument(powershell.wstring()) + L" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File " +
|
||||
quoteWindowsArgument((work / L"update.ps1").wstring()) + L" -Mode " + (install ? L"Install" : L"Check") +
|
||||
L" -CurrentVersion " + quoteWindowsArgument(AppVersion) + L" -WorkDirectory " + quoteWindowsArgument(work.wstring()) +
|
||||
L" -InstallDirectory " + quoteWindowsArgument(std::filesystem::path(executable()).parent_path().wstring()) +
|
||||
L" -ParentProcessId " + std::to_wstring(GetCurrentProcessId()) + L" -ReadyEvent " + quoteWindowsArgument(readyName);
|
||||
if (install)
|
||||
{
|
||||
command += L" -Journal " + quoteArgument((dataDirectory() / L"kswitcher.log").wstring());
|
||||
command += L" -Journal " + quoteWindowsArgument((dataDirectory() / L"kswitcher.log").wstring());
|
||||
if (expectedVersion.empty()) command += L" -Unattended";
|
||||
else command += L" -ExpectedVersion " + quoteArgument(expectedVersion);
|
||||
else command += L" -ExpectedVersion " + quoteWindowsArgument(expectedVersion);
|
||||
}
|
||||
if (showProgress) command += L" -ShowProgress";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline std::wstring quoteWindowsArgument(std::wstring_view value)
|
||||
{
|
||||
std::wstring quoted=L"\"";
|
||||
size_t slashes=0;
|
||||
for(const auto character:value)
|
||||
{
|
||||
if(character==L'\\') {++slashes;continue;}
|
||||
quoted.append(character==L'"'?slashes*2+1:slashes,L'\\');
|
||||
slashes=0;
|
||||
quoted+=character;
|
||||
}
|
||||
quoted.append(slashes*2,L'\\');
|
||||
return quoted+L'"';
|
||||
}
|
||||
}
|
||||
+297
-52
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user