Compare commits

..
Author SHA1 Message Date
agrynco 934521f404 Add Files panel layout and mouse options
Refs #124
2026-11-25 21:51:02 +02:00
agrynco 2db50fcd0e Merge pull request 'KSwitcher.Files: Copy/Move options and time estimate' (#178) from codex/issue-123-copy-options into prerelease
Refs #123
2026-11-25 21:43:00 +02:00
agrynco dbbc5c138e Add advanced Files copy and move options
Refs #123
2026-11-25 21:42:50 +02:00
agrynco 84385a1eca Merge pull request 'KSwitcher.Files: file operations for trusted LAN clients' (#177) from codex/issue-122-lan-capabilities into prerelease
Refs #122
2026-11-25 21:27:08 +02:00
agrynco f5b7ddfb53 Expose file operations to trusted LAN clients
Refs #122
2026-11-25 21:26:55 +02:00
agrynco 93e672c71d Merge pull request 'KSwitcher.Files: Windows environment variables' (#176) from codex/issue-121-environment-panel into prerelease
Refs #121
2026-11-25 21:08:57 +02:00
agrynco cc6199e9be Inspect and edit Windows environment definitions
Refs #121
2026-11-25 21:08:51 +02:00
agrynco a27ae96842 Merge pull request 'KSwitcher.Files: Stage, Unstage and reviewed local commits' (#175) from codex/issue-120-git-mutations into prerelease
Refs #120
2026-11-25 20:59:44 +02:00
agrynco 9158bf95a6 Stage and commit a reviewed Git index snapshot
Refs #120
2026-11-25 20:59:30 +02:00
agrynco 159b776199 Merge pull request 'KSwitcher.Files: Git branches and commit history' (#174) from codex/issue-119-git-history into prerelease
Refs #119
2026-11-25 20:37:56 +02:00
agrynco ada198db24 Browse Git branches and paged commit history
Refs #119
2026-11-25 20:37:46 +02:00
agrynco fe1f818582 Merge pull request 'KSwitcher.Files: Git Changes and side-by-side diff' (#173) from codex/issue-118-git-changes into prerelease
Refs #118
2026-11-25 20:27:30 +02:00
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
agrynco e11e19293f Support interactive editing in the Files terminal prompt
Refs #111
2026-11-25 18:31:36 +02:00
agrynco 5729ed2036 Merge pull request 'KSwitcher.Files: SFTP profiles and file operations' (#165) from codex/issue-110-sftp-panels into prerelease
Refs #110
2026-11-25 18:23:48 +02:00
agrynco 94ccb488c1 Add SFTP profiles and shared Files operations
Refs #110
2026-11-25 18:23:38 +02:00
agrynco e24fbc80ba Merge pull request 'KSwitcher.Files: Saved SMB connections and shares' (#164) from codex/issue-109-smb-profiles into prerelease
Refs #109
2026-11-25 17:53:43 +02:00
agrynco c735c21682 Add saved SMB connection profiles and share browsing
Refs #109
2026-11-25 17:53:30 +02:00
agrynco 9bb2221b2b Merge pull request 'KSwitcher.Files: FTP and LAN breadcrumbs and recent folders' (#161) from codex/issue-108-remote-breadcrumbs into prerelease
Refs #108
2026-11-25 17:34:37 +02:00
agrynco 20d95b37aa Add remote folder breadcrumbs and recent locations
Refs #108
2026-11-25 17:34:22 +02:00
agrynco 6467481d2f Merge pull request 'KSwitcher.Files: Restore FTP panels and recover LAN folders' (#160) from codex/issue-107-remote-panel-restore into prerelease
Refs #107
2026-11-25 17:22:57 +02:00
agrynco 7033c1e336 Restore FTP panels and recover interrupted LAN scans
Refs #107
2026-11-25 17:22:44 +02:00
agrynco 03145ae75a Merge pull request 'KSwitcher.Files: Unified diff and context folding' (#159) from codex/issue-106-unified-diff into prerelease
Refs #106
2026-11-25 17:04:17 +02:00
agrynco 9d57568351 Add unified comparison and context folding
Refs #106
2026-11-25 17:04:05 +02:00
agrynco f74b8b2ac0 Merge pull request 'KSwitcher.Files: Apply selected blocks in file comparison' (#158) from codex/issue-105-compare-apply into prerelease
Refs #105
2026-11-25 16:54:38 +02:00
agrynco 5bf2d7ab45 Apply selected blocks in file comparison
Refs #105
2026-11-25 16:54:25 +02:00
agrynco 4ab1f3c950 Merge pull request 'KSwitcher.Files: Збереження чернетки при перемиканні F6' (#157) from codex/issue-104-editor-draft into prerelease
Refs #104
2026-11-25 16:40:35 +02:00
65 changed files with 9524 additions and 1177 deletions

No files matched your search

+10 -4
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"
@@ -14,6 +14,7 @@ set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-compare.ico")
include(cmake/FilesTextLibraries.cmake)
include(cmake/FilesArchiveLibraries.cmake)
include(cmake/FilesSshLibrary.cmake)
include(cmake/FilesImageLibraries.cmake)
set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files")
target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
@@ -34,7 +35,7 @@ add_custom_target(check-files-quick-view
DEPENDS KSwitcherFiles
VERBATIM)
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet KSwitcherFilesImage)
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr userenv KSwitcherFilesImage libssh2::libssh2)
if(MSVC)
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
else()
@@ -54,7 +55,7 @@ foreach(utilityTarget StayHere StayHereTest)
target_link_options(${utilityTarget} PRIVATE -municode -static -static-libgcc -static-libstdc++)
endif()
endforeach()
add_library(kscore src/lan_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp)
add_library(kscore src/lan_files.cpp src/lan_client_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp)
target_sources(kscore PRIVATE src/drive_snapshot.cpp src/google_drive.cpp)
foreach(field IN ITEMS ID SECRET)
set(KS_GOOGLE_CLIENT_${field} "$ENV{KSWITCHER_GOOGLE_CLIENT_${field}}")
@@ -222,6 +223,11 @@ add_test(NAME files-comparison-splitter
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
add_test(NAME files-smb-password
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_smb_password.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-smb-password PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_test(NAME files-space-analyzer-layout
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1"
@@ -343,7 +349,7 @@ add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --s
add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$<TARGET_FILE:KSwitcher>")
set_tests_properties(native-regressions PROPERTIES WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
install(TARGETS KSwitcher KSwitcherConfig KSwitcherScreenshot KSwitcherFiles RUNTIME DESTINATION .)
install(FILES LICENSE vendor/json-LICENSE.txt resources/files-archive-license.txt resources/files-image-license.txt DESTINATION .)
install(FILES LICENSE vendor/json-LICENSE.txt resources/files-archive-license.txt resources/files-image-license.txt resources/files-sftp-license.txt DESTINATION .)
add_custom_command(TARGET KSwitcher POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/dictionaries" "$<TARGET_FILE_DIR:KSwitcher>/dictionaries")
install(DIRECTORY dictionaries DESTINATION .)
+204 -32
View File
@@ -42,6 +42,13 @@ Warning і початковий фокус на No.
Назви файлів і папок передаються в UTF-8. Для старого сервера, який
використовує системну кодову сторінку Windows, увімкни в профілі
**Use Windows encoding for file names** і підключися знову.
Після закриття Files окремо для кожної FTP-панелі зберігаються профіль,
каталог і рядок курсора. При наступному запуску Files відкриває цей каталог
і вибирає попередній рядок, якщо він ще існує. Коли каталог недоступний,
панель показує попередню локальну папку й причину помилки. **Ctrl+R**
повторює підключення. Натискання рядка стану відкриває повну причину
помилки й підтвердження повторної спроби. Вибір іншого джерела скасовує
відновлення.
- F5 копіює поточний або позначені файли й папки між локальною та
підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої
панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі.
@@ -57,20 +64,87 @@ Warning і початковий фокус на No.
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
- **SFTP** у меню джерел обох панелей відкриває збережені SSH-підключення.
Shift+F4 додає профіль, F4 редагує, Enter підключається. Укажи ім’я
користувача, хост, порт (типово 22) та пароль або повний шлях до ключа.
Поле пароля приймає кодову фразу для ключа. Windows DPAPI захищає
збережений пароль або кодову фразу. Для ключа користувача підходить
незашифрований RSA PEM або ECDSA OpenSSH із файлом .pub поруч.
ECDSA OpenSSH підтримує кодову фразу. Ключ залишається у вказаному файлі.
- У **Test connection** звір SHA‑256-відбиток ключа хоста з адміністратором
сервера та підтвердь довіру. Після цього Files перевіряє вхід. **Save**
зберігає профіль і підтверджений відбиток. Якщо відбиток змінюється,
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 копіює між локальною
та SFTP-панеллю в обидва боки зі спільним прогресом, скасуванням і
підтвердженням конфліктів. Для заміни існуючого файла сервер має
підтримувати атомарне перейменування OpenSSH. Якщо сервер відмовляє
в заміні, Files показує причину й зберігає попередній файл.
- **SMB** у меню джерел обох панелей відкриває збережені підключення.
**New** додає назву й сервер або повний UNC-шлях. **Open** для сервера
показує видимі дискові шари. Відомий прихований шар можна додати як
повний UNC-шлях. Вибір шару або відкриття профілю з UNC-папкою переходить
до цієї папки в панелі, з якої викликали меню.
- Для SMB діють дозволи Windows. **Sign in** використовує вказаний
обліковий запис. Прапорець **Remember in Windows Credential Manager**
типово вимкнений. Коли його ввімкнено, після успішного підключення Windows
зберігає облікові дані для цього профілю. **Remove** видаляє профіль і
його збережені облікові дані після підтвердження.
- Якщо SMB недоступний, повідомлення показує причину й залишає список
підключень відкритим. **Open** повторює спробу. Коли Windows повідомляє
про наявний сеанс до цього сервера з іншим записом, Files пропонує
вибрати той запис або завершити попередній сеанс у Windows.
- **F9 → Commands → Compare files** порівнює два позначені текстові файли
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
рядків і підсвічуванням вставок, видалень і замін. У замінених рядках
виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8)
переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків.
FTP- та SFTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
рядків і підсвічуванням вставок, видалень і замін. **Unified** перемикає
на єдину колонку з номерами рядків обох файлів, видаленнями зі знаком −
і вставками зі знаком +. Перемикання зберігає поточний блок.
**Fold unchanged** згортає довгі незмінені ділянки до рядка з лічильником
і залишає до трьох рядків контексту перед і після кожного блока.
У замінених рядках виділяється змінений фрагмент. **Previous** (F7) і
**Next** (F8) переходять між блоками змін в обох поданнях.
Подвійний клік відкриває повний текст пари рядків.
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
Текст файлів і порожня область під ним мають білий фон, рядки
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
Центральний розділювач можна перетягнути мишею. Під час зміни розміру
У поданні поруч центральний розділювач можна перетягнути мишею. Під час зміни розміру
вікна пропорція колонок зберігається.
Ctrl+колесо змінює масштаб тексту в поточному вікні.
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
@@ -79,18 +153,25 @@ Warning і початковий фокус на No.
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
і меню Commands показує поточне призначення.
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
типово пропускаються. Перемикач **Show whitespace changes** показує їх
в обох поданнях і враховує під час згортання.
Вставлені й видалені порожні рядки враховуються завжди.
**Apply to left/right** копіює виділений блок у відповідну сторону.
Порівняння перераховується, а змінену сторону позначає зірочка.
**Undo** або **Ctrl+Z** повертає останню незаписану дію.
**Save left/right** зберігає відповідну сторону, **Ctrl+S** зберігає обидві.
Зовнішня зміна цільового файла зупиняє запис і залишає правки для перегляду.
Закриття зі змінами пропонує Save, Discard або Cancel.
Кнопка розгортання в системному заголовку збільшує вікно порівняння
до робочої області екрана. Повторне натискання відновлює попередній розмір.
Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM,
до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються
як рівнозначні.
Підтримуються UTF-8 і UTF-16 з BOM, до 2 МіБ і 100 000 рядків на файл.
Стилі переносу рядків порівнюються як рівнозначні. Під час запису
зберігаються кодування, BOM і наявні кінці рядків цільового файла.
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP.
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP, SFTP і SMB.
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
до закриття меню, навіть коли оновлюється список LAN.
@@ -127,8 +208,12 @@ Warning і початковий фокус на No.
виконує команду одразу. Коли рядок
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
У повноекранному терміналі (Ctrl+O) команда редагується в промпті
під виводом. Клік у терміналі повертає курсор у промпт. Стрілки вгору й
вниз без відкритого списку підказок переглядають спільну історію, а після
останньої команди вниз повертає чернетку. Підказки відкриваються біля
курсора. Ctrl+C перериває поточну команду, а за виділеного тексту виводу
копіює виділення. Escape з порожнім промптом також перериває команду.
Локальна команда запускається в папці активної панелі, яку показано
перед командним рядком. Після перемикання панелі або переходу до іншої
папки наступна команда використовує нову папку навіть у вже відкритому
@@ -167,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, позначення клавіш сірі на чорному тлі,
@@ -460,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 перемикає вигляд відповідної
@@ -541,6 +646,11 @@ Warning і початковий фокус на No.
- Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК.
- Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно.
- Якщо читання LAN-папки переривається через мережеву помилку, Files
зберігає поточний список і до трьох разів повторює читання того самого
ПК, диска й каталогу. Після відновлення курсор залишається на наявному
рядку. Рядок стану показує причину збою й дію **Ctrl+R** для повторної
спроби. Перехід в інший каталог або джерело скасовує попередню спробу.
- F5, F6, F8 і Shift+Delete у віддалених панелях використовують спільні підтвердження, попередження й прогрес. F5/F6 працюють із файлами та деревами папок між локальними й віддаленими панелями, зокрема між двома різними ПК. Між шляхами одного віддаленого ПК вміст копіюється на ньому. F8 використовує кошик того ПК, на якому лежить файл.
- Після розриву з’єднання повтори F5 або F6 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення.
@@ -590,12 +700,15 @@ Warning і початковий фокус на No.
показують перший кадр. Пошкоджені та надто великі файли показують повідомлення.
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
останні відвідані локальні папки. Повторний візит підіймає один запис
угору, порядок зберігається після перезапуску. Enter або клік відкриває
шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис.
останні відвідані локальні, FTP, SFTP та LAN-папки. Повторний візит підіймає
один запис угору, порядок зберігається після перезапуску. Enter або клік
відкриває шлях у панелі, з якої викликали меню. Віддалені записи містять
шлях і ідентифікатор збереженого FTP- чи SFTP-профілю або спареного ПК. Паролі
зберігаються в захищених налаштуваннях профілів. Delete прибирає вибраний
запис із недавніх.
- У локальному заголовку кнопки ← та → переходять назад і вперед
в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..`
- Кнопки ← та → переходять назад і вперед в історії відповідної панелі,
зокрема між локальними, FTP, SFTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..`
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі.
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
@@ -604,7 +717,10 @@ Warning і початковий фокус на No.
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
а Esc повертає до тих самих панелей і курсора.
- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі.
- У заголовку FTP- чи SFTP-папки клік по назві профілю відкриває збережені
підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери
та їхні диски. Поле шляху й доповнення працюють у поточному джерелі.
Для FTP абсолютний шлях починається з /.
## Спільні елементи діалогів
@@ -630,12 +746,55 @@ 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 без змін.
- У Git Changes кнопка **History** або **F6** відкриває історію. **Branch**
вибирає локальну чи remote-tracking гілку для перегляду. Зірочка
позначає поточну гілку або detached HEAD. Вибір не змінює checkout.
Сусідня панель показує повідомлення коміту та змінені шляхи.
Для merge-коміту список шляхів відповідає різниці з першим батьком.
**More** або **F7** додає наступні 50 комітів, **Ctrl+R** перечитує гілки,
**F6** повертає до Git Changes, а **Esc** повертає до файлових панелей.
- У Git Changes **Stage** та **Unstage** діють на вибраний запис.
Unstage перейменування відновлює обидва індексні шляхи. Якщо шлях уже
має staged-версію, Stage запитує підтвердження заміни.
- **Commit** показує checkout-гілку й усі staged-шляхи, включно з
прихованими фільтром. Якщо гілка, HEAD або staged-вміст змінилися
після перегляду, Files зберігає повідомлення й вимагає нового перегляду.
Після коміту показує хеш і перечитує Git Changes. Для detached HEAD,
розв’язання конфліктів або продовження активної операції використовуй
Git у терміналі.
- Stage використовує clean-фільтри Git. Локальний Commit враховує
**commit.gpgSign** і налаштований засіб підписування. Git hooks для
цих операцій Files вимкнено. Для комітів із hooks або інтерактивним
підписуванням використовуй Git у терміналі.
- **F9 → Commands → Environment Variables** показує області **User**,
**System** і **Process**, джерело, сире та розгорнуте значення.
Process показує середовище поточного процесу Files лише для читання.
**Edit** зберігає тип реєстрового значення. **Copy to User** і
**Copy to System** переносять сире значення та його тип і запитують
підтвердження, якщо визначення існує. Якщо значення змінилося після
відкриття діалогу або Windows відмовила в доступі, Files показує причину.
Запущені сеанси PowerShell зберігають своє середовище. Після зміни
перезапусти Files, щоб вбудований PowerShell успадкував нові значення.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
@@ -677,6 +836,11 @@ Warning і початковий фокус на No.
- Секції поточного файла й загального прогресу мають однаковий вертикальний відступ від вмісту до верхньої та нижньої ліній. Cancel стоїть по центру спільної нижньої секції.
- Обидві шкали займають усю ширину вмісту. Відсотки показуються по центру шкали, а її висота враховує поточний шрифт.
- **Options** у Copy/Move задає маску імен файлів із символами `*` і `?`. Порожня маска або `*` копіює всі файли й порожні папки. З іншою маскою Files зберігає структуру папок із відповідними файлами. У Move файли поза маскою залишаються в джерелі.
- Додаткові папки вводяться абсолютними шляхами, по одному на рядок, на тому самому комп’ютері або підключенні, що й основне призначення. Однакові папки обробляються один раз. У Move джерело видаляється після успішного копіювання елемента в усі вибрані папки. У разі пропуску або збою вже записані копії зберігаються. Підсумок показує кількість повністю скопійованих елементів по всіх призначеннях і загальну кількість записаних файлів.
- **Preserve modification time** зберігає час зміни там, де ціль підтримує його встановлення. Збереження часу підтримують Windows і SFTP. FTP-призначення використовує час сервера. **Preserve Windows permissions** переносить DACL між файловими системами Windows, які підтримують цей тип прав. Наявні папки, у які додаються файли, зберігають власні права й час.
- Оцінка залишку часу в прогресі з’являється після кількох вимірювань швидкості. Довга пауза скидає оцінку. Скасування й конфлікти використовують спільні діалоги.
## Попередження про конфлікт
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
@@ -694,6 +858,14 @@ Warning і початковий фокус на No.
- F8 переміщує підтверджені елементи в кошик Windows. Shift+Delete видаляє підтверджене дерево від вкладених елементів до батьківської папки. Прогрес і підсумок окремо показують успішні, пропущені й невдалі дії.
- Cancel і Esc у вікні прогресу відкривають спільне червоне підтвердження скасування. Yes зупиняє операцію, а No або Esc у підтвердженні повертає до прогресу. Початковий фокус стоїть на No.
## Обмін і компонування панелей
- **Commands → Swap panels** або **Ctrl+U** міняє панелі місцями. Активна панель, шлях, курсор, прокручування, позначки, поточний режим і Quick View переходять разом.
- **Options → File panel modes → Panel layout** містить незалежні параметри для правої кнопки, кнопок дисків і компактного компонування. За замовчуванням ці параметри вимкнені.
- **Mark items with the right mouse button** перемикає позначку рядка. **Shift+права кнопка**, **Shift+F10** і клавіша **Menu** відкривають контекстне меню. Права кнопка на порожньому місці також відкриває контекстне меню панелі.
- **Show drive buttons** додає наявні локальні диски над панелями. Кнопка відкриває корінь диска в активній панелі. Якщо всі диски не поміщаються, **…** відкриває Change drive.
- **Compact commander layout** скорочує проміжки між шляхом, рядками та станом, зберігаючи розмір шрифту, командний рядок і клавіші дій.
## Перевірка змін
Відкрий Copy і Warning в одній збірці та порівняй висоту нижніх секцій, центрування, повноту підписів і видимість фокуса. Перевір Tab, стрілки й Esc. Після узгодження нового правила онови відповідний розділ цього документа.
+65 -2
View File
@@ -9,9 +9,72 @@ with all online paired computers: history and the active clipboard.
## Trusted LAN clients
Open **Settings → Computers → Manage computers → Trusted clients** and choose **Add client…**. Select the Dirlume executable, confirm, then click **Save** in Settings. Dirlume can list existing LAN pairs, browse their drives, and download regular files using each remote computer’s file-access permissions. Pairing credentials stay in the resident KSwitcher process.
Open **Settings → Computers → Manage computers → Trusted clients** and choose
**Add client…**. Select the executable, confirm, and click **Save** in Settings.
A newly approved or previously enrolled executable can list pairs, browse
drives and download regular files. For each executable you can separately
enable **Allow write** for creating, editing, renaming, and copying, and
**Allow delete** for the recycle bin and permanent deletion. Move needs both
permissions. The paired computer's Windows access and file-sharing settings
still apply. KSwitcher retains the pairing credentials.
Select an executable, choose **Remove**, then click **Save** to revoke access. Add the executable again after updating it, since KSwitcher checks the approved path and SHA-256 fingerprint.
Select an executable and choose **Remove**, or turn off an individual grant,
then click **Save** to revoke access. KSwitcher checks grants again during
streaming and before publication or source removal. Add an updated executable
again because approval covers its path and SHA-256 fingerprint.
### Local trusted-client protocol
The Windows pipe is `\\.\pipe\KSwitcher.LAN.Clients.v1.<session>` and accepts
one request per connection from the resident's user. Send a JSON object in an
unsigned 32-bit little-endian length frame (maximum 16 KiB for the request).
Replies have the same length prefix. After the last reply, send one raw
acknowledgement byte and close. An error reply is a JSON object containing
a string `error`. Existing `peers`, `drives`, `list` and `download` requests
retain their original reply formats.
- `capabilities` optionally takes a `peer`. It returns the broker `protocol`
(2), `hostRevision`, and boolean `write`, `delete`, `move`,
`revisionRead`, `onHostTransfer`, and `localEndpoint` fields. With no peer,
the fields describe the local broker and its grants. With a peer, the flags
also account for its supported protocol. A peer with revision 0 still
supports legacy browsing and downloading.
- `stat` takes `peer` and an absolute `path`. It returns Windows attributes,
byte `size` and `modified` (Windows FILETIME). Preserve 64-bit integers
without rounding. `readFile` takes the same arguments plus an optional
`expected` object with `size` and `modified`. It returns metadata followed
by raw frames up to 64 KiB and a zero-length frame. Require the declared
byte count and the zero-length frame before accepting the download.
- `writeFile` takes `peer`, `path`, and the incoming byte `size`. Omit
`expected` for an exclusive create. Include the original `size` and
`modified` in `expected` for an edit. After the `ready` JSON reply, send
raw frames up to 64 KiB followed by a zero-length frame. The final reply
contains the saved metadata or an error. The host stages bytes until
the upload is complete and checks the revision when publishing an edit.
- `mkdir`, `rename`, `recycle`, and `delete` take `peer` and `path`.
Rename also takes a single new `name` and fails if the destination exists.
Permanent deletion of nonempty directories requires `recursive: true`.
The recycle bin is subject to Windows availability on the paired host.
- `transfer` takes `source` and `target` objects with a `peer` and `path`
each, optional `move` (default false), and a `conflict` policy of `fail`
(default), `skip`, or `replace`. Replace merges directories and replaces
regular files after validating the destination revision. The broker
allows at most one local endpoint, represented by `"peer": null`. For a
local endpoint the client must open the pipe with Windows impersonation
enabled, and local files are accessed using the caller's token.
- Transfer replies are JSON progress frames containing `type: "progress"`,
`phase` (`copy` or `remove`), source `path`, byte `done` and `total` for the current file, and
`completed` and `skipped` item counts. Reply to each progress frame with
a JSON frame containing `continue: true` or `continue: false`. The
final frame has `type: "complete"` and counts, or an error. Transfers
on one paired computer use its own file service even across drives. The
local pipe exchanges only control and status for transfers.
- For a move, the copy phase finishes before source deletion begins.
Skipped items remain at the source. Cancellation or failure can leave
previously completed destination items. Failure during source cleanup
can leave a partially removed source tree. Unpublished file uploads are
discarded. File-tree transfer does not follow junctions or symbolic
links within the tree.
## Remote files and diagnostic logs
+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()
+26
View File
@@ -0,0 +1,26 @@
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
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)
set(BUILD_SHARED_LIBS OFF)
set(BUILD_EXAMPLES OFF)
set(BUILD_TESTING OFF)
set(LIBSSH2_DISABLE_INSTALL ON)
set(LIBSSH2_BUILD_DOCS OFF)
set(CRYPTO_BACKEND WinCNG)
set(ENABLE_ECDSA_WINCNG ON)
FetchContent_MakeAvailable(kswitcher_libssh2)
endfunction()
kswitcher_add_ssh_library()
+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);
+2 -1
View File
@@ -14,6 +14,7 @@ Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -Destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-text-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-archive-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-image-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-sftp-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'LAN-PREVIEW.md') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'dictionaries') -Destination $destination -Recurse -Force
@@ -22,7 +23,7 @@ Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') -
Copy-Item -LiteralPath (Join-Path $root 'build\release\tools\StayHere.exe') -Destination (Join-Path $destination 'tools\StayHere.exe') -Force
Copy-Item -LiteralPath (Join-Path $root 'utilities\StayHere\README.md') -Destination (Join-Path $destination 'tools\StayHere-README.md') -Force
# Enumerate the distributable files explicitly; do not include a user's data directory.
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','files-archive-license.txt','files-image-license.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ }
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','files-archive-license.txt','files-image-license.txt','files-sftp-license.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ }
$entries = foreach ($path in $files) {
foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) {
@{path=$file.FullName.Substring($destination.Length+1).Replace('\','/'); size=$file.Length; sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()}
+40
View File
@@ -0,0 +1,40 @@
libssh2
https://libssh2.org/
Upstream revision dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4
/* Copyright (C) 2004-2007 Sara Golemon <[email protected]>
* Copyright (C) 2005,2006 Mikhail Gusarov <[email protected]>
* Copyright (C) 2006-2007 The Written Word, Inc.
* Copyright (C) 2007 Eli Fant <[email protected]>
* Copyright (C) 2009-2023 Daniel Stenberg
* Copyright (C) 2008, 2009 Simon Josefsson
* Copyright (C) 2000 Markus Friedl
* Copyright (C) 2015 Microsoft Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
+195 -13
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
@@ -160,6 +169,10 @@ BEGIN
COMBOBOX 273, 132, 40, 108, 74, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "&Right panel", 507, 251, 27, 117, 11
COMBOBOX 274, 251, 40, 117, 74, CBS_DROPDOWNLIST | WS_TABSTOP
AUTOCHECKBOX "Mark items with the right mouse button", 520, 132, 64, 245, 13
AUTOCHECKBOX "Show drive buttons", 521, 132, 81, 245, 13
AUTOCHECKBOX "Compact commander layout", 522, 132, 98, 245, 13
LTEXT "Shift+right-click opens the Windows context menu.", 523, 132, 115, 245, 13
GROUPBOX "Wide panel columns", 275, 129, 27, 259, 59
LTEXT "Size column &width (6–16 characters)", 276, 138, 44, 175, 10
EDITTEXT 201, 335, 41, 43, 14, ES_NUMBER | ES_AUTOHSCROLL
@@ -253,8 +266,9 @@ BEGIN
LTEXT "Existing files:", 212, 14, 57, 122, 14, SS_CENTERIMAGE
COMBOBOX 213, 140, 57, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
AUTOCHECKBOX "Also ask on read-only files", 214, 14, 77, 322, 14
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 92, 86, 18
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 92, 86, 18
CONTROL "&Options...", 215, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 222, 92, 86, 18
END
103 DIALOGEX 0, 0, 460, 126
@@ -418,11 +432,12 @@ EXSTYLE WS_EX_APPWINDOW
CAPTION "Compare files"
FONT 9, "Segoe UI"
BEGIN
LTEXT "", 400, 4, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 401, 259, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 45, 510, 207
LTEXT "", 400, 4, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 401, 259, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 65, 510, 187
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
LTEXT "", 403, 216, 12, 98, 14
CONTROL "", 408, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 28, 490, 19
END
115 DIALOGEX 0, 0, 290, 58
@@ -430,7 +445,7 @@ STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Compare files"
FONT 10, "Consolas"
BEGIN
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
LTEXT "Reading and comparing files...", 548, 14, 15, 262, 13
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
END
@@ -511,3 +526,170 @@ BEGIN
CONTROL "&Create", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
END
121 DIALOGEX 0, 0, 430, 192
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB connections"
FONT 10, "Consolas"
BEGIN
LTEXT "", 540, 16, 16, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 541, "ListBox", LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP, 16, 31, 398, 103
LTEXT "", 542, 16, 140, 398, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 543, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 19, 166, 56, 17
CONTROL "&New", 544, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 166, 56, 17
CONTROL "&Edit", 545, "Button", BS_OWNERDRAW | WS_TABSTOP, 145, 166, 56, 17
CONTROL "Re&move", 546, "Button", BS_OWNERDRAW | WS_TABSTOP, 208, 166, 56, 17
CONTROL "&Sign in", 547, "Button", BS_OWNERDRAW | WS_TABSTOP, 271, 166, 60, 17
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 338, 166, 56, 17
END
122 DIALOGEX 0, 0, 355, 113
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB connection"
FONT 10, "Consolas"
BEGIN
LTEXT "Connection &name", 550, 16, 15, 323, 12
FAR_EDIT(551, 0, 16, 29, 323, 15)
LTEXT "&Server or UNC folder", 552, 16, 52, 323, 12
FAR_EDIT(553, 0, 16, 66, 323, 15)
LTEXT "", 554, 10, 87, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 93, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 93, 80, 17
END
123 DIALOGEX 0, 0, 355, 153
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB sign in"
FONT 10, "Consolas"
BEGIN
LTEXT "", 555, 16, 15, 323, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "&User name", 556, 16, 32, 323, 12
FAR_EDIT(557, 0, 16, 46, 323, 15)
LTEXT "&Password", 558, 16, 69, 323, 12
EDITTEXT 559, 16, 83, 323, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
AUTOCHECKBOX "&Remember in Windows Credential Manager", 560, 16, 106, 323, 13
LTEXT "", 561, 10, 125, 1, 1, NOT WS_VISIBLE
CONTROL "&Connect", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 132, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 132, 80, 17
END
124 DIALOGEX 0, 0, 420, 207
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SFTP connection"
FONT 10, "Consolas"
BEGIN
LTEXT "Connection &name", 381, 16, 15, 388, 12
FAR_EDIT(382, 0, 16, 28, 388, 15)
LTEXT "Server &host", 383, 16, 49, 292, 12
LTEXT "P&ort", 384, 328, 49, 76, 12
FAR_EDIT(385, 0, 16, 62, 302, 15)
FAR_EDIT(386, ES_NUMBER, 328, 62, 76, 15)
LTEXT "&User name", 387, 16, 83, 182, 12
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, 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
126 DIALOGEX 0, 0, 420, 213
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Commit staged changes"
FONT 10, "Consolas"
BEGIN
LTEXT "", 594, 16, 15, 388, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 595, 16, 31, 388, 13, SS_NOPREFIX
LISTBOX 596, 16, 45, 388, 61, LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "Commit &message", 597, 16, 112, 388, 13
EDITTEXT 598, 16, 127, 388, 39, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN
LTEXT "", 599, 16, 170, 388, 13, SS_ENDELLIPSIS | SS_NOPREFIX | NOT WS_VISIBLE
LTEXT "", 600, 10, 186, 1, 1, NOT WS_VISIBLE
CONTROL "&Commit", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 125, 193, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 215, 193, 80, 17
END
127 DIALOGEX 0, 0, 458, 224
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Environment Variables"
FONT 10, "Consolas"
BEGIN
LTEXT "&Scope", 610, 16, 16, 58, 13
COMBOBOX 611, 77, 15, 120, 75, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
LTEXT "", 613, 16, 34, 426, 13, SS_PATHELLIPSIS | SS_NOPREFIX
LISTBOX 612, 16, 50, 172, 119, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "", 614, 197, 50, 245, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "Ra&w value", 620, 197, 66, 245, 13
EDITTEXT 615, 197, 80, 245, 30, ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY
LTEXT "E&xpanded value", 621, 197, 115, 245, 13
EDITTEXT 616, 197, 129, 245, 39, ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY
LTEXT "", 617, 16, 174, 426, 24, SS_NOPREFIX
LTEXT "", 618, 10, 199, 1, 1, NOT WS_VISIBLE
CONTROL "&Edit", 622, "Button", BS_OWNERDRAW | WS_TABSTOP, 27, 204, 59, 15
CONTROL "Copy to &User", 623, "Button", BS_OWNERDRAW | WS_TABSTOP, 89, 204, 89, 15
CONTROL "Cop&y to System", 624, "Button", BS_OWNERDRAW | WS_TABSTOP, 181, 204, 100, 15
CONTROL "&Refresh", 625, "Button", BS_OWNERDRAW | WS_TABSTOP, 285, 204, 66, 15
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 354, 204, 65, 15
END
128 DIALOGEX 0, 0, 366, 122
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Edit environment definition"
FONT 10, "Consolas"
BEGIN
LTEXT "", 630, 16, 16, 334, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "Ra&w value", 631, 16, 33, 334, 13
EDITTEXT 632, 16, 47, 334, 42, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN
LTEXT "", 633, 10, 94, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 100, 78, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 186, 100, 78, 16
END
129 DIALOGEX 0, 0, 388, 177
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Copy/Move options"
FONT 10, "Consolas"
BEGIN
LTEXT "File &mask", 645, 14, 15, 360, 13
FAR_EDIT(640, 0, 14, 28, 360, 17)
LTEXT "Additional &folders on this computer (one absolute path per line)", 646, 14, 53, 360, 13
EDITTEXT 641, 14, 67, 360, 40, ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL | WS_VSCROLL
AUTOCHECKBOX "Preserve modification &time", 642, 14, 112, 360, 14
AUTOCHECKBOX "Preserve Windows &permissions", 643, 14, 127, 360, 14
LTEXT "Extra folders use the same destination computer or connection.", 647, 14, 143, 360, 13
LTEXT "", 644, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 161, 86, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 200, 161, 86, 16
END
+48 -3
View File
@@ -4,12 +4,15 @@ const terminal = new Terminal({
fontSize: 16,
cursorBlink: false,
cursorInactiveStyle: 'none',
disableStdin: true,
theme: { background: '#181818', foreground: '#e8e8e8' },
});
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,7 +25,15 @@ terminal.loadAddon(fit);
const host = document.getElementById('terminal');
terminal.open(host);
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true);
const prompt = message => bridge.postMessage('prompt:' + message);
let sshInput = false;
host.addEventListener('pointerup', () => {
if (!sshInput) prompt('focus-input');
}, true);
terminal.onData(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;
let traceBudget = 4096;
@@ -52,9 +63,28 @@ function anchorOutput() {
currentOffset = offset;
trace(2);
}
const promptKeys = new Set([
'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End',
'Tab', 'Escape', 'Delete', 'Backspace', 'F1',
]);
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);
event.preventDefault();
return false;
}
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter');
if (!event.repeat) prompt(event.shiftKey ? 'shift-enter' : 'enter');
event.preventDefault();
return false;
}
@@ -85,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>;
+10 -2
View File
@@ -95,9 +95,17 @@ void rememberCommand(const std::wstring &command)
void recallCommand(size_t index)
{
terminalHistoryIndex=index;
SetWindowTextW(terminalInput,index<terminalHistory.size()?terminalHistory[index].command.c_str():L"");
SetWindowTextW(terminalInput,index<terminalHistory.size()?terminalHistory[index].command.c_str():terminalHistoryDraft.c_str());
SetFocus(terminalInput);
SendMessageW(terminalInput,EM_SETSEL,-2,-1);
suppressCurrentCompletion();
}
void recallPreviousCommand()
{
if(!terminalHistoryIndex) return;
if(terminalHistoryIndex==terminalHistory.size()) terminalHistoryDraft=terminalInputText();
recallCommand(terminalHistoryIndex-1);
}
void showCommandHistory(HWND owner);
@@ -112,7 +120,7 @@ bool handleCommandHistoryKey(HWND window,const MSG &message)
if(binding==commandHistoryKeys[0] && (message.hwnd==terminalInput ||
message.hwnd==panels[0].list || message.hwnd==panels[1].list))
{
if(terminalHistoryIndex) recallCommand(terminalHistoryIndex-1);
recallPreviousCommand();
return true;
}
if(binding!=commandHistoryKeys[1]) return false;
+587 -148
View File
@@ -66,7 +66,12 @@ struct CompareFile
fs::path path;
std::wstring label;
std::optional<FilesPeer> peer;
std::optional<FtpProfile> ftp;
std::optional<TransferProfile> ftp;
std::optional<ks::files::RemoteTextSource> remote;
ks::files::RemoteTextRevision revision;
std::string originalBytes;
std::wstring originalText;
bool dirty{};
};
struct CompareRow
@@ -79,14 +84,31 @@ struct CompareRow
bool hasChange(bool showWhitespace) const {return changed && (showWhitespace || !whitespaceOnly);}
};
struct ComparisonDisplayRow
{
int first=-1,past{};
int side=-1;
bool folded() const {return past>first+1;}
};
struct FileComparison
{
static constexpr std::array controls{400,401,402,403,407};
static constexpr std::array controls{400,401,402,403,407,408};
CompareFile files[2];
std::vector<std::wstring> lines[2];
ks::files::ComparisonText text[2];
std::vector<CompareRow> rows;
std::vector<int> changes,allChanges;
bool showWhitespace{};
std::vector<ComparisonDisplayRow> displayRows;
std::vector<std::array<int,2>> displayPositions;
std::vector<int> displayBlockStarts;
struct Undo
{
int side{};
ks::files::ComparisonReplace edit;
};
std::vector<Undo> undo;
bool working{};
bool showWhitespace{},unified{},foldContext{};
RECT initialClient{};
std::array<RECT,controls.size()> initialControls{};
SIZE minimumWindow{};
@@ -118,7 +140,8 @@ void layoutComparisonHeaders(HWND dialog,const FileComparison &comparison)
RECT bounds{};
GetClientRect(list,&bounds);
MapWindowPoints(list,dialog,reinterpret_cast<POINT*>(&bounds),2);
const auto middle=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const auto width=bounds.right-bounds.left;
const auto middle=bounds.left+(comparison.unified?width/2:comparisonSplitX(comparison,width));
const auto inset=comparison.initialControls[0].left;
for(int side=0;side<2;++side)
{
@@ -206,63 +229,132 @@ bool handleComparisonMessage(MSG &message)
}
return true;
}
std::vector<std::wstring> readComparisonLines(const CompareFile &input,const std::atomic_bool &canceled)
struct CompareCache
{
struct TemporaryDirectory
fs::path directory;
fs::path create()
{
fs::path path;
~TemporaryDirectory()
{
if(path.empty()) return;
std::error_code ignored;
fs::remove_all(path,ignored);
}
} temporary;
auto path=input.path;
if(input.ftp || input.peer)
{
const auto directory=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
requireFileOperation(fs::create_directory(directory),ERROR_ALREADY_EXISTS);
temporary.path=directory;
path=directory/L"file";
CopyHost source(input.peer?&*input.peer:nullptr,input.ftp);
const auto info=source.stat(input.path,canceled);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_NOT_SUPPORTED);
requireFileOperation(info->size<=compareFileLimit,ERROR_FILE_TOO_LARGE);
FilesConnection local;
const auto progress=[&](uint64_t,uint64_t){return !canceled;};
if(source.ftp) downloadFtpFile(*source.ftp,local,input.path,path,*info,false,progress);
else ks::lan::streamFile(*source.files,local,input.peer->id,input.path,path,info->size,
info->modified,false,false,progress);
auto path=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
requireFileOperation(fs::create_directory(path),ERROR_ALREADY_EXISTS);
directory=std::move(path);
return directory/L"file";
}
ks::files::TextDocument document(path,false);
~CompareCache()
{
if(directory.empty()) return;
std::error_code ignored;
fs::remove_all(directory,ignored);
}
};
ks::files::RemoteTextRevision comparisonLocalRevision(const fs::path &path)
{
WIN32_FILE_ATTRIBUTE_DATA info{};
checkFileOperation(GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&info)!=FALSE);
requireFileOperation(!(info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY),ERROR_NOT_SUPPORTED);
const auto size=(uint64_t(info.nFileSizeHigh)<<32)|info.nFileSizeLow;
const auto stamp=(uint64_t(info.ftLastWriteTime.dwHighDateTime)<<32)|info.ftLastWriteTime.dwLowDateTime;
return {size,stamp,(info.dwFileAttributes&(FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_REPARSE_POINT))==0};
}
std::string comparisonRawBytes(const ks::files::TextDocument &document,const std::atomic_bool &canceled)
{
requireFileOperation(document.size()<=compareFileLimit,ERROR_FILE_TOO_LARGE);
std::string raw;
raw.reserve(static_cast<size_t>(document.size()));
while(raw.size()<document.size())
{
requireFileOperation(!canceled,ERROR_CANCELLED);
raw+=document.readBytes(raw.size(),ks::files::hexPageBytes);
}
return raw;
}
ks::files::ComparisonText readComparisonLines(CompareFile &input,const std::atomic_bool &canceled)
{
CompareCache temp;
auto path=input.path;
if(input.ftp) input.remote=transferTextSource(*input.ftp);
else if(input.peer)
{
FilesConnection source(&*input.peer);
const auto info=statFile(source,input.path);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),ERROR_NOT_SUPPORTED);
input.remote=ks::files::createLanTextSource(*input.peer);
}
if(input.remote)
{
path=temp.create();
input.revision=input.remote->download(input.path,path,false,[&](uint64_t,uint64_t){return !canceled;},
compareFileLimit);
}
else input.revision=comparisonLocalRevision(path);
ks::files::TextDocument document(path,false);
input.originalBytes=comparisonRawBytes(document,canceled);
std::string text;
for(uint64_t page=0;page<document.pages() && !canceled;++page) text+=document.readPage(page);
requireFileOperation(!canceled,ERROR_CANCELLED);
if(std::any_of(text.begin(),text.end(),[](unsigned char ch){
return ch<32 && ch!='\t' && ch!='\r' && ch!='\n' && ch!='\f';
})) throw std::runtime_error("Select two text files.");
if(!input.remote && (comparisonLocalRevision(path).modified!=input.revision.modified ||
comparisonRawBytes(document,canceled)!=input.originalBytes))
throw std::runtime_error("The file changed while it was read for comparison.");
if(text.empty()) return {};
const auto bytes=static_cast<int>(text.size());
const auto count=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,nullptr,0);
if(!count) throw std::runtime_error("Compare files supports UTF-8 and UTF-16 text.");
std::wstring decoded(count,L'\0');
checkFileOperation(MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,decoded.data(),count)!=0);
std::vector<std::wstring> lines;
size_t start=0;
while(true)
auto result=ks::files::splitComparisonText(decoded);
if(result.lines.size()>100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
input.originalText=std::move(decoded);
return result;
}
void saveComparisonFile(CompareFile &file,const ks::files::ComparisonText &text,const std::atomic_bool &canceled)
{
requireFileOperation(file.revision.editable,ERROR_ACCESS_DENIED);
CompareCache temporary;
auto target=file.path;
if(file.remote)
{
requireFileOperation(!canceled,ERROR_CANCELLED);
if(lines.size()==100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
const auto end=decoded.find_first_of(L"\r\n",start);
lines.push_back(decoded.substr(start,end==decoded.npos?end:end-start));
if(end==decoded.npos) break;
start=end+((decoded[end]==L'\r' && end+1<decoded.size() && decoded[end+1]==L'\n')?2:1);
target=temporary.create();
const auto revision=file.remote->download(file.path,target,true,[&](uint64_t,uint64_t){return !canceled;},
compareFileLimit);
if(revision.modified!=file.revision.modified || revision.size!=file.revision.size)
throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving.");
}
return lines;
else
{
const auto revision=comparisonLocalRevision(target);
requireFileOperation(revision.editable,ERROR_ACCESS_DENIED);
if(revision.modified!=file.revision.modified || revision.size!=file.revision.size)
throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving.");
}
ks::files::TextDocument document(target,true);
if(comparisonRawBytes(document,canceled)!=file.originalBytes)
throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving.");
auto joined=text.joined();
const auto contents=ks::utf8(joined);
const auto bytes=document.encoding()==ks::files::TextEncoding::utf8?contents.size():
joined.size()*sizeof(wchar_t);
requireFileOperation(bytes+document.boundary(0)<=compareFileLimit,ERROR_FILE_TOO_LARGE);
for(uint64_t page=1;page<document.pages();++page) document.stage(page,{});
document.stage(0,contents);
requireFileOperation(!canceled,ERROR_CANCELLED);
if(!document.save()) throw std::runtime_error("The file was saved but could not be reopened.");
if(file.remote)
file.revision=file.remote->upload(file.path,target,file.revision);
else file.revision=comparisonLocalRevision(target);
const std::atomic_bool committed{};
file.originalBytes=comparisonRawBytes(document,committed);
file.originalText=std::move(joined);
file.dirty=false;
}
std::wstring_view comparisonContent(std::wstring_view line)
@@ -274,7 +366,7 @@ std::wstring_view comparisonContent(std::wstring_view line)
void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
{
const auto &left=result.lines[0],&right=result.lines[1];
const auto &left=result.text[0].lines,&right=result.text[1].lines;
std::map<std::wstring_view,unsigned> ids;
std::map<unsigned,unsigned> blankIds;
unsigned nextId=1;
@@ -313,8 +405,6 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
const auto append=[&](int x,int y)
{
CompareRow row{x,y,x<0 || y<0 || left[x]!=right[y]};
if(row.changed && (result.rows.empty() || !result.rows.back().changed))
result.allChanges.push_back(static_cast<int>(result.rows.size()));
if(row.changed && x>=0 && y>=0)
{
const auto &l=left[x],&r=right[y];
@@ -328,8 +418,6 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
if(row.commonEnd && l[l.size()-row.commonEnd]>=0xdc00 && l[l.size()-row.commonEnd]<=0xdfff)
--row.commonEnd;
}
if(row.hasChange(false) && (result.rows.empty() || !result.rows.back().hasChange(false)))
result.changes.push_back(static_cast<int>(result.rows.size()));
result.rows.push_back(row);
};
const auto change=[&](size_t x,size_t y,size_t countLeft,size_t countRight)
@@ -436,6 +524,233 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
append(static_cast<int>(a.size()-suffix+i),static_cast<int>(b.size()-suffix+i));
}
enum ComparisonCommand { applyLeft=409,applyRight,undoCompare,saveLeft,saveRight,saveComparison,
unifiedCompare,foldCompareContext };
struct ComparisonProgress
{
const wchar_t *status;
bool cancelable=true;
std::atomic_bool canceled{};
};
INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp);
template<class Work>
bool runComparisonWork(HWND owner,const wchar_t *status,bool cancelable,const Work &work)
{
ComparisonProgress state{status,cancelable};
FileOperationUi worker;
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
comparisonProgressDialog,reinterpret_cast<LPARAM>(&state),false);
if(!progress.window()) throw std::runtime_error("Could not open the comparison progress dialog.");
progress.show();
try {worker.run(progress.window(),state.canceled,[&]{work(state.canceled);});}
catch(const std::system_error &error)
{
if(error.code().value()==ERROR_CANCELLED) return false;
throw;
}
return !state.canceled;
}
std::optional<ks::files::ComparisonReplace> comparisonBlock(const FileComparison &comparison,int side,LRESULT selected)
{
if(selected<0 || static_cast<size_t>(selected)>=comparison.rows.size() ||
!comparison.rows[selected].hasChange(comparison.showWhitespace)) return {};
auto first=static_cast<size_t>(selected),end=first+1;
while(first>0 && comparison.rows[first-1].hasChange(comparison.showWhitespace)) --first;
while(end<comparison.rows.size() && comparison.rows[end].hasChange(comparison.showWhitespace)) ++end;
const auto line=[](const CompareRow &row,int file){return file==0?row.left:row.right;};
const auto &target=comparison.text[side];
const auto &source=comparison.text[1-side];
ks::files::ComparisonReplace edit{target.lines.size()};
for(size_t row=first;row<end;++row)
{
const auto old=line(comparison.rows[row],side);
const auto incoming=line(comparison.rows[row],1-side);
if(old>=0)
{
edit.start=std::min(edit.start,static_cast<size_t>(old));
++edit.count;
}
if(incoming>=0)
{
edit.lines.push_back(source.lines[incoming]);
edit.endings.push_back(old>=0?target.endings[old]:target.preferred);
}
}
if(!edit.count)
for(size_t row=end;row<comparison.rows.size();++row)
if(const auto next=line(comparison.rows[row],side);next>=0)
{
edit.start=static_cast<size_t>(next);
break;
}
return edit;
}
void updateComparisonSummary(HWND dialog,const FileComparison &comparison);
ComparisonDisplayRow comparisonDisplayAnchor(const FileComparison &comparison,LRESULT position)
{
if(position<0 || static_cast<size_t>(position)>=comparison.displayRows.size()) return {};
return comparison.displayRows[position];
}
int comparisonDisplayPosition(const FileComparison &comparison,ComparisonDisplayRow anchor)
{
if(anchor.first<0 || comparison.displayPositions.empty()) return -1;
const auto last=static_cast<int>(comparison.displayPositions.size())-1;
const auto &positions=comparison.displayPositions[std::min(anchor.first,last)];
if(anchor.side>=0 && positions[anchor.side]>=0) return positions[anchor.side];
if(positions[0]<0) return positions[1];
if(positions[1]<0) return positions[0];
return std::min(positions[0],positions[1]);
}
void comparisonUpdateRows(HWND dialog,FileComparison &comparison,ComparisonDisplayRow selected,
ComparisonDisplayRow top={})
{
const auto list=GetDlgItem(dialog,402);
comparison.displayRows.clear();
const auto size=static_cast<int>(comparison.rows.size());
comparison.displayPositions.assign(size,{-1,-1});
comparison.displayBlockStarts.clear();
const auto append=[&](int first,int past,int side=-1)
{
const auto position=static_cast<int>(comparison.displayRows.size());
comparison.displayRows.push_back({first,past,side});
for(int row=first;row<past;++row)
{
auto &positions=comparison.displayPositions[row];
if(side<0) positions={position,position};
else positions[side]=position;
}
};
const auto changed=[&](int row){return comparison.rows[row].hasChange(comparison.showWhitespace);};
for(int first=0;first<size;)
{
const auto isChange=changed(first);
int past=first+1;
while(past<size && changed(past)==isChange) ++past;
if(isChange) comparison.displayBlockStarts.push_back(static_cast<int>(comparison.displayRows.size()));
if(isChange && comparison.unified)
{
for(int row=first;row<past;++row)
if(comparison.rows[row].left>=0) append(row,row+1,0);
for(int row=first;row<past;++row)
if(comparison.rows[row].right>=0) append(row,row+1,1);
}
else
{
constexpr int context=3;
const int hiddenFirst=comparison.foldContext && !isChange?first+(first>0?context:0):past;
const int hiddenPast=past-(past<size?context:0);
if(hiddenPast-hiddenFirst>=2)
{
for(int row=first;row<hiddenFirst;++row) append(row,row+1);
append(hiddenFirst,hiddenPast);
for(int row=hiddenPast;row<past;++row) append(row,row+1);
}
else for(int row=first;row<past;++row) append(row,row+1);
}
first=past;
}
SendMessageW(list,LB_SETCOUNT,comparison.displayRows.size(),0);
const auto position=comparisonDisplayPosition(comparison,selected);
if(const auto firstVisible=comparisonDisplayPosition(comparison,top);firstVisible>=0)
SendMessageW(list,LB_SETTOPINDEX,firstVisible,0);
SendMessageW(list,LB_SETCURSEL,position,0);
updateComparisonSummary(dialog,comparison);
InvalidateRect(list,nullptr,TRUE);
}
bool applyComparisonEdit(HWND dialog,FileComparison &comparison,int side,const ks::files::ComparisonReplace &edit,
bool remember)
{
const auto list=GetDlgItem(dialog,402);
const auto selected=comparisonDisplayAnchor(comparison,SendMessageW(list,LB_GETCURSEL,0,0));
const auto top=comparisonDisplayAnchor(comparison,SendMessageW(list,LB_GETTOPINDEX,0,0));
FileComparison candidate;
ks::files::ComparisonReplace reverse;
comparison.working=true;
try
{
const bool success=runComparisonWork(dialog,L"Updating comparison…",true,[&](const auto &stop) {
candidate.text[0]=comparison.text[0];
candidate.text[1]=comparison.text[1];
reverse=ks::files::replaceComparisonText(candidate.text[side],edit);
if(candidate.text[side].lines.size()>100'000)
throw std::runtime_error("Each file can contain up to 100,000 lines.");
alignComparison(candidate,stop);
});
comparison.working=false;
if(!success) return false;
if(remember) comparison.undo.push_back({side,std::move(reverse)});
else comparison.undo.pop_back();
comparison.text[side]=std::move(candidate.text[side]);
comparison.rows=std::move(candidate.rows);
comparison.files[side].dirty=comparison.text[side].joined()!=comparison.files[side].originalText;
comparisonUpdateRows(dialog,comparison,selected,top);
return true;
}
catch(const std::exception &error)
{
comparison.working=false;
showFileOperationError(dialog,L"Could not apply the block",ks::wide(error.what()));
return false;
}
}
bool commitComparison(HWND dialog,FileComparison &comparison,int requested=-1)
{
std::array committed{comparison.files[0],comparison.files[1]};
comparison.working=true;
bool success=true;
try
{
runComparisonWork(dialog,L"Saving comparison changes…",false,[&](const auto &stop) {
for(int side=0;side<2;++side)
if((requested<0 || requested==side) && comparison.files[side].dirty)
saveComparisonFile(committed[side],comparison.text[side],stop);
});
}
catch(const std::system_error &error)
{
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":fileError(error);
showFileOperationError(dialog,L"Comparison save failed",detail);
success=false;
}
catch(const std::exception &error)
{
showFileOperationError(dialog,L"Comparison save failed",ks::wide(error.what()));
success=false;
}
comparison.working=false;
for(int side=0;side<2;++side)
if(!committed[side].dirty) comparison.files[side]=std::move(committed[side]);
std::erase_if(comparison.undo,[&](const auto &previous){return !comparison.files[previous.side].dirty;});
updateComparisonSummary(dialog,comparison);
return success;
}
void closeComparison(HWND dialog,FileComparison &comparison)
{
if(comparison.working || FilesModalDialog::dismissOwned(dialog)) return;
if(comparison.files[0].dirty || comparison.files[1].dirty)
{
const auto choice=showFilesNotice(dialog,L"Save changes from the comparison?",L"Compare files",
{.saveChanges=true});
if(choice==IDYES)
{
if(!commitComparison(dialog,comparison)) return;
}
else if(choice!=IDNO) return;
}
DestroyWindow(dialog);
}
void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &item)
{
const auto dc=item.hDC;
@@ -448,47 +763,23 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it
const auto &palette=comparison.appearance.palette;
const auto cell=comparison.characterWidth;
fill(bounds,palette[CompareBackground]);
if(item.itemID>=comparison.rows.size()) return;
const auto &row=comparison.rows[item.itemID];
if(item.itemID>=comparison.displayRows.size()) return;
const auto &display=comparison.displayRows[item.itemID];
const auto &row=comparison.rows[display.first];
const bool changed=row.hasChange(comparison.showWhitespace);
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const LONG gutter=std::max(4,cell);
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
if(changed) fill(link,highlight);
else
{
const RECT divider{center,bounds.top,center+1,bounds.bottom};
fill(divider,palette[CompareDivider]);
}
if(changed)
{
const LONG middle=(bounds.top+bounds.bottom)/2;
const LONG start=row.left<0?bounds.top:middle,end=row.right<0?bounds.top:middle;
SetDCPenColor(dc,palette[CompareChangedText]);
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
MoveToEx(dc,link.left,start,nullptr);
LineTo(dc,link.right,end);
SelectObject(dc,pen);
}
const auto ink=palette[changed?CompareChangedText:CompareText];
SelectObject(dc,comparison.font?comparison.font:mono);
SetBkMode(dc,TRANSPARENT);
const auto ink=palette[changed?CompareChangedText:CompareText];
SetTextColor(dc,ink);
const auto drawSide=[&](int side,int number,RECT area)
const auto drawNumber=[&](int number,RECT area)
{
if(number<0)
{
fill(area,palette[ComparePadding]);
return;
}
if(changed) fill(area,highlight);
const auto numberText=std::to_wstring(number+1);
RECT numberArea=area;
numberArea.right=std::min(area.right,area.left+7*cell);
DrawTextW(dc,numberText.c_str(),-1,&numberArea,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
area.left=std::min(area.right,numberArea.right+cell);
const auto &line=comparison.lines[side][number];
if(number<0) return;
const auto text=std::to_wstring(number+1);
DrawTextW(dc,text.c_str(),-1,&area,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
};
const auto drawContent=[&](int side,int number,RECT area)
{
const auto &line=comparison.text[side].lines[number];
const auto paneWidth=area.right-area.left;
if(paneWidth<=0) return;
const auto limit=static_cast<size_t>(paneWidth/cell+2)*4;
@@ -519,8 +810,62 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it
}
else if(!visible.empty()) DrawTextW(dc,visible.data(),static_cast<int>(visible.size()),&area,flags);
};
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
if(display.folded())
{
fill(bounds,palette[ComparePadding]);
auto line=bounds;
line.left+=2*cell;
const auto label=L"… "+std::to_wstring(display.past-display.first)+L" unchanged lines …";
DrawTextW(dc,label.c_str(),-1,&line,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
}
else if(comparison.unified)
{
if(changed) fill(bounds,palette[display.side==0?CompareDelete:CompareInsert]);
RECT number=bounds;
number.right=std::min(bounds.right,bounds.left+7*cell);
if(display.side!=1) drawNumber(row.left,number);
number.left=number.right;
number.right=std::min(bounds.right,number.left+7*cell);
if(display.side!=0) drawNumber(row.right,number);
auto content=bounds;
content.left=std::min(bounds.right,number.right+3*cell);
if(changed)
{
RECT marker{std::min(bounds.right,number.right+cell),bounds.top,content.left,bounds.bottom};
DrawTextW(dc,display.side==0?L"−":L"+",1,&marker,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
}
const auto side=display.side<0?1:display.side;
drawContent(side,side==0?row.left:row.right,content);
}
else
{
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const LONG gutter=std::max(4,cell);
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
if(changed)
{
fill(link,highlight);
const LONG middle=(bounds.top+bounds.bottom)/2;
SetDCPenColor(dc,ink);
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
MoveToEx(dc,link.left,row.left<0?bounds.top:middle,nullptr);
LineTo(dc,link.right,row.right<0?bounds.top:middle);
SelectObject(dc,pen);
}
else fill({center,bounds.top,center+1,bounds.bottom},palette[CompareDivider]);
const auto drawSide=[&](int side,int number,RECT area)
{
if(number<0) {fill(area,palette[ComparePadding]);return;}
if(changed) fill(area,highlight);
const auto end=std::min(area.right,area.left+7*cell);
drawNumber(number,{area.left,area.top,end,area.bottom});
area.left=std::min(area.right,end+cell);
drawContent(side,number,area);
};
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
}
if(item.itemState&ODS_SELECTED)
{
SetDCBrushColor(dc,ink);
@@ -530,6 +875,11 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it
LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_KEYDOWN && (GetKeyState(VK_CONTROL)&0x8000) && (wp=='Z' || wp=='S'))
{
SendMessageW(GetParent(control),WM_COMMAND,wp=='Z'?undoCompare:saveComparison,0);
return 0;
}
if(message==WM_KEYDOWN && (wp==VK_F7 || wp==VK_F8))
{
SendMessageW(GetParent(control),WM_COMMAND,wp==VK_F7?404:405,0);
@@ -540,7 +890,7 @@ LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UI
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!comparison) return DefSubclassProc(control,message,wp,lp);
if(message==WM_MOUSEWHEEL && zoomComparison(dialog,*comparison,wp)) return 0;
if(message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)
if(!comparison->unified && (message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK))
{
RECT client{};
GetClientRect(control,&client);
@@ -604,9 +954,12 @@ LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UI
// The list box repaints its rows but can leave earlier divider marks below them.
FillRect(dc,&blank,comparison->background?comparison->background:
static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
const RECT divider{middle,blank.top,middle+1,blank.bottom};
SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]);
FillRect(dc,&divider,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
if(!comparison->unified)
{
const RECT divider{middle,blank.top,middle+1,blank.bottom};
SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]);
FillRect(dc,&divider,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
ReleaseDC(control,dc);
}
}
@@ -626,6 +979,7 @@ void layoutComparison(HWND dialog)
if(id==400 || id==401) continue;
auto bounds=comparison->initialControls[i];
if(id==402) bounds={0,bounds.top,client.right,client.bottom};
if(id==408) bounds.right=client.right-bounds.left;
SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,bounds.top,
bounds.right-bounds.left,std::max(0L,bounds.bottom-bounds.top),
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
@@ -636,12 +990,24 @@ void layoutComparison(HWND dialog)
void updateComparisonSummary(HWND dialog,const FileComparison &comparison)
{
const auto blocks=(comparison.showWhitespace?comparison.allChanges:comparison.changes).size();
const auto blocks=comparison.displayBlockStarts.size();
const auto summary=blocks==0?L"Text is identical":blocks==1?L"1 change block":
std::to_wstring(blocks)+L" change blocks";
SetDlgItemTextW(dialog,403,summary.c_str());
const auto toolbar=GetDlgItem(dialog,407);
for(const auto id:{404,405}) SendMessageW(toolbar,TB_ENABLEBUTTON,id,MAKELONG(blocks!=0,0));
const auto actions=GetDlgItem(dialog,408);
const auto row=comparisonDisplayAnchor(comparison,SendDlgItemMessageW(dialog,402,LB_GETCURSEL,0,0));
const bool selected=row.first>=0 && !row.folded() && comparison.rows[row.first].hasChange(comparison.showWhitespace);
for(int side=0;side<2;++side)
{
const auto &file=comparison.files[side];
const auto header=(file.dirty?L"* ":L"")+file.label+(file.revision.editable?L"":L" (read-only)");
SetDlgItemTextW(dialog,400+side,header.c_str());
SendMessageW(actions,TB_ENABLEBUTTON,applyLeft+side,MAKELONG(selected && file.revision.editable,0));
SendMessageW(actions,TB_ENABLEBUTTON,saveLeft+side,MAKELONG(file.dirty,0));
}
SendMessageW(actions,TB_ENABLEBUTTON,undoCompare,MAKELONG(!comparison.undo.empty(),0));
}
void initializeComparisonToolbar(HWND toolbar)
@@ -662,6 +1028,27 @@ void initializeComparisonToolbar(HWND toolbar)
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
}
void initializeComparisonActions(HWND toolbar)
{
SendMessageW(toolbar,TB_BUTTONSTRUCTSIZE,sizeof(TBBUTTON),0);
SendMessageW(toolbar,TB_SETEXTENDEDSTYLE,0,TBSTYLE_EX_MIXEDBUTTONS);
SendMessageW(toolbar,TB_SETMAXTEXTROWS,1,0);
constexpr BYTE text=BTNS_AUTOSIZE|BTNS_SHOWTEXT;
const auto separator=MulDiv(8,GetDpiForWindow(toolbar),96);
const TBBUTTON buttons[]{
{I_IMAGENONE,applyLeft,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Apply to left")},
{I_IMAGENONE,applyRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Apply to right")},
{I_IMAGENONE,undoCompare,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Undo")},
{separator,0,0,BTNS_SEP,{},0,0},
{I_IMAGENONE,saveLeft,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Save left")},
{I_IMAGENONE,saveRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Save right")},
{separator,0,0,BTNS_SEP,{},0,0},
{I_IMAGENONE,unifiedCompare,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Unified")},
{I_IMAGENONE,foldCompareContext,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Fold unchanged")}
};
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
}
INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
@@ -685,15 +1072,19 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
SendMessageW(dialog,WM_SETICON,ICON_SMALL,reinterpret_cast<LPARAM>(small));
SendMessageW(dialog,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(large));
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,L"HrynCo.KSwitcher.Files.Compare");
for(int side=0;side<2;++side) SetDlgItemTextW(dialog,400+side,comparison->files[side].label.c_str());
initializeComparisonToolbar(toolbar);
updateComparisonSummary(dialog,*comparison);
const auto actions=GetDlgItem(dialog,408);
initializeComparisonActions(actions);
SetWindowSubclass(list,comparisonKeys,1,0);
SetWindowSubclass(toolbar,comparisonKeys,1,0);
SetWindowSubclass(actions,comparisonKeys,1,0);
applyComparisonAppearance(dialog,*comparison);
SendMessageW(list,LB_SETCOUNT,comparison->rows.size(),0);
layoutComparisonHeaders(dialog,*comparison);
if(!comparison->changes.empty()) SendMessageW(list,LB_SETCURSEL,comparison->changes.front(),0);
const auto first=std::find_if(comparison->rows.begin(),comparison->rows.end(),
[](const auto &row){return row.hasChange(false);});
ComparisonDisplayRow selected;
if(first!=comparison->rows.end()) selected.first=static_cast<int>(first-comparison->rows.begin());
comparisonUpdateRows(dialog,*comparison,selected);
return TRUE;
}
if(message==filesPreferencesChanged && comparison)
@@ -702,16 +1093,16 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
layoutComparisonHeaders(dialog,*comparison);
return TRUE;
}
if(message==WM_CLOSE)
if(message==WM_CLOSE && comparison)
{
DestroyWindow(dialog);
closeComparison(dialog,*comparison);
return TRUE;
}
if(message==WM_MOUSEWHEEL && comparison && zoomComparison(dialog,*comparison,wp)) return TRUE;
if(message==WM_NCDESTROY)
{
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,nullptr);
comparisonWindows.erase(dialog);
if(comparisonWindows.erase(dialog)) ks::files::standaloneFilesWindowClosed();
return FALSE;
}
if(message==WM_GETMINMAXINFO && comparison && comparison->minimumWindow.cx)
@@ -737,45 +1128,92 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(message==WM_COMMAND && comparison)
{
const auto id=LOWORD(wp);
if(id==IDCANCEL) {DestroyWindow(dialog);return TRUE;}
if(id==406 && HIWORD(wp)==BN_CLICKED)
if(comparison->working) return TRUE;
if(id==IDCANCEL) {closeComparison(dialog,*comparison);return TRUE;}
if(id==applyLeft || id==applyRight)
{
comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0;
updateComparisonSummary(dialog,*comparison);
InvalidateRect(list,nullptr,FALSE);
const auto side=id-applyLeft;
const auto selected=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0));
if(!selected.folded() && comparison->files[side].revision.editable)
if(const auto edit=comparisonBlock(*comparison,side,selected.first))
applyComparisonEdit(dialog,*comparison,side,*edit,true);
SetFocus(list);
return TRUE;
}
const auto &changes=comparison->showWhitespace?comparison->allChanges:comparison->changes;
if(id==undoCompare)
{
if(!comparison->undo.empty())
{
const auto &previous=comparison->undo.back();
applyComparisonEdit(dialog,*comparison,previous.side,previous.edit,false);
}
SetFocus(list);
return TRUE;
}
if(id==saveLeft || id==saveRight || id==saveComparison)
{
if(comparison->files[0].dirty || comparison->files[1].dirty)
commitComparison(dialog,*comparison,id==saveComparison?-1:id-saveLeft);
SetFocus(list);
return TRUE;
}
if((id==406 || id==unifiedCompare || id==foldCompareContext) && HIWORD(wp)==BN_CLICKED)
{
const auto selected=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0));
const auto top=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETTOPINDEX,0,0));
const auto source=id==406?toolbar:GetDlgItem(dialog,408);
const bool enabled=SendMessageW(source,TB_ISBUTTONCHECKED,id,0)!=0;
if(id==406) comparison->showWhitespace=enabled;
if(id==unifiedCompare)
{
if(comparison->splitDragOffset) ReleaseCapture();
comparison->unified=enabled;
layoutComparisonHeaders(dialog,*comparison);
}
if(id==foldCompareContext) comparison->foldContext=enabled;
comparisonUpdateRows(dialog,*comparison,selected,top);
SetFocus(list);
return TRUE;
}
const auto &changes=comparison->displayBlockStarts;
if((id==404 || id==405) && !changes.empty())
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(id==404)
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
if(id==404 && next!=changes.begin())
{
const auto previous=std::lower_bound(changes.begin(),changes.end(),current);
if(previous!=changes.begin()) SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
}
else
{
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
if(next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
const auto here=comparisonDisplayAnchor(*comparison,current);
const bool inBlock=here.first>=0 && !here.folded() &&
comparison->rows[here.first].hasChange(comparison->showWhitespace);
const auto previous=std::prev(next);
if(!inBlock) SendMessageW(list,LB_SETCURSEL,*previous,0);
if(inBlock && previous!=changes.begin())
SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
}
if(id==405 && next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
updateComparisonSummary(dialog,*comparison);
return TRUE;
}
if(id==402 && HIWORD(wp)==LBN_DBLCLK)
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(current>=0 && static_cast<size_t>(current)<comparison->rows.size())
const auto current=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0));
if(current.first>=0 && !current.folded())
{
const auto &row=comparison->rows[current];
const auto &row=comparison->rows[current.first];
const auto side=[&](int file,int line)
{
return line<0?std::wstring(L"—"):comparison->lines[file][line];
return line<0?std::wstring(L"—"):comparison->text[file].lines[line];
};
const auto detail=L"Left\n"+side(0,row.left)+L"\n\nRight\n"+side(1,row.right);
showFilesNotice(dialog,detail.c_str(),L"Line details");
}
return TRUE;
}
if(id==402 && HIWORD(wp)==LBN_SELCHANGE)
{
updateComparisonSummary(dialog,*comparison);
return TRUE;
}
}
return FALSE;
}
@@ -785,29 +1223,34 @@ INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPA
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &state=*reinterpret_cast<ComparisonProgress *>(lp);
prepareTextDialog(dialog);
SetDlgItemTextW(dialog,548,state.status);
EnableWindow(GetDlgItem(dialog,IDCANCEL),state.cancelable);
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDCANCEL)
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
*reinterpret_cast<std::atomic_bool*>(GetWindowLongPtrW(dialog,DWLP_USER))=true;
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
auto &state=*reinterpret_cast<ComparisonProgress *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(state.cancelable)
{
state.canceled=true;
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
}
return TRUE;
}
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);
if(panel.archive || ftpProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder")
if(panel.archive || transferProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder")
return false;
const auto directory=path.parent_path();
const auto tail=(directory.filename()/path.filename()).native();
@@ -816,53 +1259,49 @@ 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");
return;
}
std::atomic_bool canceled{};
try
{
{
FileOperationUi worker;
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
comparisonProgressDialog,reinterpret_cast<LPARAM>(&canceled),false);
if(!progress.window()) throw std::runtime_error("Could not open the progress dialog.");
progress.show();
worker.run(progress.window(),canceled,[&]
{
for(int side=0;side<2;++side)
comparison.lines[side]=readComparisonLines(comparison.files[side],canceled);
alignComparison(comparison,canceled);
});
}
if(!canceled)
const bool read=runComparisonWork(owner,L"Reading and comparing files…",true,[&](const auto &stop) {
for(int side=0;side<2;++side)
comparison.text[side]=readComparisonLines(comparison.files[side],stop);
alignComparison(comparison,stop);
});
if(read)
{
const auto window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(114),nullptr,
comparisonDialog,reinterpret_cast<LPARAM>(&comparison));
if(!window) throw std::runtime_error("Could not open the comparison window.");
comparisonWindows.emplace(window,std::move(state));
ks::files::standaloneFilesWindowOpened();
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
SetFocus(GetDlgItem(window,402));
}
}
catch(const std::system_error &error)
{
if(canceled || error.code().value()==ERROR_CANCELLED) return;
if(error.code().value()==ERROR_CANCELLED) return;
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":
fileError(error);
showFileOperationError(owner,L"Comparison failed",detail);
}
catch(const std::exception &error)
{
if(!canceled) showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
}
}
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <algorithm>
#include <string>
#include <string_view>
#include <vector>
namespace ks::files
{
enum class ComparisonEnding { absent, crlf, lf, cr };
inline std::wstring_view comparisonEndingText(ComparisonEnding ending)
{
switch(ending)
{
case ComparisonEnding::crlf: return L"\r\n";
case ComparisonEnding::lf: return L"\n";
case ComparisonEnding::cr: return L"\r";
default: return {};
}
}
struct ComparisonText
{
std::vector<std::wstring> lines;
std::vector<ComparisonEnding> endings;
ComparisonEnding preferred=ComparisonEnding::crlf;
std::wstring joined() const
{
std::wstring result;
for(size_t i=0;i<lines.size();++i)
{
result+=lines[i];
if(i+1<lines.size())
result+=comparisonEndingText(endings[i]==ComparisonEnding::absent?preferred:endings[i]);
}
return result;
}
};
inline ComparisonText splitComparisonText(std::wstring_view contents)
{
ComparisonText result;
if(contents.empty()) return result;
size_t start=0;
while(true)
{
const auto end=contents.find_first_of(L"\r\n",start);
result.lines.emplace_back(contents.substr(start,end==contents.npos?end:end-start));
auto ending=ComparisonEnding::absent;
if(end!=contents.npos)
ending=contents[end]==L'\n'?ComparisonEnding::lf:
end+1<contents.size() && contents[end+1]==L'\n'?ComparisonEnding::crlf:ComparisonEnding::cr;
result.endings.push_back(ending);
if(ending==ComparisonEnding::absent) break;
if(result.endings.size()==1) result.preferred=ending;
start=end+(ending==ComparisonEnding::crlf?2:1);
}
return result;
}
struct ComparisonReplace
{
size_t start{}, count{};
std::vector<std::wstring> lines;
std::vector<ComparisonEnding> endings;
};
inline ComparisonReplace replaceComparisonText(ComparisonText &document,const ComparisonReplace &change)
{
const auto first=document.lines.begin()+change.start, last=first+change.count;
const auto firstEnding=document.endings.begin()+change.start, lastEnding=firstEnding+change.count;
ComparisonReplace reverse{change.start,change.lines.size(),{first,last},{firstEnding,lastEnding}};
document.lines.erase(first,last);
document.lines.insert(document.lines.begin()+change.start,change.lines.begin(),change.lines.end());
document.endings.erase(firstEnding,lastEnding);
document.endings.insert(document.endings.begin()+change.start,change.endings.begin(),change.endings.end());
return reverse;
}
}
+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();
}
+97
View File
@@ -0,0 +1,97 @@
struct CopyOptionsPrompt
{
CopyOptions value;
bool permissions{}, move{}, unixDest{};
};
INT_PTR CALLBACK copyOptionsDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int mask=640, paths=641, time=642, permissions=643, footer=644, folderLabel=646, hint=647;
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT*>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Copy/Move options ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
const auto &prompt=*reinterpret_cast<const CopyOptionsPrompt*>(lp);
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
layoutDialogContent(window,645);
fitFarEditToLine(GetDlgItem(window,mask));
installFarCheckbox(GetDlgItem(window,time),FarCheckboxSurface::gray);
installFarCheckbox(GetDlgItem(window,permissions),FarCheckboxSurface::gray);
for(const auto id:{time,permissions})
SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
layoutDialogButtons(window,footer,{IDOK,IDCANCEL});
CheckDlgButton(window,time,prompt.value.preserveTime?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(window,permissions,prompt.value.preservePermissions?BST_CHECKED:BST_UNCHECKED);
EnableWindow(GetDlgItem(window,permissions),prompt.permissions);
SetDlgItemTextW(window,mask,prompt.value.mask.c_str());
SendDlgItemMessageW(window,mask,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(window,paths,EM_SETLIMITTEXT,32767,0);
std::wstring lines;
for(const auto &path:prompt.value.additional)
{
if(!lines.empty()) lines+=L"\r\n";
lines+=path.native();
}
SetDlgItemTextW(window,paths,lines.c_str());
if(prompt.unixDest) SetDlgItemTextW(window,folderLabel,L"Additional &folders on this server (one absolute path per line)");
if(prompt.move) SetDlgItemTextW(window,hint,L"Move keeps the source until every requested copy succeeds.");
SetFocus(GetDlgItem(window,mask));
SendDlgItemMessageW(window,mask,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &prompt=*reinterpret_cast<CopyOptionsPrompt*>(GetWindowLongPtrW(window,DWLP_USER));
const auto text=[&](int id) {
auto control=GetDlgItem(window,id);
std::wstring value(GetWindowTextLengthW(control)+1,L'\0');
value.resize(GetWindowTextW(control,value.data(),static_cast<int>(value.size())));
return value;
};
auto pattern=text(mask);
if(pattern.find_first_of(L"/\\:")!=pattern.npos)
{
showFilesNotice(window,L"Enter a file name or mask without a path.",L"Copy/Move options");
SetFocus(GetDlgItem(window,mask));
return TRUE;
}
const auto entered=text(paths);
std::vector<fs::path> folders;
for(size_t start=0;start<entered.size();)
{
const auto end=entered.find(L'\n',start);
auto line=std::wstring_view(entered).substr(start,end==entered.npos?end:end-start);
if(!line.empty() && line.back()==L'\r') line.remove_suffix(1);
if(!line.empty())
{
auto path=fs::path(line);
const bool unc=!prompt.unixDest && (line.starts_with(L"\\\\") || line.starts_with(L"//"));
const bool absolute=prompt.unixDest?line.front()==L'/':path.is_absolute() || unc;
if(!absolute || line.find_first_of(L"<>|?*")!=line.npos || line.starts_with(L"\\\\.\\"))
{
showFilesNotice(window,L"Enter one absolute destination folder per line.",L"Copy/Move options");
SetFocus(GetDlgItem(window,paths));
return TRUE;
}
if(!unc) path=path.lexically_normal();
folders.push_back(folderPathWithoutSeparator(std::move(path)));
}
if(end==entered.npos) break;
start=end+1;
}
prompt.value={pattern.empty()?L"*":std::move(pattern),std::move(folders),
IsDlgButtonChecked(window,time)==BST_CHECKED,
prompt.permissions && IsDlgButtonChecked(window,permissions)==BST_CHECKED};
FilesModalDialog::finish(window,IDOK);
return TRUE;
}
+418
View File
@@ -0,0 +1,418 @@
enum class EnvironmentScope { user, system, process };
constexpr wchar_t userEnvironmentPath[]=L"Environment";
constexpr wchar_t systemEnvironmentPath[]=L"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
constexpr unsigned environmentValueLimit=32767;
const wchar_t *environmentScopeName(EnvironmentScope scope)
{
switch(scope)
{
case EnvironmentScope::user: return L"User";
case EnvironmentScope::system: return L"System";
case EnvironmentScope::process: return L"Process";
}
return L"";
}
std::wstring environmentSource(EnvironmentScope scope)
{
if(scope==EnvironmentScope::process) return L"Current KSwitcher.Files process";
return scope==EnvironmentScope::user?L"HKCU\\"+std::wstring(userEnvironmentPath):
L"HKLM\\"+std::wstring(systemEnvironmentPath);
}
struct EnvironmentKey
{
HKEY value{};
explicit EnvironmentKey(EnvironmentScope scope,bool write=false)
{
const bool user=scope==EnvironmentScope::user;
const auto root=user?HKEY_CURRENT_USER:HKEY_LOCAL_MACHINE;
const auto path=user?userEnvironmentPath:systemEnvironmentPath;
const auto access=KEY_QUERY_VALUE|(write?KEY_SET_VALUE:0);
const auto result=user && write?
RegCreateKeyExW(root,path,0,nullptr,0,access,nullptr,&value,nullptr):
RegOpenKeyExW(root,path,0,access,&value);
if(result!=ERROR_SUCCESS && (result!=ERROR_FILE_NOT_FOUND || !user || write))
throw std::system_error(result,std::system_category(),"Open the environment registry key");
}
EnvironmentKey(const EnvironmentKey &)=delete;
~EnvironmentKey(){if(value) RegCloseKey(value);}
};
struct EnvironmentValue
{
DWORD type{};
std::wstring text;
bool supported{};
bool operator==(const EnvironmentValue &) const = default;
};
struct EnvironmentVariable
{
std::wstring name;
EnvironmentValue value;
};
std::optional<EnvironmentValue> readEnvironmentValue(HKEY key,const std::wstring &name)
{
if(!key) return {};
DWORD size{},type{};
auto result=RegQueryValueExW(key,name.c_str(),nullptr,&type,nullptr,&size);
if(result==ERROR_FILE_NOT_FOUND) return {};
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Read the environment definition");
for(int attempt=0;attempt<4;++attempt)
{
if(type!=REG_SZ && type!=REG_EXPAND_SZ) return EnvironmentValue{type,{},false};
if(size%sizeof(wchar_t) || size>2*(environmentValueLimit+1))
return EnvironmentValue{type,{},false};
std::wstring text(size/sizeof(wchar_t)+1,L'\0');
result=RegQueryValueExW(key,name.c_str(),nullptr,&type,reinterpret_cast<BYTE*>(text.data()),&size);
if(result==ERROR_FILE_NOT_FOUND) return {};
if(result==ERROR_MORE_DATA) continue;
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Read the environment definition");
if((type!=REG_SZ && type!=REG_EXPAND_SZ) || size%sizeof(wchar_t))
return EnvironmentValue{type,{},false};
text.resize(size/sizeof(wchar_t));
while(!text.empty() && text.back()==L'\0') text.pop_back();
if(text.find(L'\0')!=text.npos) return EnvironmentValue{type,{},false};
return EnvironmentValue{type,std::move(text),true};
}
throw std::runtime_error("The environment definition changed while Windows was reading it.");
}
std::vector<EnvironmentVariable> readEnvironmentScope(EnvironmentScope scope)
{
std::vector<EnvironmentVariable> entries;
if(scope==EnvironmentScope::process)
{
const auto block=GetEnvironmentStringsW();
if(!block) throw std::system_error(GetLastError(),std::system_category(),"Read the current process environment");
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> owned(block,FreeEnvironmentStringsW);
for(auto offset=block;*offset;)
{
const std::wstring_view line=offset;
const auto equals=line.find(L'=');
if(equals!=line.npos && equals>0)
entries.push_back({std::wstring(line.substr(0,equals)),{REG_SZ,std::wstring(line.substr(equals+1)),true}});
offset+=line.size()+1;
}
}
else
{
const EnvironmentKey key(scope);
if(!key.value) return {};
std::vector<wchar_t> name(16384);
for(DWORD index=0;;++index)
{
DWORD length=static_cast<DWORD>(name.size());
const auto result=RegEnumValueW(key.value,index,name.data(),&length,nullptr,nullptr,nullptr,nullptr);
if(result==ERROR_NO_MORE_ITEMS) break;
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"List environment definitions");
if(!length) continue;
std::wstring label(name.data(),length);
if(label.find(L'=')!=label.npos) continue;
if(auto value=readEnvironmentValue(key.value,label);value && value->supported)
entries.push_back({std::move(label),std::move(*value)});
}
}
std::sort(entries.begin(),entries.end(),[](const auto &left,const auto &right) {
return CompareStringOrdinal(left.name.c_str(),-1,right.name.c_str(),-1,TRUE)==CSTR_LESS_THAN;
});
return entries;
}
std::wstring expandedEnvironmentValue(EnvironmentScope scope,const EnvironmentValue &value)
{
if(value.type!=REG_EXPAND_SZ) return value.text;
Handle token{};
if(scope==EnvironmentScope::user &&
!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_IMPERSONATE|TOKEN_DUPLICATE,&token.value))
throw std::system_error(GetLastError(),std::system_category(),"Open the current user's environment");
std::wstring expanded(environmentValueLimit+1,L'\0');
if(!ExpandEnvironmentStringsForUserW(token.value,value.text.c_str(),expanded.data(),static_cast<DWORD>(expanded.size())))
throw std::system_error(GetLastError(),std::system_category(),"Expand the environment definition");
expanded.resize(wcslen(expanded.c_str()));
return expanded;
}
void writeEnvironmentValue(EnvironmentScope scope,const std::wstring &name,const EnvironmentValue &replacement,
const std::optional<EnvironmentValue> &expected)
{
if(scope==EnvironmentScope::process) throw std::runtime_error("The current process environment is read-only here.");
if(replacement.text.size()>environmentValueLimit) throw std::runtime_error("The value exceeds the Windows environment limit.");
const EnvironmentKey key(scope,true);
if(readEnvironmentValue(key.value,name)!=expected)
throw std::runtime_error("Windows changed this definition while it was open. Reload and review the current value.");
if(expected==replacement) return;
const auto bytes=static_cast<DWORD>((replacement.text.size()+1)*sizeof(wchar_t));
const auto result=RegSetValueExW(key.value,name.c_str(),0,replacement.type,
reinterpret_cast<const BYTE*>(replacement.text.c_str()),bytes);
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Save the environment definition");
try
{
std::thread([] {
DWORD_PTR reply{};
SendMessageTimeoutW(HWND_BROADCAST,WM_SETTINGCHANGE,0,reinterpret_cast<LPARAM>(L"Environment"),
SMTO_ABORTIFHUNG,250,&reply);
}).detach();
}
catch(const std::exception &) {}
}
const wchar_t *environmentValueType(const EnvironmentValue &value)
{
return value.type==REG_EXPAND_SZ?L"REG_EXPAND_SZ":L"REG_SZ";
}
struct EnvironmentEdit
{
EnvironmentScope scope;
EnvironmentVariable original;
std::wstring replacement;
};
INT_PTR CALLBACK environmentEditDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int label=630,body=632,footer=633;
if(message==WM_INITDIALOG)
{
const auto &editor=*reinterpret_cast<const EnvironmentEdit *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,label);
const auto title=editor.original.name+L" · "+environmentScopeName(editor.scope)+L" · "+
environmentValueType(editor.original.value);
SetDlgItemTextW(dialog,label,title.c_str());
SendDlgItemMessageW(dialog,body,EM_SETLIMITTEXT,environmentValueLimit,0);
SetDlgItemTextW(dialog,body,editor.original.value.text.c_str());
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(dialog,body));
return FALSE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &editor=*reinterpret_cast<EnvironmentEdit *>(GetWindowLongPtrW(dialog,DWLP_USER));
editor.replacement=dialogFieldText(GetDlgItem(dialog,body));
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Edit environment definition ",false,{footer});
}
constexpr int envScope=611,envList=612,envSource=613,envSelected=614,envRaw=615,envExpanded=616,
envStatus=617,envFooter=618,envEdit=622,envCopyUser=623,envCopySystem=624,envRefresh=625;
struct EnvironmentPanel
{
EnvironmentScope scope=EnvironmentScope::user;
std::vector<EnvironmentVariable> entries;
std::wstring readFailure,notice;
};
std::wstring environmentErrorText(const std::exception &error)
{
if(const auto *system=dynamic_cast<const std::system_error *>(&error)) return fileError(*system);
return ks::wide(error.what());
}
const EnvironmentVariable *selectedEnvironmentVariable(HWND dialog,const EnvironmentPanel &panel)
{
const auto row=SendDlgItemMessageW(dialog,envList,LB_GETCURSEL,0,0);
if(row<0) return nullptr;
const auto index=SendDlgItemMessageW(dialog,envList,LB_GETITEMDATA,row,0);
return index>=0 && static_cast<size_t>(index)<panel.entries.size()?&panel.entries[index]:nullptr;
}
void setEnvironmentDetails(HWND dialog,const EnvironmentPanel &panel)
{
const auto *entry=selectedEnvironmentVariable(dialog,panel);
const bool registry=panel.scope!=EnvironmentScope::process;
SetDlgItemTextW(dialog,envSource,environmentSource(panel.scope).c_str());
SetDlgItemTextW(dialog,envSelected,entry?(entry->name+L" · "+
(registry?environmentValueType(entry->value):L"Read-only")).c_str():L"");
SetDlgItemTextW(dialog,envRaw,entry?entry->value.text.c_str():L"");
std::wstring expanded;
if(entry)
{
try {expanded=expandedEnvironmentValue(panel.scope,entry->value);}
catch(const std::exception &error) {expanded=L"Unavailable · "+environmentErrorText(error);}
}
SetDlgItemTextW(dialog,envExpanded,expanded.c_str());
EnableWindow(GetDlgItem(dialog,envEdit),entry && registry);
EnableWindow(GetDlgItem(dialog,envCopyUser),entry && panel.scope!=EnvironmentScope::user);
EnableWindow(GetDlgItem(dialog,envCopySystem),entry && panel.scope!=EnvironmentScope::system);
const auto status=!panel.readFailure.empty()?panel.readFailure:!panel.notice.empty()?panel.notice:
!entry?std::wstring(L"No environment variables in this scope."):
registry?L"Existing PowerShell sessions keep their environment. Restart Files for embedded PowerShell.":
L"These values belong to the running Files process.";
SetDlgItemTextW(dialog,envStatus,status.c_str());
}
void reloadEnvironmentPanel(HWND dialog,EnvironmentPanel &panel,const std::wstring &preferred={})
{
panel.readFailure.clear();
try {panel.entries=readEnvironmentScope(panel.scope);}
catch(const std::exception &error)
{
panel.entries.clear();
panel.readFailure=environmentErrorText(error);
}
const auto list=GetDlgItem(dialog,envList);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(size_t index=0;index<panel.entries.size();++index)
{
const auto &name=panel.entries[index].name;
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));
if(row<0) continue;
SendMessageW(list,LB_SETITEMDATA,row,index);
if(CompareStringOrdinal(name.c_str(),-1,preferred.c_str(),-1,TRUE)==CSTR_EQUAL) selected=row;
}
if(!panel.entries.empty()) SendMessageW(list,LB_SETCURSEL,selected,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,TRUE);
setEnvironmentDetails(dialog,panel);
}
void saveEnvironmentDefinition(HWND dialog,EnvironmentPanel &panel,const EnvironmentVariable &entry,
std::optional<EnvironmentScope> copyTo={})
{
try
{
if(copyTo)
{
const EnvironmentKey key(*copyTo);
const auto previous=readEnvironmentValue(key.value,entry.name);
if(previous && !previous->supported)
throw std::runtime_error("The destination already has a registry value of an unsupported type.");
const auto question=previous?L"Replace "+entry.name+L" in "+environmentScopeName(*copyTo)+L"?":
L"Copy "+entry.name+L" to "+environmentScopeName(*copyTo)+L"?";
if(showFilesNotice(dialog,question.c_str(),L"Copy environment definition",
{.confirm=true,.tone=previous?FilesNoticeTone::warning:FilesNoticeTone::dialog})!=IDYES) return;
if(panel.scope!=EnvironmentScope::process)
{
const EnvironmentKey source(panel.scope);
if(readEnvironmentValue(source.value,entry.name)!=entry.value)
throw std::runtime_error("The source definition changed. Reload and review it before copying.");
}
writeEnvironmentValue(*copyTo,entry.name,entry.value,previous);
panel.scope=*copyTo;
SendDlgItemMessageW(dialog,envScope,CB_SETCURSEL,static_cast<WPARAM>(panel.scope),0);
}
else
{
if(panel.scope==EnvironmentScope::process) return;
EnvironmentEdit editor{panel.scope,entry};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(128),dialog,environmentEditDialog,
reinterpret_cast<LPARAM>(&editor))!=IDOK || editor.replacement==entry.value.text) return;
writeEnvironmentValue(panel.scope,entry.name,{entry.value.type,editor.replacement,true},entry.value);
}
panel.notice=L"Saved. Restart Files for embedded PowerShell to inherit the new value.";
}
catch(const std::exception &error)
{
panel.notice.clear();
const auto details=environmentErrorText(error);
showFilesNotice(dialog,details.c_str(),L"Could not save environment definition",{.tone=FilesNoticeTone::warning});
}
reloadEnvironmentPanel(dialog,panel,entry.name);
}
INT_PTR CALLBACK environmentPanelDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &panel=*reinterpret_cast<EnvironmentPanel *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,610);
const auto scope=GetDlgItem(dialog,envScope);
for(const auto item:{EnvironmentScope::user,EnvironmentScope::system,EnvironmentScope::process})
SendMessageW(scope,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(environmentScopeName(item)));
SendMessageW(scope,CB_SETCURSEL,0,0);
installFarCombo(scope,GetDlgItem(dialog,610));
const auto list=GetDlgItem(dialog,envList);
const auto bounds=dialogControlBounds(dialog,envList);
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
installScrollBar(list,dialog);
layoutDialogButtons(dialog,envFooter,{envEdit,envCopyUser,envCopySystem,envRefresh,IDOK});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
reloadEnvironmentPanel(dialog,panel);
SetFocus(scope);
return FALSE;
}
auto *panel=reinterpret_cast<EnvironmentPanel *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!panel) return FALSE;
if(message==WM_DRAWITEM && wp==envScope)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=GetDlgItem(dialog,envList))
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
if(message==WM_COMMAND)
{
const auto id=LOWORD(wp),notification=HIWORD(wp);
if(id==envScope && (notification==CBN_SELENDOK ||
(notification==CBN_SELCHANGE && !SendDlgItemMessageW(dialog,envScope,CB_GETDROPPEDSTATE,0,0))))
{
const auto scope=SendDlgItemMessageW(dialog,envScope,CB_GETCURSEL,0,0);
if(scope>=0 && scope<=static_cast<LRESULT>(EnvironmentScope::process) &&
static_cast<EnvironmentScope>(scope)!=panel->scope)
{
const auto *entry=selectedEnvironmentVariable(dialog,*panel);
const auto selected=entry?entry->name:std::wstring{};
panel->scope=static_cast<EnvironmentScope>(scope);
reloadEnvironmentPanel(dialog,*panel,selected);
}
return TRUE;
}
if(id==envRefresh || (id==envList && notification==LBN_SELCHANGE))
{
if(id==envRefresh)
{
const auto *entry=selectedEnvironmentVariable(dialog,*panel);
const auto name=entry?entry->name:std::wstring{};
reloadEnvironmentPanel(dialog,*panel,name);
}
else setEnvironmentDetails(dialog,*panel);
return TRUE;
}
if(id==envEdit || id==envCopyUser || id==envCopySystem)
{
if(const auto *entry=selectedEnvironmentVariable(dialog,*panel))
saveEnvironmentDefinition(dialog,*panel,EnvironmentVariable(*entry),id==envEdit?std::nullopt:
std::optional(id==envCopyUser?EnvironmentScope::user:EnvironmentScope::system));
return TRUE;
}
if(id==IDOK || id==IDCANCEL)
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
}
if(message==WM_CLOSE) {FilesModalDialog::finish(dialog,IDCANCEL);return TRUE;}
return paintCopyDialog(dialog,message,wp,lp,L" Environment Variables ",false,{envFooter},false,GetDlgItem(dialog,envList));
}
void showEnvironmentPanel(HWND owner)
{
EnvironmentPanel panel;
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(127),owner,environmentPanelDialog,
reinterpret_cast<LPARAM>(&panel));
}
+11 -4
View File
@@ -75,15 +75,22 @@ void startFileSearch(Panel &panel,Panel::FindOptions options)
{
if(panel.scanRequest) return;
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
panel.remoteRetry.reset();
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;
}
+7
View File
@@ -65,6 +65,13 @@ struct FolderShortcutEdit
std::optional<size_t> index;
};
std::wstring trimFilesField(std::wstring value)
{
const auto first=value.find_first_not_of(L" \t\r\n");
if(first==value.npos) return {};
return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1);
}
std::wstring shortcutField(HWND dialog,int id)
{
const auto field=GetDlgItem(dialog,id);
+165 -36
View File
@@ -1,17 +1,76 @@
struct FtpProfile
enum class TransferProtocol { ftp, sftp };
constexpr unsigned defaultSftpPort=22;
const wchar_t *transferProtocolName(TransferProtocol protocol)
{
return protocol==TransferProtocol::sftp?L"SFTP":L"FTP";
}
struct TransferProfile
{
std::wstring name, host, user;
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
ks::Bytes secret;
bool legacyNames{};
std::string id;
TransferProtocol protocol{};
fs::path privateKey;
std::string hostFingerprint;
std::string jumpProfile;
std::wstring sudoSftpServer;
};
std::vector<FtpProfile> ftpProfiles;
bool ftpProfilesLoaded{};
constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles";
constexpr DWORD ftpProfilesMaxBytes=1024*1024;
struct TransferProfiles
{
const wchar_t *preference;
std::vector<TransferProfile> rows;
bool loaded{};
};
TransferProfiles &transferProfiles(TransferProtocol protocol)
{
static TransferProfiles ftp{L"FtpProfiles"},sftp{L"SftpProfiles"};
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"\\";
bool isFtpFolderPath(const fs::path &path)
{
return path.has_root_directory() && !path.has_root_name();
}
std::wstring ftpPath(const fs::path &path)
{
auto value=path.native();
@@ -19,61 +78,96 @@ std::wstring ftpPath(const fs::path &path)
return value;
}
bool saveFtpProfiles(const std::vector<FtpProfile> &profiles)
bool saveTransferProfiles(TransferProtocol protocol,const std::vector<TransferProfile> &profiles)
{
auto rows=Json::array();
for(const auto &profile:profiles)
rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
{
Json row{{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
{"legacyNames",profile.legacyNames}});
{"legacyNames",profile.legacyNames},{"id",profile.id}};
if(protocol==TransferProtocol::sftp)
{
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()<=ftpProfilesMaxBytes &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,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 loadFtpProfiles()
bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
{
if(ftpProfilesLoaded) return true;
auto &settings=transferProfiles(protocol);
if(settings.loaded) return true;
DWORD bytes{};
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference,
RRF_RT_REG_BINARY,nullptr,nullptr,&bytes);
if(query==ERROR_FILE_NOT_FOUND)
{
ftpProfilesLoaded=true;
settings.loaded=true;
return true;
}
if(query!=ERROR_SUCCESS || !bytes || bytes>ftpProfilesMaxBytes) return false;
if(query!=ERROR_SUCCESS || !bytes || bytes>transferProfilesMaxBytes) return false;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,RRF_RT_REG_BINARY,
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference,RRF_RT_REG_BINARY,
nullptr,data.data(),&bytes)!=ERROR_SUCCESS) return false;
try
{
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
if(!rows.is_array()) return false;
std::vector<FtpProfile> profiles;
std::vector<TransferProfile> profiles;
for(const auto &row:rows)
{
const auto port=row.at("port").get<unsigned>();
if(!port || port>65535) return false;
FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
TransferProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
ks::wide(row.at("user")),static_cast<INTERNET_PORT>(port),row.at("secret").get<ks::Bytes>(),
row.value("legacyNames",false)};
row.value("legacyNames",false),row.value("id",std::string{}),protocol};
if(profile.id.empty()) profile.id="legacy:"+ks::utf8(profile.name);
if(profile.name.empty() || profile.host.empty()) return false;
if(protocol==TransferProtocol::sftp)
{
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));
}
ftpProfiles=std::move(profiles);
ftpProfilesLoaded=true;
if(protocol==TransferProtocol::sftp)
sshProfiles=std::make_shared<const std::vector<TransferProfile>>(profiles);
settings.rows=std::move(profiles);
settings.loaded=true;
return true;
}
catch(const std::exception &) {return false;}
}
std::wstring ftpPassword(const FtpProfile &profile)
const TransferProfile *findTransferProfile(std::string_view id,TransferProtocol protocol=TransferProtocol::ftp)
{
const auto &profiles=transferProfiles(protocol).rows;
const auto profile=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry) {
return entry.id==id;
});
return profile==profiles.end()?nullptr:&*profile;
}
std::wstring transferPassword(const TransferProfile &profile)
{
if(profile.secret.empty()) return {};
auto bytes=ks::unprotect(profile.secret);
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid FTP password");
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid saved transfer password");
std::wstring password(bytes.size()/sizeof(wchar_t),L'\0');
std::copy(bytes.begin(),bytes.end(),reinterpret_cast<unsigned char*>(password.data()));
SecureZeroMemory(bytes.data(),bytes.size());
@@ -99,6 +193,41 @@ void checkFileOperation(bool success)
if(!success) requireFileOperation(false,GetLastError());
}
std::wstring ftpFolderError(const std::system_error &error)
{
switch(error.code().value())
{
case ERROR_INTERNET_CANNOT_CONNECT: return L"Cannot reach FTP server.";
case ERROR_INTERNET_NAME_NOT_RESOLVED: return L"FTP host name could not be resolved.";
case ERROR_INTERNET_LOGIN_FAILURE: return L"FTP sign-in failed.";
case ERROR_INTERNET_TIMEOUT: return L"FTP connection timed out.";
default: break;
}
if(error.code().value()==ERROR_INTERNET_EXTENDED_ERROR)
{
DWORD response{},length{};
InternetGetLastResponseInfoW(&response,nullptr,&length);
if(length && length<=2048)
{
std::wstring text(length,L'\0');
if(InternetGetLastResponseInfoW(&response,text.data(),&length))
{
text.resize(length);
text.resize(std::min(text.size(),text.find_first_of(L"\r\n")));
if(!text.empty()) return text;
}
}
return L"The FTP server rejected the request.";
}
wchar_t message[256]{};
const DWORD length=FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS,
GetModuleHandleW(L"wininet.dll"),error.code().value(),0,message,static_cast<DWORD>(std::size(message)),nullptr);
if(!length) return fileError(error);
std::wstring text(message,length);
while(!text.empty() && (text.back()==L'\r' || text.back()==L'\n')) text.pop_back();
return text;
}
class FtpSession
{
FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)};
@@ -107,7 +236,7 @@ class FtpSession
UINT nameCodePage_;
public:
explicit FtpSession(const FtpProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8)
explicit FtpSession(const TransferProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8)
{
checkFileOperation(internet_.value!=nullptr);
DWORD timeout=10000, retries=1;
@@ -115,7 +244,7 @@ public:
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_RETRIES,&retries,sizeof(retries));
InternetSetOptionW(internet_.value,INTERNET_OPTION_RECEIVE_TIMEOUT,&timeout,sizeof(timeout));
InternetSetOptionW(internet_.value,INTERNET_OPTION_SEND_TIMEOUT,&timeout,sizeof(timeout));
auto password=ftpPassword(profile);
auto password=transferPassword(profile);
const auto user=profile.user.empty()?(password.empty()?nullptr:L"anonymous"):profile.user.c_str();
connection_.value=InternetConnectW(internet_.value,profile.host.c_str(),profile.port,
user,password.empty()?nullptr:password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
@@ -201,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();
}
+45 -50
View File
@@ -1,7 +1,7 @@
FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr)
FileEntries transferChildren(TransferSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr)
{
FileEntries entries;
const auto error=listFtpDirectory(session,directory,[&](const fs::path &path,const FileInfo &info)
const auto error=session.list(directory,[&](const fs::path &path,const FileInfo &info)
{
if(canceled && *canceled) return false;
entries.emplace_back(path,info);
@@ -11,30 +11,23 @@ FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std:
return entries;
}
std::optional<FileInfo> ftpEntry(const FileEntries &entries,const fs::path &path)
std::optional<FileInfo> transferEntry(const FileEntries &entries,const fs::path &path)
{
const auto entry=std::find_if(entries.begin(),entries.end(),
[&](const auto &item){return item.first==path;});
return entry==entries.end()?std::nullopt:std::optional<FileInfo>(entry->second);
}
void renameFtpEntry(FtpSession &ftp,const fs::path &source,const fs::path &target)
{
ftp.setDirectory(source.parent_path());
const auto oldName=ftp.encodeName(source.filename());
const auto newName=ftp.encodeName(target.filename());
checkFileOperation(FtpRenameFileA(ftp.handle(),oldName.c_str(),newName.c_str()));
}
struct CopyHost
{
std::optional<FilesConnection> files;
std::optional<FtpSession> ftp;
std::optional<TransferSession> ftp;
FileOperationElevation *elevation{};
fs::path listedDirectory;
FileEntries listedEntries;
std::optional<bool> copyMetadataSupport;
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile,FileOperationElevation *admin=nullptr)
CopyHost(const FilesPeer *peer,const std::optional<TransferProfile> &profile,FileOperationElevation *admin=nullptr)
{
if(profile) ftp.emplace(*profile);
else files.emplace(peer);
@@ -50,7 +43,7 @@ struct CopyHost
{
if(path!=listedDirectory)
{
listedEntries=ftpChildren(*ftp,path,&canceled);
listedEntries=transferChildren(*ftp,path,&canceled);
listedDirectory=path;
}
return listedEntries;
@@ -58,7 +51,7 @@ struct CopyHost
std::optional<FileInfo> stat(const fs::path &path,const std::atomic_bool &canceled)
{
return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path)));
return ftp?transferEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path)));
}
FileEntries children(const fs::path &path,const std::atomic_bool &canceled)
@@ -75,6 +68,17 @@ struct CopyHost
return entries;
}
bool supportsCopyMetadata()
{
if(!copyMetadataSupport)
{
const auto reply=request(fileRequest("fileCapabilities",L"C:\\"));
if(reply.at("error")!=ERROR_INVALID_FUNCTION) checkFileReply(reply);
copyMetadataSupport=reply.value("copyMetadata",false);
}
return *copyMetadataSupport;
}
void makeDirectory(const fs::path &path)
{
if(!ftp)
@@ -82,8 +86,7 @@ struct CopyHost
checkFileReply(request(fileRequest("mkdir",path)));
return;
}
ftp->setDirectory(path.parent_path());
checkFileOperation(FtpCreateDirectoryA(ftp->handle(),ftp->encodeName(path.filename()).c_str()));
ftp->makeDirectory(path);
listedDirectory.clear();
}
@@ -91,10 +94,7 @@ struct CopyHost
{
if(ftp)
{
ftp->setDirectory(path.parent_path());
const auto name=ftp->encodeName(path.filename());
checkFileOperation(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)?
FtpRemoveDirectoryA(ftp->handle(),name.c_str()):FtpDeleteFileA(ftp->handle(),name.c_str()));
ftp->remove(path,attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY));
return;
}
auto message=fileRequest(permanent?"remove":"recycle",path);
@@ -103,14 +103,10 @@ struct CopyHost
}
};
constexpr DWORD ftpCopyFlags=INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE;
void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &source,const fs::path &target,
void downloadTransferFile(TransferSession &ftp,FilesConnection &local,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress)
{
ftp.setDirectory(source.parent_path());
const FtpHandle input{FtpOpenFileA(ftp.handle(),ftp.encodeName(source.filename()).c_str(),GENERIC_READ,ftpCopyFlags,0)};
checkFileOperation(input.value!=nullptr);
auto input=ftp.open(source,false);
auto upload=fileRequest("openWrite",target);
upload["transfer"]=ks::lan::randomHex(32);
upload["size"]=info.size;
@@ -123,8 +119,7 @@ void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &sour
ks::Bytes bytes(ks::lan::FileChunk);
while(!progress || progress(done,info.size))
{
DWORD read{};
checkFileOperation(InternetReadFile(input.value,bytes.data(),static_cast<DWORD>(bytes.size()),&read));
const auto read=input.read(bytes.data(),bytes.size());
if(!read)
{
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
@@ -146,9 +141,9 @@ void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &sour
}
}
FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &source,const fs::path &target,
FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress,
const ks::files::RemoteTextRevision *expected=nullptr)
const ks::files::RemoteTextRevision *expected=nullptr,bool preserveTime=false)
{
const auto directory=target.parent_path();
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
@@ -156,55 +151,55 @@ FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &so
open["size"]=info.size;
open["modified"]=info.modified;
checkFileReply(local.call(open));
ftp.setDirectory(directory);
const auto stage=ftp.encodeName(temporary.filename());
bool staged=false;
bool staged=false,reading=true;
try
{
uint64_t done=0;
{
FtpHandle output{FtpOpenFileA(ftp.handle(),stage.c_str(),GENERIC_WRITE,ftpCopyFlags,0)};
checkFileOperation(output.value!=nullptr);
auto output=ftp.open(temporary,true);
staged=true;
for(;;)
{
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
const auto packet=local.call({{"action","read"}});
checkFileReply(packet);
const auto &bytes=packet.at("data").get_binary();
if(bytes.empty()) break;
requireFileOperation(bytes.size()<=info.size-done,ERROR_FILE_INVALID);
for(DWORD offset=0;offset<bytes.size();)
for(size_t offset=0;offset<bytes.size();)
{
DWORD written{};
checkFileOperation(InternetWriteFile(output.value,bytes.data()+offset,
static_cast<DWORD>(bytes.size()-offset),&written));
const auto written=output.write(bytes.data()+offset,bytes.size()-offset);
requireFileOperation(written!=0,ERROR_WRITE_FAULT);
offset+=written;
}
done+=bytes.size();
}
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
checkFileOperation(InternetCloseHandle(output.value));
output.value=nullptr;
output.close();
}
checkFileReply(local.call({{"action","closeRead"}}));
const auto entries=ftpChildren(ftp,directory);
const auto uploaded=ftpEntry(entries,temporary);
reading=false;
const auto entries=transferChildren(ftp,directory);
const auto uploaded=transferEntry(entries,temporary);
requireFileOperation(uploaded && uploaded->size==done,ERROR_WRITE_FAULT);
const auto existing=ftpEntry(entries,target);
const auto existing=transferEntry(entries,target);
if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified))
throw std::runtime_error("The FTP file changed since it was opened. Your edits are still in the editor.");
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);
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
renameFtpEntry(ftp,temporary,target);
ftp.prepareReplacement(temporary,target);
}
if(preserveTime) ftp.preserveModificationTime(temporary,info.modified);
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
ftp.rename(temporary,target,existing.has_value());
return *uploaded;
}
catch(...)
{
if(staged) FtpDeleteFileA(ftp.handle(),stage.c_str());
if(reading) try {local.call({{"action","closeRead"}});} catch(const std::exception &) {}
if(staged) try {ftp.remove(temporary,false);} catch(const std::exception &) {}
throw;
}
}
+276 -81
View File
@@ -1,76 +1,82 @@
namespace ftpDialog
namespace transferDialog
{
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
std::wstring trim(std::wstring value)
{
const auto first=value.find_first_not_of(L" \t\r\n");
if(first==value.npos) return {};
return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1);
}
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566,jumpVia=567,jumpLabel=568;
constexpr int sudoLabel=569,sudoServer=570;
struct Edit
{
FtpProfile profile;
TransferProfile profile;
std::optional<size_t> index;
std::wstring pinnedHost;
INTERNET_PORT pinnedPort{};
std::string pin;
std::vector<std::string> jumpChoices;
bool testing{};
std::atomic_bool canceled{};
};
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
bool sameEndpoint(const Edit &edit,const TransferProfile &profile)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" FTP connection ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
return edit.pinnedPort==profile.port && CompareStringOrdinal(edit.pinnedHost.c_str(),-1,
profile.host.c_str(),-1,TRUE)==CSTR_EQUAL;
}
std::wstring connectionTitle(TransferProtocol protocol)
{
return std::wstring(transferProtocolName(protocol))+L" connection";
}
void showHostStatus(HWND dialog,const Edit &edit)
{
TransferProfile current;
current.host=trimFilesField(shortcutField(dialog,host));
BOOL valid{};
current.port=static_cast<INTERNET_PORT>(GetDlgItemInt(dialog,port,&valid,FALSE));
const bool trusted=valid && !edit.pin.empty() && sameEndpoint(edit,current);
const auto message=trusted?L"Trusted "+ks::wide(edit.pin):std::wstring(L"Host key not verified");
SetDlgItemTextW(dialog,hostStatus,message.c_str());
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;
profile.protocol=edit.profile.protocol;
const bool sftp=profile.protocol==TransferProtocol::sftp;
const auto invalid=[&](int field,const wchar_t *message)->std::optional<TransferProfile>
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
auto &profile=reinterpret_cast<Edit*>(lp)->profile;
prepareCopyDialog(dialog);
layoutDialogContent(dialog,381);
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
for(const auto id:{name,host,user,password})
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0);
SetDlgItemTextW(dialog,name,profile.name.c_str());
SetDlgItemTextW(dialog,host,profile.host.c_str());
SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str());
SetDlgItemTextW(dialog,user,profile.user.c_str());
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
try
{
auto secret=ftpPassword(profile);
SetDlgItemTextW(dialog,password,secret.c_str());
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
}
catch(const std::exception &)
{
SetWindowTextW(GetDlgItem(dialog,389),L"&Password (re-enter to replace saved password)");
}
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &edit=*reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
const auto invalid=[&](int field,const wchar_t *message)
{
showFilesNotice(dialog,message,L"FTP connection");
showFilesNotice(dialog,message,connectionTitle(profile.protocol).c_str());
SetFocus(GetDlgItem(dialog,field));
return TRUE;
return {};
};
FtpProfile profile;
profile.legacyNames=IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
profile.name=trim(shortcutField(dialog,name));
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)
return invalid(name,L"Enter a name for this connection.");
for(size_t i=0;i<ftpProfiles.size();++i)
if(edit.index!=i && CompareStringOrdinal(ftpProfiles[i].name.c_str(),-1,profile.name.c_str(),-1,TRUE)==CSTR_EQUAL)
const auto &profiles=transferProfiles(profile.protocol).rows;
for(size_t i=0;i<profiles.size();++i)
if(edit.index!=i && CompareStringOrdinal(profiles[i].name.c_str(),-1,profile.name.c_str(),-1,TRUE)==CSTR_EQUAL)
return invalid(name,L"A connection with this name already exists.");
profile.host=trim(shortcutField(dialog,host));
profile.host=trimFilesField(shortcutField(dialog,host));
if(profile.host.empty() || profile.host.find_first_of(L" /\\@\t\r\n")!=profile.host.npos)
return invalid(host,L"Enter the server host name or IP address.");
const auto value=shortcutField(dialog,port);
@@ -78,52 +84,241 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(!number || number>65535) return invalid(port,L"Enter a port from 1 to 65535.");
profile.port=static_cast<INTERNET_PORT>(number);
profile.user=shortcutField(dialog,user);
if(profile.user.find_first_of(L"\r\n")!=profile.user.npos)
if(profile.user.find_first_of(L"\r\n")!=profile.user.npos || (sftp && profile.user.empty()))
return invalid(user,L"Enter the user name on one line.");
if(sftp)
{
profile.privateKey=trimFilesField(shortcutField(dialog,keyFile));
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())
{
const auto start=reinterpret_cast<const unsigned char*>(plain.data());
ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t));
struct Erase
{
ks::Bytes &bytes;
std::wstring &text;
~Erase()
{
SecureZeroMemory(bytes.data(),bytes.size());
SecureZeroMemory(text.data(),text.size()*sizeof(wchar_t));
}
} erase{bytes,plain};
profile.secret=ks::protect(bytes);
}
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,jumpVia,sudoServer,testConnection,forgetKey,IDOK};
edit.testing=true;
edit.canceled=false;
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),FALSE);
SetFocus(GetDlgItem(dialog,IDCANCEL));
SetDlgItemTextW(dialog,hostStatus,status);
std::wstring error;
try
{
auto plain=shortcutField(dialog,password);
if(!plain.empty())
FileOperationUi worker;
worker.run(dialog,edit.canceled,std::move(task));
}
catch(const std::exception &exception) {error=ks::wide(exception.what());}
edit.testing=false;
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),TRUE);
showHostStatus(dialog,edit);
if(edit.canceled) return false;
if(error.empty()) return true;
showFilesNotice(dialog,error.c_str(),L"SFTP connection test",{.tone=FilesNoticeTone::warning});
return false;
}
void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
{
if(profile.hostFingerprint.empty())
{
std::string fingerprint;
if(!runTest(dialog,edit,L"Reading the SSH host key…",[&] {
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)+
L"\r\n\r\nVerify this fingerprint with the server administrator. Trust this SSH host key?";
if(showFilesNotice(dialog,prompt.c_str(),L"Verify SFTP host key",{.confirm=true})!=IDYES) return;
edit.pinnedHost=profile.host;
edit.pinnedPort=profile.port;
profile.hostFingerprint=edit.pin=std::move(fingerprint);
}
fs::path initial;
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\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");
}
}
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *edit=message==WM_INITDIALOG?reinterpret_cast<Edit*>(lp):
reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
const bool sftp=edit && edit->profile.protocol==TransferProtocol::sftp;
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,sftp?L" SFTP connection ":L" FTP connection ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,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,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);
SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0);
SetDlgItemTextW(dialog,name,profile.name.c_str());
SetDlgItemTextW(dialog,host,profile.host.c_str());
SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str());
SetDlgItemTextW(dialog,user,profile.user.c_str());
if(sftp)
{
const auto start=reinterpret_cast<const unsigned char*>(plain.data());
ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t));
SecureZeroMemory(plain.data(),plain.size()*sizeof(wchar_t));
profile.secret=ks::protect(bytes);
SecureZeroMemory(bytes.data(),bytes.size());
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});
}
auto updated=ftpProfiles;
if(edit.index) updated[*edit.index]=std::move(profile);
else updated.push_back(std::move(profile));
if(saveFtpProfiles(updated))
else
{
ftpProfiles=std::move(updated);
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
}
try
{
auto secret=transferPassword(profile);
SetDlgItemTextW(dialog,password,secret.c_str());
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,389,L"&Secret (re-enter to replace the saved value)");
}
return TRUE;
}
if(!edit) return FALSE;
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
if(edit->testing)
{
edit->canceled=true;
SetDlgItemTextW(dialog,hostStatus,L"Stopping when the current request returns…");
}
else
{
SetDlgItemTextW(dialog,password,L"");
SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0);
FilesModalDialog::finish(dialog,IDCANCEL);
}
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(edit->testing) return TRUE;
const auto command=LOWORD(wp);
if(sftp && HIWORD(wp)==EN_CHANGE && (command==host || command==port))
{
showHostStatus(dialog,*edit);
return TRUE;
}
if(sftp && command==forgetKey)
{
if(showFilesNotice(dialog,L"Forget the trusted key for this endpoint? A new key must be verified before signing in.",
L"SFTP host key",{.confirm=true})==IDYES)
{
edit->pin.clear();
showHostStatus(dialog,*edit);
}
return TRUE;
}
if(command!=IDOK && (!sftp || command!=testConnection)) return FALSE;
try
{
auto profile=readProfile(dialog,*edit);
if(!profile) return TRUE;
if(command==testConnection)
{
testSftp(dialog,*edit,std::move(*profile));
return TRUE;
}
auto &settings=transferProfiles(profile->protocol);
auto updated=settings.rows;
if(edit->index) updated[*edit->index]=std::move(*profile);
else updated.push_back(std::move(*profile));
if(saveTransferProfiles(edit->profile.protocol,updated))
{
settings.rows=std::move(updated);
SetDlgItemTextW(dialog,password,L"");
SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
}
catch(const std::exception &) {}
showFilesNotice(dialog,L"Could not save the FTP connection.",L"FTP connection");
const auto title=connectionTitle(edit->profile.protocol);
showFilesNotice(dialog,(L"Could not save the "+title+L".").c_str(),title.c_str());
return TRUE;
}
}
void editFtpProfile(Panel &panel,bool create)
void editTransferProfile(Panel &panel,bool create)
{
ftpDialog::Edit edit;
transferDialog::Edit edit;
const auto protocol=panel.ftp->protocol;
const auto &profiles=transferProfiles(protocol).rows;
edit.profile.protocol=protocol;
if(protocol==TransferProtocol::sftp) edit.profile.port=defaultSftpPort;
if(!create)
{
const auto row=currentPanelRow(panel);
if(row<0 || static_cast<size_t>(row)>=ftpProfiles.size()) return;
if(row<0 || static_cast<size_t>(row)>=profiles.size()) return;
edit.index=static_cast<size_t>(row);
edit.profile=ftpProfiles[*edit.index];
edit.profile=profiles[*edit.index];
edit.pinnedHost=edit.profile.host;
edit.pinnedPort=edit.profile.port;
edit.pin=edit.profile.hostFingerprint;
}
const auto owner=GetParent(panel.list);
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(112),owner,
ftpDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
const auto resource=protocol==TransferProtocol::sftp?124:112;
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(resource),owner,
transferDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
for(auto &other:panels)
{
if(!ftpProfileList(other) || other.scan.valid()) continue;
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(ftpProfiles.size()-1)):fs::path{};
showFtpProfiles(other,selection);
if(!transferProfileList(other) || other.ftp->protocol!=protocol || other.scan.valid()) continue;
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(profiles.size()-1)):fs::path{};
showTransferProfiles(other,protocol,selection);
}
}
+740
View File
@@ -0,0 +1,740 @@
#include "files_git_changes.h"
#include "core.h"
#include "windows_command_line.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <objbase.h>
#include <optional>
#include <stdexcept>
#include <system_error>
#include <tuple>
#include <utility>
namespace ks::files
{
namespace
{
namespace fs=std::filesystem;
struct GitHandle
{
HANDLE value{};
void close()
{
if(value && value!=INVALID_HANDLE_VALUE) CloseHandle(value);
value=nullptr;
}
~GitHandle(){close();}
};
[[noreturn]] void gitWindowsError(const char *operation)
{
throw std::system_error(GetLastError(),std::system_category(),operation);
}
void makeGitPipe(GitHandle &read,GitHandle &write,SECURITY_ATTRIBUTES &inheritable)
{
if(!CreatePipe(&read.value,&write.value,&inheritable,0) ||
!SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0))
gitWindowsError("Could not create the Git output pipe");
}
fs::path locateGit()
{
const DWORD size=GetEnvironmentVariableW(L"PATH",nullptr,0);
std::wstring paths(size,L'\0');
if(size)
{
const auto count=GetEnvironmentVariableW(L"PATH",paths.data(),size);
paths.resize(count<size?count:0);
}
std::wstring_view remaining=paths;
while(!remaining.empty())
{
const auto end=remaining.find(L';');
auto directory=remaining.substr(0,end);
if(directory.size()>=2 && directory.front()==L'"' && directory.back()==L'"')
directory=directory.substr(1,directory.size()-2);
const auto path=fs::path(directory);
if(path.is_absolute())
{
const auto candidate=path/L"git.exe";
const auto attributes=GetFileAttributesW(candidate.c_str());
if(attributes!=INVALID_FILE_ATTRIBUTES && !(attributes&FILE_ATTRIBUTE_DIRECTORY)) return candidate;
}
if(end==remaining.npos) break;
remaining.remove_prefix(end+1);
}
for(const auto key:{HKEY_CURRENT_USER,HKEY_LOCAL_MACHINE})
{
wchar_t install[32768]{};
DWORD bytes=sizeof(install);
if(RegGetValueW(key,L"SOFTWARE\\GitForWindows",L"InstallPath",RRF_RT_REG_SZ,nullptr,install,&bytes)!=ERROR_SUCCESS)
continue;
const auto git=fs::path(install)/L"cmd"/L"git.exe";
if(git.is_absolute() && GetFileAttributesW(git.c_str())!=INVALID_FILE_ATTRIBUTES) return git;
}
throw std::runtime_error("Git for Windows was not found. Install it or add git.exe to PATH.");
}
std::vector<wchar_t> gitEnvironment(const fs::path &alternateIndex)
{
const auto environment=GetEnvironmentStringsW();
if(!environment) gitWindowsError("Could not read the environment for Git");
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> owned(environment,FreeEnvironmentStringsW);
constexpr std::wstring_view overrides[]{
L"GIT_DIR",L"GIT_WORK_TREE",L"GIT_COMMON_DIR",L"GIT_INDEX_FILE",L"GIT_PREFIX",
L"GIT_OBJECT_DIRECTORY",L"GIT_ALTERNATE_OBJECT_DIRECTORIES",L"GIT_NAMESPACE",L"GIT_QUARANTINE_PATH",
L"GIT_CEILING_DIRECTORIES",L"GIT_GLOB_PATHSPECS",L"GIT_NOGLOB_PATHSPECS",L"GIT_ICASE_PATHSPECS"};
std::vector<std::wstring> settings;
for(auto entry=environment;*entry;)
{
const std::wstring_view setting=entry;
const auto name=setting.substr(0,setting.find(L'='));
if(std::none_of(std::begin(overrides),std::end(overrides),[&](std::wstring_view key) {
return name.size()==key.size() &&
CompareStringOrdinal(name.data(),static_cast<int>(name.size()),key.data(),static_cast<int>(key.size()),TRUE)
==CSTR_EQUAL;
}))
settings.emplace_back(setting);
entry+=setting.size()+1;
}
if(!alternateIndex.empty()) settings.push_back(L"GIT_INDEX_FILE="+alternateIndex.native());
std::sort(settings.begin(),settings.end(),[](const auto &left,const auto &right) {
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)==CSTR_LESS_THAN;
});
std::vector<wchar_t> result;
for(const auto &setting:settings) result.insert(result.end(),setting.c_str(),setting.c_str()+setting.size()+1);
result.push_back(L'\0');
if(result.size()==1) result.push_back(L'\0');
return result;
}
struct GitProcessAttributes
{
std::vector<std::byte> storage;
LPPROC_THREAD_ATTRIBUTE_LIST list{};
explicit GitProcessAttributes(HANDLE (&inherited)[3])
{
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
storage.resize(bytes);
const auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes))
gitWindowsError("Could not initialize the Git process");
if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr))
{
const auto error=GetLastError();
DeleteProcThreadAttributeList(attributes);
throw std::system_error(error,std::system_category(),"Could not set Git process handles");
}
list=attributes;
}
~GitProcessAttributes(){DeleteProcThreadAttributeList(list);}
};
struct GitOutput
{
std::string output, error;
DWORD exitCode{};
};
struct GitCommandOptions
{
fs::path index;
std::string_view input;
std::function<void()> afterPrepare;
ULONGLONG timeout=15000;
};
GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector<std::wstring> &arguments,
size_t maximum,std::stop_token stop,const GitCommandOptions &options={})
{
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
auto command=quoteWindowsArgument(git.native())+
L" --no-pager --no-optional-locks --literal-pathspecs -c core.fsmonitor=false -c core.quotePath=false -C "+
quoteWindowsArgument(directory.native());
for(const auto &argument:arguments) command+=L' '+quoteWindowsArgument(argument);
auto environment=gitEnvironment(options.index);
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
GitHandle input,writeInput;
if(options.input.empty())
{
input.value=CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr);
if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input");
}
else if(!CreatePipe(&input.value,&writeInput.value,&inheritable,65536) ||
!SetHandleInformation(writeInput.value,HANDLE_FLAG_INHERIT,0))
gitWindowsError("Could not open Git input");
GitHandle out,childOut,error,childError;
makeGitPipe(out,childOut,inheritable);
makeGitPipe(error,childError,inheritable);
HANDLE inherited[]{input.value,childOut.value,childError.value};
GitProcessAttributes attributes(inherited);
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput=input.value;
startup.StartupInfo.hStdOutput=childOut.value;
startup.StartupInfo.hStdError=childError.value;
startup.lpAttributeList=attributes.list;
PROCESS_INFORMATION child{};
if(!CreateProcessW(git.c_str(),command.data(),nullptr,nullptr,TRUE,
CREATE_NO_WINDOW|CREATE_SUSPENDED|CREATE_UNICODE_ENVIRONMENT|EXTENDED_STARTUPINFO_PRESENT,
environment.data(),directory.c_str(),&startup.StartupInfo,&child))
gitWindowsError("Could not start Git");
const GitHandle process{child.hProcess},thread{child.hThread};
const GitHandle job{CreateJobObjectW(nullptr,nullptr)};
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(job.value && SetInformationJobObject(job.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))
AssignProcessToJobObject(job.value,process.value);
try
{
if(ResumeThread(thread.value)==DWORD(-1)) gitWindowsError("Could not resume Git");
input.close();
childOut.close();
childError.close();
const auto write=[&](std::string_view payload)
{
DWORD written{};
if(payload.size()>65536 || !WriteFile(writeInput.value,payload.data(),
static_cast<DWORD>(payload.size()),&written,nullptr) || written!=payload.size())
gitWindowsError("Could not send input to Git");
};
if(writeInput.value) write(options.input);
if(!options.afterPrepare) writeInput.close();
GitOutput result;
auto deadline=GetTickCount64()+options.timeout;
const auto read=[&](HANDLE pipe,std::string &data,size_t limit)
{
DWORD waiting{},readBytes{};
char buffer[8192];
if(!PeekNamedPipe(pipe,nullptr,0,nullptr,&waiting,nullptr))
{
if(GetLastError()==ERROR_BROKEN_PIPE) return false;
gitWindowsError("Could not read Git output");
}
if(!waiting) return false;
if(!ReadFile(pipe,buffer,std::min<DWORD>(waiting,sizeof(buffer)),&readBytes,nullptr))
gitWindowsError("Could not read Git output");
if(data.size()+readBytes>limit) throw std::runtime_error("Git output was too large to display.");
data.append(buffer,readBytes);
return readBytes!=0;
};
for(;;)
{
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
if(GetTickCount64()>=deadline) throw std::runtime_error("Git did not respond in time.");
const bool readOutput=read(out.value,result.output,maximum);
const bool readErrors=read(error.value,result.error,256*1024);
if(writeInput.value && (result.output.find("prepare: ok\n")!=std::string::npos ||
result.output.find("prepare: ok\r\n")!=std::string::npos))
{
options.afterPrepare();
write("commit\n");
writeInput.close();
deadline=GetTickCount64()+options.timeout;
}
const auto state=WaitForSingleObject(process.value,readOutput || readErrors?0:20);
if(state==WAIT_FAILED) gitWindowsError("Could not wait for Git");
if(state==WAIT_OBJECT_0 && !readOutput && !readErrors)
{
if(read(out.value,result.output,maximum) || read(error.value,result.error,256*1024))
continue;
if(!GetExitCodeProcess(process.value,&result.exitCode)) gitWindowsError("Could not read Git status");
return result;
}
}
}
catch(...)
{
const bool wasWaitingForInput=writeInput.value!=nullptr;
writeInput.close(); // EOF aborts a prepared Git reference transaction.
if(!wasWaitingForInput || WaitForSingleObject(process.value,2000)!=WAIT_OBJECT_0)
TerminateProcess(process.value,ERROR_CANCELLED);
throw;
}
}
void checkGit(const GitOutput &result,const char *operation,bool allowDifference=false)
{
if(!result.exitCode || (allowDifference && result.exitCode==1)) return;
auto detail=result.error;
while(!detail.empty() && (detail.back()=='\r' || detail.back()=='\n')) detail.pop_back();
throw std::runtime_error(detail.empty()?std::string(operation):std::string(operation)+"\r\n"+detail);
}
std::string_view nulField(std::string_view &input)
{
const auto separator=input.find('\0');
if(separator==input.npos) throw std::runtime_error("Git returned incomplete output.");
const auto field=input.substr(0,separator);
input.remove_prefix(separator+1);
return field;
}
std::wstring statusPath(std::string_view value)
{
if(value.empty() || value.starts_with('/') || value.find_first_of("\\:")!=value.npos)
throw std::runtime_error("Git returned an unsupported worktree path.");
for(auto suffix=value;!suffix.empty();)
{
const auto slash=suffix.find('/');
const auto part=suffix.substr(0,slash);
if(part=="." || part==".." || part.empty())
throw std::runtime_error("Git returned an unsupported worktree path.");
if(slash==suffix.npos) break;
suffix.remove_prefix(slash+1);
}
return wide(std::string(value));
}
std::vector<GitChange> parseGitStatus(std::string_view output)
{
std::vector<GitChange> result;
while(!output.empty())
{
const auto row=nulField(output);
if(row.size()<4 || row[2]!=' ') throw std::runtime_error("Git returned an invalid status record.");
const auto code=row.substr(0,2);
const auto path=statusPath(row.substr(3));
std::wstring origin;
if(code.find_first_of("RC")!=code.npos) origin=statusPath(nulField(output));
if(code=="??") result.push_back({GitChangeKind::untracked,path,{},L"?"});
else if(code=="DD" || code=="AA" || code.find('U')!=code.npos)
result.push_back({GitChangeKind::unstaged,path,{},wide(std::string(code))});
else
{
if(code[0]!=' ') result.push_back({GitChangeKind::staged,path,origin,std::wstring(1,code[0])});
if(code[1]!=' ') result.push_back({GitChangeKind::unstaged,path,origin,std::wstring(1,code[1])});
}
}
std::sort(result.begin(),result.end(),[](const auto &left,const auto &right) {
return std::tie(left.kind,left.path)<std::tie(right.kind,right.path);
});
return result;
}
std::wstring gitRevision(std::string_view value)
{
if((value.size()!=40 && value.size()!=64) || value.find_first_not_of("0123456789abcdef")!=value.npos)
throw std::runtime_error("Git returned an invalid object ID.");
return {value.begin(),value.end()};
}
void trimGitLine(std::string &line)
{
while(!line.empty() && (line.back()=='\n' || line.back()=='\r')) line.pop_back();
}
GitCheckout readCheckout(const fs::path &git,const fs::path &root,std::stop_token stop)
{
auto branch=runGit(git,root,{L"symbolic-ref",L"--quiet",L"HEAD"},64*1024,stop);
checkGit(branch,"Could not read the checked-out branch.",true);
auto head=runGit(git,root,{L"rev-parse",L"--verify",L"--quiet",L"HEAD"},64*1024,stop);
checkGit(head,"Could not read Git HEAD.",true);
trimGitLine(branch.output);
trimGitLine(head.output);
return {branch.exitCode?std::wstring{}:wide(branch.output),
head.exitCode?std::wstring{}:gitRevision(head.output)};
}
std::vector<GitChange> readStatus(const fs::path &git,const fs::path &root,std::stop_token stop)
{
const auto status=runGit(git,root,{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"},
8*1024*1024,stop);
checkGit(status,"Could not read Git worktree status.");
return parseGitStatus(status.output);
}
struct GitWorktreeFiles
{
fs::path index;
std::vector<std::pair<fs::path,const char *>> operations;
};
GitWorktreeFiles findWorktreeFiles(const GitChanges &worktree,std::stop_token stop)
{
constexpr std::pair<const wchar_t *,const char *> markers[]{
{L"MERGE_HEAD","merge"},{L"CHERRY_PICK_HEAD","cherry-pick"},{L"REVERT_HEAD","revert"},
{L"rebase-merge","rebase"},{L"rebase-apply","rebase or am"},{L"sequencer","sequencer"},
{L"BISECT_START","bisect"}};
std::vector<std::wstring> args{L"rev-parse",L"--path-format=absolute",L"--git-path",L"index"};
for(const auto &[name,operation]:markers)
{
args.push_back(L"--git-path");
args.push_back(name);
}
const auto paths=runGit(worktree.executable,worktree.root,args,256*1024,stop);
checkGit(paths,"Could not find the worktree index.");
std::string_view lines=paths.output;
const auto next=[&]
{
if(lines.empty()) throw std::runtime_error("Git returned incomplete worktree metadata.");
const auto separator=lines.find('\n');
auto line=lines.substr(0,separator);
lines.remove_prefix(separator==lines.npos?lines.size():separator+1);
if(line.ends_with('\r')) line.remove_suffix(1);
auto path=fs::path(wide(std::string(line))).make_preferred();
if(!path.is_absolute()) throw std::runtime_error("Git returned an invalid worktree path.");
return path;
};
GitWorktreeFiles result{next(),{}};
for(const auto &[name,operation]:markers) result.operations.emplace_back(next(),operation);
return result;
}
struct WorktreeIndexLock
{
GitHandle file;
explicit WorktreeIndexLock(const fs::path &index)
{
auto name=index;
name+=L".lock";
file.value=CreateFileW(name.c_str(),GENERIC_WRITE|DELETE,0,nullptr,CREATE_NEW,
FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr);
if(file.value!=INVALID_HANDLE_VALUE) return;
const auto error=GetLastError();
if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS || error==ERROR_SHARING_VIOLATION)
throw std::runtime_error("Git index is locked. Finish the other Git operation, then refresh.");
throw std::system_error(error,std::system_category(),"Could not lock the Git index");
}
WorktreeIndexLock(const WorktreeIndexLock &)=delete;
};
struct WorktreeIndexCopy
{
fs::path path;
explicit WorktreeIndexCopy(const fs::path &index)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,static_cast<int>(std::size(name))))
throw std::runtime_error("Could not name the temporary Git index.");
path=index;
path+=std::wstring(L".kswitcher-")+name;
if(CopyFileW(index.c_str(),path.c_str(),TRUE)) return;
const auto error=GetLastError();
if(error!=ERROR_FILE_NOT_FOUND)
throw std::system_error(error,std::system_category(),"Could not copy the worktree index");
}
WorktreeIndexCopy(const WorktreeIndexCopy &)=delete;
~WorktreeIndexCopy()
{
DeleteFileW(path.c_str());
const auto lock=path.native()+L".lock";
DeleteFileW(lock.c_str());
}
void publish(const fs::path &index) const
{
if(!MoveFileExW(path.c_str(),index.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
gitWindowsError("Could not replace the Git index");
}
};
void requireWritableWorktree(const GitChanges &worktree,const GitWorktreeFiles &paths,
const GitCheckout &checkout,std::stop_token stop)
{
if(!checkout.ref.starts_with(L"refs/heads/"))
throw std::runtime_error("This worktree has detached HEAD. Check out a branch before writing Git changes.");
for(const auto &[path,operation]:paths.operations)
{
if(GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES)
throw std::runtime_error(std::string("A Git ")+operation+" is in progress. Finish it before writing changes.");
const auto error=GetLastError();
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND)
throw std::system_error(error,std::system_category(),"Could not check for active Git operations");
}
const auto conflicts=runGit(worktree.executable,worktree.root,{L"ls-files",L"--unmerged",L"-z"},2*1024*1024,stop);
checkGit(conflicts,"Could not check Git index conflicts.");
if(!conflicts.output.empty()) throw std::runtime_error("The Git index contains conflicts. Resolve them before writing changes.");
}
GitCommitReview captureGitReview(const GitChanges &worktree,const GitCheckout &checkout,std::stop_token stop,
bool listPaths)
{
GitCommitReview review{worktree.root,checkout,{},{}};
std::vector<std::wstring> args{L"diff",L"--cached",L"--no-color",L"--no-ext-diff",L"--no-textconv",
L"--ita-invisible-in-index",L"-z"};
if(!checkout.revision.empty()) args.push_back(checkout.revision);
args.push_back(L"--");
auto identityArgs=args;
identityArgs.insert(identityArgs.begin()+1,{L"--raw",L"--no-renames",L"--abbrev=64"});
auto identity=runGit(worktree.executable,worktree.root,identityArgs,16*1024*1024,stop);
checkGit(identity,"Could not read the staged snapshot.");
review.stagedIdentity=std::move(identity.output);
if(!listPaths || review.stagedIdentity.empty()) return review;
args.insert(args.begin()+1,{L"--name-status",L"--find-renames"});
const auto changed=runGit(worktree.executable,worktree.root,args,8*1024*1024,stop);
checkGit(changed,"Could not list all staged paths.");
std::string_view records=changed.output;
while(!records.empty())
{
const auto flags=nulField(records);
if(flags.empty()) throw std::runtime_error("Git returned an invalid staged-path record.");
auto path=statusPath(nulField(records));
std::wstring old;
if(flags.front()=='R' || flags.front()=='C')
{
old=std::move(path);
path=statusPath(nulField(records));
}
review.staged.push_back({GitChangeKind::staged,std::move(path),std::move(old),wide(std::string(flags))});
}
return review;
}
}
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop)
{
GitChanges result;
result.executable=locateGit();
auto root=runGit(result.executable,directory,{L"rev-parse",L"--show-toplevel"},64*1024,stop);
checkGit(root,"This folder is not inside a Git worktree.");
trimGitLine(root.output);
result.root=fs::path(wide(root.output)).make_preferred();
if(!result.root.is_absolute()) throw std::runtime_error("Git returned an invalid worktree root.");
result.checkout=readCheckout(result.executable,result.root,stop);
result.entries=readStatus(result.executable,result.root,stop);
return result;
}
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
const GitChange &change,std::stop_token stop)
{
std::vector<std::wstring> args{L"diff",L"--no-color",L"--no-ext-diff",L"--no-textconv",L"--find-renames"};
const bool untracked=change.kind==GitChangeKind::untracked;
if(untracked) args.push_back(L"--no-index");
if(change.kind==GitChangeKind::staged) args.push_back(L"--cached");
args.push_back(L"--");
if(untracked) args.push_back(L"/dev/null");
else if(!change.oldPath.empty()) args.push_back(change.oldPath);
args.push_back(change.path);
auto patch=runGit(git,root,args,2*1024*1024,stop);
checkGit(patch,"Could not read this Git diff.",untracked);
return std::move(patch.output);
}
std::vector<GitBranch> readGitBranches(const std::filesystem::path &git,const std::filesystem::path &root,
std::stop_token stop)
{
const auto refs=runGit(git,root,{L"for-each-ref",L"--sort=refname",
L"--format=%(objectname)%00%(refname)%00%(HEAD)%00%(symref)",L"refs/heads",L"refs/remotes"},
4*1024*1024,stop);
checkGit(refs,"Could not read Git branches.");
constexpr std::string_view localPrefix="refs/heads/",remotePrefix="refs/remotes/";
std::vector<GitBranch> branches;
bool foundHead=false;
for(std::string_view remaining=refs.output;!remaining.empty();)
{
const auto newline=remaining.find('\n');
auto line=remaining.substr(0,newline);
remaining.remove_prefix(newline==remaining.npos?remaining.size():newline+1);
if(line.ends_with('\r')) line.remove_suffix(1);
if(line.empty()) continue;
const auto revision=gitRevision(nulField(line));
const auto ref=nulField(line);
const bool current=nulField(line)=="*";
if(!line.empty()) continue; // Skip aliases such as origin/HEAD.
const bool remote=ref.starts_with(remotePrefix);
if(!remote && !ref.starts_with(localPrefix)) continue;
const auto branch=wide(std::string(ref.substr(remote?remotePrefix.size():localPrefix.size())));
branches.push_back({wide(std::string(ref)),(current?L"* ":remote?L"Tracking · ":L"Local · ")+branch,
revision,current});
foundHead|=current;
}
if(!foundHead)
{
auto head=runGit(git,root,{L"rev-parse",L"--verify",L"--quiet",L"HEAD"},64*1024,stop);
checkGit(head,"Could not read Git HEAD.",true);
if(!head.exitCode)
{
while(!head.output.empty() && (head.output.back()=='\n' || head.output.back()=='\r')) head.output.pop_back();
branches.insert(branches.begin(),{L"HEAD",L"* Detached HEAD",gitRevision(head.output),true});
}
}
return branches;
}
GitHistoryPage readGitHistory(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,size_t offset,std::stop_token stop)
{
constexpr size_t pageSize=50;
const auto log=runGit(git,root,{L"log",L"--no-decorate",L"--no-notes",L"--no-show-signature",
L"--encoding=UTF-8",L"--date=short",L"--format=%H%x00%h%x00%ad%x00%s",L"-z",
L"--max-count="+std::to_wstring(pageSize+1),L"--skip="+std::to_wstring(offset),revision,L"--"},
2*1024*1024,stop);
checkGit(log,"Could not read Git history.");
GitHistoryPage page;
std::string_view records=log.output;
while(!records.empty() && page.commits.size()<pageSize)
page.commits.push_back({gitRevision(nulField(records)),wide(std::string(nulField(records))),
wide(std::string(nulField(records))),wide(std::string(nulField(records)))});
page.more=!records.empty();
return page;
}
std::string readGitCommit(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,std::stop_token stop)
{
const auto metadata=runGit(git,root,{L"log",L"-1",L"--no-decorate",L"--no-notes",L"--no-show-signature",
L"--encoding=UTF-8",L"--format=%H%x00%an%x00%ae%x00%aI%x00%B",L"-z",revision,L"--"},2*1024*1024,stop);
checkGit(metadata,"Could not read the Git commit.");
std::string_view parts=metadata.output;
const auto id=nulField(parts);
const auto author=nulField(parts);
const auto email=nulField(parts);
const auto date=nulField(parts);
const auto message=nulField(parts);
std::string text="Commit ";
text.append(id).append("\nAuthor ").append(author);
if(!email.empty()) text.append(" <").append(email).push_back('>');
text.append("\nDate ").append(date).append("\n\n").append(message);
while(!text.empty() && (text.back()=='\r' || text.back()=='\n')) text.pop_back();
const auto changes=runGit(git,root,{L"show",L"--no-notes",L"--no-show-signature",L"--format=",L"--name-status",
L"-z",L"--root",L"--diff-merges=first-parent",L"--find-renames",L"--no-ext-diff",L"--no-textconv",
revision,L"--"},2*1024*1024,stop);
checkGit(changes,"Could not read changed paths.");
text+="\n\nChanged paths\n";
if(changes.output.empty()) text+="No changed paths.\n";
std::string_view records=changes.output;
while(!records.empty())
{
const auto code=nulField(records);
if(code.empty()) throw std::runtime_error("Git returned an invalid changed-path record.");
text.append(code).append(" ").append(nulField(records));
if(code.front()=='R' || code.front()=='C')
text.append(" → ").append(nulField(records));
text.push_back('\n');
}
return text;
}
void changeGitIndex(const GitChanges &worktree,const GitChange &entry,bool replaceStaged,std::stop_token stop)
{
const auto paths=findWorktreeFiles(worktree,stop);
const WorktreeIndexLock lock(paths.index);
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
requireWritableWorktree(worktree,paths,checkout,stop);
if(checkout!=worktree.checkout)
throw std::runtime_error("The checked-out branch or commit changed. Review the refreshed Git changes.");
const auto entries=readStatus(worktree.executable,worktree.root,stop);
if(std::find(entries.begin(),entries.end(),entry)==entries.end())
throw std::runtime_error("The selected change is no longer current. Review the refreshed Git changes.");
const bool stage=entry.kind!=GitChangeKind::staged;
const bool rename=entry.flags.starts_with(L"R") || entry.flags.starts_with(L"C");
const auto overlaps=[&](const GitChange &other)
{
return other.kind==GitChangeKind::staged && (other.path==entry.path || other.oldPath==entry.path ||
(rename && !entry.oldPath.empty() && (other.path==entry.oldPath || other.oldPath==entry.oldPath)));
};
if(stage && !replaceStaged && std::any_of(entries.begin(),entries.end(),overlaps))
throw std::runtime_error("The selected path already has staged changes. Review and confirm the replacement.");
if(stage)
{
const auto attributes=GetFileAttributesW((worktree.root/fs::path(entry.path)).c_str());
if(entry.path.ends_with(L'/') || (attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)))
{
const auto indexed=runGit(worktree.executable,worktree.root,{L"ls-files",L"--stage",L"--",entry.path},
256*1024,stop);
checkGit(indexed,"Could not identify the selected directory.");
if(!indexed.output.starts_with("160000 "))
throw std::runtime_error("This entry is a directory. Stage individual files or an existing submodule.");
}
}
const WorktreeIndexCopy pending(paths.index);
std::vector<std::wstring> args;
if(stage) args={L"add",L"-A",L"--"};
else if(checkout.revision.empty()) args={L"rm",L"--cached",L"-f",L"--ignore-unmatch",L"--"};
else args={L"restore",L"--staged",L"--source="+checkout.revision,L"--"};
if(rename && !entry.oldPath.empty()) args.push_back(entry.oldPath);
args.push_back(entry.path);
const auto result=runGit(worktree.executable,worktree.root,args,1024*1024,stop,{.index=pending.path});
checkGit(result,stage?"Could not stage the selected path.":"Could not unstage the selected path.");
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout || stop.stop_requested())
throw std::runtime_error("The checkout changed while Git was working. Review the refreshed Git changes.");
requireWritableWorktree(worktree,paths,checkout,stop);
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
pending.publish(paths.index);
}
GitCommitReview reviewGitCommit(const GitChanges &worktree,std::stop_token stop)
{
const auto paths=findWorktreeFiles(worktree,stop);
const WorktreeIndexLock lock(paths.index);
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
requireWritableWorktree(worktree,paths,checkout,stop);
auto review=captureGitReview(worktree,checkout,stop,true);
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout)
throw std::runtime_error("The checkout changed while reading the staged paths. Open a new review.");
if(review.staged.empty()) throw std::runtime_error("Stage at least one change before committing.");
return review;
}
std::wstring createGitCommit(const GitChanges &worktree,const GitCommitReview &review,
const std::wstring &message,std::stop_token stop)
{
if(message.find_first_not_of(L" \t\r\n")==message.npos)
throw std::runtime_error("Enter a commit message.");
if(worktree.root!=review.root || review.stagedIdentity.empty())
throw std::runtime_error("The reviewed worktree changed. Open a new review.");
const auto paths=findWorktreeFiles(worktree,stop);
const WorktreeIndexLock lock(paths.index);
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
requireWritableWorktree(worktree,paths,checkout,stop);
if(checkout!=review.checkout || captureGitReview(worktree,checkout,stop,false).stagedIdentity!=review.stagedIdentity)
throw std::runtime_error("The checkout or staged changes changed after review. Review them again. The message was kept.");
const WorktreeIndexCopy pending(paths.index);
auto tree=runGit(worktree.executable,worktree.root,{L"write-tree"},64*1024,stop,{.index=pending.path});
checkGit(tree,"Could not write the reviewed Git tree.");
trimGitLine(tree.output);
const auto treeId=gitRevision(tree.output);
auto signing=runGit(worktree.executable,worktree.root,{L"config",L"--type=bool",L"--get",L"commit.gpgSign"},64*1024,stop);
checkGit(signing,"Could not read Git signing settings.",true);
trimGitLine(signing.output);
std::vector<std::wstring> args{L"commit-tree",treeId,L"-F",L"-"};
if(!checkout.revision.empty()) args.insert(args.end(),{L"-p",checkout.revision});
if(signing.output=="true") args.push_back(L"-S");
auto contents=utf8(message);
for(size_t pos=0;(pos=contents.find('\r',pos))!=contents.npos;)
{
if(pos+1<contents.size() && contents[pos+1]=='\n') contents.erase(pos,1);
else contents[pos++]='\n';
}
auto created=runGit(worktree.executable,worktree.root,args,64*1024,stop,{.input=contents,.timeout=120000});
checkGit(created,"Could not create the commit. Check your Git author identity and signing settings.");
trimGitLine(created.output);
const auto commit=gitRevision(created.output);
const auto expected=checkout.revision.empty()?std::string(commit.size(),'0'):utf8(checkout.revision);
const std::string transaction="start\nupdate HEAD "+created.output+" "+expected+"\nprepare\n";
try
{
const auto update=runGit(worktree.executable,worktree.root,
{L"-c",L"core.hooksPath=NUL",L"update-ref",L"-m",L"KSwitcher Files: local commit",L"--stdin"},
64*1024,stop,{.input=transaction,.afterPrepare=[&] {
// Git holds HEAD and its referent after prepare, while the index remains locked by Files.
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout)
throw std::runtime_error("The checkout changed after review. Review it again. The message was kept.");
requireWritableWorktree(worktree,paths,checkout,stop);
}});
checkGit(update,"Could not update the checked-out branch. Refresh and review the staged changes.");
if(update.output.find("commit: ok")==std::string::npos)
throw std::runtime_error("Git did not confirm the branch update.");
}
catch(...)
{
try
{
if(readCheckout(worktree.executable,worktree.root,{})==GitCheckout{checkout.ref,commit}) return commit;
}
catch(const std::exception &) {}
throw;
}
return commit;
}
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <filesystem>
#include <stop_token>
#include <string>
#include <vector>
namespace ks::files
{
enum class GitChangeKind { staged, unstaged, untracked };
struct GitChange
{
GitChangeKind kind;
std::wstring path;
std::wstring oldPath;
std::wstring flags;
bool operator==(const GitChange &) const = default;
};
struct GitCheckout
{
std::wstring ref, revision;
bool operator==(const GitCheckout &) const = default;
};
struct GitChanges
{
std::filesystem::path executable, root;
std::vector<GitChange> entries;
GitCheckout checkout;
};
struct GitBranch
{
std::wstring ref, label, revision;
bool current{};
};
struct GitCommit
{
std::wstring revision, abbreviated, date, subject;
};
struct GitHistoryPage
{
std::vector<GitCommit> commits;
bool more{};
};
struct GitCommitReview
{
std::filesystem::path root;
GitCheckout checkout;
std::vector<GitChange> staged;
std::string stagedIdentity;
};
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop);
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
const GitChange &change,std::stop_token stop);
std::vector<GitBranch> readGitBranches(const std::filesystem::path &git,const std::filesystem::path &root,
std::stop_token stop);
GitHistoryPage readGitHistory(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,size_t offset,std::stop_token stop);
std::string readGitCommit(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,std::stop_token stop);
void changeGitIndex(const GitChanges &worktree,const GitChange &entry,bool replaceStaged,std::stop_token stop);
GitCommitReview reviewGitCommit(const GitChanges &worktree,std::stop_token stop);
std::wstring createGitCommit(const GitChanges &worktree,const GitCommitReview &review,
const std::wstring &message,std::stop_token stop);
}
+904
View File
@@ -0,0 +1,904 @@
using ks::files::GitChange;
using ks::files::GitChangeKind;
using ks::files::GitChanges;
using ks::files::GitBranch;
using ks::files::GitCommit;
using ks::files::GitCommitReview;
using ks::files::GitHistoryPage;
struct GitPreview
{
std::wstring heading;
std::variant<GitChange,std::wstring> item;
};
struct GitHistoryUpdate
{
std::optional<std::vector<GitBranch>> branches;
GitHistoryPage page;
size_t branch=0;
};
struct GitChangesView
{
HWND host{},heading{},switchView{},filterLabel{},filter{},branchPicker{},list{},status{},hints{},preview{},moreButton{};
HWND indexButton{},commitButton{};
fs::path folder;
GitChanges data;
std::future<GitChanges> refresh;
std::future<std::string> previewTask;
std::stop_source stopRefresh,stopPreview;
ULONGLONG previewAt{};
std::optional<GitPreview> requested;
std::string failure;
bool historyMode{},moreHistory{};
std::vector<GitBranch> branches;
std::vector<GitCommit> commits;
size_t branchIndex{};
std::future<GitHistoryUpdate> historyTask;
std::stop_source stopHistory;
std::string historyFailure;
std::future<GitCommitReview> commitReview;
std::future<std::wstring> mutation;
std::stop_source stopMutation;
std::wstring commitDraft,operation,writeStatus;
bool promptingWrite{};
};
std::unique_ptr<GitChangesView> gitChangesView;
constexpr wchar_t gitChangesClass[]=L"KSwitcher.Files.GitChanges";
constexpr UINT_PTR gitChangesTimer=1;
constexpr int gitHeading=570,gitFilter=571,gitList=572,gitStatus=573,gitSwitch=574,gitBranch=575,gitMore=576;
constexpr int gitIndexAction=577,gitCommitAction=578;
const wchar_t *gitChangeKindName(GitChangeKind kind)
{
switch(kind)
{
case GitChangeKind::staged: return L"Staged";
case GitChangeKind::unstaged: return L"Unstaged";
case GitChangeKind::untracked: return L"Untracked";
}
return L"";
}
const GitChange *selectedGitChange(const GitChangesView &view)
{
const auto row=SendMessageW(view.list,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendMessageW(view.list,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<view.data.entries.size()?&view.data.entries[index]:nullptr;
}
const GitCommit *selectedGitCommit(const GitChangesView &view)
{
const auto row=SendMessageW(view.list,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendMessageW(view.list,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<view.commits.size()?&view.commits[index]:nullptr;
}
std::wstring gitChangePathLabel(const GitChange &entry)
{
return entry.oldPath.empty()?entry.path:entry.path+L" ← "+entry.oldPath;
}
std::wstring gitCheckoutLabel(const ks::files::GitCheckout &checkout)
{
constexpr std::wstring_view prefix=L"refs/heads/";
if(!checkout.ref.starts_with(prefix)) return L"Detached HEAD";
auto label=checkout.ref.substr(prefix.size());
if(checkout.revision.empty()) label+=L" (first commit)";
return label;
}
bool gitActionPending(const GitChangesView &view)
{
return view.commitReview.valid() || view.mutation.valid() || view.promptingWrite;
}
void updateGitActionButtons(GitChangesView &view)
{
const bool ready=!view.historyMode && !view.data.root.empty() && !view.refresh.valid() && !gitActionPending(view);
const auto *entry=view.historyMode?nullptr:selectedGitChange(view);
SetWindowTextW(view.indexButton,entry && entry->kind==GitChangeKind::staged?L"Unstage":L"Stage");
EnableWindow(view.indexButton,ready && entry);
EnableWindow(view.commitButton,ready);
EnableWindow(view.switchView,!view.data.root.empty() && !view.refresh.valid() && !gitActionPending(view));
}
void updateGitChangesStatus(GitChangesView &view,LRESULT shown=-1)
{
if(gitActionPending(view)) {SetWindowTextW(view.status,view.operation.c_str());return;}
if(view.refresh.valid()) {SetWindowTextW(view.status,L"Reading Git changes…");return;}
if(!view.failure.empty()) {SetWindowTextW(view.status,L"Could not read Git changes.");return;}
if(shown<0) shown=SendMessageW(view.list,LB_GETCOUNT,0,0);
const auto count=view.data.entries.size();
const std::wstring summary=!count?L"No Git changes.":shown<=0?L"No paths match the filter.":
std::to_wstring(shown)+(static_cast<size_t>(shown)==count?L"":L" of "+std::to_wstring(count))+L" changes";
SetWindowTextW(view.status,(view.writeStatus.empty()?summary:view.writeStatus+L" · "+summary).c_str());
}
std::wstring gitDiffHeading(const GitChange &entry)
{
return std::wstring(gitChangeKindName(entry.kind))+L" diff · "+entry.path;
}
void queueGitPreview(GitChangesView &view)
{
updateGitActionButtons(view);
view.stopPreview.request_stop();
view.previewTask={};
view.previewAt=0;
view.requested.reset();
if(view.historyMode)
{
if(const auto *commit=selectedGitCommit(view))
{
view.requested=GitPreview{L"Commit · "+commit->abbreviated,commit->revision};
view.previewAt=GetTickCount64()+100;
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
}
else if(!view.historyFailure.empty())
ks::files::previewQuickViewText(view.preview,L"Git history failed",view.historyFailure);
else ks::files::previewQuickViewText(view.preview,
view.historyTask.valid()?L"Commit · Reading history…":L"Commit · Select a commit",{});
return;
}
if(view.refresh.valid())
{
ks::files::previewQuickViewText(view.preview,L"Diff · Reading Git changes…",{});
return;
}
if(!view.failure.empty())
{
ks::files::previewQuickViewText(view.preview,L"Git status failed",view.failure);
return;
}
if(const auto *entry=selectedGitChange(view))
{
view.requested=GitPreview{gitDiffHeading(*entry),*entry};
view.previewAt=GetTickCount64()+100;
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
}
else ks::files::previewQuickViewText(view.preview,L"Diff · Select a change",{});
}
void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
{
auto query=dialogFieldText(view.filter);
std::replace(query.begin(),query.end(),L'\\',L'/');
const auto matches=[&](std::wstring_view path)
{
return query.empty() || (!path.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
path.data(),static_cast<int>(path.size()),query.data(),static_cast<int>(query.size()),
nullptr,nullptr,nullptr,0)>=0);
};
SendMessageW(view.list,WM_SETREDRAW,FALSE,0);
SendMessageW(view.list,LB_RESETCONTENT,0,0);
LRESULT selected=0,count=0;
for(size_t index=0;index<view.data.entries.size();++index)
{
const auto &entry=view.data.entries[index];
if(!matches(entry.path) && !matches(entry.oldPath)) continue;
auto state=std::wstring(gitChangeKindName(entry.kind));
state.resize(10,L' ');
state+=entry.flags;
state.resize(13,L' ');
const auto label=state+gitChangePathLabel(entry);
const auto row=SendMessageW(view.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row<0) continue;
++count;
SendMessageW(view.list,LB_SETITEMDATA,row,index);
if(previous && previous->path==entry.path && previous->kind==entry.kind) selected=row;
}
if(count) SendMessageW(view.list,LB_SETCURSEL,selected,0);
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(view.list,nullptr,TRUE);
InvalidateRect(view.host,nullptr,FALSE);
updateGitChangesStatus(view,count);
queueGitPreview(view);
}
void refreshGitChanges(GitChangesView &view)
{
if(view.refresh.valid() || gitActionPending(view)) return;
view.failure.clear();
view.stopRefresh=std::stop_source{};
try
{
std::packaged_task<GitChanges()> task([folder=view.folder,stop=view.stopRefresh.get_token()] {
return ks::files::readGitChanges(folder,stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.refresh=std::move(pending);
updateGitChangesStatus(view);
queueGitPreview(view);
}
catch(const std::exception &)
{
view.failure="Could not start Git.";
renderGitChanges(view);
}
}
struct GitCommitPrompt
{
const GitCommitReview &review;
std::wstring message;
};
INT_PTR CALLBACK gitCommitDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int branch=594,summary=595,staged=596,body=598,feedback=599,footer=600;
if(message==WM_INITDIALOG)
{
auto &prompt=*reinterpret_cast<GitCommitPrompt *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,branch);
SetDlgItemTextW(dialog,branch,(L"Branch "+gitCheckoutLabel(prompt.review.checkout)).c_str());
SetDlgItemTextW(dialog,summary,(std::to_wstring(prompt.review.staged.size())+L" staged changes · all paths").c_str());
const auto list=GetDlgItem(dialog,staged);
for(const auto &entry:prompt.review.staged)
{
const auto label=entry.flags+L" "+gitChangePathLabel(entry);
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
const auto bounds=dialogControlBounds(dialog,staged);
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
installScrollBar(list,dialog);
SendDlgItemMessageW(dialog,body,EM_SETLIMITTEXT,16000,0);
SetDlgItemTextW(dialog,body,prompt.message.c_str());
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(dialog,body));
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDCANCEL || LOWORD(wp)==IDOK)))
{
auto &prompt=*reinterpret_cast<GitCommitPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
prompt.message=dialogFieldText(GetDlgItem(dialog,body));
const bool submit=message==WM_COMMAND && LOWORD(wp)==IDOK;
if(submit && prompt.message.find_first_not_of(L" \t\r\n")==prompt.message.npos)
{
SetDlgItemTextW(dialog,feedback,L"Enter a commit message.");
ShowWindow(GetDlgItem(dialog,feedback),SW_SHOWNA);
SetFocus(GetDlgItem(dialog,body));
return TRUE;
}
FilesModalDialog::finish(dialog,submit?IDOK:IDCANCEL);
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==body && HIWORD(wp)==EN_CHANGE)
{
ShowWindow(GetDlgItem(dialog,feedback),SW_HIDE);
SetDlgItemTextW(dialog,feedback,L"");
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Commit staged changes ",false,{footer},false,GetDlgItem(dialog,staged));
}
GitChanges gitWorktreeTarget(const GitChangesView &view)
{
return {view.data.executable,view.data.root,{},view.data.checkout};
}
bool gitActionAvailable(const GitChangesView &view)
{
return !view.historyMode && !view.refresh.valid() && !gitActionPending(view) && !view.data.root.empty();
}
void showGitWriteError(GitChangesView &view,const std::exception &error)
{
std::wstring detail;
if(const auto *system=dynamic_cast<const std::system_error *>(&error)) detail=fileError(*system);
else
{
try {detail=ks::wide(error.what());}
catch(const std::exception &) {detail=L"Git returned an error in an unsupported encoding.";}
}
view.promptingWrite=true;
updateGitActionButtons(view);
showFilesNotice(GetParent(view.host),detail.c_str(),L"Git operation failed",{.tone=FilesNoticeTone::warning});
view.promptingWrite=false;
view.writeStatus=L"Git operation failed";
refreshGitChanges(view);
}
void runGitMutation(GitChangesView &view,std::wstring operation,
std::function<std::wstring(std::stop_token)> action)
{
view.stopMutation=std::stop_source{};
view.operation=std::move(operation);
try
{
std::packaged_task<std::wstring()> task([action=std::move(action),stop=view.stopMutation.get_token()] {
return action(stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.mutation=std::move(pending);
updateGitActionButtons(view);
updateGitChangesStatus(view);
}
catch(const std::exception &error) {showGitWriteError(view,error);}
}
void changeSelectedGitIndex(GitChangesView &view)
{
if(!gitActionAvailable(view)) return;
const auto *selected=selectedGitChange(view);
if(!selected) return;
const auto entry=*selected;
const bool stage=entry.kind!=GitChangeKind::staged;
const bool replace=stage && std::any_of(view.data.entries.begin(),view.data.entries.end(),[&](const auto &other) {
return other.kind==GitChangeKind::staged && (other.path==entry.path || other.oldPath==entry.path ||
(!entry.oldPath.empty() && (other.path==entry.oldPath || other.oldPath==entry.oldPath)));
});
if(replace)
{
view.promptingWrite=true;
updateGitActionButtons(view);
const auto message=L"Replace the staged version of "+entry.path+L" with the current working version?";
const auto answer=showFilesNotice(GetParent(view.host),message.c_str(),L"Replace staged changes",
{.confirm=true,.tone=FilesNoticeTone::warning});
view.promptingWrite=false;
updateGitActionButtons(view);
if(answer!=IDYES) return;
}
runGitMutation(view,stage?L"Staging the selected path…":L"Unstaging the selected path…",
[worktree=gitWorktreeTarget(view),entry,replace,stage](std::stop_token stop) {
ks::files::changeGitIndex(worktree,entry,replace,stop);
return stage?std::wstring(L"Path staged"):std::wstring(L"Path unstaged");
});
}
void openGitCommitReview(GitChangesView &view)
{
if(!gitActionAvailable(view)) return;
view.stopMutation=std::stop_source{};
view.operation=L"Reading all staged changes…";
try
{
std::packaged_task<GitCommitReview()> task([worktree=gitWorktreeTarget(view),stop=view.stopMutation.get_token()] {
return ks::files::reviewGitCommit(worktree,stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.commitReview=std::move(pending);
updateGitActionButtons(view);
updateGitChangesStatus(view);
}
catch(const std::exception &error) {showGitWriteError(view,error);}
}
void finishGitCommitReview(GitChangesView &view)
{
try
{
auto review=view.commitReview.get();
GitCommitPrompt prompt{review,view.commitDraft};
view.promptingWrite=true;
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(126),
GetParent(view.host),gitCommitDialog,reinterpret_cast<LPARAM>(&prompt));
view.promptingWrite=false;
view.commitDraft=std::move(prompt.message);
if(answer==IDOK)
runGitMutation(view,L"Creating the reviewed local commit…",
[worktree=gitWorktreeTarget(view),review=std::move(review),message=view.commitDraft](std::stop_token stop) {
return L"Commit "+ks::files::createGitCommit(worktree,review,message,stop).substr(0,12);
});
else
{
updateGitActionButtons(view);
updateGitChangesStatus(view);
}
}
catch(const std::exception &error)
{
view.promptingWrite=false;
showGitWriteError(view,error);
}
}
void finishGitMutation(GitChangesView &view)
{
try
{
view.writeStatus=view.mutation.get();
if(view.writeStatus.starts_with(L"Commit ")) view.commitDraft.clear();
refreshGitChanges(view);
}
catch(const std::exception &error) {showGitWriteError(view,error);}
}
void updateGitHistoryStatus(GitChangesView &view)
{
const auto status=view.historyTask.valid()?std::wstring(L"Reading Git history…"):
!view.historyFailure.empty()?L"Could not read Git history.":
view.commits.empty()?L"No commits yet.":std::to_wstring(view.commits.size())+L" commits";
SetWindowTextW(view.status,status.c_str());
EnableWindow(view.moreButton,view.moreHistory && !view.historyTask.valid());
}
void renderGitHistory(GitChangesView &view,std::wstring_view preserve={},LRESULT top=0)
{
SendMessageW(view.list,WM_SETREDRAW,FALSE,0);
SendMessageW(view.list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(size_t i=0;i<view.commits.size();++i)
{
const auto &commit=view.commits[i];
const auto label=commit.date+L" "+commit.abbreviated+L" "+commit.subject;
const auto row=SendMessageW(view.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row<0) continue;
SendMessageW(view.list,LB_SETITEMDATA,row,i);
if(preserve==commit.revision) selected=row;
}
if(!view.commits.empty())
{
SendMessageW(view.list,LB_SETCURSEL,selected,0);
if(top>0) SendMessageW(view.list,LB_SETTOPINDEX,top,0);
}
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(view.list,nullptr,TRUE);
InvalidateRect(view.host,nullptr,FALSE);
updateGitHistoryStatus(view);
queueGitPreview(view);
}
void loadGitHistory(GitChangesView &view,bool refreshBranches,bool append=false)
{
if(append && (view.historyTask.valid() || !view.moreHistory)) return;
view.stopHistory.request_stop();
view.historyTask={};
view.stopHistory=std::stop_source{};
view.historyFailure.clear();
const auto offset=append?view.commits.size():0;
const auto haveBranch=view.branchIndex<view.branches.size();
const auto branch=haveBranch?view.branches[view.branchIndex]:GitBranch{};
if(!append)
{
view.commits.clear();
view.moreHistory=false;
}
try
{
std::packaged_task<GitHistoryUpdate()> task([git=view.data.executable,root=view.data.root,
refreshBranches,offset,branch,index=view.branchIndex,stop=view.stopHistory.get_token()]
{
GitHistoryUpdate result;
result.branch=index;
auto revision=branch.revision;
if(refreshBranches)
{
result.branches=ks::files::readGitBranches(git,root,stop);
const auto &branches=*result.branches;
if(branches.empty()) return result;
auto chosen=std::find_if(branches.begin(),branches.end(),[&](const auto &entry){return entry.ref==branch.ref;});
if(chosen==branches.end())
chosen=std::find_if(branches.begin(),branches.end(),[](const auto &entry){return entry.current;});
if(chosen==branches.end()) chosen=branches.begin();
result.branch=static_cast<size_t>(chosen-branches.begin());
revision=chosen->revision;
}
if(!revision.empty()) result.page=ks::files::readGitHistory(git,root,revision,offset,stop);
return result;
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.historyTask=std::move(pending);
}
catch(const std::exception &error) {view.historyFailure=error.what();}
if(!append) renderGitHistory(view);
else updateGitHistoryStatus(view);
}
void finishGitHistory(GitChangesView &view)
{
const auto *entry=selectedGitCommit(view);
const auto selected=entry?entry->revision:std::wstring{};
const auto top=SendMessageW(view.list,LB_GETTOPINDEX,0,0);
try
{
auto result=view.historyTask.get();
view.branchIndex=result.branch;
if(result.branches)
{
view.branches=std::move(*result.branches);
SendMessageW(view.branchPicker,CB_RESETCONTENT,0,0);
for(const auto &branch:view.branches)
SendMessageW(view.branchPicker,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(branch.label.c_str()));
if(!view.branches.empty()) SendMessageW(view.branchPicker,CB_SETCURSEL,view.branchIndex,0);
EnableWindow(view.branchPicker,!view.branches.empty());
}
view.commits.insert(view.commits.end(),std::make_move_iterator(result.page.commits.begin()),
std::make_move_iterator(result.page.commits.end()));
view.moreHistory=result.page.more;
}
catch(const std::exception &error) {view.historyFailure=error.what();}
renderGitHistory(view,selected,top);
}
void pollGitChanges(GitChangesView &view)
{
using namespace std::chrono_literals;
if(view.commitReview.valid() && view.commitReview.wait_for(0ms)==std::future_status::ready)
finishGitCommitReview(view);
if(view.mutation.valid() && view.mutation.wait_for(0ms)==std::future_status::ready)
finishGitMutation(view);
if(view.refresh.valid() && view.refresh.wait_for(0ms)==std::future_status::ready)
{
const auto *entry=selectedGitChange(view);
const auto selected=entry?std::optional(*entry):std::nullopt;
try
{
view.data=view.refresh.get();
SetWindowTextW(view.heading,(L"Git Changes · "+view.data.root.native()).c_str());
renderGitChanges(view,selected);
}
catch(const std::exception &error)
{
view.data={};
view.failure=error.what();
renderGitChanges(view);
}
}
if(view.historyTask.valid() && view.historyTask.wait_for(0ms)==std::future_status::ready)
finishGitHistory(view);
if(view.previewAt && GetTickCount64()>=view.previewAt)
{
view.previewAt=0;
view.stopPreview=std::stop_source{};
try
{
std::packaged_task<std::string()> task([git=view.data.executable,root=view.data.root,
item=view.requested->item,stop=view.stopPreview.get_token()] {
if(const auto *change=std::get_if<GitChange>(&item))
return ks::files::readGitPatch(git,root,*change,stop);
return ks::files::readGitCommit(git,root,std::get<std::wstring>(item),stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.previewTask=std::move(pending);
}
catch(const std::exception &)
{
ks::files::previewQuickViewText(view.preview,view.requested->heading,"Could not start the Git preview.");
}
}
if(view.previewTask.valid() && view.previewTask.wait_for(0ms)==std::future_status::ready)
{
try
{
const auto contents=view.previewTask.get();
ks::files::previewQuickViewText(view.preview,view.requested->heading,
contents.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(contents),
std::holds_alternative<GitChange>(view.requested->item));
}
catch(const std::exception &error)
{
ks::files::previewQuickViewText(view.preview,view.requested->heading,error.what());
}
}
}
void openGitWorkingFile(GitChangesView &view,bool edit)
{
const auto *entry=selectedGitChange(view);
if(view.historyMode || !entry || view.refresh.valid() || !view.failure.empty() || gitActionPending(view)) return;
auto relative=fs::path(entry->path);
for(const auto &component:relative)
if(!validFileName(component.native()))
{
SetWindowTextW(view.status,L"This path cannot be opened as a Windows file.");
return;
}
auto path=view.data.root/relative.make_preferred();
const auto attributes=GetFileAttributesW(path.c_str());
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY))
{
SetWindowTextW(view.status,L"No current working file for this change.");
return;
}
const auto owner=GetParent(view.host);
if(!edit && ks::files::isImagePath(path)) ks::files::openImageWindow(owner,{path},path,textWindowDialogs());
else ks::files::openTextWindow(owner,path,edit,textWindowDialogs());
}
void layoutGitChildren(GitChangesView &view)
{
RECT bounds{};
GetClientRect(view.host,&bounds);
const int middle=panelDivider(bounds.right);
const auto place=[](HWND control,int x,int y,int width,int height)
{
SetWindowPos(control,nullptr,x,y,std::max(0,width),std::max(0,height),SWP_NOZORDER|SWP_NOACTIVATE);
};
const int inset=6,top=4,filterLabel=8*cellWidth,buttonWidth=12*cellWidth;
const int filterTop=top+textHeight+6, listTop=filterTop+textHeight+6;
const int bottom=std::max(listTop,static_cast<int>(bounds.bottom)-textHeight-5);
const int leftWidth=std::max(0,middle-2*inset);
place(view.heading,inset,top,leftWidth-buttonWidth-4,textHeight);
place(view.switchView,inset+leftWidth-buttonWidth,top,buttonWidth,textHeight);
place(view.filterLabel,inset,filterTop,filterLabel,textHeight);
place(view.filter,inset+filterLabel,filterTop,leftWidth-filterLabel,textHeight);
place(view.branchPicker,inset+filterLabel,filterTop,leftWidth-filterLabel,11*textHeight);
place(view.list,inset,listTop,leftWidth-scrollBarWidth(view.list),bottom-listTop);
place(view.status,inset,bottom+3,leftWidth-(view.historyMode?1:2)*(buttonWidth+4),textHeight);
place(view.moreButton,inset+leftWidth-buttonWidth,bottom+3,buttonWidth,textHeight);
place(view.indexButton,inset+leftWidth-2*buttonWidth-4,bottom+3,buttonWidth,textHeight);
place(view.commitButton,inset+leftWidth-buttonWidth,bottom+3,buttonWidth,textHeight);
place(view.preview,middle+inset,top,bounds.right-middle-2*inset,bottom-top);
place(view.hints,middle+inset,bottom+3,bounds.right-middle-2*inset,textHeight);
for(const auto control:{view.heading,view.switchView,view.filterLabel,view.filter,view.branchPicker,
view.list,view.status,view.hints,view.moreButton,view.indexButton,view.commitButton})
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendMessageW(view.list,LB_SETITEMHEIGHT,0,textHeight);
}
void switchGitView(GitChangesView &view)
{
if(view.data.root.empty() || view.refresh.valid() || gitActionPending(view)) return;
view.historyMode=!view.historyMode;
const auto title=view.historyMode?L"Git History · ":L"Git Changes · ";
SetWindowTextW(view.heading,(title+view.data.root.native()).c_str());
SetWindowTextW(view.switchView,view.historyMode?L"Changes":L"History");
SetWindowTextW(view.filterLabel,view.historyMode?L"Branch":L"Filter");
SetWindowTextW(view.hints,view.historyMode?L"F6 Changes F7 More Ctrl+R Refresh Esc Back":
L"F3 View F4 Edit F6 History Ctrl+R Refresh Esc Back");
ShowWindow(view.filter,view.historyMode?SW_HIDE:SW_SHOWNA);
ShowWindow(view.branchPicker,view.historyMode?SW_SHOWNA:SW_HIDE);
ShowWindow(view.moreButton,view.historyMode?SW_SHOWNA:SW_HIDE);
ShowWindow(view.indexButton,view.historyMode?SW_HIDE:SW_SHOWNA);
ShowWindow(view.commitButton,view.historyMode?SW_HIDE:SW_SHOWNA);
layoutGitChildren(view);
if(view.historyMode)
{
EnableWindow(view.branchPicker,FALSE);
loadGitHistory(view,true);
}
else
{
view.stopHistory.request_stop();
view.historyTask={};
renderGitChanges(view);
}
SetFocus(view.list);
}
LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_NCCREATE)
{
const auto *create=reinterpret_cast<const CREATESTRUCTW *>(lp);
SetWindowLongPtrW(window,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(create->lpCreateParams));
}
const auto view=reinterpret_cast<GitChangesView *>(GetWindowLongPtrW(window,GWLP_USERDATA));
if(!view) return DefWindowProcW(window,message,wp,lp);
switch(message)
{
case WM_CREATE:
{
view->host=window;
const auto make=[&](const wchar_t *type,const wchar_t *text,DWORD style,int id=0)
{
return CreateWindowW(type,text,WS_CHILD|WS_VISIBLE|style,0,0,0,0,window,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
};
view->heading=make(L"STATIC",L"Git Changes",SS_PATHELLIPSIS|SS_NOPREFIX,gitHeading);
view->switchView=make(L"BUTTON",L"History",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitSwitch);
view->filterLabel=make(L"STATIC",L"Filter",SS_NOPREFIX);
view->filter=make(farEditClass,L"",ES_MULTILINE|ES_AUTOHSCROLL|WS_TABSTOP,gitFilter);
view->branchPicker=make(L"COMBOBOX",L"",CBS_DROPDOWNLIST|CBS_OWNERDRAWFIXED|CBS_HASSTRINGS|WS_TABSTOP|WS_VSCROLL,
gitBranch);
view->list=make(L"LISTBOX",L"",LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT|LBS_NOTIFY|WS_TABSTOP,gitList);
view->status=make(L"STATIC",L"",SS_ENDELLIPSIS|SS_NOPREFIX,gitStatus);
view->hints=make(L"STATIC",L"F3 View F4 Edit F6 History Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX);
view->moreButton=make(L"BUTTON",L"More",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitMore);
view->indexButton=make(L"BUTTON",L"Stage",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitIndexAction);
view->commitButton=make(L"BUTTON",L"Commit",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitCommitAction);
try {view->preview=ks::files::createQuickView(window,textWindowDialogs());}
catch(const std::exception &) {}
if(!view->heading || !view->switchView || !view->filterLabel || !view->filter || !view->branchPicker ||
!view->list || !view->status || !view->hints || !view->moreButton || !view->indexButton ||
!view->commitButton || !view->preview ||
!SetTimer(window,gitChangesTimer,35,nullptr)) return -1;
prepareDialogEdit(view->filter);
SendMessageW(view->filter,EM_SETLIMITTEXT,1024,0);
ShowWindow(view->branchPicker,SW_HIDE);
ShowWindow(view->moreButton,SW_HIDE);
layoutGitChildren(*view);
installFarCombo(view->branchPicker,view->filter);
installScrollBar(view->list,window);
return 0;
}
case WM_SIZE:
if(view->preview) layoutGitChildren(*view);
return 0;
case WM_TIMER:
if(wp==gitChangesTimer) pollGitChanges(*view);
return 0;
case WM_COMMAND:
if(!view->historyMode && view->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE)
{
const auto *entry=selectedGitChange(*view);
renderGitChanges(*view,entry?std::optional(*entry):std::nullopt);
}
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitPreview(*view);
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_DBLCLK) openGitWorkingFile(*view,false);
else if(LOWORD(wp)==gitSwitch && HIWORD(wp)==BN_CLICKED) switchGitView(*view);
else if(view->historyMode && LOWORD(wp)==gitMore && HIWORD(wp)==BN_CLICKED) loadGitHistory(*view,false,true);
else if(LOWORD(wp)==gitIndexAction && HIWORD(wp)==BN_CLICKED) changeSelectedGitIndex(*view);
else if(LOWORD(wp)==gitCommitAction && HIWORD(wp)==BN_CLICKED) openGitCommitReview(*view);
else if(view->historyMode && LOWORD(wp)==gitBranch &&
(HIWORD(wp)==CBN_SELENDOK || (HIWORD(wp)==CBN_SELCHANGE &&
!SendMessageW(view->branchPicker,CB_GETDROPPEDSTATE,0,0))))
{
const auto index=SendMessageW(view->branchPicker,CB_GETCURSEL,0,0);
if(index>=0 && size_t(index)<view->branches.size() && size_t(index)!=view->branchIndex)
{
view->branchIndex=static_cast<size_t>(index);
loadGitHistory(*view,false);
}
}
return 0;
case WM_MEASUREITEM:
reinterpret_cast<MEASUREITEMSTRUCT *>(lp)->itemHeight=textHeight;
return TRUE;
case WM_DRAWITEM:
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
if(item.CtlID==gitBranch) {drawFarComboRow(item);return TRUE;}
if(item.CtlType==ODT_BUTTON) {paintDialogButton(item,colors[Dialog],colors[Text]);return TRUE;}
if(item.itemID==static_cast<UINT>(-1)) return TRUE;
const auto count=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
if(count<0) return TRUE;
std::wstring label(count+1,L'\0');
if(SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()))==LB_ERR)
return TRUE;
const bool selected=item.itemState&ODS_SELECTED;
paintText(item.hDC,item.rcItem,label.c_str(),colors[Text],colors[selected?PanelCursor:PanelBlue]);
return TRUE;
}
case WM_CTLCOLORSTATIC:
case WM_CTLCOLOREDIT:
case WM_CTLCOLORLISTBOX:
{
const auto dc=reinterpret_cast<HDC>(wp);
const bool input=message==WM_CTLCOLOREDIT ||
(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=view->list);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[input?Dialog:PanelBlue]);
return reinterpret_cast<LRESULT>(input?teal:blue);
}
case WM_PAINT:
{
PAINTSTRUCT paint{};
const auto dc=BeginPaint(window,&paint);
FillRect(dc,&paint.rcPaint,blue);
if(view->list) paintScrollPosition(window,dc,view->list,colors[PanelBlue]);
EndPaint(window,&paint);
return 0;
}
}
return DefWindowProcW(window,message,wp,lp);
}
void layoutGitChanges(HWND window)
{
if(!gitChangesView) return;
RECT bounds{};
GetClientRect(window,&bounds);
SetWindowPos(gitChangesView->host,HWND_TOP,0,0,bounds.right,bounds.bottom,SWP_NOACTIVATE|SWP_SHOWWINDOW);
layoutGitChildren(*gitChangesView);
}
bool showingGitChanges()
{
return static_cast<bool>(gitChangesView);
}
void closeGitChanges(HWND owner,bool restore=true)
{
if(restore && gitChangesView && gitActionPending(*gitChangesView)) return;
auto view=std::move(gitChangesView);
if(!view) return;
view->stopRefresh.request_stop();
view->stopPreview.request_stop();
view->stopHistory.request_stop();
view->stopMutation.request_stop();
if(IsWindow(view->host)) DestroyWindow(view->host);
if(restore)
{
layout(owner);
restoreCommandFocus();
showFileDetails(panels[active]);
}
}
bool gitChangesAvailable(const Panel &panel)
{
return !terminalVisible && !panel.directory.empty() && !panel.ftp && !panel.peer && !panel.archive &&
!windowsNetworkPath(panel.directory);
}
void openGitChanges(HWND owner,const Panel &panel)
{
if(gitChangesView || !gitChangesAvailable(panel)) return;
const auto instance=GetModuleHandleW(nullptr);
static const bool registered=[instance]
{
WNDCLASSW type{};
type.lpfnWndProc=gitChangesProcedure;
type.hInstance=instance;
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
type.lpszClassName=gitChangesClass;
return RegisterClassW(&type)!=0;
}();
if(!registered) return;
auto view=std::make_unique<GitChangesView>();
view->folder=panel.directory;
if(!CreateWindowW(gitChangesClass,L"Git Changes",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
0,0,0,0,owner,nullptr,instance,view.get()))
{
setStatus(L"Could not open Git Changes.");
return;
}
gitChangesView=std::move(view);
closePanelSearch();
hideCompletion();
layout(owner);
ShowWindow(gitChangesView->preview,SW_SHOWNA);
SetFocus(gitChangesView->list);
refreshGitChanges(*gitChangesView);
}
bool handleGitChangesKey(HWND owner,const MSG &message)
{
auto &view=*gitChangesView;
if(message.message!=WM_KEYDOWN || FilesModalDialog::activeFor(owner) ||
(message.hwnd!=owner && message.hwnd!=view.host && !IsChild(view.host,message.hwnd))) return false;
const auto key=message.wParam;
const bool control=GetKeyState(VK_CONTROL)&0x8000;
const bool alt=GetKeyState(VK_MENU)&0x8000;
if(alt) return false;
const auto selector=view.historyMode?view.branchPicker:view.filter;
if(view.historyMode && SendMessageW(view.branchPicker,CB_GETDROPPEDSTATE,0,0)) return false;
if(!control && key==VK_ESCAPE) closeGitChanges(owner);
else if(control && key=='R')
{
if(view.historyMode) loadGitHistory(view,true);
else refreshGitChanges(view);
}
else if(control && key=='F') SetFocus(selector);
else if(!control && key==VK_TAB)
{
std::vector<HWND> focusOrder;
for(const auto controlWindow:{view.list,selector,view.indexButton,view.commitButton,view.switchView,view.moreButton})
if(IsWindowVisible(controlWindow) && IsWindowEnabled(controlWindow)) focusOrder.push_back(controlWindow);
const auto current=std::find(focusOrder.begin(),focusOrder.end(),GetFocus());
if(!focusOrder.empty())
{
const bool reverse=GetKeyState(VK_SHIFT)&0x8000;
const auto index=current==focusOrder.end()?0:static_cast<size_t>(current-focusOrder.begin());
const auto next=reverse?focusOrder.size()-1:1;
SetFocus(focusOrder[(index+next)%focusOrder.size()]);
}
}
else if(!control && key==VK_F6) switchGitView(view);
else if(!control && view.historyMode && key==VK_F7) loadGitHistory(view,false,true);
else if(!control && key==VK_RETURN &&
(GetFocus()==view.indexButton || GetFocus()==view.commitButton || GetFocus()==view.switchView || GetFocus()==view.moreButton))
SendMessageW(GetFocus(),BM_CLICK,0,0);
else if(!control && !view.historyMode && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list)))
openGitWorkingFile(view,key==VK_F4);
else if(!control && GetFocus()==view.filter &&
(key==VK_UP || key==VK_DOWN || key==VK_PRIOR || key==VK_NEXT))
SendMessageW(view.list,WM_KEYDOWN,key,message.lParam);
else return false;
return true;
}
+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));
}
+1149 -311
View File
File diff suppressed because it is too large. Load diff
+19 -2
View File
@@ -11,7 +11,8 @@ constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Pop
L"Menu selection",L"Command bar",L"File cursor"};
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
constexpr const wchar_t *panelSectionNames[]{L"Panel layout",L"Wide panel columns",L"Status line columns"};
constexpr int panelLayoutControls[]{506,273,507,274};
constexpr int rightClickMarksControl=520, driveButtonsControl=521, compactLayoutControl=522;
constexpr int panelLayoutControls[]{506,273,507,274,rightClickMarksControl,driveButtonsControl,compactLayoutControl,523};
constexpr int wideColumnControls[]{275,276,201,202,204};
constexpr int statusColumnControls[]{277,203,205,206,207,208};
constexpr int colorOptionControls[]{279,280};
@@ -67,6 +68,9 @@ struct PanelProperty
};
constexpr PanelProperty panelProperties[]{
{PanelLayout,273,L"Left panel mode",defaultWide?1u:0u},{PanelLayout,274,L"Right panel mode",defaultWide?1u:0u},
{PanelLayout,rightClickMarksControl,L"Mark items with the right mouse button",0},
{PanelLayout,driveButtonsControl,L"Show drive buttons",0},
{PanelLayout,compactLayoutControl,L"Compact commander layout",0},
{WideColumns,201,L"Size column width",defaultSizeWidth},
{WideColumns,202,L"Align file extensions",defaultAlignExtensions},
{WideColumns,204,L"Align folder extensions",defaultAlignFolders},
@@ -107,6 +111,7 @@ struct OptionsBaseline
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
bool mouseMarks=rightClickMarks, drives=showDriveButtons, compact=compactLayout;
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
ks::files::TextSettings text=ks::files::loadTextPreferences();
ComparisonAppearance comparison=readComparisonAppearance();
@@ -181,6 +186,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
const bool dirty=!valid || draft.markdownError || width!=base.width ||
panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] ||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives ||
checked(compactLayoutControl)!=base.compact ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
@@ -679,6 +686,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
showPanelModeOptions(dialog);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
@@ -898,7 +908,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
case 201:
case 202: case 203: case 204: case 205: case 206: case 207: case 208:
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
case 273: case 274: case rightClickMarksControl: case driveButtonsControl: case compactLayoutControl:
case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
updateOptionsApply(dialog,*draft);
return TRUE;
case 321: case 323: case comparisonShortcutControl:
@@ -1050,6 +1061,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
saveChanged(L"AlignExtensions",checked(202),base.extensions);
saveChanged(L"AlignFolders",checked(204),base.folders);
saveChanged(L"ShowDetails",checked(203),base.details);
saveChanged(rightClickMarksKey,checked(rightClickMarksControl),base.mouseMarks);
saveChanged(driveButtonsKey,checked(driveButtonsControl),base.drives);
saveChanged(compactLayoutKey,checked(compactLayoutControl),base.compact);
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
const auto initialFields=fields;
for(int i=0;i<4;++i)
@@ -1092,6 +1106,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
showPanelModeOptions(dialog);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
+166
View File
@@ -0,0 +1,166 @@
constexpr std::array<ULONGLONG,3> lanRetryDelays{1200,2500,5000};
constexpr const wchar_t *ftpPanelLocationKeys[]{L"LeftFtpLocation",L"RightFtpLocation"};
constexpr DWORD maxFtpLocationBytes=256*1024;
FilesPeerLookup lookupFilesPeers(HWND owner);
bool transientLanError(DWORD code)
{
switch(code)
{
case WSAENETDOWN:
case WSAENETUNREACH:
case WSAENETRESET:
case WSAECONNABORTED:
case WSAECONNRESET:
case WSAECONNREFUSED:
case WSAETIMEDOUT:
case WSAEHOSTDOWN:
case WSAEHOSTUNREACH:
case ERROR_CONNECTION_ABORTED:
case ERROR_NETNAME_DELETED:
case ERROR_NETWORK_UNREACHABLE:
case ERROR_SEM_TIMEOUT:
return true;
default:
return false;
}
}
bool retryRemotePanel(Panel &panel,bool automatic,const fs::path &fallback)
{
if(!panel.remoteRetry) return false;
auto &retry=*panel.remoteRetry;
auto location=retry.location;
const auto attempt=automatic?retry.reconnectAttempt+1:0;
if(location.peer)
{
const auto lookup=lookupFilesPeers(GetParent(panel.list));
const auto peer=std::find_if(lookup.peers.begin(),lookup.peers.end(),[&](const auto &entry) {
return entry.id==location.peer->id && !entry.address.empty();
});
if(peer!=lookup.peers.end()) location.peer=*peer;
openOn(panel,location.directory,false,std::move(location.peer),location.cursor,
{},{},location.navigationPosition,{},attempt);
return true;
}
const bool loaded=loadTransferProfiles(location.protocol);
const auto *profile=loaded?findTransferProfile(location.ftpProfile,location.protocol):nullptr;
if(!profile)
{
retry.failure=std::wstring(loaded?L"The saved connection is missing. Select a profile in Change drive → ":
L"Could not load the saved connections for ")+transferProtocolName(location.protocol)+L".";
if(&panel==&panels[active] && !panel.scan.valid()) showFileDetails(panel);
return true;
}
openOn(panel,location.directory,false,{},location.cursor,fallback,*profile,location.navigationPosition,{},0,
fallback.empty()?fs::path{}:savedPanelPath(panelCursorKeys[&panel-panels]));
return true;
}
void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional<size_t> position={})
{
if(location.directory.empty()) return;
if(location.provider==FolderProvider::local)
{
openOn(panel,location.directory,true,{},{},{},{},position);
return;
}
if(location.sameSource(folderLocation(panel,panel.directory)))
{
openOn(panel,location.directory,false,panel.peer,{},{},panel.ftp,position);
return;
}
RemotePanelLocation remote{location.directory,{},{},{},position};
if(isTransferFolder(location.provider))
{
remote.ftpProfile=location.id;
remote.protocol=folderTransferProtocol(location.provider);
}
else remote.peer=FilesPeer{location.id,{},location.label.empty()?L"LAN peer":location.label};
panel.remoteRetry=Panel::RemoteRetry{std::move(remote),L"Could not restore the remote folder."};
retryRemotePanel(panel);
}
void pollRemotePanels()
{
const auto now=GetTickCount64();
for(auto &panel:panels)
if(!panel.scan.valid() && panel.remoteRetry && panel.remoteRetry->retryAt &&
now>=panel.remoteRetry->retryAt)
retryRemotePanel(panel,true);
}
std::optional<RemotePanelLocation> savedFtpPanelLocation(int index)
{
DWORD size{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr,
nullptr,&size)!=ERROR_SUCCESS || !size || size>maxFtpLocationBytes) return {};
std::string data(size,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr,
data.data(),&size)!=ERROR_SUCCESS) return {};
try
{
const auto saved=Json::parse(data.begin(),data.begin()+size);
RemotePanelLocation location{fs::path(ks::wide(saved.at("directory"))),fs::path(ks::wide(saved.at("cursor"))),
saved.at("profile").get<std::string>()};
if(!isFtpFolderPath(location.directory) || location.ftpProfile.empty()) return {};
if(!location.cursor.empty() && !isFtpFolderPath(location.cursor)) location.cursor.clear();
return location;
}
catch(const std::exception &) {return {};}
}
void saveFtpPanelLocation(const Panel &panel,int index)
{
RemotePanelLocation location;
if(panel.ftp && panel.ftp->protocol==TransferProtocol::ftp && !panel.ftp->id.empty())
{
const auto row=currentPanelRow(panel);
location={panel.directory,row<0?fs::path{}:panel.rows[row],panel.ftp->id};
}
else if(panel.remoteRetry && panel.remoteRetry->location.protocol==TransferProtocol::ftp &&
!panel.remoteRetry->location.ftpProfile.empty())
location=panel.remoteRetry->location;
else if(panel.scanRequest && panel.scanRequest->ftp && panel.scanRequest->ftp->protocol==TransferProtocol::ftp)
location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id};
const auto key=ftpPanelLocationKeys[index];
if(location.ftpProfile.empty() || !isFtpFolderPath(location.directory))
{
RegDeleteKeyValueW(HKEY_CURRENT_USER,schemeKey,key);
return;
}
try
{
const auto data=Json{{"profile",location.ftpProfile},{"directory",ks::utf8(location.directory.native())},
{"cursor",ks::utf8(location.cursor.native())}}.dump();
if(data.size()<=maxFtpLocationBytes)
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(),static_cast<DWORD>(data.size()));
}
catch(const std::exception &) {}
}
fs::path systemPanelRoot()
{
wchar_t system[MAX_PATH]{};
GetWindowsDirectoryW(system,MAX_PATH);
return fs::path(system).root_path();
}
void restorePanelLocation(Panel &panel,int index)
{
const auto root=systemPanelRoot();
const auto saved=savedPanelPath(panelPathKeys[index]);
const auto local=saved.is_absolute()?saved:root;
auto remote=savedFtpPanelLocation(index);
if(remote)
{
panel.remoteRetry=Panel::RemoteRetry{std::move(*remote),L"Could not restore the saved FTP folder."};
retryRemotePanel(panel,false,local);
if(panel.scan.valid()) return;
}
auto retry=std::move(panel.remoteRetry);
openOn(panel,local,false,{},savedPanelPath(panelCursorKeys[index]),local!=root?root:fs::path{});
panel.remoteRetry=std::move(retry);
}
+2 -2
View File
@@ -2,7 +2,7 @@ class PanelRowsUpdate
{
public:
PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)),
profiles(ftpProfileList(panel))
profiles(transferProfileList(panel))
{
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
panel.rows.clear();
@@ -120,7 +120,7 @@ void visitPanelMarks(const Panel &panel,const Visitor &visit)
}
return;
}
if(ftpProfileList(panel)) return;
if(transferProfileList(panel)) return;
for(size_t i=0;i<panel.rows.size();++i)
{
if(!panel.marked[i] || panel.sizes[i]==L"Up") continue;
+155 -74
View File
@@ -1,22 +1,28 @@
bool localNavigationAvailable(const Panel &panel)
bool pathNavigationAvailable(const Panel &panel)
{
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.archive && !panel.directory.empty();
return !transferProfileList(panel) && !panel.findOrigin && !panel.archive && !panel.directory.empty();
}
enum class PathAction { back, forward, up, edit, ancestors, previous, folder };
enum class PathAction { back, forward, up, edit, source, ancestors, previous, folder };
void navigateLocal(Panel &panel,const fs::path &path,std::optional<size_t> position={})
void navigatePanelPath(Panel &panel,const fs::path &path)
{
if(path.empty() || sameLocalFolder(path,panel.directory)) return;
if(path.empty()) return;
const auto current=folderLocation(panel,panel.directory);
auto target=folderLocation(panel,path);
if(sameFolderLocation(current,target)) return;
closePanelSearch();
openOn(panel,path,true,{},{},{},{},position);
openFolderLocation(panel,target);
}
void navigateLocalHistory(Panel &panel,int direction)
void navigatePanelHistory(Panel &panel,int direction)
{
if(const auto next=panel.navigation.neighbor(direction))
navigateLocal(panel,panel.navigation.history[*next],next);
{
closePanelSearch();
openFolderLocation(panel,panel.navigation.history[*next],next);
}
}
struct PathPart
@@ -29,17 +35,18 @@ struct PathPart
bool current{}, dim{}, enabled=true;
};
std::wstring pathSegmentLabel(const fs::path &path)
std::wstring pathSegmentLabel(const fs::path &path,FolderProvider provider)
{
return panelParentPath(path,true).empty()?path.native():path.filename().native();
if(isTransferFolder(provider) && path==ftpRoot) return L"/";
return panelParentPath(path,provider==FolderProvider::local).empty()?path.native():path.filename().native();
}
LONG segmentWidth(const fs::path &path)
LONG segmentWidth(const fs::path &path,FolderProvider provider)
{
return static_cast<LONG>(pathSegmentLabel(path).size()+2)*cellWidth;
return static_cast<LONG>(pathSegmentLabel(path,provider).size()+2)*cellWidth;
}
std::vector<PathPart> localPathParts(const Panel &panel,RECT bounds)
std::vector<PathPart> panelPathParts(const Panel &panel,RECT bounds)
{
const LONG total=bounds.right-bounds.left;
if(total<=0) return {};
@@ -52,64 +59,74 @@ std::vector<PathPart> localPathParts(const Panel &panel,RECT bounds)
bounds.left=part.rect.right;
parts.push_back(std::move(part));
};
const auto parent=panelParentPath(panel.directory,true);
const auto location=folderLocation(panel,panel.directory);
const auto provider=location.provider;
const auto local=provider==FolderProvider::local;
const auto parent=panelParentPath(panel.directory,local);
add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width);
add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width);
add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width);
add({.action=PathAction::edit,.label=L"✎"},width);
std::vector<fs::path> ancestors, previous;
for(auto path=parent;!path.empty();path=panelParentPath(path,true)) ancestors.push_back(path);
std::reverse(ancestors.begin(),ancestors.end());
if(inLocalBranch(panel.directory,panel.navigation.previousBranch))
if(!local)
{
for(auto path=panel.navigation.previousBranch;!sameLocalFolder(path,panel.directory);
path=panelParentPath(path,true))
const auto available=std::max(1L,(bounds.right-bounds.left)/2);
const auto sourceWidth=std::min(available,static_cast<LONG>(location.label.size()+2)*cellWidth);
add({.action=PathAction::source,.label=location.label},sourceWidth);
}
std::vector<fs::path> ancestors, previous;
for(auto path=parent;!path.empty();path=panelParentPath(path,local)) ancestors.push_back(path);
std::reverse(ancestors.begin(),ancestors.end());
if(inFolderBranch(panel.directory,panel.navigation.previousBranch,provider))
{
for(auto path=panel.navigation.previousBranch;!sameFolderPath(path,panel.directory,provider);
path=panelParentPath(path,local))
previous.push_back(path);
std::reverse(previous.begin(),previous.end());
}
const LONG room=bounds.right-bounds.left;
LONG required=segmentWidth(panel.directory);
for(const auto &path:ancestors) required+=segmentWidth(path);
for(const auto &path:previous) required+=segmentWidth(path);
LONG required=segmentWidth(panel.directory,provider);
for(const auto &path:ancestors) required+=segmentWidth(path,provider);
for(const auto &path:previous) required+=segmentWidth(path,provider);
size_t firstAncestor=0,visiblePrevious=previous.size();
LONG currentWidth=segmentWidth(panel.directory);
LONG currentWidth=segmentWidth(panel.directory,provider);
if(required>room)
{
const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0);
currentWidth=std::min(currentWidth,std::max(1L,room-reserved));
LONG remaining=room-currentWidth-reserved;
firstAncestor=ancestors.size();
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1]))
remaining-=segmentWidth(ancestors[--firstAncestor]);
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1],provider))
remaining-=segmentWidth(ancestors[--firstAncestor],provider);
visiblePrevious=0;
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious]))
remaining-=segmentWidth(previous[visiblePrevious++]);
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious],provider))
remaining-=segmentWidth(previous[visiblePrevious++],provider);
}
if(firstAncestor)
add({.action=PathAction::ancestors,.label=L"…",
.hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width);
for(size_t i=firstAncestor;i<ancestors.size();++i)
add({.action=PathAction::folder,.label=pathSegmentLabel(ancestors[i]),.target=ancestors[i]},
segmentWidth(ancestors[i]));
add({.action=PathAction::edit,.label=pathSegmentLabel(panel.directory),.current=true},currentWidth);
add({.action=PathAction::folder,.label=pathSegmentLabel(ancestors[i],provider),.target=ancestors[i]},
segmentWidth(ancestors[i],provider));
add({.action=PathAction::edit,.label=pathSegmentLabel(panel.directory,provider),.current=true},currentWidth);
for(size_t i=0;i<visiblePrevious;++i)
add({.action=PathAction::folder,.label=pathSegmentLabel(previous[i]),.target=previous[i],.dim=true},
segmentWidth(previous[i]));
add({.action=PathAction::folder,.label=pathSegmentLabel(previous[i],provider),.target=previous[i],.dim=true},
segmentWidth(previous[i],provider));
if(visiblePrevious<previous.size())
add({.action=PathAction::previous,.label=L"…",
.hidden={previous.begin()+visiblePrevious,previous.end()},.dim=true},width);
return parts;
}
void paintLocalPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel)
void paintPanelPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel)
{
const int saved=SaveDC(dc);
SelectObject(dc,mono);
SetBkMode(dc,TRANSPARENT);
for(const auto &part:localPathParts(panel,bounds))
for(const auto &part:panelPathParts(panel,bounds))
{
const bool current=activePanel && part.current;
FillRect(dc,&part.rect,current?teal:blue);
@@ -126,6 +143,8 @@ constexpr int addressField=485,addressLabel=486,addressFooter=487;
struct PathPrompt
{
fs::path base, result;
std::optional<FilesPeer> peer;
std::optional<TransferProfile> ftp;
std::wstring completionInput;
std::future<std::wstring> completion;
};
@@ -133,30 +152,62 @@ struct PathPrompt
constexpr UINT addressComplete=WM_APP+29;
constexpr UINT_PTR addressCompletionTimer=1;
fs::path enteredPanelPath(const fs::path &base,std::wstring text)
fs::path enteredPanelPath(const fs::path &base,std::wstring text,bool ftp)
{
if(text.size()>=2 && text.front()==L'"' && text.back()==L'"')
text=text.substr(1,text.size()-2);
return fs::path(text).is_absolute()?fs::path(std::move(text)):base/fs::path(std::move(text));
if(ftp && text.find_first_of(L":\r\n")!=text.npos) return {};
auto path=fs::path(std::move(text));
if(ftp)
{
if(path.has_root_name()) return {};
return (path.has_root_directory()?path:base/path).lexically_normal();
}
return path.is_absolute()?path:base/path;
}
std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text)
std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text,
const std::optional<FilesPeer> &peer,const std::optional<TransferProfile> &ftp)
{
const auto path=enteredPanelPath(base,text);
const auto path=enteredPanelPath(base,text,ftp.has_value());
if(path.empty()) return {};
const auto directory=path.has_filename()?path.parent_path():path;
const auto prefix=path.filename().native();
fs::path best;
std::error_code error;
for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error))
const auto accept=[&](const fs::path &candidate)
{
const auto name=it->path().filename().native();
const auto name=candidate.filename().native();
if(name.size()<prefix.size() || (!prefix.empty() && CompareStringOrdinal(name.data(),
static_cast<int>(prefix.size()),prefix.data(),static_cast<int>(prefix.size()),TRUE)!=CSTR_EQUAL))
continue;
std::error_code typeError;
if(it->is_directory(typeError) && (best.empty() || it->path()<best)) best=it->path();
static_cast<int>(prefix.size()),prefix.data(),static_cast<int>(prefix.size()),ftp?FALSE:TRUE)!=CSTR_EQUAL))
return;
if(best.empty() || candidate<best) best=candidate;
};
const auto visit=[&](const fs::path &candidate,const FileInfo &info)
{
if(info.attributes&FILE_ATTRIBUTE_DIRECTORY) accept(candidate);
return true;
};
if(peer)
{
FilesConnection host(&*peer);
listFiles(host,directory,visit);
}
return best.empty()?std::wstring{}:best.native()+L"\\";
else if(ftp)
{
TransferSession host(*ftp);
host.list(directory,visit);
}
else
{
std::error_code error;
for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error))
{
std::error_code typeError;
if(it->is_directory(typeError)) accept(it->path());
}
}
if(best.empty()) return {};
return ftp?ftpPath(best)+L"/":best.native()+L"\\";
}
LRESULT CALLBACK addressFieldKeys(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
@@ -194,7 +245,8 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
layoutDialogButtons(dialog,addressFooter,{IDOK,IDCANCEL});
const auto field=GetDlgItem(dialog,addressField);
SendMessageW(field,EM_SETLIMITTEXT,32767,0);
SetWindowTextW(field,(prompt.base/fs::path{}).c_str());
const auto initial=prompt.base/fs::path{};
SetWindowTextW(field,(prompt.ftp?ftpPath(initial):initial.native()).c_str());
SetWindowSubclass(field,addressFieldKeys,4,0);
SetFocus(field);
SendMessageW(field,EM_SETSEL,0,-1);
@@ -205,9 +257,10 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(prompt.completion.valid()) return TRUE;
prompt.completionInput=shortcutField(dialog,addressField);
std::packaged_task<std::wstring()> task([base=prompt.base,text=prompt.completionInput]
std::packaged_task<std::wstring()> task([base=prompt.base,text=prompt.completionInput,
peer=prompt.peer,ftp=prompt.ftp]
{
return panelPathCompletion(base,text);
return panelPathCompletion(base,text,peer,ftp);
});
if(!SetTimer(dialog,addressCompletionTimer,30,nullptr)) return TRUE;
prompt.completion=task.get_future();
@@ -237,8 +290,8 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField)).lexically_normal();
if(!path.is_absolute())
auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField),prompt.ftp.has_value()).lexically_normal();
if(prompt.ftp?!isFtpFolderPath(path):!path.is_absolute())
{
showFilesNotice(dialog,L"Enter a folder path.",L"Go to folder");
return TRUE;
@@ -258,25 +311,33 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
void editPanelPath(Panel &panel)
{
PathPrompt prompt{panel.directory};
PathPrompt prompt{panel.directory,{},panel.peer,panel.ftp};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(117),GetParent(panel.list),
editPathDialog,reinterpret_cast<LPARAM>(&prompt))==IDOK)
navigateLocal(panel,prompt.result);
navigatePanelPath(panel,prompt.result);
}
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs::path> paths,RECT anchor,bool recent=false)
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<FolderLocation> locations,
RECT anchor,bool recent=false)
{
hidePicker();
showMenu(false);
commandPicker=false;
pickerPanel=side;
folderPicker=FolderPicker{caption,std::move(paths),recent};
folderPicker=FolderPicker{caption,std::move(locations),recent};
SendMessageW(picker,LB_RESETCONTENT,0,0);
size_t longest=wcslen(caption);
for(const auto &path:folderPicker->paths)
for(const auto &location:folderPicker->locations)
{
longest=std::max(longest,path.native().size());
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(path.c_str()));
auto label=isTransferFolder(location.provider)?ftpPath(location.directory):location.directory.native();
if(recent && location.provider!=FolderProvider::local)
{
const auto &source=location.label;
const auto kind=isTransferFolder(location.provider)?transferProtocolName(folderTransferProtocol(location.provider)):L"LAN";
label=std::wstring(kind)+L" · "+(source.empty()?std::wstring{}:source+L" · ")+label;
}
longest=std::max(longest,label.size());
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
RECT client{};
GetClientRect(owner,&client);
@@ -289,7 +350,7 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs:
GetWindowRect(terminalInput,&input);
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&input),2);
const int bottom=std::min(client.bottom,input.top);
const int shown=std::clamp((bottom-y-inset)/row,1,static_cast<int>(folderPicker->paths.size()));
const int shown=std::clamp((bottom-y-inset)/row,1,static_cast<int>(folderPicker->locations.size()));
showFramedList(picker,pickerFrame,x,y,width,row*shown,inset);
SendMessageW(picker,LB_SETCURSEL,0,0);
SetFocus(picker);
@@ -297,17 +358,24 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<fs:
void showRecentFolders(int side)
{
auto paths=readRecentFolders();
if(paths.empty())
auto locations=readRecentFolders();
if(locations.empty())
{
setStatus(L"No recent local folders.");
setStatus(L"No recent folders.");
return;
}
const auto owner=GetParent(picker);
RECT anchor{};
GetWindowRect(panels[side].path,&anchor);
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&anchor),2);
showFolderPicker(owner,side,L"Recent folders",std::move(paths),anchor,true);
for(auto &location:locations)
{
if(!isTransferFolder(location.provider)) continue;
const auto protocol=folderTransferProtocol(location.provider);
if(loadTransferProfiles(protocol))
if(const auto *profile=findTransferProfile(location.id,protocol)) location.label=profile->name;
}
showFolderPicker(owner,side,L"Recent folders",std::move(locations),anchor,true);
}
void showHiddenPathParts(HWND window,int side,const PathPart &part)
@@ -315,8 +383,11 @@ void showHiddenPathParts(HWND window,int side,const PathPart &part)
const auto owner=GetParent(window);
auto anchor=part.rect;
MapWindowPoints(window,owner,reinterpret_cast<POINT*>(&anchor),2);
std::vector<FolderLocation> locations;
locations.reserve(part.hidden.size());
for(const auto &path:part.hidden) locations.push_back(folderLocation(panels[side],path));
showFolderPicker(owner,side,part.action==PathAction::ancestors?L"Parent folders":L"Previous path",
part.hidden,anchor);
std::move(locations),anchor);
}
LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
@@ -333,7 +404,7 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
if(index<0 || index>=2) return 0;
panelClipboardContext=true;
auto &panel=panels[index];
if(!localNavigationAvailable(panel))
if(!pathNavigationAvailable(panel))
{
selectPanelEdge(panel,true);
return 0;
@@ -342,16 +413,26 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
RECT bounds{};
GetClientRect(window,&bounds);
const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto parts=localPathParts(panel,bounds);
const auto parts=panelPathParts(panel,bounds);
for(const auto &part:parts)
{
if(!part.enabled || !PtInRect(&part.rect,mouse)) continue;
switch(part.action)
{
case PathAction::back: navigateLocalHistory(panel,-1); break;
case PathAction::forward: navigateLocalHistory(panel,1); break;
case PathAction::up: case PathAction::folder: navigateLocal(panel,part.target); break;
case PathAction::back: navigatePanelHistory(panel,-1); break;
case PathAction::forward: navigatePanelHistory(panel,1); break;
case PathAction::up: case PathAction::folder: navigatePanelPath(panel,part.target); break;
case PathAction::edit: editPanelPath(panel); break;
case PathAction::source:
if(panel.peer) chooseDrive(index,false,true);
else
{
const auto protocol=panel.ftp->protocol;
const auto *profile=findTransferProfile(panel.ftp->id,protocol);
showTransferProfiles(panel,protocol,profile?
ftpRoot/std::to_wstring(profile-transferProfiles(protocol).rows.data()):fs::path{});
}
break;
case PathAction::ancestors: case PathAction::previous: showHiddenPathParts(window,index,part); break;
}
break;
@@ -361,7 +442,7 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
return DefSubclassProc(window,message,wp,lp);
}
bool handleLocalPathKey(HWND owner,const MSG &message)
bool handlePanelPathKey(HWND owner,const MSG &message)
{
if(!commandLineAvailable(owner) || terminalVisible ||
(message.hwnd!=terminalInput && message.hwnd!=panels[active].list) ||
@@ -374,7 +455,7 @@ bool handleLocalPathKey(HWND owner,const MSG &message)
if(!(message.lParam&(1LL<<30))) parentArchive(panel);
return true;
}
if(!localNavigationAvailable(panel)) return false;
if(!pathNavigationAvailable(panel)) return false;
if(message.message==WM_KEYDOWN && message.wParam=='L' &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000))
{
@@ -384,9 +465,9 @@ bool handleLocalPathKey(HWND owner,const MSG &message)
if(message.message!=WM_SYSKEYDOWN || !(message.lParam&(1LL<<29)) ||
(GetKeyState(VK_CONTROL)&0x8000)) return false;
if(message.wParam==VK_UP)
navigateLocal(panel,panelParentPath(panel.directory,true));
navigatePanelPath(panel,panelParentPath(panel.directory,!panel.peer && !panel.ftp));
else if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT)
navigateLocalHistory(panel,message.wParam==VK_LEFT?-1:1);
navigatePanelHistory(panel,message.wParam==VK_LEFT?-1:1);
else return false;
return true;
}
+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()}));
}
+48 -11
View File
@@ -1,24 +1,54 @@
constexpr wchar_t recentFoldersKey[]=L"RecentFolders";
constexpr size_t recentFoldersLimit=100;
std::vector<fs::path> readRecentFolders()
std::optional<FolderLocation> readRecentFolder(const Json &entry)
{
FolderLocation location;
if(entry.is_string()) location.directory=filePath(entry);
else if(entry.is_object())
{
const auto source=entry.value("source",std::string{});
if(source=="ftp") location.provider=FolderProvider::ftp;
else if(source=="sftp") location.provider=FolderProvider::sftp;
else if(source=="lan") location.provider=FolderProvider::lan;
else return {};
location.id=entry.at("id").get<std::string>();
if(location.id.empty()) return {};
location.label=ks::wide(entry.value("label",std::string{}));
location.directory=filePath(entry.at("path"));
}
else return {};
const auto &path=location.directory;
if(path.native().find(L'\0')!=std::wstring::npos) return {};
if(isTransferFolder(location.provider))
{
if(!isFtpFolderPath(path)) return {};
}
else if(!path.is_absolute()) return {};
return location;
}
std::vector<FolderLocation> readRecentFolders()
{
const auto saved=readFilesJsonPreference(recentFoldersKey);
std::vector<fs::path> folders;
std::vector<FolderLocation> folders;
if(!saved || !saved->is_array()) return folders;
for(const auto &entry:*saved)
{
if(!entry.is_string()) continue;
const auto path=filePath(entry);
if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos) continue;
if(std::none_of(folders.begin(),folders.end(),[&](const auto &known){return sameLocalFolder(path,known);}))
folders.push_back(path);
try
{
auto location=readRecentFolder(entry);
if(location && std::none_of(folders.begin(),folders.end(),
[&](const auto &known){return sameFolderLocation(*location,known);}))
folders.push_back(std::move(*location));
}
catch(const std::exception &) {}
if(folders.size()==recentFoldersLimit) break;
}
return folders;
}
bool updateRecentFolders(const fs::path &path,bool remember)
bool updateRecentFolders(const FolderLocation &location,bool remember)
{
const Handle lock{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.RecentFolders")};
if(!lock.value) return false;
@@ -28,11 +58,18 @@ bool updateRecentFolders(const fs::path &path,bool remember)
try
{
auto folders=readRecentFolders();
std::erase_if(folders,[&](const auto &known){return sameLocalFolder(path,known);});
if(remember) folders.insert(folders.begin(),path);
std::erase_if(folders,[&](const auto &known){return sameFolderLocation(location,known);});
if(remember) folders.insert(folders.begin(),location);
if(folders.size()>recentFoldersLimit) folders.resize(recentFoldersLimit);
auto data=Json::array();
for(const auto &folder:folders) data.push_back(ks::utf8(folder.native()));
for(const auto &folder:folders)
{
const auto path=ks::utf8(folder.directory.native());
if(folder.provider==FolderProvider::local) data.push_back(path);
else data.push_back({{"source",folder.provider==FolderProvider::ftp?"ftp":
folder.provider==FolderProvider::sftp?"sftp":"lan"},{"id",folder.id},
{"label",ks::utf8(folder.label)},{"path",path}});
}
saved=writeFilesJsonPreference(recentFoldersKey,data);
}
catch(const std::exception &) {}
+460
View File
@@ -0,0 +1,460 @@
constexpr long sftpTimeoutMs=10000;
void initializeSsh()
{
static const auto initialized=libssh2_init(0);
if(initialized) throw std::runtime_error("Could not initialize the SSH client.");
}
void connectSshSocket(ks::lan::WinSocket &connection,const TransferProfile &profile)
{
ADDRINFOW query{};
query.ai_socktype=SOCK_STREAM;
query.ai_protocol=IPPROTO_TCP;
ADDRINFOW *addresses{};
const auto service=std::to_wstring(profile.port);
if(const auto error=GetAddrInfoW(profile.host.c_str(),service.c_str(),&query,&addresses))
throw std::system_error(error,std::system_category());
const std::unique_ptr<ADDRINFOW,decltype(&FreeAddrInfoW)> resolved(addresses,FreeAddrInfoW);
DWORD lastError=WSAEHOSTUNREACH;
const auto deadline=GetTickCount64()+sftpTimeoutMs;
for(auto *address=addresses;address;address=address->ai_next)
{
ks::lan::WinSocket socket{::socket(address->ai_family,address->ai_socktype,address->ai_protocol)};
if(socket.value==INVALID_SOCKET) {lastError=WSAGetLastError();continue;}
u_long nonblocking=1;
if(ioctlsocket(socket.value,FIONBIO,&nonblocking)==SOCKET_ERROR)
{lastError=WSAGetLastError();continue;}
if(::connect(socket.value,address->ai_addr,static_cast<int>(address->ai_addrlen))==SOCKET_ERROR)
{
lastError=WSAGetLastError();
if(lastError!=WSAEWOULDBLOCK) continue;
const auto now=GetTickCount64();
if(now>=deadline) {lastError=WSAETIMEDOUT;break;}
const auto left=deadline-now;
timeval timeout{static_cast<long>(left/1000),static_cast<long>(left%1000)*1000};
fd_set writable{},failed{};
FD_SET(socket.value,&writable);
FD_SET(socket.value,&failed);
const auto ready=select(0,nullptr,&writable,&failed,&timeout);
if(ready==SOCKET_ERROR) {lastError=WSAGetLastError();continue;}
if(!ready) {lastError=WSAETIMEDOUT;break;}
int error{},length=sizeof(error);
if(getsockopt(socket.value,SOL_SOCKET,SO_ERROR,reinterpret_cast<char*>(&error),&length)==SOCKET_ERROR)
{lastError=WSAGetLastError();continue;}
if(error) {lastError=error;continue;}
}
nonblocking=0;
if(ioctlsocket(socket.value,FIONBIO,&nonblocking)==SOCKET_ERROR)
{lastError=WSAGetLastError();continue;}
connection.value=std::exchange(socket.value,INVALID_SOCKET);
return;
}
throw std::system_error(lastError,std::system_category());
}
using SshChannel=std::unique_ptr<LIBSSH2_CHANNEL,decltype(&libssh2_channel_free)>;
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::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(),&message,&length,0);
throw std::runtime_error(std::string(operation)+(message && length>0?": "+std::string(message,length):""));
}
void authenticate(const TransferProfile &profile)
{
auto wideSecret=transferPassword(profile);
struct EraseWide
{
std::wstring &text;
~EraseWide(){if(!text.empty()) SecureZeroMemory(text.data(),text.size()*sizeof(wchar_t));}
} eraseWide{wideSecret};
auto secret=ks::utf8(wideSecret);
struct EraseText
{
std::string &text;
~EraseText(){if(!text.empty()) SecureZeroMemory(text.data(),text.size());}
} eraseSecret{secret};
const auto user=ks::utf8(profile.user);
int result{};
if(profile.privateKey.empty())
result=libssh2_userauth_password_ex(session(),user.c_str(),static_cast<unsigned>(user.size()),
secret.c_str(),static_cast<unsigned>(secret.size()),nullptr);
else
{
auto key=ks::readFile(profile.privateKey,1024*1024);
struct EraseKey
{
ks::Bytes &bytes;
~EraseKey(){if(!bytes.empty()) SecureZeroMemory(bytes.data(),bytes.size());}
} eraseKey{key};
if(key.empty()) throw std::runtime_error("Could not read the SFTP private key file.");
auto publicPath=profile.privateKey;
publicPath+=L".pub";
ks::Bytes publicKey;
std::error_code error;
if(fs::exists(publicPath,error)) publicKey=ks::readFile(publicPath,64*1024);
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());
}
if(result) sshError(profile.privateKey.empty()?"SFTP password authentication failed":
"SFTP key authentication failed (use RSA PEM without a passphrase, or ECDSA OpenSSH with its .pub file)");
}
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.");
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(),socket_.value))
sshError("Could not negotiate an SSH connection");
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));
checkFileOperation(CryptBinaryToStringA(digest,32,CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF,fingerprint,&length));
auto encoded=std::string(fingerprint);
while(encoded.ends_with('=')) encoded.pop_back();
fingerprint_="SHA256:"+encoded;
if(probeOnly) return;
if(!ks::lan::equal(fingerprint_,profile.hostFingerprint))
throw std::runtime_error("The SFTP host key changed. Connection blocked before authentication. Received "+fingerprint_+".");
authenticate(profile);
}
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(connection_.session())==LIBSSH2_ERROR_SFTP_PROTOCOL)
{
const auto status=libssh2_sftp_last_error(sftp_.get());
if(status==LIBSSH2_FX_PERMISSION_DENIED)
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)
throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category(),operation);
if(status==LIBSSH2_FX_OP_UNSUPPORTED)
throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category(),operation);
}
connection_.operationError(operation);
}
fs::path initialDirectory() const
{
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
{
if(stop.stop_requested()) return ERROR_CANCELLED;
const auto path=encode(directory);
const SftpFile folder(libssh2_sftp_open_ex(sftp_.get(),path.c_str(),static_cast<unsigned>(path.size()),
0,0,LIBSSH2_SFTP_OPENDIR));
if(!folder.handle) operationError("Could not open the SFTP folder");
std::array<char,32768> name{};
while(!stop.stop_requested())
{
LIBSSH2_SFTP_ATTRIBUTES attrs{};
const auto length=libssh2_sftp_readdir_ex(folder.handle,name.data(),name.size(),nullptr,0,&attrs);
if(length==0) return ERROR_NO_MORE_FILES;
if(length<0) operationError("Could not read the SFTP folder");
const auto child=ks::wide(std::string(name.data(),length));
if(child.empty() || child==L"." || child==L".." || child.find_first_of(L"/\\:\r\n")!=child.npos ||
child.find(L'\0')!=child.npos) continue;
DWORD attributes=FILE_ATTRIBUTE_NORMAL;
if((attrs.flags&LIBSSH2_SFTP_ATTR_PERMISSIONS)!=0)
{
if(LIBSSH2_SFTP_S_ISDIR(attrs.permissions)) attributes=FILE_ATTRIBUTE_DIRECTORY;
else if(!LIBSSH2_SFTP_S_ISREG(attrs.permissions)) attributes=FILE_ATTRIBUTE_REPARSE_POINT;
if(!(attrs.permissions&0222)) attributes|=FILE_ATTRIBUTE_READONLY;
}
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()),
flags,0600,LIBSSH2_SFTP_OPENFILE));
if(!file.handle) operationError(write?"Could not create the staged SFTP file":"Could not open the SFTP file");
return file;
}
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 preserveModificationTime(const fs::path &path,uint64_t modified) const
{
constexpr uint64_t ticks=10000000, windowsEpoch=11644473600;
if(modified/ticks<windowsEpoch || modified/ticks-windowsEpoch>UINT32_MAX) return;
requireWriteAccess();
const auto name=encode(path);
LIBSSH2_SFTP_ATTRIBUTES attributes{};
if(libssh2_sftp_lstat(sftp_.get(),name.c_str(),&attributes))
operationError("Could not read the staged file timestamps");
const auto seconds=static_cast<unsigned long>(modified/ticks-windowsEpoch);
if(!(attributes.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)) attributes.atime=seconds;
attributes.flags=LIBSSH2_SFTP_ATTR_ACMODTIME;
attributes.mtime=seconds;
if(libssh2_sftp_setstat(sftp_.get(),name.c_str(),&attributes) &&
libssh2_sftp_last_error(sftp_.get())!=LIBSSH2_FX_OP_UNSUPPORTED)
operationError("Could not preserve the SFTP modification time");
}
void remove(const fs::path &path,bool directory) const
{
requireWriteAccess();
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)
{
const auto result=libssh2_sftp_posix_rename_ex(sftp_.get(),source.c_str(),source.size(),
target.c_str(),target.size());
if(result && (result==LIBSSH2_ERROR_METHOD_NOT_SUPPORTED ||
libssh2_sftp_last_error(sftp_.get())==LIBSSH2_FX_OP_UNSUPPORTED))
throw std::runtime_error("The SFTP server does not support atomic replacement. The original file was kept.");
if(result) operationError("Could not replace the SFTP file");
return;
}
if(libssh2_sftp_rename_ex(sftp_.get(),source.c_str(),static_cast<unsigned>(source.size()),
target.c_str(),static_cast<unsigned>(target.size()),0))
operationError("Could not rename the SFTP entry");
}
};
+633
View File
@@ -0,0 +1,633 @@
namespace smb
{
constexpr wchar_t profilesKey[]=L"SmbProfiles";
constexpr DWORD shareTypeMask=0xff;
constexpr int summary=540,list=541,status=542,footer=543,newProfile=544,editProfile=545,removeProfile=546,signIn=547;
constexpr int nameLabel=550,nameField=551,addressLabel=552,addressField=553,editFooter=554;
constexpr int loginLabel=555,userLabel=556,userField=557,passwordLabel=558,passwordField=559,rememberField=560,loginFooter=561;
struct Target
{
std::wstring server;
fs::path share,folder;
};
std::optional<Target> parseTarget(std::wstring address)
{
address=trimFilesField(std::move(address));
std::replace(address.begin(),address.end(),L'/',L'\\');
if(address.starts_with(L"\\\\")) address.erase(0,2);
while(address.ends_with(L"\\")) address.pop_back();
if(address.empty() || address.size()>=MAX_PATH-2) return {};
const auto separator=address.find(L'\\');
const auto host=address.substr(0,separator);
if(host.empty() || host==L"." || host==L".." || host.find_first_of(L" \t\r\n@<>:\"|?*")!=host.npos ||
std::any_of(host.begin(),host.end(),[](auto c){return c<L' ';})) return {};
Target target{L"\\\\"+host};
if(separator==address.npos) return target;
const auto relative=address.substr(separator+1);
if(relative.empty() || relative.front()==L'\\' || relative.find(L"\\\\")!=relative.npos ||
relative.find_first_of(L"<>:\"|?*")!=relative.npos ||
std::any_of(relative.begin(),relative.end(),[](auto c){return c<L' ';})) return {};
const fs::path components(relative);
for(const auto &part:components)
if(part==L"." || part==L".." || part.native().back()==L' ' || part.native().back()==L'.')
return {};
target.share=fs::path(target.server+L"\\"+components.begin()->native());
target.folder=fs::path(target.server+L"\\"+relative);
return target;
}
struct Profile
{
std::string id;
std::wstring name;
Target target;
};
std::wstring profileAddress(const Profile &profile)
{
return profile.target.folder.empty()?profile.target.server:profile.target.folder.native();
}
std::vector<Profile> readProfiles()
{
std::vector<Profile> profiles;
const auto saved=readFilesJsonPreference(profilesKey);
if(!saved || !saved->is_array()) return profiles;
for(const auto &row:*saved)
{
try
{
const auto id=row.at("id").get<std::string>();
auto name=ks::wide(row.at("name"));
auto target=parseTarget(ks::wide(row.at("path")));
if(ks::lan::identifier(id) && !name.empty() && target &&
std::none_of(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==id;}))
profiles.push_back({id,std::move(name),std::move(*target)});
}
catch(const std::exception &) {}
}
return profiles;
}
struct ProfilesLock
{
Handle handle{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.SmbProfiles")};
bool locked{};
ProfilesLock()
{
if(!handle.value) return;
const auto wait=WaitForSingleObject(handle.value,100);
locked=wait==WAIT_OBJECT_0 || wait==WAIT_ABANDONED;
}
~ProfilesLock() {if(locked) ReleaseMutex(handle.value);}
};
bool sameServer(const Profile &a,const Profile &b)
{
return CompareStringOrdinal(a.target.server.c_str(),-1,b.target.server.c_str(),-1,TRUE)==CSTR_EQUAL;
}
template<class Change>
std::optional<std::vector<Profile>> updateProfiles(Change change)
{
const ProfilesLock lock;
if(!lock.locked) return {};
std::optional<std::vector<Profile>> result;
try
{
auto profiles=readProfiles();
if(change(profiles))
{
auto data=Json::array();
for(const auto &entry:profiles)
data.push_back({{"id",entry.id},{"name",ks::utf8(entry.name)},{"path",ks::utf8(profileAddress(entry))}});
if(writeFilesJsonPreference(profilesKey,data)) result=std::move(profiles);
}
}
catch(const std::exception &) {}
return result;
}
std::wstring credentialTarget(const Profile &profile)
{
auto host=profile.target.server.substr(2);
for(auto &letter:host)
if(letter>=L'A' && letter<=L'Z') letter+=L'a'-L'A';
return L"KSwitcher.Files/SMB/"+ks::wide(profile.id)+L"/"+host;
}
DWORD deleteCredential(const Profile &profile)
{
if(CredDeleteW(credentialTarget(profile).c_str(),CRED_TYPE_GENERIC,0)) return ERROR_SUCCESS;
const auto error=GetLastError();
return error==ERROR_NOT_FOUND?ERROR_SUCCESS:error;
}
struct Credentials
{
std::wstring user;
std::vector<wchar_t> password;
bool remember{};
Credentials()=default;
Credentials(const Credentials &)=delete;
Credentials &operator=(const Credentials &)=delete;
~Credentials()
{
if(!password.empty()) SecureZeroMemory(password.data(),password.size()*sizeof(wchar_t));
}
};
DWORD loadCredential(const Profile &profile,Credentials &login)
{
struct Allocation
{
PCREDENTIALW data{};
~Allocation()
{
if(!data) return;
if(data->CredentialBlobSize) SecureZeroMemory(data->CredentialBlob,data->CredentialBlobSize);
CredFree(data);
}
} response;
if(!CredReadW(credentialTarget(profile).c_str(),CRED_TYPE_GENERIC,0,&response.data))
{
const auto error=GetLastError();
return error==ERROR_NOT_FOUND?ERROR_SUCCESS:error;
}
const auto &credential=*response.data;
if(!credential.UserName || !*credential.UserName || credential.CredentialBlobSize%sizeof(wchar_t))
return ERROR_INVALID_DATA;
login.user=credential.UserName;
login.password.resize(credential.CredentialBlobSize/sizeof(wchar_t)+1);
if(credential.CredentialBlobSize)
std::memcpy(login.password.data(),credential.CredentialBlob,credential.CredentialBlobSize);
return ERROR_SUCCESS;
}
DWORD saveCredential(const Profile &profile,const Credentials &login)
{
const ProfilesLock lock;
if(!lock.locked) return ERROR_BUSY;
const auto profiles=readProfiles();
if(std::none_of(profiles.begin(),profiles.end(),[&](const auto &entry) {
return entry.id==profile.id && sameServer(profile,entry);
})) return ERROR_NOT_FOUND;
auto target=credentialTarget(profile);
CREDENTIALW credential{};
credential.Type=CRED_TYPE_GENERIC;
credential.TargetName=target.data();
credential.Persist=CRED_PERSIST_LOCAL_MACHINE;
credential.UserName=const_cast<wchar_t*>(login.user.c_str());
credential.CredentialBlobSize=static_cast<DWORD>((login.password.size()-1)*sizeof(wchar_t));
credential.CredentialBlob=reinterpret_cast<LPBYTE>(const_cast<wchar_t*>(login.password.data()));
return CredWriteW(&credential,0)?ERROR_SUCCESS:GetLastError();
}
std::wstring errorText(DWORD error)
{
if(error==ERROR_SESSION_CREDENTIAL_CONFLICT)
return L"Windows already has a session to this server with another account. Use that account or disconnect that session in Windows before trying again.";
return fileError(std::system_error(error,std::system_category()));
}
struct Connection
{
fs::path folder;
std::vector<std::wstring> shares;
DWORD error{},credentialError{};
};
Connection connect(const Profile &profile,const Credentials *explicitLogin,const std::atomic_bool &canceled)
{
Connection result;
Credentials stored;
auto login=explicitLogin;
if(!login)
{
result.error=loadCredential(profile,stored);
if(result.error) return result;
if(!stored.user.empty()) login=&stored;
}
if(login && !canceled)
{
auto resource=profile.target.share.empty()?profile.target.server+L"\\IPC$":profile.target.share.native();
NETRESOURCEW endpoint{};
endpoint.dwType=profile.target.share.empty()?RESOURCETYPE_ANY:RESOURCETYPE_DISK;
endpoint.lpRemoteName=resource.data();
result.error=WNetAddConnection2W(&endpoint,login->password.data(),login->user.c_str(),CONNECT_TEMPORARY);
if(result.error) return result;
}
if(canceled) return result;
if(!profile.target.folder.empty())
{
WIN32_FIND_DATAW first{};
const auto listing=FindFirstFileW((profile.target.folder/L"*").c_str(),&first);
if(listing!=INVALID_HANDLE_VALUE) FindClose(listing);
else
{
const auto error=GetLastError();
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_NO_MORE_FILES) result.error=error;
}
if(!result.error) result.folder=profile.target.folder;
}
else
{
auto server=profile.target.server;
DWORD resume{};
do
{
struct Buffer { BYTE *data{}; ~Buffer(){if(data) NetApiBufferFree(data);} } buffer;
DWORD read{},total{};
const auto previous=resume;
result.error=NetShareEnum(server.data(),1,&buffer.data,MAX_PREFERRED_LENGTH,&read,&total,&resume);
if(result.error!=NERR_Success && result.error!=ERROR_MORE_DATA) return result;
const auto rows=reinterpret_cast<const SHARE_INFO_1*>(buffer.data);
for(DWORD i=0;i<read && !canceled;++i)
{
const auto &row=rows[i];
const std::wstring_view name=row.shi1_netname?row.shi1_netname:L"";
if(!name.empty() && (row.shi1_type&shareTypeMask)==STYPE_DISKTREE &&
!(row.shi1_type&STYPE_SPECIAL) && name.back()!=L'$' &&
name.find_first_of(L"/\\") == name.npos)
result.shares.emplace_back(name);
}
if(result.error==ERROR_MORE_DATA && previous==resume) return result;
} while(result.error==ERROR_MORE_DATA && !canceled);
std::sort(result.shares.begin(),result.shares.end(),[](const auto &a,const auto &b) {
return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,TRUE)==CSTR_LESS_THAN;
});
}
if(!result.error && !canceled && explicitLogin && explicitLogin->remember)
result.credentialError=saveCredential(profile,*explicitLogin);
return result;
}
bool closeRequest(UINT message,WPARAM command)
{
return message==WM_CLOSE || (message==WM_COMMAND && LOWORD(command)==IDCANCEL);
}
struct EditProfile
{
Profile profile;
std::optional<std::vector<Profile>> saved;
};
INT_PTR CALLBACK editDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB connection ",false,{editFooter}))
return painted;
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &edit=*reinterpret_cast<EditProfile*>(lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,nameLabel);
for(const auto id:{nameLabel,addressLabel})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendDlgItemMessageW(dialog,nameField,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(dialog,addressField,EM_SETLIMITTEXT,MAX_PATH-1,0);
SetDlgItemTextW(dialog,nameField,edit.profile.name.c_str());
SetDlgItemTextW(dialog,addressField,profileAddress(edit.profile).c_str());
layoutDialogButtons(dialog,editFooter,{IDOK,IDCANCEL});
return TRUE;
}
if(closeRequest(message,wp))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &edit=*reinterpret_cast<EditProfile*>(GetWindowLongPtrW(dialog,DWLP_USER));
auto name=trimFilesField(shortcutField(dialog,nameField));
auto target=parseTarget(shortcutField(dialog,addressField));
const bool validName=!name.empty() && name.find_first_of(L"\r\n\t")==name.npos;
if(!validName || !target)
{
showFilesNotice(dialog,!validName?L"Enter a connection name on one line.":
L"Enter a server name or a UNC folder such as \\\\server\\share.",L"SMB connection");
SetFocus(GetDlgItem(dialog,validName?addressField:nameField));
return TRUE;
}
const bool creating=edit.profile.id.empty();
Profile next{creating?ks::lan::randomHex(16):edit.profile.id,std::move(name),std::move(*target)};
DWORD error=ERROR_SUCCESS;
edit.saved=updateProfiles([&](auto &profiles) {
const auto previous=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==next.id;});
if(std::any_of(profiles.begin(),profiles.end(),[&](const auto &entry) {
return entry.id!=next.id && CompareStringOrdinal(entry.name.c_str(),-1,next.name.c_str(),-1,TRUE)==CSTR_EQUAL;
}))
{
error=ERROR_ALREADY_EXISTS;
return false;
}
if(creating) profiles.push_back(next);
else
{
if(previous==profiles.end()) {error=ERROR_NOT_FOUND;return false;}
if(!sameServer(*previous,next) && (error=deleteCredential(*previous))) return false;
*previous=next;
}
return true;
});
if(!edit.saved)
{
const auto detail=error==ERROR_ALREADY_EXISTS?L"A connection with this name already exists.":
error?errorText(error):L"Could not save the SMB connection.";
showFilesNotice(dialog,detail.c_str(),L"SMB connection");
return TRUE;
}
edit.profile=std::move(next);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
struct LoginPrompt
{
const Profile &profile;
Credentials &login;
};
INT_PTR CALLBACK loginDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB sign in ",false,{loginFooter}))
return painted;
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &prompt=*reinterpret_cast<LoginPrompt*>(lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,loginLabel);
for(const auto id:{loginLabel,userLabel,passwordLabel,rememberField})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SetDlgItemTextW(dialog,loginLabel,(L"Server "+prompt.profile.target.server).c_str());
SendDlgItemMessageW(dialog,userField,EM_SETLIMITTEXT,256,0);
SendDlgItemMessageW(dialog,passwordField,EM_SETLIMITTEXT,CRED_MAX_CREDENTIAL_BLOB_SIZE/sizeof(wchar_t),0);
installFarCheckbox(GetDlgItem(dialog,rememberField),FarCheckboxSurface::gray);
layoutDialogButtons(dialog,loginFooter,{IDOK,IDCANCEL});
return TRUE;
}
const auto clearPassword=[&]
{
SetDlgItemTextW(dialog,passwordField,L"");
SendDlgItemMessageW(dialog,passwordField,EM_EMPTYUNDOBUFFER,0,0);
};
if(closeRequest(message,wp))
{
clearPassword();
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &login=reinterpret_cast<LoginPrompt*>(GetWindowLongPtrW(dialog,DWLP_USER))->login;
auto user=trimFilesField(shortcutField(dialog,userField));
if(user.empty())
{
showFilesNotice(dialog,L"Enter the SMB account name.",L"SMB sign in");
SetFocus(GetDlgItem(dialog,userField));
return TRUE;
}
login.user=std::move(user);
const auto field=GetDlgItem(dialog,passwordField);
const auto length=GetWindowTextLengthW(field);
login.password.resize(static_cast<size_t>(length)+1);
GetWindowTextW(field,login.password.data(),length+1);
login.remember=IsDlgButtonChecked(dialog,rememberField)==BST_CHECKED;
clearPassword();
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
struct Browser
{
std::vector<Profile> profiles;
std::optional<Profile> server;
std::vector<std::wstring> shares;
fs::path chosen;
std::atomic_bool canceled{};
bool busy{};
};
void browserControls(HWND dialog,const Browser &browser)
{
const auto selected=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0)!=LB_ERR;
EnableWindow(GetDlgItem(dialog,list),!browser.busy);
EnableWindow(GetDlgItem(dialog,IDOK),!browser.busy && selected);
EnableWindow(GetDlgItem(dialog,newProfile),!browser.busy);
for(const auto button:{editProfile,removeProfile,signIn})
EnableWindow(GetDlgItem(dialog,button),!browser.busy && selected && !browser.server);
}
void showRows(HWND dialog,const Browser &browser,LRESULT selection=0)
{
const auto rows=GetDlgItem(dialog,list);
SendMessageW(rows,LB_RESETCONTENT,0,0);
const auto add=[&](const std::wstring &label){SendMessageW(rows,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));};
if(browser.server)
{
for(const auto &share:browser.shares) add(share);
SetDlgItemTextW(dialog,summary,(L"Shared folders on "+browser.server->target.server).c_str());
SetDlgItemTextW(dialog,status,browser.shares.empty()?L"No visible disk shares. A known UNC share can be saved as a profile.":L"");
SetDlgItemTextW(dialog,newProfile,L"&Back");
for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_HIDE);
layoutDialogButtons(dialog,footer,{IDOK,newProfile,IDCANCEL});
}
else
{
for(const auto &entry:browser.profiles) add(entry.name+L" · "+profileAddress(entry));
SetDlgItemTextW(dialog,summary,L"Saved SMB connections");
SetDlgItemTextW(dialog,status,browser.profiles.empty()?L"Choose New to add a server or UNC folder.":L"");
SetDlgItemTextW(dialog,newProfile,L"&New");
for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_SHOWNA);
layoutDialogButtons(dialog,footer,{IDOK,newProfile,editProfile,removeProfile,signIn,IDCANCEL});
}
const auto count=SendMessageW(rows,LB_GETCOUNT,0,0);
if(count>0) SendMessageW(rows,LB_SETCURSEL,std::clamp<LRESULT>(selection,0,count-1),0);
browserControls(dialog,browser);
SetFocus(count>0?rows:GetDlgItem(dialog,newProfile));
}
void openProfile(HWND dialog,Browser &browser,const Profile &profile,bool withLogin)
{
Credentials login;
if(withLogin)
{
LoginPrompt prompt{profile,login};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(123),dialog,loginDialog,
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
}
browser.busy=true;
browser.canceled=false;
browserControls(dialog,browser);
SetFocus(GetDlgItem(dialog,IDCANCEL));
SetDlgItemTextW(dialog,status,(L"Connecting to "+profile.target.server+L"…").c_str());
Connection result;
try
{
FileOperationUi worker;
worker.run(dialog,browser.canceled,[&]{result=connect(profile,withLogin?&login:nullptr,browser.canceled);});
}
catch(const std::exception &)
{
result.error=ERROR_GEN_FAILURE;
}
browser.busy=false;
browserControls(dialog,browser);
if(browser.canceled)
{
SetDlgItemTextW(dialog,status,L"Connection canceled.");
SetFocus(GetDlgItem(dialog,list));
return;
}
if(result.error)
{
auto detail=profileAddress(profile)+L"\r\n\r\n"+errorText(result.error);
if(result.error==ERROR_ACCESS_DENIED || result.error==ERROR_LOGON_FAILURE ||
result.error==ERROR_INVALID_PASSWORD || result.error==ERROR_BAD_USERNAME)
detail+=L"\r\n\r\nUse Sign in to try a different account.";
showFilesNotice(dialog,detail.c_str(),L"Could not open SMB connection",{.tone=FilesNoticeTone::warning});
SetDlgItemTextW(dialog,status,L"Connection failed. Open to retry or choose Sign in.");
SetFocus(GetDlgItem(dialog,list));
return;
}
if(result.credentialError)
{
const auto detail=L"Connected, but Windows Credential Manager did not save the account.\r\n\r\n"+
errorText(result.credentialError);
showFilesNotice(dialog,detail.c_str(),L"SMB sign in",{.tone=FilesNoticeTone::warning});
}
if(!result.folder.empty())
{
browser.chosen=std::move(result.folder);
FilesModalDialog::finish(dialog,IDOK);
return;
}
browser.server=profile;
browser.shares=std::move(result.shares);
showRows(dialog,browser);
}
INT_PTR CALLBACK browserDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *browser=reinterpret_cast<Browser*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(message==WM_INITDIALOG)
{
browser=reinterpret_cast<Browser*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,summary);
for(const auto id:{summary,list,status})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendDlgItemMessageW(dialog,list,LB_SETITEMHEIGHT,0,textHeight);
installScrollBar(GetDlgItem(dialog,list),dialog);
showRows(dialog,*browser);
return FALSE;
}
if(message==WM_DRAWITEM && wp==list)
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT*>(lp);
if(item.itemID==UINT(-1)) return TRUE;
const auto length=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
if(length==LB_ERR) return TRUE;
std::wstring label(static_cast<size_t>(length)+1,L'\0');
SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()));
const bool selected=(item.itemState&ODS_SELECTED)!=0;
paintDialogListRow(item.hDC,item.rcItem,label.c_str(),mono,colors[Text],
selected?colors[Selection]:colors[Dialog],dialogRowTextInset(cellWidth),DT_END_ELLIPSIS);
return TRUE;
}
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB ",false,{footer},true,GetDlgItem(dialog,list)))
return painted;
if(!browser) return FALSE;
if(closeRequest(message,wp))
{
if(browser->busy)
{
browser->canceled=true;
SetDlgItemTextW(dialog,status,L"Stopping when Windows returns…");
}
else FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(browser->busy) return TRUE;
const auto command=LOWORD(wp);
const auto row=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0);
if(command==list && HIWORD(wp)==LBN_SELCHANGE)
{
browserControls(dialog,*browser);
return TRUE;
}
const bool open=command==IDOK || (command==list && HIWORD(wp)==LBN_DBLCLK);
if(browser->server)
{
if(command==newProfile)
{
browser->server.reset();
browser->shares.clear();
showRows(dialog,*browser);
}
else if(open && row>=0 && static_cast<size_t>(row)<browser->shares.size())
{
browser->chosen=fs::path(browser->server->target.server+L"\\"+browser->shares[row]);
FilesModalDialog::finish(dialog,IDOK);
}
return TRUE;
}
const auto *selected=row>=0 && static_cast<size_t>(row)<browser->profiles.size()?&browser->profiles[row]:nullptr;
if(command==newProfile || (command==editProfile && selected))
{
EditProfile edit{command==newProfile?Profile{}:*selected};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(122),dialog,editDialog,
reinterpret_cast<LPARAM>(&edit))==IDOK)
{
browser->profiles=std::move(*edit.saved);
const auto profile=std::find_if(browser->profiles.begin(),browser->profiles.end(),[&](const auto &entry) {
return entry.id==edit.profile.id;
});
showRows(dialog,*browser,profile-browser->profiles.begin());
}
return TRUE;
}
if(selected && (open || command==signIn))
{
openProfile(dialog,*browser,*selected,command==signIn);
return TRUE;
}
if(selected && command==removeProfile)
{
const auto detail=L"Remove "+selected->name+L" and its saved credentials?";
if(showFilesNotice(dialog,detail.c_str(),L"Remove SMB connection",{.confirm=true})!=IDYES) return TRUE;
DWORD error=ERROR_SUCCESS;
auto updated=updateProfiles([&](auto &profiles) {
const auto row=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==selected->id;});
if(row==profiles.end()) return true;
if((error=deleteCredential(*row))) return false;
profiles.erase(row);
return true;
});
if(updated)
{
browser->profiles=std::move(*updated);
showRows(dialog,*browser,row);
}
else
{
const auto failure=error?errorText(error):L"Could not remove the saved connection.";
showFilesNotice(dialog,failure.c_str(),L"Remove SMB connection");
}
return TRUE;
}
return FALSE;
}
}
void showSmbProfiles(Panel &panel)
{
smb::Browser browser{smb::readProfiles()};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(121),GetParent(panel.list),
smb::browserDialog,reinterpret_cast<LPARAM>(&browser))==IDOK)
openOn(panel,browser.chosen,false,{});
}
+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)
+178 -38
View File
@@ -600,7 +600,7 @@ RemoteTextSource lanTextSource(const lan::FilesPeer &peer)
throw std::runtime_error("Update KSwitcher on the remote computer to edit this file.");
if(edit && readOnly) throw std::runtime_error("The remote file is read-only.");
const RemoteTextRevision revision{info.at("size"),info.at("modified"),canCommit && !readOnly};
if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview.");
if(revision.size>sizeLimit) throw std::system_error(ERROR_FILE_TOO_LARGE,std::system_category());
try
{
lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress);
@@ -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);
}
};
@@ -684,6 +688,12 @@ std::map<HWND,std::shared_ptr<TextWindow>> textWindows;
std::vector<HWND> textWindowOrder;
HWND filesOwner{};
bool textOwnerClosed=false;
unsigned standaloneFilesWindows{};
void quitWhenFilesWindowsClose()
{
if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty() && !standaloneFilesWindows)
PostQuitMessage(0);
}
constexpr ULONG_PTR openDocumentQuery=0x4B534644;
std::wstring documentIdentity(const std::filesystem::path &path,std::string_view peer)
@@ -794,6 +804,7 @@ public:
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
void previewFile(const std::filesystem::path &path);
void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff);
bool openBookmark(const ViewerBookmark &bookmark);
std::filesystem::path original;
const std::string peerId;
@@ -896,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;
@@ -924,6 +936,8 @@ private:
};
std::future<QuickDocument> quickLoading;
std::filesystem::path quickPath;
std::wstring quickTextTitle;
bool quickTextVisible{},quickTextDiff{};
uint64_t quickRequest{}, quickReading{};
ULONGLONG quickReadyAt{};
std::wstring quickError;
@@ -958,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();
@@ -973,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);
@@ -980,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();
@@ -1399,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);
@@ -1412,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;
@@ -1604,7 +1625,9 @@ std::string readMarkdownDocument(TextDocument &document)
void TextWindow::previewFile(const std::filesystem::path &path)
{
if(path==quickPath) return;
if(quickTextTitle.empty() && path==quickPath) return;
quickTextVisible=false;
quickTextTitle.clear();
quickPath=path;
++quickRequest;
quickReadyAt=GetTickCount64()+80;
@@ -1616,6 +1639,34 @@ void TextWindow::previewFile(const std::filesystem::path &path)
SetTimer(window,quickViewTimer,30,nullptr);
}
void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff)
{
if(!embedded) return;
if(quickTextTitle.empty())
{
++quickRequest;
KillTimer(window,quickViewTimer);
quickLoading={};
quickPath.clear();
quickError.clear();
stopPreview(false,true);
document.reset();
quickMarkdown.reset();
}
if(quickTextTitle.empty() || quickTextDiff!=diff)
{
language=automatic=diff?detectLanguage(L"preview.diff",contents):TextLanguage{};
installLexer();
}
quickTextTitle=title;
quickTextVisible=!contents.empty();
quickTextDiff=diff;
pageEol=SC_EOL_LF;
replaceEditorText(contents);
send(SCI_COLOURISE,0,-1);
layout();
}
void TextWindow::pollQuickView()
{
if(quickLoading.valid())
@@ -1671,6 +1722,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;
@@ -1683,6 +1752,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());
@@ -1690,7 +1771,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;
@@ -1704,17 +1785,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;
@@ -1739,7 +1825,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)
@@ -1775,7 +1876,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())
{
@@ -2454,7 +2559,7 @@ void TextWindow::layout()
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
ShowWindow(editor,document && !previewWanted?SW_SHOWNA:SW_HIDE);
ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
invalidate();
}
@@ -2531,6 +2636,7 @@ void TextWindow::paint()
else if(quickPath.empty()) label+=L" · Select a local text file";
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
else if(!previewVisible && pageTotal>1) label+=L" · First page";
if(!quickTextTitle.empty()) label=quickTextTitle;
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
color(TextColor::chrome),scale(6),label);
if(chromeFont) DeleteObject(chromeFont);
@@ -2645,7 +2751,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)
@@ -2871,12 +2977,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();
@@ -2990,7 +3091,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
self->window=nullptr;
textWindows.erase(window);
std::erase(textWindowOrder,window);
if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0);
quitWhenFilesWindowsClose();
break;
}
}
@@ -3108,7 +3209,18 @@ void textWindowOwnerClosed()
{
filesOwner=nullptr;
textOwnerClosed=true;
if(textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0);
quitWhenFilesWindowsClose();
}
void standaloneFilesWindowOpened()
{
++standaloneFilesWindows;
}
void standaloneFilesWindowClosed()
{
if(standaloneFilesWindows) --standaloneFilesWindows;
quitWhenFilesWindowsClose();
}
bool cycleTextWindows(HWND current,bool reverse)
@@ -3187,6 +3299,12 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
preview->second->previewFile(path);
}
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff)
{
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
preview->second->previewEmbeddedText(title,contents,diff);
}
ImageViewStyle imageViewStyle(TextDialogs dialogs)
{
const auto font=dialogs.readFont();
@@ -3211,18 +3329,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);
if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0);
});
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);
@@ -3292,6 +3427,11 @@ void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit
openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,options);
}
RemoteTextSource createLanTextSource(const lan::FilesPeer &peer)
{
return lanTextSource(peer);
}
void showAllViewerBookmarks(HWND owner,TextDialogs dialogs)
{
try
+28 -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,20 +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 previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff=false);
HWND createImageQuickView(HWND owner,TextDialogs dialogs);
void previewImageQuickViewFile(HWND window,const std::filesystem::path &path);
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
@@ -97,5 +119,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={});
void textWindowOwnerClosed();
void standaloneFilesWindowOpened();
void standaloneFilesWindowClosed();
bool cycleTextWindows(HWND current,bool reverse);
}
+122
View File
@@ -0,0 +1,122 @@
constexpr DWORD ftpCopyFlags=INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE;
class TransferFile
{
FtpHandle ftp_;
std::optional<SftpFile> sftp_;
const SftpSession *session_{};
public:
explicit TransferFile(HINTERNET handle):ftp_(handle)
{
checkFileOperation(handle!=nullptr);
}
TransferFile(SftpFile file,const SftpSession &session):sftp_(std::move(file)),session_(&session){}
size_t read(unsigned char *data,size_t bytes)
{
if(sftp_)
{
const auto result=libssh2_sftp_read(sftp_->handle,reinterpret_cast<char*>(data),bytes);
if(result<0) session_->operationError("Could not read the SFTP file");
return static_cast<size_t>(result);
}
DWORD result{};
checkFileOperation(InternetReadFile(ftp_.value,data,static_cast<DWORD>(bytes),&result));
return result;
}
size_t write(const unsigned char *data,size_t bytes)
{
if(sftp_)
{
const auto result=libssh2_sftp_write(sftp_->handle,reinterpret_cast<const char*>(data),bytes);
if(result<0) session_->operationError("Could not write the staged SFTP file");
return static_cast<size_t>(result);
}
DWORD result{};
checkFileOperation(InternetWriteFile(ftp_.value,data,static_cast<DWORD>(bytes),&result));
return result;
}
void close()
{
if(sftp_)
{
auto *handle=std::exchange(sftp_->handle,nullptr);
if(libssh2_sftp_close_handle(handle)) session_->operationError("Could not close the staged SFTP file");
return;
}
checkFileOperation(InternetCloseHandle(ftp_.value));
ftp_.value=nullptr;
}
};
class TransferSession
{
std::optional<FtpSession> ftp_;
std::optional<SftpSession> sftp_;
public:
explicit TransferSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
std::stop_token stop={})
{
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile,access,stop);
else ftp_.emplace(profile);
}
const wchar_t *label() const {return transferProtocolName(sftp_?TransferProtocol::sftp:TransferProtocol::ftp);}
fs::path initialDirectory()
{
return sftp_?sftp_->initialDirectory():ftp_->initialDirectory();
}
DWORD list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop={})
{
return sftp_?sftp_->list(directory,visit,stop):listFtpDirectory(*ftp_,directory,visit,stop);
}
TransferFile open(const fs::path &path,bool write)
{
if(sftp_) return TransferFile(sftp_->open(path,write),*sftp_);
ftp_->setDirectory(path.parent_path());
const auto name=ftp_->encodeName(path.filename());
return TransferFile(FtpOpenFileA(ftp_->handle(),name.c_str(),write?GENERIC_WRITE:GENERIC_READ,ftpCopyFlags,0));
}
void makeDirectory(const fs::path &path)
{
if(sftp_) {sftp_->makeDirectory(path);return;}
ftp_->setDirectory(path.parent_path());
checkFileOperation(FtpCreateDirectoryA(ftp_->handle(),ftp_->encodeName(path.filename()).c_str()));
}
void remove(const fs::path &path,bool directory)
{
if(sftp_) {sftp_->remove(path,directory);return;}
ftp_->setDirectory(path.parent_path());
const auto name=ftp_->encodeName(path.filename());
checkFileOperation(directory?FtpRemoveDirectoryA(ftp_->handle(),name.c_str()):
FtpDeleteFileA(ftp_->handle(),name.c_str()));
}
void preserveModificationTime(const fs::path &path,uint64_t modified)
{
if(sftp_ && modified) sftp_->preserveModificationTime(path,modified);
}
void prepareReplacement(const fs::path &staged,const fs::path &existing)
{
if(sftp_) sftp_->prepareReplacement(staged,existing);
}
void rename(const fs::path &from,const fs::path &to,bool replace=false)
{
if(sftp_) {sftp_->rename(from,to,replace);return;}
ftp_->setDirectory(from.parent_path());
const auto source=ftp_->encodeName(from.filename()),target=ftp_->encodeName(to.filename());
checkFileOperation(FtpRenameFileA(ftp_->handle(),source.c_str(),target.c_str()));
}
};
+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)
{
+23 -82
View File
@@ -9,7 +9,7 @@
#include "lan_layout.h"
#include "lan_network.h"
#include "lan_wake.h"
#include "lan_clients.h"
#include "lan_client_files.h"
#include <atomic>
#include <mutex>
#include <thread>
@@ -183,24 +183,16 @@ struct LanService::Impl
~Impl() { clients.stop(); stop(); }
void startClients()
{
clients.start([this](const Json &request, const auto &allowed, const auto &send) {
const auto action = request.at("action").get<std::string>();
auto reply = [&](const Json &result) {
const auto text = result.dump();
send(text.data(), DWORD(text.size()));
clients.start([this](const Json &request, const auto &allowed, const auto &send, const auto &receive, const auto &asCaller) {
const auto reachable = [&](const Peer &peer) {
return enabled && peer.files && peer.verified && GetTickCount64() - peer.verified < lan::PeerLifetime;
};
lan::FilesPeer target;
std::string local, key;
auto machines = Json::array();
if (request.at("action") == "peers")
{
std::lock_guard gate(commandGate);
std::lock_guard lock(mutex);
const auto now = GetTickCount64();
const auto reachable = [&](const Peer &peer) {
return enabled && peer.files && peer.verified && now - peer.verified < lan::PeerLifetime;
};
if (action == "peers")
auto machines = Json::array();
{
std::lock_guard gate(commandGate);
std::lock_guard lock(mutex);
refreshFiles = true;
for (const auto &[peer, pair] : trusted.items())
{
@@ -209,74 +201,23 @@ struct LanService::Impl
{"online", found != peers.end() && reachable(found->second)}});
}
}
else
{
if (action != "drives" && action != "list" && action != "download")
throw std::runtime_error("Unsupported LAN client operation.");
const auto peer = request.at("peer").get<std::string>();
const auto found = peers.find(peer);
if (!trusted.contains(peer) || found == peers.end() || !reachable(found->second))
throw std::runtime_error("The paired computer is offline or file browsing is unavailable.");
char address[INET_ADDRSTRLEN]{};
auto ip = found->second.address.sin_addr;
if (!InetNtopA(AF_INET, &ip, address, sizeof(address)))
throw std::runtime_error("The paired computer has no usable address.");
target = {peer, address, wide(found->second.name), lan::FilesPort, true};
local = id;
key = trusted.at(peer).at("key").get<std::string>();
}
}
if (action == "peers")
{
reply(machines);
const auto result = machines.dump();
send(result.data(), DWORD(result.size()));
return;
}
lan::FilesConnection connection(target, local, key);
if (action == "drives")
{
const auto result = connection.call({{"action", "drives"}});
lan::checkFileReply(result);
reply(result.at("drives"));
return;
}
const auto path = lan::filePath(request.at("path"));
if (action == "list")
{
auto page = connection.call(lan::fileRequest("list", path));
auto entries = Json::array();
size_t bytes{};
for (;;)
{
lan::checkFileReply(page);
for (auto &entry : page.at("entries"))
{
bytes += entry.dump().size() + 1;
if (bytes > 8 * 1024 * 1024) throw std::runtime_error("The remote directory listing is too large.");
entries.push_back(std::move(entry));
}
if (!page.at("more").get<bool>()) break;
allowed();
page = connection.call({{"action", "listNext"}});
}
reply(entries);
return;
}
const auto file = connection.call(lan::fileRequest("stat", path));
lan::checkFileReply(file);
auto open = lan::fileRequest("openRead", path);
open["size"] = file.at("size");
open["modified"] = file.at("modified");
lan::checkFileReply(connection.call(open));
reply({{"size", file.at("size")}});
for (;;)
{
allowed();
const auto chunk = connection.call({{"action", "read"}});
lan::checkFileReply(chunk);
const auto &data = chunk.at("data").get_binary();
send(data.data(), DWORD(data.size()));
if (data.empty()) break;
}
lan::routeClientFiles(request, allowed, send, receive, asCaller, [&](const std::string &peer) {
std::lock_guard gate(commandGate);
std::lock_guard lock(mutex);
const auto found = peers.find(peer);
if (!trusted.contains(peer) || found == peers.end() || !reachable(found->second))
throw std::runtime_error("The paired computer is offline or file browsing is unavailable.");
char address[INET_ADDRSTRLEN]{};
auto ip = found->second.address.sin_addr;
if (!InetNtopA(AF_INET, &ip, address, sizeof(address)))
throw std::runtime_error("The paired computer has no usable address.");
return lan::ClientFilesPeer{{peer, address, wide(found->second.name), lan::FilesPort, true},
id, trusted.at(peer).at("key").get<std::string>()};
});
});
}
void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted},
+380
View File
@@ -0,0 +1,380 @@
#include "lan_client_files.h"
#include "files_win32_directory.h"
namespace ks::lan
{
namespace
{
namespace fs = std::filesystem;
using Access = ClientFilesAccess;
Json checked(FilesConnection &connection, const Json &request, const FileProgress &progress = {})
{
auto reply = connection.call(request, progress);
checkFileReply(reply);
return reply;
}
void sendJson(const ClientSend &send, const Json &reply)
{
const auto text = reply.dump();
send(text.data(), DWORD(text.size()));
}
void revision(Json &request, const Json &file)
{
request["size"] = file.at("size");
request["modified"] = file.at("modified");
}
Json stat(FilesConnection &host, const fs::path &path)
{
return checked(host, fileRequest("stat", path));
}
unsigned hostRevision(FilesConnection &host)
{
const auto result = host.call(fileRequest("fileCapabilities", L"C:\\"));
if (result.at("error") == ERROR_INVALID_FUNCTION) return 0;
checkFileReply(result);
return result.at("revision").get<unsigned>();
}
void requireCurrentHost(FilesConnection &host)
{
if (!hostRevision(host)) throw std::runtime_error("Update the paired computer to use this operation.");
}
bool granted(const ClientCheck &check, Access access)
{
try { check(access); return true; }
catch (const std::runtime_error &) { check(Access::Browse); return false; }
}
Json capabilities(bool write, bool erase, unsigned host)
{
return {{"protocol", 2}, {"hostRevision", host}, {"write", write && host},
{"delete", erase && host}, {"move", write && erase && host},
{"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0}};
}
fs::path itemPath(const Json &value)
{
auto path = filePath(value).lexically_normal();
// Only regular drive paths reach remote mutations; never allow operating on a drive root.
const auto root = path.root_name().native();
if (root.size() != 2 || root[1] != L':' || !path.is_absolute() || path.filename().empty())
throw std::runtime_error("Choose a file or folder below a drive root.");
for (const auto &part : path.relative_path())
if (!files::validWindowsFileName(part.native()))
throw std::runtime_error("Invalid Windows file name.");
return path;
}
bool directory(const Json &item) { return item.at("attributes").get<DWORD>() & FILE_ATTRIBUTE_DIRECTORY; }
bool reparse(const Json &item) { return item.at("attributes").get<DWORD>() & FILE_ATTRIBUTE_REPARSE_POINT; }
void requireRegular(const Json &item)
{
if (reparse(item)) throw std::runtime_error("A file tree cannot include a junction or symbolic link.");
}
Json list(FilesConnection &host, const fs::path &path, const std::function<void()> &guard)
{
auto page = host.call(fileRequest("list", path));
auto entries = Json::array();
size_t bytes{};
for (;;)
{
checkFileReply(page);
for (auto &entry : page.at("entries"))
{
bytes += entry.dump().size() + 1;
if (bytes > 8 * 1024 * 1024) throw std::runtime_error("The remote directory listing is too large.");
entries.push_back(std::move(entry));
}
if (!page.at("more").get<bool>()) return entries;
guard();
page = host.call({{"action", "listNext"}});
}
}
bool absent(const Json &result)
{
return result.at("error") == ERROR_FILE_NOT_FOUND || result.at("error") == ERROR_PATH_NOT_FOUND;
}
bool sameOrBelow(const fs::path &parent, const fs::path &candidate)
{
auto part = candidate.begin();
for (const auto &component : parent)
{
if (part == candidate.end() || CompareStringOrdinal(component.c_str(), -1, part->c_str(), -1, TRUE) != CSTR_EQUAL)
return false;
++part;
}
return true;
}
fs::path canonical(FilesConnection &host, const fs::path &path)
{
return filePath(checked(host, fileRequest("canonical", path)).at("path")).lexically_normal();
}
class ClientTransfer
{
FilesConnection &source, &target;
const bool sameHost, move;
const std::string sourceId, conflict;
const std::function<void()> guard;
const ClientSend &send;
const ClientReceive &receive;
uint64_t completed{}, skipped{};
struct Removal { fs::path path; Json metadata; };
std::vector<Removal> removals;
void progress(const fs::path &path, uint64_t done, uint64_t total, const char *phase = "copy")
{
guard();
sendJson(send, {{"type", "progress"}, {"phase", phase}, {"path", utf8(path.native())},
{"done", done}, {"total", total},
{"completed", completed}, {"skipped", skipped}});
const auto result = Json::parse(receive(256));
if (!result.at("continue").get<bool>()) throw std::system_error(ERROR_CANCELLED, std::system_category());
guard();
}
bool copy(const fs::path &from, const fs::path &to, unsigned depth)
{
if (depth > 256) throw std::runtime_error("The file tree is too deep.");
progress(from, 0, 0);
const auto original = stat(source, from);
requireRegular(original);
const auto existing = target.call(fileRequest("stat", to));
const bool found = !absent(existing);
if (found)
{
checkFileReply(existing);
if (conflict == "skip") { ++skipped; return false; }
if (conflict != "replace" || directory(original) != directory(existing))
throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category());
requireRegular(existing);
}
bool whole = true;
if (directory(original))
{
if (!found)
{
guard();
checked(target, fileRequest("mkdir", to));
}
for (const auto &entry : list(source, from, guard))
{
const auto child = wide(entry.at("name").get<std::string>());
if (!files::validWindowsFileName(child)) throw std::runtime_error("Invalid directory entry.");
if (!copy(from / child, to / child, depth + 1)) whole = false;
}
}
else
{
ULONGLONG last{};
const auto onProgress = [&](uint64_t done, uint64_t total) {
guard();
const auto now = GetTickCount64();
if (!last || now - last >= 200 || done == total)
{
progress(from, done, total);
last = now;
}
return true;
};
const FileRevision expected{existing.value("size", uint64_t{}), existing.value("modified", uint64_t{})};
if (sameHost)
{
auto request = fileRequest("copy", from);
request.update({{"target", utf8(to.native())}, {"replace", found}, {"append", false}, {"resume", false}});
revision(request, original);
if (found) request.update({{"expectedSize", expected.size}, {"expectedModified", expected.modified}});
checked(source, request, onProgress);
}
else streamFile(source, target, sourceId, from, to, original.at("size"), original.at("modified"),
found, false, onProgress, found ? &expected : nullptr, false);
}
++completed;
if (move && whole) removals.push_back({from, original});
return whole;
}
public:
ClientTransfer(FilesConnection &source, FilesConnection &target, bool sameHost, bool move,
const std::string &sourceId, const std::string &conflict, const std::function<void()> &guard,
const ClientSend &send, const ClientReceive &receive)
: source(source), target(target), sameHost(sameHost), move(move), sourceId(sourceId), conflict(conflict),
guard(guard), send(send), receive(receive) {}
void run(const fs::path &from, const fs::path &to)
{
if (conflict != "fail" && conflict != "skip" && conflict != "replace")
throw std::runtime_error("Unknown conflict policy.");
if (sameHost)
{
const auto sourcePath = canonical(source, from);
const auto targetPath = canonical(target, to);
if (sameOrBelow(sourcePath, targetPath) || sameOrBelow(targetPath, sourcePath))
throw std::runtime_error("Source and destination paths overlap.");
}
copy(from, to, 0);
if (!removals.empty()) progress(from, 0, 0, "remove");
for (const auto &entry : removals)
{
guard();
auto request = fileRequest(directory(entry.metadata) ? "rmdir" : "remove", entry.path);
if (!directory(entry.metadata)) revision(request, entry.metadata);
checked(source, request);
}
sendJson(send, {{"type", "complete"}, {"completed", completed}, {"skipped", skipped}});
}
};
void read(FilesConnection &host, const fs::path &path, const Json &request, bool legacy, const ClientSend &send,
const std::function<void()> &guard)
{
const auto file = stat(host, path);
auto open = fileRequest("openRead", path);
revision(open, file);
if (request.contains("expected") &&
(request.at("expected").at("size") != file.at("size") ||
request.at("expected").at("modified") != file.at("modified")))
throw std::system_error(ERROR_FILE_INVALID, std::system_category());
guard();
checked(host, open);
sendJson(send, legacy ? Json{{"size", file.at("size")}} : file);
for (;;)
{
guard();
const auto chunk = checked(host, {{"action", "read"}});
const auto &data = chunk.at("data").get_binary();
send(data.data(), DWORD(data.size()));
if (data.empty()) return;
}
}
void write(FilesConnection &host, const fs::path &path, const Json &request, const ClientSend &send,
const ClientReceive &receive, const std::function<void()> &guard)
{
const auto size = request.at("size").get<uint64_t>();
auto upload = fileRequest("openWrite", path);
upload.update({{"size", size}, {"transfer", randomHex(32)}, {"resume", false}});
guard();
checked(host, upload);
sendJson(send, {{"type", "ready"}});
uint64_t done{};
for (;;)
{
auto data = receive(DWORD(FileChunk));
guard();
if (data.empty()) break;
if (data.size() > size - done) throw std::runtime_error("The upload exceeds the declared size.");
done += data.size();
checked(host, {{"action", "write"}, {"data", Json::binary(std::move(data))}});
}
if (done != size) throw std::runtime_error("The upload ended before the declared size.");
FILETIME now{};
GetSystemTimeAsFileTime(&now);
Json commit{{"action", "commit"}, {"replace", false},
{"modified", uint64_t(now.dwLowDateTime) | (uint64_t(now.dwHighDateTime) << 32)}};
if (request.contains("expected"))
{
commit["action"] = "commitEdit";
commit["expectedSize"] = request.at("expected").at("size");
commit["expectedModified"] = request.at("expected").at("modified");
}
guard();
checked(host, commit);
sendJson(send, stat(host, path));
}
void removeTree(FilesConnection &host, const fs::path &path, bool recursive, unsigned depth,
const std::function<void()> &guard)
{
if (depth > 256) throw std::runtime_error("The file tree is too deep.");
guard();
const auto item = stat(host, path);
if (recursive && directory(item) && !reparse(item))
{
for (const auto &entry : list(host, path, guard))
{
const auto child = wide(entry.at("name").get<std::string>());
if (!files::validWindowsFileName(child)) throw std::runtime_error("Invalid directory entry.");
removeTree(host, path / child, true, depth + 1, guard);
}
}
auto request = fileRequest(directory(item) ? "rmdir" : "remove", path);
if (!directory(item) && !reparse(item)) revision(request, item);
guard();
checked(host, request);
}
}
void routeClientFiles(const Json &request, const ClientCheck &check, const ClientSend &send,
const ClientReceive &receive, const ClientAsCaller &asCaller, const ClientFilesResolve &resolve)
{
const auto action = request.at("action").get<std::string>();
if (action == "capabilities" && !request.contains("peer"))
{
sendJson(send, capabilities(granted(check, Access::Write), granted(check, Access::Delete), 1));
return;
}
if (action == "transfer")
{
const auto &from = request.at("source");
const auto &to = request.at("target");
const bool move = request.value("move", false);
const auto guard = [&] { check(move ? Access::Move : Access::Write); };
guard();
const bool fromLocal = from.at("peer").is_null(), toLocal = to.at("peer").is_null();
if (fromLocal && toLocal) throw std::runtime_error("At least one path must be on a paired computer.");
const auto first = fromLocal ? ClientFilesPeer{} : resolve(from.at("peer"));
const auto second = toLocal ? ClientFilesPeer{} : resolve(to.at("peer"));
const auto copy = [&] {
const auto open = [](const ClientFilesPeer &peer) {
if (peer.peer.id.empty()) return std::make_unique<FilesConnection>();
auto host = std::make_unique<FilesConnection>(peer.peer, peer.localId, peer.key);
requireCurrentHost(*host);
return host;
};
const auto source = open(first), target = open(second);
ClientTransfer(*source, *target, first.peer.id == second.peer.id, move, first.peer.id,
request.value("conflict", "fail"), guard, send, receive)
.run(itemPath(from.at("path")), itemPath(to.at("path")));
};
if (fromLocal || toLocal) asCaller(copy);
else copy();
return;
}
auto access = Access::Browse;
if (action == "mkdir" || action == "rename" || action == "writeFile") access = Access::Write;
else if (action == "recycle" || action == "delete") access = Access::Delete;
else if (action != "drives" && action != "list" && action != "download" && action != "stat" &&
action != "readFile" && action != "capabilities")
throw std::runtime_error("Unsupported LAN client operation.");
const auto guard = [&] { check(access); };
guard();
const auto resolved = resolve(request.at("peer"));
FilesConnection host(resolved.peer, resolved.localId, resolved.key);
if (action == "capabilities")
sendJson(send, capabilities(granted(check, Access::Write), granted(check, Access::Delete), hostRevision(host)));
else if (action == "drives") sendJson(send, checked(host, {{"action", "drives"}}).at("drives"));
else if (action == "list") sendJson(send, list(host, filePath(request.at("path")), guard));
else if (action == "download") read(host, filePath(request.at("path")), Json::object(), true, send, guard);
else if (action == "stat") sendJson(send, stat(host, filePath(request.at("path"))));
else
{
requireCurrentHost(host);
const auto path = itemPath(request.at("path"));
if (action == "readFile") read(host, path, request, false, send, guard);
else if (action == "writeFile") write(host, path, request, send, receive, guard);
else if (action == "delete")
{
removeTree(host, path, request.value("recursive", false), 0, guard);
sendJson(send, {{"error", 0}});
}
else
{
auto operation = fileRequest(action == "rename" ? "move" : action, path);
if (action == "rename")
{
const auto name = wide(request.at("name").get<std::string>());
if (!files::validWindowsFileName(name)) throw std::runtime_error("Invalid Windows file name.");
operation.update({{"target", utf8((path.parent_path() / name).native())}, {"replace", false}});
}
guard();
sendJson(send, checked(host, operation));
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include "lan_clients.h"
#include "lan_files.h"
namespace ks::lan
{
struct ClientFilesPeer
{
FilesPeer peer;
std::string localId, key;
};
using ClientFilesResolve = std::function<ClientFilesPeer(const std::string &)>;
void routeClientFiles(const Json &request, const ClientCheck &check, const ClientSend &send,
const ClientReceive &receive, const ClientAsCaller &asCaller, const ClientFilesResolve &resolve);
}
+47 -10
View File
@@ -9,6 +9,12 @@
namespace ks::lan
{
enum class ClientFilesAccess : unsigned { Browse = 0, Write = 1, Delete = 2, Move = 3 };
using ClientCheck = std::function<void(ClientFilesAccess)>;
using ClientSend = std::function<void(const void *, DWORD)>;
using ClientReceive = std::function<Bytes(DWORD)>;
using ClientAsCaller = std::function<void(const std::function<void()> &)>;
class LanClients
{
struct Handle
@@ -106,8 +112,7 @@ class LanClients
{
return std::filesystem::exists(store) ? Json::parse(unprotect(readFile(store, 256 * 1024))) : Json::array();
}
using Rule = std::function<void()>;
Rule authorize(HANDLE pipe) const
ClientCheck authorize(HANDLE pipe) const
{
ULONG pid{};
if (!GetNamedPipeClientProcessId(pipe, &pid))
@@ -123,17 +128,25 @@ class LanClients
auto image = std::make_shared<ClientImage>(std::wstring(filename, length));
if (CompareFileTime(&image->modified, &started) > 0)
throw std::runtime_error("Restart the client after replacing its executable.");
Rule check = [this, process, image] {
ClientCheck check = [this, pipe, process, image](ClientFilesAccess access) {
if (WaitForSingleObject(stopped.value, 0) != WAIT_TIMEOUT ||
WaitForSingleObject(process->value, 0) != WAIT_TIMEOUT)
WaitForSingleObject(process->value, 0) != WAIT_TIMEOUT ||
!PeekNamedPipe(pipe, nullptr, 0, nullptr, nullptr, nullptr))
throw std::runtime_error("The local client disconnected.");
std::lock_guard lock(storeMutex);
for (const auto &entry : clients())
if (!_wcsicmp(wide(entry.at("path").get<std::string>()).c_str(), image->path.c_str()) &&
entry.at("sha256") == image->digest) return;
entry.at("sha256") == image->digest)
{
const auto mask = static_cast<unsigned>(access);
if (((mask & 1) && !entry.value("writeFiles", false)) ||
((mask & 2) && !entry.value("deleteFiles", false)))
throw std::runtime_error("Grant the required file permission in Trusted clients.");
return;
}
throw std::runtime_error("Authorize this executable in KSwitcher → Computers → Trusted clients.");
};
check();
check(ClientFilesAccess::Browse);
return check;
}
struct LocalMemory
@@ -141,8 +154,7 @@ class LanClients
void *value{};
~LocalMemory() { if (value) LocalFree(value); }
};
using Send = std::function<void(const void *, DWORD)>;
using Route = std::function<void(const Json &, const Rule &, const Send &)>;
using Route = std::function<void(const Json &, const ClientCheck &, const ClientSend &, const ClientReceive &, const ClientAsCaller &)>;
void serve(const Route &route, const std::wstring &instance) const
{
HANDLE rawToken{};
@@ -194,8 +206,32 @@ class LanClients
{
auto check = authorize(pipe.value);
route(Json::parse(request), check, [&](const void *data, DWORD bytes) {
check();
check(ClientFilesAccess::Browse);
if (!writeFrame(pipe.value, data, bytes)) throw std::runtime_error("The local client disconnected.");
}, [&](DWORD maximum) {
check(ClientFilesAccess::Browse);
DWORD bytes{};
if (!io(pipe.value, &bytes, sizeof(bytes), false) || bytes > maximum)
throw std::runtime_error("The local client disconnected or sent an invalid frame.");
Bytes data(bytes);
if (bytes && !io(pipe.value, data.data(), bytes, false))
throw std::runtime_error("The local client disconnected.");
return data;
}, [&](const std::function<void()> &operation) {
if (!ImpersonateNamedPipeClient(pipe.value))
throw std::runtime_error("The pipe must allow Windows client impersonation for local paths.");
struct Revert
{
~Revert() { if (!RevertToSelf()) std::terminate(); }
} revert;
Handle caller;
SECURITY_IMPERSONATION_LEVEL level{};
DWORD length{};
if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &caller.value) ||
!GetTokenInformation(caller.value, TokenImpersonationLevel, &level, sizeof(level), &length) ||
level < SecurityImpersonation)
throw std::runtime_error("The pipe must allow Windows client impersonation for local paths.");
operation();
});
}
}
@@ -235,7 +271,8 @@ public:
return !_wcsicmp(wide(entry.at("path").template get<std::string>()).c_str(), image.path.c_str());
});
if (entries.size() >= 64) throw std::runtime_error("The trusted client list is full.");
entries.push_back({{"path", utf8(image.path)}, {"sha256", image.digest}});
entries.push_back({{"path", utf8(image.path)}, {"sha256", image.digest},
{"writeFiles", request.value("writeFiles", false)}, {"deleteFiles", request.value("deleteFiles", false)}});
}
else
{
+104 -17
View File
@@ -8,6 +8,7 @@
#include <bcrypt.h>
#include <wincrypt.h>
#include <sddl.h>
#include <aclapi.h>
#include <winsafer.h>
#include <cstring>
#include <mutex>
@@ -115,6 +116,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 +124,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();
@@ -661,6 +680,7 @@ public:
}
return reply;
}
if(action=="fileCapabilities") return {{"error",0},{"revision",1},{"copyMetadata",true}};
if(action=="listNext") return listNext();
if(action=="read")
{
@@ -751,6 +771,67 @@ public:
const auto canonical=fs::weakly_canonical(name,error);
return error?failure(error.value()):Json{{"error",0},{"path",utf8(canonical.native())}};
}
if(action=="copyPermissions")
{
DWORD size{};
GetFileSecurityW(name.c_str(),DACL_SECURITY_INFORMATION,nullptr,0,&size);
if(!size || GetLastError()!=ERROR_INSUFFICIENT_BUFFER) return failure();
Bytes descriptor(size);
if(!GetFileSecurityW(name.c_str(),DACL_SECURITY_INFORMATION,descriptor.data(),size,&size)) return failure();
LPWSTR sddl{};
if(!ConvertSecurityDescriptorToStringSecurityDescriptorW(descriptor.data(),SDDL_REVISION_1,
DACL_SECURITY_INFORMATION,&sddl,nullptr)) return failure();
const auto value=utf8(sddl);
LocalFree(sddl);
return {{"error",0},{"permissions",value}};
}
if(action=="applyCopyMetadata")
{
if(request.contains("modified"))
{
FileHandle file{CreateFileW(name.c_str(),FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return failure();
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file.value,&info)) return failure();
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT) return failure(ERROR_NOT_SUPPORTED);
auto stamp=request.at("modified").get<uint64_t>();
FILETIME time{static_cast<DWORD>(stamp),static_cast<DWORD>(stamp>>32)};
if(!stamp) GetSystemTimeAsFileTime(&time);
if(!SetFileTime(file.value,nullptr,nullptr,&time)) return failure();
}
if(request.contains("permissions"))
{
FileHandle file{CreateFileW(name.c_str(),FILE_READ_ATTRIBUTES|READ_CONTROL|WRITE_DAC,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return failure();
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file.value,&info)) return failure();
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT) return failure(ERROR_NOT_SUPPORTED);
PSECURITY_DESCRIPTOR descriptor{};
const auto sddl=wide(request.at("permissions").get<std::string>());
if(!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(),SDDL_REVISION_1,
&descriptor,nullptr)) return failure();
SECURITY_DESCRIPTOR_CONTROL control{};
DWORD revision{};
BOOL present{}, defaulted{};
PACL acl{};
auto error=DWORD(ERROR_SUCCESS);
if(!GetSecurityDescriptorDacl(descriptor,&present,&acl,&defaulted) || !present ||
!GetSecurityDescriptorControl(descriptor,&control,&revision)) error=ERROR_INVALID_DATA;
else
{
auto security=DACL_SECURITY_INFORMATION|((control&SE_DACL_PROTECTED)?
PROTECTED_DACL_SECURITY_INFORMATION:UNPROTECTED_DACL_SECURITY_INFORMATION);
error=SetSecurityInfo(file.value,SE_FILE_OBJECT,security,nullptr,nullptr,acl,nullptr);
}
LocalFree(descriptor);
if(error) return failure(error);
}
return ok();
}
if(action=="mkdir") return CreateDirectoryW(name.c_str(),nullptr)?ok():failure();
if(action=="mkdir-link")
{
@@ -806,8 +887,11 @@ public:
{
// Both streams execute inside the serving process.
FilesConnection source,target;
const auto edit=request.contains("expectedSize");
const FileRevision expected{request.value("expectedSize",uint64_t{}),
request.value("expectedModified",uint64_t{})};
streamFile(source,target,"same host",name,destination,request.at("size"),request.at("modified"),
request.at("replace"),request.at("append"),progress);
request.at("replace"),request.at("append"),progress,edit?&expected:nullptr,request.value("resume",true));
return ok();
}
return copy(name,destination,request.at("replace"),request.at("append"),progress);
@@ -838,7 +922,8 @@ public:
expectedSize=request.at("size").get<uint64_t>();
const bool append=request.value("append",false);
appendBase=0;
auto staging=target.parent_path()/wide(".kswitcher-"+transfer+".partial");
const bool resume=request.value("resume",true);
const auto staging=target.parent_path()/wide(".kswitcher-"+transfer+".partial");
FileHandle original;
if(append)
{
@@ -848,7 +933,7 @@ public:
if(!GetFileInformationByHandle(original.value,&info)) return failure();
appendBase=fileSize(info.nFileSizeHigh,info.nFileSizeLow);
}
output.value=CreateFileW(staging.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_ALWAYS,
output.value=CreateFileW(staging.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,resume?OPEN_ALWAYS:CREATE_NEW,
FILE_ATTRIBUTE_HIDDEN|FILE_FLAG_OPEN_REPARSE_POINT,nullptr);
if(output.value==INVALID_HANDLE_VALUE) return failure();
const bool created=GetLastError()!=ERROR_ALREADY_EXISTS;
@@ -857,7 +942,7 @@ public:
if(info.nNumberOfLinks!=1 || (info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)))
return failure(ERROR_ACCESS_DENIED);
temporary=staging;
resumable=true;
resumable=resume;
if(created && appendBase)
{
Bytes buffer(FileChunk);
@@ -897,7 +982,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 +990,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 +1015,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)
@@ -952,7 +1038,7 @@ Json FilesConnection::call(const Json &request,const FileProgress &progress)
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination)
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination,bool resumable)
{
auto openSource=fileRequest("openRead",from);
openSource["size"]=size;
@@ -963,7 +1049,8 @@ void streamFile(FilesConnection &source,FilesConnection &target,const std::strin
upload["size"]=size;
const auto identity=Json::array({sourceId,ks::utf8(from.native()),ks::utf8(to.native()),
size,modified,append});
upload["transfer"]=ks::lan::mac("KSwitcher partial v1",identity.dump());
upload["transfer"]=resumable?ks::lan::mac("KSwitcher partial v1",identity.dump()):randomHex(32);
upload["resume"]=resumable;
uint64_t done=0;
const auto resumeProgress=[&](uint64_t,uint64_t){return !progress || progress(done,size);};
try
+4 -3
View File
@@ -23,15 +23,16 @@ 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 = {});
};
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr);
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr,
bool resumable=true);
DWORD runRemoteCommand(FilesConnection &host,const std::filesystem::path &directory,std::wstring_view command,
const std::function<void(std::string_view)> &output,std::stop_token stop={});
+43 -8
View File
@@ -54,6 +54,16 @@ struct LanClientsView
LanView *lan{};
nlohmann::json entries, saved;
};
void selectLanClient(HWND window, const LanClientsView &view, LRESULT index)
{
const bool selected = index >= 0 && size_t(index) < view.entries.size();
EnableWindow(GetDlgItem(window, 734), selected);
EnableWindow(GetDlgItem(window, 736), selected);
EnableWindow(GetDlgItem(window, 737), selected);
for (const auto &[id, key] : {std::pair{736, "writeFiles"}, std::pair{737, "deleteFiles"}})
SendDlgItemMessageW(window, id, BM_SETCHECK,
selected && view.entries[size_t(index)].value(key, false) ? BST_CHECKED : BST_UNCHECKED, 0);
}
void refreshLanClients(HWND window, LanClientsView &view)
{
view.entries = view.saved;
@@ -75,7 +85,7 @@ void refreshLanClients(HWND window, LanClientsView &view)
if (width > SendDlgItemMessageW(window, 732, LB_GETHORIZONTALEXTENT, 0, 0))
SendDlgItemMessageW(window, 732, LB_SETHORIZONTALEXTENT, width, 0);
}
EnableWindow(GetDlgItem(window, 734), FALSE);
selectLanClient(window, view, LB_ERR);
}
LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
{
@@ -100,7 +110,7 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
const auto index = SendDlgItemMessageW(window, 732, LB_GETCURSEL, 0, 0);
if (id == 732 && HIWORD(wp) == LBN_SELCHANGE)
{
EnableWindow(GetDlgItem(window, 734), index != LB_ERR);
selectLanClient(window, *view, index);
return 0;
}
try
@@ -116,7 +126,9 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
const auto canonical = entry.at("path").get<std::string>();
const auto key = utf8(lower(wide(canonical)));
auto &changes = view->lan->draft["clients"];
if (std::find(view->saved.begin(), view->saved.end(), entry) == view->saved.end())
if (std::none_of(view->saved.begin(), view->saved.end(), [&](const auto &saved) {
return saved.at("path") == entry.at("path") && saved.at("sha256") == entry.at("sha256");
}))
changes[key] = {{"action", "trustClient"}, {"path", canonical}, {"sha256", entry.at("sha256")}};
else if (changes.is_object()) changes.erase(key);
if (changes.empty()) view->lan->draft.erase("clients");
@@ -125,6 +137,27 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
}
return 0;
}
if ((id == 736 || id == 737) && index >= 0 && size_t(index) < view->entries.size())
{
auto entry = view->entries[size_t(index)];
const auto *permission = id == 736 ? "writeFiles" : "deleteFiles";
const auto checked = SendDlgItemMessageW(window, id, BM_GETCHECK, 0, 0) == BST_CHECKED;
if (checked && MessageBoxW(window, id == 736 ?
L"Allow this executable to create, rename, copy and overwrite files on paired computers?" :
L"Allow this executable to recycle and permanently delete files on paired computers?",
L"Change trusted client permissions", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES)
{
selectLanClient(window, *view, index);
return 0;
}
entry["action"] = "trustClient";
entry[permission] = checked;
const auto key = utf8(lower(wide(entry.at("path").get<std::string>())));
view->lan->draft["clients"][key] = entry;
view->entries[size_t(index)] = std::move(entry);
refreshLanFooter(*view->lan);
return 0;
}
if (id == 734 && index >= 0 && size_t(index) < view->entries.size())
{
const auto path = view->entries[size_t(index)].at("path").get<std::string>();
@@ -149,17 +182,19 @@ LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
}
void showLanClients(HWND parent, LanView &lan)
{
auto window = makeWindow(*lan.app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 280, 0, false);
auto window = makeWindow(*lan.app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 318, 0, false);
SetWindowLongPtrW(window, GWLP_HWNDPARENT, reinterpret_cast<LONG_PTR>(parent));
auto view = new LanClientsView{&lan};
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(view));
label(window, L"Trusted executables can browse and download files from paired computers.", 16, 14, 578);
control(window, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | WS_BORDER | LBS_NOTIFY |
LBS_NOINTEGRALHEIGHT, 732, 16, 42, 578, 152);
label(window, L"After updating an executable, add it again and click Apply or Save in Settings.", 16, 202, 578);
button(window, L"&Add client…", 733, 16, 236, 126);
button(window, L"&Remove", 734, 150, 236, 110);
button(window, L"&Close", IDCANCEL, 494, 236, 100);
control(window, L"BUTTON", L"Allow &write", WS_TABSTOP | BS_AUTOCHECKBOX, 736, 16, 200, 150, 26);
control(window, L"BUTTON", L"Allow &delete", WS_TABSTOP | BS_AUTOCHECKBOX, 737, 182, 200, 150, 26);
label(window, L"Move requires both permissions. Click Apply or Save in Settings.", 16, 232, 578);
button(window, L"&Add client…", 733, 16, 271, 126);
button(window, L"&Remove", 734, 150, 271, 110);
button(window, L"&Close", IDCANCEL, 494, 271, 100);
try
{
view->saved = lanRequest(*lan.app, {{"action", "trustedClients"}});
+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'"';
}
}
+82 -1
View File
@@ -34,6 +34,20 @@ public static class FilesActivationUi {
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] static extern int GetSystemMetrics(int index);
[DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr window, IntPtr after,
int x, int y, int width, int height, uint flags);
public static void SizeTerminalWindow(IntPtr window) {
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
try {
if (!SetWindowPos(window, IntPtr.Zero, 20, 20, GetSystemMetrics(0) - 40,
GetSystemMetrics(1) - 100, 0x14))
throw new InvalidOperationException("Could not size the terminal test window.");
} finally {
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
}
}
public static uint ReadScreenCenter(IntPtr window) {
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
@@ -68,6 +82,21 @@ public static class FilesActivationUi {
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr Write(IntPtr window, uint msg, IntPtr w, string text);
[DllImport("shell32.dll")] public static extern void SHChangeNotify(int eventId, uint flags, IntPtr first, IntPtr second);
public static bool CompletionFollowsCaret(IntPtr input, IntPtr suggestions) {
var info = new GuiInfo { Size = Marshal.SizeOf(typeof(GuiInfo)) };
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
try {
Rect inputBounds, popup;
return GetGUIThreadInfo(GetWindowThreadProcessId(input, IntPtr.Zero), ref info) &&
info.Caret == input && GetWindowRect(input, out inputBounds) &&
GetWindowRect(suggestions, out popup) && popup.Bottom <= inputBounds.Top &&
info.CaretRect.Left > 0 &&
Math.Abs(inputBounds.Left + info.CaretRect.Left - popup.Left) <= 4;
} finally {
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
}
}
public static IntPtr Focus(IntPtr window) {
var info = new GuiInfo { Size = Marshal.SizeOf(typeof(GuiInfo)) };
if (!GetGUIThreadInfo(GetWindowThreadProcessId(window, IntPtr.Zero), ref info))
@@ -207,7 +236,7 @@ $extension = ".ksfiles$unique"
$progId = "KSwitcher.Files.Test.$unique"
$saved = @{}
$profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide',
'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement'
'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement', 'FontPoints'
$process = $null
$trace = $null
$webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
@@ -249,6 +278,7 @@ try {
$profile.SetValue('StatusFields', 3)
if($TerminalOnly){
$profile.SetValue('FontPoints',80,'DWord')
$terminalPage = Join-Path $app 'terminal/index.html'
$page = Get-Content -Raw -LiteralPath $terminalPage
$page = $page.Replace('<style>','<style media="not all">').Replace('src="terminal.js"','src="startup-fixture.js"')
@@ -279,6 +309,7 @@ function startTerminalFixture() {
$trace = Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
Wait-Until 'Files window' { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
$window = $process.MainWindowHandle
if($TerminalOnly){[FilesActivationUi]::SizeTerminalWindow($window)}
$left = [FilesActivationUi]::GetDlgItem($window, 102)
$right = [FilesActivationUi]::GetDlgItem($window, 103)
$status = [FilesActivationUi]::GetDlgItem($window, 144)
@@ -498,6 +529,56 @@ function startTerminalFixture() {
!(Read-Text $inputBox)
}
Write-Output 'Verified Enter from the terminal WebView runs the command exactly once.'
$keys.SendKeys('^o')
Wait-Until 'full-screen terminal prompt' { ![FilesActivationUi]::IsWindowVisible($left) }
$draft='чернетка термінала'
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-prompt-text' $draft
if ($LASTEXITCODE) { throw 'Could not type into the terminal WebView.' }
Wait-Until 'WebView input using the shared prompt' { (Read-Text $inputBox) -ceq $draft }
[void][FilesActivationUi]::PostMessage($inputBox,0x100,[IntPtr]38,[IntPtr]0)
Wait-Until 'the terminal recalling a command from the visible command line' { (Read-Text $inputBox) -ceq $command }
[void][FilesActivationUi]::PostMessage($inputBox,0x100,[IntPtr]40,[IntPtr]0)
Wait-Until 'Down restoring the in-progress draft' { (Read-Text $inputBox) -ceq $draft }
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'cd Test')
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]7,[IntPtr]7)
$suggestions=[FilesActivationUi]::FindWindowEx($window,[IntPtr]::Zero,'ListBox','Command suggestions')
Wait-Until 'PowerShell path completion in the full-screen prompt' {
[FilesActivationUi]::IsWindowVisible($suggestions)
}
if(![FilesActivationUi]::CompletionFollowsCaret($inputBox,$suggestions)){
throw 'The terminal suggestions must open above the editing caret.'
}
[void][FilesActivationUi]::PostMessage($inputBox,0x100,[IntPtr]9,[IntPtr]0)
Wait-Until 'Tab inserting the suggested path in the prompt' {
(Read-Text $inputBox) -like 'cd *Test folder*'
}
Press-Enter $inputBox
Wait-Until 'the prompt following cd while the file panels are hidden' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -eq "$leftDir\Test folder"
}
foreach($key in 'terminal-interrupt','Escape'){
$running=Join-Path $root "$key-running.txt"
$finished=Join-Path $root "$key-finished.txt"
Send-InteractiveTerminal "[IO.File]::WriteAllText('$running','started'); Start-Sleep -Seconds 45; [IO.File]::WriteAllText('$finished','unexpected')"
Wait-Until "a running PowerShell command for $key" { Test-Path -LiteralPath $running }
if($key -eq 'Escape'){
[void][FilesActivationUi]::PostMessage($inputBox,0x100,[IntPtr]27,[IntPtr]0)
} else {
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port $key
if ($LASTEXITCODE) { throw 'Could not send Ctrl+C to the terminal WebView.' }
}
$next=Join-Path $root "$key-next.txt"
Send-InteractiveTerminal "[IO.File]::WriteAllText('$next','ready')"
Wait-Until "PowerShell accepting a new command after $key" { Test-Path -LiteralPath $next }
if(Test-Path -LiteralPath $finished){throw "$key failed to interrupt the PowerShell command."}
}
Send-InteractiveTerminal 'cd ..'
Wait-Until 'the active panel returning to its original folder' {
(Read-Text ([FilesActivationUi]::GetDlgItem($window,142))) -eq $leftDir
}
$keys.SendKeys('^o')
Wait-Until 'file panes restored after editing in the terminal prompt' { [FilesActivationUi]::IsWindowVisible($left) }
Write-Output 'Verified terminal prompt typing, the shared history and completion, panel synchronization and interruption.'
# The left panel is already active after the working-directory check.
$folderRow = Find-Row $left '[Test folder]'
if ($folderRow -lt 0) { throw 'Missing folder for the terminal clipboard check.' }
+1
View File
@@ -24,6 +24,7 @@ public static class FilesCommandsUi {
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point);
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr window, IntPtr target, uint flags);
[DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
+55 -14
View File
@@ -5,7 +5,8 @@ Add-Type -AssemblyName System.Drawing
. "$PSScriptRoot/files_commands_ui.ps1"
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance'
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance',
'LeftFtpLocation', 'RightFtpLocation'
$saved = @{}
foreach ($name in $names) {
if ($name -in $preferences.GetValueNames()) {
@@ -16,6 +17,24 @@ $temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
$root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N'))
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
$process = $null
function Render-ComparisonList([IntPtr]$List, [FilesCommandsUi+Rect]$Bounds) {
$bitmap = [Drawing.Bitmap]::new($Bounds.Right, $Bounds.Bottom)
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try {
if (![FilesCommandsUi]::PrintWindow($List, $dc, 3)) { throw 'Could not render the comparison list.' }
} finally { $graphics.ReleaseHdc($dc) }
} finally { $graphics.Dispose() }
} catch {
$bitmap.Dispose()
throw
}
$bitmap
}
try {
$left = Join-Path $root 'left'
$right = Join-Path $root 'right'
@@ -25,7 +44,8 @@ try {
[IO.File]::WriteAllText((Join-Path $right 'sample.txt'), "one`nthree")
$preferences.SetValue('LeftPath', $left)
$preferences.SetValue('RightPath', $right)
foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance') {
foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance',
'LeftFtpLocation', 'RightFtpLocation') {
$preferences.DeleteValue($name, $false)
}
@@ -42,40 +62,37 @@ try {
[void][FilesCommandsUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
}
Invoke-FilesCommand $main 'Compare files*'
$list = Wait-For 'the foreground comparison list' {
$comparison = Wait-For 'the rendered comparison window' {
$dialog = [IntPtr]::Zero
while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
[uint32]$ownerPid = 0
[void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
if ($ownerPid -ne $process.Id) { continue }
$control = [FilesCommandsUi]::GetDlgItem($dialog, 402)
if ([FilesCommandsUi]::IsWindowVisible($control) -and [FilesCommandsUi]::Activate($dialog)) {
return $control
if ([FilesCommandsUi]::IsWindowVisible($control)) {
return $dialog
}
}
}
$list = [FilesCommandsUi]::GetDlgItem($comparison, 402)
$bounds = [FilesCommandsUi+Rect]::new()
[void][FilesCommandsUi]::GetClientRect($list, [ref]$bounds)
$middle = [int]($bounds.Right / 2)
$destination = [int]($bounds.Right * 0.65)
$mouseY = 30 -shl 16
[void][FilesCommandsUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
for ($x = $middle + 5; $x -lt $destination; $x += 5) {
for ($step = 1; $step -lt 8; ++$step) {
$x = $middle + [int](($destination - $middle) * $step / 8)
[void][FilesCommandsUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
}
[void][FilesCommandsUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
$origin = [FilesCommandsUi+Point]::new()
[void][FilesCommandsUi]::ClientToScreen($list, [ref]$origin)
$bitmap = [Drawing.Bitmap]::new($bounds.Right, 1)
$bitmap = Render-ComparisonList $list $bounds
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try { $graphics.CopyFromScreen($origin.X, ($origin.Y + $bounds.Bottom - 10), 0, 0, $bitmap.Size) }
finally { $graphics.Dispose() }
$ink = @(for ($x = $middle - 4; $x -le $destination + 4; ++$x) {
if ($bitmap.GetPixel($x, 0).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x }
if ($bitmap.GetPixel($x, $bounds.Bottom - 10).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x }
})
# Desktop scaling can spread the single-pixel divider across two adjacent screen pixels.
if (!$ink.Count -or $ink.Count -gt 2 -or [Math]::Abs($ink[0] - $destination) -gt 1 -or
@@ -83,7 +100,31 @@ try {
throw "Expected one divider under the last row at $destination. Found $($ink.Count) marked pixels, starting at $($ink | Select-Object -First 8)."
}
} finally { $bitmap.Dispose() }
'Verified that dragging leaves exactly one divider below the file contents.'
$toolbar = [FilesCommandsUi]::GetDlgItem($comparison, 408)
if ([FilesCommandsUi]::Send($toolbar, 0x402, [IntPtr]415, [IntPtr]1) -eq [IntPtr]::Zero) {
throw 'The Unified toolbar button is missing.'
}
[void][FilesCommandsUi]::Send($comparison, 0x111, [IntPtr]415, $toolbar)
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
$height = [FilesCommandsUi]::Send($list, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
# This part of the first unchanged row contains the right line number in the default font.
$numbers = Render-ComparisonList $list $bounds
try {
$left = [int]($height * 3.6)
$right = [int]($height * 5.05)
$hasNumber = $false
for ($y = [int]($height / 4); $y -lt [int]($height * 3 / 4) -and !$hasNumber; ++$y) {
for ($x = $left; $x -lt $right; ++$x) {
$pixel = $numbers.GetPixel($x, $y)
if ($pixel.R -lt 90 -and $pixel.G -lt 90 -and $pixel.B -lt 90) {
$hasNumber = $true
break
}
}
}
if (!$hasNumber) { throw 'The right line number did not render in the Unified view.' }
} finally { $numbers.Dispose() }
'Verified the dragged divider and the right line number in the Unified view.'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
foreach ($name in $names) {
+26 -8
View File
@@ -6,6 +6,7 @@ param(
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
. "$PSScriptRoot/files_commands_ui.ps1"
Add-Type @'
using System;
using System.Text;
@@ -44,7 +45,8 @@ $previousDpi = [FilesDriveShortcutTest]::SetThreadDpiAwarenessContext([IntPtr](-
try {
if ($FtpProfiles) {
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$preferenceNames = 'FtpProfiles', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
$preferenceNames = 'FtpProfiles', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor',
'LeftFtpLocation', 'RightFtpLocation', 'FontPoints', 'WindowPlacement'
foreach ($name in $preferenceNames) {
if ($name -in $preferences.GetValueNames()) {
$savedPreferences[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
@@ -53,10 +55,22 @@ try {
$profile = '[{"name":"Test FTP profile","host":"localhost","user":"","port":21,"secret":[]}]'
$preferences.SetValue('FtpProfiles', [Text.Encoding]::UTF8.GetBytes($profile), 'Binary')
foreach ($name in 'LeftWide', 'RightWide') { $preferences.SetValue($name, 1, 'DWord') }
$preferences.SetValue('FontPoints', 80, 'DWord')
foreach ($name in 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement') {
$preferences.DeleteValue($name, $false)
}
}
$process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
$window = $process.MainWindowHandle
$process = Start-Process -FilePath (Resolve-Path $Executable) -WindowStyle Hidden -PassThru
$window = Wait-For 'the Files window' {
$candidate = [IntPtr]::Zero
while (($candidate = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $candidate, 'KSwitcher.Files', [NullString]::Value)) -ne [IntPtr]::Zero) {
[uint32]$owner = 0
[void][FilesCommandsUi]::GetWindowThreadProcessId($candidate, [ref]$owner)
if ($owner -eq $process.Id) { return $candidate }
}
}
[void][FilesCommandsUi]::SetWindowPos($window, [IntPtr]::Zero, 65, 50, 1500, 900, 20)
[void][FilesCommandsUi]::ShowWindow($window, 4)
$picker = [FilesDriveShortcutTest]::GetDlgItem($window, 121)
$path = [FilesDriveShortcutTest]::GetDlgItem($window, 142)
function Open-Picker([int]$Side = 0) {
@@ -89,8 +103,8 @@ try {
Open-Picker $side
$rows = @(Read-Picker)
$row = [Array]::IndexOf($rows, 'FTP')
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'Recent folders' -or
$rows[$row + 2] -cne 'KSwitcher LAN') {
if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'SFTP' -or $rows[$row + 2] -cne 'SMB' -or
$rows[$row + 3] -cne 'Recent folders' -or $rows[$row + 4] -cne 'KSwitcher LAN') {
throw "Source groups are missing separators in panel $side."
}
[void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$row, $null)
@@ -101,12 +115,16 @@ try {
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 }
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 2 }
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 3 }
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero)
Wait-Until {
$selected = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32()
$selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 2)
$selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 4)
}
[void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero)
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 }
Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 3 }
[void][FilesDriveShortcutTest]::SendMessage($picker, 407, [IntPtr]($row - 2), $null)
$bitmap = Render-Picker
try {
+6
View File
@@ -84,6 +84,12 @@ try {
}
})()`), 'the terminal output fixture');
assert.equal(selection, 'terminal-output-copy-fixture');
} else if (scenario === 'terminal-prompt-text') {
await evaluate('terminal.focus()');
await command('Input.insertText', { text: artifact });
} else if (scenario === 'terminal-interrupt') {
await evaluate('terminal.focus()');
await pressKey('c', 'KeyC', 67, 2);
} else if (terminalScenario) {
assert.equal(await evaluate('terminal.options.cursorInactiveStyle'), 'none');
assert.equal(await evaluate('document.querySelectorAll(".xterm-cursor-outline").length'), 0);
+111
View File
@@ -0,0 +1,111 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$PreferenceKey = 'Software\KSwitcher\Files'
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
. "$PSScriptRoot/files_commands_ui.ps1"
function Set-Password([IntPtr]$Field, [string]$Value) {
[void][FilesCommandsUi]::Read($Field, 12, [IntPtr]::Zero, [Text.StringBuilder]::new($Value))
[void][FilesCommandsUi]::RedrawWindow($Field, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
}
function Render-Password([IntPtr]$Field) {
$bounds = [FilesCommandsUi+Rect]::new()
[void][FilesCommandsUi]::GetClientRect($Field, [ref]$bounds)
$bitmap = [Drawing.Bitmap]::new($bounds.Right, $bounds.Bottom)
$data = [IO.MemoryStream]::new()
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try {
if (![FilesCommandsUi]::PrintWindow($Field, $dc, 3)) { throw 'Could not render the password field.' }
} finally { $graphics.ReleaseHdc($dc) }
} finally { $graphics.Dispose() }
$bitmap.Save($data, [Drawing.Imaging.ImageFormat]::Png)
[Convert]::ToBase64String($data.ToArray())
} finally {
$data.Dispose()
$bitmap.Dispose()
}
}
$exe = (Resolve-Path -LiteralPath $Executable).Path
$local = Split-Path -Parent $exe
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($PreferenceKey)
$saved = @{}
$names = 'SmbProfiles', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement'
foreach ($name in $names) {
if ($name -in $preferences.GetValueNames()) {
$saved[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name))
}
}
$process = $null
try {
$profile = '[{"id":"e2932abf62404facb66fc8a98dfe47f4","name":"Render fixture","path":"\\\\masked-field.invalid"}]'
$preferences.SetValue('SmbProfiles', [Text.Encoding]::UTF8.GetBytes($profile), 'Binary')
foreach ($name in 'LeftPath', 'RightPath') { $preferences.SetValue($name, $local, 'String') }
foreach ($name in 'LeftCursor', 'RightCursor', 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement') {
$preferences.DeleteValue($name, $false)
}
$process = Start-Process -FilePath $exe -WindowStyle Hidden -PassThru
$main = Wait-For 'the Files window' {
$window = [IntPtr]::Zero
while (($window = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $window, 'KSwitcher.Files', [NullString]::Value)) -ne [IntPtr]::Zero) {
[uint32]$owner = 0
[void][FilesCommandsUi]::GetWindowThreadProcessId($window, [ref]$owner)
if ($owner -eq $process.Id) { return $window }
}
}
[void][FilesCommandsUi]::ShowWindow($main, 4)
$picker = [FilesCommandsUi]::GetDlgItem($main, 121)
[void][FilesCommandsUi]::Post($main, 0x104, [IntPtr]112, [IntPtr]::Zero)
[void](Wait-For 'Change drive' { [FilesCommandsUi]::IsWindowVisible($picker) })
$count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
$selection = -1
for ($row = 0; $row -lt $count; ++$row) {
$label = [Text.StringBuilder]::new(256)
[void][FilesCommandsUi]::Read($picker, 393, [IntPtr]$row, $label)
if ($label.ToString() -ceq 'SMB') { $selection = $row; break }
}
if ($selection -lt 0) { throw 'SMB was missing from Change drive.' }
[void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$selection, [IntPtr]::Zero)
[void][FilesCommandsUi]::Post($picker, 0x100, [IntPtr]13, [IntPtr]::Zero)
function Find-DialogControl([int]$Id) {
$dialog = [IntPtr]::Zero
while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $dialog, '#32770', [NullString]::Value)) -ne [IntPtr]::Zero) {
[uint32]$owner = 0
[void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$owner)
$control = [FilesCommandsUi]::GetDlgItem($dialog, $Id)
if ($owner -eq $process.Id -and [FilesCommandsUi]::IsWindowVisible($control)) {
return @($dialog, $control)
}
}
}
$browser, $signIn = Wait-For 'the SMB Sign in command' { Find-DialogControl 547 }
[void][FilesCommandsUi]::Post($browser, 0x111, [IntPtr]547, $signIn)
$dialog, $password = Wait-For 'the SMB password field' { Find-DialogControl 559 }
$empty = Render-Password $password
Set-Password $password 'WWWWWWWW'
$first = Render-Password $password
Set-Password $password 'iiiiiiii'
$second = Render-Password $password
if ($first -eq $empty -or $first -ne $second) {
throw 'Equal-length password inputs must render as the same visible mask.'
}
$remember = [FilesCommandsUi]::GetDlgItem($dialog, 560)
if ([FilesCommandsUi]::Send($remember, 0xf0, [IntPtr]::Zero, [IntPtr]::Zero) -ne [IntPtr]::Zero) {
throw 'Remember in Windows Credential Manager must be unchecked by default.'
}
'Verified password masking and the default credential-saving choice.'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $preferences.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $preferences.DeleteValue($name, $false) }
}
$preferences.Dispose()
}
+20
View File
@@ -1,4 +1,5 @@
#include "files_text_document.h"
#include "files_compare_text.h"
#include <objbase.h>
#include <winioctl.h>
@@ -189,6 +190,24 @@ void bookmarkedLines(const fs::path &file)
check(rejected,"Cancel a bookmark scan");
}
void comparisonEdits()
{
using namespace ks::files;
auto mixed=splitComparisonText(L"alpha\r\nbeta\nlast\r");
check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Round-trip mixed line endings");
const auto replace=replaceComparisonText(mixed,{1,1,{L"new",L"extra"},{ComparisonEnding::lf,ComparisonEnding::crlf}});
check(mixed.joined()==L"alpha\r\nnew\nextra\r\nlast\r","Replace a block and retain the other line endings");
replaceComparisonText(mixed,replace);
check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Undo a block replacement");
const auto shorten=replaceComparisonText(mixed,{3,1,{},{}});
check(mixed.joined()==L"alpha\r\nbeta\nlast","Remove the terminating empty line");
replaceComparisonText(mixed,shorten);
check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Undo preserves the original trailing separator");
auto single=splitComparisonText(L"first");
replaceComparisonText(single,{1,0,{L"second"},{ComparisonEnding::absent}});
check(single.joined()==L"first\r\nsecond","Use the target convention when inserting past EOF");
}
void saveDraft(const fs::path &file)
{
TextDocument draft({});
@@ -238,6 +257,7 @@ int main()
saveDraft(fixture.directory / L"created.txt");
hexBytes(fixture.directory / L"raw.bin");
bookmarkedLines(fixture.directory / L"bookmarks.txt");
comparisonEdits();
sparseFile(fixture.directory / L"5gib.log");
std::cout << "Files text document regressions passed.\n";
}
+297 -52
View File
@@ -1,90 +1,335 @@
#include "lan_clients.h"
#include <winsock2.h>
#include "lan_client_files.h"
#include "lan_network.h"
#include <atomic>
#include <fstream>
#include <iostream>
namespace
{
using ks::lan::Json;
using namespace ks;
using namespace ks::lan;
namespace fs = std::filesystem;
void require(bool value, const char *message)
{
if (!value) throw std::runtime_error(message);
}
Json request(const std::wstring &name)
class Pipe
{
require(WaitNamedPipeW(name.c_str(), 3000) != FALSE, "LAN client pipe did not start");
struct Pipe
HANDLE handle = INVALID_HANDLE_VALUE;
void io(void *buffer, DWORD length, bool write)
{
HANDLE value;
~Pipe() { if (value != INVALID_HANDLE_VALUE) CloseHandle(value); }
} pipe{CreateFileW(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, nullptr)};
require(pipe.value != INVALID_HANDLE_VALUE, "could not open LAN client pipe");
auto transfer = [&](void *buffer, DWORD length, bool write) {
auto *cursor = static_cast<char *>(buffer);
while (length)
{
DWORD count{};
require((write ? WriteFile(pipe.value, cursor, length, &count, nullptr) :
ReadFile(pipe.value, cursor, length, &count, nullptr)) && count, "pipe transfer failed");
require((write ? WriteFile(handle, cursor, length, &count, nullptr) :
ReadFile(handle, cursor, length, &count, nullptr)) && count, "pipe transfer failed");
cursor += count;
length -= count;
}
}
public:
Pipe(const std::wstring &name, const Json &request, bool impersonate = false)
{
const auto end = GetTickCount64() + 3000;
do
{
handle = CreateFileW(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING,
SECURITY_SQOS_PRESENT | (impersonate ? SECURITY_IMPERSONATION : SECURITY_IDENTIFICATION), nullptr);
if (handle != INVALID_HANDLE_VALUE) break;
Sleep(10);
} while (GetTickCount64() < end);
require(handle != INVALID_HANDLE_VALUE, "could not open LAN client pipe");
sendJson(request);
}
~Pipe() { if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); }
void send(std::string data)
{
DWORD length = DWORD(data.size());
io(&length, sizeof(length), true);
if (length) io(data.data(), length, true);
}
void sendJson(const Json &data) { send(data.dump()); }
std::string read()
{
DWORD length{};
io(&length, sizeof(length), false);
require(length <= 8 * 1024 * 1024, "unexpected reply size");
std::string payload(length, '\0');
if (length) io(payload.data(), length, false);
return payload;
}
Json reply() { return Json::parse(read()); }
void ack()
{
char ack{};
io(&ack, 1, true);
}
};
Json request(const std::wstring &name, const Json &body, bool impersonate = false)
{
Pipe pipe(name, body, impersonate);
auto reply = pipe.reply();
pipe.ack();
return reply;
}
void save(const fs::path &path, const std::string &content)
{
std::ofstream file(path, std::ios::binary | std::ios::trunc);
file << content;
require(bool(file), "could not write test file");
}
std::string read(const fs::path &path)
{
std::ifstream file(path, std::ios::binary);
require(bool(file), "could not read test file");
return {std::istreambuf_iterator<char>(file), {}};
}
Json endpoint(const Json &peer, const fs::path &path)
{
return {{"peer", peer}, {"path", utf8(path.native())}};
}
Json operation(const char *action, const Json &peer, const fs::path &path)
{
auto result = endpoint(peer, path);
result["action"] = action;
return result;
}
Json transfer(const Json &from, const Json &to, bool move, const char *conflict = "fail")
{
return {{"action", "transfer"}, {"source", from}, {"target", to}, {"move", move}, {"conflict", conflict}};
}
Json runTransfer(const std::wstring &name, const Json &job,
const std::function<bool(const Json &)> &progress = {}, bool impersonate = false)
{
Pipe pipe(name, job, impersonate);
for (;;)
{
auto result = pipe.reply();
if (result.value("type", "") != "progress")
{
pipe.ack();
return result;
}
pipe.sendJson({{"continue", !progress || progress(result)}});
}
}
void verifyFiles(LanClients &clients, const Json &trusted, const std::wstring &pipe,
const fs::path &root, const fs::path &secondVolume)
{
const auto caller = randomHex(16), a = randomHex(16), b = randomHex(16), key = randomHex(32);
std::atomic<bool> available{true};
const auto pair = [&](const std::string &id) { return id == caller && available.load() ? key : std::string{}; };
Network network;
FilesListener first(a, pair, 0), second(b, pair, 0);
require(first.port() && second.port(), "could not start paired file listeners");
std::jthread listeners([&](std::stop_token stop) {
while (!stop.stop_requested()) { first.poll(); second.poll(); Sleep(1); }
});
const auto running = [&](const std::string &peer) -> ClientFilesPeer {
require(peer == a || peer == b, "an unknown peer was routed");
return {{peer, "127.0.0.1", L"Fixture", peer == a ? first.port() : second.port(), true}, caller, key};
};
auto payload = Json{{"action", "peers"}}.dump();
DWORD length = DWORD(payload.size());
transfer(&length, sizeof(length), true);
transfer(payload.data(), length, true);
transfer(&length, sizeof(length), false);
require(length > 0 && length < 4096, "unexpected reply size");
payload.resize(length);
transfer(payload.data(), length, false);
char ack{};
transfer(&ack, 1, true);
return Json::parse(payload);
clients.start([&](const Json &body, const ClientCheck &check, const ClientSend &send,
const ClientReceive &receive, const ClientAsCaller &asCaller) {
if (body.at("action") == "peers")
{
constexpr std::string_view reply = R"([{"id":"fixture","name":"Paired PC","online":true}])";
send(reply.data(), DWORD(reply.size()));
}
else routeClientFiles(body, check, send, receive, asCaller, running);
}, pipe.substr(pipe.find(L".test.")));
struct Stop { LanClients &clients; ~Stop() { clients.stop(); } } stop{clients};
const auto path = utf8(executable());
const auto canonical = trusted.at("path");
const Json peers{{"action", "peers"}};
require(request(pipe, peers).contains("error"), "an untrusted executable was accepted");
const auto grant = [&](bool write, bool erase) {
clients.settings("trustClient", {{"path", path}, {"writeFiles", write}, {"deleteFiles", erase}});
};
grant(false, false);
require(request(pipe, peers).at(0).at("name") == "Paired PC", "the trusted executable was rejected");
const auto setCapabilities = [&](bool write, bool erase) {
const auto caps = request(pipe, {{"action", "capabilities"}, {"peer", a}});
require(caps.value("protocol", 0) == 2 && caps.value("hostRevision", 0) == 1 &&
caps.at("write") == write && caps.at("delete") == erase && caps.at("move") == (write && erase),
"wrong advertised capabilities");
};
setCapabilities(false, false);
const auto src = root / L"source", dst = root / L"target", file = src / L"content.txt";
const std::string content(FileChunk * 4 + 19, 'x');
fs::create_directory(src);
save(file, content);
const auto mkdir = operation("mkdir", b, dst);
require(request(pipe, mkdir).contains("error") && !fs::exists(dst), "browse grant allowed creation");
const auto legacy = request(pipe, operation("list", a, src));
require(legacy.at(0).at("name") == "content.txt", "legacy list schema changed");
{
Pipe download(pipe, operation("download", a, file));
const auto header = download.reply();
require(header.size() == 1 && header.at("size") == content.size(), "legacy download schema changed");
std::string downloaded;
for (auto chunk = download.read(); !chunk.empty(); chunk = download.read()) downloaded += chunk;
download.ack();
require(downloaded == content, "legacy download content changed");
}
const auto info = request(pipe, operation("stat", a, file));
auto readVersion = operation("readFile", a, file);
readVersion["expected"] = {{"size", info.at("size")}, {"modified", info.at("modified")}};
{
Pipe reader(pipe, readVersion);
require(reader.reply().at("modified") == info.at("modified"), "revision read omitted metadata");
std::string downloaded;
for (auto chunk = reader.read(); !chunk.empty(); chunk = reader.read()) downloaded += chunk;
reader.ack();
require(downloaded == content, "revision read had incorrect content");
}
readVersion["expected"]["size"] = 0;
require(request(pipe, readVersion).at("error").is_string(), "stale revision read was accepted");
grant(true, false);
setCapabilities(true, false);
require(request(pipe, mkdir).at("error") == 0, "mkdir failed");
require(request(pipe, operation("delete", a, file)).contains("error") && fs::exists(file),
"write grant allowed deletion");
auto up = operation("writeFile", b, dst / L"upload.txt");
up["size"] = 3;
const auto upload = [&](const std::string &value) {
Pipe writer(pipe, up);
require(writer.reply().value("type", "") == "ready", "upload did not open");
writer.send(value);
writer.send("");
const auto result = writer.reply();
writer.ack();
return result;
};
const auto original = upload("one");
require(original.at("error") == 0 && read(dst / L"upload.txt") == "one", "exclusive create failed");
const auto collision = upload("two");
require(collision.at("error").is_string() && read(dst / L"upload.txt") == "one",
"exclusive create overwrote existing file");
up["expected"] = {{"size", original.at("size")}, {"modified", original.at("modified")}};
require(upload("two").at("error") == 0 && read(dst / L"upload.txt") == "two", "revision save failed");
require(upload("bad").at("error").is_string() && read(dst / L"upload.txt") == "two", "stale save lost data");
auto rename = operation("rename", b, dst / L"upload.txt");
rename["name"] = "renamed.txt";
require(request(pipe, rename).at("error") == 0 && read(dst / L"renamed.txt") == "two", "rename failed");
const auto to = dst / L"copy";
const auto cross = transfer(endpoint(a, src), endpoint(b, to), false);
require(runTransfer(pipe, cross).at("type") == "complete" && read(to / L"content.txt") == content,
"cross-peer tree copy failed");
require(runTransfer(pipe, cross).contains("error"), "the fail conflict policy overwrote a directory");
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "skip")).at("skipped") == 1,
"skip conflict policy failed");
save(to / L"content.txt", "replace me");
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "replace")).at("type") == "complete" &&
read(to / L"content.txt") == content, "replace conflict policy failed");
const auto localCopy = root / L"local.txt";
const auto fromLocal = transfer(endpoint(nullptr, file), endpoint(b, dst / L"from-local.txt"), false);
require(runTransfer(pipe, fromLocal).contains("error"), "identification-only pipe accessed local files");
const auto localUpload = runTransfer(pipe, fromLocal, {}, true);
require(localUpload.value("type", "") == "complete" && read(dst / L"from-local.txt") == content,
localUpload.value("error", "local upload failed under the caller token").c_str());
require(runTransfer(pipe, transfer(endpoint(b, dst / L"from-local.txt"), endpoint(nullptr, localCopy), false),
{}, true).at("type") == "complete" && read(localCopy) == content, "local download failed under the caller token");
const auto remoteSide = secondVolume.empty() ? dst : secondVolume;
const auto sameCopy = remoteSide / L"same-host.txt";
unsigned progressFrames{};
require(runTransfer(pipe, transfer(endpoint(a, file), endpoint(a, sameCopy), false),
[&](const Json &) { ++progressFrames; return true; }).at("type") == "complete" &&
progressFrames > 1 && read(sameCopy) == content, "same-host transfer failed");
const auto cancelled = dst / L"cancelled.txt";
const auto cancellation = transfer(endpoint(a, file), endpoint(a, cancelled), false);
require(runTransfer(pipe, cancellation, [](const Json &progress) { return progress.at("total") == 0; })
.contains("error") && !fs::exists(cancelled) && read(file) == content, "same-host cancellation lost data");
{
Pipe disconnect(pipe, cancellation);
while (disconnect.reply().at("total") == 0) disconnect.sendJson({{"continue", true}});
}
require(request(pipe, peers).is_array() && !fs::exists(cancelled) && read(file) == content,
"pipe disconnect published an incomplete transfer");
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(a, src / L"inside"), false)).contains("error") &&
!fs::exists(src / L"inside"), "same-host transfer recursed into its source");
grant(true, true);
setCapabilities(true, true);
const auto moved = dst / L"moved.txt";
const auto move = transfer(endpoint(a, file), endpoint(b, moved), true);
require(runTransfer(pipe, move, [&](const Json &progress) {
if (progress.at("phase") == "remove") grant(true, false);
return true;
}).contains("error") && fs::exists(file) && read(moved) == content,
"revoked delete grant still removed the source or failed to publish the full destination");
fs::remove(moved);
grant(true, true);
require(runTransfer(pipe, move, [&](const Json &progress) {
if (progress.at("total") != 0) available = false;
return true;
}).contains("error") && fs::exists(file) && !fs::exists(moved), "connection loss published a partial move");
available = true;
const auto sameMove = remoteSide / L"same-move";
require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(a, sameMove), true)).at("type") == "complete" &&
read(sameMove / L"content.txt") == content && !fs::exists(src), "same-host tree move failed");
const auto crossMove = dst / L"cross-move";
require(runTransfer(pipe, transfer(endpoint(a, sameMove), endpoint(b, crossMove), true)).at("type") == "complete" &&
read(crossMove / L"content.txt") == content && !fs::exists(sameMove), "cross-peer tree move failed");
auto erase = operation("delete", b, crossMove);
erase["recursive"] = true;
require(request(pipe, erase).at("error") == 0 && !fs::exists(crossMove), "recursive delete failed");
for (const auto &entry : fs::recursive_directory_iterator(root))
require(entry.path().extension() != L".partial", "an interrupted client operation left a partial upload");
auto changed = clients.settings("trustedClients", {});
changed.at(0)["sha256"] = std::string(64, '0');
const auto differentHash = changed.dump();
atomicWrite(root / L"lan-clients.bin", protect(Bytes(differentHash.begin(), differentHash.end())));
require(request(pipe, peers).contains("error"), "an executable with a different fingerprint was accepted");
grant(true, true);
clients.settings("removeClient", {{"path", canonical}});
require(request(pipe, peers).contains("error"), "revocation must reject the next request");
}
}
int main()
{
const auto suffix = L".test." + std::to_wstring(GetCurrentProcessId());
const auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-LAN" + suffix);
const auto root = fs::temp_directory_path() / (L"KSwitcher-LAN" + suffix);
fs::path secondVolume;
try
{
require(std::filesystem::create_directory(root), "could not create test directory");
require(fs::create_directory(root), "could not create test directory");
wchar_t other[512]{};
const auto length = GetEnvironmentVariableW(L"KSWITCHER_TEST_LAN_OTHER_VOLUME", other, DWORD(std::size(other)));
if (length && length < std::size(other))
{
secondVolume = fs::path(other) / root.filename();
require(fs::create_directory(secondVolume), "could not create other-volume fixture");
}
DWORD session{};
require(ProcessIdToSessionId(GetCurrentProcessId(), &session) != FALSE, "no Windows session");
const auto pipe = L"\\\\.\\pipe\\KSwitcher.LAN.Clients.v1." + std::to_wstring(session) + suffix;
{
ks::lan::LanClients clients(root);
clients.start([](const Json &request, const auto &, const auto &send) {
require(request.at("action") == "peers", "unexpected request");
constexpr std::string_view reply = R"([{"id":"fixture","name":"Paired PC","online":true}])";
send(reply.data(), DWORD(reply.size()));
}, suffix);
// WaitNamedPipe returns immediately if the instance has not been created yet.
for (int n = 0; n < 100 && !WaitNamedPipeW(pipe.c_str(), 20); ++n) Sleep(20);
require(request(pipe).contains("error"), "an untrusted executable was accepted");
const auto path = ks::utf8(ks::executable());
const auto trusted = clients.settings("trustClient", {{"path", path}});
require(trusted.size() == 1, "the program must be enrolled exactly once");
require(request(pipe).at(0).at("name") == "Paired PC", "the trusted program was rejected");
auto changed = trusted;
changed.at(0)["sha256"] = std::string(64, '0');
const auto store = root / L"lan-clients.bin";
const auto differentHash = changed.dump();
ks::atomicWrite(store, ks::protect(ks::Bytes(differentHash.begin(), differentHash.end())));
require(request(pipe).contains("error"), "an executable with a different fingerprint was accepted");
clients.settings("trustClient", {{"path", path}});
clients.settings("removeClient", {{"path", trusted.at(0).at("path")}});
require(request(pipe).contains("error"), "revocation must reject the next request");
LanClients clients(root);
const auto trusted = clients.settings("inspectClient", {{"path", utf8(executable())}});
verifyFiles(clients, trusted, pipe, root, secondVolume);
clients.stop();
}
std::filesystem::remove(root / L"lan-clients.bin");
std::filesystem::remove(root);
std::cout << "Verified executable approval, resident pipe access and revocation.\n";
if (!secondVolume.empty()) fs::remove_all(secondVolume);
fs::remove_all(root);
std::cout << "Verified approval, permissions, legacy discovery/download, revisions and transfers between paired hosts.\n";
return 0;
}
catch (const std::exception &error)
{
if (!secondVolume.empty()) { std::error_code ignored; fs::remove_all(secondVolume, ignored); }
{ std::error_code ignored; fs::remove_all(root, ignored); }
std::cerr << error.what() << '\n';
return 1;
}
+54
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,7 +198,39 @@ int main()
require(false,"unpaired client authenticated");
}
catch(const std::system_error &){}
verifyConnectionCancellation(client,key);
FilesConnection host(one,client,key);
{
const auto source=root/L"acl-source.txt", copied=root/L"acl-target.txt";
save(source,"source");
save(copied,"target");
auto get=fileRequest("copyPermissions",source);
const auto inherited=host.call(get);
checkFileReply(inherited);
auto acl=inherited.at("permissions").get<std::string>();
if(!acl.starts_with("D:P")) acl.insert(2,"P");
auto protect=fileRequest("applyCopyMetadata",source);
protect["permissions"]=acl;
const auto protectedSource=host.call(protect);
require(protectedSource.at("error")==ERROR_SUCCESS, "could not set a protected source DACL");
const auto permissions=host.call(get);
checkFileReply(permissions);
require(permissions.at("permissions").get<std::string>().starts_with("D:P"),
"copy permission action did not protect the Windows DACL");
auto apply=fileRequest("applyCopyMetadata",copied);
constexpr uint64_t modified=132537600000000000ULL;
apply["permissions"]=permissions.at("permissions");
apply["modified"]=modified;
const auto applied=host.call(apply);
require(applied.at("error")==ERROR_SUCCESS, "could not copy Windows metadata to the target");
auto result=host.call(fileRequest("copyPermissions",copied));
checkFileReply(result);
require(result.at("permissions")==permissions.at("permissions"),
"Windows permissions did not survive LAN metadata copy");
result=host.call(fileRequest("stat",copied));
checkFileReply(result);
require(result.at("modified")==modified,"LAN copy metadata lost the file modification time");
}
{
const Json hibernate={{"action","hibernate"}};
FilesConnection target(two,client,key);