Compare commits

..
Author SHA1 Message Date
agrynco 1217887e14 Add read-only Git Changes mode to Files
Refs #118
2026-11-25 20:27:10 +02:00
agrynco 10847244f0 Merge pull request 'KSwitcher.Files: Process panel and locking processes' (#172) from codex/issue-117-process-panel into prerelease
Refs #117
2026-11-25 20:11:25 +02:00
agrynco 82f1179970 Add a process panel and reuse lock searches
Refs #117
2026-11-25 20:11:14 +02:00
agrynco 92bee6bb67 Merge pull request 'KSwitcher.Files: Item properties and Windows attributes' (#171) from codex/issue-116-attributes into prerelease
Refs #116
2026-11-25 20:00:54 +02:00
agrynco e1f45a0098 Show and edit item properties in Files
Refs #116
2026-11-25 20:00:38 +02:00
agrynco bc44e0c1fc Merge pull request 'KSwitcher.Files: Windows Shell context menus' (#170) from codex/issue-115-shell-context into prerelease
Refs #115
2026-11-25 19:43:58 +02:00
agrynco 4992b783bc Add Windows Shell context menus to Files panels
Refs #115
2026-11-25 19:43:40 +02:00
agrynco fe1b114b38 Merge pull request 'KSwitcher.Files: Find files in remote sources' (#169) from codex/issue-114-remote-find into prerelease
Refs #114
2026-11-25 19:30:45 +02:00
agrynco 936c199a43 Search FTP, SFTP and LAN panels while retaining partial results
Refs #114
2026-11-25 19:30:31 +02:00
agrynco d12273da67 Merge pull request 'KSwitcher.Files: Temporary sudo access for SFTP Viewer and Editor' (#168) from codex/issue-113-sftp-sudo into prerelease
Refs #113
2026-11-25 19:11:42 +02:00
agrynco 1a81075763 Add single-operation sudo authorization for SFTP Viewer and Editor
Refs #113
2026-11-25 19:11:30 +02:00
agrynco d5996237c6 Merge pull request 'KSwitcher.Files: SSH terminal and saved jump routes' (#167) from codex/issue-112-files into prerelease
Refs #112
2026-11-25 18:54:01 +02:00
agrynco 4ef30ab5e8 Add routed SSH connections and the Files SSH terminal
Refs #112
2026-11-25 18:53:52 +02:00
agrynco 6279a2ee4f Merge pull request 'KSwitcher.Files: Interactive PowerShell terminal prompt' (#166) from codex/issue-111-terminal-input into prerelease
Refs #111
2026-11-25 18:31:45 +02:00
38 changed files with 3160 additions and 396 deletions

No files matched your search

+1 -1
View File
@@ -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"
+74 -14
View File
@@ -77,6 +77,32 @@ Warning і початковий фокус на No.
Files блокує підключення до передачі пароля або підпису.
Для запланованої заміни ключа використовуй **Forget host key**,
а тоді **Test connection** зі звіркою нового відбитка.
- **Jump via** у SFTP-профілі вибирає попередній збережений SSH-профіль
у маршруті. **Direct** підключається напряму. Профіль-посередник може
мати власний **Jump via**. Кожен хост має окремий довірений ключ і
перевіряється до входу. Маршрут підтримує до восьми хостів і перевіряється
на цикли під час збереження. Профіль без доступу до SFTP можна
використовувати для пересилання через SSH.
- На підключеній SFTP-панелі Ctrl+O відкриває інтерактивну SSH-сесію.
Enter після введення команди запускає ту саму сесію з командного рядка.
Після `cd` успішно відкритий каталог відображається в панелі.
Зміна каталогу в панелі також оновлює робочу папку сесії.
Поки команда працює, термінал приймає її інтерактивне введення, зокрема
Ctrl+C. При переході до іншої панелі чи джерела сесія від'єднується.
Для синхронізації потрібні POSIX-оболонка й утиліта `base64` на сервері.
Оболонка та SFTP мають бачити однакові абсолютні шляхи.
- **SFTP server for sudo** у профілі приймає абсолютний шлях до
серверного OpenSSH `sftp-server`. Після відмови в доступі Viewer і
Hex Viewer пропонують один повтор через `sudo` в режимі тільки читання.
F2 в Editor після відмови в доступі до запису показує окремий запит.
Відмова або Esc під час привілейованого запису залишає чернетку в Editor,
якщо заміна файла ще не завершилась. Успішна заміна зберігає POSIX-власника,
групу та біти режиму доступу.
- Серверний адміністратор має окремо дозволити потрібний варіант команди
`sudo -n` для цього облікового запису. Перегляд використовує
`sftp-server -R`, а збереження використовує `sftp-server` без цього
прапорця. Files закриває привілейоване з'єднання після операції, розриву
або тайм-ауту мережевого запиту. Пароль sudo не запитується.
- Для SFTP використовуються ключі хоста ECDSA або RSA з підписом SHA‑2.
F3 і F4 відкривають Viewer та Editor. F2 в Editor перевіряє розмір і час
зміни віддаленого файла перед збереженням. F5 копіює між локальною
@@ -226,6 +252,20 @@ Warning і початковий фокус на No.
останніх команд з історії, які починаються з набраного тексту.
Вибір підставляє всю команду. Підказки з історії доступні й у LAN-панелі.
- Правий клік по локальному файлу чи папці відкриває системне контекстне
меню Windows Shell. Правий клік по вільній області відкриває меню
поточної папки. Клавіша Context Menu або Shift+F10 використовує поточний
рядок. Команда з меню оновлює панель і зберігає папку, курсор та
актуальні позначки. Для LAN, FTP, SFTP, UNC та архівів контекстне меню
показує доступні команди Files.
- **Ctrl+A** або **F9 → Files → Properties** показує властивості поточного
файла чи папки. У локальній панелі можна змінити прапорці **Read-only**,
**Hidden**, **System**, **Archive** та **Not indexed**. **Save** застосовує
лише змінені прапорці й перечитує панель. Помилка Windows з’являється
окремим повідомленням. Прапорці папки застосовуються лише до самої папки.
У LAN, FTP, SFTP, UNC та архіві команда **Properties** також є в
контекстному меню й показує доступні метадані без редагування.
Для SFTP власник відображається як числовий UID, якщо сервер його надає.
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
що й клавіша F8.
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
@@ -519,18 +559,24 @@ Warning і початковий фокус на No.
## Панелі
- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук
файлів у поточній локальній папці та її підпапках. Поле приймає повне
ім’я або маску без урахування регістру. `*` відповідає довільній
файлів у поточній папці та її підпапках. Підтримуються локальні папки,
FTP, SFTP і KSwitcher LAN. Поле приймає повне ім’я або маску без
урахування регістру. `*` відповідає довільній
послідовності символів, `?` — одному символу. Приховані та системні
елементи можна включити прапорцем. Пошук не обходить junction та інші
посилання на каталоги. Esc під час пошуку зупиняє обхід і показує знайдене.
Результати відкриваються в тій самій панелі з відносними шляхами.
елементи можна включити прапорцем. У FTP і SFTP це також стосується
імен із крапкою на початку. Пошук не обходить junction та інші посилання
на каталоги, які джерело позначає як посилання. Esc зупиняє обхід.
При скасуванні або втраті з’єднання знайдені файли залишаються в панелі.
Заголовок віддалених результатів показує джерело і початкову папку,
а рядки показують відносний шлях до кожного файла.
Enter або подвійний клік відкриває папку й ставить курсор на файл.
Esc у результатах повертає вихідну папку, курсор і позначки.
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
або поточним файлом, використовуючи папку іншої панелі як призначення.
F8 і Shift+Delete використовують звичайні підтвердження. Успішно
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
або поточним файлом. F5 використовує папку іншої панелі як призначення.
У FTP і SFTP F6 перейменовує один результат у його власній папці.
Меню Files і нижній рядок клавіш враховують джерело, виділення та
можливість копіювання в іншу панель. F8 і Shift+Delete використовують звичайні підтвердження.
Успішно перейменовані, переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
з тією самою маскою й видимістю прихованих файлів.
- **Left/Right → Tree view** або Ctrl+F10 перемикає вигляд відповідної
@@ -700,12 +746,26 @@ Warning і початковий фокус на No.
діалог можна скасувати. Помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
- Помилки копіювання, переміщення й видалення показуються в червоному
модальному діалозі Far із причиною помилки та кнопкою OK.
- Якщо локальне перейменування або видалення заблоковане, кнопка Processes… відкриває
список процесів із назвою та PID. Перевірка папки включає вкладені елементи.
End process завершує вибраний процес після окремого підтвердження, після
чого список оновлюється. Якщо Windows обмежила доступ або перевірку
великої папки завершено частково, про це повідомляється в діалозі.
Операцію можна повторити після звільнення файла чи папки.
- **F9 → Commands → Processes** показує локальні процеси, PID, частку
загальної потужності CPU, робочий набір пам’яті та шлях виконуваного файла.
**Filter** шукає за іменем, шляхом або PID. **Sort** змінює порядок,
**Refresh** робить новий вимір. **Go to file** вибирає виконуваний файл
в активній панелі. **End process** завершує процес лише після підтвердження.
- **F9 → Files → Locking processes** перевіряє поточний локальний елемент або
позначені елементи. Кнопка **Processes…** у повідомленні про заблоковане
перейменування або видалення відкриває той самий список із фільтром за
вихідним шляхом. Для папки перевіряються також її вкладені елементи.
**Go to file** у цьому режимі відкриває виконуваний файл у другій панелі
зі збереженням вихідного файла в першій. Після завершення процесу список
перечитується. Якщо 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 без змін.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
+22
View File
@@ -0,0 +1,22 @@
# Apply the exec-channel variant of SFTP initialization to the pinned library.
file(REAL_PATH ".." source_parent)
set(patch_file "${CMAKE_CURRENT_BINARY_DIR}/.kswitcher-sftp-command.patch")
configure_file("${PATCH}" "${patch_file}" @ONLY NEWLINE_STYLE LF)
set(patch_git "${CMAKE_COMMAND}" -E env "GIT_CEILING_DIRECTORIES=${source_parent}" "${GIT}")
execute_process(COMMAND ${patch_git} apply --unidiff-zero --check "${patch_file}"
RESULT_VARIABLE can_apply ERROR_QUIET)
if(can_apply EQUAL 0)
execute_process(COMMAND ${patch_git} apply --unidiff-zero "${patch_file}" COMMAND_ERROR_IS_FATAL ANY)
else()
execute_process(COMMAND ${patch_git} apply --unidiff-zero --reverse --check "${patch_file}"
RESULT_VARIABLE already_applied)
if(NOT already_applied EQUAL 0)
message(FATAL_ERROR "Could not apply the SFTP command patch")
endif()
endif()
file(REMOVE "${patch_file}")
file(STRINGS "include/libssh2_sftp.h" exec_api REGEX "^libssh2_sftp_init_command")
if(NOT exec_api)
message(FATAL_ERROR "The SFTP command API is missing after applying the patch")
endif()
+7 -1
View File
@@ -1,10 +1,16 @@
include(FetchContent)
find_package(Git REQUIRED)
set(kswitcher_ssh_patch "${CMAKE_CURRENT_LIST_DIR}/libssh2-sftp-command.patch")
file(SHA256 "${kswitcher_ssh_patch}" kswitcher_ssh_patch_hash)
# This revision includes the published SFTP security fixes after the 1.11.1 release.
FetchContent_Declare(kswitcher_libssh2
URL https://codeload.github.com/libssh2/libssh2/tar.gz/dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4
URL_HASH SHA256=67d20d434055faef76439c6829ab253c892fcdd68d9a9c86cf5824bd8366e6eb
DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
PATCH_COMMAND "${CMAKE_COMMAND}" "-DGIT=${GIT_EXECUTABLE}"
"-DPATCH=${kswitcher_ssh_patch}" "-DPATCH_HASH=${kswitcher_ssh_patch_hash}"
-P "${CMAKE_CURRENT_LIST_DIR}/ApplyFilesSshPatch.cmake")
function(kswitcher_add_ssh_library)
set(BUILD_STATIC_LIBS ON)
+35
View File
@@ -0,0 +1,35 @@
diff --git a/include/libssh2_sftp.h b/include/libssh2_sftp.h
--- a/include/libssh2_sftp.h
+++ b/include/libssh2_sftp.h
@@ -226,0 +227,2 @@
+LIBSSH2_API LIBSSH2_SFTP *
+libssh2_sftp_init_command(LIBSSH2_SESSION *session, const char *command);
diff --git a/src/sftp.c b/src/sftp.c
--- a/src/sftp.c
+++ b/src/sftp.c
@@ -758 +758,2 @@
-static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session)
+static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session,
+ const char *command)
@@ -811,3 +812,5 @@
- "subsystem",
- sizeof("subsystem") - 1,
- "sftp", sizeof("sftp") - 1);
+ command ? "exec" : "subsystem",
+ command ? 4 : 9,
+ command ? command : "sftp",
+ command ?
+ strlen(command) : 4);
@@ -1011 +1014,2 @@
-LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
+LIBSSH2_SFTP *libssh2_sftp_init_command(LIBSSH2_SESSION *session,
+ const char *command)
@@ -1024 +1028 @@
- BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session));
+ BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session, command));
@@ -1025,0 +1030,5 @@
+}
+
+LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
+{
+ return libssh2_sftp_init_command(session, NULL);
+45 -10
View File
@@ -124,16 +124,25 @@ BEGIN
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 275, 140, 58, 16
END
609 DIALOGEX 0, 0, 350, 135
609 DIALOGEX 0, 0, 430, 204
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 430, 14, 17, 322, 20
LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
CONTROL "", 432, "Static", NOT WS_VISIBLE, 14, 108, 1, 1
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 56, 110, 80, 16
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 140, 110, 74, 16
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 218, 110, 65, 16
LTEXT "", 430, 16, 15, 398, 13, SS_PATHELLIPSIS | SS_NOPREFIX
LTEXT "&Filter", 440, 16, 33, 38, 13
FAR_EDIT(435, 0, 58, 32, 212, 15)
LTEXT "&Sort", 441, 277, 33, 34, 13
COMBOBOX 436, 312, 32, 102, 92, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
LTEXT "", 439, 17, 51, 397, 13, SS_NOPREFIX
LISTBOX 431, 16, 65, 398, 70, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "E&xecutable", 442, 16, 144, 71, 13
FAR_EDIT(438, ES_READONLY, 89, 143, 325, 15)
LTEXT "", 443, 16, 162, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 432, "Static", NOT WS_VISIBLE, 16, 179, 1, 1
CONTROL "&Go to file", 437, "Button", BS_OWNERDRAW | WS_TABSTOP, 35, 185, 90, 16
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 130, 185, 90, 16
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 225, 185, 78, 16
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 308, 185, 72, 16
END
608 DIALOGEX 0, 0, 220, 67
@@ -575,12 +584,38 @@ BEGIN
FAR_EDIT(388, 0, 16, 96, 182, 15)
LTEXT "&Password or key passphrase", 389, 210, 83, 194, 12
EDITTEXT 390, 210, 96, 194, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
LTEXT "Private &key file (optional)", 562, 16, 117, 388, 12
FAR_EDIT(563, 0, 16, 130, 388, 15)
LTEXT "", 566, 16, 153, 388, 14, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "Private &key file (optional)", 562, 16, 117, 182, 12
FAR_EDIT(563, 0, 16, 130, 182, 15)
LTEXT "SFTP ser&ver for sudo (optional)", 569, 210, 117, 194, 12
FAR_EDIT(570, 0, 210, 130, 194, 15)
LTEXT "", 566, 16, 153, 218, 14, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "&Jump via", 568, 240, 153, 56, 14
COMBOBOX 567, 298, 150, 106, 90, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "", 391, 10, 175, 1, 1, NOT WS_VISIBLE
CONTROL "&Test connection", 564, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 183, 128, 17
CONTROL "&Forget host key", 565, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 183, 112, 17
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 270, 183, 60, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 336, 183, 67, 17
END
125 DIALOGEX 0, 0, 360, 178
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Properties"
FONT 10, "Consolas"
BEGIN
LTEXT "", 580, 16, 15, 328, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 581, 16, 32, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 582, 16, 45, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 583, 16, 58, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 584, 16, 71, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 585, 16, 84, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 586, 16, 99, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
AUTOCHECKBOX "&Read-only", 587, 16, 114, 106, 13
AUTOCHECKBOX "&Hidden", 588, 128, 114, 106, 13
AUTOCHECKBOX "S&ystem", 589, 240, 114, 104, 13
AUTOCHECKBOX "&Archive", 590, 16, 128, 106, 13
AUTOCHECKBOX "Not &indexed", 591, 128, 128, 106, 13
LTEXT "", 592, 10, 146, 1, 1, NOT WS_VISIBLE
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
+33 -2
View File
@@ -9,6 +9,10 @@ const terminal = new Terminal({
const fit = new FitAddon.FitAddon();
terminal.parser.registerOscHandler(633, data => {
const prefix = 'ks-directory:';
if (data.startsWith('ks-ssh-dir:')) {
bridge.postMessage('ssh-directory:' + data.slice(11));
return true;
}
if (!data.startsWith(prefix)) return false;
try {
bridge.postMessage('directory:' + decodeURIComponent(data.slice(prefix.length)));
@@ -22,9 +26,13 @@ const host = document.getElementById('terminal');
terminal.open(host);
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
const prompt = message => bridge.postMessage('prompt:' + message);
host.addEventListener('pointerup', () => prompt('focus-input'), true);
let sshInput = false;
host.addEventListener('pointerup', () => {
if (!sshInput) prompt('focus-input');
}, true);
terminal.onData(text => {
if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
if (sshInput) bridge.postMessage('ssh-input:' + text);
else if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
});
const screen = host.querySelector('.xterm-screen');
let traceEnabled = false;
@@ -61,6 +69,14 @@ const promptKeys = new Set([
]);
terminal.attachCustomKeyEventHandler(event => {
if (event.isComposing) return true;
if (sshInput) {
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.metaKey) return true;
const copy = event.code === 'KeyC' && terminal.hasSelection();
if (!copy && (event.shiftKey || event.code !== 'KeyO')) return true;
event.preventDefault();
if (!event.repeat) bridge.postMessage(copy ? 'copy-command-line' : 'toggle');
return false;
}
if (event.type === 'keydown' && promptKeys.has(event.key) &&
!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {
prompt(event.key);
@@ -99,6 +115,21 @@ terminal.onScroll(() => {
anchorOutput();
});
bridge.addEventListener('message', ({ data }) => {
if (data === 'ssh-input:on' || data === 'ssh-input:off') {
sshInput = data === 'ssh-input:on';
terminal.options.cursorBlink = sshInput;
terminal.write(sshInput ? '\x1b[?25h' : '\x1b[?25l');
return;
}
if (data === 'ssh-focus') {
terminal.focus();
return;
}
if (data === 'ssh-reset') {
terminal.reset();
terminal.write('\x1b[?25l');
return;
}
if (data === 'clear-selection') {
terminal.clearSelection();
return;
+17 -7
View File
@@ -37,6 +37,13 @@ constexpr std::int64_t archiveEpochOffset=11644473600, archiveTicksPerSecond=100
constexpr char unsafePath[]="The archive contains an unsafe or conflicting path.";
constexpr char encryptedArchive[]="This archive requires a password. Password-protected entries cannot be opened in Files.";
uint64_t archiveTime(bool present,int64_t seconds,long nanos)
{
if(!present || seconds < -archiveEpochOffset || seconds>=INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)
return 0;
return static_cast<uint64_t>((seconds+archiveEpochOffset)*archiveTicksPerSecond+nanos/100);
}
struct ArchiveFileHandle
{
HANDLE value=INVALID_HANDLE_VALUE;
@@ -100,11 +107,15 @@ std::pair<fs::path,ArchiveEntry> decodeEntry(archive_entry *entry)
const auto size=archive_entry_size(entry);
if(size<0 || (!folder && !archive_entry_size_is_set(entry)))
throw std::runtime_error("The archive entry has an invalid size.");
const int64_t seconds=archive_entry_mtime(entry);
const auto modified=archive_entry_mtime_is_set(entry) && seconds>=-archiveEpochOffset &&
seconds<(INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)?
static_cast<uint64_t>((seconds+archiveEpochOffset)*archiveTicksPerSecond+archive_entry_mtime_nsec(entry)/100):0;
return {relative,{static_cast<uint64_t>(size),modified,folder,archive_entry_is_encrypted(entry)!=0}};
ArchiveEntry metadata{
static_cast<uint64_t>(size),
archiveTime(archive_entry_mtime_is_set(entry),archive_entry_mtime(entry),archive_entry_mtime_nsec(entry)),
folder,archive_entry_is_encrypted(entry)!=0};
metadata.created=archiveTime(archive_entry_birthtime_is_set(entry),archive_entry_birthtime(entry),
archive_entry_birthtime_nsec(entry));
metadata.accessed=archiveTime(archive_entry_atime_is_set(entry),archive_entry_atime(entry),archive_entry_atime_nsec(entry));
if(const auto *owner=archive_entry_uname_w(entry)) metadata.owner=owner;
return {relative,std::move(metadata)};
}
void registerEntry(ArchiveEntries &entries,const fs::path &path,const ArchiveEntry &entry)
@@ -240,8 +251,7 @@ uint64_t archiveFileSize(const BY_HANDLE_FILE_INFORMATION &info)
bool sameArchiveFile(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
{
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
left.nFileIndexLow==right.nFileIndexLow && archiveFileSize(left)==archiveFileSize(right) &&
return sameFileIdentity(left,right) && archiveFileSize(left)==archiveFileSize(right) &&
CompareFileTime(&left.ftLastWriteTime,&right.ftLastWriteTime)==0;
}
+3
View File
@@ -5,6 +5,7 @@
#include <functional>
#include <map>
#include <stop_token>
#include <string>
#include <vector>
namespace ks::files
@@ -18,6 +19,8 @@ struct ArchiveEntry
{
uint64_t size{}, modified{};
bool directory{}, encrypted{}, implicit{};
uint64_t created{}, accessed{};
std::wstring owner{};
};
using ArchiveEntries=std::map<std::filesystem::path,ArchiveEntry,ArchiveNameOrder>;
+11 -9
View File
@@ -1242,13 +1242,11 @@ INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPA
return paintTextDialog(dialog,message,wp,lp,L" Compare files ");
}
void compareSelectedFiles(HWND owner)
bool selectedComparisonFiles(CompareFile (&files)[2])
{
auto &current=panels[active],&other=panels[1-active];
const auto selected=selectedPanelPaths(current);
const auto opposite=selectedPanelPaths(other);
auto state=std::make_unique<FileComparison>();
auto &comparison=*state;
const auto pick=[](const Panel &panel,const fs::path &path,CompareFile &file)
{
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
@@ -1261,13 +1259,17 @@ void compareSelectedFiles(HWND owner)
file={path,label,panel.peer,panel.ftp};
return true;
};
bool valid=false;
if(selected.size()==2)
valid=pick(current,selected[0],comparison.files[0]) && pick(current,selected[1],comparison.files[1]);
else if(selected.size()==1 && opposite.size()==1)
valid=pick(current,selected.front(),comparison.files[active]) &&
pick(other,opposite.front(),comparison.files[1-active]);
if(!valid)
return pick(current,selected[0],files[0]) && pick(current,selected[1],files[1]);
return selected.size()==1 && opposite.size()==1 && pick(current,selected.front(),files[active]) &&
pick(other,opposite.front(),files[1-active]);
}
void compareSelectedFiles(HWND owner)
{
auto state=std::make_unique<FileComparison>();
auto &comparison=*state;
if(!selectedComparisonFiles(comparison.files))
{
showFilesNotice(owner,L"Mark two text files in the active panel or select one text file in each panel.",
L"Compare files");
+189
View File
@@ -0,0 +1,189 @@
struct ContextPopup
{
HMENU handle=CreatePopupMenu();
~ContextPopup(){if(handle) DestroyMenu(handle);}
};
struct ShellMenuMessages
{
Microsoft::WRL::ComPtr<IContextMenu2> second;
Microsoft::WRL::ComPtr<IContextMenu3> third;
};
LRESULT CALLBACK shellMenuMessage(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR data)
{
if(message==WM_INITMENUPOPUP || message==WM_MENUCHAR ||
((message==WM_DRAWITEM || message==WM_MEASUREITEM) && !wp))
{
const auto &menu=*reinterpret_cast<const ShellMenuMessages*>(data);
LRESULT result{};
if(menu.third && menu.third->HandleMenuMsg2(message,wp,lp,&result)==S_OK) return result;
if(menu.second && message!=WM_MENUCHAR && menu.second->HandleMenuMsg(message,wp,lp)==S_OK)
return message==WM_DRAWITEM || message==WM_MEASUREITEM;
}
return DefSubclassProc(window,message,wp,lp);
}
enum class ShellPanelMenuResult { unavailable, canceled, invoked, rename, failed };
ShellPanelMenuResult showShellPanelMenu(HWND owner,const fs::path &directory,const fs::path &item,POINT screen)
{
const auto &path=item.empty()?directory:item;
PIDLIST_ABSOLUTE raw{};
if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&raw,0,nullptr)) || !raw) return ShellPanelMenuResult::unavailable;
const std::unique_ptr<ITEMIDLIST,decltype(&CoTaskMemFree)> id(raw,CoTaskMemFree);
Microsoft::WRL::ComPtr<IShellFolder> folder;
Microsoft::WRL::ComPtr<IContextMenu> menu;
if(item.empty())
{
Microsoft::WRL::ComPtr<IShellFolder> desktop;
if(FAILED(SHGetDesktopFolder(desktop.GetAddressOf())) ||
FAILED(desktop->BindToObject(id.get(),nullptr,IID_PPV_ARGS(folder.GetAddressOf()))) ||
FAILED(folder->CreateViewObject(owner,IID_PPV_ARGS(menu.GetAddressOf()))))
return ShellPanelMenuResult::unavailable;
}
else
{
PCUITEMID_CHILD child{};
if(FAILED(SHBindToParent(id.get(),IID_PPV_ARGS(folder.GetAddressOf()),&child)) ||
FAILED(folder->GetUIObjectOf(owner,1,&child,IID_IContextMenu,nullptr,
reinterpret_cast<void**>(menu.GetAddressOf()))))
return ShellPanelMenuResult::unavailable;
}
ContextPopup popup;
const auto flags=item.empty()?CMF_NORMAL:CMF_NORMAL|CMF_CANRENAME;
constexpr UINT firstCommand=1,lastCommand=0x7fff;
if(!menu || !popup.handle || FAILED(menu->QueryContextMenu(popup.handle,0,firstCommand,lastCommand,flags)) ||
GetMenuItemCount(popup.handle)<=0) return ShellPanelMenuResult::unavailable;
ShellMenuMessages handler;
if(FAILED(menu.As(&handler.third))) menu.As(&handler.second);
constexpr UINT_PTR subclass=27;
if((handler.third || handler.second) &&
!SetWindowSubclass(owner,shellMenuMessage,subclass,reinterpret_cast<DWORD_PTR>(&handler)))
return ShellPanelMenuResult::unavailable;
const auto choice=static_cast<UINT>(TrackPopupMenuEx(popup.handle,TPM_RETURNCMD|TPM_RIGHTBUTTON,
screen.x,screen.y,owner,nullptr));
RemoveWindowSubclass(owner,shellMenuMessage,subclass);
if(choice<firstCommand || choice>lastCommand) return ShellPanelMenuResult::canceled;
const auto verb=choice-firstCommand;
wchar_t name[64]{};
if(SUCCEEDED(menu->GetCommandString(verb,GCS_VERBW,nullptr,reinterpret_cast<LPSTR>(name),std::size(name))))
{
if(!item.empty() && lstrcmpiW(name,L"rename")==0) return ShellPanelMenuResult::rename;
if(item.empty() && lstrcmpiW(name,L"refresh")==0) return ShellPanelMenuResult::invoked;
}
CMINVOKECOMMANDINFOEX request{sizeof(request)};
request.fMask=CMIC_MASK_UNICODE|CMIC_MASK_NOASYNC|CMIC_MASK_PTINVOKE;
request.hwnd=owner;
request.lpVerb=MAKEINTRESOURCEA(verb);
request.lpVerbW=MAKEINTRESOURCEW(verb);
const auto working=item.empty()?directory:item.parent_path();
request.lpDirectoryW=working.c_str();
request.nShow=SW_SHOWNORMAL;
request.ptInvoke=screen;
const auto result=menu->InvokeCommand(reinterpret_cast<LPCMINVOKECOMMANDINFO>(&request));
if(result==E_ABORT || result==HRESULT_FROM_WIN32(ERROR_CANCELLED)) return ShellPanelMenuResult::canceled;
return SUCCEEDED(result)?ShellPanelMenuResult::invoked:ShellPanelMenuResult::failed;
}
void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
{
const auto owner=GetParent(panel.list);
ContextPopup popup;
if(!popup.handle) return;
constexpr UINT openItem=1,findItems=2,newProfile=3,properties=4;
const auto add=[&](UINT id,const wchar_t *label){AppendMenuW(popup.handle,MF_STRING,id,label);};
if(transferProfileList(panel))
{
if(row!=LB_ERR)
{
add(openItem,L"Connect");
add(112,L"Edit connection");
}
add(newProfile,L"New connection");
}
else
{
if(row!=LB_ERR)
{
const bool folder=panel.sizes[row]==L"Folder";
if(folder || panel.findOrigin) add(openItem,folder?L"Open folder":L"Go to file");
if(!folder && remoteSearchActionAvailable(111)) add(111,L"View");
if(!folder && !panel.archive && remoteSearchActionAvailable(112)) add(112,L"Edit");
const auto &other=panels[1-active];
const bool localDestination=!other.peer && !other.ftp && !other.archive && !other.findOrigin;
const bool canCopy=panel.ftp || panel.archive?localDestination:!other.ftp && !other.archive && !other.findOrigin;
if(canCopy && !other.directory.empty() && remoteSearchActionAvailable(113))
add(113,panel.archive?L"Extract":L"Copy");
if(!panel.archive && (panel.ftp || canCopy) && remoteSearchActionAvailable(114))
add(114,panel.ftp?L"Rename":L"Move");
if(!panel.archive && remoteSearchActionAvailable(117)) add(117,L"Delete");
if(panelItemPropertiesAvailable(panel)) add(properties,L"Properties");
}
else if(!panel.findOrigin && !panel.archive && !panel.directory.empty()) add(115,L"Make folder");
if(!panel.archive && !panel.directory.empty()) add(findItems,L"Find files");
add(110,L"Refresh panel");
}
const auto command=static_cast<UINT>(TrackPopupMenuEx(popup.handle,TPM_RETURNCMD|TPM_RIGHTBUTTON,
screen.x,screen.y,owner,nullptr));
if(command==openItem) enter(panel);
else if(command==findItems) findPanelFiles(owner,panel);
else if(command==newProfile) editTransferProfile(panel,true);
else if(command==properties) showPanelItemProperties(owner,panel);
else if(command) SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0);
}
void showPanelContextMenu(HWND list,LPARAM position)
{
const auto index=GetDlgCtrlID(list)-102;
if(index<0 || index>=static_cast<int>(std::size(panels)) || terminalVisible || !IsWindowVisible(list)) return;
const auto owner=GetParent(list);
if(!commandLineAvailable(owner)) return;
auto &panel=panels[index];
RECT bounds{};
GetClientRect(list,&bounds);
POINT client{};
LRESULT hit=LB_ERR;
if(position==-1)
{
hit=currentPanelRow(panel);
RECT rowBounds{};
if(hit!=LB_ERR && SendMessageW(list,LB_GETITEMRECT,hit,reinterpret_cast<LPARAM>(&rowBounds))!=LB_ERR)
client.y=std::clamp(rowBounds.bottom,0L,std::max(0L,bounds.bottom-1));
client.x=std::min(2L*cellWidth,std::max(0L,bounds.right-1));
}
else
{
client={GET_X_LPARAM(position),GET_Y_LPARAM(position)};
ScreenToClient(list,&client);
if(!PtInRect(&bounds,client)) return;
hit=panelRowAt(list,client,SendMessageW(list,LB_GETTOPINDEX,0,0),panel.rows.size());
if(hit!=LB_ERR)
{
const auto previous=currentPanelRow(panel);
SendMessageW(list,LB_SETCURSEL,hit,0);
invalidatePanelCursorChange(list,previous);
}
}
activatePanel(index);
closePanelSearch();
panelClipboardContext=true;
clearTerminalSelection();
SetFocus(list);
POINT screen=client;
ClientToScreen(list,&screen);
const auto row=hit!=LB_ERR && panel.sizes[hit]!=L"Up"?hit:LB_ERR;
const auto directory=panel.directory;
const auto item=row==LB_ERR?fs::path{}:panel.rows[row];
const bool shell=!panel.peer && !panel.ftp && !panel.archive && !directory.empty() &&
!windowsNetworkPath(directory);
const auto result=shell?showShellPanelMenu(owner,directory,item,screen):ShellPanelMenuResult::unavailable;
if(result==ShellPanelMenuResult::unavailable) showFilesPanelContext(panel,row,screen);
else if(result==ShellPanelMenuResult::rename)
copySelection(owner,panel,panel,true,{item},item.parent_path(),true);
else if(result==ShellPanelMenuResult::invoked && IsWindow(owner) && panel.directory==directory &&
!panel.peer && !panel.ftp && !panel.archive) refreshPanel(panel);
else if(result==ShellPanelMenuResult::failed) setStatus(L"Windows could not complete the Shell command.");
if(IsWindow(owner)) restoreCommandFocus();
}
+10 -4
View File
@@ -76,15 +76,21 @@ void startFileSearch(Panel &panel,Panel::FindOptions options)
if(panel.scanRequest) return;
cancelFolderSizes(panel);
panel.remoteRetry.reset();
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.peer=panel.peer,.statusRevision=statusRevision,
.ftp=panel.ftp,.find=std::move(options)};
startDirectoryScan(panel);
}
void findLocalFiles(HWND owner,Panel &panel)
bool canFindFiles(const Panel &panel)
{
if(panel.peer || panel.ftp || panel.archive || panel.directory.empty())
return !panel.archive && !panel.directory.empty() && !transferProfileList(panel);
}
void findPanelFiles(HWND owner,Panel &panel)
{
if(!canFindFiles(panel))
{
setStatus(L"Find files requires a local folder.");
setStatus(L"Find files requires an open folder.");
return;
}
if(panel.scanRequest)
+64 -26
View File
@@ -29,45 +29,83 @@ std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &req
std::atomic_size_t &entriesRead,std::stop_token stop)
{
auto result=std::make_unique<Panel::ScanResult>();
FilesConnection local(nullptr);
std::vector<fs::path> pending{request.directory};
size_t visited=0;
while(!pending.empty() && !stop.stop_requested())
const bool remote=request.peer || request.ftp;
const auto walk=[&](const auto &listDirectory)
{
const auto directory=std::move(pending.back());
pending.pop_back();
try
std::vector<fs::path> pending{request.directory};
size_t visited=0;
while(!pending.empty() && !stop.stop_requested())
{
listFiles(local,directory,[&](const fs::path &path,const FileInfo &entry)
const auto directory=std::move(pending.back());
pending.pop_back();
try
{
if(stop.stop_requested()) return false;
entriesRead.store(++visited,std::memory_order_relaxed);
if(!request.find->includeHidden && (entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)))
if(!listDirectory(directory,[&](const fs::path &path,const FileInfo &entry)
{
if(stop.stop_requested()) return false;
if(path.parent_path()!=folderPathWithoutSeparator(directory)) return true;
entriesRead.store(++visited,std::memory_order_relaxed);
const auto name=path.filename().native();
if(!request.find->includeHidden &&
((entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) ||
(request.ftp && name.starts_with(L'.')))) return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
{
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
}
else if((!request.ftp || !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) &&
matchesFileMask(name,request.find->mask) &&
result->metadata.emplace(path,FolderEntryMetadata{
entry.attributes,entry.size,entry.modified}).second)
{
result->files.push_back(path);
if(entry.transfer) result->columnMetadata[path].transfer=entry.transfer;
}
return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
})) break;
}
catch(const std::system_error &error)
{
if(stop.stop_requested()) break;
const auto code=error.code().value();
if(remote && code!=ERROR_FILE_NOT_FOUND && code!=ERROR_PATH_NOT_FOUND &&
code!=ERROR_ACCESS_DENIED && code!=ERROR_DIRECTORY)
throw;
if(!remote && directory==request.directory)
{
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
}
else if(matchesFileMask(path.filename().native(),request.find->mask))
{
result->files.push_back(path);
result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size,entry.modified});
result->failure=L"Cannot search folder: "+directory.native();
return;
}
result->error=ERROR_PARTIAL_COPY;
}
}
};
try
{
if(request.ftp)
{
TransferSession connection(*request.ftp,SftpAccess::normal,stop);
walk([&](const fs::path &directory,const FileVisitor &visit)
{
const auto error=connection.list(directory,visit,stop);
if(error==ERROR_CANCELLED) return false;
requireFileOperation(error==ERROR_SUCCESS || error==ERROR_NO_MORE_FILES,error);
return true;
});
}
catch(const std::system_error &)
else
{
if(directory==request.directory)
{
result->failure=L"Cannot search folder: "+directory.native();
return result;
}
result->error=ERROR_PARTIAL_COPY;
FilesConnection connection(request.peer?&*request.peer:nullptr,stop);
walk([&](const fs::path &directory,const FileVisitor &visit){return listFiles(connection,directory,visit);});
}
}
catch(const std::exception &)
{
if(remote) result->error=ERROR_CONNECTION_ABORTED;
else if(!stop.stop_requested()) result->failure=L"Cannot search folder: "+request.directory.native();
}
if(stop.stop_requested()) result->error=ERROR_CANCELLED;
result->opened=true;
result->opened=result->failure.empty();
std::sort(result->files.begin(),result->files.end());
return result;
}
+56 -13
View File
@@ -16,6 +16,8 @@ struct TransferProfile
TransferProtocol protocol{};
fs::path privateKey;
std::string hostFingerprint;
std::string jumpProfile;
std::wstring sudoSftpServer;
};
struct TransferProfiles
@@ -31,6 +33,36 @@ TransferProfiles &transferProfiles(TransferProtocol protocol)
return protocol==TransferProtocol::sftp?sftp:ftp;
}
std::atomic<std::shared_ptr<const std::vector<TransferProfile>>> sshProfiles;
constexpr size_t sshRouteLimit=8;
std::vector<TransferProfile> sshRoute(const TransferProfile &destination,
const std::vector<TransferProfile> &profiles)
{
std::vector<TransferProfile> route{destination};
std::set<std::string> seen{destination.id};
while(!route.back().jumpProfile.empty())
{
const auto &id=route.back().jumpProfile;
if(!seen.insert(id).second) throw std::runtime_error("The SSH jump route contains a loop.");
if(route.size()>=sshRouteLimit) throw std::runtime_error("An SSH route can contain up to eight hosts.");
const auto hop=std::find_if(profiles.begin(),profiles.end(),
[&id](const auto &profile){return profile.id==id;});
if(hop==profiles.end()) throw std::runtime_error("An SSH jump profile is missing. Edit this connection to update its route.");
route.push_back(*hop);
}
std::reverse(route.begin(),route.end());
return route;
}
bool validSudoSftpServer(std::wstring_view path)
{
constexpr std::wstring_view pathCharacters=L"/-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return path.empty() || (path.starts_with(L'/') && path.ends_with(L"/sftp-server") &&
path.size()<=255 && path.find_first_not_of(pathCharacters)==path.npos);
}
constexpr DWORD transferProfilesMaxBytes=1024*1024;
const fs::path ftpRoot=L"\\";
@@ -58,13 +90,19 @@ bool saveTransferProfiles(TransferProtocol protocol,const std::vector<TransferPr
{
row["privateKey"]=ks::utf8(profile.privateKey.native());
row["hostFingerprint"]=profile.hostFingerprint;
row["jumpProfile"]=profile.jumpProfile;
row["sudoSftpServer"]=ks::utf8(profile.sudoSftpServer);
}
rows.push_back(std::move(row));
}
const auto data=rows.dump();
return data.size()<=transferProfilesMaxBytes &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
if(data.size()>transferProfilesMaxBytes) return false;
const auto snapshot=protocol==TransferProtocol::sftp?
std::make_shared<const std::vector<TransferProfile>>(profiles):nullptr;
if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))!=ERROR_SUCCESS) return false;
if(snapshot) sshProfiles=snapshot;
return true;
}
bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
@@ -101,9 +139,14 @@ bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
{
profile.privateKey=ks::wide(row.value("privateKey",std::string{}));
profile.hostFingerprint=row.value("hostFingerprint",std::string{});
profile.jumpProfile=row.value("jumpProfile",std::string{});
profile.sudoSftpServer=ks::wide(row.value("sudoSftpServer",std::string{}));
if(!validSudoSftpServer(profile.sudoSftpServer)) return false;
}
profiles.push_back(std::move(profile));
}
if(protocol==TransferProtocol::sftp)
sshProfiles=std::make_shared<const std::vector<TransferProfile>>(profiles);
settings.rows=std::move(profiles);
settings.loaded=true;
return true;
@@ -287,17 +330,17 @@ DWORD listFtpDirectory(FtpSession &session,const fs::path &directory,const FileV
const auto name=session.decodeName(entry.cFileName);
if(name.empty() || name==L"." || name==L".." || name.find_first_of(L"/\\:\r\n")!=name.npos)
continue;
ULARGE_INTEGER modified{}, size{};
FILETIME utc{};
if(LocalFileTimeToFileTime(&entry.ftLastWriteTime,&utc))
const auto ftpTime=[](const FILETIME &local) -> uint64_t
{
modified.HighPart=utc.dwHighDateTime;
modified.LowPart=utc.dwLowDateTime;
}
size.HighPart=entry.nFileSizeHigh;
size.LowPart=entry.nFileSizeLow;
if(!visit(directory/name,{entry.dwFileAttributes,size.QuadPart,modified.QuadPart}))
return ERROR_CANCELLED;
FILETIME utc{};
if((!local.dwLowDateTime && !local.dwHighDateTime) || !LocalFileTimeToFileTime(&local,&utc)) return 0;
return (uint64_t(utc.dwHighDateTime)<<32)|utc.dwLowDateTime;
};
FileInfo info{entry.dwFileAttributes,(uint64_t(entry.nFileSizeHigh)<<32)|entry.nFileSizeLow,
ftpTime(entry.ftLastWriteTime)};
const TransferItemMetadata details{ftpTime(entry.ftCreationTime),ftpTime(entry.ftLastAccessTime)};
if(details.created || details.accessed) info.transfer=details;
if(!visit(directory/name,info)) return ERROR_CANCELLED;
} while(!stop.stop_requested() && InternetFindNextFileA(search.value,&entry));
return stop.stop_requested()?ERROR_CANCELLED:GetLastError();
}
+3
View File
@@ -174,8 +174,11 @@ FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs
if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified))
throw std::runtime_error("The "+ks::utf8(ftp.label())+" file changed since it was opened. Your edits are still in the editor.");
if(existing)
{
requireFileOperation(replace && !(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_ALREADY_EXISTS);
ftp.prepareReplacement(temporary,target);
}
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
ftp.rename(temporary,target,existing.has_value());
return *uploaded;
+46 -9
View File
@@ -1,7 +1,8 @@
namespace transferDialog
{
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566;
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566,jumpVia=567,jumpLabel=568;
constexpr int sudoLabel=569,sudoServer=570;
struct Edit
{
@@ -10,6 +11,7 @@ struct Edit
std::wstring pinnedHost;
INTERNET_PORT pinnedPort{};
std::string pin;
std::vector<std::string> jumpChoices;
bool testing{};
std::atomic_bool canceled{};
};
@@ -37,6 +39,23 @@ void showHostStatus(HWND dialog,const Edit &edit)
EnableWindow(GetDlgItem(dialog,forgetKey),trusted && !edit.testing);
}
void addJumpChoice(HWND dialog,Edit &edit,const std::wstring &label,const std::string &id)
{
const auto row=SendDlgItemMessageW(dialog,jumpVia,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row==CB_ERR || row==CB_ERRSPACE) return;
edit.jumpChoices.push_back(id);
if(id==edit.profile.jumpProfile) SendDlgItemMessageW(dialog,jumpVia,CB_SETCURSEL,row,0);
}
void populateJumpChoices(HWND dialog,Edit &edit)
{
addJumpChoice(dialog,edit,L"Direct",{});
for(const auto &profile:transferProfiles(TransferProtocol::sftp).rows)
if(profile.id!=edit.profile.id) addJumpChoice(dialog,edit,profile.name,profile.id);
if(SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0)==CB_ERR)
addJumpChoice(dialog,edit,L"Missing profile",edit.profile.jumpProfile);
}
std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
{
TransferProfile profile;
@@ -48,6 +67,7 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
SetFocus(GetDlgItem(dialog,field));
return {};
};
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
profile.legacyNames=!sftp && IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
profile.name=trimFilesField(shortcutField(dialog,name));
if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos)
@@ -72,6 +92,17 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
if(!profile.privateKey.empty() && !profile.privateKey.is_absolute())
return invalid(keyFile,L"Enter the full path of the private key file.");
if(sameEndpoint(edit,profile)) profile.hostFingerprint=edit.pin;
profile.sudoSftpServer=trimFilesField(shortcutField(dialog,sudoServer));
if(!validSudoSftpServer(profile.sudoSftpServer))
return invalid(sudoServer,L"Enter the absolute path to sftp-server, for example /usr/lib/openssh/sftp-server.");
const auto choice=SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0);
if(choice>=0 && static_cast<size_t>(choice)<edit.jumpChoices.size())
profile.jumpProfile=edit.jumpChoices[choice];
try {sshRoute(profile,profiles);}
catch(const std::exception &error)
{
return invalid(jumpVia,ks::wide(error.what()).c_str());
}
}
auto plain=shortcutField(dialog,password);
if(!plain.empty())
@@ -90,14 +121,13 @@ std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
} erase{bytes,plain};
profile.secret=ks::protect(bytes);
}
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
return profile;
}
template<class Task>
bool runTest(HWND dialog,Edit &edit,const wchar_t *status,Task task)
{
constexpr int controls[]{name,host,port,user,password,keyFile,testConnection,forgetKey,IDOK};
constexpr int controls[]{name,host,port,user,password,keyFile,jumpVia,sudoServer,testConnection,forgetKey,IDOK};
edit.testing=true;
edit.canceled=false;
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),FALSE);
@@ -125,7 +155,7 @@ void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
{
std::string fingerprint;
if(!runTest(dialog,edit,L"Reading the SSH host key…",[&] {
const SftpSession probe(profile,true);
const SshConnection probe(profile,true);
fingerprint=probe.fingerprint();
})) return;
const auto prompt=profile.host+L":"+std::to_wstring(profile.port)+L"\r\n"+ks::wide(fingerprint)+
@@ -136,12 +166,15 @@ void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
profile.hostFingerprint=edit.pin=std::move(fingerprint);
}
fs::path initial;
if(runTest(dialog,edit,L"Testing the SFTP login…",[&] {
SftpSession session(profile);
initial=session.initialDirectory();
if(runTest(dialog,edit,L"Testing the SSH login…",[&] {
SshConnection connection(profile);
const SftpSubsystem sftp(libssh2_sftp_init(connection.session()),libssh2_sftp_shutdown);
if(sftp) initial=sftpInitialDirectory(sftp.get());
}))
{
const auto details=L"Connected to "+profile.host+L".\r\n\r\nInitial folder "+ftpPath(initial)+L".";
const auto details=L"Connected to "+profile.host+L".\r\n\r\n"+(initial.empty()?
L"SFTP is unavailable. This profile can still be used as an SSH jump host.":
L"Initial folder "+ftpPath(initial)+L".");
showFilesNotice(dialog,details.c_str(),L"SFTP connection test");
}
}
@@ -159,7 +192,7 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto &profile=edit->profile;
prepareCopyDialog(dialog);
layoutDialogContent(dialog,381);
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus})
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus,jumpVia,jumpLabel,sudoLabel})
if(const auto control=GetDlgItem(dialog,id)) SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
for(const auto id:{name,host,user,password})
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
@@ -172,6 +205,10 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
SendDlgItemMessageW(dialog,keyFile,EM_SETLIMITTEXT,32767,0);
SetDlgItemTextW(dialog,keyFile,profile.privateKey.c_str());
SendDlgItemMessageW(dialog,sudoServer,EM_SETLIMITTEXT,255,0);
SetDlgItemTextW(dialog,sudoServer,profile.sudoSftpServer.c_str());
populateJumpChoices(dialog,*edit);
installFarCombo(GetDlgItem(dialog,jumpVia),GetDlgItem(dialog,keyFile));
showHostStatus(dialog,*edit);
layoutDialogButtons(dialog,footer,{testConnection,forgetKey,IDOK,IDCANCEL});
}
+307
View File
@@ -0,0 +1,307 @@
#include "files_git_changes.h"
#include "core.h"
#include "windows_command_line.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#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 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_CEILING_DIRECTORIES",L"GIT_GLOB_PATHSPECS",L"GIT_NOGLOB_PATHSPECS",L"GIT_ICASE_PATHSPECS"};
std::vector<wchar_t> result;
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;
}))
result.insert(result.end(),entry,entry+setting.size()+1);
entry+=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{};
};
GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector<std::wstring> &arguments,
size_t maximum,std::stop_token stop)
{
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();
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
const GitHandle input{CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr)};
if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input");
GitHandle 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");
childOut.close();
childError.close();
GitOutput result;
const auto deadline=GetTickCount64()+15000;
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);
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(...)
{
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 statusField(std::string_view &input)
{
const auto separator=input.find('\0');
if(separator==input.npos) throw std::runtime_error("Git returned incomplete status 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=statusField(output);
if(row.size()<4 || row[2]!=' ') throw std::runtime_error("Git returned an invalid status record.");
const auto code=row.substr(0,2);
const auto path=statusPath(row.substr(3));
std::wstring origin;
if(code.find_first_of("RC")!=code.npos) origin=statusPath(statusField(output));
if(code=="??") 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;
}
}
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.");
while(!root.output.empty() && (root.output.back()=='\r' || root.output.back()=='\n')) root.output.pop_back();
result.root=fs::path(wide(root.output)).make_preferred();
if(!result.root.is_absolute()) throw std::runtime_error("Git returned an invalid worktree root.");
const auto status=runGit(result.executable,result.root,
{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"},8*1024*1024,stop);
checkGit(status,"Could not read Git worktree status.");
result.entries=parseGitStatus(status.output);
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);
}
}
+29
View File
@@ -0,0 +1,29 @@
#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 GitChanges
{
std::filesystem::path executable, root;
std::vector<GitChange> entries;
};
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);
}
+412
View File
@@ -0,0 +1,412 @@
using ks::files::GitChange;
using ks::files::GitChangeKind;
using ks::files::GitChanges;
struct GitChangesView
{
HWND host{},heading{},filterLabel{},filter{},list{},status{},hints{},preview{};
fs::path folder;
GitChanges data;
std::future<GitChanges> refresh;
std::future<std::string> diff;
std::stop_source stopRefresh,stopDiff;
ULONGLONG diffAt{};
std::optional<GitChange> requested;
std::string failure;
};
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;
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;
}
std::wstring gitDiffHeading(const GitChange &entry)
{
return std::wstring(gitChangeKindName(entry.kind))+L" diff · "+entry.path;
}
void queueGitDiff(GitChangesView &view)
{
view.stopDiff.request_stop();
view.diff={};
view.diffAt=0;
view.requested.reset();
if(view.refresh.valid())
{
ks::files::previewQuickViewDiff(view.preview,L"Diff · Reading Git changes…",{});
return;
}
if(!view.failure.empty())
{
ks::files::previewQuickViewDiff(view.preview,L"Git status failed",view.failure);
return;
}
if(const auto *entry=selectedGitChange(view))
{
view.requested=*entry;
view.diffAt=GetTickCount64()+100;
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*entry)+L" · Loading…",{});
}
else ks::files::previewQuickViewDiff(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+(entry.oldPath.empty()?entry.path:entry.path+L" ← "+entry.oldPath);
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);
const auto total=view.data.entries.size();
const auto status=view.refresh.valid()?std::wstring(L"Reading Git changes…"):
!view.failure.empty()?L"Could not read Git changes.":
!total?L"No Git changes.":!count?L"No paths match the filter.":
std::to_wstring(count)+(query.empty()?L"":L" of "+std::to_wstring(total))+L" changes";
SetWindowTextW(view.status,status.c_str());
queueGitDiff(view);
}
void refreshGitChanges(GitChangesView &view)
{
if(view.refresh.valid()) 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);
SetWindowTextW(view.status,L"Reading Git changes…");
queueGitDiff(view);
}
catch(const std::exception &)
{
view.failure="Could not start Git.";
renderGitChanges(view);
}
}
void pollGitChanges(GitChangesView &view)
{
using namespace std::chrono_literals;
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.diffAt && GetTickCount64()>=view.diffAt)
{
view.diffAt=0;
view.stopDiff=std::stop_source{};
try
{
std::packaged_task<std::string()> task([git=view.data.executable,root=view.data.root,
entry=*view.requested,stop=view.stopDiff.get_token()] {
return ks::files::readGitPatch(git,root,entry,stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.diff=std::move(pending);
}
catch(const std::exception &)
{
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),"Could not start Git diff.");
}
}
if(view.diff.valid() && view.diff.wait_for(0ms)==std::future_status::ready)
{
try
{
const auto patch=view.diff.get();
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),
patch.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(patch));
}
catch(const std::exception &error)
{
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),error.what());
}
}
}
void openGitWorkingFile(GitChangesView &view,bool edit)
{
const auto *entry=selectedGitChange(view);
if(!entry || view.refresh.valid() || !view.failure.empty()) 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;
const int filterTop=top+textHeight+6, listTop=filterTop+textHeight+6;
const int bottom=std::max(listTop,static_cast<int>(bounds.bottom)-textHeight-5);
const int leftWidth=std::max(0,middle-2*inset);
place(view.heading,inset,top,leftWidth,textHeight);
place(view.filterLabel,inset,filterTop,filterLabel,textHeight);
place(view.filter,inset+filterLabel,filterTop,leftWidth-filterLabel,textHeight);
place(view.list,inset,listTop,leftWidth-scrollBarWidth(view.list),bottom-listTop);
place(view.status,inset,bottom+3,leftWidth,textHeight);
place(view.preview,middle+inset,top,bounds.right-middle-2*inset,bottom-top);
place(view.hints,middle+inset,bottom+3,bounds.right-middle-2*inset,textHeight);
for(const auto control:{view.heading,view.filterLabel,view.filter,view.list,view.status,view.hints})
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendMessageW(view.list,LB_SETITEMHEIGHT,0,textHeight);
}
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->filterLabel=make(L"STATIC",L"Filter",SS_NOPREFIX);
view->filter=make(farEditClass,L"",ES_MULTILINE|ES_AUTOHSCROLL|WS_TABSTOP,gitFilter);
view->list=make(L"LISTBOX",L"",LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT|LBS_NOTIFY|WS_TABSTOP,gitList);
view->status=make(L"STATIC",L"",SS_ENDELLIPSIS|SS_NOPREFIX,gitStatus);
view->hints=make(L"STATIC",L"F3 View F4 Edit Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX);
try {view->preview=ks::files::createQuickView(window,textWindowDialogs());}
catch(const std::exception &) {}
if(!view->heading || !view->filterLabel || !view->filter || !view->list || !view->status ||
!view->hints || !view->preview || !SetTimer(window,gitChangesTimer,35,nullptr)) return -1;
prepareDialogEdit(view->filter);
SendMessageW(view->filter,EM_SETLIMITTEXT,1024,0);
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->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE)
{
const auto *entry=selectedGitChange(*view);
renderGitChanges(*view,entry?std::optional(*entry):std::nullopt);
}
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitDiff(*view);
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_DBLCLK) openGitWorkingFile(*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.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;
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)
{
auto view=std::move(gitChangesView);
if(!view) return;
view->stopRefresh.request_stop();
view->stopDiff.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;
if(!control && key==VK_ESCAPE) closeGitChanges(owner);
else if(control && key=='R') refreshGitChanges(view);
else if(control && key=='F') SetFocus(view.filter);
else if(!control && key==VK_TAB) SetFocus(GetFocus()==view.filter?view.list:view.filter);
else if(!control && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list)))
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;
}
+22 -7
View File
@@ -34,6 +34,8 @@ struct ImageView
std::vector<fs::path> images;
size_t position{};
ImageLoad load;
ImageLoadRetry retry;
bool retried{};
std::function<void(HWND)> onClose;
std::array<HWND,6> buttons{};
HFONT font{};
@@ -116,6 +118,7 @@ struct ImageView
requested=path;
++revision;
stop.request_stop();
retried=false;
error.clear();
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
width=height=0;
@@ -154,21 +157,32 @@ struct ImageView
if(reading.valid())
{
if(reading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
const auto current=revision==started;
if(current) KillTimer(window,imageTimer);
bool retryApproved=false;
try
{
auto image=reading.get();
if(revision==started) show(std::move(image));
if(current) show(std::move(image));
}
catch(const std::exception &e)
catch(const std::exception &failure)
{
if(revision==started) error=wide(e.what());
if(current)
{
if(!retried && retry.approve) retryApproved=retry.approve(window,requested,failure);
if(!retryApproved) error=wide(failure.what());
}
}
if(revision==started)
if(current && !retryApproved)
{
KillTimer(window,imageTimer);
InvalidateRect(window,nullptr,FALSE);
return;
}
if(retryApproved)
{
retried=true;
SetTimer(window,imageTimer,30,nullptr);
}
}
if(requested.empty())
{
@@ -177,7 +191,7 @@ struct ImageView
}
stop=std::stop_source{};
started=revision;
std::packaged_task<ImageRaster()> task([path=requested,decoder=load,token=stop.get_token()]
std::packaged_task<ImageRaster()> task([path=requested,decoder=retried?retry.load:load,token=stop.get_token()]
{
return decoder?decoder(path,token):decodeImage(path,path,token);
});
@@ -421,7 +435,7 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
}
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose)
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry)
{
const auto instance=GetModuleHandleW(nullptr);
static const bool registered=[instance]
@@ -439,6 +453,7 @@ HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<s
state->style=style;
state->images=std::move(images);
state->load=std::move(load);
state->retry=std::move(retry);
state->onClose=std::move(onClose);
const auto position=std::find(state->images.begin(),state->images.end(),initial);
if(position!=state->images.end()) state->position=static_cast<size_t>(position-state->images.begin());
+8 -1
View File
@@ -3,11 +3,18 @@
#include "files_image_decode.h"
#include <windows.h>
#include <functional>
#include <exception>
namespace ks::files
{
using ImageLoad=std::function<ImageRaster(const std::filesystem::path &,std::stop_token)>;
struct ImageLoadRetry
{
ImageLoad load;
std::function<bool(HWND,const std::filesystem::path &,const std::exception &)> approve;
};
struct ImageViewStyle
{
LOGFONTW font{};
@@ -16,6 +23,6 @@ struct ImageViewStyle
};
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={});
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={});
void showImageViewFile(HWND window,const std::filesystem::path &path);
}
+338 -97
View File
@@ -12,15 +12,9 @@ DWORD probeDeleteAccess(const fs::path &path)
return probe.value==INVALID_HANDLE_VALUE?GetLastError():ERROR_SUCCESS;
}
struct LockProcess
{
DWORD pid;
FILETIME started{};
std::wstring name;
};
struct LockScan
{
std::vector<LockProcess> processes;
std::set<DWORD> pids;
bool incomplete{};
};
@@ -30,7 +24,6 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
const auto query=reinterpret_cast<decltype(&NtQueryInformationFile)>(
GetProcAddress(GetModuleHandleW(L"ntdll.dll"),"NtQueryInformationFile"));
if(!query) { result.incomplete=true; return result; }
std::set<DWORD> pids;
std::vector<ULONG_PTR> buffer(128);
const auto inspect=[&](const fs::path &path) {
const auto error=probeDeleteAccess(path);
@@ -63,7 +56,7 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
}
for(ULONG i=0;i<count;++i)
if(const auto pid=buffer[i+1];pid && pid<=MAXDWORD && pid!=GetCurrentProcessId())
pids.insert(static_cast<DWORD>(pid));
result.pids.insert(static_cast<DWORD>(pid));
};
auto remaining=8192u;
const auto deadline=GetTickCount64()+4000;
@@ -90,162 +83,410 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
}
if(error) result.incomplete=true;
}
for(const auto pid:pids)
return result;
}
struct ProcessIdentity
{
DWORD pid{};
uint64_t started{};
bool operator==(const ProcessIdentity &) const = default;
};
struct ProcessEntry
{
ProcessIdentity identity;
std::wstring name;
fs::path image;
std::optional<uint64_t> workingSet;
std::optional<double> cpu;
};
struct ProcessScan
{
std::vector<ProcessEntry> entries;
bool incomplete{};
};
constexpr uint64_t processTimeTicks(const FILETIME &time)
{
return (uint64_t(time.dwHighDateTime)<<32)|time.dwLowDateTime;
}
struct ProcessTimes
{
uint64_t started, busy;
std::chrono::steady_clock::time_point measured;
};
std::optional<ProcessTimes> readProcessTimes(HANDLE process)
{
FILETIME started{},exited{},kernel{},user{};
if(!GetProcessTimes(process,&started,&exited,&kernel,&user)) return {};
return ProcessTimes{processTimeTicks(started),processTimeTicks(kernel)+processTimeTicks(user),
std::chrono::steady_clock::now()};
}
ProcessScan scanProcesses(const std::vector<fs::path> &files,std::stop_token stop)
{
ProcessScan result;
LockScan locks;
if(!files.empty())
{
Handle process{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,pid)};
LockProcess entry{pid};
if(process.value)
locks=scanLockProcesses(files,stop);
result.incomplete=locks.incomplete;
if(locks.pids.empty() || stop.stop_requested()) return result;
}
const Handle snapshot{CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0)};
if(snapshot.value==INVALID_HANDLE_VALUE)
throw std::system_error(GetLastError(),std::system_category());
PROCESSENTRY32W process{sizeof(PROCESSENTRY32W)};
if(!Process32FirstW(snapshot.value,&process))
throw std::system_error(GetLastError(),std::system_category());
do
{
const auto pid=process.th32ProcessID;
if(files.empty() || locks.pids.contains(pid))
result.entries.push_back({{pid},process.szExeFile});
} while(!stop.stop_requested() && Process32NextW(snapshot.value,&process));
if(!stop.stop_requested() && GetLastError()!=ERROR_NO_MORE_FILES) result.incomplete=true;
std::map<DWORD,ProcessTimes> initial;
for(const auto &entry:result.entries)
{
if(stop.stop_requested()) return {};
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
if(handle.value)
if(const auto time=readProcessTimes(handle.value)) initial.emplace(entry.identity.pid,*time);
}
if(!initial.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(350));
const auto logicalCpus=std::max(1ul,static_cast<unsigned long>(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)));
std::array<wchar_t,32768> image;
for(auto &entry:result.entries)
{
if(stop.stop_requested()) return {};
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
if(!handle.value) continue;
const auto current=readProcessTimes(handle.value);
const auto before=initial.find(entry.identity.pid);
if(current && before!=initial.end() && current->started!=before->second.started) continue;
if(current)
{
FILETIME exit{},kernel{},user{};
GetProcessTimes(process.value,&entry.started,&exit,&kernel,&user);
wchar_t path[32768];
DWORD count=std::size(path);
if(QueryFullProcessImageNameW(process.value,0,path,&count))
entry.name=fs::path(std::wstring_view(path,count)).filename().wstring();
entry.identity.started=current->started;
if(before!=initial.end() && current->busy>=before->second.busy)
{
const auto elapsed=std::chrono::duration<double>(current->measured-before->second.measured).count();
if(elapsed>0)
entry.cpu=std::clamp((current->busy-before->second.busy)*0.00001/(elapsed*logicalCpus),0.0,100.0);
}
}
if(entry.name.empty()) entry.name=L"Unknown process";
result.processes.push_back(std::move(entry));
DWORD count=image.size();
if(QueryFullProcessImageNameW(handle.value,0,image.data(),&count))
entry.image=std::wstring_view(image.data(),count);
PROCESS_MEMORY_COUNTERS memory{sizeof(memory)};
if(K32GetProcessMemoryInfo(handle.value,&memory,sizeof(memory))) entry.workingSet=memory.WorkingSetSize;
}
return result;
}
struct LockDialog
constexpr int processScope=430,processList=431,processDivider=432,processEnd=433,processRefresh=434,
processFilter=435,processSort=436,processReveal=437,processImage=438,processColumns=439,processStatus=443;
constexpr UINT_PTR processScanTimer=1;
enum class ProcessOrder { pid, cpu, memory, name, image };
struct ProcessDialog
{
std::vector<fs::path> paths;
std::vector<LockProcess> processes;
std::future<LockScan> scan;
std::vector<fs::path> files;
std::vector<ProcessEntry> entries;
std::future<ProcessScan> scan;
std::stop_source stop;
std::wstring failure;
fs::path reveal;
bool incomplete{};
};
constexpr UINT_PTR lockScanTimer=1;
const ProcessEntry *selectedProcess(HWND dialog,const ProcessDialog &state)
{
const auto row=SendDlgItemMessageW(dialog,processList,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendDlgItemMessageW(dialog,processList,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<state.entries.size()?&state.entries[index]:nullptr;
}
void refreshLockProcesses(HWND window,LockDialog &state,std::shared_ptr<Handle> terminated={})
bool mayEndProcess(ProcessIdentity identity)
{
return identity.pid && identity.pid!=GetCurrentProcessId() && identity.started;
}
void updateSelectedProcess(HWND dialog,const ProcessDialog &state)
{
const auto *entry=selectedProcess(dialog,state);
const bool hasImage=entry && !entry->image.empty();
SetDlgItemTextW(dialog,processImage,hasImage?entry->image.c_str():entry?L"Unavailable":L"");
EnableWindow(GetDlgItem(dialog,processReveal),!state.scan.valid() && hasImage);
EnableWindow(GetDlgItem(dialog,processEnd),!state.scan.valid() && entry && mayEndProcess(entry->identity));
}
std::wstring processColumnsText(std::wstring_view pid,std::wstring_view cpu,std::wstring_view memory,
std::wstring_view name)
{
std::wostringstream fields;
fields<<std::right<<std::setw(10)<<pid<<L" "<<std::setw(7)<<cpu<<L" "<<std::setw(12)<<memory<<L" "<<name;
return fields.str();
}
int compareProcessNames(const std::wstring &left,const std::wstring &right)
{
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE);
}
void renderProcessList(HWND dialog,const ProcessDialog &state,std::optional<ProcessIdentity> preferred={})
{
const auto field=GetDlgItem(dialog,processFilter);
std::wstring query(GetWindowTextLengthW(field)+1,L'\0');
query.resize(GetWindowTextW(field,query.data(),static_cast<int>(query.size())));
const auto contains=[&](std::wstring_view value)
{
return query.empty() || (!value.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
value.data(),static_cast<int>(value.size()),query.c_str(),static_cast<int>(query.size()),nullptr,
nullptr,nullptr,0)>=0);
};
std::vector<size_t> rows;
for(size_t i=0;i<state.entries.size();++i)
{
const auto &entry=state.entries[i];
if(contains(entry.name) || contains(entry.image.native()) || contains(std::to_wstring(entry.identity.pid)))
rows.push_back(i);
}
const auto order=static_cast<ProcessOrder>(SendDlgItemMessageW(dialog,processSort,CB_GETCURSEL,0,0));
std::sort(rows.begin(),rows.end(),[&](size_t a,size_t b)
{
const auto &left=state.entries[a],&right=state.entries[b];
if(order==ProcessOrder::cpu && left.cpu!=right.cpu) return left.cpu>right.cpu;
if(order==ProcessOrder::memory && left.workingSet!=right.workingSet) return left.workingSet>right.workingSet;
if(order==ProcessOrder::name || order==ProcessOrder::image)
{
const auto names=order==ProcessOrder::name?compareProcessNames(left.name,right.name):
compareProcessNames(left.image.native(),right.image.native());
if(names!=CSTR_EQUAL) return names==CSTR_LESS_THAN;
}
return left.identity.pid<right.identity.pid;
});
const auto list=GetDlgItem(dialog,processList);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(const auto index:rows)
{
const auto &entry=state.entries[index];
wchar_t cpu[16]=L"—";
if(entry.cpu) swprintf_s(cpu,L"%.1f%%",*entry.cpu);
const auto text=processColumnsText(std::to_wstring(entry.identity.pid),cpu,
entry.workingSet?formatSize(*entry.workingSet):L"—",entry.name);
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(text.c_str()));
if(row<0) continue;
SendMessageW(list,LB_SETITEMDATA,row,index);
if(preferred==entry.identity) selected=row;
}
if(!rows.empty()) SendMessageW(list,LB_SETCURSEL,selected,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,TRUE);
updateSelectedProcess(dialog,state);
std::wstring status;
if(state.scan.valid()) status=state.files.empty()?L"Sampling processes…":L"Checking files for locking processes…";
else if(!state.failure.empty()) status=state.failure;
else if(state.entries.empty()) status=state.files.empty()?L"No processes found.":L"No locking processes found.";
else if(rows.empty()) status=L"No processes match the filter.";
else status=std::to_wstring(rows.size())+(query.empty()?L"":L" of "+std::to_wstring(state.entries.size()))+L" shown";
if(state.incomplete && !state.scan.valid() && state.failure.empty()) status+=L" Some items could not be checked.";
SetDlgItemTextW(dialog,processStatus,status.c_str());
}
void refreshProcesses(HWND dialog,ProcessDialog &state,std::shared_ptr<Handle> ended={})
{
if(state.scan.valid()) return;
state.processes.clear();
SendDlgItemMessageW(window,431,LB_RESETCONTENT,0,0);
EnableWindow(GetDlgItem(window,433),FALSE);
EnableWindow(GetDlgItem(window,434),FALSE);
SetDlgItemTextW(window,430,L"Checking which processes are using the file or folder…");
const auto *entry=selectedProcess(dialog,state);
const auto selected=entry?std::optional(entry->identity):std::nullopt;
state.failure.clear();
try
{
std::packaged_task<LockScan()> task([paths=state.paths,stop=state.stop.get_token(),terminated=std::move(terminated)] {
if(terminated) WaitForSingleObject(terminated->value,2500);
return scanLockProcesses(paths,stop);
std::packaged_task<ProcessScan()> task([files=state.files,stop=state.stop.get_token(),ended=std::move(ended)] {
if(ended) WaitForSingleObject(ended->value,2500);
return scanProcesses(files,stop);
});
auto future=task.get_future();
if(!SetTimer(window,lockScanTimer,50,nullptr))
if(!SetTimer(dialog,processScanTimer,50,nullptr))
throw std::runtime_error("Could not start the process scan.");
std::thread(std::move(task)).detach();
state.scan=std::move(future);
}
catch(const std::exception &)
{
KillTimer(window,lockScanTimer);
EnableWindow(GetDlgItem(window,434),TRUE);
SetDlgItemTextW(window,430,L"Could not start the process scan.");
KillTimer(dialog,processScanTimer);
state.failure=L"Could not start the process scan.";
}
EnableWindow(GetDlgItem(dialog,processRefresh),!state.scan.valid());
renderProcessList(dialog,state,selected);
}
void endLockProcess(HWND window,LockDialog &state)
void endFileProcess(HWND dialog,ProcessDialog &state)
{
const auto index=SendDlgItemMessageW(window,431,LB_GETCURSEL,0,0);
if(index<0 || size_t(index)>=state.processes.size()) return;
const auto &entry=state.processes[index];
auto error=[&](const wchar_t *message) {
showFilesNotice(window,message,L"End process",{.tone=FilesNoticeTone::warning});
const auto *entry=selectedProcess(dialog,state);
if(state.scan.valid() || !entry || !mayEndProcess(entry->identity)) return;
const auto error=[&](const wchar_t *message)
{
showFilesNotice(dialog,message,L"End process",{.tone=FilesNoticeTone::warning});
};
auto process=std::make_shared<Handle>();
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry.pid);
FILETIME started{},exited{},kernel{},user{};
const auto process=std::make_shared<Handle>();
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry->identity.pid);
const auto current=process->value?readProcessTimes(process->value):std::nullopt;
BOOL critical{};
if(!process->value || !(entry.started.dwHighDateTime || entry.started.dwLowDateTime) ||
!GetProcessTimes(process->value,&started,&exited,&kernel,&user) ||
CompareFileTime(&started,&entry.started)!=0 || !IsProcessCritical(process->value,&critical) || critical)
if(!current || current->started!=entry->identity.started ||
!IsProcessCritical(process->value,&critical) || critical)
{
error(L"This process has exited, is protected, or cannot be identified.");
return;
}
const auto question=L"End "+entry.name+L" (PID "+std::to_wstring(entry.pid)+
const auto question=L"End "+entry->name+L" (PID "+std::to_wstring(entry->identity.pid)+
L")?\r\nUnsaved work in the process may be lost.";
if(showFilesNotice(window,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
if(showFilesNotice(dialog,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
return;
if(WaitForSingleObject(process->value,0)==WAIT_TIMEOUT && !TerminateProcess(process->value,1))
const auto alive=WaitForSingleObject(process->value,0);
if(alive!=WAIT_OBJECT_0 && (alive!=WAIT_TIMEOUT || !TerminateProcess(process->value,1)))
{
const auto message=ks::lastError(L"Could not end the process");
error(message.c_str());
const auto reason=ks::lastError(L"Could not end the process");
error(reason.c_str());
return;
}
refreshLockProcesses(window,state,std::move(process));
refreshProcesses(dialog,state,process);
}
INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
INT_PTR CALLBACK processesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
for(const auto id:{430,431}) SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
const auto list=GetDlgItem(window,431);
RECT bounds{};
GetWindowRect(list,&bounds);
auto &state=*reinterpret_cast<ProcessDialog *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,processScope);
if(state.files.empty()) SetDlgItemTextW(dialog,processScope,L"This PC");
else
{
auto scope=L"Locks for "+state.files.front().native();
if(state.files.size()>1) scope+=L" (+"+std::to_wstring(state.files.size()-1)+L" more)";
SetDlgItemTextW(dialog,processScope,scope.c_str());
}
const auto filterField=GetDlgItem(dialog,processFilter);
SendMessageW(filterField,EM_SETLIMITTEXT,1024,0);
const auto sortField=GetDlgItem(dialog,processSort);
for(const auto name:{L"PID",L"CPU",L"Memory",L"Name",L"Executable"})
SendMessageW(sortField,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
SendMessageW(sortField,CB_SETCURSEL,1,0);
installFarCombo(sortField,filterField);
SetDlgItemTextW(dialog,processColumns,processColumnsText(L"PID",L"CPU",L"Working set",L"Process").c_str());
const auto list=GetDlgItem(dialog,processList);
const auto bounds=dialogControlBounds(dialog,processList);
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,window);
layoutDialogButtons(window,432,{433,434,IDOK});
SendMessageW(window,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(window,IDOK));
refreshLockProcesses(window,*reinterpret_cast<LockDialog *>(lp));
installScrollBar(list,dialog);
layoutDialogButtons(dialog,processDivider,{processReveal,processEnd,processRefresh,IDOK});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(filterField);
refreshProcesses(dialog,state);
return FALSE;
}
auto *data=reinterpret_cast<LockDialog *>(GetWindowLongPtrW(window,DWLP_USER));
auto *data=reinterpret_cast<ProcessDialog *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!data) return FALSE;
auto &state=*data;
if(message==WM_TIMER && wp==lockScanTimer)
if(message==WM_TIMER && wp==processScanTimer)
{
if(!state.scan.valid() || state.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
return TRUE;
KillTimer(window,lockScanTimer);
EnableWindow(GetDlgItem(window,434),TRUE);
KillTimer(dialog,processScanTimer);
EnableWindow(GetDlgItem(dialog,processRefresh),TRUE);
const auto *entry=selectedProcess(dialog,state);
const auto selected=entry?std::optional(entry->identity):std::nullopt;
try
{
auto result=state.scan.get();
for(auto &entry:result.processes)
{
const auto label=entry.name+L" (PID "+std::to_wstring(entry.pid)+L")";
if(SendDlgItemMessageW(window,431,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))>=0)
state.processes.push_back(std::move(entry));
}
SetDlgItemTextW(window,430,state.processes.empty()?
(result.incomplete?L"No processes found. Some items could not be checked.":L"No locking processes found."):
(result.incomplete?L"Possible locking processes. The scan was incomplete.":L"Processes using locked files or folders."));
if(!state.processes.empty())
{
SendDlgItemMessageW(window,431,LB_SETCURSEL,0,0);
EnableWindow(GetDlgItem(window,433),TRUE);
}
state.entries=std::move(result.entries);
state.incomplete=result.incomplete;
}
catch(const std::exception &) {SetDlgItemTextW(window,430,L"Could not check for locking processes.");}
catch(const std::system_error &e) {state.failure=fileError(e);}
catch(const std::exception &) {state.failure=L"Could not read the process list.";}
renderProcessList(dialog,state,selected);
return TRUE;
}
if(message==WM_DRAWITEM && wp==processSort)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=GetDlgItem(dialog,processList))
{
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)
{
switch(LOWORD(wp))
const auto id=LOWORD(wp),notification=HIWORD(wp);
if((id==processFilter && notification==EN_CHANGE) || (id==processSort && notification==CBN_SELCHANGE))
{
case 433: endLockProcess(window,state); return TRUE;
case 434: refreshLockProcesses(window,state); return TRUE;
const auto *entry=selectedProcess(dialog,state);
renderProcessList(dialog,state,entry?std::optional(entry->identity):std::nullopt);
return TRUE;
}
if(id==processList && notification==LBN_SELCHANGE)
{
updateSelectedProcess(dialog,state);
return TRUE;
}
if(id==processReveal || (id==processList && notification==LBN_DBLCLK))
{
const auto *entry=selectedProcess(dialog,state);
if(!state.scan.valid() && entry && !entry->image.empty())
{
state.reveal=entry->image;
FilesModalDialog::finish(dialog,processReveal);
}
return TRUE;
}
switch(id)
{
case processEnd: endFileProcess(dialog,state); return TRUE;
case processRefresh: refreshProcesses(dialog,state); return TRUE;
case IDOK:
case IDCANCEL: FilesModalDialog::finish(window,IDCANCEL); return TRUE;
case IDCANCEL: FilesModalDialog::finish(dialog,IDCANCEL); return TRUE;
}
}
if(message==WM_CLOSE) {FilesModalDialog::finish(window,IDCANCEL);return TRUE;}
return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432},false,GetDlgItem(window,431));
if(message==WM_CLOSE) {FilesModalDialog::finish(dialog,IDCANCEL);return TRUE;}
const auto title=state.files.empty()?L" Processes ":L" Locking processes ";
return paintCopyDialog(dialog,message,wp,lp,title,false,{processDivider},false,GetDlgItem(dialog,processList));
}
void showLockProcesses(HWND owner,std::vector<fs::path> paths)
void showProcesses(HWND owner,std::vector<fs::path> paths)
{
LockDialog state{std::move(paths)};
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,lockProcessesDialog,
const auto source=active;
ProcessDialog state{std::move(paths)};
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,processesDialog,
reinterpret_cast<LPARAM>(&state));
state.stop.request_stop();
if(result!=processReveal) return;
const auto destination=state.files.empty()?source:1-source;
if(quickViewWindow && destination!=quickViewSource) toggleQuickView(owner);
revealLocalFile(panels[destination],state.reveal);
}
bool panelLockSearchAvailable(const Panel &panel)
{
return !terminalVisible && panelItemPropertiesAvailable(panel) && !panel.ftp && !panel.peer &&
!panel.archive && !windowsNetworkPath(panel.directory);
}
void showPanelLockProcesses(HWND owner,Panel &panel)
{
if(panelLockSearchAvailable(panel)) showProcesses(owner,selectedPanelPaths(panel));
}
+367 -74
View File
@@ -9,6 +9,8 @@
#include <commdlg.h>
#include <aclapi.h>
#include <sddl.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <cmath>
#include <numbers>
#include <algorithm>
@@ -36,9 +38,11 @@
#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"
#include "files_win32_replace.h"
#include "files_command_completion.h"
#include "files_text_window.h"
#include "files_menu_navigation.h"
@@ -67,11 +71,18 @@ using ks::lan::filePath;
using ks::lan::checkFileReply;
using ks::files::validFileName;
struct TransferItemMetadata
{
uint64_t created{}, accessed{};
std::optional<uint32_t> owner, permissions;
};
struct FileInfo
{
DWORD attributes;
uint64_t size, modified;
std::optional<uint64_t> allocated{};
std::optional<TransferItemMetadata> transfer{};
};
FileInfo fileInfo(const Json &row)
{
@@ -373,6 +384,7 @@ constexpr auto schemeKey = L"Software\\KSwitcher\\Files";
#include "files_registry_json.inl"
#include "files_ftp.inl"
#include "files_sftp.inl"
#include "files_ssh_terminal.inl"
#include "files_transfer.inl"
@@ -382,6 +394,20 @@ fs::path folderPathWithoutSeparator(fs::path path)
return path;
}
bool windowsNetworkPath(const fs::path &path)
{
std::wstring_view name=path.native();
if(name.starts_with(L"\\\\?\\"))
{
name.remove_prefix(4);
if(name.size()>=4 && CompareStringOrdinal(name.data(),4,L"UNC\\",4,TRUE)==CSTR_EQUAL) return true;
return name.size()>=3 && name[1]==L':' && name[2]==L'\\' &&
GetDriveTypeW(std::wstring(name.substr(0,3)).c_str())==DRIVE_REMOTE;
}
return name.starts_with(L"\\\\") || name.starts_with(L"//") ||
GetDriveTypeW(path.root_path().c_str())==DRIVE_REMOTE;
}
fs::path panelParentPath(const fs::path &directory,bool local)
{
if(!directory.has_relative_path()) return {};
@@ -503,6 +529,7 @@ struct ColumnMetadata
std::wstring owner;
std::optional<uint64_t> allocated;
std::optional<DWORD> links;
std::optional<TransferItemMetadata> transfer;
};
using ColumnMetadataMap=std::map<fs::path,ColumnMetadata>;
@@ -714,7 +741,8 @@ std::wstring panelCaption(const Panel &panel)
const auto display=panel.directory.lexically_relative(panel.archive->file.parent_path());
return L"Archive · "+display.native();
}
return panel.findOrigin?L"Search results":panelLocation(panel);
if(!panel.findOrigin) return panelLocation(panel);
return panel.ftp || panel.peer?L"Search results · "+panelLocation(panel):L"Search results";
}
Panel panels[2];
@@ -739,7 +767,22 @@ void traceTerminal(const char *event,int a=0,int b=0,int c=0,int d=0,int e=0)
++terminalTraceLines;
terminalTrace<<GetTickCount64()<<' '<<event<<' '<<a<<' '<<b<<' '<<c<<' '<<d<<' '<<e<<std::endl;
}
FilesTerminalView terminalView;
FilesTerminalView terminalView,sshView;
FilesSshTerminal sshTerminal;
struct SshPrompt
{
int panel{};
std::string profile,token;
fs::path panelDirectory,shellDirectory;
std::optional<std::wstring> startupCommand;
bool waiting=true;
bool raw{},finished{};
};
std::optional<SshPrompt> sshPrompt;
COORD sshSize{80,25};
bool sshViewRequested{};
FilesTerminalView &activeTerminalView(){return sshPrompt?sshView:terminalView;}
std::wstring terminalSelection;
COORD terminalSize{80,25};
bool terminalViewRequested{};
@@ -1162,6 +1205,7 @@ bool applyFont(HWND owner, LOGFONTW font, int points)
displayFont=font;
fontPoints=points;
terminalView.setFont(displayFont,fontPoints);
sshView.setFont(displayFont,fontPoints);
for(auto &panel:panels)
{
if(panel.path) SendMessageW(panel.path,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
@@ -1533,6 +1577,7 @@ void swapPanels(HWND window)
std::swap(panels[0],panels[1]);
active=1-active;
if(quickViewWindow) quickViewSource=1-quickViewSource;
if(sshPrompt) sshPrompt->panel=1-sshPrompt->panel;
for(auto &command:terminalCommands)
if(command.panel>=0) command.panel=1-command.panel;
for(int i=0;i<2;++i)
@@ -1573,19 +1618,23 @@ 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 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)
@@ -1602,7 +1651,7 @@ void layout(HWND window,bool activeOnly)
place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), 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 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);
@@ -1651,8 +1700,11 @@ void layout(HWND window,bool activeOnly)
}
if(!showOutput) clearTerminalSelection();
ShowWindow(terminalOutput,showOutput?SW_SHOWNA:SW_HIDE);
ShowWindow(status,terminalVisible?SW_HIDE:SW_SHOWNA);
terminalView.layout(terminalOutput,showOutput,terminalBottom-4);
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;
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
{
@@ -1661,6 +1713,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)
{
@@ -1672,10 +1725,11 @@ void layout(HWND window,bool activeOnly)
SetWindowPos(preview,nullptr,left+5,4,std::max(0,right-left-10),
std::max(0,panelBottom+summaryHeight+textHeight),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);
}
@@ -1717,7 +1771,12 @@ void showTerminal(HWND owner,bool show)
{
terminalVisible=show;
layout(owner);
SetFocus(terminalInput);
if(show && sshPrompt && sshPrompt->raw)
{
sshView.focus();
sshView.post(L"ssh-focus");
}
else SetFocus(terminalInput);
}
void open(Panel &panel,const fs::path &directory,bool offerElevation);
@@ -2044,7 +2103,7 @@ void clearTerminalSelection()
{
if(terminalSelection.empty()) return;
terminalSelection.clear();
terminalView.post(L"clear-selection");
activeTerminalView().post(L"clear-selection");
}
bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure)
@@ -2056,6 +2115,8 @@ bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure)
bool interruptTerminal()
{
if(sshPrompt)
return sshPrompt->raw && sshTerminal.write("\x03");
if(remoteCommandRunning)
{
remoteCommandThread.request_stop();
@@ -2111,6 +2172,37 @@ std::vector<fs::path> selectedPanelPaths(const Panel &panel)
return paths;
}
bool remoteSearchResults(const Panel &panel)
{
return panel.findOrigin && (panel.peer || panel.ftp);
}
bool remoteSearchActionAvailable(int command)
{
const auto &panel=panels[active];
if(!remoteSearchResults(panel)) return true;
if(command==110 || command==116) return true;
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.scanRequest || command==115) return false;
if(command==112)
{
const auto entry=panel.metadata.find(panel.rows[row]);
return entry!=panel.metadata.end() && !(entry->second.attributes&FILE_ATTRIBUTE_READONLY);
}
if(command==114 && panel.ftp)
{
const auto marked=std::find(panel.marked.begin(),panel.marked.end(),true);
return marked==panel.marked.end() || std::find(std::next(marked),panel.marked.end(),true)==panel.marked.end();
}
if(command==113 || command==114)
{
const auto &destination=panels[1-active];
return !quickViewWindow && !destination.findOrigin && !destination.archive && !destination.ftp &&
(!panel.ftp || !destination.peer) && !destination.directory.empty();
}
return true;
}
void copyPanelNames(HWND owner)
{
const auto &panel=panels[active];
@@ -2260,16 +2352,22 @@ void handleTerminalPromptInput(HWND owner,std::wstring_view action)
SendMessageW(terminalInput,character?WM_CHAR:WM_KEYDOWN,key->second,0);
}
bool ensureTerminalView(HWND owner)
void acceptSshDirectory(HWND owner,std::wstring_view message);
bool ensureTerminalView(HWND owner,bool ssh=false)
{
if(!terminalViewRequested)
auto &view=ssh?sshView:terminalView;
auto &requested=ssh?sshViewRequested:terminalViewRequested;
if(!requested)
{
terminalViewRequested=terminalView.create(terminalOutput,[owner](const std::wstring &message)
requested=view.create(terminalOutput,[owner,ssh](const std::wstring &message)
{
auto &source=ssh?sshView:terminalView;
if(message==L"ready")
{
terminalView.setFont(displayFont,fontPoints);
if(terminalTrace.is_open()) terminalView.enableTrace(traceTerminalOutput);
source.setFont(displayFont,fontPoints);
if(ssh) source.post(L"ssh-reset");
if(terminalTrace.is_open() && !ssh) source.enableTrace(traceTerminalOutput);
}
else if(traceTerminalOutput && terminalTrace.is_open() && message.starts_with(L"output:"))
terminalTrace<<"output "<<ks::utf8(message.substr(7))<<std::endl;
@@ -2283,7 +2381,14 @@ bool ensureTerminalView(HWND owner)
traceTerminal(events[phase],height,rows,viewport,base,offset);
}
}
else if(message.starts_with(L"directory:"))
else if(ssh && message.starts_with(L"ssh-directory:"))
acceptSshDirectory(owner,std::wstring_view(message).substr(14));
else if(ssh && message.starts_with(L"ssh-input:"))
{
if(sshPrompt && sshPrompt->raw && GetForegroundWindow()==owner && commandLineAvailable(owner))
sshTerminal.write(ks::utf8(message.substr(10)));
}
else if(!ssh && message.starts_with(L"directory:"))
{
const auto directory=message.substr(10);
if(!terminalCommands.empty())
@@ -2302,8 +2407,14 @@ bool ensureTerminalView(HWND owner)
}
terminalDirectory=directory;
}
else if(message.starts_with(L"selection:")) terminalSelection=message.substr(10);
else if(message.starts_with(L"prompt:")) handleTerminalPromptInput(owner,std::wstring_view(message).substr(7));
else if(message.starts_with(L"selection:"))
{
if(ssh==sshPrompt.has_value()) terminalSelection=message.substr(10);
}
else if(message.starts_with(L"prompt:"))
{
if(ssh==sshPrompt.has_value()) handleTerminalPromptInput(owner,std::wstring_view(message).substr(7));
}
else if(message==L"insert-path") insertCurrentPanelPath();
else if(message==L"insert-name") insertCurrentPanelPath(true);
else if(message==L"copy-command-line" && GetForegroundWindow()==owner && commandLineAvailable(owner))
@@ -2322,16 +2433,24 @@ bool ensureTerminalView(HWND owner)
if(swscanf_s(message.c_str()+5,L"%d,%d",&columns,&rows)==2 &&
columns>=2 && columns<=32767 && rows>=2 && rows<=32767)
{
terminalSize={static_cast<SHORT>(columns),static_cast<SHORT>(rows)};
terminal.resize(terminalSize);
const COORD size{static_cast<SHORT>(columns),static_cast<SHORT>(rows)};
if(ssh) {sshSize=size;sshTerminal.resize(size);}
else {terminalSize=size;terminal.resize(size);}
}
}
},[owner]
},[owner,ssh]
{
showTerminal(owner,false);
if(ssh)
{
sshTerminal.stop();
sshPrompt.reset();
sshViewRequested=false;
sshView.close();
}
if(ssh || !sshPrompt) showTerminal(owner,false);
setStatus(L"Could not initialize the terminal view.");
});
if(!terminalViewRequested)
},false,{},ssh);
if(!requested)
{
setStatus(L"WebView2 and the local terminal assets are required.");
return false;
@@ -2340,8 +2459,11 @@ bool ensureTerminalView(HWND owner)
return true;
}
#include "files_ssh_prompt.inl"
bool startTerminal(HWND owner,const fs::path &directory)
{
closeSshPrompt(owner);
if(terminal.alive()) return true;
if(!ensureTerminalView(owner)) return false;
if(terminal.start(directory.c_str(),terminalSize))
@@ -2356,12 +2478,16 @@ bool startTerminal(HWND owner,const fs::path &directory)
bool showCommandOutput(HWND owner,const Panel &panel)
{
if(panel.ftp && panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty())
return startSshTerminal(owner,panel);
closeSshPrompt(owner);
if(panel.archive) return startTerminal(owner,panel.archive->file.parent_path());
return panel.peer || panel.ftp?ensureTerminalView(owner):startTerminal(owner,panel.directory);
}
void updateTerminalOutput()
void updateTerminalOutput(HWND owner)
{
updateSshTerminal(owner);
if(!terminalView.initialized()) return;
const auto bytes=terminal.takeOutput();
if(!bytes.empty()) terminalView.send(bytes);
@@ -2396,9 +2522,12 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
}
if(panel.ftp)
{
setStatus(std::wstring(L"Shell commands are unavailable in ")+transferProtocolName(panel.ftp->protocol)+L" panels.");
if(panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty())
return submitSshCommand(owner,panel,value);
setStatus(L"Shell commands require a connected SFTP, LAN or local folder.");
return false;
}
closeSshPrompt(owner);
if(remoteCommandRunning)
{
constexpr auto busy=L"A remote command is running. Clear the command line and press Escape to cancel it.";
@@ -2476,7 +2605,7 @@ void runCommandLine()
{
const auto value=terminalInputText();
if(!submitTerminalCommand(panels[active],value)) return;
terminalView.post(L"scroll-bottom");
activeTerminalView().post(L"scroll-bottom");
if(value.find_first_not_of(L" \t\r\n")!=value.npos)
{
rememberCommand(value);
@@ -2565,6 +2694,8 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U
void updateSelectionSummary(const Panel &panel)
{
if(&panel==&panels[active] && remoteSearchResults(panel))
for(const auto key:commands) InvalidateRect(key,nullptr,FALSE);
const bool hadSummary=hasSelectionSummary();
size_t marked=0,unmeasured=0;
uint64_t total=0;
@@ -2652,6 +2783,8 @@ std::wstring folderMeasurementText(const Panel &panel,const fs::path &path,size_
void showFileDetails(const Panel &panel)
{
refreshQuickView(panel);
if(&panel==&panels[active])
for(const auto key:commands) InvalidateRect(key,nullptr,FALSE);
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
if(panel.remoteRetry)
{
@@ -2661,7 +2794,11 @@ void showFileDetails(const Panel &panel)
if(panel.findOrigin)
{
const auto error=panel.findOrigin->error;
setStatus(std::to_wstring(panel.rows.size())+(error==ERROR_CANCELLED?L" matches (stopped)":
const auto count=std::to_wstring(panel.rows.size());
if(error==ERROR_CONNECTION_ABORTED)
setStatus(count+(panel.rows.size()==1?L" match":L" matches")+
L" · Connection interrupted · Ctrl+R Retry · Esc Back");
else setStatus(count+(error==ERROR_CANCELLED?L" matches (stopped)":
error?L" matches (some folders could not be read)":L" matches")+
L" · Enter: Go · Esc: Back");
return;
@@ -2778,6 +2915,7 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
error=ftp.list(directory.empty()?ftpInitialDirectory:directory,[&](const fs::path &path,const FileInfo &info)
{
if(!metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size,info.modified}).second) return true;
if(info.transfer) columnMetadata[path].transfer=info.transfer;
(info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
return !stop.stop_requested();
@@ -2897,6 +3035,14 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
const bool sameDirectory=sameFolderPath(previousDirectory,directory,provider);
auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan;
const bool partial=error==ERROR_CANCELLED;
if(error==ERROR_CONNECTION_ABORTED && request.find && panel.findOrigin && sameDirectory && files.empty() &&
request.find->mask==panel.findOrigin->options.mask &&
request.find->includeHidden==panel.findOrigin->options.includeHidden)
{
panel.findOrigin->error=error;
if(&panel==&panels[active]) showFileDetails(panel);
return true;
}
if(!failure.empty())
{
if((!peer && !request.ftp) || &panel==&panels[active]) setStatus(failure);
@@ -3048,7 +3194,11 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
if(renderTree) appendTreeRows(panel,rows);
else if(finding)
{
for(const auto &file:files) add(file,file.lexically_relative(directory).native(),false);
for(const auto &file:files)
{
const auto relative=file.lexically_relative(directory);
add(file,panel.ftp?ftpPath(relative):relative.native(),false);
}
}
else
{
@@ -3144,7 +3294,8 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
if(directory.empty() && !ftp) return;
panel.remoteRetry.reset();
if(!panel.view.revealedFile.empty() &&
(peer || ftp || panel.view.revealedFile.parent_path()!=directory)) panel.view.revealedFile.clear();
(panel.view.revealedFile.parent_path()!=folderPathWithoutSeparator(directory) ||
(!samePanelSource(panel,peer,ftp) && panel.view.revealedFile!=selection))) panel.view.revealedFile.clear();
if(directory!=panel.directory || !samePanelSource(panel,peer,ftp))
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback),
@@ -3184,7 +3335,7 @@ void collectDirectoryScans()
try
{
auto result=panel.scan.get();
if(!result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested())
if(!request.find && !result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested())
{
retry=Panel::RemoteRetry{{request.directory,request.selection,usesFtp?request.ftp->id:std::string{},
request.peer,request.navigationPosition,usesFtp?request.ftp->protocol:TransferProtocol::ftp},
@@ -3570,7 +3721,7 @@ void collectFolderSizes(Panel &panel)
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false);
ks::files::TextDialogs textWindowDialogs();
void findLocalFiles(HWND owner,Panel &panel);
void findPanelFiles(HWND owner,Panel &panel);
void compareSelectedFiles(HWND owner);
void createArchive(HWND owner,Panel &panel);
void addToArchive(HWND owner,Panel &panel,std::vector<fs::path> sources);
@@ -3690,6 +3841,14 @@ bool driveSourceRow(LRESULT row)
row==sftpDriveRow() || row==smbDriveRow() || row==recentDriveRow());
}
bool panelItemPropertiesAvailable(const Panel &panel);
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);
bool selectablePickerRow(LRESULT row)
{
if(row<0) return false;
@@ -3730,13 +3889,17 @@ void selectDrive()
else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true);
else if(menuIndex==2 && (row==6 || row==7)) runActivePeerAction(owner,row==7);
else if(menuIndex==2 && row==8) compareSelectedFiles(owner);
else if(menuIndex==2 && row==9) findLocalFiles(owner,panels[active]);
else if(menuIndex==2 && row==9) findPanelFiles(owner,panels[active]);
else if(menuIndex==2 && row==10) toggleQuickView(owner);
else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]);
else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]);
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==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]);
else
{
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
@@ -4464,7 +4627,8 @@ void enter(Panel &panel)
}
if(panel.findOrigin)
{
revealLocalFile(panel,target);
panel.view.revealedFile=target;
openOn(panel,target.parent_path(),false,panel.peer,target,{},panel.ftp);
return;
}
if(panel.sizes[row]==L"Folder" && toggleTreeRow(panel,static_cast<size_t>(row))) return;
@@ -4927,12 +5091,17 @@ LRESULT CALLBACK paintFarCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UIN
const auto dc=message==WM_PAINT?BeginPaint(control,&paint):reinterpret_cast<HDC>(wp);
RECT bounds{};
GetClientRect(control,&bounds);
wchar_t label[64]{};
std::wstring label;
const auto selected=SendMessageW(control,CB_GETCURSEL,0,0);
if(selected!=CB_ERR) SendMessageW(control,CB_GETLBTEXT,selected,reinterpret_cast<LPARAM>(label));
const auto length=selected==CB_ERR?CB_ERR:SendMessageW(control,CB_GETLBTEXTLEN,selected,0);
if(length>=0)
{
label.resize(static_cast<size_t>(length)+1);
SendMessageW(control,CB_GETLBTEXT,selected,reinterpret_cast<LPARAM>(label.data()));
}
const auto parts=farDropDownBounds(bounds);
const bool enabled=IsWindowEnabled(control)!=FALSE;
paintFarDropDownText(dc,parts.field,label,enabled);
paintFarDropDownText(dc,parts.field,label.c_str(),enabled);
ks::files::paintFarFieldArrow(dc,parts.arrow,enabled,GetDpiForWindow(control));
if(GetFocus()==control) DrawFocusRect(dc,&parts.field);
if(message==WM_PAINT) EndPaint(control,&paint);
@@ -5816,7 +5985,7 @@ void showFileOperationError(HWND owner,const wchar_t *title,const std::wstring &
setStatus(L"");
const auto choice=showFilesNotice(owner,message.c_str(),title,
{.tone=FilesNoticeTone::warning,.processes=!lockPaths.empty()});
if(choice==showProcessesButton) showLockProcesses(owner,std::move(lockPaths));
if(choice==showProcessesButton) showProcesses(owner,std::move(lockPaths));
}
void showTextMessage(HWND owner,const wchar_t *text)
@@ -6072,33 +6241,59 @@ ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile)
{
auto identity=Json::array({ks::utf8(transferProtocolName(profile.protocol)),ks::utf8(ks::lower(profile.host)),
profile.port,ks::utf8(profile.user)}).dump();
return {std::move(identity),profile.name,
[profile](const fs::path &path,const fs::path &cache,bool edit,
const auto reader=[profile](SftpAccess access) -> ks::files::RemoteTextSource::Download
{
return [profile,access](const fs::path &path,const fs::path &cache,bool edit,
const ks::files::RemoteTextSource::Progress &progress,uint64_t limit)
{
requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED);
TransferSession ftp(profile);
TransferSession ftp(profile,access);
const auto info=transferEntry(transferChildren(ftp,path.parent_path()),path);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_NOT_SUPPORTED);
const bool editable=!(info->attributes&FILE_ATTRIBUTE_READONLY);
const bool editable=access!=SftpAccess::sudoRead && !(info->attributes&FILE_ATTRIBUTE_READONLY);
if(edit && !editable) throw std::runtime_error("The "+ks::utf8(transferProtocolName(profile.protocol))+" file is read-only.");
if(info->size>limit) throw std::system_error(ERROR_FILE_TOO_LARGE,std::system_category());
FilesConnection local;
downloadTransferFile(ftp,local,path,cache,*info,false,progress);
return ks::files::RemoteTextRevision{info->size,info->modified,editable};
},
[profile](const fs::path &path,const fs::path &cache,const ks::files::RemoteTextRevision &expected)
};
};
const auto write=[profile](SftpAccess access,const fs::path &path,const fs::path &cache,
const ks::files::RemoteTextRevision &expected,const ks::files::RemoteTextSource::Progress &progress)
{
requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED);
FilesConnection local;
const auto info=statFile(local,cache);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
TransferSession ftp(profile,access);
requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED);
const auto result=uploadTransferFile(local,ftp,cache,path,*info,true,progress,&expected);
return ks::files::RemoteTextRevision{result.size,result.modified,expected.editable};
};
ks::files::RemoteTextSource source{std::move(identity),profile.name,reader(SftpAccess::normal),
[write](const auto &path,const auto &cache,const auto &expected)
{
FilesConnection local;
const auto info=statFile(local,cache);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
TransferSession ftp(profile);
const auto result=uploadTransferFile(local,ftp,cache,path,*info,true,
[](uint64_t,uint64_t){return true;},&expected);
return ks::files::RemoteTextRevision{result.size,result.modified,expected.editable};
return write(SftpAccess::normal,path,cache,expected,{});
}};
if(profile.protocol==TransferProtocol::sftp && !profile.sudoSftpServer.empty())
{
source.elevation=ks::files::RemoteTextSource::Elevation{reader(SftpAccess::sudoRead),
[write](const auto &path,const auto &cache,const auto &expected,const auto &progress)
{
return write(SftpAccess::sudoWrite,path,cache,expected,progress);
},[name=profile.name](HWND owner,const fs::path &path,bool write)
{
const auto action=write?L"Retry this save with temporary sudo write access?":
L"Open this file with temporary read-only sudo access?";
const auto message=std::wstring(L"The SFTP server denied access.\r\n\r\n")+action+
L"\r\n\r\n"+name+L" · "+ftpPath(path);
return showFilesNotice(owner,message.c_str(),write?L"SFTP save with sudo":L"SFTP read with sudo",
{.confirm=true})==IDYES;
}};
}
return source;
}
bool countCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
@@ -6350,20 +6545,20 @@ struct ArchiveStaging
}
};
void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector<fs::path> external={},
fs::path targetFolder={})
void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector<fs::path> explicitItems={},
fs::path targetFolder={},bool renameHere=false)
{
const auto sourceFtp=source.ftp;
const bool ftpRename=move && sourceFtp && !transferProfileList(source);
const auto archive=source.archive?source.archive->file:fs::path{};
auto archiveDirectory=archive.empty()?fs::path{}:source.directory.lexically_relative(archive);
if(archiveDirectory==L".") archiveDirectory.clear();
if(quickViewWindow && &destination!=&panels[quickViewSource] && !ftpRename)
if(quickViewWindow && &destination!=&panels[quickViewSource] && !ftpRename && !renameHere)
{
setStatus(L"Close Quick View to use the destination pane.");
return;
}
if(destination.findOrigin && !ftpRename)
if(destination.findOrigin && !ftpRename && !renameHere)
{
setStatus(L"Open a destination folder in the other panel before copying or moving files.");
return;
@@ -6377,7 +6572,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
{
if(move || source.archive || source.peer || source.ftp)
setStatus(L"Use F5 from a local folder to add files to an archive.");
else addToArchive(owner,destination,external.empty()?selectedPanelPaths(source):std::move(external));
else addToArchive(owner,destination,explicitItems.empty()?selectedPanelPaths(source):std::move(explicitItems));
return;
}
if(!archive.empty() && (move || destination.peer || destination.ftp))
@@ -6403,7 +6598,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
CopyRequest request{{},targetFolder};
request.move=move;
request.ftpRename=ftpRename;
request.externalSources=!external.empty();
request.externalSources=!explicitItems.empty() && !renameHere;
request.archiveSource=!archive.empty();
if(ftp)
{
@@ -6413,12 +6608,16 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
request.otherDirectory=ftpRename?destination.directory:targetFolder;
request.sourcePeer=source.peer?&*source.peer:nullptr;
request.otherPeer=request.destinationPeer=destination.peer?&*destination.peer:nullptr;
request.sources=request.externalSources?std::move(external):selectedPanelPaths(source);
request.sources=explicitItems.empty()?selectedPanelPaths(source):std::move(explicitItems);
if(request.sources.empty()) return;
if(ftpRename && request.sources.size()!=1)
if(ftpRename)
{
setStatus(L"Select one remote file or folder to rename.");
return;
if(request.sources.size()!=1)
{
setStatus(L"Select one remote file or folder to rename.");
return;
}
request.destination=request.sources.front().parent_path();
}
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(ftpRename?113:102),owner,copyDialog,
reinterpret_cast<LPARAM>(&request));
@@ -6492,6 +6691,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category());
if(progress.canceled) return;
sourceHost.ftp->rename(path,target);
if(fromSearch) removed.insert(path);
++copied;
++progress.files;
++progress.totalFiles;
@@ -6969,7 +7169,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
}
else host.remove(current,permanent,attributes,readOnly);
++done;
if(!panel.peer && !ftp) removed.insert(current);
removed.insert(current);
}
catch(const std::system_error &e)
{
@@ -6989,8 +7189,12 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
progressDialog.close();
for(auto &visible:panels)
{
if(treePanelActive(visible) && samePanelSource(panel,visible.peer,visible.ftp)) pruneTreeMarks(visible,removed);
if(visible.findOrigin) pruneSearchResults(visible,removed);
const bool sameSource=samePanelSource(panel,visible.peer,visible.ftp);
if(treePanelActive(visible) && sameSource) pruneTreeMarks(visible,removed);
if(visible.findOrigin)
{
if(sameSource) pruneSearchResults(visible,removed);
}
else if(!visible.directory.empty()) open(visible,visible.directory);
}
SetFocus(panel.list);
@@ -7452,12 +7656,26 @@ void openOrCreateText(HWND owner,const Panel &panel)
void editTransferProfile(Panel &panel,bool create);
#include "files_drag_drop.inl"
#include "files_properties.inl"
#include "files_context_menu.inl"
LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
const auto index=GetDlgCtrlID(window)-102;
if(message==WM_NCDESTROY) RevokeDragDrop(window);
if(message==WM_CAPTURECHANGED) panelDragStart.reset();
if(message==WM_CONTEXTMENU)
{
showPanelContextMenu(window,lp);
return 0;
}
if(message==WM_RBUTTONUP)
{
POINT screen{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
ClientToScreen(window,&screen);
showPanelContextMenu(window,MAKELPARAM(screen.x,screen.y));
return 0;
}
if(message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window && panelDragStart)
{
const auto dpi=GetDpiForWindow(window);
@@ -7731,23 +7949,57 @@ void openMenu(HWND window, int index)
if(detailedPanel(panel)) rows.push_back(L" Columns…");
}
}
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10",L"Pack files…\tAlt+F5"};
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10",L"Pack files…\tAlt+F5",
L"Properties…\tCtrl+A",L"Locking processes…"};
else if(index==2)
{
rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
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"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…",
L"Git Changes…"};
}
const auto &panel=panels[active];
const bool remoteResults=remoteSearchResults(panel);
const auto resultRow=remoteResults?currentPanelRow(panel):LB_ERR;
commandActions.clear();
if(index==2)
if(index==1 && remoteResults)
{
if(remoteSearchActionAvailable(113)) commandActions.push_back(0);
if(remoteSearchActionAvailable(114))
{
if(panel.ftp) rows[1]=L"Rename\tF6";
commandActions.push_back(1);
}
commandActions.push_back(3);
if(panelItemPropertiesAvailable(panel)) commandActions.push_back(5);
}
else if(index==1)
{
commandActions={0,1,2,3,4};
if(panelItemPropertiesAvailable(panel)) commandActions.push_back(5);
if(panelLockSearchAvailable(panel)) commandActions.push_back(6);
}
else if(index==2)
{
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
if(!panels[active].peer && !panels[active].ftp)
if(!terminalVisible) commandActions.push_back(15);
if(gitChangesAvailable(panel)) commandActions.push_back(16);
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);
if(remoteResults)
{
commandActions.insert(commandActions.begin()+1,9);
if(!terminalVisible) commandActions.insert(commandActions.begin()+2,12);
CompareFile comparison[2];
const auto view=remoteSearchActionAvailable(111);
const auto edit=remoteSearchActionAvailable(112);
const auto compare=view && selectedComparisonFiles(comparison);
std::erase_if(commandActions,[&](int action)
{
return action==4 || action==5 || (action==2 && !edit) || (action==8 && !compare) ||
(!view && (action==1 || action==13)) || (resultRow==LB_ERR && action==11);
});
}
if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10);
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
@@ -7936,8 +8188,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);
}
@@ -7958,6 +8218,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);
@@ -8020,7 +8281,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
if(pendingPeerAction.valid() &&
pendingPeerAction.wait_for(std::chrono::seconds(0))==std::future_status::ready)
setStatus(pendingPeerAction.get());
updateTerminalOutput();
updateTerminalOutput(window);
updateCompletion(window);
return 0;
}
@@ -8397,6 +8658,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
{
if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp)
text=L"F6 Rename";
const auto separator=text.find(L' ');
auto key=text.substr(0,separator);
if(key.starts_with(L'F') && key.size()>1) key.erase(0,1);
@@ -8405,7 +8668,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
action.left=shortcut.right;
paintText(item.hDC,shortcut,key.c_str(),RGB(184,184,184),RGB(0,0,0));
if(action.left<action.right)
paintText(item.hDC,action,text.c_str()+separator+1,colors[Selection],colors[Footer]);
paintText(item.hDC,action,remoteSearchActionAvailable(item.CtlID)?text.c_str()+separator+1:L"",
colors[Selection],colors[Footer]);
return TRUE;
}
const bool popupRow=item.hwndItem==picker || item.hwndItem==completionList;
@@ -8690,7 +8954,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
if (HIWORD(wp) == BN_CLICKED)
{
for(const auto &command:keyBar)
if(LOWORD(wp)==command.id) SendMessageW(panels[active].list,WM_KEYDOWN,command.key,0);
if(LOWORD(wp)==command.id && remoteSearchActionAvailable(command.id))
SendMessageW(panels[active].list,WM_KEYDOWN,command.key,0);
}
if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_DBLCLK)
enter(panels[LOWORD(wp) - 102]);
@@ -8731,6 +8996,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);
@@ -8741,6 +9007,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
stopTreeBranches(panel);
panel.watch.reset();
}
sshTerminal.stop();
sshView.close();
terminalView.close();
terminal.close();
if(remoteCommandThread.joinable())
@@ -8838,7 +9106,26 @@ 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) &&
(message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list) &&
!(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
(message.wParam==VK_APPS || (message.wParam==VK_F10 && (GetKeyState(VK_SHIFT)&0x8000))))
{
if(!(message.lParam & (1LL<<30))) showPanelContextMenu(
message.hwnd==terminalInput?panels[active].list:message.hwnd,-1);
continue;
}
if(message.hwnd==terminalInput && message.message==WM_KEYDOWN &&
!(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) &&
!(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) &&
@@ -8872,7 +9159,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
}
if(panel.findOrigin && !panel.scanRequest)
{
openOn(panel,panel.directory,false,{});
open(panel,panel.directory);
continue;
}
if(panel.folderSizeJob)
@@ -8896,7 +9183,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
hidePicker();
showMenu(false);
if(message.wParam==VK_F5) createArchive(window,panels[active]);
else findLocalFiles(window,panels[active]);
else findPanelFiles(window,panels[active]);
}
continue;
}
@@ -9021,6 +9308,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
if(!(message.lParam & (1LL<<30))) copyFullPanelPath(window,panels[active]);
continue;
}
if(ctrl && !shift && message.wParam=='A' && !terminalVisible && commandLineAvailable(window) &&
(!GetWindowTextLengthW(terminalInput) || panelFocused) && panelItemPropertiesAvailable(panels[active]))
{
if(!(message.lParam&(1LL<<30))) showPanelItemProperties(window,panels[active]);
continue;
}
if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible)
{
if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window))
+244
View File
@@ -0,0 +1,244 @@
constexpr int propertiesName=580, propertiesFirstDetail=581, propertiesOtherFlags=586;
constexpr int propertiesFirstFlag=587, propertiesDivider=592;
constexpr DWORD propertyOpenFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
constexpr DWORD editablePropertyFlags[]{
FILE_ATTRIBUTE_READONLY,FILE_ATTRIBUTE_HIDDEN,FILE_ATTRIBUTE_SYSTEM,FILE_ATTRIBUTE_ARCHIVE,
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED};
struct FilePropertyFlag
{
DWORD flag;
const wchar_t *name;
};
std::wstring propertyFlagNames(DWORD flags)
{
constexpr FilePropertyFlag names[]{
{FILE_ATTRIBUTE_READONLY,L"Read-only"},{FILE_ATTRIBUTE_HIDDEN,L"Hidden"},
{FILE_ATTRIBUTE_SYSTEM,L"System"},{FILE_ATTRIBUTE_DIRECTORY,L"Directory"},
{FILE_ATTRIBUTE_ARCHIVE,L"Archive"},{FILE_ATTRIBUTE_NORMAL,L"Normal"},
{FILE_ATTRIBUTE_TEMPORARY,L"Temporary"},{FILE_ATTRIBUTE_SPARSE_FILE,L"Sparse"},
{FILE_ATTRIBUTE_REPARSE_POINT,L"Reparse point"},{FILE_ATTRIBUTE_COMPRESSED,L"Compressed"},
{FILE_ATTRIBUTE_OFFLINE,L"Offline"},{FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,L"Not indexed"},
{FILE_ATTRIBUTE_ENCRYPTED,L"Encrypted"},{FILE_ATTRIBUTE_INTEGRITY_STREAM,L"Integrity stream"},
{FILE_ATTRIBUTE_NO_SCRUB_DATA,L"No scrub"},{FILE_ATTRIBUTE_PINNED,L"Pinned"},
{FILE_ATTRIBUTE_UNPINNED,L"Unpinned"}};
std::wstring text;
const auto append=[&](std::wstring_view name)
{
if(!text.empty()) text+=L", ";
text+=name;
};
for(const auto &[flag,name]:names)
if(flags&flag)
{
append(name);
flags&=~flag;
}
if(flags)
{
wchar_t number[16]{};
swprintf_s(number,L"0x%08lX",static_cast<unsigned long>(flags));
append(number);
}
return text.empty()?L"—":text;
}
std::wstring propertyDate(uint64_t ticks)
{
const auto time=localFileTime(ticks);
if(!time) return L"—";
wchar_t label[32]{};
swprintf_s(label,L"%04u-%02u-%02u %02u:%02u:%02u",unsigned(time->wYear),unsigned(time->wMonth),
unsigned(time->wDay),unsigned(time->wHour),unsigned(time->wMinute),unsigned(time->wSecond));
return label;
}
struct ItemProperties
{
std::wstring name, owner;
uint64_t created{}, modified{}, accessed{}, changed{};
DWORD flags{}, requested{};
std::vector<std::wstring> details(bool includeMissing) const
{
std::vector<std::wstring> rows;
if(includeMissing || !owner.empty()) rows.push_back(L"Owner "+(owner.empty()?L"—":owner));
const auto date=[&](const wchar_t *label,uint64_t value)
{
if(includeMissing || value) rows.push_back(label+propertyDate(value));
};
date(L"Created ",created);
date(L"Modified ",modified);
date(L"Accessed ",accessed);
date(L"Changed ",changed);
return rows;
}
};
INT_PTR CALLBACK itemPropertiesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &properties=*reinterpret_cast<ItemProperties*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,propertiesName);
SetDlgItemTextW(dialog,propertiesName,properties.name.c_str());
const auto details=properties.details(true);
for(size_t index=0;index<details.size();++index)
SetDlgItemTextW(dialog,propertiesFirstDetail+static_cast<int>(index),details[index].c_str());
auto other=properties.flags&~FILE_ATTRIBUTE_NORMAL;
for(size_t index=0;index<std::size(editablePropertyFlags);++index)
{
const auto flag=editablePropertyFlags[index];
const auto id=propertiesFirstFlag+static_cast<int>(index);
installFarCheckbox(GetDlgItem(dialog,id),FarCheckboxSurface::gray);
CheckDlgButton(dialog,id,(properties.flags&flag)?BST_CHECKED:BST_UNCHECKED);
other&=~flag;
}
SetDlgItemTextW(dialog,propertiesOtherFlags,(L"Other flags "+propertyFlagNames(other)).c_str());
layoutDialogButtons(dialog,propertiesDivider,{IDOK,IDCANCEL});
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &properties=*reinterpret_cast<ItemProperties*>(GetWindowLongPtrW(dialog,DWLP_USER));
for(size_t index=0;index<std::size(editablePropertyFlags);++index)
if(IsDlgButtonChecked(dialog,propertiesFirstFlag+static_cast<int>(index))==BST_CHECKED)
properties.requested|=editablePropertyFlags[index];
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" Properties ",false,{propertiesDivider});
}
void showReadOnlyProperties(HWND owner,const ItemProperties &properties,const std::wstring &attributes)
{
auto text=properties.name+L"\r\n\r\n";
for(const auto &line:properties.details(false)) text+=line+L"\r\n";
text+=attributes;
showFilesNotice(owner,text.c_str(),L"Properties",{.tone=FilesNoticeTone::neutral});
}
bool panelItemPropertiesAvailable(const Panel &panel)
{
const auto row=currentPanelRow(panel);
return row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel);
}
void showSourceItemProperties(HWND owner,const Panel &panel,const fs::path &path,ItemProperties properties)
{
const auto found=panel.metadata.find(path);
if(found==panel.metadata.end()) return;
const auto &entry=found->second;
properties.modified=entry.modified;
if(panel.peer)
{
showReadOnlyProperties(owner,properties,L"Attributes "+propertyFlagNames(entry.attributes));
return;
}
auto attributes=(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)?std::wstring(L"Folder"):
(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)?std::wstring(L"Special file"):std::wstring(L"File");
if(panel.archive && panel.archive->entries)
{
const auto &members=*panel.archive->entries;
if(const auto member=members.find(path.lexically_relative(panel.archive->file));member!=members.end())
{
properties.owner=member->second.owner;
properties.created=member->second.created;
properties.accessed=member->second.accessed;
if(member->second.encrypted) attributes+=L", Encrypted";
}
}
else if(const auto extra=panel.columnMetadata.find(path);
extra!=panel.columnMetadata.end() && extra->second.transfer)
{
const auto &details=*extra->second.transfer;
properties.created=details.created;
properties.accessed=details.accessed;
if(details.owner) properties.owner=L"UID "+std::to_wstring(*details.owner);
if(details.permissions)
{
wchar_t mode[12]{};
swprintf_s(mode,L"%04o",static_cast<unsigned>(*details.permissions));
attributes+=std::wstring(L"\r\nPermissions ")+mode;
}
}
if(panel.ftp && panel.ftp->protocol==TransferProtocol::ftp)
{
const auto flags=entry.attributes&~(FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_DIRECTORY);
if(flags) attributes+=L"\r\nAttributes "+propertyFlagNames(flags);
}
showReadOnlyProperties(owner,properties,L"Type "+attributes);
}
DWORD changeItemProperties(const fs::path &path,HANDLE original,const ItemProperties &properties)
{
DWORD editable{};
for(const auto flag:editablePropertyFlags) editable|=flag;
const DWORD changed=(properties.flags^properties.requested)&editable;
if(!changed) return ERROR_SUCCESS;
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES,columnFileShare,nullptr,
OPEN_EXISTING,propertyOpenFlags,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return GetLastError();
BY_HANDLE_FILE_INFORMATION before{},current{};
if(!GetFileInformationByHandle(original,&before) || !GetFileInformationByHandle(file.value,&current))
return GetLastError();
if(!ks::files::sameFileIdentity(before,current)) return ERROR_FILE_INVALID;
FILE_BASIC_INFO latest{};
if(!GetFileInformationByHandleEx(file.value,FileBasicInfo,&latest,sizeof(latest))) return GetLastError();
if(!((latest.FileAttributes^properties.requested)&changed)) return ERROR_SUCCESS;
FILE_BASIC_INFO update{};
update.FileAttributes=(latest.FileAttributes&~(changed|FILE_ATTRIBUTE_NORMAL))|(properties.requested&changed);
if(!update.FileAttributes) update.FileAttributes=FILE_ATTRIBUTE_NORMAL;
if(!SetFileInformationByHandle(file.value,FileBasicInfo,&update,sizeof(update))) return GetLastError();
return ERROR_SUCCESS;
}
void showPanelItemProperties(HWND owner,Panel &panel)
{
if(!panelItemPropertiesAvailable(panel)) return;
const auto path=panel.rows[currentPanelRow(panel)];
ItemProperties properties{path.filename().native()};
if(panel.ftp || panel.peer || panel.archive)
{
showSourceItemProperties(owner,panel,path,std::move(properties));
return;
}
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,OPEN_EXISTING,
propertyOpenFlags,nullptr)};
FILE_BASIC_INFO info{};
if(file.value==INVALID_HANDLE_VALUE || !GetFileInformationByHandleEx(file.value,FileBasicInfo,&info,sizeof(info)))
{
const auto error=GetLastError();
refreshPanel(panel);
showFileOperationError(owner,L"Could not read properties",fileError({static_cast<int>(error),std::system_category()}));
return;
}
std::map<std::wstring,std::wstring> owners;
properties.owner=localOwnerName(path,owners);
properties.created=info.CreationTime.QuadPart;
properties.modified=info.LastWriteTime.QuadPart;
properties.accessed=info.LastAccessTime.QuadPart;
properties.changed=info.ChangeTime.QuadPart;
properties.flags=info.FileAttributes;
if(windowsNetworkPath(path))
{
showReadOnlyProperties(owner,properties,L"Attributes "+propertyFlagNames(properties.flags));
return;
}
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(125),owner,itemPropertiesDialog,
reinterpret_cast<LPARAM>(&properties))!=IDOK) return;
const auto error=changeItemProperties(path,file.value,properties);
refreshPanel(panel);
if(error!=ERROR_SUCCESS)
showFileOperationError(owner,L"Could not save attributes",error==ERROR_FILE_INVALID?
L"The item was replaced while the properties were open.":
fileError({static_cast<int>(error),std::system_category()}));
}
+229 -42
View File
@@ -6,7 +6,7 @@ void initializeSsh()
if(initialized) throw std::runtime_error("Could not initialize the SSH client.");
}
void connectSftpSocket(ks::lan::WinSocket &connection,const TransferProfile &profile)
void connectSshSocket(ks::lan::WinSocket &connection,const TransferProfile &profile)
{
ADDRINFOW query{};
query.ai_socktype=SOCK_STREAM;
@@ -53,28 +53,66 @@ void connectSftpSocket(ks::lan::WinSocket &connection,const TransferProfile &pro
throw std::system_error(lastError,std::system_category());
}
struct SftpFile
{
LIBSSH2_SFTP_HANDLE *handle{};
explicit SftpFile(LIBSSH2_SFTP_HANDLE *value):handle(value){}
SftpFile(const SftpFile &)=delete;
SftpFile(SftpFile &&other) noexcept:handle(std::exchange(other.handle,nullptr)){}
~SftpFile(){if(handle) libssh2_sftp_close_handle(handle);}
};
using SshChannel=std::unique_ptr<LIBSSH2_CHANNEL,decltype(&libssh2_channel_free)>;
class SftpSession
class SshConnection
{
struct Tunnel
{
SshChannel channel;
LIBSSH2_SESSION *parent;
struct Nonblocking
{
LIBSSH2_SESSION *parent;
int previous;
explicit Nonblocking(LIBSSH2_SESSION *session):
parent(session),previous(libssh2_session_get_blocking(parent))
{
libssh2_session_set_blocking(parent,0);
}
~Nonblocking(){libssh2_session_set_blocking(parent,previous);}
};
};
struct Hop
{
std::unique_ptr<Tunnel> tunnel;
std::unique_ptr<LIBSSH2_SESSION,decltype(&libssh2_session_free)> session{nullptr,libssh2_session_free};
};
ks::lan::Network network_;
ks::lan::WinSocket socket_;
std::unique_ptr<LIBSSH2_SESSION,decltype(&libssh2_session_free)> session_{nullptr,libssh2_session_free};
std::unique_ptr<LIBSSH2_SFTP,decltype(&libssh2_sftp_shutdown)> sftp_{nullptr,libssh2_sftp_shutdown};
std::optional<std::stop_callback<std::function<void()>>> stopConnection_;
std::vector<Hop> hops_;
std::string fingerprint_;
static LIBSSH2_SEND_FUNC(sendThroughJump)
{
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
// Channel writes drain incoming packets first. A nested transport must
// report when that drain would block so it can still send its own data.
const Tunnel::Nonblocking nonblocking(tunnel.parent);
const auto result=libssh2_channel_write(tunnel.channel.get(),static_cast<const char*>(buffer),length);
return result>=0?result:result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
}
static LIBSSH2_RECV_FUNC(receiveThroughJump)
{
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
const Tunnel::Nonblocking nonblocking(tunnel.parent);
auto *channel=tunnel.channel.get();
const auto result=libssh2_channel_read(channel,static_cast<char*>(buffer),length);
if(result>0) return result;
if(result==0 && libssh2_channel_eof(channel)) return 0;
return result==0 || result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
}
[[noreturn]] void sshError(const char *operation) const
{
char *message{};
int length{};
libssh2_session_last_error(session_.get(),&message,&length,0);
libssh2_session_last_error(session(),&message,&length,0);
throw std::runtime_error(std::string(operation)+(message && length>0?": "+std::string(message,length):""));
}
@@ -95,7 +133,7 @@ class SftpSession
const auto user=ks::utf8(profile.user);
int result{};
if(profile.privateKey.empty())
result=libssh2_userauth_password_ex(session_.get(),user.c_str(),static_cast<unsigned>(user.size()),
result=libssh2_userauth_password_ex(session(),user.c_str(),static_cast<unsigned>(user.size()),
secret.c_str(),static_cast<unsigned>(secret.size()),nullptr);
else
{
@@ -111,7 +149,7 @@ class SftpSession
ks::Bytes publicKey;
std::error_code error;
if(fs::exists(publicPath,error)) publicKey=ks::readFile(publicPath,64*1024);
result=libssh2_userauth_publickey_frommemory(session_.get(),user.c_str(),user.size(),
result=libssh2_userauth_publickey_frommemory(session(),user.c_str(),user.size(),
publicKey.empty()?nullptr:reinterpret_cast<const char*>(publicKey.data()),publicKey.size(),
reinterpret_cast<const char*>(key.data()),key.size(),secret.c_str());
}
@@ -119,24 +157,40 @@ class SftpSession
"SFTP key authentication failed (use RSA PEM without a passphrase, or ECDSA OpenSSH with its .pub file)");
}
static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));}
public:
explicit SftpSession(const TransferProfile &profile,bool probeOnly=false)
void connectHop(const TransferProfile &profile,bool probeOnly,std::stop_token stop)
{
if(!probeOnly && profile.hostFingerprint.empty())
throw std::runtime_error("The SFTP host key is untrusted. Edit the profile and use Test connection to verify it.");
initializeSsh();
connectSftpSocket(socket_,profile);
session_.reset(libssh2_session_init());
if(!session_) throw std::runtime_error("Could not create an SSH session.");
libssh2_session_set_timeout(session_.get(),sftpTimeoutMs);
libssh2_session_set_read_timeout(session_.get(),sftpTimeoutMs/1000);
if(libssh2_session_method_pref(session_.get(),LIBSSH2_METHOD_HOSTKEY,
Hop hop;
if(hops_.empty())
{
connectSshSocket(socket_,profile);
if(stop.stop_possible()) stopConnection_.emplace(stop,[handle=socket_.value] {shutdown(handle,SD_BOTH);});
}
else
{
const auto host=ks::utf8(profile.host);
SshChannel channel(libssh2_channel_direct_tcpip(session(),host.c_str(),profile.port),libssh2_channel_free);
if(!channel) sshError("Could not open an SSH jump tunnel");
hop.tunnel=std::make_unique<Tunnel>(Tunnel{std::move(channel),session()});
}
hop.session.reset(libssh2_session_init_ex(nullptr,nullptr,nullptr,hop.tunnel.get()));
if(!hop.session) throw std::runtime_error("Could not create an SSH session.");
hops_.push_back(std::move(hop));
if(hops_.back().tunnel)
{
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_SEND,
reinterpret_cast<libssh2_cb_generic*>(sendThroughJump));
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_RECV,
reinterpret_cast<libssh2_cb_generic*>(receiveThroughJump));
}
libssh2_session_set_timeout(session(),sftpTimeoutMs);
libssh2_session_set_read_timeout(session(),sftpTimeoutMs/1000);
if(libssh2_session_method_pref(session(),LIBSSH2_METHOD_HOSTKEY,
"ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256") ||
libssh2_session_handshake(session_.get(),socket_.value))
libssh2_session_handshake(session(),socket_.value))
sshError("Could not negotiate an SSH connection");
const auto digest=reinterpret_cast<const BYTE*>(libssh2_hostkey_hash(session_.get(),LIBSSH2_HOSTKEY_HASH_SHA256));
const auto digest=reinterpret_cast<const BYTE*>(libssh2_hostkey_hash(session(),LIBSSH2_HOSTKEY_HASH_SHA256));
if(!digest) throw std::runtime_error("The server did not provide a verifiable SSH host key.");
char fingerprint[64]{};
DWORD length=static_cast<DWORD>(std::size(fingerprint));
@@ -148,19 +202,117 @@ public:
if(!ks::lan::equal(fingerprint_,profile.hostFingerprint))
throw std::runtime_error("The SFTP host key changed. Connection blocked before authentication. Received "+fingerprint_+".");
authenticate(profile);
sftp_.reset(libssh2_sftp_init(session_.get()));
if(!sftp_) sshError("Could not start the SFTP subsystem");
}
void close() noexcept
{
if(socket_.value!=INVALID_SOCKET) shutdown(socket_.value,SD_BOTH);
while(!hops_.empty())
{
auto &hop=hops_.back();
libssh2_session_set_blocking(hop.session.get(),1);
hop.session.reset();
hops_.pop_back();
}
}
public:
explicit SshConnection(const TransferProfile &destination,bool probeOnly=false,std::stop_token stop={})
{
initializeSsh();
const auto profiles=sshProfiles.load();
static const std::vector<TransferProfile> empty;
const auto route=sshRoute(destination,profiles?*profiles:empty);
try
{
for(size_t i=0;i<route.size();++i)
{
requireFileOperation(!stop.stop_requested(),ERROR_CANCELLED);
const auto &profile=route[i];
try {connectHop(profile,probeOnly && i+1==route.size(),stop);}
catch(const std::exception &error)
{
if(route.size()==1) throw;
throw std::runtime_error(ks::utf8(profile.name)+": "+error.what());
}
}
}
catch(...) {close();throw;}
}
~SshConnection(){close();}
LIBSSH2_SESSION *session() const {return hops_.back().session.get();}
const std::string &fingerprint() const {return fingerprint_;}
void nonblocking()
{
for(const auto &hop:hops_) libssh2_session_set_blocking(hop.session.get(),0);
}
[[noreturn]] void operationError(const char *operation) const {sshError(operation);}
};
struct SftpFile
{
LIBSSH2_SFTP_HANDLE *handle{};
explicit SftpFile(LIBSSH2_SFTP_HANDLE *value):handle(value){}
SftpFile(const SftpFile &)=delete;
SftpFile(SftpFile &&other) noexcept:handle(std::exchange(other.handle,nullptr)){}
~SftpFile(){if(handle) libssh2_sftp_close_handle(handle);}
};
using SftpSubsystem=std::unique_ptr<LIBSSH2_SFTP,decltype(&libssh2_sftp_shutdown)>;
fs::path sftpInitialDirectory(LIBSSH2_SFTP *sftp)
{
std::array<char,32768> path{};
const auto length=libssh2_sftp_realpath(sftp,".",path.data(),path.size());
if(length<=0) return {};
auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal();
if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path.");
return value;
}
enum class SftpAccess { normal, sudoRead, sudoWrite };
class SftpSession
{
SshConnection connection_;
const SftpAccess access_;
SftpSubsystem sftp_{nullptr,libssh2_sftp_shutdown};
static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));}
void requireWriteAccess() const
{
if(access_==SftpAccess::sudoRead)
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category(),"The sudo SFTP session is read-only");
}
public:
explicit SftpSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
std::stop_token stop={}):connection_(profile,false,stop),access_(access)
{
if(access==SftpAccess::normal)
{
sftp_.reset(libssh2_sftp_init(connection_.session()));
if(!sftp_) connection_.operationError("Could not start the SFTP subsystem");
return;
}
if(profile.sudoSftpServer.empty() || !validSudoSftpServer(profile.sudoSftpServer))
throw std::runtime_error("Configure the absolute sftp-server path for sudo in this SFTP profile.");
const auto command="sudo -n -- "+ks::utf8(profile.sudoSftpServer)+(access==SftpAccess::sudoRead?" -R":"");
sftp_.reset(libssh2_sftp_init_command(connection_.session(),command.c_str()));
if(!sftp_) connection_.operationError("Could not start sudo SFTP. Verify the sftp-server path and the server's sudo authorization");
}
[[noreturn]] void operationError(const char *operation) const
{
if(libssh2_session_last_errno(session_.get())==LIBSSH2_ERROR_SFTP_PROTOCOL)
if(libssh2_session_last_errno(connection_.session())==LIBSSH2_ERROR_SFTP_PROTOCOL)
{
const auto status=libssh2_sftp_last_error(sftp_.get());
if(status==LIBSSH2_FX_PERMISSION_DENIED)
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category(),operation);
throw ks::files::RemoteAccessDenied(operation);
if(status==LIBSSH2_FX_NO_SUCH_FILE || status==LIBSSH2_FX_NO_SUCH_PATH)
throw std::system_error(ERROR_FILE_NOT_FOUND,std::system_category(),operation);
if(status==LIBSSH2_FX_FILE_ALREADY_EXISTS)
@@ -168,17 +320,14 @@ public:
if(status==LIBSSH2_FX_OP_UNSUPPORTED)
throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category(),operation);
}
sshError(operation);
connection_.operationError(operation);
}
fs::path initialDirectory() const
{
std::array<char,32768> path{};
const auto length=libssh2_sftp_realpath(sftp_.get(),".",path.data(),path.size());
if(length<=0) operationError("Could not resolve the initial SFTP folder");
auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal();
if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path.");
return value;
auto path=sftpInitialDirectory(sftp_.get());
if(path.empty()) operationError("Could not resolve the initial SFTP folder");
return path;
}
DWORD list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop={}) const
@@ -205,15 +354,25 @@ public:
else if(!LIBSSH2_SFTP_S_ISREG(attrs.permissions)) attributes=FILE_ATTRIBUTE_REPARSE_POINT;
if(!(attrs.permissions&0222)) attributes|=FILE_ATTRIBUTE_READONLY;
}
const auto modified=(attrs.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)?
(uint64_t(attrs.mtime)+11644473600ULL)*10000000ULL:0;
if(!visit(directory/child,{attributes,attrs.filesize,modified})) return ERROR_CANCELLED;
const auto sftpTime=[](unsigned long seconds){return (uint64_t(seconds)+11644473600ULL)*10000000ULL;};
FileInfo info{attributes,attrs.filesize,0};
TransferItemMetadata details;
if(attrs.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)
{
info.modified=sftpTime(attrs.mtime);
details.accessed=sftpTime(attrs.atime);
}
if(attrs.flags&LIBSSH2_SFTP_ATTR_UIDGID) details.owner=attrs.uid;
if(attrs.flags&LIBSSH2_SFTP_ATTR_PERMISSIONS) details.permissions=attrs.permissions&07777;
if(details.accessed || details.owner || details.permissions) info.transfer=details;
if(!visit(directory/child,info)) return ERROR_CANCELLED;
}
return ERROR_CANCELLED;
}
SftpFile open(const fs::path &path,bool write) const
{
if(write) requireWriteAccess();
const auto name=encode(path);
const auto flags=write?LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_EXCL:LIBSSH2_FXF_READ;
SftpFile file(libssh2_sftp_open_ex(sftp_.get(),name.c_str(),static_cast<unsigned>(name.size()),
@@ -224,19 +383,47 @@ public:
void makeDirectory(const fs::path &path) const
{
requireWriteAccess();
const auto name=encode(path);
if(libssh2_sftp_mkdir(sftp_.get(),name.c_str(),0755)) operationError("Could not create the SFTP folder");
}
void remove(const fs::path &path,bool directory) const
{
requireWriteAccess();
const auto name=encode(path);
const auto result=directory?libssh2_sftp_rmdir(sftp_.get(),name.c_str()):libssh2_sftp_unlink(sftp_.get(),name.c_str());
if(result) operationError("Could not remove the SFTP entry");
}
void prepareReplacement(const fs::path &staged,const fs::path &existing) const
{
if(access_!=SftpAccess::sudoWrite) return;
const auto source=encode(existing),target=encode(staged);
LIBSSH2_SFTP_ATTRIBUTES attributes{};
if(libssh2_sftp_lstat(sftp_.get(),source.c_str(),&attributes))
operationError("Could not read the file ownership and permissions");
constexpr auto metadata=LIBSSH2_SFTP_ATTR_UIDGID|LIBSSH2_SFTP_ATTR_PERMISSIONS;
if((attributes.flags&metadata)!=metadata || !LIBSSH2_SFTP_S_ISREG(attributes.permissions))
throw std::runtime_error("The server did not supply the file ownership and permissions. The original was kept.");
const auto original=attributes;
attributes.flags=LIBSSH2_SFTP_ATTR_UIDGID;
if(libssh2_sftp_setstat(sftp_.get(),target.c_str(),&attributes))
operationError("Could not preserve the file ownership");
attributes.flags=LIBSSH2_SFTP_ATTR_PERMISSIONS;
attributes.permissions=original.permissions&07777;
if(libssh2_sftp_setstat(sftp_.get(),target.c_str(),&attributes))
operationError("Could not preserve the file permissions");
if(libssh2_sftp_lstat(sftp_.get(),target.c_str(),&attributes))
operationError("Could not verify the staged file permissions");
if((attributes.flags&metadata)!=metadata || attributes.uid!=original.uid ||
attributes.gid!=original.gid || (attributes.permissions&07777)!=(original.permissions&07777))
throw std::runtime_error("The server did not preserve ownership and permissions. The original was kept.");
}
void rename(const fs::path &from,const fs::path &to,bool replace) const
{
requireWriteAccess();
const auto source=encode(from),target=encode(to);
if(replace)
{
+150
View File
@@ -0,0 +1,150 @@
bool panelMatchesSshPrompt()
{
const auto &panel=panels[active];
return sshPrompt && sshPrompt->panel==active && panel.ftp &&
panel.ftp->protocol==TransferProtocol::sftp && panel.ftp->id==sshPrompt->profile;
}
void closeSshPrompt(HWND owner)
{
if(!sshPrompt) return;
clearTerminalSelection();
sshPrompt.reset();
sshTerminal.stop();
sshView.post(L"ssh-input:off");
layout(owner);
}
bool startSshTerminal(HWND owner,const Panel &panel)
{
if(panelMatchesSshPrompt() && !sshPrompt->finished) return true;
if(sshTerminal.running())
{
setStatus(L"The previous SSH session is closing. Try again when it has disconnected.");
return false;
}
if(!ensureTerminalView(owner,true)) return false;
try
{
auto token=ks::lan::randomHex(16);
sshTerminal.start(*panel.ftp,panel.directory,token,sshSize);
clearTerminalSelection();
sshPrompt=SshPrompt{active,panel.ftp->id,std::move(token),panel.directory};
}
catch(const std::exception &error) {setStatus(ks::wide(error.what()));return false;}
sshView.post(L"ssh-reset");
if(!terminalVisible) terminalRows=std::max(terminalRows,5);
layout(owner);
return true;
}
bool sendSshCommand(HWND owner,const fs::path &directory,const std::wstring &value)
{
const auto text=ks::utf8(value);
const auto command=directory==sshPrompt->shellDirectory?text:
"if "+sshChangeDirectory(directory)+"; then eval "+sshShellQuote(text)+"; fi";
if(!sshTerminal.write(command+"\r"))
{
setStatus(L"Could not send input to the SSH terminal.");
return false;
}
sshPrompt->panelDirectory=directory;
sshPrompt->waiting=true;
sshPrompt->raw=true;
sshView.post(L"ssh-input:on");
if(GetForegroundWindow()==owner)
{
sshView.focus();
sshView.post(L"ssh-focus");
}
return true;
}
bool submitSshCommand(HWND owner,const Panel &panel,const std::wstring &value)
{
if(!startSshTerminal(owner,panel)) return false;
if(!sshPrompt->waiting) return sendSshCommand(owner,panel.directory,value);
if(sshPrompt->shellDirectory.empty() && !sshPrompt->startupCommand)
{
sshPrompt->startupCommand=value;
return true;
}
setStatus(L"The SSH prompt is busy.");
return false;
}
std::optional<fs::path> sshReportedDirectory(std::wstring_view encoded)
{
if(encoded.empty() || encoded.size()>49152) return {};
DWORD length{};
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
nullptr,&length,nullptr,nullptr) || !length) return {};
auto bytes=std::string(length,'\0');
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
reinterpret_cast<BYTE*>(bytes.data()),&length,nullptr,nullptr) || bytes.front()!='/' ||
bytes.find_first_of("\\:\r\n")!=bytes.npos || bytes.find('\0')!=bytes.npos) return {};
auto path=fs::path(ks::wide(bytes)).lexically_normal();
return isFtpFolderPath(path)?std::optional(std::move(path)):std::nullopt;
}
void acceptSshDirectory(HWND owner,std::wstring_view message)
{
if(!panelMatchesSshPrompt() || sshPrompt->finished || message.size()<33 || message[32]!=L':' ||
message.substr(0,32)!=ks::wide(sshPrompt->token)) return;
const auto reported=sshReportedDirectory(message.substr(33));
if(!reported) return;
auto &panel=panels[active];
auto &prompt=*sshPrompt;
const bool initial=prompt.shellDirectory.empty();
const bool command=std::exchange(prompt.raw,false);
prompt.shellDirectory=*reported;
prompt.waiting=false;
if(command)
{
sshView.post(L"ssh-input:off");
if(GetForegroundWindow()==owner) restoreCommandFocus();
}
if(prompt.startupCommand)
{
const auto pending=std::exchange(prompt.startupCommand,{});
if(!sendSshCommand(owner,prompt.panelDirectory,*pending) && !GetWindowTextLengthW(terminalInput))
SetWindowTextW(terminalInput,pending->c_str());
return;
}
if(panel.scan.valid() || panel.directory!=prompt.panelDirectory || panel.directory==*reported) return;
if(initial || command)
{
prompt.panelDirectory=*reported;
open(panel,*reported,false);
}
else setStatus(L"The SSH shell could not enter the panel folder.");
}
void updateSshTerminal(HWND owner)
{
if(!sshPrompt) return;
if(!panelMatchesSshPrompt()) {closeSshPrompt(owner);return;}
if(!sshView.initialized()) return;
const auto output=sshTerminal.takeOutput();
if(!output.empty()) sshView.send(output);
auto &prompt=*sshPrompt;
if(!sshTerminal.running() && !prompt.finished)
{
auto reason=sshTerminal.takeError();
if(reason.empty()) reason=L"SSH session disconnected.";
sshView.send(ks::utf8(L"\r\n["+reason+L"]\r\n"));
if(prompt.startupCommand && !GetWindowTextLengthW(terminalInput))
SetWindowTextW(terminalInput,prompt.startupCommand->c_str());
prompt.finished=true;
prompt.raw=false;
sshView.post(L"ssh-input:off");
setStatus(reason);
if(GetForegroundWindow()==owner) restoreCommandFocus();
return;
}
const auto &panel=panels[active];
if(prompt.finished || prompt.waiting || panel.scan.valid() || panel.directory==prompt.panelDirectory) return;
prompt.panelDirectory=panel.directory;
if(panel.directory!=prompt.shellDirectory && sshTerminal.write(sshChangeDirectory(panel.directory)+"\r"))
prompt.waiting=true;
}
+164
View File
@@ -0,0 +1,164 @@
std::string sshShellQuote(std::string_view text)
{
std::string quoted="'";
for(const auto character:text)
if(character=='\'') quoted+="'\\''";
else quoted+=character;
return quoted+"'";
}
std::string sshChangeDirectory(const fs::path &path)
{
return "cd "+sshShellQuote(ks::utf8(ftpPath(path)));
}
class FilesSshTerminal
{
std::mutex mutex_;
std::string input_,output_;
std::wstring error_;
COORD size_{};
std::atomic_bool running_{};
std::jthread worker_;
void run(const TransferProfile &profile,const fs::path &directory,const std::string &token,
COORD terminalSize,std::stop_token stop)
{
SshConnection connection(profile);
if(stop.stop_requested()) return;
SshChannel channel(libssh2_channel_open_session(connection.session()),libssh2_channel_free);
if(!channel) connection.operationError("Could not open the SSH terminal");
if(libssh2_channel_request_pty_ex(channel.get(),"xterm-256color",14,nullptr,0,
terminalSize.X,terminalSize.Y,0,0)) connection.operationError("Could not allocate the SSH terminal");
// Expand the prompt after every command so panel navigation can follow even scripted directory changes.
const auto report="printf '\\033]633;ks-ssh-dir:"+token+
":%s\\007' \"$(printf '%s' \"$(pwd -P)\" | base64 | tr -d '\\r\\n')\"";
const auto command=sshChangeDirectory(directory)+
" || exit; command -v base64 >/dev/null 2>&1 || { echo 'SSH directory sync requires base64.'; exit 1; }; "
"if command -v bash >/dev/null 2>&1; then exec env PS1='' PS2='> ' PROMPT_COMMAND="+
sshShellQuote(report)+" bash --noprofile --norc -i; else exec env ENV=/dev/null PS2='> ' PS1="+
sshShellQuote("$("+report+")")+" /bin/sh -i; fi";
if(libssh2_channel_exec(channel.get(),command.c_str()))
connection.operationError("Could not start the SSH shell");
connection.nonblocking();
auto buffer=std::array<char,32768>{};
std::string pending;
size_t offset{};
std::optional<COORD> resize;
while(!stop.stop_requested())
{
{
const std::lock_guard lock(mutex_);
if(pending.empty()) pending.swap(input_);
if(!resize && (terminalSize.X!=size_.X || terminalSize.Y!=size_.Y)) resize=size_;
}
bool progressed=false;
if(resize)
{
const auto result=libssh2_channel_request_pty_size(channel.get(),resize->X,resize->Y);
if(result!=LIBSSH2_ERROR_EAGAIN)
{
terminalSize=*resize;
resize.reset();
}
}
if(!pending.empty())
{
const auto count=libssh2_channel_write(channel.get(),pending.data()+offset,pending.size()-offset);
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not send SSH terminal input");
if(count>0)
{
offset+=count;
if(offset==pending.size()) {pending.clear();offset=0;}
progressed=true;
}
}
for(int stream:{0,SSH_EXTENDED_DATA_STDERR})
{
const auto count=libssh2_channel_read_ex(channel.get(),stream,buffer.data(),buffer.size());
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not read SSH terminal output");
if(count>0)
{
const std::lock_guard lock(mutex_);
output_.append(buffer.data(),count);
constexpr size_t limit=1024*1024;
if(output_.size()>limit) output_.erase(0,output_.size()-limit);
progressed=true;
}
}
if(!progressed)
{
if(libssh2_channel_eof(channel.get())) break;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
// The connection owns all channels. Its teardown also handles a channel blocked in a nonblocking request.
channel.release();
}
public:
bool running() const {return running_;}
void start(TransferProfile profile,fs::path directory,std::string token,COORD size)
{
{
const std::lock_guard lock(mutex_);
input_.clear();
output_.clear();
error_.clear();
size_=size;
}
running_=true;
try
{
worker_=std::jthread([this,profile=std::move(profile),directory=std::move(directory),
token=std::move(token),size](std::stop_token stop)
{
try {run(profile,directory,token,size,stop);}
catch(const std::exception &error)
{
const std::lock_guard lock(mutex_);
error_=ks::wide(error.what());
}
running_=false;
});
}
catch(...)
{
running_=false;
throw;
}
}
void stop() {worker_.request_stop();}
bool write(std::string_view input)
{
if(!running_) return false;
const std::lock_guard lock(mutex_);
constexpr size_t limit=256*1024;
if(input.size()>limit-input_.size()) return false;
input_+=input;
return true;
}
void resize(COORD size)
{
const std::lock_guard lock(mutex_);
size_=size;
}
std::string takeOutput()
{
const std::lock_guard lock(mutex_);
return std::exchange(output_,{});
}
std::wstring takeError()
{
const std::lock_guard lock(mutex_);
return std::exchange(error_,{});
}
};
+2 -2
View File
@@ -127,7 +127,7 @@ public:
return SUCCEEDED(web->PostWebMessageAsString(message.c_str()));
}
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed,
bool markdown=false,std::function<bool(UINT)> handleKey={})
bool markdown=false,std::function<bool(UINT)> handleKey={},bool ssh=false)
{
wchar_t exe[MAX_PATH]{};
if(!GetModuleFileNameW(nullptr,exe,MAX_PATH)) return false;
@@ -144,7 +144,7 @@ public:
if(!length || length>=MAX_PATH) return false;
const auto profile=std::filesystem::path(local)/L"KSwitcher"/(markdown?L"MarkdownWebView":L"TerminalWebView");
const auto origin=markdown?L"kswitcher-markdown.invalid":L"kswitcher-terminal.invalid";
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":ssh?L"/index.html?ssh":L"/index.html");
const auto assets=folder/L"terminal";
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
waitForReady=!markdown;
+1 -2
View File
@@ -87,8 +87,7 @@ bool sameFile(HANDLE a, HANDLE b)
BY_HANDLE_FILE_INFORMATION first{}, second{};
if (!GetFileInformationByHandle(a, &first) || !GetFileInformationByHandle(b, &second))
fail("Check file identity");
return first.dwVolumeSerialNumber == second.dwVolumeSerialNumber &&
first.nFileIndexHigh == second.nFileIndexHigh && first.nFileIndexLow == second.nFileIndexLow;
return sameFileIdentity(first,second);
}
std::filesystem::path temporaryPath(const std::filesystem::path &directory)
+148 -34
View File
@@ -647,22 +647,26 @@ struct RemoteTextFile
std::filesystem::remove(cache.parent_path(),ignored);
}
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX)
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX,bool elevated=false)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
if(!std::filesystem::create_directory(directory))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
cache=directory/L"content";
revision=source.download(original,cache,edit,progress,sizeLimit);
if(cache.empty())
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
if(!std::filesystem::create_directory(directory))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
cache=directory/L"content";
}
const auto &read=elevated?source.elevation->download:source.download;
revision=read(original,cache,edit,progress,sizeLimit);
}
void upload()
void upload(const RemoteTextSource::Progress &cancel)
{
revision=source.upload(original,cache,revision);
revision=cancel?source.elevation->upload(original,cache,revision,cancel):source.upload(original,cache,revision);
}
};
@@ -800,6 +804,7 @@ public:
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
void previewFile(const std::filesystem::path &path);
void previewDiff(const std::wstring &title,std::string_view patch);
bool openBookmark(const ViewerBookmark &bookmark);
std::filesystem::path original;
const std::string peerId;
@@ -902,9 +907,10 @@ private:
std::future<std::string> image;
ImageRequest activeImage;
std::shared_ptr<std::atomic<bool>> cancelImages;
std::atomic<bool> cancelOpen{};
std::atomic<bool> cancelOpen{},cancelElevatedSave{};
std::future<void> opening;
std::future<bool> saving;
bool elevatedOpen{},elevatedSave{};
static constexpr UINT_PTR saveTimer = 1;
static constexpr UINT_PTR openTimer = 2;
static constexpr UINT_PTR previewTimer = 3;
@@ -930,6 +936,8 @@ private:
};
std::future<QuickDocument> quickLoading;
std::filesystem::path quickPath;
std::wstring quickDiffTitle;
bool quickDiffVisible{};
uint64_t quickRequest{}, quickReading{};
ULONGLONG quickReadyAt{};
std::wstring quickError;
@@ -964,6 +972,7 @@ private:
void invalidateHints() const;
void initializeDocument(std::optional<std::string> firstPage={});
void startRemoteOpen(bool elevated=false);
void finishOpen();
void createMenu();
void releaseMenu();
@@ -979,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);
@@ -986,7 +996,7 @@ private:
void pickBookmark(bool currentFile);
void stagePage();
void go(uint64_t index);
void saveFile(bool closeWhenDone);
void saveFile(bool closeWhenDone,bool elevated=false);
void finishSave();
void requestClose();
void toggleMode();
@@ -1405,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);
@@ -1418,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;
@@ -1610,7 +1625,9 @@ std::string readMarkdownDocument(TextDocument &document)
void TextWindow::previewFile(const std::filesystem::path &path)
{
if(path==quickPath) return;
if(quickDiffTitle.empty() && path==quickPath) return;
quickDiffVisible=false;
quickDiffTitle.clear();
quickPath=path;
++quickRequest;
quickReadyAt=GetTickCount64()+80;
@@ -1622,6 +1639,30 @@ void TextWindow::previewFile(const std::filesystem::path &path)
SetTimer(window,quickViewTimer,30,nullptr);
}
void TextWindow::previewDiff(const std::wstring &title,std::string_view patch)
{
if(!embedded) return;
if(quickDiffTitle.empty())
{
++quickRequest;
KillTimer(window,quickViewTimer);
quickLoading={};
quickPath.clear();
quickError.clear();
stopPreview(false,true);
document.reset();
quickMarkdown.reset();
language=automatic=detectLanguage(L"preview.diff",patch);
installLexer();
}
quickDiffTitle=title;
quickDiffVisible=!patch.empty();
pageEol=SC_EOL_LF;
replaceEditorText(patch);
send(SCI_COLOURISE,0,-1);
layout();
}
void TextWindow::pollQuickView()
{
if(quickLoading.valid())
@@ -1677,6 +1718,24 @@ void TextWindow::pollQuickView()
std::thread(std::move(task)).detach();
}
void TextWindow::startRemoteOpen(bool elevated)
{
elevatedOpen=elevated;
if(!SetTimer(window,openTimer,75,nullptr)) throw std::runtime_error("Cannot start the remote file timer.");
try
{
opening=std::async(std::launch::async,[this,elevated]
{
remote->download(edit,[this](uint64_t,uint64_t){return !cancelOpen;},UINT64_MAX,elevated);
});
}
catch(...)
{
KillTimer(window,openTimer);
throw;
}
}
void TextWindow::finishOpen()
{
if(!opening.valid() || opening.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready) return;
@@ -1689,6 +1748,18 @@ void TextWindow::finishOpen()
initializeDocument();
invalidate();
}
catch(const RemoteAccessDenied &error)
{
if(!cancelOpen && !edit && !elevatedOpen && remote->source.elevation)
{
if(remote->source.elevation->approve(window,original,false))
startRemoteOpen(true);
else DestroyWindow(window);
return;
}
if(!cancelOpen) search.style.message(window,wide(error.what()).c_str());
DestroyWindow(window);
}
catch(const std::exception &error)
{
if(!cancelOpen) search.style.message(window,wide(error.what()).c_str());
@@ -1696,7 +1767,7 @@ void TextWindow::finishOpen()
}
}
void TextWindow::saveFile(bool closeWhenDone)
void TextWindow::saveFile(bool closeWhenDone,bool elevated)
{
if (busy() || savedViewerLoad.valid() || !edit) return;
auto destination=original;
@@ -1710,17 +1781,22 @@ void TextWindow::saveFile(bool closeWhenDone)
pendingCaret = send(SCI_GETCURRENTPOS);
if(draft) pendingSavePath=destination;
closeAfterSave = closeWhenDone;
elevatedSave=elevated;
cancelElevatedSave=false;
if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer.");
send(SCI_SETREADONLY, TRUE);
try
{
saving=std::async(std::launch::async,[this,destination=std::move(destination)]
saving=std::async(std::launch::async,[this,destination=std::move(destination),elevated]
{
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
if(remote)
{
uploadPending=true;
remote->upload();
const auto progress=elevated?RemoteTextSource::Progress([this](uint64_t,uint64_t) {
return !cancelElevatedSave;
}):RemoteTextSource::Progress{};
remote->upload(progress);
uploadPending=false;
}
return reopened;
@@ -1745,7 +1821,22 @@ void TextWindow::finishSave()
return;
}
send(SCI_SETREADONLY, !edit);
const auto reopened = saving.get();
bool reopened{};
try {reopened=saving.get();}
catch(const RemoteAccessDenied &)
{
if(!remote || elevatedSave || !remote->source.elevation) throw;
if(remote->source.elevation->approve(window,original,true)) saveFile(closeAfterSave,true);
else {closeAfterSave=false;invalidate();}
return;
}
catch(const std::system_error &error)
{
if(!elevatedSave || error.code().value()!=ERROR_CANCELLED) throw;
closeAfterSave=false;
invalidate();
return;
}
stagedDirty = false;
const bool created=std::exchange(draft,false);
if(created)
@@ -1781,7 +1872,11 @@ void TextWindow::finishSave()
void TextWindow::requestClose()
{
if (opening.valid()) { cancelOpen=true; return; }
if (busy()) return;
if (busy())
{
if(elevatedSave) cancelElevatedSave=true;
return;
}
cancelSavedViewerLoad();
if (needsSave())
{
@@ -2460,7 +2555,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 || quickDiffVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
invalidate();
}
@@ -2537,6 +2632,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(!quickDiffTitle.empty()) label=quickDiffTitle;
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
color(TextColor::chrome),scale(6),label);
if(chromeFont) DeleteObject(chromeFont);
@@ -2651,7 +2747,7 @@ void TextWindow::find(bool down, DWORD flags)
void TextWindow::command(UINT id)
{
if(!document && id!=close) return;
if (busy()) return;
if (busy() && id!=close) return;
if(hex && (id==switchMode || id==historyBack || id==historyForward || id==findText || id==findNext ||
id==findPrevious || id==lexerAuto || id==lexerPlain || id>=lexerStart)) return;
switch (id)
@@ -2877,12 +2973,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
{
self->applyPreferences();
self->send(SCI_SETREADONLY,TRUE);
if(!SetTimer(window,openTimer,75,nullptr))
throw std::runtime_error("Cannot start the remote file timer.");
self->opening=std::async(std::launch::async,[state=self.get()]
{
state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;});
});
self->startRemoteOpen();
}
else if(self->embedded) self->applyPreferences();
else self->initializeDocument();
@@ -3204,6 +3295,12 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
preview->second->previewFile(path);
}
void previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch)
{
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
preview->second->previewDiff(title,patch);
}
ImageViewStyle imageViewStyle(TextDialogs dialogs)
{
const auto font=dialogs.readFont();
@@ -3228,18 +3325,35 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
{
const auto backend=source?std::optional(*source):peer?std::optional(lanTextSource(*peer)):std::nullopt;
ImageLoad load;
ImageLoadRetry retry;
if(backend)
load=[backend=*backend](const std::filesystem::path &original,std::stop_token stop) {
RemoteTextFile file(backend,original);
file.download(false,[&](uint64_t,uint64_t){return !stop.stop_requested();},imageSourceLimit);
return decodeImage(file.cache,original,stop);
{
const auto reader=[&](bool elevated) -> ImageLoad
{
return [backend=*backend,elevated](const std::filesystem::path &original,std::stop_token stop)
{
RemoteTextFile file(backend,original);
file.download(false,[&](uint64_t,uint64_t){return !stop.stop_requested();},imageSourceLimit,elevated);
return decodeImage(file.cache,original,stop);
};
};
load=reader(false);
if(backend->elevation)
{
retry.load=reader(true);
retry.approve=[approve=backend->elevation->approve](HWND window,
const std::filesystem::path &file,const std::exception &failure)
{
return dynamic_cast<const RemoteAccessDenied*>(&failure) && approve(window,file,false);
};
}
}
if(!textWindows.contains(owner)) filesOwner=owner;
const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load),
[](HWND closed) {
std::erase(textWindowOrder,closed);
quitWhenFilesWindowsClose();
});
},std::move(retry));
if(!window) throw std::runtime_error("Could not open the image viewer.");
textWindowOrder.push_back(window);
const auto instance=GetModuleHandleW(nullptr);
+25 -4
View File
@@ -3,6 +3,8 @@
#include <windows.h>
#include <filesystem>
#include <functional>
#include <optional>
#include <system_error>
#include <cstdint>
#include <string_view>
#include <vector>
@@ -71,21 +73,40 @@ struct RemoteTextRevision
bool editable{};
};
struct RemoteAccessDenied : std::system_error
{
explicit RemoteAccessDenied(const char *operation):
std::system_error(ERROR_ACCESS_DENIED,std::system_category(),operation) {}
};
struct RemoteTextSource
{
using Progress=std::function<bool(uint64_t,uint64_t)>;
using Download=std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
bool,const Progress &,uint64_t)>;
using Upload=std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
const RemoteTextRevision &)>;
struct Elevation
{
Download download;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
const RemoteTextRevision &,const Progress &)> upload;
std::function<bool(HWND,const std::filesystem::path &,bool)> approve;
};
std::string id;
std::wstring name;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
bool,const Progress &,uint64_t)> download;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
const RemoteTextRevision &)> upload;
Download download;
Upload upload;
std::optional<Elevation> elevation;
};
RemoteTextSource createLanTextSource(const lan::FilesPeer &peer);
inline constexpr UINT quickViewToggleMessage=WM_APP+31;
HWND createQuickView(HWND owner,TextDialogs dialogs);
void previewQuickViewFile(HWND window,const std::filesystem::path &path);
void previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch);
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,
+8 -2
View File
@@ -59,9 +59,10 @@ class TransferSession
std::optional<SftpSession> sftp_;
public:
explicit TransferSession(const TransferProfile &profile)
explicit TransferSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
std::stop_token stop={})
{
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile);
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile,access,stop);
else ftp_.emplace(profile);
}
@@ -101,6 +102,11 @@ public:
FtpDeleteFileA(ftp_->handle(),name.c_str()));
}
void prepareReplacement(const fs::path &staged,const fs::path &existing)
{
if(sftp_) sftp_->prepareReplacement(staged,existing);
}
void rename(const fs::path &from,const fs::path &to,bool replace=false)
{
if(sftp_) {sftp_->rename(from,to,replace);return;}
+6
View File
@@ -7,6 +7,12 @@
namespace ks::files
{
inline bool sameFileIdentity(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
{
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
left.nFileIndexLow==right.nFileIndexLow;
}
inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement,
const std::filesystem::path &backup)
{
+30 -11
View File
@@ -115,6 +115,7 @@ constexpr DWORD SocketTimeout=5000;
class Wire
{
SOCKET socket;
std::stop_token stop;
std::unique_ptr<InputCipher> tx,rx;
void bytes(void *buffer,size_t size,bool sending)
{
@@ -122,19 +123,36 @@ class Wire
const auto deadline=GetTickCount64()+SocketTimeout;
while(size)
{
if(GetTickCount64()>=deadline)
throw std::system_error(WSAETIMEDOUT,std::system_category());
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto now=GetTickCount64();
if(now>=deadline) throw std::system_error(WSAETIMEDOUT,std::system_category());
if(stop.stop_possible())
{
fd_set ready{};
FD_SET(socket,&ready);
const auto interval=static_cast<long>(std::min<ULONGLONG>(100,deadline-now));
timeval wait{0,interval*1000};
const auto available=select(0,sending?nullptr:&ready,sending?&ready:nullptr,nullptr,&wait);
if(available==SOCKET_ERROR) socketError();
if(!available) continue;
}
const auto n=sending?send(socket,next,static_cast<int>(size),0):
recv(socket,next,static_cast<int>(size),0);
if(n==SOCKET_ERROR) socketError();
if(n==SOCKET_ERROR)
{
if(stop.stop_possible() && WSAGetLastError()==WSAEWOULDBLOCK) continue;
socketError();
}
if(!n) throw std::system_error(WSAECONNRESET,std::system_category());
size-=n;
next+=n;
}
}
public:
explicit Wire(SOCKET socket):socket(socket)
explicit Wire(SOCKET socket,std::stop_token stop={}):socket(socket),stop(stop)
{
u_long nonblocking=1;
if(stop.stop_possible() && ioctlsocket(socket,FIONBIO,&nonblocking)==SOCKET_ERROR) socketError();
if(setsockopt(socket,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast<const char*>(&SocketTimeout),sizeof(SocketTimeout)) ||
setsockopt(socket,SOL_SOCKET,SO_SNDTIMEO,reinterpret_cast<const char*>(&SocketTimeout),sizeof(SocketTimeout)))
socketError();
@@ -897,7 +915,7 @@ struct FilesConnection::Impl
std::unique_ptr<Wire> wire;
FileOperations local{false};
Impl()=default;
explicit Impl(const FilesPeer *peer)
explicit Impl(const FilesPeer *peer,std::stop_token stop)
{
if(!peer) return;
const auto pairing=Json::parse(unprotect(readFile(dataDirectory()/L"lan-pairing.bin",256*1024)));
@@ -905,15 +923,16 @@ struct FilesConnection::Impl
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category());
const auto id=pairing.at("id").get<std::string>();
const auto key=pairing.at("trusted").at(peer->id).at("key").get<std::string>();
connect(*peer,id,key);
connect(*peer,id,key,stop);
}
void connect(const FilesPeer &peer,const std::string &id,const std::string &key)
void connect(const FilesPeer &peer,const std::string &id,const std::string &key,std::stop_token stop={})
{
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
network.emplace();
socket.value=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(socket.value==INVALID_SOCKET) socketError();
connectPeer(socket.value,peer);
wire=std::make_unique<Wire>(socket.value);
wire=std::make_unique<Wire>(socket.value,stop);
const auto nonce=randomHex(16);
wire->write({{"version",1},{"client",id},{"server",peer.id},{"nonce",nonce}});
const auto challenge=wire->read().at("challenge").get<std::string>();
@@ -929,11 +948,11 @@ DWORD hibernateFromPairedPC()
return requestSystemHibernate();
}
FilesConnection::FilesConnection(const FilesPeer *peer):impl(std::make_unique<Impl>(peer)){}
FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key):
FilesConnection::FilesConnection(const FilesPeer *peer,std::stop_token stop):impl(std::make_unique<Impl>(peer,stop)){}
FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key,std::stop_token stop):
impl(std::make_unique<Impl>())
{
impl->connect(peer,local,key);
impl->connect(peer,local,key,stop);
}
FilesConnection::~FilesConnection()=default;
Json FilesConnection::call(const Json &request,const FileProgress &progress)
+2 -2
View File
@@ -23,8 +23,8 @@ class FilesConnection
struct Impl;
std::unique_ptr<Impl> impl;
public:
explicit FilesConnection(const FilesPeer *peer = nullptr);
FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key);
explicit FilesConnection(const FilesPeer *peer = nullptr,std::stop_token stop={});
FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key,std::stop_token stop={});
~FilesConnection();
Json call(const Json &request, const FileProgress &progress = {});
};
+8 -22
View File
@@ -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)};
+21
View File
@@ -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'"';
}
}
+23
View File
@@ -5,6 +5,7 @@
#include <bit>
#include <atomic>
#include <fstream>
#include <future>
#include <iostream>
#include <thread>
@@ -49,6 +50,27 @@ std::string load(const fs::path &path)
return {std::istreambuf_iterator<char>(file),{}};
}
void verifyConnectionCancellation(const std::string &client,const std::string &key)
{
const auto serverId=randomHex(16);
// Keep the server listening while deliberately withholding its handshake response.
FilesListener stalled(serverId,[&](const std::string &id){return id==client?key:std::string{};},0);
require(stalled.port()!=0,"cancellation fixture did not start");
const FilesPeer peer{serverId,"127.0.0.1",L"Stalled peer",stalled.port()};
std::stop_source stop;
auto waiting=std::async(std::launch::async,[&]
{
try {FilesConnection connection(peer,client,key,stop.get_token());}
catch(const std::system_error &error) {return error.code().value();}
return 0;
});
std::this_thread::sleep_for(std::chrono::milliseconds(150));
stop.request_stop();
require(waiting.wait_for(std::chrono::seconds(3))==std::future_status::ready,
"cancellation did not stop the stalled LAN handshake");
require(waiting.get()==ERROR_CANCELLED,"stalled LAN handshake reported the wrong cancellation error");
}
void verifyDirection(const FilesPeer *sourcePeer,const FilesPeer *targetPeer,
const std::string &id,const std::string &key,const fs::path &root)
{
@@ -176,6 +198,7 @@ int main()
require(false,"unpaired client authenticated");
}
catch(const std::system_error &){}
verifyConnectionCancellation(client,key);
FilesConnection host(one,client,key);
{
const Json hibernate={{"action","hibernate"}};