Compare commits

...
Author SHA1 Message Date
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
28 changed files with 2899 additions and 554 deletions

No files matched your search

+8 -2
View File
@@ -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 KSwitcherFilesImage libssh2::libssh2)
if(MSVC)
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
else()
@@ -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 .)
+79 -15
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,61 @@ 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** зі звіркою нового відбитка.
- Для 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,7 +127,8 @@ Warning і початковий фокус на No.
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
і меню Commands показує поточне призначення.
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
типово пропускаються. Перемикач **Show whitespace changes** показує їх
в обох поданнях і враховує під час згортання.
Вставлені й видалені порожні рядки враховуються завжди.
**Apply to left/right** копіює виділений блок у відповідну сторону.
Порівняння перераховується, а змінену сторону позначає зірочка.
@@ -96,7 +145,7 @@ Warning і початковий фокус на No.
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP.
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP, SFTP і SMB.
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
до закриття меню, навіть коли оновлюється список LAN.
@@ -133,8 +182,12 @@ Warning і початковий фокус на No.
виконує команду одразу. Коли рядок
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
У повноекранному терміналі (Ctrl+O) команда редагується в промпті
під виводом. Клік у терміналі повертає курсор у промпт. Стрілки вгору й
вниз без відкритого списку підказок переглядають спільну історію, а після
останньої команди вниз повертає чернетку. Підказки відкриваються біля
курсора. Ctrl+C перериває поточну команду, а за виділеного тексту виводу
копіює виділення. Escape з порожнім промптом також перериває команду.
Локальна команда запускається в папці активної панелі, яку показано
перед командним рядком. Після перемикання панелі або переходу до іншої
папки наступна команда використовує нову папку навіть у вже відкритому
@@ -547,6 +600,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 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення.
@@ -596,12 +654,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+→ працюють з історією активної панелі.
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
@@ -610,7 +671,10 @@ Warning і початковий фокус на No.
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
а Esc повертає до тих самих панелей і курсора.
- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі.
- У заголовку FTP- чи SFTP-папки клік по назві профілю відкриває збережені
підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери
та їхні диски. Поле шляху й доповнення працюють у поточному джерелі.
Для FTP абсолютний шлях починається з /.
## Спільні елементи діалогів
+20
View File
@@ -0,0 +1,20 @@
include(FetchContent)
# 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)
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()
+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.
*/
+72
View File
@@ -512,3 +512,75 @@ 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, 388, 12
FAR_EDIT(563, 0, 16, 130, 388, 15)
LTEXT "", 566, 16, 153, 388, 14, SS_ENDELLIPSIS | SS_NOPREFIX
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
+17 -3
View File
@@ -4,7 +4,6 @@ const terminal = new Terminal({
fontSize: 16,
cursorBlink: false,
cursorInactiveStyle: 'none',
disableStdin: true,
theme: { background: '#181818', foreground: '#e8e8e8' },
});
const fit = new FitAddon.FitAddon();
@@ -22,7 +21,11 @@ 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);
host.addEventListener('pointerup', () => prompt('focus-input'), true);
terminal.onData(text => {
if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
});
const screen = host.querySelector('.xterm-screen');
let traceEnabled = false;
let traceBudget = 4096;
@@ -52,9 +55,20 @@ 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 (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;
}
+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;
+205 -88
View File
@@ -66,7 +66,7 @@ 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;
@@ -84,13 +84,23 @@ 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,408};
CompareFile files[2];
ks::files::ComparisonText text[2];
std::vector<CompareRow> rows;
std::vector<int> changes,allChanges;
std::vector<ComparisonDisplayRow> displayRows;
std::vector<std::array<int,2>> displayPositions;
std::vector<int> displayBlockStarts;
struct Undo
{
int side{};
@@ -98,7 +108,7 @@ struct FileComparison
};
std::vector<Undo> undo;
bool working{};
bool showWhitespace{};
bool showWhitespace{},unified{},foldContext{};
RECT initialClient{};
std::array<RECT,controls.size()> initialControls{};
SIZE minimumWindow{};
@@ -130,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)
{
@@ -265,7 +276,7 @@ ks::files::ComparisonText readComparisonLines(CompareFile &input,const std::atom
{
CompareCache temp;
auto path=input.path;
if(input.ftp) input.remote=ftpTextSource(*input.ftp);
if(input.ftp) input.remote=transferTextSource(*input.ftp);
else if(input.peer)
{
FilesConnection source(&*input.peer);
@@ -394,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];
@@ -409,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)
@@ -517,7 +524,8 @@ 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 };
enum ComparisonCommand { applyLeft=409,applyRight,undoCompare,saveLeft,saveRight,saveComparison,
unifiedCompare,foldCompareContext };
struct ComparisonProgress
{
@@ -584,16 +592,76 @@ std::optional<ks::files::ComparisonReplace> comparisonBlock(const FileComparison
void updateComparisonSummary(HWND dialog,const FileComparison &comparison);
void comparisonUpdateRows(HWND dialog,const FileComparison &comparison,LRESULT selected,LRESULT top)
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);
SendMessageW(list,LB_SETCOUNT,comparison.rows.size(),0);
if(!comparison.rows.empty())
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 last=static_cast<LRESULT>(comparison.rows.size())-1;
SendMessageW(list,LB_SETCURSEL,std::clamp<LRESULT>(selected,0,last),0);
SendMessageW(list,LB_SETTOPINDEX,std::clamp<LRESULT>(top,0,last),0);
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);
}
@@ -602,8 +670,8 @@ bool applyComparisonEdit(HWND dialog,FileComparison &comparison,int side,const k
bool remember)
{
const auto list=GetDlgItem(dialog,402);
const auto selected=SendMessageW(list,LB_GETCURSEL,0,0);
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
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;
@@ -623,8 +691,6 @@ bool applyComparisonEdit(HWND dialog,FileComparison &comparison,int side,const k
else comparison.undo.pop_back();
comparison.text[side]=std::move(candidate.text[side]);
comparison.rows=std::move(candidate.rows);
comparison.changes=std::move(candidate.changes);
comparison.allChanges=std::move(candidate.allChanges);
comparison.files[side].dirty=comparison.text[side].joined()!=comparison.files[side].originalText;
comparisonUpdateRows(dialog,comparison,selected,top);
return true;
@@ -697,46 +763,22 @@ 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) 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)
{
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.text[side].lines[number];
const auto paneWidth=area.right-area.left;
if(paneWidth<=0) return;
@@ -768,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);
@@ -794,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);
@@ -858,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);
}
}
@@ -891,16 +990,15 @@ 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=SendDlgItemMessageW(dialog,402,LB_GETCURSEL,0,0);
const bool selected=row>=0 && static_cast<size_t>(row)<comparison.rows.size() &&
comparison.rows[row].hasChange(comparison.showWhitespace);
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];
@@ -943,7 +1041,10 @@ void initializeComparisonActions(HWND toolbar)
{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")}
{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));
}
@@ -978,10 +1079,12 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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);
updateComparisonSummary(dialog,*comparison);
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)
@@ -1030,8 +1133,9 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(id==applyLeft || id==applyRight)
{
const auto side=id-applyLeft;
if(comparison->files[side].revision.editable)
if(const auto edit=comparisonBlock(*comparison,side,SendMessageW(list,LB_GETCURSEL,0,0)))
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;
@@ -1053,36 +1157,49 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
SetFocus(list);
return TRUE;
}
if(id==406 && HIWORD(wp)==BN_CLICKED)
if((id==406 || id==unifiedCompare || id==foldCompareContext) && HIWORD(wp)==BN_CLICKED)
{
comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0;
updateComparisonSummary(dialog,*comparison);
InvalidateRect(list,nullptr,FALSE);
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->showWhitespace?comparison->allChanges:comparison->changes;
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->text[file].lines[line];
@@ -1135,7 +1252,7 @@ void compareSelectedFiles(HWND owner)
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();
+1
View File
@@ -75,6 +75,7 @@ void startFileSearch(Panel &panel,Panel::FindOptions options)
{
if(panel.scanRequest) return;
cancelFolderSizes(panel);
panel.remoteRetry.reset();
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
startDirectoryScan(panel);
}
+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);
+111 -25
View File
@@ -1,17 +1,44 @@
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::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;
}
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 +46,85 @@ 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;
}
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(),
return data.size()<=transferProfilesMaxBytes &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
}
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{});
}
profiles.push_back(std::move(profile));
}
ftpProfiles=std::move(profiles);
ftpProfilesLoaded=true;
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 +150,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 +193,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 +201,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);
+28 -49
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,22 @@ 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;
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 +42,7 @@ struct CopyHost
{
if(path!=listedDirectory)
{
listedEntries=ftpChildren(*ftp,path,&canceled);
listedEntries=transferChildren(*ftp,path,&canceled);
listedDirectory=path;
}
return listedEntries;
@@ -58,7 +50,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)
@@ -82,8 +74,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 +82,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 +91,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 +107,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,7 +129,7 @@ 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)
{
@@ -156,55 +139,51 @@ 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);
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;
}
}
+239 -81
View File
@@ -1,76 +1,62 @@
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;
struct Edit
{
FtpProfile profile;
TransferProfile profile;
std::optional<size_t> index;
std::wstring pinnedHost;
INTERNET_PORT pinnedPort{};
std::string pin;
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);
}
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.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 +64,224 @@ 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;
}
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);
}
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
return profile;
}
template<class Task>
bool runTest(HWND dialog,Edit &edit,const wchar_t *status,Task task)
{
constexpr int controls[]{name,host,port,user,password,keyFile,testConnection,forgetKey,IDOK};
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 SftpSession 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 SFTP login…",[&] {
SftpSession session(profile);
initial=session.initialDirectory();
}))
{
const auto details=L"Connected to "+profile.host+L".\r\n\r\nInitial 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})
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());
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);
}
}
+409 -178
View File
File diff suppressed because it is too large. Load diff
+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;
}
+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 &) {}
+255
View File
@@ -0,0 +1,255 @@
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 connectSftpSocket(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());
}
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);}
};
class SftpSession
{
ks::lan::Network network_;
ks::lan::WinSocket socket_;
std::unique_ptr<LIBSSH2_SESSION,decltype(&libssh2_session_free)> session_{nullptr,libssh2_session_free};
std::unique_ptr<LIBSSH2_SFTP,decltype(&libssh2_sftp_shutdown)> sftp_{nullptr,libssh2_sftp_shutdown};
std::string fingerprint_;
[[noreturn]] void sshError(const char *operation) const
{
char *message{};
int length{};
libssh2_session_last_error(session_.get(),&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_.get(),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_.get(),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)");
}
static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));}
public:
explicit SftpSession(const TransferProfile &profile,bool probeOnly=false)
{
if(!probeOnly && profile.hostFingerprint.empty())
throw std::runtime_error("The SFTP host key is untrusted. Edit the profile and use Test connection to verify it.");
initializeSsh();
connectSftpSocket(socket_,profile);
session_.reset(libssh2_session_init());
if(!session_) throw std::runtime_error("Could not create an SSH session.");
libssh2_session_set_timeout(session_.get(),sftpTimeoutMs);
libssh2_session_set_read_timeout(session_.get(),sftpTimeoutMs/1000);
if(libssh2_session_method_pref(session_.get(),LIBSSH2_METHOD_HOSTKEY,
"ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256") ||
libssh2_session_handshake(session_.get(),socket_.value))
sshError("Could not negotiate an SSH connection");
const auto digest=reinterpret_cast<const BYTE*>(libssh2_hostkey_hash(session_.get(),LIBSSH2_HOSTKEY_HASH_SHA256));
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);
sftp_.reset(libssh2_sftp_init(session_.get()));
if(!sftp_) sshError("Could not start the SFTP subsystem");
}
const std::string &fingerprint() const {return fingerprint_;}
[[noreturn]] void operationError(const char *operation) const
{
if(libssh2_session_last_errno(session_.get())==LIBSSH2_ERROR_SFTP_PROTOCOL)
{
const auto status=libssh2_sftp_last_error(sftp_.get());
if(status==LIBSSH2_FX_PERMISSION_DENIED)
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category(),operation);
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);
}
sshError(operation);
}
fs::path initialDirectory() const
{
std::array<char,32768> path{};
const auto length=libssh2_sftp_realpath(sftp_.get(),".",path.data(),path.size());
if(length<=0) operationError("Could not resolve the initial SFTP folder");
auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal();
if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path.");
return value;
}
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 modified=(attrs.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)?
(uint64_t(attrs.mtime)+11644473600ULL)*10000000ULL:0;
if(!visit(directory/child,{attributes,attrs.filesize,modified})) return ERROR_CANCELLED;
}
return ERROR_CANCELLED;
}
SftpFile open(const fs::path &path,bool write) const
{
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
{
const auto name=encode(path);
if(libssh2_sftp_mkdir(sftp_.get(),name.c_str(),0755)) operationError("Could not create the SFTP folder");
}
void remove(const fs::path &path,bool directory) const
{
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 rename(const fs::path &from,const fs::path &to,bool replace) const
{
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,{});
}
+111
View File
@@ -0,0 +1,111 @@
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)
{
if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile);
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 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()));
}
};
+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()
}