Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ef30ab5e8 | ||
|
|
6279a2ee4f | ||
|
|
e11e19293f | ||
|
|
5729ed2036 | ||
|
|
94ccb488c1 | ||
|
|
e24fbc80ba | ||
|
|
c735c21682 | ||
|
|
9bb2221b2b | ||
|
|
20d95b37aa | ||
|
|
6467481d2f | ||
|
|
7033c1e336 | ||
|
|
03145ae75a | ||
|
|
9d57568351 | ||
|
|
f74b8b2ac0 | ||
|
|
5bf2d7ab45 | ||
|
|
4ab1f3c950 | ||
|
|
872c03823f | ||
|
|
0c09fbdb88 | ||
|
|
50010c99ba | ||
|
|
e92984d124 | ||
|
|
6f2f1f38e2 | ||
|
|
dc4e503c84 | ||
|
|
06c35c893c | ||
|
|
74e3248434 | ||
|
|
1f4baed2ed | ||
|
|
4147ccc04a | ||
|
|
cde7dacffc | ||
|
|
f1077909ef | ||
|
|
3efe108853 | ||
|
|
2348306b81 | ||
|
|
4b252bd111 | ||
|
|
7577d19a84 | ||
|
|
24fbf72d60 | ||
|
|
291d7597e3 | ||
|
|
ea6338e9b9 | ||
|
|
5ea222ad8a | ||
|
|
efe7937507 | ||
|
|
30a904b386 | ||
|
|
2545886092 | ||
|
|
3971cb1871 | ||
|
|
31473baa49 | ||
|
|
c7b9ee5cb1 | ||
|
|
07ed4cf724 | ||
|
|
4b5bcd2983 | ||
|
|
2a4df70079 | ||
|
|
e986dd90e5 |
No files matched your search
+40
-5
@@ -1,18 +1,21 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.7.4 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.7.4 LANGUAGES C CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
|
||||
src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
|
||||
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp resources/files.rc)
|
||||
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico"
|
||||
"${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)
|
||||
find_program(KSWITCHER_POWERSHELL NAMES pwsh powershell REQUIRED)
|
||||
@@ -32,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)
|
||||
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()
|
||||
@@ -153,6 +156,28 @@ if(NOT MSVC)
|
||||
target_link_options(KSwitcherFilesTextTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME files-text-document COMMAND KSwitcherFilesTextTests)
|
||||
add_executable(KSwitcherFilesArchiveTests tests/files_archive.cpp src/files_archive.cpp)
|
||||
target_include_directories(KSwitcherFilesArchiveTests PRIVATE src)
|
||||
target_compile_definitions(KSwitcherFilesArchiveTests PRIVATE NOMINMAX)
|
||||
target_link_libraries(KSwitcherFilesArchiveTests PRIVATE KSwitcherArchive ole32)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesArchiveTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
target_compile_options(KSwitcherFilesArchiveTests PRIVATE /utf-8)
|
||||
elseif(MINGW)
|
||||
target_link_options(KSwitcherFilesArchiveTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME files-archive COMMAND KSwitcherFilesArchiveTests)
|
||||
add_executable(KSwitcherFilesImageTests tests/files_image.cpp)
|
||||
target_include_directories(KSwitcherFilesImageTests PRIVATE src)
|
||||
target_compile_definitions(KSwitcherFilesImageTests PRIVATE NOMINMAX)
|
||||
target_link_libraries(KSwitcherFilesImageTests PRIVATE KSwitcherFilesImage webp)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesImageTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
target_compile_options(KSwitcherFilesImageTests PRIVATE /utf-8)
|
||||
elseif(MINGW)
|
||||
target_link_options(KSwitcherFilesImageTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME files-image COMMAND KSwitcherFilesImageTests)
|
||||
add_executable(KSwitcherFilesModalTests tests/files_modal_dialog.cpp)
|
||||
target_include_directories(KSwitcherFilesModalTests PRIVATE src)
|
||||
target_link_libraries(KSwitcherFilesModalTests PRIVATE user32 comctl32)
|
||||
@@ -198,6 +223,16 @@ 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"
|
||||
-Executable "$<TARGET_FILE:KSwitcherFiles>")
|
||||
set_tests_properties(files-space-analyzer-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 25)
|
||||
find_program(KSWITCHER_NODE NAMES node)
|
||||
if(KSWITCHER_NODE)
|
||||
add_test(NAME files-terminal-enter
|
||||
@@ -210,7 +245,7 @@ if(KSWITCHER_NODE)
|
||||
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
|
||||
target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText)
|
||||
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText KSwitcherFilesImage)
|
||||
add_dependencies(KSwitcherFilesMarkdownLanFixture KSwitcherTerminalAssets)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesMarkdownLanFixture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
@@ -314,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 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 .)
|
||||
|
||||
+226
-24
@@ -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,75 @@ Warning і початковий фокус на No.
|
||||
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
|
||||
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
|
||||
|
||||
- **SFTP** у меню джерел обох панелей відкриває збережені SSH-підключення.
|
||||
Shift+F4 додає профіль, F4 редагує, Enter підключається. Укажи ім’я
|
||||
користувача, хост, порт (типово 22) та пароль або повний шлях до ключа.
|
||||
Поле пароля приймає кодову фразу для ключа. Windows DPAPI захищає
|
||||
збережений пароль або кодову фразу. Для ключа користувача підходить
|
||||
незашифрований RSA PEM або ECDSA OpenSSH із файлом .pub поруч.
|
||||
ECDSA OpenSSH підтримує кодову фразу. Ключ залишається у вказаному файлі.
|
||||
- У **Test connection** звір SHA‑256-відбиток ключа хоста з адміністратором
|
||||
сервера та підтвердь довіру. Після цього Files перевіряє вхід. **Save**
|
||||
зберігає профіль і підтверджений відбиток. Якщо відбиток змінюється,
|
||||
Files блокує підключення до передачі пароля або підпису.
|
||||
Для запланованої заміни ключа використовуй **Forget host key**,
|
||||
а тоді **Test connection** зі звіркою нового відбитка.
|
||||
- **Jump via** у SFTP-профілі вибирає попередній збережений SSH-профіль
|
||||
у маршруті. **Direct** підключається напряму. Профіль-посередник може
|
||||
мати власний **Jump via**. Кожен хост має окремий довірений ключ і
|
||||
перевіряється до входу. Маршрут підтримує до восьми хостів і перевіряється
|
||||
на цикли під час збереження. Профіль без доступу до SFTP можна
|
||||
використовувати для пересилання через SSH.
|
||||
- На підключеній SFTP-панелі Ctrl+O відкриває інтерактивну SSH-сесію.
|
||||
Enter після введення команди запускає ту саму сесію з командного рядка.
|
||||
Після `cd` успішно відкритий каталог відображається в панелі.
|
||||
Зміна каталогу в панелі також оновлює робочу папку сесії.
|
||||
Поки команда працює, термінал приймає її інтерактивне введення, зокрема
|
||||
Ctrl+C. При переході до іншої панелі чи джерела сесія від'єднується.
|
||||
Для синхронізації потрібні POSIX-оболонка й утиліта `base64` на сервері.
|
||||
Оболонка та SFTP мають бачити однакові абсолютні шляхи.
|
||||
- Для SFTP використовуються ключі хоста ECDSA або RSA з підписом SHA‑2.
|
||||
F3 і F4 відкривають Viewer та Editor. F2 в Editor перевіряє розмір і час
|
||||
зміни віддаленого файла перед збереженням. F5 копіює між локальною
|
||||
та SFTP-панеллю в обидва боки зі спільним прогресом, скасуванням і
|
||||
підтвердженням конфліктів. Для заміни існуючого файла сервер має
|
||||
підтримувати атомарне перейменування OpenSSH. Якщо сервер відмовляє
|
||||
в заміні, Files показує причину й зберігає попередній файл.
|
||||
|
||||
- **SMB** у меню джерел обох панелей відкриває збережені підключення.
|
||||
**New** додає назву й сервер або повний UNC-шлях. **Open** для сервера
|
||||
показує видимі дискові шари. Відомий прихований шар можна додати як
|
||||
повний UNC-шлях. Вибір шару або відкриття профілю з UNC-папкою переходить
|
||||
до цієї папки в панелі, з якої викликали меню.
|
||||
- Для SMB діють дозволи Windows. **Sign in** використовує вказаний
|
||||
обліковий запис. Прапорець **Remember in Windows Credential Manager**
|
||||
типово вимкнений. Коли його ввімкнено, після успішного підключення Windows
|
||||
зберігає облікові дані для цього профілю. **Remove** видаляє профіль і
|
||||
його збережені облікові дані після підтвердження.
|
||||
- Якщо SMB недоступний, повідомлення показує причину й залишає список
|
||||
підключень відкритим. **Open** повторює спробу. Коли Windows повідомляє
|
||||
про наявний сеанс до цього сервера з іншим записом, Files пропонує
|
||||
вибрати той запис або завершити попередній сеанс у Windows.
|
||||
|
||||
- **F9 → Commands → Compare files** порівнює два позначені текстові файли
|
||||
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
|
||||
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
|
||||
FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
|
||||
рядків і підсвічуванням вставок, видалень і замін. У замінених рядках
|
||||
виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8)
|
||||
переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків.
|
||||
FTP- та SFTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
|
||||
рядків і підсвічуванням вставок, видалень і замін. **Unified** перемикає
|
||||
на єдину колонку з номерами рядків обох файлів, видаленнями зі знаком −
|
||||
і вставками зі знаком +. Перемикання зберігає поточний блок.
|
||||
**Fold unchanged** згортає довгі незмінені ділянки до рядка з лічильником
|
||||
і залишає до трьох рядків контексту перед і після кожного блока.
|
||||
У замінених рядках виділяється змінений фрагмент. **Previous** (F7) і
|
||||
**Next** (F8) переходять між блоками змін в обох поданнях.
|
||||
Подвійний клік відкриває повний текст пари рядків.
|
||||
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
|
||||
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
|
||||
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
|
||||
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
|
||||
Текст файлів і порожня область під ним мають білий фон, рядки
|
||||
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
|
||||
Центральний розділювач можна перетягнути мишею. Під час зміни розміру
|
||||
У поданні поруч центральний розділювач можна перетягнути мишею. Під час зміни розміру
|
||||
вікна пропорція колонок зберігається.
|
||||
Ctrl+колесо змінює масштаб тексту в поточному вікні.
|
||||
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
|
||||
@@ -79,18 +141,25 @@ Warning і початковий фокус на No.
|
||||
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
|
||||
і меню Commands показує поточне призначення.
|
||||
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
|
||||
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
|
||||
типово пропускаються. Перемикач **Show whitespace changes** показує їх
|
||||
в обох поданнях і враховує під час згортання.
|
||||
Вставлені й видалені порожні рядки враховуються завжди.
|
||||
**Apply to left/right** копіює виділений блок у відповідну сторону.
|
||||
Порівняння перераховується, а змінену сторону позначає зірочка.
|
||||
**Undo** або **Ctrl+Z** повертає останню незаписану дію.
|
||||
**Save left/right** зберігає відповідну сторону, **Ctrl+S** зберігає обидві.
|
||||
Зовнішня зміна цільового файла зупиняє запис і залишає правки для перегляду.
|
||||
Закриття зі змінами пропонує Save, Discard або Cancel.
|
||||
Кнопка розгортання в системному заголовку збільшує вікно порівняння
|
||||
до робочої області екрана. Повторне натискання відновлює попередній розмір.
|
||||
Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM,
|
||||
до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються
|
||||
як рівнозначні.
|
||||
Підтримуються UTF-8 і UTF-16 з BOM, до 2 МіБ і 100 000 рядків на файл.
|
||||
Стилі переносу рядків порівнюються як рівнозначні. Під час запису
|
||||
зберігаються кодування, BOM і наявні кінці рядків цільового файла.
|
||||
|
||||
- У меню Files і його списках, що випадають, стрілки вгору й вниз
|
||||
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
|
||||
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
|
||||
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP.
|
||||
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP, SFTP і SMB.
|
||||
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
|
||||
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
|
||||
до закриття меню, навіть коли оновлюється список LAN.
|
||||
@@ -127,8 +196,12 @@ Warning і початковий фокус на No.
|
||||
виконує команду одразу. Коли рядок
|
||||
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
|
||||
Enter передає порожній рядок у термінал.
|
||||
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
|
||||
командного рядка й виконують відповідну дію за тими самими правилами.
|
||||
У повноекранному терміналі (Ctrl+O) команда редагується в промпті
|
||||
під виводом. Клік у терміналі повертає курсор у промпт. Стрілки вгору й
|
||||
вниз без відкритого списку підказок переглядають спільну історію, а після
|
||||
останньої команди вниз повертає чернетку. Підказки відкриваються біля
|
||||
курсора. Ctrl+C перериває поточну команду, а за виділеного тексту виводу
|
||||
копіює виділення. Escape з порожнім промптом також перериває команду.
|
||||
Локальна команда запускається в папці активної панелі, яку показано
|
||||
перед командним рядком. Після перемикання панелі або переходу до іншої
|
||||
папки наступна команда використовує нову папку навіть у вже відкритому
|
||||
@@ -204,6 +277,17 @@ Warning і початковий фокус на No.
|
||||
Незбережені зміни у примусово закритих вікнах втрачаються.
|
||||
Закриття процесів і результат записуються до `kswitcher.log`.
|
||||
|
||||
- У файловій панелі Ctrl+C копіює позначені або поточний локальний
|
||||
елемент у файловий буфер Windows. Ctrl+V вставляє файли й папки в
|
||||
поточний локальний каталог через звичайний діалог Copy і показує
|
||||
конфлікти та прогрес. Клік або навігація у файловій панелі вибирають
|
||||
файловий контекст. Клік у командному рядку або введення тексту
|
||||
повертають текстовий контекст Ctrl+C / Ctrl+V.
|
||||
|
||||
- **Commands → Copy full path** або **Ctrl+Shift+C** копіює повний шлях
|
||||
файла чи папки під курсором як текст. У LAN- і FTP-панелях текст включає
|
||||
адресу віддаленого джерела. Для рядка `..` команда не змінює буфер.
|
||||
|
||||
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
|
||||
курсора командного рядка або замінює виділення. Подвійні лапки додаються
|
||||
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
|
||||
@@ -283,7 +367,7 @@ Warning і початковий фокус на No.
|
||||
|
||||
- Ctrl+Shift+0–9 відкриває діалог Title і Path із поточною папкою. OK додає запис без дублювання, Escape скасовує. Title необов’язковий, порожнє значення показує шлях. Записи LAN зберігають ID ПК, а редагування Path залишає запис на тому самому ПК.
|
||||
- Ctrl+0–9 відкриває лише папки, призначені натиснутій цифрі. Єдина папка відкривається одразу. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
|
||||
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options.
|
||||
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10 перемикає List і Tree. Ctrl+F11 перемикає фоновий підрахунок розмірів папок. Brief, Wide, Medium і Full доступні в меню Left/Right та Options → Panel layout.
|
||||
|
||||
## Налаштування Files
|
||||
|
||||
@@ -300,8 +384,18 @@ Warning і початковий фокус на No.
|
||||
При повторному відкритті Files пропонує перейти до вже
|
||||
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
|
||||
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
|
||||
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
|
||||
Помилка збереження залишає відкритим редактор зі змінами.
|
||||
Viewer показує збережену версію, а чернетка зберігається в поточному
|
||||
вікні з позначкою Draft retained. Повторне F6 повертає правки, сторінку,
|
||||
виділення й прокрутку.
|
||||
Для нового файла Viewer показує порожній документ. Закриття вікна
|
||||
з чернеткою в обох режимах пропонує Save, Discard або Cancel.
|
||||
- **Shift+F3** або **Commands → View as hex** відкриває файл у Hex Viewer.
|
||||
**F4** у Viewer перемикає текстовий або форматований перегляд і Hex.
|
||||
Hex показує 64-бітну адресу, 16 вихідних байтів у рядку й ASCII.
|
||||
Нульові й недруковані байти видно в hex, а в ASCII їх позначає крапка.
|
||||
Блоки по 64 КіБ перемикаються через Ctrl+Page Up, Ctrl+Page Down або F5.
|
||||
Esc повертає до попереднього режиму Viewer або, якщо файл відкрито
|
||||
напряму в Hex, до файлової панелі.
|
||||
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
|
||||
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
|
||||
порядку. Коли відкрито лише Files, активна панель не змінюється.
|
||||
@@ -379,6 +473,15 @@ Warning і початковий фокус на No.
|
||||
Ctrl+Shift+Home/End відкривають першу й останню. Ctrl+F шукає в поточній
|
||||
сторінці, F3 повторює пошук. Ctrl+A виділяє поточну сторінку.
|
||||
Історія Undo/Redo діє в межах відкритої сторінки.
|
||||
- **Ctrl+D** або **Navigate → Add bookmark** у Viewer додає закладку
|
||||
на рядок локального файла. Номер рахується від початку файла, а назва
|
||||
необов’язкова. У Markdown номер можна вказати за вихідним текстом.
|
||||
**Navigate → Bookmarks in this file** і **All bookmarks** відкривають
|
||||
відповідні списки. **Commands → Viewer bookmarks** у панелях працює,
|
||||
навіть коли Viewer закрито. Списки зберігаються після перезапуску.
|
||||
Open переходить до рядка, для Markdown у вихідному тексті. Rename
|
||||
змінює назву, Remove видаляє закладку. Якщо файл або рядок недоступний,
|
||||
Files показує повідомлення.
|
||||
- Початкова сторінка займає близько 1 МіБ файла. Для вставок і редагування
|
||||
сторінка може вирости до 8 МіБ у UTF-8. Зміни інших сторінок тимчасово
|
||||
зберігаються на диску. F2 або Ctrl+S потоково записують нову копію в
|
||||
@@ -444,6 +547,46 @@ Warning і початковий фокус на No.
|
||||
переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
|
||||
з тією самою маскою й видимістю прихованих файлів.
|
||||
|
||||
- **Left/Right → Tree view** або Ctrl+F10 перемикає вигляд відповідної
|
||||
панелі незалежно від Brief і Wide. Enter, подвійний клік чи стрілка біля
|
||||
папки розкриває або згортає гілку. Стрілки вправо й вліво працюють із
|
||||
гілкою та її батьківською папкою. Вміст гілки читається у фоні під час
|
||||
розкриття. Позначки згорнутих гілок залишаються доступними для F5, F6 і F8.
|
||||
Якщо позначено папку та її вміст, команда обробляє їх одним деревом.
|
||||
Повернення до List відкриває батьківську папку поточного елемента.
|
||||
- **Background folder sizes** або Ctrl+F11 вмикає вимірювання видимих папок
|
||||
у фоні для відповідної панелі. Під час оновлення попереднє число лишається
|
||||
поруч із символом … . Знак + позначає частковий розмір. Error з’являється,
|
||||
коли вимірювання недоступне. Якщо попереднє число є, позначка ! відрізняє
|
||||
його від свіжого результату.
|
||||
|
||||
- **Commands → Space Analyzer** показує місткість і вільне місце за даними
|
||||
Windows перед скануванням. Volume вибирає корінь тому, Folder повертає
|
||||
поточну локальну папку, Start запускає фоновий аналіз тим самим обходом,
|
||||
що й підрахунок розмірів F3. Посилання на каталоги всередині області
|
||||
сканування позначаються як link. Stop залишає часткові результати, а
|
||||
Rescan повторює аналіз із початку.
|
||||
- Дерево показує логічний розмір, зайняті байти та частку логічного розміру
|
||||
від батьківської папки. Знак + позначає частковий підрахунок. Зайняті байти
|
||||
підсумовуються за файловими записами, включно з окремими іменами для
|
||||
жорстких посилань. Службові дані файлової системи в цей підсумок не входять.
|
||||
Відсутні дані про зайняті байти позначаються в рядку стану.
|
||||
- Treemap показує дочірні елементи вибраної папки прямокутниками,
|
||||
пропорційними до їхнього логічного розміру. Дрібні елементи доступні в
|
||||
дереві. Клік по плитці відкриває точний елемент у сусідній панелі. Стрілки
|
||||
переводять фокус між плитками, Enter відкриває плитку у фокусі.
|
||||
- Sunburst показує до трьох рівнів вкладеності секторами за логічним
|
||||
розміром. Клік по сектору та Enter у відповідному рядку списку ведуть
|
||||
до одного елемента. Обраний рядок підсвічує відповідний сектор.
|
||||
- Під час аналізу всього NTFS-тому Files використовує індекс MFT за
|
||||
наявності доступу Windows. Звичайний обхід працює без такого доступу.
|
||||
Обидва режими перераховують доступні записи каталогів, ураховують
|
||||
жорсткі посилання за їхніми іменами та позначають недоступні гілки.
|
||||
- View відкриває вибраний файл у спільному переглядачі Files. Show in
|
||||
other panel відкриває вибрану папку або ставить курсор на файл у сусідній
|
||||
панелі. Команди роботи з файлами доступні там. Якщо фільтр приховує
|
||||
вибраний файл, панель показує його до зміни фільтра або переходу в іншу папку.
|
||||
|
||||
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
|
||||
у відкритих локальних папках. Фокус залишається там, де був, а курсор
|
||||
лишається на поточному елементі, якщо той ще існує.
|
||||
@@ -471,6 +614,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 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення.
|
||||
|
||||
@@ -478,25 +626,57 @@ Warning і початковий фокус на No.
|
||||
- Process multiple names дозволяє розділити імена комами або крапками з комою. Якщо такий символ є частиною імені, візьми ім’я в подвійні лапки. Діалог створює елементи у поточному каталозі, оновлює панель і ставить курсор на останній створений елемент. При помилці в середині списку вже створені елементи зберігаються.
|
||||
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
|
||||
|
||||
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
|
||||
Розділювач Size проходить по одній вертикалі в заголовку та списку, а праві краї підпису й значень вирівняні.
|
||||
- **Left/Right → Sort by** та Ctrl+F3, Ctrl+F4, Ctrl+F5 і Ctrl+F6 сортують
|
||||
відповідну панель за іменем, розширенням, розміром і часом зміни.
|
||||
Повторний вибір того самого стовпця змінює напрямок. Клік по заголовку
|
||||
Wide виконує ту саму команду. Стрілка показує поточний напрямок.
|
||||
Ctrl+F7 перемикає пріоритет папок. За вимкненого пріоритету папки й файли
|
||||
сортуються разом. Рядок `..` лишається першим. Сортування, напрямок і
|
||||
пріоритет папок зберігаються окремо для кожної панелі.
|
||||
- Ctrl+F8 відкриває фільтр імен файлів без урахування регістру. Маска
|
||||
підтримує `*` і `?` так само, як Find files. Папки залишаються доступними
|
||||
для навігації. Порожнє поле або `*` вимикає фільтр. Позначки повертаються
|
||||
для прихованих фільтром елементів, які ще є в поточній папці.
|
||||
Ctrl+F9 перемикає показ прихованих та системних елементів окремо для
|
||||
кожної панелі. Типово їх видно. Маска діє до закриття вікна.
|
||||
- Brief показує імена. Medium додає Size. Wide показує також Ext і
|
||||
Modified. Full додає Allocated, Links і Owner. Для локальних файлів
|
||||
Allocated показує зайняте місце, Links — кількість жорстких посилань, а
|
||||
Owner — власника за даними Windows. Для відсутніх метаданих показується —.
|
||||
Modified показує місцеву дату. Сортування враховує повний час зміни.
|
||||
- **Left/Right → Columns** налаштовує видимість стовпців і автоматичну
|
||||
ширину для поточного режиму. Кожна панель зберігає свій режим і
|
||||
налаштування Medium, Wide та Full. Автоматична ширина враховує вміст.
|
||||
У вузькій панелі Name має пріоритет. Межі стовпців збігаються в заголовку
|
||||
та списку. Стрілки, PgUp, PgDn, Home та End керують рядками в усіх режимах.
|
||||
|
||||
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
|
||||
тексту й Markdown у сусідній панелі. Перегляд слідує за курсором активної
|
||||
тексту, Markdown і зображень у сусідній панелі. Перегляд слідує за курсором активної
|
||||
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
|
||||
Під час перегляду файлові операції з призначенням у сусідній панелі
|
||||
пропонують спершу закрити Quick View.
|
||||
- **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й
|
||||
вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі
|
||||
зображення в порядку вихідної панелі на момент відкриття Viewer.
|
||||
- У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб,
|
||||
перетягування мишею панорамує збільшене зображення, Fit підганяє його
|
||||
під область перегляду, а 100% повертає вихідний масштаб. Клавіші 0 і 1
|
||||
виконують Fit і 100% у сфокусованому перегляді. GIF та анімований WebP
|
||||
показують перший кадр. Пошкоджені та надто великі файли показують повідомлення.
|
||||
|
||||
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
|
||||
останні відвідані локальні папки. Повторний візит підіймає один запис
|
||||
угору, порядок зберігається після перезапуску. Enter або клік відкриває
|
||||
шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис.
|
||||
останні відвідані локальні, FTP, SFTP та LAN-папки. Повторний візит підіймає
|
||||
один запис угору, порядок зберігається після перезапуску. Enter або клік
|
||||
відкриває шлях у панелі, з якої викликали меню. Віддалені записи містять
|
||||
шлях і ідентифікатор збереженого FTP- чи SFTP-профілю або спареного ПК. Паролі
|
||||
зберігаються в захищених налаштуваннях профілів. Delete прибирає вибраний
|
||||
запис із недавніх.
|
||||
|
||||
- У локальному заголовку кнопки ← та → переходять назад і вперед
|
||||
в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..`
|
||||
- Кнопки ← та → переходять назад і вперед в історії відповідної панелі,
|
||||
зокрема між локальними, FTP, SFTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..`
|
||||
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
|
||||
а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі.
|
||||
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
|
||||
@@ -505,7 +685,10 @@ Warning і початковий фокус на No.
|
||||
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
|
||||
а Esc повертає до тих самих панелей і курсора.
|
||||
|
||||
- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі.
|
||||
- У заголовку FTP- чи SFTP-папки клік по назві профілю відкриває збережені
|
||||
підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери
|
||||
та їхні диски. Поле шляху й доповнення працюють у поточному джерелі.
|
||||
Для FTP абсолютний шлях починається з /.
|
||||
|
||||
## Спільні елементи діалогів
|
||||
|
||||
@@ -544,6 +727,25 @@ Warning і початковий фокус на No.
|
||||
- Розкриті списки й історія Far використовують спільний попап із бірюзовим тлом, світлою рамкою та чорним вибраним рядком. Попап прилягає до обох країв бірюзового поля, стрілка лишається праворуч за межами списку. Історія групується за датами. Довгі списки прокручуються, Enter вибирає рядок, Escape закриває список і повертає фокус до поля.
|
||||
- Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів.
|
||||
|
||||
## Перетягування файлів
|
||||
|
||||
- Перетягування з Explorer або іншої локальної панелі відкриває діалог
|
||||
Drop files із повним шляхом призначення та кнопками Copy, Move і Cancel.
|
||||
Якщо курсор над папкою, призначенням є ця папка. В інших випадках
|
||||
призначенням є поточна папка панелі. Cancel або Esc скасовує дію.
|
||||
- Copy і Move відкривають наявний діалог операції з її параметрами,
|
||||
перевіркою призначення, розв’язанням конфліктів і прогресом. Віддалені
|
||||
панелі, результати пошуку й віртуальні елементи Explorer без локального
|
||||
шляху не підтримують перетягування. Files повідомляє причину в рядку стану.
|
||||
|
||||
## Архіви ZIP і 7z
|
||||
|
||||
- Enter на локальному архіві відкриває його в поточній панелі. Заголовок панелі починається з Archive і містить ім’я архіву та шлях усередині нього. Enter відкриває папки всередині архіву, а рядок `..`, Alt+Up і Escape піднімають на один рівень. Вихід із кореня повертає курсор на архів.
|
||||
- F3 відкриває текстовий файл у спільному переглядачі. F5 копіює позначені записи або поточний запис у локальну папку через спільні діалоги Copy, конфлікту та прогресу. F4, F6, F7 і F8 не змінюють вміст архіву.
|
||||
- Небезпечні шляхи й посилання блокують читання архіву. Для зашифрованих записів та архівів із зашифрованими заголовками Files показує підказку про пароль.
|
||||
- **Files → Pack files** або **Alt+F5** створює в поточній локальній папці архів із позначених елементів або з поточного елемента. Розширення `.zip` чи `.7z` визначає формат.
|
||||
- **F5** з локальної панелі в панель архіву та **Ctrl+V** зі списком локальних файлів додають елементи до відкритої папки архіву. Діалог підтвердження попереджає про заміну файлів з однаковими іменами. Скасування або помилка зберігають попередній архів. Режим запису підтримує звичайні ZIP і 7z.
|
||||
|
||||
## Діалог Copy
|
||||
|
||||
- Вирівнюй підпис Existing files по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені.
|
||||
|
||||
@@ -67,6 +67,14 @@ try {
|
||||
if ($LASTEXITCODE) { throw 'Files text test build failed' }
|
||||
& (Join-Path $filesBuild 'KSwitcherFilesTextTests.exe')
|
||||
if ($LASTEXITCODE) { throw 'Files text tests failed' }
|
||||
& cmake --build $filesBuild --target KSwitcherFilesArchiveTests
|
||||
if ($LASTEXITCODE) { throw 'Files archive test build failed' }
|
||||
& (Join-Path $filesBuild 'KSwitcherFilesArchiveTests.exe')
|
||||
if ($LASTEXITCODE) { throw 'Files archive tests failed' }
|
||||
& cmake --build $filesBuild --target KSwitcherFilesImageTests
|
||||
if ($LASTEXITCODE) { throw 'Files image test build failed' }
|
||||
& (Join-Path $filesBuild 'KSwitcherFilesImageTests.exe')
|
||||
if ($LASTEXITCODE) { throw 'Files image tests failed' }
|
||||
& $compiler @common -Werror tests/settings_merge.cpp build/sync.o @driveObjects build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
|
||||
if ($LASTEXITCODE) { throw 'Settings merge test build failed' }
|
||||
& .\build\KSwitcherSettingsMergeTests.exe
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
include(ExternalProject)
|
||||
|
||||
# Keep these dependencies private to Files. Build codecs before configuring
|
||||
# libarchive so its feature checks link the exact libraries that Files ships.
|
||||
set(archive_deps "${CMAKE_CURRENT_BINARY_DIR}/files-archive")
|
||||
if(CMAKE_CONFIGURATION_TYPES)
|
||||
set(archive_configs ${CMAKE_CONFIGURATION_TYPES})
|
||||
elseif(CMAKE_BUILD_TYPE)
|
||||
set(archive_configs ${CMAKE_BUILD_TYPE})
|
||||
else()
|
||||
set(archive_configs Release)
|
||||
endif()
|
||||
|
||||
add_library(KSwitcherArchive INTERFACE)
|
||||
target_compile_definitions(KSwitcherArchive INTERFACE LIBARCHIVE_STATIC)
|
||||
function(build_files_archive config)
|
||||
set(archive_config "${archive_deps}/${config}")
|
||||
if(config STREQUAL "Debug")
|
||||
set(debug_suffix d)
|
||||
set(runtime_suffix Debug)
|
||||
endif()
|
||||
set(archive_lib "${archive_config}/lib")
|
||||
set(archive_include "${archive_config}/include")
|
||||
set(archive_cmake_args
|
||||
"-DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER}"
|
||||
"-DCMAKE_BUILD_TYPE:STRING=${config}"
|
||||
"-DCMAKE_TRY_COMPILE_CONFIGURATION:STRING=${config}"
|
||||
"-DCMAKE_INSTALL_PREFIX:PATH=${archive_config}"
|
||||
"-DCMAKE_INSTALL_LIBDIR:STRING=lib"
|
||||
"-DCMAKE_INSTALL_INCLUDEDIR:STRING=include"
|
||||
"-DCMAKE_MSVC_RUNTIME_LIBRARY:STRING=MultiThreaded${runtime_suffix}"
|
||||
"-DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW"
|
||||
"-DBUILD_SHARED_LIBS:BOOL=OFF")
|
||||
if(MSVC)
|
||||
set(zlib_name libzs)
|
||||
else()
|
||||
set(zlib_name zs)
|
||||
endif()
|
||||
set(archive_zlib "${archive_lib}/${CMAKE_STATIC_LIBRARY_PREFIX}${zlib_name}${debug_suffix}${CMAKE_STATIC_LIBRARY_SUFFIX}")
|
||||
set(archive_lzma "${archive_lib}/${CMAKE_STATIC_LIBRARY_PREFIX}lzma${CMAKE_STATIC_LIBRARY_SUFFIX}")
|
||||
set(archive_archive "${archive_lib}/${CMAKE_STATIC_LIBRARY_PREFIX}archive${CMAKE_STATIC_LIBRARY_SUFFIX}")
|
||||
|
||||
function(files_archive_dependency name url checksum library)
|
||||
ExternalProject_Add(${name}_${config}
|
||||
PREFIX "${archive_config}/${name}"
|
||||
BINARY_DIR "${archive_config}/build/${name}"
|
||||
STAMP_DIR "${archive_config}/stamp/${name}"
|
||||
CMAKE_GENERATOR_PLATFORM "${CMAKE_GENERATOR_PLATFORM}"
|
||||
CMAKE_GENERATOR_TOOLSET "${CMAKE_GENERATOR_TOOLSET}"
|
||||
URL "${url}"
|
||||
URL_HASH "SHA256=${checksum}"
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP FALSE
|
||||
CMAKE_ARGS ${archive_cmake_args} ${ARGN}
|
||||
BUILD_COMMAND "${CMAKE_COMMAND}" --build <BINARY_DIR> --config "${config}"
|
||||
INSTALL_COMMAND "${CMAKE_COMMAND}" --install <BINARY_DIR> --config "${config}"
|
||||
BUILD_BYPRODUCTS "${library}"
|
||||
EXCLUDE_FROM_ALL TRUE
|
||||
LOG_CONFIGURE TRUE
|
||||
LOG_BUILD TRUE
|
||||
LOG_INSTALL TRUE
|
||||
LOG_OUTPUT_ON_FAILURE TRUE)
|
||||
endfunction()
|
||||
|
||||
files_archive_dependency(files_zlib
|
||||
https://github.com/madler/zlib/releases/download/v1.4/zlib-1.4.tar.gz
|
||||
02dd159783677a749c04adbdd02b55b8a2bcc7e054f51b76b549199a916ad584
|
||||
"${archive_zlib}"
|
||||
-DZLIB_BUILD_SHARED=OFF -DZLIB_BUILD_TESTING=OFF)
|
||||
files_archive_dependency(files_xz
|
||||
https://github.com/tukaani-project/xz/releases/download/v5.8.4/xz-5.8.4.tar.gz
|
||||
0014c7886930454fe8bd4228665b51af55eeae560ea135c9c4cd33f55b2591d9
|
||||
"${archive_lzma}"
|
||||
-DBUILD_TESTING=OFF -DXZ_NLS=OFF -DXZ_TOOL_XZ=OFF -DXZ_TOOL_XZDEC=OFF
|
||||
-DXZ_TOOL_LZMADEC=OFF -DXZ_TOOL_LZMAINFO=OFF -DXZ_TOOL_SCRIPTS=OFF)
|
||||
files_archive_dependency(files_libarchive
|
||||
https://github.com/libarchive/libarchive/releases/download/v3.8.11/libarchive-3.8.11.tar.gz
|
||||
900fe9fc7237c2b04f090f3c3648de8fe597525771f5035016537ce2d667d12b
|
||||
"${archive_archive}"
|
||||
"-DZLIB_INCLUDE_DIR:PATH=${archive_include}" "-DZLIB_LIBRARY:FILEPATH=${archive_zlib}"
|
||||
"-DLIBLZMA_INCLUDE_DIR:PATH=${archive_include}" "-DLIBLZMA_LIBRARY:FILEPATH=${archive_lzma}"
|
||||
-DENABLE_TAR=OFF -DENABLE_CPIO=OFF -DENABLE_CAT=OFF -DENABLE_UNZIP=OFF
|
||||
-DENABLE_TEST=OFF -DENABLE_WERROR=OFF -DENABLE_OPENSSL=OFF -DENABLE_MD=OFF
|
||||
-DMSVC_USE_STATIC_CRT=ON
|
||||
-DENABLE_LIBB2=OFF -DENABLE_LZ4=OFF -DENABLE_ZSTD=OFF -DENABLE_BZip2=OFF
|
||||
-DENABLE_LIBXML2=OFF -DENABLE_EXPAT=OFF -DENABLE_WIN32_XMLLITE=OFF
|
||||
-DENABLE_PCREPOSIX=OFF -DENABLE_PCRE2POSIX=OFF -DENABLE_ICONV=OFF)
|
||||
add_dependencies(files_libarchive_${config} files_zlib_${config} files_xz_${config})
|
||||
add_dependencies(KSwitcherArchive files_libarchive_${config})
|
||||
if(CMAKE_CONFIGURATION_TYPES)
|
||||
set(config_matches "$<CONFIG:${config}>")
|
||||
else()
|
||||
set(config_matches 1)
|
||||
endif()
|
||||
target_include_directories(KSwitcherArchive INTERFACE "$<${config_matches}:${archive_include}>")
|
||||
target_link_libraries(KSwitcherArchive INTERFACE
|
||||
"$<${config_matches}:${archive_archive};${archive_zlib};${archive_lzma}>")
|
||||
endfunction()
|
||||
|
||||
foreach(config IN LISTS archive_configs)
|
||||
build_files_archive("${config}")
|
||||
endforeach()
|
||||
target_link_libraries(KSwitcherArchive INTERFACE bcrypt)
|
||||
target_link_libraries(KSwitcherFiles PRIVATE KSwitcherArchive)
|
||||
@@ -0,0 +1,25 @@
|
||||
include(FetchContent)
|
||||
FetchContent_Declare(files_webp
|
||||
URL https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-1.6.0.tar.gz
|
||||
URL_HASH SHA256=e4ab7009bf0629fd11982d4c2aa83964cf244cffba7347ecd39019a9e38c4564
|
||||
DOWNLOAD_EXTRACT_TIMESTAMP FALSE
|
||||
SOURCE_SUBDIR kswitcher-download-only)
|
||||
FetchContent_MakeAvailable(files_webp)
|
||||
|
||||
function(build_files_webp)
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
foreach(component IN ITEMS ANIM_UTILS CWEBP DWEBP GIF2WEBP IMG2WEBP VWEBP WEBPINFO LIBWEBPMUX WEBPMUX EXTRAS)
|
||||
set(WEBP_BUILD_${component} OFF)
|
||||
endforeach()
|
||||
add_subdirectory("${files_webp_SOURCE_DIR}" "${files_webp_BINARY_DIR}" EXCLUDE_FROM_ALL)
|
||||
endfunction()
|
||||
build_files_webp()
|
||||
|
||||
add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_view.cpp)
|
||||
target_compile_definitions(KSwitcherFilesImage PRIVATE NOMINMAX UNICODE _UNICODE _WIN32_WINNT=0x0A00)
|
||||
target_link_libraries(KSwitcherFilesImage PRIVATE webpdemux windowscodecs msimg32 ole32)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesImage PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
target_compile_options(KSwitcherFilesImage PRIVATE /utf-8)
|
||||
endif()
|
||||
@@ -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()
|
||||
+4
-1
@@ -12,6 +12,9 @@ Copy-Item -LiteralPath (Join-Path $root 'build\release\terminal') -Destination $
|
||||
Copy-Item -LiteralPath (Join-Path $root 'LICENSE') -Destination $destination
|
||||
Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -Destination $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
|
||||
@@ -20,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','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()}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
libarchive 3.8.11
|
||||
https://www.libarchive.org/
|
||||
|
||||
The libarchive distribution as a whole is Copyright by Tim Kientzle
|
||||
and is subject to the copyright notice reproduced at the bottom of
|
||||
this file.
|
||||
|
||||
Each individual file in this distribution should have a clear
|
||||
copyright/licensing statement at the beginning of the file. If any do
|
||||
not, please let me know and I will rectify it. The following is
|
||||
intended to summarize the copyright status of the individual files;
|
||||
the actual statements in the files are controlling.
|
||||
|
||||
* Except as listed below, all C sources (including .c and .h files)
|
||||
and documentation files are subject to the copyright notice reproduced
|
||||
at the bottom of this file.
|
||||
|
||||
* The following source files are also subject in whole or in part to
|
||||
a 3-clause UC Regents copyright; please read the individual source
|
||||
files for details:
|
||||
libarchive/archive_read_support_filter_compress.c
|
||||
libarchive/archive_write_add_filter_compress.c
|
||||
libarchive/mtree.5
|
||||
|
||||
* The following source files are in the public domain:
|
||||
libarchive/archive_parse_date.c
|
||||
|
||||
* The following source files are triple-licensed with the ability to choose
|
||||
from CC0 1.0 Universal, OpenSSL or Apache 2.0 licenses:
|
||||
libarchive/archive_blake2.h
|
||||
libarchive/archive_blake2_impl.h
|
||||
libarchive/archive_blake2s_ref.c
|
||||
libarchive/archive_blake2sp_ref.c
|
||||
|
||||
* The build files---including Makefiles, configure scripts,
|
||||
and auxiliary scripts used as part of the compile process---have
|
||||
widely varying licensing terms. Please check individual files before
|
||||
distributing them to see if those restrictions apply to you.
|
||||
|
||||
I intend for all new source code to use the license below and hope over
|
||||
time to replace code with other licenses with new implementations that
|
||||
do use the license below. The varying licensing of the build scripts
|
||||
seems to be an unavoidable mess.
|
||||
|
||||
|
||||
Copyright (c) 2003-2018 <author(s)>
|
||||
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
|
||||
in this position and unchanged.
|
||||
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.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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 AUTHOR(S) 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.
|
||||
|
||||
zlib 1.4
|
||||
https://zlib.net/
|
||||
|
||||
Copyright notice:
|
||||
|
||||
(C) 1995-2026 Jean-loup Gailly and Mark Adler
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
|
||||
Jean-loup Gailly Mark Adler
|
||||
[email protected] [email protected]
|
||||
|
||||
liblzma from XZ Utils 5.8.4
|
||||
https://tukaani.org/xz/
|
||||
Copyright (C) The XZ Utils authors and contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this
|
||||
software for any purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
|
||||
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
|
||||
THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
|
||||
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
|
||||
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
@@ -0,0 +1,56 @@
|
||||
libwebp 1.6.0
|
||||
https://developers.google.com/speed/webp
|
||||
|
||||
Copyright (c) 2010, Google Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* 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.
|
||||
|
||||
* Neither the name of Google 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.
|
||||
|
||||
Additional IP Rights Grant (Patents)
|
||||
------------------------------------
|
||||
|
||||
"These implementations" means the copyrightable works that implement the WebM
|
||||
codecs distributed by Google as part of the WebM Project.
|
||||
|
||||
Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge,
|
||||
royalty-free, irrevocable (except as stated in this section) patent license to
|
||||
make, have made, use, offer to sell, sell, import, transfer, and otherwise
|
||||
run, modify and propagate the contents of these implementations of WebM, where
|
||||
such license applies only to those patent claims, both currently owned by
|
||||
Google and acquired in the future, licensable by Google that are necessarily
|
||||
infringed by these implementations of WebM. This grant does not include claims
|
||||
that would be infringed only as a consequence of further modification of these
|
||||
implementations. If you or your agent or exclusive licensee institute or order
|
||||
or agree to the institution of patent litigation or any other patent
|
||||
enforcement activity against any entity (including a cross-claim or
|
||||
counterclaim in a lawsuit) alleging that any of these implementations of WebM
|
||||
or any code incorporated within any of these implementations of WebM
|
||||
constitute direct or contributory patent infringement, or inducement of
|
||||
patent infringement, then any patent rights granted to you under this License
|
||||
for these implementations of WebM shall terminate as of the date such
|
||||
litigation is filed.
|
||||
@@ -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.
|
||||
*/
|
||||
+160
-6
@@ -100,6 +100,30 @@ BEGIN
|
||||
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
|
||||
END
|
||||
|
||||
613 DIALOGEX 0, 0, 255, 100
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Line:", 534, 14, 17, 60, 12
|
||||
FAR_EDIT(536, ES_NUMBER | WS_BORDER, 75, 16, 166, 14)
|
||||
LTEXT "&Name (optional):", 537, 14, 37, 227, 12
|
||||
FAR_EDIT(535, WS_BORDER, 14, 50, 227, 14)
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 76, 60, 16
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 76, 60, 16
|
||||
END
|
||||
|
||||
614 DIALOGEX 0, 0, 418, 166
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 541, 14, 16, 390, 12, SS_PATHELLIPSIS | SS_NOPREFIX
|
||||
LISTBOX 538, 14, 33, 390, 100, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP
|
||||
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 83, 140, 58, 16
|
||||
CONTROL "Re&name", 539, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 140, 58, 16
|
||||
CONTROL "&Remove", 540, "Button", BS_OWNERDRAW | WS_TABSTOP, 211, 140, 58, 16
|
||||
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 275, 140, 58, 16
|
||||
END
|
||||
|
||||
609 DIALOGEX 0, 0, 350, 135
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
@@ -132,8 +156,10 @@ BEGIN
|
||||
EDITTEXT 270, 8, 21, 113, 14, ES_AUTOHSCROLL
|
||||
CONTROL "", 271, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 8, 40, 113, 240
|
||||
LTEXT "", 272, 131, 8, 253, 12
|
||||
AUTOCHECKBOX "Left panel: &Wide", 273, 132, 27, 115, 12
|
||||
AUTOCHECKBOX "Right panel: W&ide", 274, 251, 27, 125, 12
|
||||
LTEXT "&Left panel", 506, 132, 27, 108, 11
|
||||
COMBOBOX 273, 132, 40, 108, 74, CBS_DROPDOWNLIST | WS_TABSTOP
|
||||
LTEXT "&Right panel", 507, 251, 27, 117, 11
|
||||
COMBOBOX 274, 251, 40, 117, 74, CBS_DROPDOWNLIST | WS_TABSTOP
|
||||
GROUPBOX "Wide panel columns", 275, 129, 27, 259, 59
|
||||
LTEXT "Size column &width (6–16 characters)", 276, 138, 44, 175, 10
|
||||
EDITTEXT 201, 335, 41, 43, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
@@ -392,11 +418,12 @@ EXSTYLE WS_EX_APPWINDOW
|
||||
CAPTION "Compare files"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "", 400, 4, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 401, 259, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 45, 510, 207
|
||||
LTEXT "", 400, 4, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 401, 259, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 65, 510, 187
|
||||
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
|
||||
LTEXT "", 403, 216, 12, 98, 14
|
||||
CONTROL "", 408, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 28, 490, 19
|
||||
END
|
||||
|
||||
115 DIALOGEX 0, 0, 290, 58
|
||||
@@ -404,7 +431,7 @@ STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Compare files"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
|
||||
LTEXT "Reading and comparing files...", 548, 14, 15, 262, 13
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
|
||||
END
|
||||
|
||||
@@ -432,3 +459,130 @@ BEGIN
|
||||
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
|
||||
END
|
||||
|
||||
118 DIALOGEX 0, 0, 420, 209
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Space Analyzer"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 488, 16, 15, 353, 13, SS_PATHELLIPSIS
|
||||
LTEXT "", 495, 16, 28, 353, 13, SS_ENDELLIPSIS
|
||||
CONTROL "Vo&lume", 496, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 64, 16
|
||||
CONTROL "Tree&map", 497, "Button", BS_OWNERDRAW | WS_TABSTOP, 84, 43, 64, 16
|
||||
CONTROL "S&unburst", 499, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 43, 64, 16
|
||||
LTEXT "Sunburst items", 501, 171, 43, 201, 16, NOT WS_VISIBLE
|
||||
LISTBOX 500, 171, 60, 201, 105, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | NOT WS_VISIBLE
|
||||
CONTROL "", 498, "Static", SS_OWNERDRAW | SS_NOTIFY | WS_TABSTOP | NOT WS_VISIBLE, 16, 60, 353, 105
|
||||
CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131
|
||||
LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS
|
||||
LTEXT "", 491, 12, 184, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "S&top", 492, "Button", BS_OWNERDRAW | WS_TABSTOP, 22, 189, 46, 16
|
||||
CONTROL "St&art", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16
|
||||
CONTROL "&View", 494, "Button", BS_OWNERDRAW | WS_TABSTOP, 126, 189, 46, 16
|
||||
CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16
|
||||
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16
|
||||
END
|
||||
|
||||
119 DIALOGEX 0, 0, 260, 197
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Panel columns"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
AUTOCHECKBOX "E&xtension", 510, 18, 18, 224, 13
|
||||
AUTOCHECKBOX "Si&ze", 511, 18, 36, 224, 13
|
||||
AUTOCHECKBOX "&Modified", 512, 18, 54, 224, 13
|
||||
AUTOCHECKBOX "A&llocated bytes", 513, 18, 72, 224, 13
|
||||
AUTOCHECKBOX "Link cou&nt", 514, 18, 90, 224, 13
|
||||
AUTOCHECKBOX "&Owner", 515, 18, 108, 224, 13
|
||||
AUTOCHECKBOX "Automatic column &widths", 516, 18, 135, 224, 13
|
||||
LTEXT "", 517, 10, 159, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Apply", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 168, 62, 17
|
||||
CONTROL "&Reset", 518, "Button", BS_OWNERDRAW | WS_TABSTOP, 88, 168, 74, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 168, 64, 17
|
||||
END
|
||||
|
||||
120 DIALOGEX 0, 0, 290, 82
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Pack files"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "Archive name (.zip or .7z)", 530, 16, 15, 258, 12
|
||||
FAR_EDIT(531, 0, 16, 32, 258, 15)
|
||||
LTEXT "", 532, 10, 54, 1, 1, NOT WS_VISIBLE
|
||||
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, 218, 14, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "&Jump via", 568, 240, 153, 56, 14
|
||||
COMBOBOX 567, 298, 150, 106, 90, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "", 391, 10, 175, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Test connection", 564, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 183, 128, 17
|
||||
CONTROL "&Forget host key", 565, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 183, 112, 17
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 270, 183, 60, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 336, 183, 67, 17
|
||||
END
|
||||
@@ -4,12 +4,15 @@ const terminal = new Terminal({
|
||||
fontSize: 16,
|
||||
cursorBlink: false,
|
||||
cursorInactiveStyle: 'none',
|
||||
disableStdin: true,
|
||||
theme: { background: '#181818', foreground: '#e8e8e8' },
|
||||
});
|
||||
const fit = new FitAddon.FitAddon();
|
||||
terminal.parser.registerOscHandler(633, data => {
|
||||
const prefix = 'ks-directory:';
|
||||
if (data.startsWith('ks-ssh-dir:')) {
|
||||
bridge.postMessage('ssh-directory:' + data.slice(11));
|
||||
return true;
|
||||
}
|
||||
if (!data.startsWith(prefix)) return false;
|
||||
try {
|
||||
bridge.postMessage('directory:' + decodeURIComponent(data.slice(prefix.length)));
|
||||
@@ -22,7 +25,15 @@ terminal.loadAddon(fit);
|
||||
const host = document.getElementById('terminal');
|
||||
terminal.open(host);
|
||||
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
|
||||
host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true);
|
||||
const prompt = message => bridge.postMessage('prompt:' + message);
|
||||
let sshInput = false;
|
||||
host.addEventListener('pointerup', () => {
|
||||
if (!sshInput) prompt('focus-input');
|
||||
}, true);
|
||||
terminal.onData(text => {
|
||||
if (sshInput) bridge.postMessage('ssh-input:' + text);
|
||||
else if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
|
||||
});
|
||||
const screen = host.querySelector('.xterm-screen');
|
||||
let traceEnabled = false;
|
||||
let traceBudget = 4096;
|
||||
@@ -52,9 +63,28 @@ function anchorOutput() {
|
||||
currentOffset = offset;
|
||||
trace(2);
|
||||
}
|
||||
const promptKeys = new Set([
|
||||
'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End',
|
||||
'Tab', 'Escape', 'Delete', 'Backspace', 'F1',
|
||||
]);
|
||||
terminal.attachCustomKeyEventHandler(event => {
|
||||
if (event.isComposing) return true;
|
||||
if (sshInput) {
|
||||
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.metaKey) return true;
|
||||
const copy = event.code === 'KeyC' && terminal.hasSelection();
|
||||
if (!copy && (event.shiftKey || event.code !== 'KeyO')) return true;
|
||||
event.preventDefault();
|
||||
if (!event.repeat) bridge.postMessage(copy ? 'copy-command-line' : 'toggle');
|
||||
return false;
|
||||
}
|
||||
if (event.type === 'keydown' && promptKeys.has(event.key) &&
|
||||
!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {
|
||||
prompt(event.key);
|
||||
event.preventDefault();
|
||||
return false;
|
||||
}
|
||||
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
|
||||
if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter');
|
||||
if (!event.repeat) prompt(event.shiftKey ? 'shift-enter' : 'enter');
|
||||
event.preventDefault();
|
||||
return false;
|
||||
}
|
||||
@@ -85,6 +115,21 @@ terminal.onScroll(() => {
|
||||
anchorOutput();
|
||||
});
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
if (data === 'ssh-input:on' || data === 'ssh-input:off') {
|
||||
sshInput = data === 'ssh-input:on';
|
||||
terminal.options.cursorBlink = sshInput;
|
||||
terminal.write(sshInput ? '\x1b[?25h' : '\x1b[?25l');
|
||||
return;
|
||||
}
|
||||
if (data === 'ssh-focus') {
|
||||
terminal.focus();
|
||||
return;
|
||||
}
|
||||
if (data === 'ssh-reset') {
|
||||
terminal.reset();
|
||||
terminal.write('\x1b[?25l');
|
||||
return;
|
||||
}
|
||||
if (data === 'clear-selection') {
|
||||
terminal.clearSelection();
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
#include "files_archive.h"
|
||||
#include "files_win32_directory.h"
|
||||
#include "files_win32_replace.h"
|
||||
#include <objbase.h>
|
||||
#include <archive.h>
|
||||
#include <archive_entry.h>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace fs=std::filesystem;
|
||||
|
||||
bool ArchiveNameOrder::operator()(const fs::path &left,const fs::path &right) const
|
||||
{
|
||||
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)==CSTR_LESS_THAN;
|
||||
}
|
||||
|
||||
bool isArchivePath(const fs::path &path)
|
||||
{
|
||||
const auto extension=path.extension();
|
||||
return CompareStringOrdinal(extension.c_str(),-1,L".zip",-1,TRUE)==CSTR_EQUAL ||
|
||||
CompareStringOrdinal(extension.c_str(),-1,L".7z",-1,TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
using ArchiveReader=std::unique_ptr<archive,decltype(&archive_read_free)>;
|
||||
using ArchiveWriter=std::unique_ptr<archive,decltype(&archive_write_free)>;
|
||||
constexpr std::int64_t archiveEpochOffset=11644473600, archiveTicksPerSecond=10000000;
|
||||
constexpr char unsafePath[]="The archive contains an unsafe or conflicting path.";
|
||||
constexpr char encryptedArchive[]="This archive requires a password. Password-protected entries cannot be opened in Files.";
|
||||
|
||||
struct ArchiveFileHandle
|
||||
{
|
||||
HANDLE value=INVALID_HANDLE_VALUE;
|
||||
explicit ArchiveFileHandle(HANDLE handle) : value(handle)
|
||||
{
|
||||
if(value==INVALID_HANDLE_VALUE) throw std::system_error(GetLastError(),std::system_category());
|
||||
}
|
||||
ArchiveFileHandle(const ArchiveFileHandle &)=delete;
|
||||
ArchiveFileHandle &operator=(const ArchiveFileHandle &)=delete;
|
||||
~ArchiveFileHandle() {CloseHandle(value);}
|
||||
};
|
||||
|
||||
[[noreturn]] void archiveError(archive *reader)
|
||||
{
|
||||
const auto *error=archive_error_string(reader);
|
||||
std::string detail=error?error:"";
|
||||
std::transform(detail.begin(),detail.end(),detail.begin(),
|
||||
[](unsigned char ch){return static_cast<char>(std::tolower(ch));});
|
||||
if(detail.find("password")!=detail.npos || detail.find("passphrase")!=detail.npos ||
|
||||
detail.find("encrypted")!=detail.npos) throw std::runtime_error(encryptedArchive);
|
||||
throw std::runtime_error("Could not read the ZIP or 7z archive.");
|
||||
}
|
||||
|
||||
ArchiveReader openArchive(const fs::path &file)
|
||||
{
|
||||
ArchiveReader reader(archive_read_new(),archive_read_free);
|
||||
if(!reader) throw std::runtime_error("Could not create the archive reader.");
|
||||
if(archive_read_support_format_zip(reader.get())!=ARCHIVE_OK ||
|
||||
archive_read_support_format_7zip(reader.get())!=ARCHIVE_OK ||
|
||||
archive_read_open_filename_w(reader.get(),file.c_str(),64*1024)!=ARCHIVE_OK)
|
||||
archiveError(reader.get());
|
||||
return reader;
|
||||
}
|
||||
|
||||
std::pair<fs::path,ArchiveEntry> decodeEntry(archive_entry *entry)
|
||||
{
|
||||
const auto *wide=archive_entry_pathname_w(entry);
|
||||
std::wstring name=wide?wide:L"";
|
||||
if(name.empty() || name.front()==L'/' || name.front()==L'\\')
|
||||
throw std::runtime_error(unsafePath);
|
||||
std::replace(name.begin(),name.end(),L'/',L'\\');
|
||||
const auto type=archive_entry_filetype(entry);
|
||||
const bool folder=type==AE_IFDIR;
|
||||
if((!folder && type!=AE_IFREG) || archive_entry_hardlink_w(entry) || archive_entry_symlink_w(entry))
|
||||
throw std::runtime_error("The archive contains a link or an unsupported entry type.");
|
||||
fs::path relative;
|
||||
for(size_t start=0;start<name.size();)
|
||||
{
|
||||
const auto end=name.find(L'\\',start);
|
||||
const auto component=std::wstring_view(name).substr(start,end==name.npos?end:end-start);
|
||||
if(component!=L".")
|
||||
{
|
||||
if(component.size()>255 || !validWindowsFileName(component))
|
||||
throw std::runtime_error(unsafePath);
|
||||
relative/=component;
|
||||
}
|
||||
if(end==name.npos) break;
|
||||
start=end+1;
|
||||
}
|
||||
if(relative.empty() && !folder) throw std::runtime_error(unsafePath);
|
||||
const auto size=archive_entry_size(entry);
|
||||
if(size<0 || (!folder && !archive_entry_size_is_set(entry)))
|
||||
throw std::runtime_error("The archive entry has an invalid size.");
|
||||
const int64_t seconds=archive_entry_mtime(entry);
|
||||
const auto modified=archive_entry_mtime_is_set(entry) && seconds>=-archiveEpochOffset &&
|
||||
seconds<(INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)?
|
||||
static_cast<uint64_t>((seconds+archiveEpochOffset)*archiveTicksPerSecond+archive_entry_mtime_nsec(entry)/100):0;
|
||||
return {relative,{static_cast<uint64_t>(size),modified,folder,archive_entry_is_encrypted(entry)!=0}};
|
||||
}
|
||||
|
||||
void registerEntry(ArchiveEntries &entries,const fs::path &path,const ArchiveEntry &entry)
|
||||
{
|
||||
if(path.empty()) return;
|
||||
const auto [existing,inserted]=entries.try_emplace(path,entry);
|
||||
if(!inserted)
|
||||
{
|
||||
if(existing->first.native()!=path.native() || !entry.directory || !existing->second.directory ||
|
||||
!existing->second.implicit) throw std::runtime_error(unsafePath);
|
||||
existing->second=entry;
|
||||
}
|
||||
for(auto parent=path.parent_path();!parent.empty();parent=parent.parent_path())
|
||||
{
|
||||
const auto [item,fresh]=entries.try_emplace(parent,ArchiveEntry{.directory=true,.implicit=true});
|
||||
if(fresh) continue;
|
||||
if(!item->second.directory || item->first.native()!=parent.native()) throw std::runtime_error(unsafePath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
template<class Visit>
|
||||
ArchiveEntries walkArchive(const fs::path &file,const Visit &visit)
|
||||
{
|
||||
auto reader=openArchive(file);
|
||||
ArchiveEntries entries;
|
||||
for(;;)
|
||||
{
|
||||
archive_entry *raw=nullptr;
|
||||
const auto status=archive_read_next_header(reader.get(),&raw);
|
||||
if(status==ARCHIVE_EOF) return entries;
|
||||
if(status!=ARCHIVE_OK) archiveError(reader.get());
|
||||
auto [path,entry]=decodeEntry(raw);
|
||||
registerEntry(entries,path,entry);
|
||||
if(!visit(reader.get(),raw,path,entry)) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
}
|
||||
}
|
||||
|
||||
void writeMember(archive *reader,const ArchiveEntry &entry,const fs::path &output,uint64_t limit,
|
||||
const ArchiveProgress &progress)
|
||||
{
|
||||
if(entry.encrypted) throw std::runtime_error(encryptedArchive);
|
||||
if(entry.size>limit) throw std::runtime_error("The archive entry is too large to preview.");
|
||||
const ArchiveFileHandle owned(CreateFileW(output.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,
|
||||
FILE_ATTRIBUTE_NORMAL,nullptr));
|
||||
std::array<char,64*1024> buffer{};
|
||||
uint64_t done=0;
|
||||
for(;;)
|
||||
{
|
||||
if(progress && !progress(done,entry.size)) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
const auto size=archive_read_data(reader,buffer.data(),buffer.size());
|
||||
if(size<0) archiveError(reader);
|
||||
if(size==0) break;
|
||||
if(static_cast<uint64_t>(size)>entry.size-done)
|
||||
throw std::runtime_error("The archive entry exceeds its declared size.");
|
||||
DWORD written=0;
|
||||
if(!WriteFile(owned.value,buffer.data(),static_cast<DWORD>(size),&written,nullptr) ||
|
||||
written!=static_cast<DWORD>(size))
|
||||
throw std::system_error(GetLastError(),std::system_category());
|
||||
done+=written;
|
||||
}
|
||||
if(done!=entry.size) throw std::runtime_error("The archive entry is incomplete.");
|
||||
if(entry.modified)
|
||||
{
|
||||
const FILETIME time{static_cast<DWORD>(entry.modified),static_cast<DWORD>(entry.modified>>32)};
|
||||
if(!SetFileTime(owned.value,nullptr,nullptr,&time))
|
||||
throw std::system_error(GetLastError(),std::system_category());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ArchiveEntries readArchive(const fs::path &file,std::stop_token stop)
|
||||
{
|
||||
return walkArchive(file,[&](auto *,auto *,const auto &,const auto &){return !stop.stop_requested();});
|
||||
}
|
||||
|
||||
ArchiveEntry readArchiveMember(const fs::path &file,const fs::path &member,const fs::path &output,
|
||||
uint64_t limit,const ArchiveProgress &progress)
|
||||
{
|
||||
std::optional<ArchiveEntry> found;
|
||||
walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry)
|
||||
{
|
||||
if(progress && !progress(found?found->size:0,found?found->size:0)) return false;
|
||||
if(!entry.directory && path==member)
|
||||
{
|
||||
writeMember(reader,entry,output,limit,progress);
|
||||
found=entry;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if(!found) throw std::runtime_error("The archive entry is no longer available.");
|
||||
return *found;
|
||||
}
|
||||
|
||||
void extractArchiveSelection(const fs::path &file,const fs::path &directory,const std::vector<fs::path> &selection,
|
||||
const fs::path &staging,const ArchiveProgress &progress)
|
||||
{
|
||||
const std::set<fs::path> selected(selection.begin(),selection.end());
|
||||
for(const auto &path:selected)
|
||||
if(path.empty() || path.parent_path()!=directory) throw std::runtime_error(unsafePath);
|
||||
const auto wanted=[&](const fs::path &path)
|
||||
{
|
||||
for(auto item=path;!item.empty() && item!=directory;item=item.parent_path())
|
||||
if(selected.contains(item)) return true;
|
||||
return false;
|
||||
};
|
||||
const auto entries=walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry)
|
||||
{
|
||||
if(progress && !progress(0,0)) return false;
|
||||
if(!wanted(path)) return true;
|
||||
const auto output=staging/path.lexically_relative(directory);
|
||||
fs::create_directories(entry.directory?output:output.parent_path());
|
||||
if(!entry.directory) writeMember(reader,entry,output,UINT64_MAX,progress);
|
||||
return true;
|
||||
});
|
||||
for(const auto &path:selected)
|
||||
if(!entries.contains(path)) throw std::runtime_error("A selected archive entry is no longer available.");
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
BY_HANDLE_FILE_INFORMATION archiveFileInfo(HANDLE file)
|
||||
{
|
||||
BY_HANDLE_FILE_INFORMATION info{};
|
||||
if(!GetFileInformationByHandle(file,&info)) throw std::system_error(GetLastError(),std::system_category());
|
||||
return info;
|
||||
}
|
||||
|
||||
uint64_t archiveFileSize(const BY_HANDLE_FILE_INFORMATION &info)
|
||||
{
|
||||
return (uint64_t(info.nFileSizeHigh)<<32)|info.nFileSizeLow;
|
||||
}
|
||||
|
||||
bool sameArchiveFile(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
|
||||
{
|
||||
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
|
||||
left.nFileIndexLow==right.nFileIndexLow && archiveFileSize(left)==archiveFileSize(right) &&
|
||||
CompareFileTime(&left.ftLastWriteTime,&right.ftLastWriteTime)==0;
|
||||
}
|
||||
|
||||
struct ArchiveTemporaryFile
|
||||
{
|
||||
fs::path directory, file;
|
||||
|
||||
explicit ArchiveTemporaryFile(const fs::path &parent)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
|
||||
throw std::runtime_error("Could not prepare a temporary archive.");
|
||||
directory=parent/(L".ks-files-pack-"+std::wstring(name));
|
||||
file=directory/L"archive";
|
||||
if(!fs::create_directory(directory)) throw std::runtime_error("Could not prepare a temporary archive.");
|
||||
}
|
||||
|
||||
~ArchiveTemporaryFile()
|
||||
{
|
||||
std::error_code error;
|
||||
fs::remove(file,error);
|
||||
fs::remove(directory,error);
|
||||
}
|
||||
};
|
||||
|
||||
bool isZip(const fs::path &file)
|
||||
{
|
||||
return CompareStringOrdinal(file.extension().c_str(),-1,L".zip",-1,TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
HANDLE lockArchiveFolder(const fs::path &directory)
|
||||
{
|
||||
const auto lock=directory/L".ks-files-archive-write.lock";
|
||||
const HANDLE handle=CreateFileW(lock.c_str(),GENERIC_WRITE|DELETE,0,nullptr,CREATE_NEW,
|
||||
FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr);
|
||||
if(handle!=INVALID_HANDLE_VALUE) return handle;
|
||||
const DWORD error=GetLastError();
|
||||
if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS || error==ERROR_SHARING_VIOLATION)
|
||||
throw std::runtime_error("Another archive operation is active in this folder.");
|
||||
throw std::system_error(error,std::system_category());
|
||||
}
|
||||
|
||||
void checkArchiveWrite(int status)
|
||||
{
|
||||
if(status!=ARCHIVE_OK) throw std::runtime_error("Could not create the ZIP or 7z data.");
|
||||
}
|
||||
|
||||
ArchiveWriter openArchiveWriter(const fs::path &file,bool zip)
|
||||
{
|
||||
ArchiveWriter writer(archive_write_new(),archive_write_free);
|
||||
if(!writer) throw std::runtime_error("Could not create the archive writer.");
|
||||
checkArchiveWrite(zip?archive_write_set_format_zip(writer.get()):archive_write_set_format_7zip(writer.get()));
|
||||
checkArchiveWrite(archive_write_set_options(writer.get(),zip?"hdrcharset=UTF-8":"compression=lzma2"));
|
||||
checkArchiveWrite(archive_write_open_filename_w(writer.get(),file.c_str()));
|
||||
return writer;
|
||||
}
|
||||
|
||||
struct ArchiveInput
|
||||
{
|
||||
fs::path source;
|
||||
BY_HANDLE_FILE_INFORMATION info;
|
||||
};
|
||||
|
||||
using ArchiveInputs=std::map<fs::path,ArchiveInput,ArchiveNameOrder>;
|
||||
|
||||
void addArchiveInput(ArchiveInputs &inputs,const fs::path &source,const fs::path &member,const fs::path &target,
|
||||
const std::function<void()> &checkCanceled)
|
||||
{
|
||||
checkCanceled();
|
||||
if(member.empty() || member.filename().native().size()>255 || !validWindowsFileName(member.filename().native()))
|
||||
throw std::runtime_error("A selected file has a name that cannot be stored safely in the archive.");
|
||||
std::error_code error;
|
||||
if(fs::equivalent(source,target,error)) throw std::runtime_error("The archive cannot contain itself.");
|
||||
if(fs::equivalent(source,target.parent_path(),error))
|
||||
throw std::runtime_error("Choose an archive location outside the selected folders.");
|
||||
const ArchiveFileHandle file(CreateFileW(source.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE,
|
||||
nullptr,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr));
|
||||
const auto info=archiveFileInfo(file.value);
|
||||
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT)
|
||||
throw std::runtime_error("The selection contains a Windows link or reparse point.");
|
||||
if(!inputs.emplace(member,ArchiveInput{source,info}).second)
|
||||
throw std::runtime_error("The selection contains conflicting names.");
|
||||
if(!(info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) return;
|
||||
for(const auto &child:fs::directory_iterator(source))
|
||||
addArchiveInput(inputs,child.path(),member/child.path().filename(),target,checkCanceled);
|
||||
}
|
||||
|
||||
template<class Read>
|
||||
void transferArchiveData(archive *writer,uint64_t size,const Read &read,const std::function<void(uint64_t)> &advance)
|
||||
{
|
||||
std::array<char,64*1024> buffer{};
|
||||
uint64_t bytes=0;
|
||||
while(bytes<size)
|
||||
{
|
||||
const auto count=read(buffer.data(),static_cast<DWORD>(std::min<uint64_t>(size-bytes,buffer.size())));
|
||||
if(!count) throw std::runtime_error("An archive input ended before its declared size.");
|
||||
if(archive_write_data(writer,buffer.data(),count)!=static_cast<la_ssize_t>(count))
|
||||
throw std::runtime_error("Could not write archive contents.");
|
||||
bytes+=count;
|
||||
advance(count);
|
||||
}
|
||||
if(read(buffer.data(),1)!=0) throw std::runtime_error("An archive input changed size while it was being written.");
|
||||
checkArchiveWrite(archive_write_finish_entry(writer));
|
||||
}
|
||||
|
||||
void archiveLocalInput(archive *writer,const fs::path &path,const ArchiveInput &input,
|
||||
const std::function<void(uint64_t)> &advance)
|
||||
{
|
||||
const bool folder=(input.info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
|
||||
std::unique_ptr<archive_entry,decltype(&archive_entry_free)> entry(archive_entry_new(),archive_entry_free);
|
||||
if(!entry) throw std::runtime_error("Could not create an archive entry.");
|
||||
const auto name=path.generic_wstring();
|
||||
archive_entry_copy_pathname_w(entry.get(),name.c_str());
|
||||
archive_entry_set_filetype(entry.get(),folder?AE_IFDIR:AE_IFREG);
|
||||
archive_entry_set_perm(entry.get(),folder?0755:0644);
|
||||
const uint64_t size=folder?0:archiveFileSize(input.info);
|
||||
archive_entry_set_size(entry.get(),static_cast<la_int64_t>(size));
|
||||
const auto stamp=(uint64_t(input.info.ftLastWriteTime.dwHighDateTime)<<32)|input.info.ftLastWriteTime.dwLowDateTime;
|
||||
archive_entry_set_mtime(entry.get(),static_cast<int64_t>(stamp/archiveTicksPerSecond)-archiveEpochOffset,
|
||||
static_cast<long>((stamp%archiveTicksPerSecond)*100));
|
||||
if(folder)
|
||||
{
|
||||
checkArchiveWrite(archive_write_header(writer,entry.get()));
|
||||
checkArchiveWrite(archive_write_finish_entry(writer));
|
||||
return;
|
||||
}
|
||||
const ArchiveFileHandle file(CreateFileW(input.source.c_str(),GENERIC_READ,FILE_SHARE_READ,nullptr,OPEN_EXISTING,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_SEQUENTIAL_SCAN,nullptr));
|
||||
const auto current=archiveFileInfo(file.value);
|
||||
if((current.dwFileAttributes&(FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY)) ||
|
||||
!sameArchiveFile(input.info,current))
|
||||
throw std::runtime_error("A selected file changed before it could be added.");
|
||||
checkArchiveWrite(archive_write_header(writer,entry.get()));
|
||||
transferArchiveData(writer,size,[&](char *buffer,DWORD goal)
|
||||
{
|
||||
DWORD used=0;
|
||||
if(!ReadFile(file.value,buffer,goal,&used,nullptr))
|
||||
throw std::system_error(GetLastError(),std::system_category());
|
||||
return used;
|
||||
},advance);
|
||||
}
|
||||
}
|
||||
|
||||
void writeArchive(const fs::path &file,ArchiveWriteMode mode,const fs::path &directory,
|
||||
const std::vector<fs::path> &sources,const ArchiveProgress &progress)
|
||||
{
|
||||
if(!isArchivePath(file)) throw std::runtime_error("Files can write ZIP and 7z archives.");
|
||||
if(!file.is_absolute() || !validWindowsFileName(file.filename().native()) || sources.empty())
|
||||
throw std::runtime_error("Select local files and enter a valid archive name.");
|
||||
for(const auto &part:directory)
|
||||
if(!validWindowsFileName(part.native())) throw std::runtime_error(unsafePath);
|
||||
const bool zip=isZip(file);
|
||||
const bool updating=mode==ArchiveWriteMode::update;
|
||||
if(!updating && !directory.empty()) throw std::runtime_error("Create a new archive at its root.");
|
||||
if(!updating && GetFileAttributesW(file.c_str())!=INVALID_FILE_ATTRIBUTES)
|
||||
throw std::runtime_error("A file or folder with this archive name already exists.");
|
||||
|
||||
uint64_t done=0, total=0;
|
||||
const auto checkCanceled=[&]
|
||||
{
|
||||
if(progress && !progress(done,total)) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
};
|
||||
const auto advance=[&](uint64_t bytes) {done+=bytes;checkCanceled();};
|
||||
const auto plan=[&](uint64_t bytes)
|
||||
{
|
||||
if(UINT64_MAX-total<bytes) throw std::runtime_error("The selection is too large to archive.");
|
||||
total+=bytes;
|
||||
};
|
||||
|
||||
ArchiveInputs inputs;
|
||||
for(const auto &source:sources)
|
||||
{
|
||||
if(!source.is_absolute()) throw std::runtime_error("Select files from a local folder.");
|
||||
addArchiveInput(inputs,source,directory/source.filename(),file,checkCanceled);
|
||||
}
|
||||
const ArchiveFileHandle lock(lockArchiveFolder(file.parent_path()));
|
||||
std::optional<ArchiveFileHandle> original;
|
||||
BY_HANDLE_FILE_INFORMATION originalInfo{};
|
||||
ArchiveEntries existing;
|
||||
if(updating)
|
||||
{
|
||||
original.emplace(CreateFileW(file.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT,nullptr));
|
||||
originalInfo=archiveFileInfo(original->value);
|
||||
if(originalInfo.dwFileAttributes&(FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_READONLY))
|
||||
throw std::runtime_error("This archive is read-only or is a Windows link.");
|
||||
existing=walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry)
|
||||
{
|
||||
checkCanceled();
|
||||
const int expected=zip?ARCHIVE_FORMAT_ZIP:ARCHIVE_FORMAT_7ZIP;
|
||||
if((archive_format(reader)&ARCHIVE_FORMAT_BASE_MASK)!=expected)
|
||||
throw std::runtime_error("The archive contents do not match its ZIP or 7z extension.");
|
||||
if(entry.encrypted) throw std::runtime_error("Password-protected archives cannot be updated in Files.");
|
||||
if(!entry.directory && !inputs.contains(path)) plan(entry.size);
|
||||
return true;
|
||||
});
|
||||
if(!directory.empty())
|
||||
{
|
||||
const auto parent=existing.find(directory);
|
||||
if(parent==existing.end() || !parent->second.directory || parent->first.native()!=directory.native())
|
||||
throw std::runtime_error("This folder is no longer present in the archive.");
|
||||
}
|
||||
}
|
||||
auto combined=existing;
|
||||
for(const auto &[path,input]:inputs)
|
||||
{
|
||||
checkCanceled();
|
||||
const bool folder=(input.info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
|
||||
if(const auto present=combined.find(path);present!=combined.end())
|
||||
{
|
||||
if(present->first.native()!=path.native() || present->second.directory!=folder)
|
||||
throw std::runtime_error(unsafePath);
|
||||
}
|
||||
else registerEntry(combined,path,ArchiveEntry{.directory=folder});
|
||||
if(!folder) plan(archiveFileSize(input.info));
|
||||
}
|
||||
checkCanceled();
|
||||
const ArchiveTemporaryFile temp(file.parent_path());
|
||||
auto writer=openArchiveWriter(temp.file,zip);
|
||||
if(updating)
|
||||
walkArchive(file,[&](archive *reader,archive_entry *raw,const fs::path &path,const ArchiveEntry &entry)
|
||||
{
|
||||
checkCanceled();
|
||||
if(path.empty() || inputs.contains(path)) return true;
|
||||
const auto name=path.generic_wstring();
|
||||
archive_entry_copy_pathname_w(raw,name.c_str());
|
||||
checkArchiveWrite(archive_write_header(writer.get(),raw));
|
||||
if(entry.directory) checkArchiveWrite(archive_write_finish_entry(writer.get()));
|
||||
else transferArchiveData(writer.get(),entry.size,[&](char *buffer,DWORD goal)
|
||||
{
|
||||
const auto used=archive_read_data(reader,buffer,goal);
|
||||
if(used<0) archiveError(reader);
|
||||
return static_cast<DWORD>(used);
|
||||
},advance);
|
||||
return true;
|
||||
});
|
||||
for(const auto &[path,input]:inputs)
|
||||
{
|
||||
checkCanceled();
|
||||
archiveLocalInput(writer.get(),path,input,advance);
|
||||
}
|
||||
checkArchiveWrite(archive_write_close(writer.get()));
|
||||
writer.reset();
|
||||
{
|
||||
const ArchiveFileHandle completed(CreateFileW(temp.file.c_str(),GENERIC_WRITE,FILE_SHARE_READ,nullptr,
|
||||
OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr));
|
||||
if(!FlushFileBuffers(completed.value)) throw std::system_error(GetLastError(),std::system_category());
|
||||
}
|
||||
if(updating)
|
||||
{
|
||||
const ArchiveFileHandle current(CreateFileW(file.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr));
|
||||
if(!sameArchiveFile(originalInfo,archiveFileInfo(current.value)))
|
||||
throw std::runtime_error("The archive changed while it was being updated.");
|
||||
}
|
||||
checkCanceled();
|
||||
if(updating)
|
||||
{
|
||||
const auto backup=temp.directory/L"original";
|
||||
if(const auto error=replaceFileWithBackup(file,temp.file,backup))
|
||||
throw std::system_error(error,std::system_category());
|
||||
original.reset();
|
||||
DeleteFileW(backup.c_str());
|
||||
}
|
||||
else if(!MoveFileExW(temp.file.c_str(),file.c_str(),MOVEFILE_WRITE_THROUGH))
|
||||
throw std::system_error(GetLastError(),std::system_category());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <stop_token>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
struct ArchiveNameOrder
|
||||
{
|
||||
bool operator()(const std::filesystem::path &left,const std::filesystem::path &right) const;
|
||||
};
|
||||
|
||||
struct ArchiveEntry
|
||||
{
|
||||
uint64_t size{}, modified{};
|
||||
bool directory{}, encrypted{}, implicit{};
|
||||
};
|
||||
|
||||
using ArchiveEntries=std::map<std::filesystem::path,ArchiveEntry,ArchiveNameOrder>;
|
||||
using ArchiveProgress=std::function<bool(uint64_t done,uint64_t total)>;
|
||||
|
||||
bool isArchivePath(const std::filesystem::path &path);
|
||||
ArchiveEntries readArchive(const std::filesystem::path &file,std::stop_token stop);
|
||||
ArchiveEntry readArchiveMember(const std::filesystem::path &file,const std::filesystem::path &member,
|
||||
const std::filesystem::path &output,uint64_t limit,const ArchiveProgress &progress);
|
||||
void extractArchiveSelection(const std::filesystem::path &file,const std::filesystem::path &directory,
|
||||
const std::vector<std::filesystem::path> &selection,const std::filesystem::path &staging,
|
||||
const ArchiveProgress &progress);
|
||||
|
||||
enum class ArchiveWriteMode { create, update };
|
||||
void writeArchive(const std::filesystem::path &file,ArchiveWriteMode mode,const std::filesystem::path &directory,
|
||||
const std::vector<std::filesystem::path> &sources,const ArchiveProgress &progress);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
INT_PTR CALLBACK archiveNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
constexpr int field=531, footer=532;
|
||||
const auto input=GetDlgItem(dialog,field);
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
const auto &name=*reinterpret_cast<const std::wstring *>(lp);
|
||||
prepareTextDialog(dialog);
|
||||
fitFarEditToLine(input);
|
||||
SetWindowTextW(input,name.c_str());
|
||||
SendMessageW(input,EM_SETLIMITTEXT,255,0);
|
||||
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
|
||||
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
|
||||
SetFocus(input);
|
||||
SendMessageW(input,EM_SETSEL,0,static_cast<LPARAM>(name.rfind(L'.')));
|
||||
return FALSE;
|
||||
}
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Pack files ",false,{footer}))
|
||||
return painted;
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
if(LOWORD(wp)==IDCANCEL)
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(LOWORD(wp)!=IDOK) return FALSE;
|
||||
auto name=dialogFieldText(input);
|
||||
if(!ks::files::validWindowsFileName(name) || !ks::files::isArchivePath(fs::path(name)))
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a file name ending in .zip or .7z.",L"Archive format",
|
||||
{.tone=FilesNoticeTone::warning});
|
||||
SetFocus(input);
|
||||
return TRUE;
|
||||
}
|
||||
auto &result=*reinterpret_cast<std::wstring *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
result=std::move(name);
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void performArchiveWrite(HWND owner,Panel &panel,const fs::path &archive,ks::files::ArchiveWriteMode mode,
|
||||
const fs::path &directory,const std::vector<fs::path> &sources)
|
||||
{
|
||||
if(copyInProgress || sources.empty()) return;
|
||||
const bool updating=mode==ks::files::ArchiveWriteMode::update;
|
||||
CopyProgress progress;
|
||||
progress.writingArchive=true;
|
||||
progress.from=sources.size()==1?sources.front():sources.front().parent_path();
|
||||
progress.to=archive;
|
||||
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner,
|
||||
copyProgressDialog,reinterpret_cast<LPARAM>(&progress));
|
||||
progress.window=dialog.window();
|
||||
if(!progress.window)
|
||||
{
|
||||
setStatus(L"Could not open archive progress.");
|
||||
return;
|
||||
}
|
||||
copyInProgress=true;
|
||||
activeCopy=&progress;
|
||||
dialog.show();
|
||||
bool committed=false;
|
||||
std::wstring failure;
|
||||
try
|
||||
{
|
||||
progress.ui.run(progress.window,progress.canceled,[&] {
|
||||
ks::files::writeArchive(archive,mode,directory,sources,[&](uint64_t done,uint64_t total) {
|
||||
progress.totalBytes=total;
|
||||
reportCopyProgress(progress,done,total);
|
||||
return !progress.canceled;
|
||||
});
|
||||
committed=true;
|
||||
});
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(error.code().value()!=ERROR_CANCELLED) failure=fileError(error);
|
||||
}
|
||||
catch(const std::exception &error) {failure=ks::wide(error.what());}
|
||||
dialog.close();
|
||||
activeCopy=nullptr;
|
||||
copyInProgress=false;
|
||||
if(progress.closeOwner)
|
||||
{
|
||||
PostMessageW(owner,WM_CLOSE,0,0);
|
||||
return;
|
||||
}
|
||||
if(committed)
|
||||
{
|
||||
if(!updating)
|
||||
{
|
||||
open(panel,panel.directory);
|
||||
selectPanelPath(panel,archive);
|
||||
}
|
||||
for(auto &view:panels)
|
||||
{
|
||||
std::error_code error;
|
||||
if(view.archive && fs::equivalent(view.archive->file,archive,error)) refreshArchive(view);
|
||||
}
|
||||
setStatus(updating?L"Archive updated.":L"Archive created.");
|
||||
}
|
||||
else if(failure.empty()) setStatus(L"Archive operation canceled.");
|
||||
else
|
||||
{
|
||||
showFileOperationError(owner,updating?L"Archive update failed":L"Archive creation failed",failure);
|
||||
setStatus(failure);
|
||||
}
|
||||
}
|
||||
|
||||
void createArchive(HWND owner,Panel &panel)
|
||||
{
|
||||
if(panel.peer || panel.ftp || panel.archive || !panel.directory.is_absolute())
|
||||
{
|
||||
setStatus(L"Open a local folder to create an archive.");
|
||||
return;
|
||||
}
|
||||
if(panel.scanRequest)
|
||||
{
|
||||
setStatus(L"Wait for the panel to finish reading.");
|
||||
return;
|
||||
}
|
||||
const auto selection=selectedPanelPaths(panel);
|
||||
if(selection.empty())
|
||||
{
|
||||
setStatus(L"Select files or folders to pack.");
|
||||
return;
|
||||
}
|
||||
auto stem=(selection.size()==1?selection.front().stem():panel.directory.filename()).wstring();
|
||||
if(stem.empty()) stem=L"Archive";
|
||||
auto name=stem+L".zip";
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(120),owner,
|
||||
archiveNameDialog,reinterpret_cast<LPARAM>(&name))!=IDOK) return;
|
||||
performArchiveWrite(owner,panel,panel.directory/name,ks::files::ArchiveWriteMode::create,{},selection);
|
||||
}
|
||||
|
||||
void addToArchive(HWND owner,Panel &panel,std::vector<fs::path> sources)
|
||||
{
|
||||
if(sources.empty())
|
||||
{
|
||||
setStatus(L"Select local files or folders to add.");
|
||||
return;
|
||||
}
|
||||
if(panel.scanRequest || !panel.archive)
|
||||
{
|
||||
setStatus(L"Wait for the archive panel to finish reading.");
|
||||
return;
|
||||
}
|
||||
const auto file=panel.archive->file;
|
||||
auto directory=panel.directory.lexically_relative(file);
|
||||
if(directory==L".") directory.clear();
|
||||
const auto question=L"Add the selected items to "+file.filename().native()+L"?\r\nMatching files will be replaced.";
|
||||
if(showFilesNotice(owner,question.c_str(),L"Add to archive",{.confirm=true})!=IDYES) return;
|
||||
performArchiveWrite(owner,panel,file,ks::files::ArchiveWriteMode::update,directory,sources);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
constexpr DWORD columnFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
|
||||
|
||||
std::optional<FILE_STANDARD_INFO> fileStorageInformation(HANDLE file)
|
||||
{
|
||||
FILE_STANDARD_INFO result{};
|
||||
if(GetFileInformationByHandleEx(file,FileStandardInfo,&result,sizeof(result))) return result;
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<uint64_t> allocatedFileBytes(HANDLE file,DWORD attributes,
|
||||
const std::optional<FILE_STANDARD_INFO> &metadata)
|
||||
{
|
||||
if(attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) return {};
|
||||
if(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))
|
||||
{
|
||||
FILE_COMPRESSION_INFO compression{};
|
||||
if(GetFileInformationByHandleEx(file,FileCompressionInfo,&compression,sizeof(compression)) &&
|
||||
compression.CompressedFileSize.QuadPart>=0)
|
||||
return static_cast<uint64_t>(compression.CompressedFileSize.QuadPart);
|
||||
return {};
|
||||
}
|
||||
if(metadata && !metadata->Directory && metadata->AllocationSize.QuadPart>=0)
|
||||
return static_cast<uint64_t>(metadata->AllocationSize.QuadPart);
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<uint64_t> allocatedFileBytes(const fs::path &path,DWORD attributes)
|
||||
{
|
||||
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,
|
||||
OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
|
||||
if(file.value==INVALID_HANDLE_VALUE) return {};
|
||||
const auto metadata=(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))?
|
||||
std::optional<FILE_STANDARD_INFO>{}:fileStorageInformation(file.value);
|
||||
return allocatedFileBytes(file.value,attributes,metadata);
|
||||
}
|
||||
|
||||
std::wstring localOwnerName(const fs::path &path,std::map<std::wstring,std::wstring> &owners)
|
||||
{
|
||||
const Handle file{CreateFileW(path.c_str(),READ_CONTROL,columnFileShare,nullptr,OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
|
||||
if(file.value==INVALID_HANDLE_VALUE) return {};
|
||||
PSECURITY_DESCRIPTOR descriptor=nullptr;
|
||||
PSID owner=nullptr;
|
||||
const auto result=GetSecurityInfo(file.value,SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,&owner,
|
||||
nullptr,nullptr,nullptr,&descriptor);
|
||||
const std::unique_ptr<void,decltype(&LocalFree)> security(descriptor,LocalFree);
|
||||
if(result!=ERROR_SUCCESS || !owner) return {};
|
||||
wchar_t *sidText=nullptr;
|
||||
if(!ConvertSidToStringSidW(owner,&sidText)) return {};
|
||||
const std::unique_ptr<void,decltype(&LocalFree)> sid(sidText,LocalFree);
|
||||
if(const auto existing=owners.find(sidText);existing!=owners.end()) return existing->second;
|
||||
|
||||
wchar_t name[256]{},domain[256]{};
|
||||
DWORD nameLength=static_cast<DWORD>(std::size(name)),domainLength=static_cast<DWORD>(std::size(domain));
|
||||
SID_NAME_USE use{};
|
||||
std::wstring label=sidText;
|
||||
if(LookupAccountSidW(nullptr,owner,name,&nameLength,domain,&domainLength,&use))
|
||||
label=*domain?std::wstring(domain)+L"\\"+name:name;
|
||||
owners.emplace(sidText,label);
|
||||
return label;
|
||||
}
|
||||
|
||||
void readLocalColumnMetadata(Panel::ScanResult &result,DWORD mask,std::stop_token stop)
|
||||
{
|
||||
std::map<std::wstring,std::wstring> owners;
|
||||
for(const auto &entry:result.ordered)
|
||||
{
|
||||
if(stop.stop_requested()) return;
|
||||
const auto attributes=result.metadata.at(entry.path).attributes;
|
||||
ColumnMetadata data;
|
||||
if(mask&(columnMask(allocationColumn)|columnMask(linkColumn)))
|
||||
{
|
||||
const Handle file{CreateFileW(entry.path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,
|
||||
OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
|
||||
if(file.value!=INVALID_HANDLE_VALUE)
|
||||
{
|
||||
const auto information=fileStorageInformation(file.value);
|
||||
if((mask&columnMask(linkColumn)) && information) data.links=information->NumberOfLinks;
|
||||
if(mask&columnMask(allocationColumn)) data.allocated=allocatedFileBytes(file.value,attributes,information);
|
||||
}
|
||||
}
|
||||
if(mask&columnMask(ownerColumn)) data.owner=localOwnerName(entry.path,owners);
|
||||
if(!data.owner.empty() || data.allocated || data.links)
|
||||
result.columnMetadata.emplace(entry.path,std::move(data));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
+576
-139
@@ -66,7 +66,12 @@ struct CompareFile
|
||||
fs::path path;
|
||||
std::wstring label;
|
||||
std::optional<FilesPeer> peer;
|
||||
std::optional<FtpProfile> ftp;
|
||||
std::optional<TransferProfile> ftp;
|
||||
std::optional<ks::files::RemoteTextSource> remote;
|
||||
ks::files::RemoteTextRevision revision;
|
||||
std::string originalBytes;
|
||||
std::wstring originalText;
|
||||
bool dirty{};
|
||||
};
|
||||
|
||||
struct CompareRow
|
||||
@@ -79,14 +84,31 @@ struct CompareRow
|
||||
bool hasChange(bool showWhitespace) const {return changed && (showWhitespace || !whitespaceOnly);}
|
||||
};
|
||||
|
||||
struct ComparisonDisplayRow
|
||||
{
|
||||
int first=-1,past{};
|
||||
int side=-1;
|
||||
|
||||
bool folded() const {return past>first+1;}
|
||||
};
|
||||
|
||||
struct FileComparison
|
||||
{
|
||||
static constexpr std::array controls{400,401,402,403,407};
|
||||
static constexpr std::array controls{400,401,402,403,407,408};
|
||||
CompareFile files[2];
|
||||
std::vector<std::wstring> lines[2];
|
||||
ks::files::ComparisonText text[2];
|
||||
std::vector<CompareRow> rows;
|
||||
std::vector<int> changes,allChanges;
|
||||
bool showWhitespace{};
|
||||
std::vector<ComparisonDisplayRow> displayRows;
|
||||
std::vector<std::array<int,2>> displayPositions;
|
||||
std::vector<int> displayBlockStarts;
|
||||
struct Undo
|
||||
{
|
||||
int side{};
|
||||
ks::files::ComparisonReplace edit;
|
||||
};
|
||||
std::vector<Undo> undo;
|
||||
bool working{};
|
||||
bool showWhitespace{},unified{},foldContext{};
|
||||
RECT initialClient{};
|
||||
std::array<RECT,controls.size()> initialControls{};
|
||||
SIZE minimumWindow{};
|
||||
@@ -118,7 +140,8 @@ void layoutComparisonHeaders(HWND dialog,const FileComparison &comparison)
|
||||
RECT bounds{};
|
||||
GetClientRect(list,&bounds);
|
||||
MapWindowPoints(list,dialog,reinterpret_cast<POINT*>(&bounds),2);
|
||||
const auto middle=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
|
||||
const auto width=bounds.right-bounds.left;
|
||||
const auto middle=bounds.left+(comparison.unified?width/2:comparisonSplitX(comparison,width));
|
||||
const auto inset=comparison.initialControls[0].left;
|
||||
for(int side=0;side<2;++side)
|
||||
{
|
||||
@@ -206,63 +229,132 @@ bool handleComparisonMessage(MSG &message)
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::vector<std::wstring> readComparisonLines(const CompareFile &input,const std::atomic_bool &canceled)
|
||||
struct CompareCache
|
||||
{
|
||||
struct TemporaryDirectory
|
||||
fs::path directory;
|
||||
|
||||
fs::path create()
|
||||
{
|
||||
fs::path path;
|
||||
~TemporaryDirectory()
|
||||
{
|
||||
if(path.empty()) return;
|
||||
std::error_code ignored;
|
||||
fs::remove_all(path,ignored);
|
||||
}
|
||||
} temporary;
|
||||
auto path=input.path;
|
||||
if(input.ftp || input.peer)
|
||||
{
|
||||
const auto directory=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
|
||||
requireFileOperation(fs::create_directory(directory),ERROR_ALREADY_EXISTS);
|
||||
temporary.path=directory;
|
||||
path=directory/L"file";
|
||||
CopyHost source(input.peer?&*input.peer:nullptr,input.ftp);
|
||||
const auto info=source.stat(input.path,canceled);
|
||||
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
|
||||
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
|
||||
ERROR_NOT_SUPPORTED);
|
||||
requireFileOperation(info->size<=compareFileLimit,ERROR_FILE_TOO_LARGE);
|
||||
FilesConnection local;
|
||||
const auto progress=[&](uint64_t,uint64_t){return !canceled;};
|
||||
if(source.ftp) downloadFtpFile(*source.ftp,local,input.path,path,*info,false,progress);
|
||||
else ks::lan::streamFile(*source.files,local,input.peer->id,input.path,path,info->size,
|
||||
info->modified,false,false,progress);
|
||||
auto path=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
|
||||
requireFileOperation(fs::create_directory(path),ERROR_ALREADY_EXISTS);
|
||||
directory=std::move(path);
|
||||
return directory/L"file";
|
||||
}
|
||||
ks::files::TextDocument document(path,false);
|
||||
|
||||
~CompareCache()
|
||||
{
|
||||
if(directory.empty()) return;
|
||||
std::error_code ignored;
|
||||
fs::remove_all(directory,ignored);
|
||||
}
|
||||
};
|
||||
|
||||
ks::files::RemoteTextRevision comparisonLocalRevision(const fs::path &path)
|
||||
{
|
||||
WIN32_FILE_ATTRIBUTE_DATA info{};
|
||||
checkFileOperation(GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&info)!=FALSE);
|
||||
requireFileOperation(!(info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY),ERROR_NOT_SUPPORTED);
|
||||
const auto size=(uint64_t(info.nFileSizeHigh)<<32)|info.nFileSizeLow;
|
||||
const auto stamp=(uint64_t(info.ftLastWriteTime.dwHighDateTime)<<32)|info.ftLastWriteTime.dwLowDateTime;
|
||||
return {size,stamp,(info.dwFileAttributes&(FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_REPARSE_POINT))==0};
|
||||
}
|
||||
|
||||
std::string comparisonRawBytes(const ks::files::TextDocument &document,const std::atomic_bool &canceled)
|
||||
{
|
||||
requireFileOperation(document.size()<=compareFileLimit,ERROR_FILE_TOO_LARGE);
|
||||
std::string raw;
|
||||
raw.reserve(static_cast<size_t>(document.size()));
|
||||
while(raw.size()<document.size())
|
||||
{
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
raw+=document.readBytes(raw.size(),ks::files::hexPageBytes);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
ks::files::ComparisonText readComparisonLines(CompareFile &input,const std::atomic_bool &canceled)
|
||||
{
|
||||
CompareCache temp;
|
||||
auto path=input.path;
|
||||
if(input.ftp) input.remote=transferTextSource(*input.ftp);
|
||||
else if(input.peer)
|
||||
{
|
||||
FilesConnection source(&*input.peer);
|
||||
const auto info=statFile(source,input.path);
|
||||
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
|
||||
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),ERROR_NOT_SUPPORTED);
|
||||
input.remote=ks::files::createLanTextSource(*input.peer);
|
||||
}
|
||||
if(input.remote)
|
||||
{
|
||||
path=temp.create();
|
||||
input.revision=input.remote->download(input.path,path,false,[&](uint64_t,uint64_t){return !canceled;},
|
||||
compareFileLimit);
|
||||
}
|
||||
else input.revision=comparisonLocalRevision(path);
|
||||
|
||||
ks::files::TextDocument document(path,false);
|
||||
input.originalBytes=comparisonRawBytes(document,canceled);
|
||||
std::string text;
|
||||
for(uint64_t page=0;page<document.pages() && !canceled;++page) text+=document.readPage(page);
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
if(std::any_of(text.begin(),text.end(),[](unsigned char ch){
|
||||
return ch<32 && ch!='\t' && ch!='\r' && ch!='\n' && ch!='\f';
|
||||
})) throw std::runtime_error("Select two text files.");
|
||||
if(!input.remote && (comparisonLocalRevision(path).modified!=input.revision.modified ||
|
||||
comparisonRawBytes(document,canceled)!=input.originalBytes))
|
||||
throw std::runtime_error("The file changed while it was read for comparison.");
|
||||
if(text.empty()) return {};
|
||||
const auto bytes=static_cast<int>(text.size());
|
||||
const auto count=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,nullptr,0);
|
||||
if(!count) throw std::runtime_error("Compare files supports UTF-8 and UTF-16 text.");
|
||||
std::wstring decoded(count,L'\0');
|
||||
checkFileOperation(MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,decoded.data(),count)!=0);
|
||||
std::vector<std::wstring> lines;
|
||||
size_t start=0;
|
||||
while(true)
|
||||
auto result=ks::files::splitComparisonText(decoded);
|
||||
if(result.lines.size()>100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
|
||||
input.originalText=std::move(decoded);
|
||||
return result;
|
||||
}
|
||||
|
||||
void saveComparisonFile(CompareFile &file,const ks::files::ComparisonText &text,const std::atomic_bool &canceled)
|
||||
{
|
||||
requireFileOperation(file.revision.editable,ERROR_ACCESS_DENIED);
|
||||
CompareCache temporary;
|
||||
auto target=file.path;
|
||||
if(file.remote)
|
||||
{
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
if(lines.size()==100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
|
||||
const auto end=decoded.find_first_of(L"\r\n",start);
|
||||
lines.push_back(decoded.substr(start,end==decoded.npos?end:end-start));
|
||||
if(end==decoded.npos) break;
|
||||
start=end+((decoded[end]==L'\r' && end+1<decoded.size() && decoded[end+1]==L'\n')?2:1);
|
||||
target=temporary.create();
|
||||
const auto revision=file.remote->download(file.path,target,true,[&](uint64_t,uint64_t){return !canceled;},
|
||||
compareFileLimit);
|
||||
if(revision.modified!=file.revision.modified || revision.size!=file.revision.size)
|
||||
throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving.");
|
||||
}
|
||||
return lines;
|
||||
else
|
||||
{
|
||||
const auto revision=comparisonLocalRevision(target);
|
||||
requireFileOperation(revision.editable,ERROR_ACCESS_DENIED);
|
||||
if(revision.modified!=file.revision.modified || revision.size!=file.revision.size)
|
||||
throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving.");
|
||||
}
|
||||
ks::files::TextDocument document(target,true);
|
||||
if(comparisonRawBytes(document,canceled)!=file.originalBytes)
|
||||
throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving.");
|
||||
auto joined=text.joined();
|
||||
const auto contents=ks::utf8(joined);
|
||||
const auto bytes=document.encoding()==ks::files::TextEncoding::utf8?contents.size():
|
||||
joined.size()*sizeof(wchar_t);
|
||||
requireFileOperation(bytes+document.boundary(0)<=compareFileLimit,ERROR_FILE_TOO_LARGE);
|
||||
for(uint64_t page=1;page<document.pages();++page) document.stage(page,{});
|
||||
document.stage(0,contents);
|
||||
requireFileOperation(!canceled,ERROR_CANCELLED);
|
||||
if(!document.save()) throw std::runtime_error("The file was saved but could not be reopened.");
|
||||
if(file.remote)
|
||||
file.revision=file.remote->upload(file.path,target,file.revision);
|
||||
else file.revision=comparisonLocalRevision(target);
|
||||
const std::atomic_bool committed{};
|
||||
file.originalBytes=comparisonRawBytes(document,committed);
|
||||
file.originalText=std::move(joined);
|
||||
file.dirty=false;
|
||||
}
|
||||
|
||||
std::wstring_view comparisonContent(std::wstring_view line)
|
||||
@@ -274,7 +366,7 @@ std::wstring_view comparisonContent(std::wstring_view line)
|
||||
|
||||
void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
|
||||
{
|
||||
const auto &left=result.lines[0],&right=result.lines[1];
|
||||
const auto &left=result.text[0].lines,&right=result.text[1].lines;
|
||||
std::map<std::wstring_view,unsigned> ids;
|
||||
std::map<unsigned,unsigned> blankIds;
|
||||
unsigned nextId=1;
|
||||
@@ -313,8 +405,6 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
|
||||
const auto append=[&](int x,int y)
|
||||
{
|
||||
CompareRow row{x,y,x<0 || y<0 || left[x]!=right[y]};
|
||||
if(row.changed && (result.rows.empty() || !result.rows.back().changed))
|
||||
result.allChanges.push_back(static_cast<int>(result.rows.size()));
|
||||
if(row.changed && x>=0 && y>=0)
|
||||
{
|
||||
const auto &l=left[x],&r=right[y];
|
||||
@@ -328,8 +418,6 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
|
||||
if(row.commonEnd && l[l.size()-row.commonEnd]>=0xdc00 && l[l.size()-row.commonEnd]<=0xdfff)
|
||||
--row.commonEnd;
|
||||
}
|
||||
if(row.hasChange(false) && (result.rows.empty() || !result.rows.back().hasChange(false)))
|
||||
result.changes.push_back(static_cast<int>(result.rows.size()));
|
||||
result.rows.push_back(row);
|
||||
};
|
||||
const auto change=[&](size_t x,size_t y,size_t countLeft,size_t countRight)
|
||||
@@ -436,6 +524,233 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
|
||||
append(static_cast<int>(a.size()-suffix+i),static_cast<int>(b.size()-suffix+i));
|
||||
}
|
||||
|
||||
enum ComparisonCommand { applyLeft=409,applyRight,undoCompare,saveLeft,saveRight,saveComparison,
|
||||
unifiedCompare,foldCompareContext };
|
||||
|
||||
struct ComparisonProgress
|
||||
{
|
||||
const wchar_t *status;
|
||||
bool cancelable=true;
|
||||
std::atomic_bool canceled{};
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp);
|
||||
|
||||
template<class Work>
|
||||
bool runComparisonWork(HWND owner,const wchar_t *status,bool cancelable,const Work &work)
|
||||
{
|
||||
ComparisonProgress state{status,cancelable};
|
||||
FileOperationUi worker;
|
||||
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
|
||||
comparisonProgressDialog,reinterpret_cast<LPARAM>(&state),false);
|
||||
if(!progress.window()) throw std::runtime_error("Could not open the comparison progress dialog.");
|
||||
progress.show();
|
||||
try {worker.run(progress.window(),state.canceled,[&]{work(state.canceled);});}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(error.code().value()==ERROR_CANCELLED) return false;
|
||||
throw;
|
||||
}
|
||||
return !state.canceled;
|
||||
}
|
||||
|
||||
std::optional<ks::files::ComparisonReplace> comparisonBlock(const FileComparison &comparison,int side,LRESULT selected)
|
||||
{
|
||||
if(selected<0 || static_cast<size_t>(selected)>=comparison.rows.size() ||
|
||||
!comparison.rows[selected].hasChange(comparison.showWhitespace)) return {};
|
||||
auto first=static_cast<size_t>(selected),end=first+1;
|
||||
while(first>0 && comparison.rows[first-1].hasChange(comparison.showWhitespace)) --first;
|
||||
while(end<comparison.rows.size() && comparison.rows[end].hasChange(comparison.showWhitespace)) ++end;
|
||||
const auto line=[](const CompareRow &row,int file){return file==0?row.left:row.right;};
|
||||
const auto &target=comparison.text[side];
|
||||
const auto &source=comparison.text[1-side];
|
||||
ks::files::ComparisonReplace edit{target.lines.size()};
|
||||
for(size_t row=first;row<end;++row)
|
||||
{
|
||||
const auto old=line(comparison.rows[row],side);
|
||||
const auto incoming=line(comparison.rows[row],1-side);
|
||||
if(old>=0)
|
||||
{
|
||||
edit.start=std::min(edit.start,static_cast<size_t>(old));
|
||||
++edit.count;
|
||||
}
|
||||
if(incoming>=0)
|
||||
{
|
||||
edit.lines.push_back(source.lines[incoming]);
|
||||
edit.endings.push_back(old>=0?target.endings[old]:target.preferred);
|
||||
}
|
||||
}
|
||||
if(!edit.count)
|
||||
for(size_t row=end;row<comparison.rows.size();++row)
|
||||
if(const auto next=line(comparison.rows[row],side);next>=0)
|
||||
{
|
||||
edit.start=static_cast<size_t>(next);
|
||||
break;
|
||||
}
|
||||
return edit;
|
||||
}
|
||||
|
||||
void updateComparisonSummary(HWND dialog,const FileComparison &comparison);
|
||||
|
||||
ComparisonDisplayRow comparisonDisplayAnchor(const FileComparison &comparison,LRESULT position)
|
||||
{
|
||||
if(position<0 || static_cast<size_t>(position)>=comparison.displayRows.size()) return {};
|
||||
return comparison.displayRows[position];
|
||||
}
|
||||
|
||||
int comparisonDisplayPosition(const FileComparison &comparison,ComparisonDisplayRow anchor)
|
||||
{
|
||||
if(anchor.first<0 || comparison.displayPositions.empty()) return -1;
|
||||
const auto last=static_cast<int>(comparison.displayPositions.size())-1;
|
||||
const auto &positions=comparison.displayPositions[std::min(anchor.first,last)];
|
||||
if(anchor.side>=0 && positions[anchor.side]>=0) return positions[anchor.side];
|
||||
if(positions[0]<0) return positions[1];
|
||||
if(positions[1]<0) return positions[0];
|
||||
return std::min(positions[0],positions[1]);
|
||||
}
|
||||
|
||||
void comparisonUpdateRows(HWND dialog,FileComparison &comparison,ComparisonDisplayRow selected,
|
||||
ComparisonDisplayRow top={})
|
||||
{
|
||||
const auto list=GetDlgItem(dialog,402);
|
||||
comparison.displayRows.clear();
|
||||
const auto size=static_cast<int>(comparison.rows.size());
|
||||
comparison.displayPositions.assign(size,{-1,-1});
|
||||
comparison.displayBlockStarts.clear();
|
||||
const auto append=[&](int first,int past,int side=-1)
|
||||
{
|
||||
const auto position=static_cast<int>(comparison.displayRows.size());
|
||||
comparison.displayRows.push_back({first,past,side});
|
||||
for(int row=first;row<past;++row)
|
||||
{
|
||||
auto &positions=comparison.displayPositions[row];
|
||||
if(side<0) positions={position,position};
|
||||
else positions[side]=position;
|
||||
}
|
||||
};
|
||||
const auto changed=[&](int row){return comparison.rows[row].hasChange(comparison.showWhitespace);};
|
||||
for(int first=0;first<size;)
|
||||
{
|
||||
const auto isChange=changed(first);
|
||||
int past=first+1;
|
||||
while(past<size && changed(past)==isChange) ++past;
|
||||
if(isChange) comparison.displayBlockStarts.push_back(static_cast<int>(comparison.displayRows.size()));
|
||||
if(isChange && comparison.unified)
|
||||
{
|
||||
for(int row=first;row<past;++row)
|
||||
if(comparison.rows[row].left>=0) append(row,row+1,0);
|
||||
for(int row=first;row<past;++row)
|
||||
if(comparison.rows[row].right>=0) append(row,row+1,1);
|
||||
}
|
||||
else
|
||||
{
|
||||
constexpr int context=3;
|
||||
const int hiddenFirst=comparison.foldContext && !isChange?first+(first>0?context:0):past;
|
||||
const int hiddenPast=past-(past<size?context:0);
|
||||
if(hiddenPast-hiddenFirst>=2)
|
||||
{
|
||||
for(int row=first;row<hiddenFirst;++row) append(row,row+1);
|
||||
append(hiddenFirst,hiddenPast);
|
||||
for(int row=hiddenPast;row<past;++row) append(row,row+1);
|
||||
}
|
||||
else for(int row=first;row<past;++row) append(row,row+1);
|
||||
}
|
||||
first=past;
|
||||
}
|
||||
SendMessageW(list,LB_SETCOUNT,comparison.displayRows.size(),0);
|
||||
const auto position=comparisonDisplayPosition(comparison,selected);
|
||||
if(const auto firstVisible=comparisonDisplayPosition(comparison,top);firstVisible>=0)
|
||||
SendMessageW(list,LB_SETTOPINDEX,firstVisible,0);
|
||||
SendMessageW(list,LB_SETCURSEL,position,0);
|
||||
updateComparisonSummary(dialog,comparison);
|
||||
InvalidateRect(list,nullptr,TRUE);
|
||||
}
|
||||
|
||||
bool applyComparisonEdit(HWND dialog,FileComparison &comparison,int side,const ks::files::ComparisonReplace &edit,
|
||||
bool remember)
|
||||
{
|
||||
const auto list=GetDlgItem(dialog,402);
|
||||
const auto selected=comparisonDisplayAnchor(comparison,SendMessageW(list,LB_GETCURSEL,0,0));
|
||||
const auto top=comparisonDisplayAnchor(comparison,SendMessageW(list,LB_GETTOPINDEX,0,0));
|
||||
FileComparison candidate;
|
||||
ks::files::ComparisonReplace reverse;
|
||||
comparison.working=true;
|
||||
try
|
||||
{
|
||||
const bool success=runComparisonWork(dialog,L"Updating comparison…",true,[&](const auto &stop) {
|
||||
candidate.text[0]=comparison.text[0];
|
||||
candidate.text[1]=comparison.text[1];
|
||||
reverse=ks::files::replaceComparisonText(candidate.text[side],edit);
|
||||
if(candidate.text[side].lines.size()>100'000)
|
||||
throw std::runtime_error("Each file can contain up to 100,000 lines.");
|
||||
alignComparison(candidate,stop);
|
||||
});
|
||||
comparison.working=false;
|
||||
if(!success) return false;
|
||||
if(remember) comparison.undo.push_back({side,std::move(reverse)});
|
||||
else comparison.undo.pop_back();
|
||||
comparison.text[side]=std::move(candidate.text[side]);
|
||||
comparison.rows=std::move(candidate.rows);
|
||||
comparison.files[side].dirty=comparison.text[side].joined()!=comparison.files[side].originalText;
|
||||
comparisonUpdateRows(dialog,comparison,selected,top);
|
||||
return true;
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
comparison.working=false;
|
||||
showFileOperationError(dialog,L"Could not apply the block",ks::wide(error.what()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool commitComparison(HWND dialog,FileComparison &comparison,int requested=-1)
|
||||
{
|
||||
std::array committed{comparison.files[0],comparison.files[1]};
|
||||
comparison.working=true;
|
||||
bool success=true;
|
||||
try
|
||||
{
|
||||
runComparisonWork(dialog,L"Saving comparison changes…",false,[&](const auto &stop) {
|
||||
for(int side=0;side<2;++side)
|
||||
if((requested<0 || requested==side) && comparison.files[side].dirty)
|
||||
saveComparisonFile(committed[side],comparison.text[side],stop);
|
||||
});
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":fileError(error);
|
||||
showFileOperationError(dialog,L"Comparison save failed",detail);
|
||||
success=false;
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
showFileOperationError(dialog,L"Comparison save failed",ks::wide(error.what()));
|
||||
success=false;
|
||||
}
|
||||
comparison.working=false;
|
||||
for(int side=0;side<2;++side)
|
||||
if(!committed[side].dirty) comparison.files[side]=std::move(committed[side]);
|
||||
std::erase_if(comparison.undo,[&](const auto &previous){return !comparison.files[previous.side].dirty;});
|
||||
updateComparisonSummary(dialog,comparison);
|
||||
return success;
|
||||
}
|
||||
|
||||
void closeComparison(HWND dialog,FileComparison &comparison)
|
||||
{
|
||||
if(comparison.working || FilesModalDialog::dismissOwned(dialog)) return;
|
||||
if(comparison.files[0].dirty || comparison.files[1].dirty)
|
||||
{
|
||||
const auto choice=showFilesNotice(dialog,L"Save changes from the comparison?",L"Compare files",
|
||||
{.saveChanges=true});
|
||||
if(choice==IDYES)
|
||||
{
|
||||
if(!commitComparison(dialog,comparison)) return;
|
||||
}
|
||||
else if(choice!=IDNO) return;
|
||||
}
|
||||
DestroyWindow(dialog);
|
||||
}
|
||||
|
||||
void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &item)
|
||||
{
|
||||
const auto dc=item.hDC;
|
||||
@@ -448,47 +763,23 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it
|
||||
const auto &palette=comparison.appearance.palette;
|
||||
const auto cell=comparison.characterWidth;
|
||||
fill(bounds,palette[CompareBackground]);
|
||||
if(item.itemID>=comparison.rows.size()) return;
|
||||
const auto &row=comparison.rows[item.itemID];
|
||||
if(item.itemID>=comparison.displayRows.size()) return;
|
||||
const auto &display=comparison.displayRows[item.itemID];
|
||||
const auto &row=comparison.rows[display.first];
|
||||
const bool changed=row.hasChange(comparison.showWhitespace);
|
||||
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
|
||||
const LONG gutter=std::max(4,cell);
|
||||
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
|
||||
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
|
||||
if(changed) fill(link,highlight);
|
||||
else
|
||||
{
|
||||
const RECT divider{center,bounds.top,center+1,bounds.bottom};
|
||||
fill(divider,palette[CompareDivider]);
|
||||
}
|
||||
if(changed)
|
||||
{
|
||||
const LONG middle=(bounds.top+bounds.bottom)/2;
|
||||
const LONG start=row.left<0?bounds.top:middle,end=row.right<0?bounds.top:middle;
|
||||
SetDCPenColor(dc,palette[CompareChangedText]);
|
||||
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
|
||||
MoveToEx(dc,link.left,start,nullptr);
|
||||
LineTo(dc,link.right,end);
|
||||
SelectObject(dc,pen);
|
||||
}
|
||||
const auto ink=palette[changed?CompareChangedText:CompareText];
|
||||
SelectObject(dc,comparison.font?comparison.font:mono);
|
||||
SetBkMode(dc,TRANSPARENT);
|
||||
const auto ink=palette[changed?CompareChangedText:CompareText];
|
||||
SetTextColor(dc,ink);
|
||||
const auto drawSide=[&](int side,int number,RECT area)
|
||||
const auto drawNumber=[&](int number,RECT area)
|
||||
{
|
||||
if(number<0)
|
||||
{
|
||||
fill(area,palette[ComparePadding]);
|
||||
return;
|
||||
}
|
||||
if(changed) fill(area,highlight);
|
||||
const auto numberText=std::to_wstring(number+1);
|
||||
RECT numberArea=area;
|
||||
numberArea.right=std::min(area.right,area.left+7*cell);
|
||||
DrawTextW(dc,numberText.c_str(),-1,&numberArea,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
|
||||
area.left=std::min(area.right,numberArea.right+cell);
|
||||
const auto &line=comparison.lines[side][number];
|
||||
if(number<0) return;
|
||||
const auto text=std::to_wstring(number+1);
|
||||
DrawTextW(dc,text.c_str(),-1,&area,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
|
||||
};
|
||||
const auto drawContent=[&](int side,int number,RECT area)
|
||||
{
|
||||
const auto &line=comparison.text[side].lines[number];
|
||||
const auto paneWidth=area.right-area.left;
|
||||
if(paneWidth<=0) return;
|
||||
const auto limit=static_cast<size_t>(paneWidth/cell+2)*4;
|
||||
@@ -519,8 +810,62 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it
|
||||
}
|
||||
else if(!visible.empty()) DrawTextW(dc,visible.data(),static_cast<int>(visible.size()),&area,flags);
|
||||
};
|
||||
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
|
||||
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
|
||||
if(display.folded())
|
||||
{
|
||||
fill(bounds,palette[ComparePadding]);
|
||||
auto line=bounds;
|
||||
line.left+=2*cell;
|
||||
const auto label=L"… "+std::to_wstring(display.past-display.first)+L" unchanged lines …";
|
||||
DrawTextW(dc,label.c_str(),-1,&line,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
}
|
||||
else if(comparison.unified)
|
||||
{
|
||||
if(changed) fill(bounds,palette[display.side==0?CompareDelete:CompareInsert]);
|
||||
RECT number=bounds;
|
||||
number.right=std::min(bounds.right,bounds.left+7*cell);
|
||||
if(display.side!=1) drawNumber(row.left,number);
|
||||
number.left=number.right;
|
||||
number.right=std::min(bounds.right,number.left+7*cell);
|
||||
if(display.side!=0) drawNumber(row.right,number);
|
||||
auto content=bounds;
|
||||
content.left=std::min(bounds.right,number.right+3*cell);
|
||||
if(changed)
|
||||
{
|
||||
RECT marker{std::min(bounds.right,number.right+cell),bounds.top,content.left,bounds.bottom};
|
||||
DrawTextW(dc,display.side==0?L"−":L"+",1,&marker,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
|
||||
}
|
||||
const auto side=display.side<0?1:display.side;
|
||||
drawContent(side,side==0?row.left:row.right,content);
|
||||
}
|
||||
else
|
||||
{
|
||||
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
|
||||
const LONG gutter=std::max(4,cell);
|
||||
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
|
||||
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
|
||||
if(changed)
|
||||
{
|
||||
fill(link,highlight);
|
||||
const LONG middle=(bounds.top+bounds.bottom)/2;
|
||||
SetDCPenColor(dc,ink);
|
||||
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
|
||||
MoveToEx(dc,link.left,row.left<0?bounds.top:middle,nullptr);
|
||||
LineTo(dc,link.right,row.right<0?bounds.top:middle);
|
||||
SelectObject(dc,pen);
|
||||
}
|
||||
else fill({center,bounds.top,center+1,bounds.bottom},palette[CompareDivider]);
|
||||
const auto drawSide=[&](int side,int number,RECT area)
|
||||
{
|
||||
if(number<0) {fill(area,palette[ComparePadding]);return;}
|
||||
if(changed) fill(area,highlight);
|
||||
const auto end=std::min(area.right,area.left+7*cell);
|
||||
drawNumber(number,{area.left,area.top,end,area.bottom});
|
||||
area.left=std::min(area.right,end+cell);
|
||||
drawContent(side,number,area);
|
||||
};
|
||||
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
|
||||
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
|
||||
}
|
||||
if(item.itemState&ODS_SELECTED)
|
||||
{
|
||||
SetDCBrushColor(dc,ink);
|
||||
@@ -530,6 +875,11 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it
|
||||
|
||||
LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_KEYDOWN && (GetKeyState(VK_CONTROL)&0x8000) && (wp=='Z' || wp=='S'))
|
||||
{
|
||||
SendMessageW(GetParent(control),WM_COMMAND,wp=='Z'?undoCompare:saveComparison,0);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_KEYDOWN && (wp==VK_F7 || wp==VK_F8))
|
||||
{
|
||||
SendMessageW(GetParent(control),WM_COMMAND,wp==VK_F7?404:405,0);
|
||||
@@ -540,7 +890,7 @@ LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UI
|
||||
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!comparison) return DefSubclassProc(control,message,wp,lp);
|
||||
if(message==WM_MOUSEWHEEL && zoomComparison(dialog,*comparison,wp)) return 0;
|
||||
if(message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)
|
||||
if(!comparison->unified && (message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK))
|
||||
{
|
||||
RECT client{};
|
||||
GetClientRect(control,&client);
|
||||
@@ -604,9 +954,12 @@ LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UI
|
||||
// The list box repaints its rows but can leave earlier divider marks below them.
|
||||
FillRect(dc,&blank,comparison->background?comparison->background:
|
||||
static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
|
||||
const RECT divider{middle,blank.top,middle+1,blank.bottom};
|
||||
SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]);
|
||||
FillRect(dc,÷r,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,÷r,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
ReleaseDC(control,dc);
|
||||
}
|
||||
}
|
||||
@@ -626,6 +979,7 @@ void layoutComparison(HWND dialog)
|
||||
if(id==400 || id==401) continue;
|
||||
auto bounds=comparison->initialControls[i];
|
||||
if(id==402) bounds={0,bounds.top,client.right,client.bottom};
|
||||
if(id==408) bounds.right=client.right-bounds.left;
|
||||
SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,bounds.top,
|
||||
bounds.right-bounds.left,std::max(0L,bounds.bottom-bounds.top),
|
||||
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
|
||||
@@ -636,12 +990,24 @@ void layoutComparison(HWND dialog)
|
||||
|
||||
void updateComparisonSummary(HWND dialog,const FileComparison &comparison)
|
||||
{
|
||||
const auto blocks=(comparison.showWhitespace?comparison.allChanges:comparison.changes).size();
|
||||
const auto blocks=comparison.displayBlockStarts.size();
|
||||
const auto summary=blocks==0?L"Text is identical":blocks==1?L"1 change block":
|
||||
std::to_wstring(blocks)+L" change blocks";
|
||||
SetDlgItemTextW(dialog,403,summary.c_str());
|
||||
const auto toolbar=GetDlgItem(dialog,407);
|
||||
for(const auto id:{404,405}) SendMessageW(toolbar,TB_ENABLEBUTTON,id,MAKELONG(blocks!=0,0));
|
||||
const auto actions=GetDlgItem(dialog,408);
|
||||
const auto row=comparisonDisplayAnchor(comparison,SendDlgItemMessageW(dialog,402,LB_GETCURSEL,0,0));
|
||||
const bool selected=row.first>=0 && !row.folded() && comparison.rows[row.first].hasChange(comparison.showWhitespace);
|
||||
for(int side=0;side<2;++side)
|
||||
{
|
||||
const auto &file=comparison.files[side];
|
||||
const auto header=(file.dirty?L"* ":L"")+file.label+(file.revision.editable?L"":L" (read-only)");
|
||||
SetDlgItemTextW(dialog,400+side,header.c_str());
|
||||
SendMessageW(actions,TB_ENABLEBUTTON,applyLeft+side,MAKELONG(selected && file.revision.editable,0));
|
||||
SendMessageW(actions,TB_ENABLEBUTTON,saveLeft+side,MAKELONG(file.dirty,0));
|
||||
}
|
||||
SendMessageW(actions,TB_ENABLEBUTTON,undoCompare,MAKELONG(!comparison.undo.empty(),0));
|
||||
}
|
||||
|
||||
void initializeComparisonToolbar(HWND toolbar)
|
||||
@@ -662,6 +1028,27 @@ void initializeComparisonToolbar(HWND toolbar)
|
||||
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
|
||||
}
|
||||
|
||||
void initializeComparisonActions(HWND toolbar)
|
||||
{
|
||||
SendMessageW(toolbar,TB_BUTTONSTRUCTSIZE,sizeof(TBBUTTON),0);
|
||||
SendMessageW(toolbar,TB_SETEXTENDEDSTYLE,0,TBSTYLE_EX_MIXEDBUTTONS);
|
||||
SendMessageW(toolbar,TB_SETMAXTEXTROWS,1,0);
|
||||
constexpr BYTE text=BTNS_AUTOSIZE|BTNS_SHOWTEXT;
|
||||
const auto separator=MulDiv(8,GetDpiForWindow(toolbar),96);
|
||||
const TBBUTTON buttons[]{
|
||||
{I_IMAGENONE,applyLeft,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Apply to left")},
|
||||
{I_IMAGENONE,applyRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Apply to right")},
|
||||
{I_IMAGENONE,undoCompare,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Undo")},
|
||||
{separator,0,0,BTNS_SEP,{},0,0},
|
||||
{I_IMAGENONE,saveLeft,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Save left")},
|
||||
{I_IMAGENONE,saveRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Save right")},
|
||||
{separator,0,0,BTNS_SEP,{},0,0},
|
||||
{I_IMAGENONE,unifiedCompare,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Unified")},
|
||||
{I_IMAGENONE,foldCompareContext,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Fold unchanged")}
|
||||
};
|
||||
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
@@ -685,15 +1072,19 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
SendMessageW(dialog,WM_SETICON,ICON_SMALL,reinterpret_cast<LPARAM>(small));
|
||||
SendMessageW(dialog,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(large));
|
||||
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,L"HrynCo.KSwitcher.Files.Compare");
|
||||
for(int side=0;side<2;++side) SetDlgItemTextW(dialog,400+side,comparison->files[side].label.c_str());
|
||||
initializeComparisonToolbar(toolbar);
|
||||
updateComparisonSummary(dialog,*comparison);
|
||||
const auto actions=GetDlgItem(dialog,408);
|
||||
initializeComparisonActions(actions);
|
||||
SetWindowSubclass(list,comparisonKeys,1,0);
|
||||
SetWindowSubclass(toolbar,comparisonKeys,1,0);
|
||||
SetWindowSubclass(actions,comparisonKeys,1,0);
|
||||
applyComparisonAppearance(dialog,*comparison);
|
||||
SendMessageW(list,LB_SETCOUNT,comparison->rows.size(),0);
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
if(!comparison->changes.empty()) SendMessageW(list,LB_SETCURSEL,comparison->changes.front(),0);
|
||||
const auto first=std::find_if(comparison->rows.begin(),comparison->rows.end(),
|
||||
[](const auto &row){return row.hasChange(false);});
|
||||
ComparisonDisplayRow selected;
|
||||
if(first!=comparison->rows.end()) selected.first=static_cast<int>(first-comparison->rows.begin());
|
||||
comparisonUpdateRows(dialog,*comparison,selected);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==filesPreferencesChanged && comparison)
|
||||
@@ -702,16 +1093,16 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE)
|
||||
if(message==WM_CLOSE && comparison)
|
||||
{
|
||||
DestroyWindow(dialog);
|
||||
closeComparison(dialog,*comparison);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_MOUSEWHEEL && comparison && zoomComparison(dialog,*comparison,wp)) return TRUE;
|
||||
if(message==WM_NCDESTROY)
|
||||
{
|
||||
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,nullptr);
|
||||
comparisonWindows.erase(dialog);
|
||||
if(comparisonWindows.erase(dialog)) ks::files::standaloneFilesWindowClosed();
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_GETMINMAXINFO && comparison && comparison->minimumWindow.cx)
|
||||
@@ -737,45 +1128,92 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
if(message==WM_COMMAND && comparison)
|
||||
{
|
||||
const auto id=LOWORD(wp);
|
||||
if(id==IDCANCEL) {DestroyWindow(dialog);return TRUE;}
|
||||
if(id==406 && HIWORD(wp)==BN_CLICKED)
|
||||
if(comparison->working) return TRUE;
|
||||
if(id==IDCANCEL) {closeComparison(dialog,*comparison);return TRUE;}
|
||||
if(id==applyLeft || id==applyRight)
|
||||
{
|
||||
comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0;
|
||||
updateComparisonSummary(dialog,*comparison);
|
||||
InvalidateRect(list,nullptr,FALSE);
|
||||
const auto side=id-applyLeft;
|
||||
const auto selected=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0));
|
||||
if(!selected.folded() && comparison->files[side].revision.editable)
|
||||
if(const auto edit=comparisonBlock(*comparison,side,selected.first))
|
||||
applyComparisonEdit(dialog,*comparison,side,*edit,true);
|
||||
SetFocus(list);
|
||||
return TRUE;
|
||||
}
|
||||
const auto &changes=comparison->showWhitespace?comparison->allChanges:comparison->changes;
|
||||
if(id==undoCompare)
|
||||
{
|
||||
if(!comparison->undo.empty())
|
||||
{
|
||||
const auto &previous=comparison->undo.back();
|
||||
applyComparisonEdit(dialog,*comparison,previous.side,previous.edit,false);
|
||||
}
|
||||
SetFocus(list);
|
||||
return TRUE;
|
||||
}
|
||||
if(id==saveLeft || id==saveRight || id==saveComparison)
|
||||
{
|
||||
if(comparison->files[0].dirty || comparison->files[1].dirty)
|
||||
commitComparison(dialog,*comparison,id==saveComparison?-1:id-saveLeft);
|
||||
SetFocus(list);
|
||||
return TRUE;
|
||||
}
|
||||
if((id==406 || id==unifiedCompare || id==foldCompareContext) && HIWORD(wp)==BN_CLICKED)
|
||||
{
|
||||
const auto selected=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0));
|
||||
const auto top=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETTOPINDEX,0,0));
|
||||
const auto source=id==406?toolbar:GetDlgItem(dialog,408);
|
||||
const bool enabled=SendMessageW(source,TB_ISBUTTONCHECKED,id,0)!=0;
|
||||
if(id==406) comparison->showWhitespace=enabled;
|
||||
if(id==unifiedCompare)
|
||||
{
|
||||
if(comparison->splitDragOffset) ReleaseCapture();
|
||||
comparison->unified=enabled;
|
||||
layoutComparisonHeaders(dialog,*comparison);
|
||||
}
|
||||
if(id==foldCompareContext) comparison->foldContext=enabled;
|
||||
comparisonUpdateRows(dialog,*comparison,selected,top);
|
||||
SetFocus(list);
|
||||
return TRUE;
|
||||
}
|
||||
const auto &changes=comparison->displayBlockStarts;
|
||||
if((id==404 || id==405) && !changes.empty())
|
||||
{
|
||||
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
|
||||
if(id==404)
|
||||
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
|
||||
if(id==404 && next!=changes.begin())
|
||||
{
|
||||
const auto previous=std::lower_bound(changes.begin(),changes.end(),current);
|
||||
if(previous!=changes.begin()) SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
|
||||
if(next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
|
||||
const auto here=comparisonDisplayAnchor(*comparison,current);
|
||||
const bool inBlock=here.first>=0 && !here.folded() &&
|
||||
comparison->rows[here.first].hasChange(comparison->showWhitespace);
|
||||
const auto previous=std::prev(next);
|
||||
if(!inBlock) SendMessageW(list,LB_SETCURSEL,*previous,0);
|
||||
if(inBlock && previous!=changes.begin())
|
||||
SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
|
||||
}
|
||||
if(id==405 && next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
|
||||
updateComparisonSummary(dialog,*comparison);
|
||||
return TRUE;
|
||||
}
|
||||
if(id==402 && HIWORD(wp)==LBN_DBLCLK)
|
||||
{
|
||||
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
|
||||
if(current>=0 && static_cast<size_t>(current)<comparison->rows.size())
|
||||
const auto current=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0));
|
||||
if(current.first>=0 && !current.folded())
|
||||
{
|
||||
const auto &row=comparison->rows[current];
|
||||
const auto &row=comparison->rows[current.first];
|
||||
const auto side=[&](int file,int line)
|
||||
{
|
||||
return line<0?std::wstring(L"—"):comparison->lines[file][line];
|
||||
return line<0?std::wstring(L"—"):comparison->text[file].lines[line];
|
||||
};
|
||||
const auto detail=L"Left\n"+side(0,row.left)+L"\n\nRight\n"+side(1,row.right);
|
||||
showFilesNotice(dialog,detail.c_str(),L"Line details");
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(id==402 && HIWORD(wp)==LBN_SELCHANGE)
|
||||
{
|
||||
updateComparisonSummary(dialog,*comparison);
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
@@ -785,13 +1223,20 @@ INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPA
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
const auto &state=*reinterpret_cast<ComparisonProgress *>(lp);
|
||||
prepareTextDialog(dialog);
|
||||
SetDlgItemTextW(dialog,548,state.status);
|
||||
EnableWindow(GetDlgItem(dialog,IDCANCEL),state.cancelable);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDCANCEL)
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
*reinterpret_cast<std::atomic_bool*>(GetWindowLongPtrW(dialog,DWLP_USER))=true;
|
||||
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
|
||||
auto &state=*reinterpret_cast<ComparisonProgress *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(state.cancelable)
|
||||
{
|
||||
state.canceled=true;
|
||||
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
return paintTextDialog(dialog,message,wp,lp,L" Compare files ");
|
||||
@@ -807,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(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();
|
||||
@@ -828,41 +1273,33 @@ void compareSelectedFiles(HWND owner)
|
||||
L"Compare files");
|
||||
return;
|
||||
}
|
||||
std::atomic_bool canceled{};
|
||||
try
|
||||
{
|
||||
{
|
||||
FileOperationUi worker;
|
||||
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
|
||||
comparisonProgressDialog,reinterpret_cast<LPARAM>(&canceled),false);
|
||||
if(!progress.window()) throw std::runtime_error("Could not open the progress dialog.");
|
||||
progress.show();
|
||||
worker.run(progress.window(),canceled,[&]
|
||||
{
|
||||
for(int side=0;side<2;++side)
|
||||
comparison.lines[side]=readComparisonLines(comparison.files[side],canceled);
|
||||
alignComparison(comparison,canceled);
|
||||
});
|
||||
}
|
||||
if(!canceled)
|
||||
const bool read=runComparisonWork(owner,L"Reading and comparing files…",true,[&](const auto &stop) {
|
||||
for(int side=0;side<2;++side)
|
||||
comparison.text[side]=readComparisonLines(comparison.files[side],stop);
|
||||
alignComparison(comparison,stop);
|
||||
});
|
||||
if(read)
|
||||
{
|
||||
const auto window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(114),nullptr,
|
||||
comparisonDialog,reinterpret_cast<LPARAM>(&comparison));
|
||||
if(!window) throw std::runtime_error("Could not open the comparison window.");
|
||||
comparisonWindows.emplace(window,std::move(state));
|
||||
ks::files::standaloneFilesWindowOpened();
|
||||
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
SetFocus(GetDlgItem(window,402));
|
||||
}
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
if(canceled || error.code().value()==ERROR_CANCELLED) return;
|
||||
if(error.code().value()==ERROR_CANCELLED) return;
|
||||
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":
|
||||
fileError(error);
|
||||
showFileOperationError(owner,L"Comparison failed",detail);
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(!canceled) showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
|
||||
showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
enum class ComparisonEnding { absent, crlf, lf, cr };
|
||||
|
||||
inline std::wstring_view comparisonEndingText(ComparisonEnding ending)
|
||||
{
|
||||
switch(ending)
|
||||
{
|
||||
case ComparisonEnding::crlf: return L"\r\n";
|
||||
case ComparisonEnding::lf: return L"\n";
|
||||
case ComparisonEnding::cr: return L"\r";
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
struct ComparisonText
|
||||
{
|
||||
std::vector<std::wstring> lines;
|
||||
std::vector<ComparisonEnding> endings;
|
||||
ComparisonEnding preferred=ComparisonEnding::crlf;
|
||||
|
||||
std::wstring joined() const
|
||||
{
|
||||
std::wstring result;
|
||||
for(size_t i=0;i<lines.size();++i)
|
||||
{
|
||||
result+=lines[i];
|
||||
if(i+1<lines.size())
|
||||
result+=comparisonEndingText(endings[i]==ComparisonEnding::absent?preferred:endings[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
inline ComparisonText splitComparisonText(std::wstring_view contents)
|
||||
{
|
||||
ComparisonText result;
|
||||
if(contents.empty()) return result;
|
||||
size_t start=0;
|
||||
while(true)
|
||||
{
|
||||
const auto end=contents.find_first_of(L"\r\n",start);
|
||||
result.lines.emplace_back(contents.substr(start,end==contents.npos?end:end-start));
|
||||
auto ending=ComparisonEnding::absent;
|
||||
if(end!=contents.npos)
|
||||
ending=contents[end]==L'\n'?ComparisonEnding::lf:
|
||||
end+1<contents.size() && contents[end+1]==L'\n'?ComparisonEnding::crlf:ComparisonEnding::cr;
|
||||
result.endings.push_back(ending);
|
||||
if(ending==ComparisonEnding::absent) break;
|
||||
if(result.endings.size()==1) result.preferred=ending;
|
||||
start=end+(ending==ComparisonEnding::crlf?2:1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
struct ComparisonReplace
|
||||
{
|
||||
size_t start{}, count{};
|
||||
std::vector<std::wstring> lines;
|
||||
std::vector<ComparisonEnding> endings;
|
||||
};
|
||||
|
||||
inline ComparisonReplace replaceComparisonText(ComparisonText &document,const ComparisonReplace &change)
|
||||
{
|
||||
const auto first=document.lines.begin()+change.start, last=first+change.count;
|
||||
const auto firstEnding=document.endings.begin()+change.start, lastEnding=firstEnding+change.count;
|
||||
ComparisonReplace reverse{change.start,change.lines.size(),{first,last},{firstEnding,lastEnding}};
|
||||
document.lines.erase(first,last);
|
||||
document.lines.insert(document.lines.begin()+change.start,change.lines.begin(),change.lines.end());
|
||||
document.endings.erase(firstEnding,lastEnding);
|
||||
document.endings.insert(document.endings.begin()+change.start,change.endings.begin(),change.endings.end());
|
||||
return reverse;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
constexpr UINT panelDropReady=WM_APP+33;
|
||||
|
||||
struct PanelDrop
|
||||
{
|
||||
HWND source{}, target{};
|
||||
fs::path directory, destination;
|
||||
std::vector<fs::path> paths;
|
||||
};
|
||||
|
||||
std::optional<PanelDrop> pendingPanelDrop;
|
||||
HWND draggingPanel{};
|
||||
std::optional<POINT> panelDragStart;
|
||||
|
||||
bool localDropPanel(const Panel &panel)
|
||||
{
|
||||
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.archive && panel.directory.is_absolute();
|
||||
}
|
||||
|
||||
LRESULT panelRowAt(HWND window,POINT point,LRESULT top,LRESULT count)
|
||||
{
|
||||
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,MAKELPARAM(point.x,point.y));
|
||||
// LB_ITEMFROMPOINT only returns the low 16 bits of the row index.
|
||||
constexpr LRESULT rowRange=1<<16;
|
||||
auto row=(top&~(rowRange-1))|LOWORD(hit);
|
||||
if(row<top) row+=rowRange;
|
||||
RECT bounds{};
|
||||
return !HIWORD(hit) && row>=0 && row<count &&
|
||||
SendMessageW(window,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR &&
|
||||
PtInRect(&bounds,point)?row:LB_ERR;
|
||||
}
|
||||
|
||||
FORMATETC fileDropFormat()
|
||||
{
|
||||
return {CF_HDROP,nullptr,DVASPECT_CONTENT,-1,TYMED_HGLOBAL};
|
||||
}
|
||||
|
||||
template<class Interface,class Derived>
|
||||
class DragInterface : public Interface
|
||||
{
|
||||
public:
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **out) override
|
||||
{
|
||||
if(!out) return E_POINTER;
|
||||
*out=nullptr;
|
||||
if(iid!=IID_IUnknown && iid!=__uuidof(Interface)) return E_NOINTERFACE;
|
||||
*out=static_cast<Interface *>(this);
|
||||
AddRef();
|
||||
return S_OK;
|
||||
}
|
||||
ULONG STDMETHODCALLTYPE AddRef() override {return ++references;}
|
||||
ULONG STDMETHODCALLTYPE Release() override
|
||||
{
|
||||
const auto count=--references;
|
||||
if(!count) delete static_cast<Derived *>(this);
|
||||
return count;
|
||||
}
|
||||
|
||||
private:
|
||||
ULONG references{1};
|
||||
};
|
||||
|
||||
class PanelDropTarget final : public DragInterface<IDropTarget,PanelDropTarget>
|
||||
{
|
||||
public:
|
||||
explicit PanelDropTarget(HWND window) : target(window) {}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE DragEnter(IDataObject *data,DWORD,POINTL,DWORD *effect) override
|
||||
{
|
||||
auto format=fileDropFormat();
|
||||
filesystem=data->QueryGetData(&format)==S_OK;
|
||||
return updateEffect(effect);
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE DragOver(DWORD,POINTL,DWORD *effect) override
|
||||
{
|
||||
return updateEffect(effect);
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE DragLeave() override
|
||||
{
|
||||
filesystem=false;
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE Drop(IDataObject *data,DWORD,POINTL location,DWORD *effect) override
|
||||
{
|
||||
updateEffect(effect);
|
||||
filesystem=false;
|
||||
if(*effect==DROPEFFECT_NONE) return S_OK;
|
||||
*effect=DROPEFFECT_NONE;
|
||||
auto format=fileDropFormat();
|
||||
STGMEDIUM medium{};
|
||||
if(FAILED(data->GetData(&format,&medium)))
|
||||
{
|
||||
setStatus(L"Could not read local paths from the drop.");
|
||||
return S_OK;
|
||||
}
|
||||
std::vector<fs::path> paths;
|
||||
try
|
||||
{
|
||||
if(medium.tymed==TYMED_HGLOBAL) paths=ks::fileDropPaths(medium.hGlobal);
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
ReleaseStgMedium(&medium);
|
||||
if(paths.empty())
|
||||
{
|
||||
setStatus(L"The drop contains no usable file or folder paths.");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
const auto &panel=panels[GetDlgCtrlID(target)-102];
|
||||
POINT point{location.x,location.y};
|
||||
ScreenToClient(target,&point);
|
||||
const auto row=panelRowAt(target,point,SendMessageW(target,LB_GETTOPINDEX,0,0),
|
||||
static_cast<LRESULT>(panel.rows.size()));
|
||||
const auto &destination=row!=LB_ERR && panel.sizes[row]==L"Folder"?panel.rows[row]:panel.directory;
|
||||
pendingPanelDrop=PanelDrop{draggingPanel,target,panel.directory,destination,std::move(paths)};
|
||||
if(PostMessageW(GetParent(target),panelDropReady,0,0))
|
||||
{
|
||||
// Files performs the requested move after confirmation.
|
||||
*effect=DROPEFFECT_COPY;
|
||||
}
|
||||
else pendingPanelDrop.reset();
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
setStatus(L"Could not prepare the drop.");
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
private:
|
||||
HRESULT updateEffect(DWORD *effect)
|
||||
{
|
||||
const auto allowed=*effect;
|
||||
*effect=DROPEFFECT_NONE;
|
||||
if(!filesystem || !(allowed&DROPEFFECT_COPY))
|
||||
setStatus(L"Drag files or folders from a Windows filesystem.");
|
||||
else if(target==draggingPanel)
|
||||
setStatus(L"Drop files onto the other panel.");
|
||||
else if(!localDropPanel(panels[GetDlgCtrlID(target)-102]))
|
||||
setStatus(L"Open a local folder in the destination panel before dropping files.");
|
||||
else if(!copyInProgress && !pendingPanelDrop && !FilesModalDialog::activeFor(GetParent(target)))
|
||||
*effect=DROPEFFECT_COPY;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HWND target;
|
||||
bool filesystem{};
|
||||
};
|
||||
|
||||
class PanelDragSource final : public DragInterface<IDropSource,PanelDragSource>
|
||||
{
|
||||
public:
|
||||
HRESULT STDMETHODCALLTYPE QueryContinueDrag(BOOL escape,DWORD keys) override
|
||||
{
|
||||
if(escape) return DRAGDROP_S_CANCEL;
|
||||
return keys&MK_LBUTTON?S_OK:DRAGDROP_S_DROP;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE GiveFeedback(DWORD) override {return DRAGDROP_S_USEDEFAULTCURSORS;}
|
||||
};
|
||||
|
||||
void beginPanelDrag(HWND window)
|
||||
{
|
||||
auto &panel=panels[GetDlgCtrlID(window)-102];
|
||||
if(!localDropPanel(panel))
|
||||
{
|
||||
setStatus(L"Drag files or folders from an open local folder.");
|
||||
return;
|
||||
}
|
||||
auto paths=selectedPanelPaths(panel);
|
||||
if(paths.empty()) return;
|
||||
std::vector<PCIDLIST_ABSOLUTE> items;
|
||||
items.reserve(paths.size());
|
||||
const auto clear=[&](void *){for(auto item:items) CoTaskMemFree(const_cast<PIDLIST_ABSOLUTE>(item));};
|
||||
const std::unique_ptr<void,decltype(clear)> cleanup(&items,clear);
|
||||
for(const auto &path:paths)
|
||||
{
|
||||
PIDLIST_ABSOLUTE item{};
|
||||
if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&item,0,nullptr)))
|
||||
{
|
||||
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
|
||||
return;
|
||||
}
|
||||
items.push_back(item);
|
||||
}
|
||||
IShellItemArray *array{};
|
||||
if(FAILED(SHCreateShellItemArrayFromIDLists(static_cast<UINT>(items.size()),items.data(),&array)))
|
||||
{
|
||||
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
|
||||
return;
|
||||
}
|
||||
IDataObject *data{};
|
||||
const auto result=array->BindToHandler(nullptr,BHID_DataObject,IID_PPV_ARGS(&data));
|
||||
array->Release();
|
||||
if(FAILED(result))
|
||||
{
|
||||
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
|
||||
return;
|
||||
}
|
||||
const auto source=new(std::nothrow) PanelDragSource;
|
||||
if(source)
|
||||
{
|
||||
draggingPanel=window;
|
||||
DWORD effect{};
|
||||
DoDragDrop(data,source,DROPEFFECT_COPY,&effect);
|
||||
draggingPanel=nullptr;
|
||||
source->Release();
|
||||
}
|
||||
data->Release();
|
||||
}
|
||||
|
||||
void performPanelDrop(HWND owner)
|
||||
{
|
||||
if(!pendingPanelDrop) return;
|
||||
auto drop=std::move(*pendingPanelDrop);
|
||||
pendingPanelDrop.reset();
|
||||
auto index=GetDlgCtrlID(drop.target)-102;
|
||||
if(index<0 || index>=static_cast<int>(std::size(panels))) return;
|
||||
auto &panel=panels[index];
|
||||
if(!localDropPanel(panel) || panel.directory!=drop.directory || !IsWindowVisible(drop.target))
|
||||
{
|
||||
setStatus(L"The destination panel changed. Drop the files again.");
|
||||
return;
|
||||
}
|
||||
if(copyInProgress || FilesModalDialog::activeFor(owner))
|
||||
{
|
||||
setStatus(L"Finish the current operation before dropping files.");
|
||||
return;
|
||||
}
|
||||
|
||||
const auto text=L"Destination folder:\r\n"+drop.destination.native();
|
||||
const auto answer=showFilesNotice(owner,text.c_str(),L"Drop files",
|
||||
{.tone=FilesNoticeTone::neutral,.chooseTransfer=true});
|
||||
if(answer!=IDYES && answer!=IDNO) return;
|
||||
auto &source=drop.source?panels[GetDlgCtrlID(drop.source)-102]:panel;
|
||||
activatePanel(index);
|
||||
panelClipboardContext=true;
|
||||
copySelection(owner,source,panel,answer==IDNO,std::move(drop.paths),std::move(drop.destination));
|
||||
}
|
||||
+41
-9
@@ -1,20 +1,37 @@
|
||||
constexpr int findMask=480, findHidden=481, findFooter=482, findLabel=483;
|
||||
|
||||
INT_PTR CALLBACK findFilesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
struct FileMaskPrompt
|
||||
{
|
||||
Panel::FindOptions options;
|
||||
bool filter{};
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK fileMaskDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_DRAWITEM)
|
||||
{
|
||||
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
|
||||
return TRUE;
|
||||
}
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Find files ",false,{findFooter}))
|
||||
const auto *prompt=reinterpret_cast<const FileMaskPrompt *>(message==WM_INITDIALOG?lp:GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
const bool filter=prompt && prompt->filter;
|
||||
const auto title=filter?L" Panel filter ":L" Find files ";
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,title,false,{findFooter}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
const auto &options=*reinterpret_cast<Panel::FindOptions *>(lp);
|
||||
const auto &options=prompt->options;
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
if(filter)
|
||||
{
|
||||
SetWindowTextW(dialog,L"Panel filter");
|
||||
SetDlgItemTextW(dialog,findLabel,L"File &name or mask (blank clears)");
|
||||
SetDlgItemTextW(dialog,findHidden,L"Show &hidden and system files");
|
||||
SetDlgItemTextW(dialog,IDOK,L"&Apply");
|
||||
}
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,findLabel);
|
||||
fitFarEditToLine(GetDlgItem(dialog,findMask));
|
||||
for(const auto id:{IDOK,IDCANCEL})
|
||||
{
|
||||
const auto button=GetDlgItem(dialog,id);
|
||||
@@ -32,12 +49,12 @@ INT_PTR CALLBACK findFilesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
|
||||
{
|
||||
auto &options=*reinterpret_cast<Panel::FindOptions *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
auto &options=reinterpret_cast<FileMaskPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER))->options;
|
||||
wchar_t mask[256]{};
|
||||
GetDlgItemTextW(dialog,findMask,mask,static_cast<int>(std::size(mask)));
|
||||
if(std::wstring_view(mask).find_first_of(L"/\\:")!=std::wstring_view::npos)
|
||||
{
|
||||
showFilesNotice(dialog,L"Enter a file name or mask without a path.",L"Find files");
|
||||
showFilesNotice(dialog,L"Enter a file name or mask without a path.",filter?L"Panel filter":L"Find files");
|
||||
SetFocus(GetDlgItem(dialog,findMask));
|
||||
return TRUE;
|
||||
}
|
||||
@@ -58,13 +75,14 @@ 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);
|
||||
}
|
||||
|
||||
void findLocalFiles(HWND owner,Panel &panel)
|
||||
{
|
||||
if(panel.peer || panel.ftp || panel.directory.empty())
|
||||
if(panel.peer || panel.ftp || panel.archive || panel.directory.empty())
|
||||
{
|
||||
setStatus(L"Find files requires a local folder.");
|
||||
return;
|
||||
@@ -74,8 +92,22 @@ void findLocalFiles(HWND owner,Panel &panel)
|
||||
setStatus(L"Wait for the current scan to finish.");
|
||||
return;
|
||||
}
|
||||
auto options=panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{};
|
||||
FileMaskPrompt prompt{panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{}};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
|
||||
findFilesDialog,reinterpret_cast<LPARAM>(&options))!=IDOK) return;
|
||||
startFileSearch(panel,std::move(options));
|
||||
fileMaskDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
|
||||
startFileSearch(panel,std::move(prompt.options));
|
||||
}
|
||||
|
||||
void editPanelFilter(HWND owner,Panel &panel)
|
||||
{
|
||||
if(!panelViewAvailable(panel)) return;
|
||||
FileMaskPrompt prompt{{panel.view.mask,panel.view.showHidden},true};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
|
||||
fileMaskDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
|
||||
auto &options=prompt.options;
|
||||
if(options.mask==L"*") options.mask.clear();
|
||||
if(panel.view.mask==options.mask && panel.view.showHidden==options.includeHidden) return;
|
||||
panel.view.mask=std::move(options.mask);
|
||||
panel.view.showHidden=options.includeHidden;
|
||||
updatePanelView(panel);
|
||||
}
|
||||
@@ -51,8 +51,7 @@ std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &req
|
||||
else if(matchesFileMask(path.filename().native(),request.find->mask))
|
||||
{
|
||||
result->files.push_back(path);
|
||||
result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size});
|
||||
result->timestamps.emplace(path,entry.modified);
|
||||
result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size,entry.modified});
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
@@ -145,7 +152,7 @@ bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
|
||||
|
||||
void addFolderShortcut(const Panel &panel,int digit)
|
||||
{
|
||||
if(panel.directory.empty() || panel.ftp) return;
|
||||
if(panel.directory.empty() || panel.ftp || panel.archive) return;
|
||||
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
|
||||
panel.peer?panel.peer->name:L""},digit,{}};
|
||||
if(editFolderShortcut(GetParent(panel.list),edit))
|
||||
@@ -351,7 +358,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto &panel=*view->panel;
|
||||
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
|
||||
panel.peer?panel.peer->name:L""},view->digit,{}};
|
||||
if(!panel.directory.empty() && editFolderShortcut(dialog,edit))
|
||||
if(!panel.directory.empty() && !panel.archive && editFolderShortcut(dialog,edit))
|
||||
layoutQuickFolders(dialog,*view,static_cast<int>(group.size())-1);
|
||||
SetFocus(GetDlgItem(dialog,shortcutList));
|
||||
return TRUE;
|
||||
|
||||
+144
-26
@@ -1,17 +1,68 @@
|
||||
struct FtpProfile
|
||||
enum class TransferProtocol { ftp, sftp };
|
||||
constexpr unsigned defaultSftpPort=22;
|
||||
|
||||
const wchar_t *transferProtocolName(TransferProtocol protocol)
|
||||
{
|
||||
return protocol==TransferProtocol::sftp?L"SFTP":L"FTP";
|
||||
}
|
||||
|
||||
struct TransferProfile
|
||||
{
|
||||
std::wstring name, host, user;
|
||||
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
|
||||
ks::Bytes secret;
|
||||
bool legacyNames{};
|
||||
std::string id;
|
||||
TransferProtocol protocol{};
|
||||
fs::path privateKey;
|
||||
std::string hostFingerprint;
|
||||
std::string jumpProfile;
|
||||
};
|
||||
|
||||
std::vector<FtpProfile> ftpProfiles;
|
||||
bool ftpProfilesLoaded{};
|
||||
constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles";
|
||||
constexpr DWORD ftpProfilesMaxBytes=1024*1024;
|
||||
struct TransferProfiles
|
||||
{
|
||||
const wchar_t *preference;
|
||||
std::vector<TransferProfile> rows;
|
||||
bool loaded{};
|
||||
};
|
||||
|
||||
TransferProfiles &transferProfiles(TransferProtocol protocol)
|
||||
{
|
||||
static TransferProfiles ftp{L"FtpProfiles"},sftp{L"SftpProfiles"};
|
||||
return protocol==TransferProtocol::sftp?sftp:ftp;
|
||||
}
|
||||
|
||||
std::atomic<std::shared_ptr<const std::vector<TransferProfile>>> sshProfiles;
|
||||
|
||||
constexpr size_t sshRouteLimit=8;
|
||||
|
||||
std::vector<TransferProfile> sshRoute(const TransferProfile &destination,
|
||||
const std::vector<TransferProfile> &profiles)
|
||||
{
|
||||
std::vector<TransferProfile> route{destination};
|
||||
std::set<std::string> seen{destination.id};
|
||||
while(!route.back().jumpProfile.empty())
|
||||
{
|
||||
const auto &id=route.back().jumpProfile;
|
||||
if(!seen.insert(id).second) throw std::runtime_error("The SSH jump route contains a loop.");
|
||||
if(route.size()>=sshRouteLimit) throw std::runtime_error("An SSH route can contain up to eight hosts.");
|
||||
const auto hop=std::find_if(profiles.begin(),profiles.end(),
|
||||
[&id](const auto &profile){return profile.id==id;});
|
||||
if(hop==profiles.end()) throw std::runtime_error("An SSH jump profile is missing. Edit this connection to update its route.");
|
||||
route.push_back(*hop);
|
||||
}
|
||||
std::reverse(route.begin(),route.end());
|
||||
return route;
|
||||
}
|
||||
|
||||
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 +70,93 @@ std::wstring ftpPath(const fs::path &path)
|
||||
return value;
|
||||
}
|
||||
|
||||
bool saveFtpProfiles(const std::vector<FtpProfile> &profiles)
|
||||
bool saveTransferProfiles(TransferProtocol protocol,const std::vector<TransferProfile> &profiles)
|
||||
{
|
||||
auto rows=Json::array();
|
||||
for(const auto &profile:profiles)
|
||||
rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
|
||||
{
|
||||
Json row{{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
|
||||
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
|
||||
{"legacyNames",profile.legacyNames}});
|
||||
{"legacyNames",profile.legacyNames},{"id",profile.id}};
|
||||
if(protocol==TransferProtocol::sftp)
|
||||
{
|
||||
row["privateKey"]=ks::utf8(profile.privateKey.native());
|
||||
row["hostFingerprint"]=profile.hostFingerprint;
|
||||
row["jumpProfile"]=profile.jumpProfile;
|
||||
}
|
||||
rows.push_back(std::move(row));
|
||||
}
|
||||
const auto data=rows.dump();
|
||||
return data.size()<=ftpProfilesMaxBytes &&
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
|
||||
if(data.size()>transferProfilesMaxBytes) return false;
|
||||
const auto snapshot=protocol==TransferProtocol::sftp?
|
||||
std::make_shared<const std::vector<TransferProfile>>(profiles):nullptr;
|
||||
if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
|
||||
static_cast<DWORD>(data.size()))!=ERROR_SUCCESS) return false;
|
||||
if(snapshot) sshProfiles=snapshot;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool loadFtpProfiles()
|
||||
bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
|
||||
{
|
||||
if(ftpProfilesLoaded) return true;
|
||||
auto &settings=transferProfiles(protocol);
|
||||
if(settings.loaded) return true;
|
||||
DWORD bytes{};
|
||||
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,
|
||||
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference,
|
||||
RRF_RT_REG_BINARY,nullptr,nullptr,&bytes);
|
||||
if(query==ERROR_FILE_NOT_FOUND)
|
||||
{
|
||||
ftpProfilesLoaded=true;
|
||||
settings.loaded=true;
|
||||
return true;
|
||||
}
|
||||
if(query!=ERROR_SUCCESS || !bytes || bytes>ftpProfilesMaxBytes) return false;
|
||||
if(query!=ERROR_SUCCESS || !bytes || bytes>transferProfilesMaxBytes) return false;
|
||||
std::string data(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,RRF_RT_REG_BINARY,
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference,RRF_RT_REG_BINARY,
|
||||
nullptr,data.data(),&bytes)!=ERROR_SUCCESS) return false;
|
||||
try
|
||||
{
|
||||
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
|
||||
if(!rows.is_array()) return false;
|
||||
std::vector<FtpProfile> profiles;
|
||||
std::vector<TransferProfile> profiles;
|
||||
for(const auto &row:rows)
|
||||
{
|
||||
const auto port=row.at("port").get<unsigned>();
|
||||
if(!port || port>65535) return false;
|
||||
FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
|
||||
TransferProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
|
||||
ks::wide(row.at("user")),static_cast<INTERNET_PORT>(port),row.at("secret").get<ks::Bytes>(),
|
||||
row.value("legacyNames",false)};
|
||||
row.value("legacyNames",false),row.value("id",std::string{}),protocol};
|
||||
if(profile.id.empty()) profile.id="legacy:"+ks::utf8(profile.name);
|
||||
if(profile.name.empty() || profile.host.empty()) return false;
|
||||
if(protocol==TransferProtocol::sftp)
|
||||
{
|
||||
profile.privateKey=ks::wide(row.value("privateKey",std::string{}));
|
||||
profile.hostFingerprint=row.value("hostFingerprint",std::string{});
|
||||
profile.jumpProfile=row.value("jumpProfile",std::string{});
|
||||
}
|
||||
profiles.push_back(std::move(profile));
|
||||
}
|
||||
ftpProfiles=std::move(profiles);
|
||||
ftpProfilesLoaded=true;
|
||||
if(protocol==TransferProtocol::sftp)
|
||||
sshProfiles=std::make_shared<const std::vector<TransferProfile>>(profiles);
|
||||
settings.rows=std::move(profiles);
|
||||
settings.loaded=true;
|
||||
return true;
|
||||
}
|
||||
catch(const std::exception &) {return false;}
|
||||
}
|
||||
|
||||
std::wstring ftpPassword(const FtpProfile &profile)
|
||||
const TransferProfile *findTransferProfile(std::string_view id,TransferProtocol protocol=TransferProtocol::ftp)
|
||||
{
|
||||
const auto &profiles=transferProfiles(protocol).rows;
|
||||
const auto profile=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry) {
|
||||
return entry.id==id;
|
||||
});
|
||||
return profile==profiles.end()?nullptr:&*profile;
|
||||
}
|
||||
|
||||
std::wstring transferPassword(const TransferProfile &profile)
|
||||
{
|
||||
if(profile.secret.empty()) return {};
|
||||
auto bytes=ks::unprotect(profile.secret);
|
||||
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid FTP password");
|
||||
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid saved transfer password");
|
||||
std::wstring password(bytes.size()/sizeof(wchar_t),L'\0');
|
||||
std::copy(bytes.begin(),bytes.end(),reinterpret_cast<unsigned char*>(password.data()));
|
||||
SecureZeroMemory(bytes.data(),bytes.size());
|
||||
@@ -99,6 +182,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 +225,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 +233,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
@@ -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;
|
||||
}
|
||||
}
|
||||
+270
-81
@@ -1,76 +1,81 @@
|
||||
namespace ftpDialog
|
||||
namespace transferDialog
|
||||
{
|
||||
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
|
||||
|
||||
std::wstring trim(std::wstring value)
|
||||
{
|
||||
const auto first=value.find_first_not_of(L" \t\r\n");
|
||||
if(first==value.npos) return {};
|
||||
return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1);
|
||||
}
|
||||
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566,jumpVia=567,jumpLabel=568;
|
||||
|
||||
struct Edit
|
||||
{
|
||||
FtpProfile profile;
|
||||
TransferProfile profile;
|
||||
std::optional<size_t> index;
|
||||
std::wstring pinnedHost;
|
||||
INTERNET_PORT pinnedPort{};
|
||||
std::string pin;
|
||||
std::vector<std::string> jumpChoices;
|
||||
bool testing{};
|
||||
std::atomic_bool canceled{};
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
bool sameEndpoint(const Edit &edit,const TransferProfile &profile)
|
||||
{
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" FTP connection ",false,{footer}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
return edit.pinnedPort==profile.port && CompareStringOrdinal(edit.pinnedHost.c_str(),-1,
|
||||
profile.host.c_str(),-1,TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
std::wstring connectionTitle(TransferProtocol protocol)
|
||||
{
|
||||
return std::wstring(transferProtocolName(protocol))+L" connection";
|
||||
}
|
||||
|
||||
void showHostStatus(HWND dialog,const Edit &edit)
|
||||
{
|
||||
TransferProfile current;
|
||||
current.host=trimFilesField(shortcutField(dialog,host));
|
||||
BOOL valid{};
|
||||
current.port=static_cast<INTERNET_PORT>(GetDlgItemInt(dialog,port,&valid,FALSE));
|
||||
const bool trusted=valid && !edit.pin.empty() && sameEndpoint(edit,current);
|
||||
const auto message=trusted?L"Trusted "+ks::wide(edit.pin):std::wstring(L"Host key not verified");
|
||||
SetDlgItemTextW(dialog,hostStatus,message.c_str());
|
||||
EnableWindow(GetDlgItem(dialog,forgetKey),trusted && !edit.testing);
|
||||
}
|
||||
|
||||
void addJumpChoice(HWND dialog,Edit &edit,const std::wstring &label,const std::string &id)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,jumpVia,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
if(row==CB_ERR || row==CB_ERRSPACE) return;
|
||||
edit.jumpChoices.push_back(id);
|
||||
if(id==edit.profile.jumpProfile) SendDlgItemMessageW(dialog,jumpVia,CB_SETCURSEL,row,0);
|
||||
}
|
||||
|
||||
void populateJumpChoices(HWND dialog,Edit &edit)
|
||||
{
|
||||
addJumpChoice(dialog,edit,L"Direct",{});
|
||||
for(const auto &profile:transferProfiles(TransferProtocol::sftp).rows)
|
||||
if(profile.id!=edit.profile.id) addJumpChoice(dialog,edit,profile.name,profile.id);
|
||||
if(SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0)==CB_ERR)
|
||||
addJumpChoice(dialog,edit,L"Missing profile",edit.profile.jumpProfile);
|
||||
}
|
||||
|
||||
std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
|
||||
{
|
||||
TransferProfile profile;
|
||||
profile.protocol=edit.profile.protocol;
|
||||
const bool sftp=profile.protocol==TransferProtocol::sftp;
|
||||
const auto invalid=[&](int field,const wchar_t *message)->std::optional<TransferProfile>
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
auto &profile=reinterpret_cast<Edit*>(lp)->profile;
|
||||
prepareCopyDialog(dialog);
|
||||
layoutDialogContent(dialog,381);
|
||||
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL})
|
||||
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
for(const auto id:{name,host,user,password})
|
||||
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
|
||||
SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0);
|
||||
SetDlgItemTextW(dialog,name,profile.name.c_str());
|
||||
SetDlgItemTextW(dialog,host,profile.host.c_str());
|
||||
SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str());
|
||||
SetDlgItemTextW(dialog,user,profile.user.c_str());
|
||||
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
|
||||
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
|
||||
try
|
||||
{
|
||||
auto secret=ftpPassword(profile);
|
||||
SetDlgItemTextW(dialog,password,secret.c_str());
|
||||
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetWindowTextW(GetDlgItem(dialog,389),L"&Password (re-enter to replace saved password)");
|
||||
}
|
||||
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
|
||||
auto &edit=*reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
const auto invalid=[&](int field,const wchar_t *message)
|
||||
{
|
||||
showFilesNotice(dialog,message,L"FTP connection");
|
||||
showFilesNotice(dialog,message,connectionTitle(profile.protocol).c_str());
|
||||
SetFocus(GetDlgItem(dialog,field));
|
||||
return TRUE;
|
||||
return {};
|
||||
};
|
||||
FtpProfile profile;
|
||||
profile.legacyNames=IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
|
||||
profile.name=trim(shortcutField(dialog,name));
|
||||
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
|
||||
profile.legacyNames=!sftp && IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
|
||||
profile.name=trimFilesField(shortcutField(dialog,name));
|
||||
if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos)
|
||||
return invalid(name,L"Enter a name for this connection.");
|
||||
for(size_t i=0;i<ftpProfiles.size();++i)
|
||||
if(edit.index!=i && CompareStringOrdinal(ftpProfiles[i].name.c_str(),-1,profile.name.c_str(),-1,TRUE)==CSTR_EQUAL)
|
||||
const auto &profiles=transferProfiles(profile.protocol).rows;
|
||||
for(size_t i=0;i<profiles.size();++i)
|
||||
if(edit.index!=i && CompareStringOrdinal(profiles[i].name.c_str(),-1,profile.name.c_str(),-1,TRUE)==CSTR_EQUAL)
|
||||
return invalid(name,L"A connection with this name already exists.");
|
||||
profile.host=trim(shortcutField(dialog,host));
|
||||
profile.host=trimFilesField(shortcutField(dialog,host));
|
||||
if(profile.host.empty() || profile.host.find_first_of(L" /\\@\t\r\n")!=profile.host.npos)
|
||||
return invalid(host,L"Enter the server host name or IP address.");
|
||||
const auto value=shortcutField(dialog,port);
|
||||
@@ -78,52 +83,236 @@ 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;
|
||||
const auto choice=SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0);
|
||||
if(choice>=0 && static_cast<size_t>(choice)<edit.jumpChoices.size())
|
||||
profile.jumpProfile=edit.jumpChoices[choice];
|
||||
try {sshRoute(profile,profiles);}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
return invalid(jumpVia,ks::wide(error.what()).c_str());
|
||||
}
|
||||
}
|
||||
auto plain=shortcutField(dialog,password);
|
||||
if(!plain.empty())
|
||||
{
|
||||
const auto start=reinterpret_cast<const unsigned char*>(plain.data());
|
||||
ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t));
|
||||
struct Erase
|
||||
{
|
||||
ks::Bytes &bytes;
|
||||
std::wstring &text;
|
||||
~Erase()
|
||||
{
|
||||
SecureZeroMemory(bytes.data(),bytes.size());
|
||||
SecureZeroMemory(text.data(),text.size()*sizeof(wchar_t));
|
||||
}
|
||||
} erase{bytes,plain};
|
||||
profile.secret=ks::protect(bytes);
|
||||
}
|
||||
return profile;
|
||||
}
|
||||
|
||||
template<class Task>
|
||||
bool runTest(HWND dialog,Edit &edit,const wchar_t *status,Task task)
|
||||
{
|
||||
constexpr int controls[]{name,host,port,user,password,keyFile,jumpVia,testConnection,forgetKey,IDOK};
|
||||
edit.testing=true;
|
||||
edit.canceled=false;
|
||||
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),FALSE);
|
||||
SetFocus(GetDlgItem(dialog,IDCANCEL));
|
||||
SetDlgItemTextW(dialog,hostStatus,status);
|
||||
std::wstring error;
|
||||
try
|
||||
{
|
||||
auto plain=shortcutField(dialog,password);
|
||||
if(!plain.empty())
|
||||
FileOperationUi worker;
|
||||
worker.run(dialog,edit.canceled,std::move(task));
|
||||
}
|
||||
catch(const std::exception &exception) {error=ks::wide(exception.what());}
|
||||
edit.testing=false;
|
||||
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),TRUE);
|
||||
showHostStatus(dialog,edit);
|
||||
if(edit.canceled) return false;
|
||||
if(error.empty()) return true;
|
||||
showFilesNotice(dialog,error.c_str(),L"SFTP connection test",{.tone=FilesNoticeTone::warning});
|
||||
return false;
|
||||
}
|
||||
|
||||
void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
|
||||
{
|
||||
if(profile.hostFingerprint.empty())
|
||||
{
|
||||
std::string fingerprint;
|
||||
if(!runTest(dialog,edit,L"Reading the SSH host key…",[&] {
|
||||
const SshConnection probe(profile,true);
|
||||
fingerprint=probe.fingerprint();
|
||||
})) return;
|
||||
const auto prompt=profile.host+L":"+std::to_wstring(profile.port)+L"\r\n"+ks::wide(fingerprint)+
|
||||
L"\r\n\r\nVerify this fingerprint with the server administrator. Trust this SSH host key?";
|
||||
if(showFilesNotice(dialog,prompt.c_str(),L"Verify SFTP host key",{.confirm=true})!=IDYES) return;
|
||||
edit.pinnedHost=profile.host;
|
||||
edit.pinnedPort=profile.port;
|
||||
profile.hostFingerprint=edit.pin=std::move(fingerprint);
|
||||
}
|
||||
fs::path initial;
|
||||
if(runTest(dialog,edit,L"Testing the SSH login…",[&] {
|
||||
SshConnection connection(profile);
|
||||
const SftpSubsystem sftp(libssh2_sftp_init(connection.session()),libssh2_sftp_shutdown);
|
||||
if(sftp) initial=sftpInitialDirectory(sftp.get());
|
||||
}))
|
||||
{
|
||||
const auto details=L"Connected to "+profile.host+L".\r\n\r\n"+(initial.empty()?
|
||||
L"SFTP is unavailable. This profile can still be used as an SSH jump host.":
|
||||
L"Initial folder "+ftpPath(initial)+L".");
|
||||
showFilesNotice(dialog,details.c_str(),L"SFTP connection test");
|
||||
}
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
auto *edit=message==WM_INITDIALOG?reinterpret_cast<Edit*>(lp):
|
||||
reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
const bool sftp=edit && edit->profile.protocol==TransferProtocol::sftp;
|
||||
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,sftp?L" SFTP connection ":L" FTP connection ",false,{footer}))
|
||||
return painted;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
const auto &profile=edit->profile;
|
||||
prepareCopyDialog(dialog);
|
||||
layoutDialogContent(dialog,381);
|
||||
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus,jumpVia,jumpLabel})
|
||||
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());
|
||||
populateJumpChoices(dialog,*edit);
|
||||
installFarCombo(GetDlgItem(dialog,jumpVia),GetDlgItem(dialog,keyFile));
|
||||
showHostStatus(dialog,*edit);
|
||||
layoutDialogButtons(dialog,footer,{testConnection,forgetKey,IDOK,IDCANCEL});
|
||||
}
|
||||
auto updated=ftpProfiles;
|
||||
if(edit.index) updated[*edit.index]=std::move(profile);
|
||||
else updated.push_back(std::move(profile));
|
||||
if(saveFtpProfiles(updated))
|
||||
else
|
||||
{
|
||||
ftpProfiles=std::move(updated);
|
||||
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
|
||||
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
|
||||
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
|
||||
}
|
||||
try
|
||||
{
|
||||
auto secret=transferPassword(profile);
|
||||
SetDlgItemTextW(dialog,password,secret.c_str());
|
||||
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetDlgItemTextW(dialog,389,L"&Secret (re-enter to replace the saved value)");
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(!edit) return FALSE;
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
if(edit->testing)
|
||||
{
|
||||
edit->canceled=true;
|
||||
SetDlgItemTextW(dialog,hostStatus,L"Stopping when the current request returns…");
|
||||
}
|
||||
else
|
||||
{
|
||||
SetDlgItemTextW(dialog,password,L"");
|
||||
SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0);
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
if(edit->testing) return TRUE;
|
||||
const auto command=LOWORD(wp);
|
||||
if(sftp && HIWORD(wp)==EN_CHANGE && (command==host || command==port))
|
||||
{
|
||||
showHostStatus(dialog,*edit);
|
||||
return TRUE;
|
||||
}
|
||||
if(sftp && command==forgetKey)
|
||||
{
|
||||
if(showFilesNotice(dialog,L"Forget the trusted key for this endpoint? A new key must be verified before signing in.",
|
||||
L"SFTP host key",{.confirm=true})==IDYES)
|
||||
{
|
||||
edit->pin.clear();
|
||||
showHostStatus(dialog,*edit);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(command!=IDOK && (!sftp || command!=testConnection)) return FALSE;
|
||||
try
|
||||
{
|
||||
auto profile=readProfile(dialog,*edit);
|
||||
if(!profile) return TRUE;
|
||||
if(command==testConnection)
|
||||
{
|
||||
testSftp(dialog,*edit,std::move(*profile));
|
||||
return TRUE;
|
||||
}
|
||||
auto &settings=transferProfiles(profile->protocol);
|
||||
auto updated=settings.rows;
|
||||
if(edit->index) updated[*edit->index]=std::move(*profile);
|
||||
else updated.push_back(std::move(*profile));
|
||||
if(saveTransferProfiles(edit->profile.protocol,updated))
|
||||
{
|
||||
settings.rows=std::move(updated);
|
||||
SetDlgItemTextW(dialog,password,L"");
|
||||
SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0);
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
showFilesNotice(dialog,L"Could not save the FTP connection.",L"FTP connection");
|
||||
const auto title=connectionTitle(edit->profile.protocol);
|
||||
showFilesNotice(dialog,(L"Could not save the "+title+L".").c_str(),title.c_str());
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
void editFtpProfile(Panel &panel,bool create)
|
||||
void editTransferProfile(Panel &panel,bool create)
|
||||
{
|
||||
ftpDialog::Edit edit;
|
||||
transferDialog::Edit edit;
|
||||
const auto protocol=panel.ftp->protocol;
|
||||
const auto &profiles=transferProfiles(protocol).rows;
|
||||
edit.profile.protocol=protocol;
|
||||
if(protocol==TransferProtocol::sftp) edit.profile.port=defaultSftpPort;
|
||||
if(!create)
|
||||
{
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(row<0 || static_cast<size_t>(row)>=ftpProfiles.size()) return;
|
||||
if(row<0 || static_cast<size_t>(row)>=profiles.size()) return;
|
||||
edit.index=static_cast<size_t>(row);
|
||||
edit.profile=ftpProfiles[*edit.index];
|
||||
edit.profile=profiles[*edit.index];
|
||||
edit.pinnedHost=edit.profile.host;
|
||||
edit.pinnedPort=edit.profile.port;
|
||||
edit.pin=edit.profile.hostFingerprint;
|
||||
}
|
||||
const auto owner=GetParent(panel.list);
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(112),owner,
|
||||
ftpDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
|
||||
const auto resource=protocol==TransferProtocol::sftp?124:112;
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(resource),owner,
|
||||
transferDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
|
||||
for(auto &other:panels)
|
||||
{
|
||||
if(!ftpProfileList(other) || other.scan.valid()) continue;
|
||||
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(ftpProfiles.size()-1)):fs::path{};
|
||||
showFtpProfiles(other,selection);
|
||||
if(!transferProfileList(other) || other.ftp->protocol!=protocol || other.scan.valid()) continue;
|
||||
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(profiles.size()-1)):fs::path{};
|
||||
showTransferProfiles(other,protocol,selection);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
#include "files_image_decode.h"
|
||||
#include <windows.h>
|
||||
#include <wincodec.h>
|
||||
#include <webp/decode.h>
|
||||
#include <webp/demux.h>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace
|
||||
{
|
||||
namespace fs=std::filesystem;
|
||||
constexpr char invalidImage[]="Could not decode the image. The file may be damaged.";
|
||||
constexpr char largeImage[]="This image is too large to preview.";
|
||||
|
||||
enum class ImageFormat { unknown, png, jpeg, gif, webp, bmp };
|
||||
|
||||
ImageFormat imageFormat(const fs::path &path)
|
||||
{
|
||||
const auto extension=path.extension();
|
||||
const auto matches=[&](const wchar_t *suffix)
|
||||
{
|
||||
return CompareStringOrdinal(extension.c_str(),-1,suffix,-1,TRUE)==CSTR_EQUAL;
|
||||
};
|
||||
if(matches(L".png")) return ImageFormat::png;
|
||||
if(matches(L".jpg") || matches(L".jpeg") || matches(L".jpe")) return ImageFormat::jpeg;
|
||||
if(matches(L".gif")) return ImageFormat::gif;
|
||||
if(matches(L".webp")) return ImageFormat::webp;
|
||||
if(matches(L".bmp")) return ImageFormat::bmp;
|
||||
return ImageFormat::unknown;
|
||||
}
|
||||
|
||||
void checkImage(HRESULT result)
|
||||
{
|
||||
if(FAILED(result)) throw std::runtime_error(invalidImage);
|
||||
}
|
||||
|
||||
void checkImageDimensions(unsigned width,unsigned height)
|
||||
{
|
||||
if(!width || !height) throw std::runtime_error(invalidImage);
|
||||
if(width>16384 || height>16384 || uint64_t(width)*height>32ULL*1024*1024)
|
||||
throw std::runtime_error(largeImage);
|
||||
}
|
||||
|
||||
void checkImageStop(std::stop_token stop)
|
||||
{
|
||||
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
}
|
||||
|
||||
template<class T>
|
||||
struct ImagingObject
|
||||
{
|
||||
T *value{};
|
||||
~ImagingObject() {if(value) value->Release();}
|
||||
T *operator->() const {return value;}
|
||||
};
|
||||
|
||||
ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop)
|
||||
{
|
||||
struct Apartment
|
||||
{
|
||||
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
|
||||
};
|
||||
const Apartment apartment;
|
||||
if(apartment.initialized!=RPC_E_CHANGED_MODE) checkImage(apartment.initialized);
|
||||
ImagingObject<IWICImagingFactory> factory;
|
||||
checkImage(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
|
||||
ImagingObject<IWICStream> stream;
|
||||
checkImage(factory->CreateStream(&stream.value));
|
||||
checkImage(stream->InitializeFromFilename(file.c_str(),GENERIC_READ));
|
||||
const auto &container=format==ImageFormat::png?GUID_ContainerFormatPng:
|
||||
format==ImageFormat::jpeg?GUID_ContainerFormatJpeg:format==ImageFormat::gif?GUID_ContainerFormatGif:
|
||||
GUID_ContainerFormatBmp;
|
||||
ImagingObject<IWICBitmapDecoder> decoder;
|
||||
checkImage(factory->CreateDecoder(container,nullptr,&decoder.value));
|
||||
checkImage(decoder->Initialize(stream.value,WICDecodeMetadataCacheOnDemand));
|
||||
ImagingObject<IWICBitmapFrameDecode> frame;
|
||||
checkImage(decoder->GetFrame(0,&frame.value));
|
||||
ImageRaster raster;
|
||||
checkImage(frame->GetSize(&raster.width,&raster.height));
|
||||
checkImageDimensions(raster.width,raster.height);
|
||||
checkImageStop(stop);
|
||||
ImagingObject<IWICFormatConverter> formatConverter;
|
||||
checkImage(factory->CreateFormatConverter(&formatConverter.value));
|
||||
checkImage(formatConverter->Initialize(frame.value,GUID_WICPixelFormat32bppPBGRA,WICBitmapDitherTypeNone,
|
||||
nullptr,0,WICBitmapPaletteTypeCustom));
|
||||
raster.pixels.resize(size_t(raster.width)*raster.height);
|
||||
checkImage(formatConverter->CopyPixels(nullptr,raster.width*sizeof(uint32_t),
|
||||
static_cast<UINT>(raster.pixels.size()*sizeof(uint32_t)),reinterpret_cast<BYTE *>(raster.pixels.data())));
|
||||
return raster;
|
||||
}
|
||||
|
||||
ImageRaster decodeWebp(const fs::path &file,size_t size,std::stop_token stop)
|
||||
{
|
||||
std::vector<uint8_t> bytes(size);
|
||||
std::ifstream stream(file,std::ios::binary);
|
||||
if(!stream.read(reinterpret_cast<char *>(bytes.data()),size)) throw std::runtime_error(invalidImage);
|
||||
WebPBitstreamFeatures info{};
|
||||
if(WebPGetFeatures(bytes.data(),bytes.size(),&info)!=VP8_STATUS_OK) throw std::runtime_error(invalidImage);
|
||||
ImageRaster raster{static_cast<unsigned>(info.width),static_cast<unsigned>(info.height)};
|
||||
checkImageDimensions(raster.width,raster.height);
|
||||
checkImageStop(stop);
|
||||
raster.pixels.resize(size_t(raster.width)*raster.height);
|
||||
auto *output=reinterpret_cast<uint8_t *>(raster.pixels.data());
|
||||
const auto outputSize=raster.pixels.size()*sizeof(uint32_t);
|
||||
if(info.has_animation)
|
||||
{
|
||||
WebPAnimDecoderOptions options{};
|
||||
if(!WebPAnimDecoderOptionsInit(&options)) throw std::runtime_error(invalidImage);
|
||||
options.color_mode=MODE_bgrA;
|
||||
const WebPData data{bytes.data(),bytes.size()};
|
||||
const std::unique_ptr<WebPAnimDecoder,decltype(&WebPAnimDecoderDelete)> decoder(
|
||||
WebPAnimDecoderNew(&data,&options),WebPAnimDecoderDelete);
|
||||
uint8_t *frame=nullptr;
|
||||
int timestamp{};
|
||||
if(!decoder || !WebPAnimDecoderGetNext(decoder.get(),&frame,×tamp))
|
||||
throw std::runtime_error(invalidImage);
|
||||
std::memcpy(output,frame,outputSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
WebPDecoderConfig config{};
|
||||
if(!WebPInitDecoderConfig(&config)) throw std::runtime_error(invalidImage);
|
||||
config.output.colorspace=MODE_bgrA;
|
||||
config.output.is_external_memory=1;
|
||||
config.output.u.RGBA={output,static_cast<int>(raster.width*sizeof(uint32_t)),outputSize};
|
||||
const auto status=WebPDecode(bytes.data(),bytes.size(),&config);
|
||||
WebPFreeDecBuffer(&config.output);
|
||||
if(status!=VP8_STATUS_OK) throw std::runtime_error(invalidImage);
|
||||
}
|
||||
return raster;
|
||||
}
|
||||
}
|
||||
|
||||
bool isImagePath(const std::filesystem::path &path)
|
||||
{
|
||||
return imageFormat(path)!=ImageFormat::unknown;
|
||||
}
|
||||
|
||||
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop)
|
||||
{
|
||||
const auto format=imageFormat(name);
|
||||
if(format==ImageFormat::unknown) throw std::runtime_error("This image format is not supported.");
|
||||
checkImageStop(stop);
|
||||
const auto size=std::filesystem::file_size(contents);
|
||||
if(size==0) throw std::runtime_error(invalidImage);
|
||||
if(size>imageSourceLimit) throw std::runtime_error(largeImage);
|
||||
auto image=format==ImageFormat::webp?decodeWebp(contents,static_cast<size_t>(size),stop):
|
||||
decodeNativeImage(contents,format,stop);
|
||||
checkImageStop(stop);
|
||||
return image;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <stop_token>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
struct ImageRaster
|
||||
{
|
||||
unsigned width{}, height{};
|
||||
std::vector<uint32_t> pixels;
|
||||
};
|
||||
|
||||
inline constexpr uint64_t imageSourceLimit=96ULL*1024*1024;
|
||||
bool isImagePath(const std::filesystem::path &path);
|
||||
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop={});
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
#include "files_image_view.h"
|
||||
#include "platform.h"
|
||||
#include <windowsx.h>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace
|
||||
{
|
||||
namespace fs=std::filesystem;
|
||||
constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer";
|
||||
constexpr UINT_PTR imageTimer=1;
|
||||
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize };
|
||||
|
||||
void fillImageView(HDC dc,const RECT &rect,COLORREF color)
|
||||
{
|
||||
SetDCBrushColor(dc,color);
|
||||
FillRect(dc,&rect,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
}
|
||||
|
||||
struct ImageView
|
||||
{
|
||||
HWND window{};
|
||||
bool embedded{};
|
||||
ImageViewStyle style;
|
||||
std::vector<fs::path> images;
|
||||
size_t position{};
|
||||
ImageLoad load;
|
||||
std::function<void(HWND)> onClose;
|
||||
std::array<HWND,6> buttons{};
|
||||
HFONT font{};
|
||||
UINT fontDpi{};
|
||||
HBITMAP bitmap{};
|
||||
unsigned width{},height{};
|
||||
fs::path requested;
|
||||
std::wstring error;
|
||||
std::future<ImageRaster> reading;
|
||||
std::stop_source stop;
|
||||
uint64_t revision{}, started{};
|
||||
double zoom=1, x{}, y{};
|
||||
bool fit=true, dragging{};
|
||||
POINT lastMouse{};
|
||||
|
||||
~ImageView()
|
||||
{
|
||||
stop.request_stop();
|
||||
if(bitmap) DeleteObject(bitmap);
|
||||
if(font) DeleteObject(font);
|
||||
}
|
||||
|
||||
int scale(int pixels) const {return MulDiv(pixels,GetDpiForWindow(window),96);}
|
||||
|
||||
RECT viewport() const
|
||||
{
|
||||
RECT area{};
|
||||
GetClientRect(window,&area);
|
||||
area.top=std::min(area.bottom,static_cast<LONG>(scale(35)));
|
||||
area.bottom=std::max(area.top,area.bottom-scale(27));
|
||||
return area;
|
||||
}
|
||||
|
||||
void layout()
|
||||
{
|
||||
const auto dpi=GetDpiForWindow(window);
|
||||
if(fontDpi!=dpi)
|
||||
{
|
||||
LOGFONTW definition=style.font;
|
||||
definition.lfHeight=-MulDiv(style.tenthsOfPoint,dpi,720);
|
||||
if(const auto next=CreateFontIndirectW(&definition))
|
||||
{
|
||||
if(font) DeleteObject(font);
|
||||
font=next;
|
||||
fontDpi=dpi;
|
||||
}
|
||||
}
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
const int left=scale(4), gap=scale(3), height=scale(27);
|
||||
const int count=embedded?4:6;
|
||||
const int available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
|
||||
const int unit=std::min(scale(80),available/count);
|
||||
int x=left;
|
||||
for(auto button:buttons)
|
||||
{
|
||||
if(!button) continue;
|
||||
SetWindowPos(button,nullptr,x,scale(4),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
x+=unit+gap;
|
||||
}
|
||||
clampOffset();
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void updateButtons() const
|
||||
{
|
||||
if(!embedded)
|
||||
{
|
||||
EnableWindow(buttons[previous-1],position>0);
|
||||
EnableWindow(buttons[following-1],position+1<images.size());
|
||||
}
|
||||
for(unsigned id=zoomOut;id<=actualSize;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
|
||||
for(auto button:buttons)
|
||||
if(button) InvalidateRect(button,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void request(const fs::path &path)
|
||||
{
|
||||
if(requested==path) return;
|
||||
requested=path;
|
||||
++revision;
|
||||
stop.request_stop();
|
||||
error.clear();
|
||||
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
|
||||
width=height=0;
|
||||
fit=true;
|
||||
x=y=0;
|
||||
if(!embedded)
|
||||
{
|
||||
const auto label=L"Viewer — "+path.filename().wstring();
|
||||
SetWindowTextW(window,label.c_str());
|
||||
}
|
||||
updateButtons();
|
||||
SetTimer(window,imageTimer,30,nullptr);
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void show(ImageRaster image)
|
||||
{
|
||||
BITMAPINFO info{};
|
||||
info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
|
||||
info.bmiHeader.biWidth=static_cast<LONG>(image.width);
|
||||
info.bmiHeader.biHeight=-static_cast<LONG>(image.height);
|
||||
info.bmiHeader.biPlanes=1;
|
||||
info.bmiHeader.biBitCount=32;
|
||||
info.bmiHeader.biCompression=BI_RGB;
|
||||
void *bits=nullptr;
|
||||
bitmap=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
|
||||
if(!bitmap || !bits) throw std::runtime_error("Could not display this image.");
|
||||
std::memcpy(bits,image.pixels.data(),image.pixels.size()*sizeof(uint32_t));
|
||||
width=image.width;
|
||||
height=image.height;
|
||||
updateButtons();
|
||||
}
|
||||
|
||||
void poll()
|
||||
{
|
||||
if(reading.valid())
|
||||
{
|
||||
if(reading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
try
|
||||
{
|
||||
auto image=reading.get();
|
||||
if(revision==started) show(std::move(image));
|
||||
}
|
||||
catch(const std::exception &e)
|
||||
{
|
||||
if(revision==started) error=wide(e.what());
|
||||
}
|
||||
if(revision==started)
|
||||
{
|
||||
KillTimer(window,imageTimer);
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if(requested.empty())
|
||||
{
|
||||
KillTimer(window,imageTimer);
|
||||
return;
|
||||
}
|
||||
stop=std::stop_source{};
|
||||
started=revision;
|
||||
std::packaged_task<ImageRaster()> task([path=requested,decoder=load,token=stop.get_token()]
|
||||
{
|
||||
return decoder?decoder(path,token):decodeImage(path,path,token);
|
||||
});
|
||||
reading=task.get_future();
|
||||
try {std::thread(std::move(task)).detach();}
|
||||
catch(const std::exception &e)
|
||||
{
|
||||
reading={};
|
||||
error=wide(e.what());
|
||||
KillTimer(window,imageTimer);
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
double factor() const
|
||||
{
|
||||
if(!fit || !width || !height) return zoom;
|
||||
const auto area=viewport();
|
||||
return std::min({1.0,static_cast<double>(std::max(1L,area.right-area.left))/width,
|
||||
static_cast<double>(std::max(1L,area.bottom-area.top))/height});
|
||||
}
|
||||
|
||||
void clampOffset()
|
||||
{
|
||||
const auto area=viewport();
|
||||
const auto value=factor();
|
||||
const auto limitX=std::max(0.0,(width*value-(area.right-area.left))/2);
|
||||
const auto limitY=std::max(0.0,(height*value-(area.bottom-area.top))/2);
|
||||
x=std::clamp(x,-limitX,limitX);
|
||||
y=std::clamp(y,-limitY,limitY);
|
||||
}
|
||||
|
||||
void changeZoom(double multiplier,const POINT *anchor=nullptr)
|
||||
{
|
||||
if(!bitmap) return;
|
||||
const auto before=factor();
|
||||
fit=false;
|
||||
zoom=std::clamp(before*multiplier,std::min(0.025,before),16.0);
|
||||
if(anchor)
|
||||
{
|
||||
const auto area=viewport();
|
||||
const double dx=anchor->x-(area.left+area.right)/2.0;
|
||||
const double dy=anchor->y-(area.top+area.bottom)/2.0;
|
||||
x=dx+(x-dx)*zoom/before;
|
||||
y=dy+(y-dy)*zoom/before;
|
||||
}
|
||||
clampOffset();
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void action(UINT id)
|
||||
{
|
||||
if(id==previous && position>0) request(images[--position]);
|
||||
else if(id==following && position+1<images.size()) request(images[++position]);
|
||||
else if(id==zoomOut || id==zoomIn) changeZoom(id==zoomIn?1.25:0.8);
|
||||
else if(id==fitImage || id==actualSize)
|
||||
{
|
||||
fit=id==fitImage;
|
||||
zoom=1;
|
||||
x=y=0;
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
void paintButton(const DRAWITEMSTRUCT &item) const
|
||||
{
|
||||
const bool enabled=(item.itemState&ODS_DISABLED)==0;
|
||||
const auto mix=[](BYTE a,BYTE b){return (int(a)+b)/2;};
|
||||
const auto foreground=enabled?style.toolbarText:RGB(
|
||||
mix(GetRValue(style.toolbar),GetRValue(style.toolbarText)),
|
||||
mix(GetGValue(style.toolbar),GetGValue(style.toolbarText)),
|
||||
mix(GetBValue(style.toolbar),GetBValue(style.toolbarText)));
|
||||
fillImageView(item.hDC,item.rcItem,(item.itemState&(ODS_FOCUS|ODS_SELECTED))?style.selection:style.toolbar);
|
||||
SetDCBrushColor(item.hDC,foreground);
|
||||
FrameRect(item.hDC,&item.rcItem,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||||
if(font) SelectObject(item.hDC,font);
|
||||
SetBkMode(item.hDC,TRANSPARENT);
|
||||
SetTextColor(item.hDC,foreground);
|
||||
wchar_t label[24]{};
|
||||
GetWindowTextW(item.hwndItem,label,static_cast<int>(std::size(label)));
|
||||
auto labelArea=item.rcItem;
|
||||
InflateRect(&labelArea,-scale(2),0);
|
||||
DrawTextW(item.hDC,label,-1,&labelArea,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
}
|
||||
|
||||
void paint()
|
||||
{
|
||||
PAINTSTRUCT repaint{};
|
||||
const auto dc=BeginPaint(window,&repaint);
|
||||
RECT all{};
|
||||
GetClientRect(window,&all);
|
||||
const auto area=viewport();
|
||||
fillImageView(dc,all,style.toolbar);
|
||||
fillImageView(dc,area,style.background);
|
||||
if(font) SelectObject(dc,font);
|
||||
SetBkMode(dc,TRANSPARENT);
|
||||
SetTextColor(dc,style.text);
|
||||
if(bitmap)
|
||||
{
|
||||
if(const auto source=CreateCompatibleDC(dc))
|
||||
{
|
||||
const auto old=SelectObject(source,bitmap);
|
||||
const auto saved=SaveDC(dc);
|
||||
IntersectClipRect(dc,area.left,area.top,area.right,area.bottom);
|
||||
const auto displayWidth=std::max(1L,std::lround(width*factor()));
|
||||
const auto displayHeight=std::max(1L,std::lround(height*factor()));
|
||||
const auto left=std::lround((area.left+area.right-displayWidth)/2.0+x);
|
||||
const auto top=std::lround((area.top+area.bottom-displayHeight)/2.0+y);
|
||||
const double horizontal=double(displayWidth)/width, vertical=double(displayHeight)/height;
|
||||
const auto clippedSource=[](LONG edge,LONG start,double ratio,unsigned size,bool end)
|
||||
{
|
||||
const auto pixel=(edge-start)/ratio;
|
||||
return static_cast<int>(std::clamp(end?std::ceil(pixel):std::floor(pixel),0.0,double(size)));
|
||||
};
|
||||
const int startX=clippedSource(area.left,left,horizontal,width,false);
|
||||
const int endX=clippedSource(area.right,left,horizontal,width,true);
|
||||
const int startY=clippedSource(area.top,top,vertical,height,false);
|
||||
const int endY=clippedSource(area.bottom,top,vertical,height,true);
|
||||
const auto destX=left+std::lround(startX*horizontal), destY=top+std::lround(startY*vertical);
|
||||
AlphaBlend(dc,destX,destY,left+std::lround(endX*horizontal)-destX,top+std::lround(endY*vertical)-destY,
|
||||
source,startX,startY,endX-startX,endY-startY,{AC_SRC_OVER,0,255,AC_SRC_ALPHA});
|
||||
if(saved) RestoreDC(dc,saved);
|
||||
SelectObject(source,old);
|
||||
DeleteDC(source);
|
||||
}
|
||||
}
|
||||
else if(!requested.empty())
|
||||
{
|
||||
auto message=area;
|
||||
InflateRect(&message,-scale(8),0);
|
||||
DrawTextW(dc,error.empty()?L"Loading image…":error.c_str(),-1,&message,
|
||||
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
}
|
||||
SetTextColor(dc,style.toolbarText);
|
||||
auto status=requested.filename().wstring();
|
||||
if(bitmap) status+=L" · "+std::to_wstring(width)+L" × "+std::to_wstring(height)+L" · "+
|
||||
std::to_wstring(std::lround(factor()*100))+L"%";
|
||||
RECT footer{scale(8),area.bottom,all.right-scale(8),all.bottom};
|
||||
DrawTextW(dc,status.c_str(),-1,&footer,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||||
EndPaint(window,&repaint);
|
||||
}
|
||||
};
|
||||
|
||||
std::map<HWND,std::shared_ptr<ImageView>> imageViews;
|
||||
|
||||
LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_NCCREATE)
|
||||
{
|
||||
const auto *created=reinterpret_cast<const CREATESTRUCTW *>(lp);
|
||||
const auto state=*static_cast<std::shared_ptr<ImageView> *>(created->lpCreateParams);
|
||||
state->window=window;
|
||||
imageViews.emplace(window,state);
|
||||
}
|
||||
const auto found=imageViews.find(window);
|
||||
if(found==imageViews.end()) return DefWindowProcW(window,message,wp,lp);
|
||||
const auto state=found->second;
|
||||
auto &view=*state;
|
||||
switch(message)
|
||||
{
|
||||
case WM_CREATE:
|
||||
{
|
||||
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%"};
|
||||
for(unsigned id=view.embedded?zoomOut:previous;id<=actualSize;++id)
|
||||
view.buttons[id-1]=CreateWindowW(L"BUTTON",labels[id-1],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
|
||||
view.layout();
|
||||
view.updateButtons();
|
||||
return 0;
|
||||
}
|
||||
case WM_SIZE: view.layout(); return 0;
|
||||
case WM_DPICHANGED:
|
||||
if(!view.embedded)
|
||||
{
|
||||
const auto &bounds=*reinterpret_cast<const RECT *>(lp);
|
||||
SetWindowPos(window,nullptr,bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top,
|
||||
SWP_NOACTIVATE|SWP_NOZORDER);
|
||||
}
|
||||
view.layout();
|
||||
return 0;
|
||||
case WM_DPICHANGED_AFTERPARENT: view.layout(); return 0;
|
||||
case WM_ERASEBKGND: return 1;
|
||||
case WM_PAINT: view.paint(); return 0;
|
||||
case WM_DRAWITEM: view.paintButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp)); return TRUE;
|
||||
case WM_TIMER: if(wp==imageTimer) view.poll(); return 0;
|
||||
case WM_COMMAND:
|
||||
if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);}
|
||||
return 0;
|
||||
case WM_LBUTTONDOWN:
|
||||
{
|
||||
const auto area=view.viewport();
|
||||
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
if(view.bitmap && PtInRect(&area,point))
|
||||
{
|
||||
SetFocus(window);
|
||||
view.dragging=true;
|
||||
view.lastMouse=point;
|
||||
SetCapture(window);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
case WM_MOUSEMOVE:
|
||||
if(view.dragging)
|
||||
{
|
||||
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
view.x+=point.x-view.lastMouse.x;
|
||||
view.y+=point.y-view.lastMouse.y;
|
||||
view.lastMouse=point;
|
||||
view.clampOffset();
|
||||
InvalidateRect(window,nullptr,FALSE);
|
||||
}
|
||||
return 0;
|
||||
case WM_LBUTTONUP:
|
||||
if(view.dragging) ReleaseCapture();
|
||||
return 0;
|
||||
case WM_CAPTURECHANGED: view.dragging=false; return 0;
|
||||
case WM_MOUSEWHEEL:
|
||||
{
|
||||
POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
ScreenToClient(window,&point);
|
||||
view.changeZoom(std::pow(1.25,static_cast<double>(GET_WHEEL_DELTA_WPARAM(wp))/WHEEL_DELTA),&point);
|
||||
return 0;
|
||||
}
|
||||
case WM_KEYDOWN:
|
||||
if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
|
||||
else if(wp==VK_SUBTRACT || wp==VK_OEM_MINUS) view.action(zoomOut);
|
||||
else if(wp=='0') view.action(fitImage);
|
||||
else if(wp=='1') view.action(actualSize);
|
||||
else if(!view.embedded && (wp==VK_LEFT || wp==VK_PRIOR)) view.action(previous);
|
||||
else if(!view.embedded && (wp==VK_RIGHT || wp==VK_NEXT)) view.action(following);
|
||||
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) DestroyWindow(window);
|
||||
else break;
|
||||
return 0;
|
||||
case WM_NCDESTROY:
|
||||
imageViews.erase(found);
|
||||
if(view.onClose) view.onClose(window);
|
||||
break;
|
||||
}
|
||||
return DefWindowProcW(window,message,wp,lp);
|
||||
}
|
||||
}
|
||||
|
||||
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
|
||||
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose)
|
||||
{
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
static const bool registered=[instance]
|
||||
{
|
||||
WNDCLASSW type{};
|
||||
type.hInstance=instance;
|
||||
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
|
||||
type.lpfnWndProc=imageProcedure;
|
||||
type.lpszClassName=imageWindowClass;
|
||||
return RegisterClassW(&type)!=0;
|
||||
}();
|
||||
if(!registered) return nullptr;
|
||||
auto state=std::make_shared<ImageView>();
|
||||
state->embedded=embedded;
|
||||
state->style=style;
|
||||
state->images=std::move(images);
|
||||
state->load=std::move(load);
|
||||
state->onClose=std::move(onClose);
|
||||
const auto position=std::find(state->images.begin(),state->images.end(),initial);
|
||||
if(position!=state->images.end()) state->position=static_cast<size_t>(position-state->images.begin());
|
||||
RECT bounds{};
|
||||
if(!embedded) GetWindowRect(owner,&bounds);
|
||||
const auto window=CreateWindowExW(embedded?0:WS_EX_APPWINDOW,imageWindowClass,embedded?L"Quick View":L"Viewer",
|
||||
embedded?(WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS):(WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN),
|
||||
bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top,
|
||||
embedded?owner:nullptr,nullptr,instance,&state);
|
||||
if(window) state->request(initial);
|
||||
return window;
|
||||
}
|
||||
|
||||
void showImageViewFile(HWND window,const std::filesystem::path &path)
|
||||
{
|
||||
if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include "files_image_decode.h"
|
||||
#include <windows.h>
|
||||
#include <functional>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
using ImageLoad=std::function<ImageRaster(const std::filesystem::path &,std::stop_token)>;
|
||||
|
||||
struct ImageViewStyle
|
||||
{
|
||||
LOGFONTW font{};
|
||||
int tenthsOfPoint{};
|
||||
COLORREF background{}, text{}, toolbar{}, toolbarText{}, selection{};
|
||||
};
|
||||
|
||||
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
|
||||
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={});
|
||||
void showImageViewFile(HWND window,const std::filesystem::path &path);
|
||||
}
|
||||
+1826
-558
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,192 @@
|
||||
constexpr DWORD spaceFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
|
||||
|
||||
bool sameVolumeRoot(const fs::path &directory,const fs::path &root)
|
||||
{
|
||||
if(root.empty()) return false;
|
||||
const auto comparable=[](const fs::path &path) {
|
||||
auto value=std::wstring_view(path.native());
|
||||
if(!value.empty() && (value.back()==L'\\' || value.back()==L'/')) value.remove_suffix(1);
|
||||
return value;
|
||||
};
|
||||
const auto left=comparable(directory),right=comparable(root);
|
||||
return !left.empty() && !right.empty() && CompareStringOrdinal(left.data(),static_cast<int>(left.size()),
|
||||
right.data(),static_cast<int>(right.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
bool isNtfsVolume(const fs::path &root)
|
||||
{
|
||||
wchar_t filesystem[16]{};
|
||||
return GetVolumeInformationW(root.c_str(),nullptr,0,nullptr,nullptr,nullptr,filesystem,
|
||||
static_cast<DWORD>(std::size(filesystem))) && std::wstring_view(filesystem)==L"NTFS";
|
||||
}
|
||||
|
||||
using NtfsDirectoryIds=std::set<uint64_t>;
|
||||
|
||||
bool appendMftDirectories(std::span<const unsigned char> records,NtfsDirectoryIds &directories)
|
||||
{
|
||||
struct UsnRow
|
||||
{
|
||||
DWORD length;
|
||||
WORD major,minor;
|
||||
DWORDLONG id,parent;
|
||||
USN usn;
|
||||
LARGE_INTEGER time;
|
||||
DWORD reason,source,security,attributes;
|
||||
WORD nameLength,nameOffset;
|
||||
};
|
||||
constexpr auto header=offsetof(UsnRow,nameOffset)+sizeof(WORD);
|
||||
static_assert(header==60);
|
||||
while(!records.empty())
|
||||
{
|
||||
if(records.size()<header) return false;
|
||||
UsnRow row{};
|
||||
memcpy(&row,records.data(),header);
|
||||
if(row.major!=2 || row.length<header || row.length>records.size()) return false;
|
||||
if((row.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(row.attributes&FILE_ATTRIBUTE_REPARSE_POINT))
|
||||
directories.insert(row.id);
|
||||
records=records.subspan(row.length);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isExpectedNtfsDirectory(HANDLE handle,const fs::path &directory)
|
||||
{
|
||||
std::wstring name(MAX_PATH,L'\0');
|
||||
const auto getName=[&] {
|
||||
return GetFinalPathNameByHandleW(handle,name.data(),static_cast<DWORD>(name.size()),
|
||||
FILE_NAME_OPENED|VOLUME_NAME_DOS);
|
||||
};
|
||||
auto length=getName();
|
||||
if(length>=name.size())
|
||||
{
|
||||
name.resize(length+1);
|
||||
length=getName();
|
||||
}
|
||||
if(!length || length>=name.size()) return false;
|
||||
name.resize(length);
|
||||
constexpr std::wstring_view devicePrefix=LR"(\\?\)";
|
||||
const auto &expected=directory.native();
|
||||
std::wstring_view actual(name);
|
||||
if(actual.starts_with(devicePrefix) && !std::wstring_view(expected).starts_with(devicePrefix))
|
||||
actual.remove_prefix(devicePrefix.size());
|
||||
return CompareStringOrdinal(actual.data(),static_cast<int>(actual.size()),expected.data(),
|
||||
static_cast<int>(expected.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
|
||||
bool readMftDirectoryIds(const fs::path &root,NtfsDirectoryIds &directories,std::stop_token stop)
|
||||
{
|
||||
wchar_t name[64]{};
|
||||
if(!GetVolumeNameForVolumeMountPointW(root.c_str(),name,static_cast<DWORD>(std::size(name)))) return false;
|
||||
const auto length=wcslen(name);
|
||||
if(!length || name[length-1]!=L'\\') return false;
|
||||
name[length-1]=L'\0';
|
||||
const Handle volume{CreateFileW(name,GENERIC_READ,spaceFileShare,nullptr,OPEN_EXISTING,0,nullptr)};
|
||||
if(volume.value==INVALID_HANDLE_VALUE) return false;
|
||||
struct Enumeration {DWORDLONG first; USN low,high;};
|
||||
static_assert(sizeof(Enumeration)==24);
|
||||
Enumeration request{0,0,std::numeric_limits<USN>::max()};
|
||||
auto buffer=std::vector<unsigned char>(512*1024);
|
||||
while(!stop.stop_requested())
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(!DeviceIoControl(volume.value,FSCTL_ENUM_USN_DATA,&request,sizeof(request),buffer.data(),
|
||||
static_cast<DWORD>(buffer.size()),&bytes,nullptr))
|
||||
return GetLastError()==ERROR_HANDLE_EOF && !directories.empty();
|
||||
DWORDLONG next{};
|
||||
if(bytes<sizeof(next) || bytes>buffer.size()) return false;
|
||||
memcpy(&next,buffer.data(),sizeof(next));
|
||||
if(next<=request.first) return false;
|
||||
if(!appendMftDirectories(std::span<const unsigned char>(buffer).subspan(sizeof(next),bytes-sizeof(next)),
|
||||
directories)) return false;
|
||||
request.first=next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
class NtfsSpaceWalk
|
||||
{
|
||||
public:
|
||||
NtfsSpaceWalk(const fs::path &root,const fs::path &mount,std::stop_token stop) : root(root),
|
||||
volumeHint{CreateFileW(root.c_str(),FILE_READ_ATTRIBUTES,spaceFileShare,nullptr,OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS,nullptr)}
|
||||
{
|
||||
if(volumeHint.value!=INVALID_HANDLE_VALUE)
|
||||
{
|
||||
try {indexed=readMftDirectoryIds(mount,mft,stop);}
|
||||
catch(const std::exception &) {}
|
||||
}
|
||||
if(!indexed) mft.clear();
|
||||
}
|
||||
|
||||
bool usedMft() const { return usedIndex; }
|
||||
|
||||
bool list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop,FilesConnection &fallback)
|
||||
{
|
||||
const bool atRoot=directory==root;
|
||||
const auto known=byPath.extract(directory);
|
||||
constexpr DWORD openFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
|
||||
Handle handle{INVALID_HANDLE_VALUE};
|
||||
if(known && mft.contains(known.mapped()))
|
||||
{
|
||||
FILE_ID_DESCRIPTOR id{};
|
||||
id.dwSize=sizeof(id);
|
||||
id.Type=FileIdType;
|
||||
id.FileId.QuadPart=static_cast<LONGLONG>(known.mapped());
|
||||
handle.value=OpenFileById(volumeHint.value,&id,FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES,
|
||||
spaceFileShare,nullptr,openFlags);
|
||||
if(handle.value!=INVALID_HANDLE_VALUE)
|
||||
{
|
||||
if(isExpectedNtfsDirectory(handle.value,directory)) usedIndex=true;
|
||||
else
|
||||
{
|
||||
CloseHandle(handle.value);
|
||||
handle.value=INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(handle.value==INVALID_HANDLE_VALUE)
|
||||
handle.value=CreateFileW(directory.c_str(),FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES,
|
||||
spaceFileShare,nullptr,OPEN_EXISTING,atRoot?FILE_FLAG_BACKUP_SEMANTICS:openFlags,nullptr);
|
||||
if(handle.value==INVALID_HANDLE_VALUE) return false;
|
||||
|
||||
FILE_ATTRIBUTE_TAG_INFO tag{};
|
||||
if(!GetFileInformationByHandleEx(handle.value,FileAttributeTagInfo,&tag,sizeof(tag)) ||
|
||||
!(tag.FileAttributes&FILE_ATTRIBUTE_DIRECTORY) ||
|
||||
(!atRoot && (tag.FileAttributes&FILE_ATTRIBUTE_REPARSE_POINT))) return false;
|
||||
|
||||
bool emitted=false;
|
||||
const auto status=ks::files::visitDirectoryRecords(handle.value,[&](const FILE_ID_BOTH_DIR_INFO &row,
|
||||
std::wstring_view name) -> DWORD
|
||||
{
|
||||
if(stop.stop_requested()) return ERROR_CANCELLED;
|
||||
const auto path=directory/name;
|
||||
const auto attributes=row.FileAttributes;
|
||||
const auto directoryEntry=(attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
|
||||
if(directoryEntry && !(attributes&FILE_ATTRIBUTE_REPARSE_POINT) && indexed)
|
||||
{
|
||||
const auto id=static_cast<uint64_t>(row.FileId.QuadPart);
|
||||
if(mft.contains(id)) byPath.try_emplace(path,id);
|
||||
}
|
||||
FileInfo entry{attributes,static_cast<uint64_t>(row.EndOfFile.QuadPart),
|
||||
static_cast<uint64_t>(row.LastWriteTime.QuadPart)};
|
||||
if(!(attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT|
|
||||
FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE)) && row.AllocationSize.QuadPart>=0)
|
||||
entry.allocated=static_cast<uint64_t>(row.AllocationSize.QuadPart);
|
||||
emitted=true;
|
||||
return visit(path,entry)?ERROR_SUCCESS:ERROR_CANCELLED;
|
||||
});
|
||||
if(!emitted && (status==ERROR_NOT_SUPPORTED || status==ERROR_INVALID_PARAMETER || status==ERROR_INVALID_FUNCTION))
|
||||
{
|
||||
if(atRoot) return !stop.stop_requested() && listFiles(fallback,directory,visit);
|
||||
return listMeasuredDirectory(fallback,directory,visit,stop);
|
||||
}
|
||||
return status==ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
private:
|
||||
fs::path root;
|
||||
Handle volumeHint;
|
||||
NtfsDirectoryIds mft;
|
||||
std::map<fs::path,uint64_t> byPath;
|
||||
bool indexed{}, usedIndex{};
|
||||
};
|
||||
+29
-10
@@ -11,7 +11,7 @@ constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Pop
|
||||
L"Menu selection",L"Command bar",L"File cursor"};
|
||||
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
|
||||
constexpr const wchar_t *panelSectionNames[]{L"Panel layout",L"Wide panel columns",L"Status line columns"};
|
||||
constexpr int panelLayoutControls[]{273,274};
|
||||
constexpr int panelLayoutControls[]{506,273,507,274};
|
||||
constexpr int wideColumnControls[]{275,276,201,202,204};
|
||||
constexpr int statusColumnControls[]{277,203,205,206,207,208};
|
||||
constexpr int colorOptionControls[]{279,280};
|
||||
@@ -66,7 +66,7 @@ struct PanelProperty
|
||||
DWORD defaultValue;
|
||||
};
|
||||
constexpr PanelProperty panelProperties[]{
|
||||
{PanelLayout,273,L"Left panel: Wide",defaultWide},{PanelLayout,274,L"Right panel: Wide",defaultWide},
|
||||
{PanelLayout,273,L"Left panel mode",defaultWide?1u:0u},{PanelLayout,274,L"Right panel mode",defaultWide?1u:0u},
|
||||
{WideColumns,201,L"Size column width",defaultSizeWidth},
|
||||
{WideColumns,202,L"Align file extensions",defaultAlignExtensions},
|
||||
{WideColumns,204,L"Align folder extensions",defaultAlignFolders},
|
||||
@@ -76,9 +76,24 @@ constexpr PanelProperty panelProperties[]{
|
||||
void resetPanelProperty(HWND dialog,const PanelProperty &property)
|
||||
{
|
||||
if(property.control==201) SetDlgItemInt(dialog,property.control,property.defaultValue,FALSE);
|
||||
else if(property.control==273 || property.control==274)
|
||||
SendDlgItemMessageW(dialog,property.control,CB_SETCURSEL,property.defaultValue,0);
|
||||
else CheckDlgButton(dialog,property.control,property.defaultValue);
|
||||
}
|
||||
|
||||
PanelMode panelModeOption(HWND dialog,int index)
|
||||
{
|
||||
const auto selection=SendDlgItemMessageW(dialog,273+index,CB_GETCURSEL,0,0);
|
||||
return selection>=0 && static_cast<size_t>(selection)<std::size(panelModeNames)?
|
||||
static_cast<PanelMode>(selection):PanelMode::brief;
|
||||
}
|
||||
|
||||
void showPanelModeOptions(HWND dialog)
|
||||
{
|
||||
for(int index=0;index<2;++index)
|
||||
SendDlgItemMessageW(dialog,273+index,CB_SETCURSEL,static_cast<WPARAM>(panels[index].mode),0);
|
||||
}
|
||||
|
||||
struct OptionsBaseline
|
||||
{
|
||||
LOGFONTW font=displayFont;
|
||||
@@ -92,7 +107,7 @@ struct OptionsBaseline
|
||||
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
|
||||
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
|
||||
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
|
||||
std::array<bool,2> wide{panels[0].wide,panels[1].wide};
|
||||
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
|
||||
ks::files::TextSettings text=ks::files::loadTextPreferences();
|
||||
ComparisonAppearance comparison=readComparisonAppearance();
|
||||
WORD compareShortcut=comparisonShortcut;
|
||||
@@ -164,7 +179,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
for(int i=0;i<4;++i) if(checked(205+i)) fields|=1u<<i;
|
||||
const auto &base=draft.baseline;
|
||||
const bool dirty=!valid || draft.markdownError || width!=base.width ||
|
||||
checked(273)!=base.wide[0] || checked(274)!=base.wide[1] ||
|
||||
panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] ||
|
||||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
|
||||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
|
||||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
|
||||
@@ -636,6 +651,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
|
||||
SendDlgItemMessageW(dialog,201,EM_SETLIMITTEXT,2,0);
|
||||
for(const auto id:{273,274})
|
||||
for(const auto mode:panelModeNames)
|
||||
SendDlgItemMessageW(dialog,id,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(mode));
|
||||
SendDlgItemMessageW(dialog,markdownWidth,EM_SETLIMITTEXT,6,0);
|
||||
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
|
||||
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
|
||||
@@ -661,8 +679,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,202,alignExtensions);
|
||||
CheckDlgButton(dialog,203,showDetails);
|
||||
CheckDlgButton(dialog,204,alignFolders);
|
||||
CheckDlgButton(dialog,273,panels[0].wide);
|
||||
CheckDlgButton(dialog,274,panels[1].wide);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
|
||||
@@ -1051,8 +1068,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
savePreference(L"FontPoints",fontPoints);
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",REG_BINARY,&displayFont,sizeof(displayFont));
|
||||
}
|
||||
saveChanged(L"LeftWide",checked(273),base.wide[0]);
|
||||
saveChanged(L"RightWide",checked(274),base.wide[1]);
|
||||
for(int index=0;index<2;++index)
|
||||
{
|
||||
const auto mode=panelModeOption(dialog,index);
|
||||
if(mode!=base.modes[index]) savePanelMode(index,mode);
|
||||
}
|
||||
loadFilesPreferences(owner);
|
||||
notifyFilesPreferences(owner);
|
||||
const auto dialogOwner=GetWindow(dialog,GW_OWNER);
|
||||
@@ -1072,8 +1092,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,202,alignExtensions);
|
||||
CheckDlgButton(dialog,203,showDetails);
|
||||
CheckDlgButton(dialog,204,alignFolders);
|
||||
CheckDlgButton(dialog,273,panels[0].wide);
|
||||
CheckDlgButton(dialog,274,panels[1].wide);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
constexpr int panelColumnFirst=510,panelColumnAuto=516,panelColumnFooter=517,panelColumnReset=518;
|
||||
|
||||
void setColumnControls(HWND dialog,DWORD columns,bool automatic)
|
||||
{
|
||||
for(size_t i=1;i<panelColumnCount;++i)
|
||||
CheckDlgButton(dialog,panelColumnFirst+static_cast<int>(i)-1,columns&(1u<<i)?BST_CHECKED:BST_UNCHECKED);
|
||||
CheckDlgButton(dialog,panelColumnAuto,automatic?BST_CHECKED:BST_UNCHECKED);
|
||||
}
|
||||
|
||||
struct PanelColumnPrompt
|
||||
{
|
||||
ColumnSettings draft;
|
||||
PanelMode mode;
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK panelColumnsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
const auto &prompt=*reinterpret_cast<const PanelColumnPrompt *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,panelColumnFirst);
|
||||
for(int id=panelColumnFirst;id<=panelColumnAuto;++id)
|
||||
installFarCheckbox(GetDlgItem(dialog,id),FarCheckboxSurface::gray);
|
||||
layoutDialogButtons(dialog,panelColumnFooter,{IDOK,panelColumnReset,IDCANCEL});
|
||||
setColumnControls(dialog,prompt.draft.visibility,prompt.draft.automatic);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND)
|
||||
{
|
||||
const auto command=LOWORD(wp);
|
||||
auto *prompt=reinterpret_cast<PanelColumnPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!prompt) return FALSE;
|
||||
if(command==panelColumnReset)
|
||||
{
|
||||
setColumnControls(dialog,defaultVisibleColumns(prompt->mode),true);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==IDOK)
|
||||
{
|
||||
auto &draft=prompt->draft;
|
||||
draft.visibility=0;
|
||||
for(size_t i=1;i<panelColumnCount;++i)
|
||||
if(IsDlgButtonChecked(dialog,panelColumnFirst+static_cast<int>(i)-1)==BST_CHECKED)
|
||||
draft.visibility|=1u<<i;
|
||||
draft.automatic=IsDlgButtonChecked(dialog,panelColumnAuto)==BST_CHECKED;
|
||||
draft.customized=draft.visibility!=defaultVisibleColumns(prompt->mode);
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
return paintCopyDialog(dialog,message,wp,lp,L" Panel columns ",false,{panelColumnFooter});
|
||||
}
|
||||
|
||||
void editPanelColumns(HWND owner,Panel &panel)
|
||||
{
|
||||
if(!hasPanelColumns(panel) || !panelViewAvailable(panel)) return;
|
||||
auto &settings=panel.columns[static_cast<size_t>(panel.mode)];
|
||||
auto draft=settings;
|
||||
if(!draft.customized) draft.visibility=defaultVisibleColumns(panel.mode);
|
||||
PanelColumnPrompt prompt{draft,panel.mode};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(119),owner,
|
||||
panelColumnsDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
|
||||
if(prompt.draft.visibility==draft.visibility && prompt.draft.automatic==draft.automatic) return;
|
||||
settings=prompt.draft;
|
||||
savePanelColumns(static_cast<int>(&panel-panels),panel.mode);
|
||||
notifyFilesPreferences(owner);
|
||||
if((draft.visibility^settings.visibility)&extendedColumnMask) refreshPanelColumnData(panel);
|
||||
InvalidateRect(panel.heading,nullptr,FALSE);
|
||||
InvalidateRect(panel.list,nullptr,TRUE);
|
||||
InvalidateRect(owner,nullptr,FALSE);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
std::wstring_view directoryRowName(const fs::path &path)
|
||||
{
|
||||
const auto name=std::wstring_view(path.native());
|
||||
const auto slash=name.find_last_of(L"/\\");
|
||||
return slash==name.npos?name:name.substr(slash+1);
|
||||
}
|
||||
|
||||
std::wstring_view directoryRowExtension(std::wstring_view name)
|
||||
{
|
||||
const auto dot=name.find_last_of(L'.');
|
||||
return dot==name.npos || dot==0?std::wstring_view{}:name.substr(dot+1);
|
||||
}
|
||||
|
||||
int compareDirectoryText(std::wstring_view left,std::wstring_view right)
|
||||
{
|
||||
if(left.empty() || right.empty()) return static_cast<int>(!left.empty())-static_cast<int>(!right.empty());
|
||||
return CompareStringOrdinal(left.data(),static_cast<int>(left.size()),right.data(),static_cast<int>(right.size()),TRUE)
|
||||
- CSTR_EQUAL;
|
||||
}
|
||||
|
||||
void orderDirectoryRows(Panel::ScanResult &result,const PanelView &view)
|
||||
{
|
||||
auto &rows=result.ordered;
|
||||
if(view.showHidden && view.mask.empty()) rows.reserve(result.folders.size()+result.files.size());
|
||||
const auto append=[&](std::vector<fs::path> &paths,bool folder)
|
||||
{
|
||||
for(auto &path:paths)
|
||||
{
|
||||
const auto &metadata=result.metadata.at(path);
|
||||
const uint64_t value=view.sort==PanelSort::modified?metadata.modified:
|
||||
view.sort==PanelSort::size?metadata.size:0;
|
||||
if(visibleToPanelView(view,path,metadata)) rows.push_back({std::move(path),value,folder});
|
||||
}
|
||||
};
|
||||
append(result.folders,true);
|
||||
append(result.files,false);
|
||||
std::sort(rows.begin(),rows.end(),[&](const DirectoryRow &left,const DirectoryRow &right)
|
||||
{
|
||||
if(view.foldersFirst && left.folder!=right.folder) return left.folder;
|
||||
const auto leftName=directoryRowName(left.path), rightName=directoryRowName(right.path);
|
||||
int order=0;
|
||||
if(view.sort==PanelSort::extension)
|
||||
order=compareDirectoryText(directoryRowExtension(leftName),directoryRowExtension(rightName));
|
||||
else if(left.value!=right.value) order=left.value<right.value?-1:1;
|
||||
if(!order) order=compareDirectoryText(leftName,rightName);
|
||||
if(!order) order=leftName.compare(rightName);
|
||||
return view.descending?order>0:order<0;
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
class PanelRowsUpdate
|
||||
{
|
||||
public:
|
||||
PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)),
|
||||
profiles(transferProfileList(panel))
|
||||
{
|
||||
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
|
||||
panel.rows.clear();
|
||||
panel.sizes.clear();
|
||||
panel.dimmed.clear();
|
||||
panel.marked.clear();
|
||||
panel.fileExtensionLength=panel.folderExtensionLength=0;
|
||||
panel.longestColumn.fill(0);
|
||||
panel.rows.reserve(count);
|
||||
panel.sizes.reserve(count);
|
||||
panel.dimmed.reserve(count);
|
||||
panel.marked.reserve(count);
|
||||
SendMessageW(panel.list,LB_RESETCONTENT,0,0);
|
||||
SendMessageW(panel.list,LB_INITSTORAGE,count,0);
|
||||
}
|
||||
|
||||
~PanelRowsUpdate() {finish();}
|
||||
|
||||
bool add(const fs::path &path,const std::wstring &label,bool folder,bool marked,bool up=false)
|
||||
{
|
||||
if(SendMessageW(panel.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))<0) return false;
|
||||
panel.rows.push_back(path);
|
||||
if(!up)
|
||||
{
|
||||
const auto extension=path.extension().native();
|
||||
auto &longest=folder?panel.folderExtensionLength:panel.fileExtensionLength;
|
||||
if(extension.size()>1) longest=std::max(longest,extension.size()-1);
|
||||
}
|
||||
panel.marked.push_back(!up && marked);
|
||||
const auto found=panel.metadata.find(path);
|
||||
const auto entry=up || profiles || found==panel.metadata.end()?FolderEntryMetadata{}:found->second;
|
||||
panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0);
|
||||
panel.sizes.push_back(profiles?L"":folder?(up?L"Up":L"Folder"):std::to_wstring(entry.size));
|
||||
if(!up && !profiles)
|
||||
{
|
||||
auto &longest=panel.longestColumn;
|
||||
longest[sizeColumn]=std::max(longest[sizeColumn],panel.sizes.back().size());
|
||||
if(const auto extra=panel.columnMetadata.find(path);extra!=panel.columnMetadata.end())
|
||||
{
|
||||
longest[ownerColumn]=std::max(longest[ownerColumn],extra->second.owner.size());
|
||||
if(extra->second.links)
|
||||
longest[linkColumn]=std::max(longest[linkColumn],std::to_wstring(*extra->second.links).size());
|
||||
if(extra->second.allocated)
|
||||
longest[allocationColumn]=std::max(longest[allocationColumn],std::to_wstring(*extra->second.allocated).size());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void finish()
|
||||
{
|
||||
if(visible)
|
||||
{
|
||||
SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
|
||||
visible=false;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
Panel &panel;
|
||||
bool visible,profiles;
|
||||
};
|
||||
|
||||
bool treePanelActive(const Panel &panel)
|
||||
{
|
||||
return panel.view.tree && !panel.findOrigin && !panel.tree.root.empty();
|
||||
}
|
||||
|
||||
void markPanelRow(Panel &panel,size_t row,bool mark)
|
||||
{
|
||||
if(row>=panel.rows.size() || panel.sizes[row]==L"Up") return;
|
||||
panel.marked[row]=mark;
|
||||
if(!treePanelActive(panel)) return;
|
||||
const auto &path=panel.rows[row];
|
||||
if(mark) panel.tree.marks.insert(path);
|
||||
else panel.tree.marks.erase(path);
|
||||
}
|
||||
|
||||
const FolderEntryMetadata *treePanelEntry(const Panel &panel,const fs::path &path)
|
||||
{
|
||||
const auto branch=panel.tree.branches.find(path.parent_path());
|
||||
if(branch==panel.tree.branches.end()) return nullptr;
|
||||
const auto item=branch->second.metadata.find(path);
|
||||
return item==branch->second.metadata.end()?nullptr:&item->second;
|
||||
}
|
||||
|
||||
bool matchesFileMask(std::wstring_view name,std::wstring_view mask);
|
||||
|
||||
bool visibleToPanelView(const PanelView &view,const fs::path &path,const FolderEntryMetadata &metadata)
|
||||
{
|
||||
if(path==view.revealedFile) return true;
|
||||
return (view.showHidden || !(metadata.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) &&
|
||||
((metadata.attributes&FILE_ATTRIBUTE_DIRECTORY) || view.mask.empty() ||
|
||||
matchesFileMask(path.filename().native(),view.mask));
|
||||
}
|
||||
|
||||
template<class Visitor>
|
||||
void visitPanelMarks(const Panel &panel,const Visitor &visit)
|
||||
{
|
||||
if(treePanelActive(panel))
|
||||
{
|
||||
for(const auto &path:panel.tree.marks)
|
||||
{
|
||||
const auto entry=treePanelEntry(panel,path);
|
||||
if(!entry || !visibleToPanelView(panel.view,path,*entry)) continue;
|
||||
auto directory=path.parent_path();
|
||||
while(directory!=panel.tree.root)
|
||||
{
|
||||
const auto parent=treePanelEntry(panel,directory);
|
||||
const auto ancestor=directory.parent_path();
|
||||
if(!parent || ancestor==directory || !visibleToPanelView(panel.view,directory,*parent)) break;
|
||||
directory=ancestor;
|
||||
}
|
||||
if(directory==panel.tree.root) visit(path,*entry);
|
||||
}
|
||||
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;
|
||||
if(const auto item=panel.metadata.find(panel.rows[i]);item!=panel.metadata.end())
|
||||
visit(item->first,item->second);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
void stopTreeBranches(Panel &panel)
|
||||
{
|
||||
for(auto &[path,branch]:panel.tree.branches) branch.stop.request_stop();
|
||||
panel.tree={};
|
||||
}
|
||||
|
||||
bool canExpandTreeEntry(const FolderEntryMetadata &entry)
|
||||
{
|
||||
return (entry.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT);
|
||||
}
|
||||
|
||||
void startPendingTreeScans(Panel &panel)
|
||||
{
|
||||
if(!treePanelActive(panel)) return;
|
||||
auto running=std::count_if(panel.tree.branches.begin(),panel.tree.branches.end(),
|
||||
[](const auto &item){return item.second.scan.valid();});
|
||||
for(auto &[path,branch]:panel.tree.branches)
|
||||
{
|
||||
if(running>=2) break;
|
||||
if(!branch.expanded || !branch.needsScan || branch.scan.valid() || path==panel.tree.root) continue;
|
||||
branch.needsScan=false;
|
||||
const auto entry=treePanelEntry(panel,path);
|
||||
if(!entry || !canExpandTreeEntry(*entry)) continue;
|
||||
branch.stop=std::stop_source{};
|
||||
Panel::ScanRequest request{.directory=path,.peer=panel.peer,.ftp=panel.ftp};
|
||||
try
|
||||
{
|
||||
branch.scan=scanDirectoryInBackground(GetParent(panel.list),std::move(request),panel.view,
|
||||
effectivePanelColumns(panel)&extendedColumnMask,std::make_shared<std::atomic_size_t>(0),branch.stop.get_token());
|
||||
++running;
|
||||
}
|
||||
catch(const std::exception &) {branch.failed=true;}
|
||||
}
|
||||
}
|
||||
|
||||
void refreshTreeBranches(Panel &panel)
|
||||
{
|
||||
if(!treePanelActive(panel)) return;
|
||||
for(auto &[path,branch]:panel.tree.branches)
|
||||
if(branch.expanded && path!=panel.tree.root) branch.needsScan=true;
|
||||
startPendingTreeScans(panel);
|
||||
}
|
||||
|
||||
void replaceTreeRoot(Panel &panel,Panel::ScanResult &scan,bool sameDirectory,const std::set<fs::path> &marks)
|
||||
{
|
||||
auto directory=folderPathWithoutSeparator(panel.directory);
|
||||
if(!sameDirectory || panel.tree.root!=directory) stopTreeBranches(panel);
|
||||
panel.tree.root=std::move(directory);
|
||||
auto &root=panel.tree.branches[panel.tree.root];
|
||||
root.expanded=root.loaded=true;
|
||||
root.ordered=std::move(scan.ordered);
|
||||
root.metadata=std::move(scan.metadata);
|
||||
root.columnMetadata=std::move(scan.columnMetadata);
|
||||
panel.tree.marks.insert(marks.begin(),marks.end());
|
||||
if(scan.error!=ERROR_CANCELLED)
|
||||
std::erase_if(panel.tree.marks,[&](const auto &path) {
|
||||
return path.parent_path()==panel.tree.root && !root.metadata.contains(path);
|
||||
});
|
||||
refreshTreeBranches(panel);
|
||||
}
|
||||
|
||||
void pruneTreeMarks(Panel &panel,const std::set<fs::path> &removed)
|
||||
{
|
||||
if(!treePanelActive(panel) || removed.empty()) return;
|
||||
std::erase_if(panel.tree.marks,[&](auto path) {
|
||||
for(;path!=panel.tree.root && path!=path.parent_path();path=path.parent_path())
|
||||
if(removed.contains(path)) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
std::wstring treeRowPrefix(const Panel &panel,const fs::path &path,bool folder)
|
||||
{
|
||||
const auto depth=panel.tree.depths.find(path);
|
||||
if(depth==panel.tree.depths.end()) return {};
|
||||
std::wstring prefix(2*std::min<size_t>(depth->second,40),L' ');
|
||||
if(!folder) return prefix+L" ";
|
||||
const auto branch=panel.tree.branches.find(path);
|
||||
if(branch!=panel.tree.branches.end())
|
||||
{
|
||||
if(branch->second.scan.valid() || branch->second.needsScan) return prefix+L"… ";
|
||||
if(branch->second.expanded) return prefix+(branch->second.failed?L"! ":L"▾ ");
|
||||
}
|
||||
if(const auto entry=treePanelEntry(panel,path);entry && canExpandTreeEntry(*entry)) return prefix+L"▸ ";
|
||||
return prefix+L" ";
|
||||
}
|
||||
|
||||
void appendTreeRows(Panel &panel,PanelRowsUpdate &rows)
|
||||
{
|
||||
panel.tree.depths.clear();
|
||||
panel.metadata.clear();
|
||||
panel.columnMetadata.clear();
|
||||
struct BranchRows {const Panel::TreeBranch *branch; size_t next;};
|
||||
std::vector<BranchRows> stack{{&panel.tree.branches.at(panel.tree.root),0}};
|
||||
while(!stack.empty())
|
||||
{
|
||||
auto ¤t=stack.back();
|
||||
if(current.next==current.branch->ordered.size())
|
||||
{
|
||||
stack.pop_back();
|
||||
continue;
|
||||
}
|
||||
const auto &entry=current.branch->ordered[current.next++];
|
||||
const auto &path=entry.path;
|
||||
panel.tree.depths.emplace(path,stack.size()-1);
|
||||
const auto metadata=current.branch->metadata.find(path);
|
||||
if(metadata==current.branch->metadata.end() || !visibleToPanelView(panel.view,path,metadata->second)) continue;
|
||||
panel.metadata.emplace(path,metadata->second);
|
||||
if(const auto extra=current.branch->columnMetadata.find(path);extra!=current.branch->columnMetadata.end())
|
||||
panel.columnMetadata.emplace(path,extra->second);
|
||||
const auto label=treeRowPrefix(panel,path,entry.folder)+path.filename().native();
|
||||
rows.add(path,label,entry.folder,panel.tree.marks.contains(path));
|
||||
const auto child=panel.tree.branches.find(path);
|
||||
if(entry.folder && child!=panel.tree.branches.end() && child->second.expanded && child->second.loaded)
|
||||
stack.push_back({&child->second,0});
|
||||
}
|
||||
}
|
||||
|
||||
void redrawTreeRows(Panel &panel)
|
||||
{
|
||||
if(!treePanelActive(panel)) return;
|
||||
const auto current=SendMessageW(panel.list,LB_GETCURSEL,0,0);
|
||||
const auto top=SendMessageW(panel.list,LB_GETTOPINDEX,0,0);
|
||||
auto selected=current>=0 && static_cast<size_t>(current)<panel.rows.size()?panel.rows[current]:fs::path{};
|
||||
const auto parent=panelParentPath(panel.directory,!panel.peer && !panel.ftp);
|
||||
PanelRowsUpdate rows(panel,panel.rows.size());
|
||||
if(!parent.empty()) rows.add(parent,L"..",true,false,true);
|
||||
appendTreeRows(panel,rows);
|
||||
auto position=std::find(panel.rows.begin(),panel.rows.end(),selected);
|
||||
while(position==panel.rows.end() && !selected.empty() && selected!=panel.tree.root)
|
||||
{
|
||||
const auto next=selected.parent_path();
|
||||
if(next==selected) break;
|
||||
selected=next;
|
||||
position=std::find(panel.rows.begin(),panel.rows.end(),selected);
|
||||
}
|
||||
if(!panel.rows.empty())
|
||||
{
|
||||
SendMessageW(panel.list,LB_SETTOPINDEX,top,0);
|
||||
SendMessageW(panel.list,LB_SETCURSEL,position==panel.rows.end()?
|
||||
std::clamp<LRESULT>(current,0,panel.rows.size()-1):position-panel.rows.begin(),0);
|
||||
}
|
||||
rows.finish();
|
||||
InvalidateRect(panel.list,nullptr,FALSE);
|
||||
InvalidateRect(panel.heading,nullptr,FALSE);
|
||||
updateSelectionSummary(panel);
|
||||
refreshQuickView(panel);
|
||||
}
|
||||
|
||||
void collectTreeBranches()
|
||||
{
|
||||
for(auto &panel:panels)
|
||||
{
|
||||
if(!treePanelActive(panel)) continue;
|
||||
bool updated=false;
|
||||
for(auto &[path,branch]:panel.tree.branches)
|
||||
{
|
||||
if(!branch.scan.valid() || branch.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready) continue;
|
||||
updated=true;
|
||||
try
|
||||
{
|
||||
auto scan=branch.scan.get();
|
||||
const auto error=scan->error;
|
||||
branch.failed=!scan->opened || !scan->failure.empty() ||
|
||||
(error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND);
|
||||
if(scan->opened && scan->failure.empty())
|
||||
{
|
||||
branch.loaded=true;
|
||||
branch.ordered=std::move(scan->ordered);
|
||||
branch.metadata=std::move(scan->metadata);
|
||||
branch.columnMetadata=std::move(scan->columnMetadata);
|
||||
if(!branch.failed) std::erase_if(panel.tree.marks,[&](const auto &marked) {
|
||||
return marked.parent_path()==path && !branch.metadata.contains(marked);
|
||||
});
|
||||
}
|
||||
}
|
||||
catch(const std::exception &) {branch.failed=true;}
|
||||
if(branch.failed && &panel==&panels[active] && branch.expanded)
|
||||
setStatus(L"Could not read tree folder: "+path.native());
|
||||
}
|
||||
if(updated)
|
||||
{
|
||||
startPendingTreeScans(panel);
|
||||
redrawTreeRows(panel);
|
||||
queueAutomaticPanelSizes(panel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool toggleTreeRow(Panel &panel,size_t row,std::optional<bool> expanded={})
|
||||
{
|
||||
if(!treePanelActive(panel) || row>=panel.rows.size() || panel.sizes[row]!=L"Folder") return false;
|
||||
const auto path=panel.rows[row];
|
||||
const auto entry=treePanelEntry(panel,path);
|
||||
if(!entry || !canExpandTreeEntry(*entry)) return false;
|
||||
auto &branch=panel.tree.branches[path];
|
||||
const auto next=expanded.value_or(!branch.expanded);
|
||||
if(next==branch.expanded) return false;
|
||||
branch.expanded=next;
|
||||
if(next)
|
||||
{
|
||||
branch.needsScan=true;
|
||||
startPendingTreeScans(panel);
|
||||
}
|
||||
else branch.needsScan=false;
|
||||
redrawTreeRows(panel);
|
||||
if(&panel==&panels[active])
|
||||
{
|
||||
if(next && branch.scan.valid()) setStatus(L"Reading tree folder: "+path.native());
|
||||
else showFileDetails(panel);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool moveTreeCursor(Panel &panel,bool forward)
|
||||
{
|
||||
if(!treePanelActive(panel)) return false;
|
||||
const auto position=SendMessageW(panel.list,LB_GETCURSEL,0,0);
|
||||
if(position<0 || static_cast<size_t>(position)>=panel.rows.size() || panel.sizes[position]==L"Up") return false;
|
||||
if(toggleTreeRow(panel,static_cast<size_t>(position),forward)) return true;
|
||||
const auto &path=panel.rows[position];
|
||||
if(forward)
|
||||
{
|
||||
if(static_cast<size_t>(position+1)<panel.rows.size() && panel.rows[position+1].parent_path()==path)
|
||||
SendMessageW(panel.list,LB_SETCURSEL,position+1,0);
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto parent=std::find(panel.rows.begin(),panel.rows.end(),path.parent_path());
|
||||
if(parent!=panel.rows.end()) SendMessageW(panel.list,LB_SETCURSEL,parent-panel.rows.begin(),0);
|
||||
}
|
||||
invalidatePanelCursorChange(panel.list,position);
|
||||
return true;
|
||||
}
|
||||
+164
-74
@@ -1,22 +1,28 @@
|
||||
|
||||
bool localNavigationAvailable(const Panel &panel)
|
||||
bool pathNavigationAvailable(const Panel &panel)
|
||||
{
|
||||
return !panel.peer && !panel.ftp && !panel.findOrigin && !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)
|
||||
@@ -331,8 +402,9 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
|
||||
ReleaseCapture();
|
||||
const int index=GetDlgCtrlID(window)-142;
|
||||
if(index<0 || index>=2) return 0;
|
||||
panelClipboardContext=true;
|
||||
auto &panel=panels[index];
|
||||
if(!localNavigationAvailable(panel))
|
||||
if(!pathNavigationAvailable(panel))
|
||||
{
|
||||
selectPanelEdge(panel,true);
|
||||
return 0;
|
||||
@@ -341,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;
|
||||
@@ -360,12 +442,20 @@ 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 || !localNavigationAvailable(panels[active]) ||
|
||||
if(!commandLineAvailable(owner) || terminalVisible ||
|
||||
(message.hwnd!=terminalInput && message.hwnd!=panels[active].list) ||
|
||||
((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return false;
|
||||
auto &panel=panels[active];
|
||||
if(panel.archive)
|
||||
{
|
||||
if(message.message!=WM_SYSKEYDOWN || message.wParam!=VK_UP ||
|
||||
!(message.lParam&(1LL<<29)) || (GetKeyState(VK_CONTROL)&0x8000)) return false;
|
||||
if(!(message.lParam&(1LL<<30))) parentArchive(panel);
|
||||
return true;
|
||||
}
|
||||
if(!pathNavigationAvailable(panel)) return false;
|
||||
if(message.message==WM_KEYDOWN && message.wParam=='L' &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000))
|
||||
{
|
||||
@@ -375,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;
|
||||
}
|
||||
@@ -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 &) {}
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
constexpr long sftpTimeoutMs=10000;
|
||||
|
||||
void initializeSsh()
|
||||
{
|
||||
static const auto initialized=libssh2_init(0);
|
||||
if(initialized) throw std::runtime_error("Could not initialize the SSH client.");
|
||||
}
|
||||
|
||||
void connectSshSocket(ks::lan::WinSocket &connection,const TransferProfile &profile)
|
||||
{
|
||||
ADDRINFOW query{};
|
||||
query.ai_socktype=SOCK_STREAM;
|
||||
query.ai_protocol=IPPROTO_TCP;
|
||||
ADDRINFOW *addresses{};
|
||||
const auto service=std::to_wstring(profile.port);
|
||||
if(const auto error=GetAddrInfoW(profile.host.c_str(),service.c_str(),&query,&addresses))
|
||||
throw std::system_error(error,std::system_category());
|
||||
const std::unique_ptr<ADDRINFOW,decltype(&FreeAddrInfoW)> resolved(addresses,FreeAddrInfoW);
|
||||
DWORD lastError=WSAEHOSTUNREACH;
|
||||
const auto deadline=GetTickCount64()+sftpTimeoutMs;
|
||||
for(auto *address=addresses;address;address=address->ai_next)
|
||||
{
|
||||
ks::lan::WinSocket socket{::socket(address->ai_family,address->ai_socktype,address->ai_protocol)};
|
||||
if(socket.value==INVALID_SOCKET) {lastError=WSAGetLastError();continue;}
|
||||
u_long nonblocking=1;
|
||||
if(ioctlsocket(socket.value,FIONBIO,&nonblocking)==SOCKET_ERROR)
|
||||
{lastError=WSAGetLastError();continue;}
|
||||
if(::connect(socket.value,address->ai_addr,static_cast<int>(address->ai_addrlen))==SOCKET_ERROR)
|
||||
{
|
||||
lastError=WSAGetLastError();
|
||||
if(lastError!=WSAEWOULDBLOCK) continue;
|
||||
const auto now=GetTickCount64();
|
||||
if(now>=deadline) {lastError=WSAETIMEDOUT;break;}
|
||||
const auto left=deadline-now;
|
||||
timeval timeout{static_cast<long>(left/1000),static_cast<long>(left%1000)*1000};
|
||||
fd_set writable{},failed{};
|
||||
FD_SET(socket.value,&writable);
|
||||
FD_SET(socket.value,&failed);
|
||||
const auto ready=select(0,nullptr,&writable,&failed,&timeout);
|
||||
if(ready==SOCKET_ERROR) {lastError=WSAGetLastError();continue;}
|
||||
if(!ready) {lastError=WSAETIMEDOUT;break;}
|
||||
int error{},length=sizeof(error);
|
||||
if(getsockopt(socket.value,SOL_SOCKET,SO_ERROR,reinterpret_cast<char*>(&error),&length)==SOCKET_ERROR)
|
||||
{lastError=WSAGetLastError();continue;}
|
||||
if(error) {lastError=error;continue;}
|
||||
}
|
||||
nonblocking=0;
|
||||
if(ioctlsocket(socket.value,FIONBIO,&nonblocking)==SOCKET_ERROR)
|
||||
{lastError=WSAGetLastError();continue;}
|
||||
connection.value=std::exchange(socket.value,INVALID_SOCKET);
|
||||
return;
|
||||
}
|
||||
throw std::system_error(lastError,std::system_category());
|
||||
}
|
||||
|
||||
using SshChannel=std::unique_ptr<LIBSSH2_CHANNEL,decltype(&libssh2_channel_free)>;
|
||||
|
||||
class SshConnection
|
||||
{
|
||||
struct Tunnel
|
||||
{
|
||||
SshChannel channel;
|
||||
LIBSSH2_SESSION *parent;
|
||||
|
||||
struct Nonblocking
|
||||
{
|
||||
LIBSSH2_SESSION *parent;
|
||||
int previous;
|
||||
explicit Nonblocking(LIBSSH2_SESSION *session):
|
||||
parent(session),previous(libssh2_session_get_blocking(parent))
|
||||
{
|
||||
libssh2_session_set_blocking(parent,0);
|
||||
}
|
||||
~Nonblocking(){libssh2_session_set_blocking(parent,previous);}
|
||||
};
|
||||
};
|
||||
|
||||
struct Hop
|
||||
{
|
||||
std::unique_ptr<Tunnel> tunnel;
|
||||
std::unique_ptr<LIBSSH2_SESSION,decltype(&libssh2_session_free)> session{nullptr,libssh2_session_free};
|
||||
};
|
||||
|
||||
ks::lan::Network network_;
|
||||
ks::lan::WinSocket socket_;
|
||||
std::vector<Hop> hops_;
|
||||
std::string fingerprint_;
|
||||
|
||||
static LIBSSH2_SEND_FUNC(sendThroughJump)
|
||||
{
|
||||
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
|
||||
// Channel writes drain incoming packets first. A nested transport must
|
||||
// report when that drain would block so it can still send its own data.
|
||||
const Tunnel::Nonblocking nonblocking(tunnel.parent);
|
||||
const auto result=libssh2_channel_write(tunnel.channel.get(),static_cast<const char*>(buffer),length);
|
||||
return result>=0?result:result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
|
||||
}
|
||||
|
||||
static LIBSSH2_RECV_FUNC(receiveThroughJump)
|
||||
{
|
||||
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
|
||||
const Tunnel::Nonblocking nonblocking(tunnel.parent);
|
||||
auto *channel=tunnel.channel.get();
|
||||
const auto result=libssh2_channel_read(channel,static_cast<char*>(buffer),length);
|
||||
if(result>0) return result;
|
||||
if(result==0 && libssh2_channel_eof(channel)) return 0;
|
||||
return result==0 || result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
|
||||
}
|
||||
|
||||
[[noreturn]] void sshError(const char *operation) const
|
||||
{
|
||||
char *message{};
|
||||
int length{};
|
||||
libssh2_session_last_error(session(),&message,&length,0);
|
||||
throw std::runtime_error(std::string(operation)+(message && length>0?": "+std::string(message,length):""));
|
||||
}
|
||||
|
||||
void authenticate(const TransferProfile &profile)
|
||||
{
|
||||
auto wideSecret=transferPassword(profile);
|
||||
struct EraseWide
|
||||
{
|
||||
std::wstring &text;
|
||||
~EraseWide(){if(!text.empty()) SecureZeroMemory(text.data(),text.size()*sizeof(wchar_t));}
|
||||
} eraseWide{wideSecret};
|
||||
auto secret=ks::utf8(wideSecret);
|
||||
struct EraseText
|
||||
{
|
||||
std::string &text;
|
||||
~EraseText(){if(!text.empty()) SecureZeroMemory(text.data(),text.size());}
|
||||
} eraseSecret{secret};
|
||||
const auto user=ks::utf8(profile.user);
|
||||
int result{};
|
||||
if(profile.privateKey.empty())
|
||||
result=libssh2_userauth_password_ex(session(),user.c_str(),static_cast<unsigned>(user.size()),
|
||||
secret.c_str(),static_cast<unsigned>(secret.size()),nullptr);
|
||||
else
|
||||
{
|
||||
auto key=ks::readFile(profile.privateKey,1024*1024);
|
||||
struct EraseKey
|
||||
{
|
||||
ks::Bytes &bytes;
|
||||
~EraseKey(){if(!bytes.empty()) SecureZeroMemory(bytes.data(),bytes.size());}
|
||||
} eraseKey{key};
|
||||
if(key.empty()) throw std::runtime_error("Could not read the SFTP private key file.");
|
||||
auto publicPath=profile.privateKey;
|
||||
publicPath+=L".pub";
|
||||
ks::Bytes publicKey;
|
||||
std::error_code error;
|
||||
if(fs::exists(publicPath,error)) publicKey=ks::readFile(publicPath,64*1024);
|
||||
result=libssh2_userauth_publickey_frommemory(session(),user.c_str(),user.size(),
|
||||
publicKey.empty()?nullptr:reinterpret_cast<const char*>(publicKey.data()),publicKey.size(),
|
||||
reinterpret_cast<const char*>(key.data()),key.size(),secret.c_str());
|
||||
}
|
||||
if(result) sshError(profile.privateKey.empty()?"SFTP password authentication failed":
|
||||
"SFTP key authentication failed (use RSA PEM without a passphrase, or ECDSA OpenSSH with its .pub file)");
|
||||
}
|
||||
|
||||
void connectHop(const TransferProfile &profile,bool probeOnly)
|
||||
{
|
||||
if(!probeOnly && profile.hostFingerprint.empty())
|
||||
throw std::runtime_error("The SFTP host key is untrusted. Edit the profile and use Test connection to verify it.");
|
||||
Hop hop;
|
||||
if(hops_.empty()) connectSshSocket(socket_,profile);
|
||||
else
|
||||
{
|
||||
const auto host=ks::utf8(profile.host);
|
||||
SshChannel channel(libssh2_channel_direct_tcpip(session(),host.c_str(),profile.port),libssh2_channel_free);
|
||||
if(!channel) sshError("Could not open an SSH jump tunnel");
|
||||
hop.tunnel=std::make_unique<Tunnel>(Tunnel{std::move(channel),session()});
|
||||
}
|
||||
hop.session.reset(libssh2_session_init_ex(nullptr,nullptr,nullptr,hop.tunnel.get()));
|
||||
if(!hop.session) throw std::runtime_error("Could not create an SSH session.");
|
||||
hops_.push_back(std::move(hop));
|
||||
if(hops_.back().tunnel)
|
||||
{
|
||||
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_SEND,
|
||||
reinterpret_cast<libssh2_cb_generic*>(sendThroughJump));
|
||||
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_RECV,
|
||||
reinterpret_cast<libssh2_cb_generic*>(receiveThroughJump));
|
||||
}
|
||||
libssh2_session_set_timeout(session(),sftpTimeoutMs);
|
||||
libssh2_session_set_read_timeout(session(),sftpTimeoutMs/1000);
|
||||
if(libssh2_session_method_pref(session(),LIBSSH2_METHOD_HOSTKEY,
|
||||
"ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256") ||
|
||||
libssh2_session_handshake(session(),socket_.value))
|
||||
sshError("Could not negotiate an SSH connection");
|
||||
const auto digest=reinterpret_cast<const BYTE*>(libssh2_hostkey_hash(session(),LIBSSH2_HOSTKEY_HASH_SHA256));
|
||||
if(!digest) throw std::runtime_error("The server did not provide a verifiable SSH host key.");
|
||||
char fingerprint[64]{};
|
||||
DWORD length=static_cast<DWORD>(std::size(fingerprint));
|
||||
checkFileOperation(CryptBinaryToStringA(digest,32,CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF,fingerprint,&length));
|
||||
auto encoded=std::string(fingerprint);
|
||||
while(encoded.ends_with('=')) encoded.pop_back();
|
||||
fingerprint_="SHA256:"+encoded;
|
||||
if(probeOnly) return;
|
||||
if(!ks::lan::equal(fingerprint_,profile.hostFingerprint))
|
||||
throw std::runtime_error("The SFTP host key changed. Connection blocked before authentication. Received "+fingerprint_+".");
|
||||
authenticate(profile);
|
||||
}
|
||||
|
||||
void close() noexcept
|
||||
{
|
||||
if(socket_.value!=INVALID_SOCKET) shutdown(socket_.value,SD_BOTH);
|
||||
while(!hops_.empty())
|
||||
{
|
||||
auto &hop=hops_.back();
|
||||
libssh2_session_set_blocking(hop.session.get(),1);
|
||||
hop.session.reset();
|
||||
hops_.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
explicit SshConnection(const TransferProfile &destination,bool probeOnly=false)
|
||||
{
|
||||
initializeSsh();
|
||||
const auto profiles=sshProfiles.load();
|
||||
static const std::vector<TransferProfile> empty;
|
||||
const auto route=sshRoute(destination,profiles?*profiles:empty);
|
||||
try
|
||||
{
|
||||
for(size_t i=0;i<route.size();++i)
|
||||
{
|
||||
const auto &profile=route[i];
|
||||
try {connectHop(profile,probeOnly && i+1==route.size());}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(route.size()==1) throw;
|
||||
throw std::runtime_error(ks::utf8(profile.name)+": "+error.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(...) {close();throw;}
|
||||
}
|
||||
|
||||
~SshConnection(){close();}
|
||||
LIBSSH2_SESSION *session() const {return hops_.back().session.get();}
|
||||
const std::string &fingerprint() const {return fingerprint_;}
|
||||
|
||||
void nonblocking()
|
||||
{
|
||||
for(const auto &hop:hops_) libssh2_session_set_blocking(hop.session.get(),0);
|
||||
}
|
||||
|
||||
[[noreturn]] void operationError(const char *operation) const {sshError(operation);}
|
||||
};
|
||||
|
||||
struct SftpFile
|
||||
{
|
||||
LIBSSH2_SFTP_HANDLE *handle{};
|
||||
explicit SftpFile(LIBSSH2_SFTP_HANDLE *value):handle(value){}
|
||||
SftpFile(const SftpFile &)=delete;
|
||||
SftpFile(SftpFile &&other) noexcept:handle(std::exchange(other.handle,nullptr)){}
|
||||
~SftpFile(){if(handle) libssh2_sftp_close_handle(handle);}
|
||||
};
|
||||
|
||||
using SftpSubsystem=std::unique_ptr<LIBSSH2_SFTP,decltype(&libssh2_sftp_shutdown)>;
|
||||
|
||||
fs::path sftpInitialDirectory(LIBSSH2_SFTP *sftp)
|
||||
{
|
||||
std::array<char,32768> path{};
|
||||
const auto length=libssh2_sftp_realpath(sftp,".",path.data(),path.size());
|
||||
if(length<=0) return {};
|
||||
auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal();
|
||||
if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path.");
|
||||
return value;
|
||||
}
|
||||
|
||||
class SftpSession
|
||||
{
|
||||
SshConnection connection_;
|
||||
SftpSubsystem sftp_{nullptr,libssh2_sftp_shutdown};
|
||||
|
||||
static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));}
|
||||
|
||||
public:
|
||||
explicit SftpSession(const TransferProfile &profile):connection_(profile)
|
||||
{
|
||||
sftp_.reset(libssh2_sftp_init(connection_.session()));
|
||||
if(!sftp_) connection_.operationError("Could not start the SFTP subsystem");
|
||||
}
|
||||
|
||||
[[noreturn]] void operationError(const char *operation) const
|
||||
{
|
||||
if(libssh2_session_last_errno(connection_.session())==LIBSSH2_ERROR_SFTP_PROTOCOL)
|
||||
{
|
||||
const auto status=libssh2_sftp_last_error(sftp_.get());
|
||||
if(status==LIBSSH2_FX_PERMISSION_DENIED)
|
||||
throw 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);
|
||||
}
|
||||
connection_.operationError(operation);
|
||||
}
|
||||
|
||||
fs::path initialDirectory() const
|
||||
{
|
||||
auto path=sftpInitialDirectory(sftp_.get());
|
||||
if(path.empty()) operationError("Could not resolve the initial SFTP folder");
|
||||
return path;
|
||||
}
|
||||
|
||||
DWORD list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop={}) const
|
||||
{
|
||||
if(stop.stop_requested()) return ERROR_CANCELLED;
|
||||
const auto path=encode(directory);
|
||||
const SftpFile folder(libssh2_sftp_open_ex(sftp_.get(),path.c_str(),static_cast<unsigned>(path.size()),
|
||||
0,0,LIBSSH2_SFTP_OPENDIR));
|
||||
if(!folder.handle) operationError("Could not open the SFTP folder");
|
||||
std::array<char,32768> name{};
|
||||
while(!stop.stop_requested())
|
||||
{
|
||||
LIBSSH2_SFTP_ATTRIBUTES attrs{};
|
||||
const auto length=libssh2_sftp_readdir_ex(folder.handle,name.data(),name.size(),nullptr,0,&attrs);
|
||||
if(length==0) return ERROR_NO_MORE_FILES;
|
||||
if(length<0) operationError("Could not read the SFTP folder");
|
||||
const auto child=ks::wide(std::string(name.data(),length));
|
||||
if(child.empty() || child==L"." || child==L".." || child.find_first_of(L"/\\:\r\n")!=child.npos ||
|
||||
child.find(L'\0')!=child.npos) continue;
|
||||
DWORD attributes=FILE_ATTRIBUTE_NORMAL;
|
||||
if((attrs.flags&LIBSSH2_SFTP_ATTR_PERMISSIONS)!=0)
|
||||
{
|
||||
if(LIBSSH2_SFTP_S_ISDIR(attrs.permissions)) attributes=FILE_ATTRIBUTE_DIRECTORY;
|
||||
else if(!LIBSSH2_SFTP_S_ISREG(attrs.permissions)) attributes=FILE_ATTRIBUTE_REPARSE_POINT;
|
||||
if(!(attrs.permissions&0222)) attributes|=FILE_ATTRIBUTE_READONLY;
|
||||
}
|
||||
const auto 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");
|
||||
}
|
||||
};
|
||||
@@ -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,{});
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
constexpr int spacePath=488,spaceTree=489,spaceStatus=490,spaceFooter=491;
|
||||
constexpr int spaceStop=492,spaceRescan=493,spaceView=494;
|
||||
constexpr int spaceCapacity=495,spaceScope=496,spaceMapButton=497,spaceMap=498;
|
||||
constexpr int spaceSunburstButton=499,spaceSunburstList=500,spaceSunburstLabel=501;
|
||||
constexpr UINT_PTR spaceUpdateTimer=1;
|
||||
constexpr UINT_PTR spaceVolumeTimer=2;
|
||||
constexpr size_t spaceBatchSize=256;
|
||||
constexpr std::initializer_list<int> spaceFooterButtons{spaceStop,spaceRescan,spaceView,IDOK,IDCANCEL};
|
||||
|
||||
struct SpaceVolume
|
||||
{
|
||||
fs::path root;
|
||||
std::optional<std::pair<uint64_t,uint64_t>> capacity;
|
||||
};
|
||||
|
||||
std::future<SpaceVolume> readSpaceVolume(const fs::path &folder)
|
||||
{
|
||||
std::packaged_task<SpaceVolume()> task([folder] {
|
||||
SpaceVolume result;
|
||||
std::wstring root(32768,L'\0');
|
||||
if(GetVolumePathNameW(folder.c_str(),root.data(),static_cast<DWORD>(root.size())))
|
||||
{
|
||||
root.resize(wcslen(root.c_str()));
|
||||
result.root=fs::path(std::move(root));
|
||||
}
|
||||
ULARGE_INTEGER total{},free{};
|
||||
if(GetDiskFreeSpaceExW(result.root.empty()?folder.c_str():result.root.c_str(),&free,&total,nullptr))
|
||||
result.capacity=std::pair{total.QuadPart,free.QuadPart};
|
||||
return result;
|
||||
});
|
||||
auto result=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
return result;
|
||||
}
|
||||
|
||||
struct SpaceAllocation
|
||||
{
|
||||
FolderSize known;
|
||||
size_t measured{}, unavailable{};
|
||||
|
||||
void add(std::optional<uint64_t> size)
|
||||
{
|
||||
if(size)
|
||||
{
|
||||
++measured;
|
||||
known.add(*size);
|
||||
}
|
||||
else ++unavailable;
|
||||
}
|
||||
};
|
||||
|
||||
struct SpaceTile
|
||||
{
|
||||
RECT box;
|
||||
size_t node;
|
||||
};
|
||||
|
||||
#include "files_ntfs_space.inl"
|
||||
|
||||
struct SpaceSector
|
||||
{
|
||||
size_t node;
|
||||
unsigned ring;
|
||||
double start,end;
|
||||
};
|
||||
|
||||
enum class SpaceDisplay { tree, treemap, sunburst };
|
||||
|
||||
struct SpaceEvent
|
||||
{
|
||||
fs::path path;
|
||||
std::optional<FileInfo> item;
|
||||
std::optional<uint64_t> allocated;
|
||||
};
|
||||
|
||||
struct SpaceRun
|
||||
{
|
||||
std::stop_source stop;
|
||||
std::mutex mutex;
|
||||
std::deque<std::vector<SpaceEvent>> pending;
|
||||
FolderSize result;
|
||||
bool finished{}, stopped{}, indexed{};
|
||||
};
|
||||
|
||||
std::shared_ptr<SpaceRun> startSpaceRun(const fs::path &root,const fs::path &mount)
|
||||
{
|
||||
auto run=std::make_shared<SpaceRun>();
|
||||
std::thread([run,root,mount] {
|
||||
std::vector<SpaceEvent> batch;
|
||||
auto lastUpdate=GetTickCount64();
|
||||
const auto publish=[&] {
|
||||
if(batch.empty()) return;
|
||||
std::lock_guard lock(run->mutex);
|
||||
run->pending.push_back(std::move(batch));
|
||||
batch.clear();
|
||||
lastUpdate=GetTickCount64();
|
||||
};
|
||||
FolderSize total;
|
||||
const auto stop=run->stop.get_token();
|
||||
try
|
||||
{
|
||||
FilesConnection host(nullptr);
|
||||
const bool volume=!mount.empty();
|
||||
std::optional<NtfsSpaceWalk> ntfs;
|
||||
if(volume && isNtfsVolume(mount)) ntfs.emplace(root,mount,stop);
|
||||
bool indexReported=false;
|
||||
total=measureFolder(root,stop,[&](const fs::path &directory,const FileVisitor &visit) {
|
||||
if(ntfs)
|
||||
{
|
||||
const auto result=ntfs->list(directory,visit,stop,host);
|
||||
if(!indexReported && ntfs->usedMft())
|
||||
{
|
||||
std::lock_guard lock(run->mutex);
|
||||
run->indexed=indexReported=true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if(volume && directory==root) return !stop.stop_requested() && listFiles(host,directory,visit);
|
||||
return listMeasuredDirectory(host,directory,visit,stop);
|
||||
},[&](const fs::path &path,const FileInfo *info) {
|
||||
const auto allocate=info && !(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT));
|
||||
const auto allocation=allocate?(info->allocated?info->allocated:allocatedFileBytes(path,info->attributes)):
|
||||
std::nullopt;
|
||||
batch.push_back({path,info?std::optional<FileInfo>(*info):std::nullopt,allocation});
|
||||
if(batch.size()>=spaceBatchSize || GetTickCount64()-lastUpdate>=80) publish();
|
||||
});
|
||||
publish();
|
||||
}
|
||||
catch(const std::exception &) {total.partial=true;}
|
||||
std::lock_guard lock(run->mutex);
|
||||
run->result=total;
|
||||
run->stopped=stop.stop_requested();
|
||||
run->finished=true;
|
||||
}).detach();
|
||||
return run;
|
||||
}
|
||||
|
||||
struct SpaceNode
|
||||
{
|
||||
fs::path path;
|
||||
FolderSize size;
|
||||
SpaceAllocation allocated;
|
||||
size_t parent{};
|
||||
std::vector<size_t> children;
|
||||
HTREEITEM item{};
|
||||
bool folder{}, link{}, expanded{};
|
||||
};
|
||||
|
||||
struct SpaceAnalyzer
|
||||
{
|
||||
fs::path folder, root, selected;
|
||||
SpaceVolume volume;
|
||||
std::future<SpaceVolume> pendingVolume;
|
||||
bool selectedFolder{}, volumeScope{};
|
||||
SpaceDisplay display{SpaceDisplay::tree};
|
||||
std::shared_ptr<SpaceRun> run;
|
||||
std::vector<SpaceNode> nodes;
|
||||
std::map<fs::path,size_t> directories;
|
||||
size_t files{}, mapFolder{}, selectedTile{};
|
||||
std::vector<SpaceTile> tiles;
|
||||
std::vector<SpaceSector> sectors;
|
||||
ULONGLONG lastMapUpdate{};
|
||||
bool scanning{}, hasResults{};
|
||||
};
|
||||
|
||||
void layoutSpaceAnalyzer(HWND dialog)
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(dialog,&bounds);
|
||||
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
|
||||
const auto inset=frame.content();
|
||||
const auto width=std::max(1L,bounds.right-2*inset);
|
||||
const auto place=[&](int id,int top,int height) {
|
||||
SetWindowPos(GetDlgItem(dialog,id),nullptr,inset,top,width,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
};
|
||||
auto top=dialogListInset(frame,textHeight);
|
||||
place(spacePath,top,textHeight);
|
||||
top+=textHeight;
|
||||
place(spaceCapacity,top,textHeight);
|
||||
top+=textHeight+dialogRowGap();
|
||||
const auto buttonHeight=textHeight;
|
||||
auto x=inset;
|
||||
for(const auto id:{spaceScope,spaceMapButton,spaceSunburstButton})
|
||||
{
|
||||
const auto button=GetDlgItem(dialog,id);
|
||||
const auto width=std::max(12L*cellWidth,farDialogButtonWidth(button));
|
||||
SetWindowPos(button,nullptr,x,top,width,buttonHeight,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
x+=width+dialogColumnGap();
|
||||
}
|
||||
top+=buttonHeight+dialogRowGap();
|
||||
place(spaceTree,top,9*textHeight);
|
||||
const auto state=reinterpret_cast<const SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(state && state->display==SpaceDisplay::sunburst)
|
||||
{
|
||||
const auto graphWidth=width*3/5;
|
||||
const auto gap=dialogColumnGap();
|
||||
SetWindowPos(GetDlgItem(dialog,spaceSunburstLabel),nullptr,inset+graphWidth,top-textHeight-dialogRowGap(),
|
||||
width-graphWidth,textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SetWindowPos(GetDlgItem(dialog,spaceMap),nullptr,inset,top,graphWidth-gap,9*textHeight,
|
||||
SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
SetWindowPos(GetDlgItem(dialog,spaceSunburstList),nullptr,inset+graphWidth,top,width-graphWidth,
|
||||
9*textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
}
|
||||
else place(spaceMap,top,9*textHeight);
|
||||
top+=9*textHeight+dialogRowGap();
|
||||
place(spaceStatus,top,textHeight);
|
||||
place(spaceFooter,top+textHeight+dialogRowGap(),1);
|
||||
layoutDialogButtons(dialog,spaceFooter,spaceFooterButtons);
|
||||
}
|
||||
|
||||
HTREEITEM insertSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
|
||||
{
|
||||
auto &node=state.nodes[index];
|
||||
TVINSERTSTRUCTW insert{};
|
||||
insert.hParent=index?state.nodes[node.parent].item:TVI_ROOT;
|
||||
insert.hInsertAfter=TVI_LAST;
|
||||
insert.item.mask=TVIF_TEXT|TVIF_PARAM|TVIF_CHILDREN;
|
||||
insert.item.pszText=LPSTR_TEXTCALLBACKW;
|
||||
insert.item.lParam=static_cast<LPARAM>(index);
|
||||
insert.item.cChildren=node.folder && !node.link?I_CHILDRENCALLBACK:0;
|
||||
node.item=TreeView_InsertItem(tree,&insert);
|
||||
return node.item;
|
||||
}
|
||||
|
||||
void expandSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
|
||||
{
|
||||
auto &node=state.nodes[index];
|
||||
if(node.expanded) return;
|
||||
node.expanded=true;
|
||||
for(auto child:node.children) insertSpaceNode(tree,state,child);
|
||||
}
|
||||
|
||||
void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event)
|
||||
{
|
||||
if(!event.item)
|
||||
{
|
||||
const auto directory=state.directories.find(event.path);
|
||||
if(directory==state.directories.end()) return;
|
||||
for(auto i=directory->second;;i=state.nodes[i].parent)
|
||||
{
|
||||
state.nodes[i].size.partial=true;
|
||||
if(!i) break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const auto parent=state.directories.find(event.path.parent_path());
|
||||
if(parent==state.directories.end()) return;
|
||||
const auto index=state.nodes.size();
|
||||
const bool folder=(event.item->attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
|
||||
const bool link=(event.item->attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0;
|
||||
const auto bytes=folder || link?0:event.item->size;
|
||||
if(folder) state.directories.emplace(event.path,index);
|
||||
else ++state.files;
|
||||
state.nodes.push_back({.path=std::move(event.path),.size={bytes,false},.parent=parent->second,
|
||||
.folder=folder,.link=link});
|
||||
if(!folder && !link) state.nodes[index].allocated.add(event.allocated);
|
||||
auto &parentNode=state.nodes[parent->second];
|
||||
parentNode.children.push_back(index);
|
||||
if(parentNode.item && parentNode.expanded)
|
||||
{
|
||||
insertSpaceNode(tree,state,index);
|
||||
if(parentNode.children.size()==1) TreeView_Expand(tree,parentNode.item,TVE_EXPAND);
|
||||
}
|
||||
for(auto i=parent->second;;i=state.nodes[i].parent)
|
||||
{
|
||||
state.nodes[i].size.add(bytes);
|
||||
if(!folder && !link) state.nodes[i].allocated.add(event.allocated);
|
||||
if(!i) break;
|
||||
}
|
||||
}
|
||||
|
||||
std::wstring spaceLogicalSize(const SpaceNode &node)
|
||||
{
|
||||
return formatSize(node.size.bytes)+(node.size.partial?L"+ logical":L" logical");
|
||||
}
|
||||
|
||||
std::wstring spaceAllocatedSize(const SpaceNode &node)
|
||||
{
|
||||
const auto &allocation=node.allocated;
|
||||
if(!allocation.measured && allocation.unavailable) return L"— on disk";
|
||||
auto result=formatSize(allocation.known.bytes);
|
||||
if(allocation.unavailable || allocation.known.partial || node.size.partial) result+=L"+";
|
||||
return result+L" on disk";
|
||||
}
|
||||
|
||||
std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index)
|
||||
{
|
||||
const auto &node=state.nodes[index];
|
||||
const auto &parent=state.nodes[node.parent];
|
||||
auto name=node.path.filename().native();
|
||||
if(name.empty()) name=node.path.native();
|
||||
if(name.size()>196)
|
||||
{
|
||||
name.resize(196);
|
||||
if(name.back()>=0xD800 && name.back()<=0xDBFF) name.pop_back();
|
||||
name+=L"…";
|
||||
}
|
||||
if(!state.hasResults) return name;
|
||||
if(node.link) return name+L" [link]";
|
||||
auto result=name+L" — "+spaceLogicalSize(node)+L" · "+spaceAllocatedSize(node);
|
||||
if(parent.size.bytes)
|
||||
{
|
||||
wchar_t share[48]{};
|
||||
swprintf_s(share,L" (%.1f%%)",100.0*static_cast<double>(node.size.bytes)/static_cast<double>(parent.size.bytes));
|
||||
result+=share;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<size_t> selectedSpaceNode(HWND tree,const SpaceAnalyzer &state)
|
||||
{
|
||||
TVITEMW item{};
|
||||
item.mask=TVIF_PARAM;
|
||||
item.hItem=TreeView_GetSelection(tree);
|
||||
if(item.hItem && TreeView_GetItem(tree,&item) && static_cast<size_t>(item.lParam)<state.nodes.size())
|
||||
return static_cast<size_t>(item.lParam);
|
||||
return {};
|
||||
}
|
||||
|
||||
#include "files_space_map.inl"
|
||||
|
||||
void updateSpaceTree(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
const auto tree=GetDlgItem(dialog,spaceTree);
|
||||
const auto budget=GetTickCount64()+15;
|
||||
bool finished=false,stopped=false,changed=false,indexed=false;
|
||||
do
|
||||
{
|
||||
std::vector<SpaceEvent> batch;
|
||||
{
|
||||
std::lock_guard lock(state.run->mutex);
|
||||
indexed=state.run->indexed;
|
||||
if(!state.run->pending.empty())
|
||||
{
|
||||
batch=std::move(state.run->pending.front());
|
||||
state.run->pending.pop_front();
|
||||
}
|
||||
else if(state.run->finished)
|
||||
{
|
||||
finished=true;
|
||||
stopped=state.run->stopped;
|
||||
state.nodes[0].size.partial|=state.run->result.partial;
|
||||
}
|
||||
}
|
||||
if(batch.empty()) break;
|
||||
if(!changed) SendMessageW(tree,WM_SETREDRAW,FALSE,0);
|
||||
changed=true;
|
||||
for(auto &event:batch) addSpaceEvent(tree,state,std::move(event));
|
||||
} while(GetTickCount64()<budget);
|
||||
if(finished) state.scanning=false;
|
||||
if(changed) SendMessageW(tree,WM_SETREDRAW,TRUE,0);
|
||||
if(state.display!=SpaceDisplay::tree && (finished || (changed && GetTickCount64()-state.lastMapUpdate>=200)))
|
||||
refreshSpaceChart(GetDlgItem(dialog,spaceMap),state);
|
||||
if(changed || finished) InvalidateRect(tree,nullptr,FALSE);
|
||||
|
||||
const bool stopping=state.run->stop.stop_requested();
|
||||
auto status=finished?(stopped?L"Stopped · partial":state.nodes[0].size.partial?L"Partial results":L"Complete"):
|
||||
stopping?L"Stopping…":L"Scanning…";
|
||||
const auto &allocation=state.nodes[0].allocated;
|
||||
auto label=std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files";
|
||||
if(indexed) label+=L" · NTFS index";
|
||||
if(allocation.unavailable || allocation.known.partial) label+=L" · on-disk sizes partial";
|
||||
else label+=state.display==SpaceDisplay::treemap?L" · logical size by area":
|
||||
state.display==SpaceDisplay::sunburst?L" · logical size by angle":L" · logical shares of parent";
|
||||
SetDlgItemTextW(dialog,spaceStatus,label.c_str());
|
||||
if(finished)
|
||||
{
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
|
||||
!sameVolumeRoot(state.folder,state.volume.root));
|
||||
KillTimer(dialog,spaceUpdateTimer);
|
||||
}
|
||||
}
|
||||
|
||||
void resetSpaceResults(HWND dialog,SpaceAnalyzer &state,bool scanning)
|
||||
{
|
||||
const auto tree=GetDlgItem(dialog,spaceTree);
|
||||
TreeView_DeleteAllItems(tree);
|
||||
state.nodes.clear();
|
||||
state.nodes.push_back({.path=state.root,.folder=true,.expanded=true});
|
||||
state.directories.clear();
|
||||
state.directories.emplace(state.root,0);
|
||||
state.files=0;
|
||||
state.mapFolder=0;
|
||||
state.tiles.clear();
|
||||
state.sectors.clear();
|
||||
state.selectedTile=0;
|
||||
state.scanning=scanning;
|
||||
state.hasResults=scanning;
|
||||
TreeView_SelectItem(tree,insertSpaceNode(tree,state,0));
|
||||
if(state.display!=SpaceDisplay::tree) refreshSpaceChart(GetDlgItem(dialog,spaceMap),state);
|
||||
EnableWindow(GetDlgItem(dialog,spaceView),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,IDOK),state.display==SpaceDisplay::tree);
|
||||
}
|
||||
|
||||
void prepareSpaceScope(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
state.run.reset();
|
||||
const auto scope=state.volumeScope?state.volume.root:state.folder;
|
||||
state.root=folderPathWithoutSeparator(scope);
|
||||
SetDlgItemTextW(dialog,spacePath,scope.c_str());
|
||||
SetDlgItemTextW(dialog,spaceScope,state.volumeScope?L"&Folder":L"Vo&lume");
|
||||
SetDlgItemTextW(dialog,spaceRescan,L"St&art");
|
||||
SetDlgItemTextW(dialog,spaceStatus,L"Ready to scan");
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
|
||||
resetSpaceResults(dialog,state,false);
|
||||
layoutSpaceAnalyzer(dialog);
|
||||
}
|
||||
|
||||
void updateSpaceVolume(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
if(!state.pendingVolume.valid() ||
|
||||
state.pendingVolume.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
try {state.volume=state.pendingVolume.get();}
|
||||
catch(const std::exception &) {}
|
||||
KillTimer(dialog,spaceVolumeTimer);
|
||||
std::wstring caption=L"Volume capacity unavailable";
|
||||
if(const auto capacity=state.volume.capacity)
|
||||
{
|
||||
caption=L"Capacity "+formatSize(capacity->first)+L" · Free "+formatSize(capacity->second);
|
||||
if(!state.volume.root.empty()) caption+=L" · "+state.volume.root.native();
|
||||
}
|
||||
SetDlgItemTextW(dialog,spaceCapacity,caption.c_str());
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),
|
||||
!state.volume.root.empty() && !sameVolumeRoot(state.folder,state.volume.root));
|
||||
prepareSpaceScope(dialog,state);
|
||||
}
|
||||
|
||||
void rescanSpace(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
resetSpaceResults(dialog,state,true);
|
||||
SetDlgItemTextW(dialog,spaceRescan,L"&Rescan");
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),FALSE);
|
||||
try
|
||||
{
|
||||
const bool volume=state.volumeScope || sameVolumeRoot(state.root,state.volume.root);
|
||||
state.run=startSpaceRun(state.root,volume?state.volume.root:fs::path{});
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),TRUE);
|
||||
SetTimer(dialog,spaceUpdateTimer,60,nullptr);
|
||||
updateSpaceTree(dialog,state);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
|
||||
state.scanning=false;
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
|
||||
!sameVolumeRoot(state.folder,state.volume.root));
|
||||
SetDlgItemTextW(dialog,spaceStatus,L"Could not start space analysis.");
|
||||
}
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &state=*reinterpret_cast<SpaceAnalyzer *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
SetDlgItemTextW(dialog,spacePath,state.folder.c_str());
|
||||
SetDlgItemTextW(dialog,spaceCapacity,L"Reading volume capacity…");
|
||||
const auto tree=GetDlgItem(dialog,spaceTree);
|
||||
SetWindowSubclass(GetDlgItem(dialog,spaceMap),spaceMapInput,1,reinterpret_cast<DWORD_PTR>(&state));
|
||||
SetWindowSubclass(GetDlgItem(dialog,spaceSunburstList),spaceSunburstListKeys,1,reinterpret_cast<DWORD_PTR>(&state));
|
||||
TreeView_SetBkColor(tree,RGB(255,255,255));
|
||||
TreeView_SetTextColor(tree,RGB(0,0,0));
|
||||
layoutSpaceAnalyzer(dialog);
|
||||
const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content();
|
||||
// Rescan is one character wider than the initial Start label.
|
||||
const auto minimum=dialogButtonGroupWidth(dialog,spaceFooterButtons)+cellWidth+2*inset;
|
||||
FilesModalDialog::fitWidthToOwner(dialog,minimum,layoutSpaceAnalyzer);
|
||||
SendMessageW(dialog,DM_SETDEFID,IDCANCEL,0);
|
||||
resetSpaceResults(dialog,state,false);
|
||||
EnableWindow(GetDlgItem(dialog,spaceScope),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE);
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
|
||||
try
|
||||
{
|
||||
state.pendingVolume=readSpaceVolume(state.folder);
|
||||
SetTimer(dialog,spaceVolumeTimer,60,nullptr);
|
||||
updateSpaceVolume(dialog,state);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetDlgItemTextW(dialog,spaceCapacity,L"Volume capacity unavailable");
|
||||
prepareSpaceScope(dialog,state);
|
||||
}
|
||||
SetFocus(tree);
|
||||
return FALSE;
|
||||
}
|
||||
const auto state=reinterpret_cast<SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!state) return FALSE;
|
||||
const auto tree=GetDlgItem(dialog,spaceTree);
|
||||
if(message==WM_DRAWITEM && wp==spaceMap)
|
||||
{
|
||||
const auto &paint=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
|
||||
if(state->display==SpaceDisplay::sunburst) paintSunburst(paint,*state);
|
||||
else paintSpaceMap(paint,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_TIMER && wp==spaceVolumeTimer)
|
||||
{
|
||||
updateSpaceVolume(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_TIMER && wp==spaceUpdateTimer)
|
||||
{
|
||||
updateSpaceTree(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_NOTIFY)
|
||||
{
|
||||
const auto *notification=reinterpret_cast<const NMHDR *>(lp);
|
||||
if(notification->hwndFrom==tree)
|
||||
{
|
||||
if(notification->code==TVN_GETDISPINFOW)
|
||||
{
|
||||
auto &item=reinterpret_cast<NMTVDISPINFOW *>(lp)->item;
|
||||
const auto index=static_cast<size_t>(item.lParam);
|
||||
if(index>=state->nodes.size()) return TRUE;
|
||||
const auto &node=state->nodes[index];
|
||||
if(item.mask&TVIF_CHILDREN) item.cChildren=node.folder && !node.link &&
|
||||
(state->scanning || !node.children.empty())?1:0;
|
||||
if((item.mask&TVIF_TEXT) && item.pszText && item.cchTextMax>0)
|
||||
{
|
||||
const auto text=spaceNodeText(*state,index);
|
||||
lstrcpynW(item.pszText,text.c_str(),item.cchTextMax);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(notification->code==TVN_ITEMEXPANDINGW)
|
||||
{
|
||||
const auto &item=*reinterpret_cast<const NMTREEVIEWW *>(lp);
|
||||
const auto index=static_cast<size_t>(item.itemNew.lParam);
|
||||
if(item.action==TVE_EXPAND && index<state->nodes.size()) expandSpaceNode(tree,*state,index);
|
||||
}
|
||||
if(notification->code==TVN_SELCHANGEDW)
|
||||
{
|
||||
const auto selected=selectedSpaceNode(tree,*state);
|
||||
if(state->display==SpaceDisplay::tree)
|
||||
{
|
||||
EnableWindow(GetDlgItem(dialog,spaceView),selected && !state->nodes[*selected].folder);
|
||||
EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(message==WM_COMMAND)
|
||||
{
|
||||
const auto command=LOWORD(wp);
|
||||
if(command==spaceStop && IsWindowEnabled(GetDlgItem(dialog,spaceStop)))
|
||||
{
|
||||
state->run->stop.request_stop();
|
||||
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
|
||||
updateSpaceTree(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==spaceScope && IsWindowEnabled(GetDlgItem(dialog,spaceScope)))
|
||||
{
|
||||
state->volumeScope=!state->volumeScope;
|
||||
prepareSpaceScope(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==spaceMapButton || command==spaceSunburstButton)
|
||||
{
|
||||
const auto chart=command==spaceMapButton?SpaceDisplay::treemap:SpaceDisplay::sunburst;
|
||||
setSpaceDisplay(dialog,*state,state->display==chart?SpaceDisplay::tree:chart);
|
||||
if(state->run) updateSpaceTree(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==spaceSunburstList && state->display==SpaceDisplay::sunburst)
|
||||
{
|
||||
updateSunburstSelection(dialog,*state);
|
||||
if(HIWORD(wp)==LBN_DBLCLK)
|
||||
if(const auto selected=sunburstSelection(dialog,*state))
|
||||
finishSpaceSelection(dialog,*state,*selected,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==spaceRescan && IsWindowEnabled(GetDlgItem(dialog,spaceRescan)))
|
||||
{
|
||||
rescanSpace(dialog,*state);
|
||||
return TRUE;
|
||||
}
|
||||
if(command==IDOK || command==spaceView)
|
||||
{
|
||||
const auto selected=state->display==SpaceDisplay::sunburst?sunburstSelection(dialog,*state):
|
||||
state->display==SpaceDisplay::tree?selectedSpaceNode(tree,*state):std::nullopt;
|
||||
if(selected) finishSpaceSelection(dialog,*state,*selected,command);
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_DESTROY)
|
||||
{
|
||||
if(state->run) state->run->stop.request_stop();
|
||||
KillTimer(dialog,spaceUpdateTimer);
|
||||
KillTimer(dialog,spaceVolumeTimer);
|
||||
}
|
||||
return paintCopyDialog(dialog,message,wp,lp,L" Space Analyzer ",false,{spaceFooter});
|
||||
}
|
||||
|
||||
void openSpaceAnalyzer(HWND owner,Panel &panel)
|
||||
{
|
||||
if(panel.peer || panel.ftp || panel.archive || panel.directory.empty())
|
||||
{
|
||||
setStatus(L"Space Analyzer requires an open local folder.");
|
||||
return;
|
||||
}
|
||||
const auto origin=static_cast<int>(&panel-panels);
|
||||
SpaceAnalyzer state{.folder=folderPathWithoutSeparator(panel.directory),.root=folderPathWithoutSeparator(panel.directory)};
|
||||
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner,
|
||||
spaceAnalyzerDialog,reinterpret_cast<LPARAM>(&state));
|
||||
if(answer==spaceView)
|
||||
{
|
||||
ks::files::openTextWindow(owner,state.selected,false,textWindowDialogs(),nullptr);
|
||||
return;
|
||||
}
|
||||
if(answer!=IDOK) return;
|
||||
|
||||
if(quickViewWindow) toggleQuickView(owner);
|
||||
if(terminalVisible) showTerminal(owner,false);
|
||||
const auto index=1-origin;
|
||||
auto &other=panels[index];
|
||||
activatePanel(index);
|
||||
panelClipboardContext=true;
|
||||
if(state.selectedFolder) openOn(other,state.selected,true,{});
|
||||
else revealLocalFile(other,state.selected);
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
void finishSpaceSelection(HWND dialog,SpaceAnalyzer &state,size_t selected,int action)
|
||||
{
|
||||
if(selected>=state.nodes.size()) return;
|
||||
const auto &node=state.nodes[selected];
|
||||
if(action==spaceView && node.folder) return;
|
||||
state.selected=node.path;
|
||||
state.selectedFolder=node.folder;
|
||||
FilesModalDialog::finish(dialog,action);
|
||||
}
|
||||
|
||||
void divideSpaceTiles(std::span<const size_t> nodes,std::span<const long double> prefix,RECT bounds,
|
||||
LONG margin,std::vector<SpaceTile> &tiles)
|
||||
{
|
||||
const auto width=bounds.right-bounds.left, height=bounds.bottom-bounds.top;
|
||||
if(width<margin || height<margin || nodes.empty()) return;
|
||||
if(nodes.size()==1)
|
||||
{
|
||||
tiles.push_back({bounds,nodes.front()});
|
||||
return;
|
||||
}
|
||||
const auto total=prefix.back()-prefix.front();
|
||||
if(total<=0) return;
|
||||
const auto middle=prefix.front()+total/2;
|
||||
auto pivot=std::lower_bound(prefix.begin()+1,prefix.end()-1,middle);
|
||||
if(pivot==prefix.end()-1 ||
|
||||
(pivot>prefix.begin()+1 && middle-pivot[-1]<*pivot-middle)) --pivot;
|
||||
const auto offset=static_cast<size_t>(pivot-prefix.begin());
|
||||
const auto share=(*pivot-prefix.front())/total;
|
||||
auto first=bounds, second=bounds;
|
||||
if(width>=height)
|
||||
{
|
||||
const auto split=bounds.left+std::clamp(static_cast<LONG>(width*share+0.5L),1L,width-1);
|
||||
first.right=second.left=split;
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto split=bounds.top+std::clamp(static_cast<LONG>(height*share+0.5L),1L,height-1);
|
||||
first.bottom=second.top=split;
|
||||
}
|
||||
divideSpaceTiles(nodes.first(offset),prefix.first(offset+1),first,margin,tiles);
|
||||
divideSpaceTiles(nodes.subspan(offset),prefix.subspan(offset),second,margin,tiles);
|
||||
}
|
||||
|
||||
void layoutSpaceMap(HWND map,SpaceAnalyzer &state)
|
||||
{
|
||||
state.lastMapUpdate=GetTickCount64();
|
||||
const auto previous=state.selectedTile<state.tiles.size()?
|
||||
state.tiles[state.selectedTile].node:std::numeric_limits<size_t>::max();
|
||||
state.tiles.clear();
|
||||
state.selectedTile=0;
|
||||
if(state.mapFolder>=state.nodes.size()) return;
|
||||
std::vector<size_t> items;
|
||||
for(auto index:state.nodes[state.mapFolder].children)
|
||||
if(state.nodes[index].size.bytes) items.push_back(index);
|
||||
std::sort(items.begin(),items.end(),[&](size_t left,size_t right) {
|
||||
const auto a=state.nodes[left].size.bytes, b=state.nodes[right].size.bytes;
|
||||
return a!=b?a>b:left<right;
|
||||
});
|
||||
std::vector<long double> prefix{0};
|
||||
prefix.reserve(items.size()+1);
|
||||
for(auto index:items) prefix.push_back(prefix.back()+state.nodes[index].size.bytes);
|
||||
RECT bounds{};
|
||||
GetClientRect(map,&bounds);
|
||||
const auto minimum=std::max(4,MulDiv(8,GetDpiForWindow(map),96));
|
||||
divideSpaceTiles(items,prefix,bounds,minimum,state.tiles);
|
||||
for(size_t index=0;index<state.tiles.size();++index)
|
||||
if(state.tiles[index].node==previous)
|
||||
{
|
||||
state.selectedTile=index;
|
||||
break;
|
||||
}
|
||||
InvalidateRect(map,nullptr,FALSE);
|
||||
}
|
||||
|
||||
constexpr COLORREF spaceChartColors[]{RGB(158,203,218),RGB(167,205,172),RGB(230,198,142),
|
||||
RGB(197,179,211),RGB(226,178,173),RGB(177,190,225)};
|
||||
|
||||
void paintEmptySpaceChart(const DRAWITEMSTRUCT &paint)
|
||||
{
|
||||
auto bounds=paint.rcItem;
|
||||
SelectObject(paint.hDC,mono);
|
||||
SetBkMode(paint.hDC,TRANSPARENT);
|
||||
SetTextColor(paint.hDC,RGB(15,27,35));
|
||||
DrawTextW(paint.hDC,L"No measured space to display",-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
|
||||
}
|
||||
|
||||
void paintSpaceMap(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state)
|
||||
{
|
||||
FillRect(paint.hDC,&paint.rcItem,GetSysColorBrush(COLOR_WINDOW));
|
||||
SelectObject(paint.hDC,mono);
|
||||
SetBkMode(paint.hDC,TRANSPARENT);
|
||||
SetTextColor(paint.hDC,RGB(15,27,35));
|
||||
if(state.tiles.empty())
|
||||
{
|
||||
paintEmptySpaceChart(paint);
|
||||
return;
|
||||
}
|
||||
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
const auto focused=GetFocus()==paint.hwndItem;
|
||||
for(size_t index=0;index<state.tiles.size();++index)
|
||||
{
|
||||
const auto &tile=state.tiles[index];
|
||||
if(!RectVisible(paint.hDC,&tile.box)) continue;
|
||||
const auto &node=state.nodes[tile.node];
|
||||
auto bounds=tile.box;
|
||||
SetDCBrushColor(paint.hDC,spaceChartColors[index%std::size(spaceChartColors)]);
|
||||
FillRect(paint.hDC,&bounds,brush);
|
||||
FrameRect(paint.hDC,&bounds,GetSysColorBrush(COLOR_WINDOW));
|
||||
if(focused && index==state.selectedTile)
|
||||
{
|
||||
InflateRect(&bounds,-2,-2);
|
||||
DrawFocusRect(paint.hDC,&bounds);
|
||||
bounds=tile.box;
|
||||
}
|
||||
InflateRect(&bounds,-std::max(3,cellWidth/2),-2);
|
||||
if(bounds.right-bounds.left>=3*cellWidth && bounds.bottom-bounds.top>=textHeight)
|
||||
{
|
||||
const auto name=node.path.filename().native();
|
||||
DrawTextW(paint.hDC,name.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
|
||||
bounds.top+=textHeight;
|
||||
if(bounds.bottom-bounds.top>=textHeight)
|
||||
{
|
||||
const auto logical=spaceLogicalSize(node);
|
||||
DrawTextW(paint.hDC,logical.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
|
||||
bounds.top+=textHeight;
|
||||
if(bounds.bottom-bounds.top>=textHeight)
|
||||
{
|
||||
const auto allocated=spaceAllocatedSize(node);
|
||||
DrawTextW(paint.hDC,allocated.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#include "files_space_sunburst.inl"
|
||||
|
||||
void refreshSpaceChart(HWND map,SpaceAnalyzer &state)
|
||||
{
|
||||
if(state.display==SpaceDisplay::sunburst) layoutSunburst(map,state);
|
||||
else layoutSpaceMap(map,state);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK spaceSunburstListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload)
|
||||
{
|
||||
auto &state=*reinterpret_cast<SpaceAnalyzer *>(payload);
|
||||
if(message==WM_GETDLGCODE && lp && wp==VK_RETURN)
|
||||
return DefSubclassProc(list,message,wp,lp)|DLGC_WANTMESSAGE;
|
||||
if(message==WM_KEYDOWN && wp==VK_RETURN)
|
||||
{
|
||||
const auto dialog=GetParent(list);
|
||||
if(const auto selected=sunburstSelection(dialog,state)) finishSpaceSelection(dialog,state,*selected,IDOK);
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(list,message,wp,lp);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK spaceMapInput(HWND map,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload)
|
||||
{
|
||||
auto &state=*reinterpret_cast<SpaceAnalyzer *>(payload);
|
||||
if(message==WM_SIZE && state.display!=SpaceDisplay::tree) refreshSpaceChart(map,state);
|
||||
if(message==WM_SETFOCUS || message==WM_KILLFOCUS) InvalidateRect(map,nullptr,FALSE);
|
||||
if(message==WM_LBUTTONDOWN)
|
||||
{
|
||||
SetFocus(map);
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_LBUTTONUP)
|
||||
{
|
||||
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
if(state.display==SpaceDisplay::sunburst)
|
||||
{
|
||||
if(const auto hit=hitSunburst(map,state,point))
|
||||
finishSpaceSelection(GetParent(map),state,state.sectors[*hit].node,IDOK);
|
||||
return 0;
|
||||
}
|
||||
for(const auto &tile:state.tiles)
|
||||
if(PtInRect(&tile.box,point))
|
||||
{
|
||||
finishSpaceSelection(GetParent(map),state,tile.node,IDOK);
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(message==WM_GETDLGCODE)
|
||||
{
|
||||
const auto *key=reinterpret_cast<const MSG *>(lp);
|
||||
return DLGC_WANTARROWS|(key && key->message==WM_KEYDOWN && wp==VK_RETURN?DLGC_WANTMESSAGE:0);
|
||||
}
|
||||
if(message==WM_KEYDOWN && state.display==SpaceDisplay::treemap && !state.tiles.empty())
|
||||
{
|
||||
if(wp==VK_RETURN)
|
||||
{
|
||||
finishSpaceSelection(GetParent(map),state,state.tiles[state.selectedTile].node,IDOK);
|
||||
return 0;
|
||||
}
|
||||
if(wp==VK_DOWN || wp==VK_RIGHT || wp==VK_UP || wp==VK_LEFT)
|
||||
{
|
||||
auto &index=state.selectedTile;
|
||||
if(wp==VK_DOWN || wp==VK_RIGHT) index=(index+1)%state.tiles.size();
|
||||
else index=index?index-1:state.tiles.size()-1;
|
||||
InvalidateRect(map,nullptr,FALSE);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return DefSubclassProc(map,message,wp,lp);
|
||||
}
|
||||
|
||||
void setSpaceDisplay(HWND dialog,SpaceAnalyzer &state,SpaceDisplay display)
|
||||
{
|
||||
const auto tree=GetDlgItem(dialog,spaceTree), map=GetDlgItem(dialog,spaceMap);
|
||||
const auto list=GetDlgItem(dialog,spaceSunburstList);
|
||||
const bool showTree=display==SpaceDisplay::tree, showSunburst=display==SpaceDisplay::sunburst;
|
||||
const auto selection=selectedSpaceNode(tree,state);
|
||||
if(state.display==SpaceDisplay::tree && !showTree)
|
||||
{
|
||||
const auto index=selection.value_or(0);
|
||||
const auto &node=state.nodes[index];
|
||||
state.mapFolder=node.folder && !node.link?index:node.parent;
|
||||
}
|
||||
state.display=display;
|
||||
SetDlgItemTextW(dialog,spaceMapButton,display==SpaceDisplay::treemap?L"Tr&ee":L"Tree&map");
|
||||
SetDlgItemTextW(dialog,spaceSunburstButton,showSunburst?L"Tr&ee":L"S&unburst");
|
||||
layoutSpaceAnalyzer(dialog);
|
||||
ShowWindow(tree,showTree?SW_SHOW:SW_HIDE);
|
||||
ShowWindow(map,showTree?SW_HIDE:SW_SHOW);
|
||||
ShowWindow(GetDlgItem(dialog,spaceSunburstLabel),showSunburst?SW_SHOW:SW_HIDE);
|
||||
ShowWindow(list,showSunburst?SW_SHOW:SW_HIDE);
|
||||
if(!showSunburst)
|
||||
{
|
||||
EnableWindow(GetDlgItem(dialog,spaceView),showTree && selection && !state.nodes[*selection].folder);
|
||||
EnableWindow(GetDlgItem(dialog,IDOK),showTree && selection.has_value());
|
||||
}
|
||||
if(!showTree) refreshSpaceChart(map,state);
|
||||
SetFocus(showTree?tree:showSunburst?list:map);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
constexpr double fullCircle=2*std::numbers::pi_v<double>;
|
||||
constexpr unsigned sunburstRings=3;
|
||||
|
||||
double sunburstRingWidth(const RECT &bounds)
|
||||
{
|
||||
return std::max(0L,std::min(bounds.right-bounds.left,bounds.bottom-bounds.top)-4)/
|
||||
(2.0*(sunburstRings+0.5));
|
||||
}
|
||||
|
||||
void addSunburstRing(SpaceAnalyzer &state,size_t folder,unsigned ring,double start,double end)
|
||||
{
|
||||
if(ring>=sunburstRings || end-start<0.02) return;
|
||||
const auto &parent=state.nodes[folder];
|
||||
double total=0;
|
||||
for(auto index:parent.children) total+=static_cast<double>(state.nodes[index].size.bytes);
|
||||
if(total<=0) return;
|
||||
const auto span=end-start;
|
||||
auto cursor=start;
|
||||
for(auto index:parent.children)
|
||||
{
|
||||
const auto &item=state.nodes[index];
|
||||
if(!item.size.bytes) continue;
|
||||
const auto next=std::min(end,cursor+span*static_cast<double>(item.size.bytes)/total);
|
||||
if(next-cursor>=0.02)
|
||||
{
|
||||
state.sectors.push_back({index,ring,cursor,next});
|
||||
if(item.folder) addSunburstRing(state,index,ring+1,cursor,next);
|
||||
}
|
||||
cursor=next;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<size_t> sunburstSelectedSector(HWND dialog,const SpaceAnalyzer &state)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETCURSEL,0,0);
|
||||
if(row==LB_ERR) return {};
|
||||
const auto sector=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETITEMDATA,row,0);
|
||||
if(sector==LB_ERR || static_cast<size_t>(sector)>=state.sectors.size()) return {};
|
||||
return static_cast<size_t>(sector);
|
||||
}
|
||||
|
||||
std::optional<size_t> sunburstSelection(HWND dialog,const SpaceAnalyzer &state)
|
||||
{
|
||||
const auto sector=sunburstSelectedSector(dialog,state);
|
||||
return sector?std::optional<size_t>(state.sectors[*sector].node):std::nullopt;
|
||||
}
|
||||
|
||||
void updateSunburstSelection(HWND dialog,SpaceAnalyzer &state)
|
||||
{
|
||||
state.selectedTile=sunburstSelectedSector(dialog,state).value_or(state.sectors.size());
|
||||
const auto selected=sunburstSelection(dialog,state);
|
||||
EnableWindow(GetDlgItem(dialog,spaceView),selected && !state.nodes[*selected].folder);
|
||||
EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value());
|
||||
InvalidateRect(GetDlgItem(dialog,spaceMap),nullptr,FALSE);
|
||||
}
|
||||
|
||||
void layoutSunburst(HWND map,SpaceAnalyzer &state)
|
||||
{
|
||||
const auto dialog=GetParent(map);
|
||||
const auto list=GetDlgItem(dialog,spaceSunburstList);
|
||||
const auto selected=sunburstSelection(dialog,state);
|
||||
state.lastMapUpdate=GetTickCount64();
|
||||
state.sectors.clear();
|
||||
state.selectedTile=0;
|
||||
if(state.mapFolder<state.nodes.size())
|
||||
addSunburstRing(state,state.mapFolder,0,0,fullCircle);
|
||||
SendMessageW(list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
SendMessageW(list,LB_INITSTORAGE,state.sectors.size(),0);
|
||||
LRESULT selection=0;
|
||||
size_t longest=0;
|
||||
for(size_t i=0;i<state.sectors.size();++i)
|
||||
{
|
||||
const auto §or=state.sectors[i];
|
||||
const auto &node=state.nodes[sector.node];
|
||||
const auto &root=state.nodes[state.mapFolder];
|
||||
const auto name=node.path.lexically_relative(root.path).native();
|
||||
const auto line=name+L" — "+spaceLogicalSize(node);
|
||||
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(line.c_str()));
|
||||
if(row>=0)
|
||||
{
|
||||
SendMessageW(list,LB_SETITEMDATA,row,i);
|
||||
if(selected==sector.node) selection=row;
|
||||
longest=std::max(longest,line.size());
|
||||
}
|
||||
}
|
||||
SendMessageW(list,LB_SETHORIZONTALEXTENT,(longest+1)*cellWidth,0);
|
||||
if(!state.sectors.empty()) SendMessageW(list,LB_SETCURSEL,selection,0);
|
||||
SendMessageW(list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(list,nullptr,FALSE);
|
||||
updateSunburstSelection(dialog,state);
|
||||
}
|
||||
|
||||
std::optional<size_t> hitSunburst(HWND map,const SpaceAnalyzer &state,POINT point)
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(map,&bounds);
|
||||
const auto width=sunburstRingWidth(bounds);
|
||||
if(width<=0) return {};
|
||||
const auto x=point.x-(bounds.left+bounds.right)/2.0;
|
||||
const auto y=point.y-(bounds.top+bounds.bottom)/2.0;
|
||||
const auto radius=std::hypot(x,y)/width-0.5;
|
||||
if(radius<0 || radius>=sunburstRings) return {};
|
||||
const auto ring=static_cast<unsigned>(radius);
|
||||
auto angle=std::atan2(x,-y);
|
||||
if(angle<0) angle+=fullCircle;
|
||||
for(size_t i=0;i<state.sectors.size();++i)
|
||||
{
|
||||
const auto §or=state.sectors[i];
|
||||
if(sector.ring==ring && angle>=sector.start && angle<sector.end) return i;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void paintSunburst(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state)
|
||||
{
|
||||
auto bounds=paint.rcItem;
|
||||
FillRect(paint.hDC,&bounds,GetSysColorBrush(COLOR_WINDOW));
|
||||
if(state.sectors.empty())
|
||||
{
|
||||
paintEmptySpaceChart(paint);
|
||||
return;
|
||||
}
|
||||
const auto width=sunburstRingWidth(bounds);
|
||||
const auto x=(bounds.left+bounds.right)/2.0, y=(bounds.top+bounds.bottom)/2.0;
|
||||
const auto point=[&](double angle,double radius) {
|
||||
return POINT{std::lround(x+radius*std::sin(angle)),std::lround(y-radius*std::cos(angle))};
|
||||
};
|
||||
const auto oldBrush=SelectObject(paint.hDC,GetStockObject(DC_BRUSH));
|
||||
const auto oldPen=SelectObject(paint.hDC,GetStockObject(DC_PEN));
|
||||
for(size_t i=0;i<state.sectors.size();++i)
|
||||
{
|
||||
const auto §or=state.sectors[i];
|
||||
const auto segments=std::clamp(static_cast<int>((sector.end-sector.start)*26),2,164);
|
||||
const auto inner=(sector.ring+0.5)*width, outer=inner+width;
|
||||
std::array<POINT,330> points;
|
||||
for(int segment=0;segment<=segments;++segment)
|
||||
{
|
||||
const auto angle=sector.start+(sector.end-sector.start)*segment/segments;
|
||||
points[segment]=point(angle,outer);
|
||||
points[2*segments+1-segment]=point(angle,inner);
|
||||
}
|
||||
SetDCPenColor(paint.hDC,i==state.selectedTile?RGB(35,48,62):RGB(255,255,255));
|
||||
SetDCBrushColor(paint.hDC,spaceChartColors[i%std::size(spaceChartColors)]);
|
||||
Polygon(paint.hDC,points.data(),2*(segments+1));
|
||||
}
|
||||
SelectObject(paint.hDC,oldPen);
|
||||
SelectObject(paint.hDC,oldBrush);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
bool panelMatchesSshPrompt()
|
||||
{
|
||||
const auto &panel=panels[active];
|
||||
return sshPrompt && sshPrompt->panel==active && panel.ftp &&
|
||||
panel.ftp->protocol==TransferProtocol::sftp && panel.ftp->id==sshPrompt->profile;
|
||||
}
|
||||
|
||||
void closeSshPrompt(HWND owner)
|
||||
{
|
||||
if(!sshPrompt) return;
|
||||
clearTerminalSelection();
|
||||
sshPrompt.reset();
|
||||
sshTerminal.stop();
|
||||
sshView.post(L"ssh-input:off");
|
||||
layout(owner);
|
||||
}
|
||||
|
||||
bool startSshTerminal(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(panelMatchesSshPrompt() && !sshPrompt->finished) return true;
|
||||
if(sshTerminal.running())
|
||||
{
|
||||
setStatus(L"The previous SSH session is closing. Try again when it has disconnected.");
|
||||
return false;
|
||||
}
|
||||
if(!ensureTerminalView(owner,true)) return false;
|
||||
try
|
||||
{
|
||||
auto token=ks::lan::randomHex(16);
|
||||
sshTerminal.start(*panel.ftp,panel.directory,token,sshSize);
|
||||
clearTerminalSelection();
|
||||
sshPrompt=SshPrompt{active,panel.ftp->id,std::move(token),panel.directory};
|
||||
}
|
||||
catch(const std::exception &error) {setStatus(ks::wide(error.what()));return false;}
|
||||
sshView.post(L"ssh-reset");
|
||||
if(!terminalVisible) terminalRows=std::max(terminalRows,5);
|
||||
layout(owner);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool sendSshCommand(HWND owner,const fs::path &directory,const std::wstring &value)
|
||||
{
|
||||
const auto text=ks::utf8(value);
|
||||
const auto command=directory==sshPrompt->shellDirectory?text:
|
||||
"if "+sshChangeDirectory(directory)+"; then eval "+sshShellQuote(text)+"; fi";
|
||||
if(!sshTerminal.write(command+"\r"))
|
||||
{
|
||||
setStatus(L"Could not send input to the SSH terminal.");
|
||||
return false;
|
||||
}
|
||||
sshPrompt->panelDirectory=directory;
|
||||
sshPrompt->waiting=true;
|
||||
sshPrompt->raw=true;
|
||||
sshView.post(L"ssh-input:on");
|
||||
if(GetForegroundWindow()==owner)
|
||||
{
|
||||
sshView.focus();
|
||||
sshView.post(L"ssh-focus");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool submitSshCommand(HWND owner,const Panel &panel,const std::wstring &value)
|
||||
{
|
||||
if(!startSshTerminal(owner,panel)) return false;
|
||||
if(!sshPrompt->waiting) return sendSshCommand(owner,panel.directory,value);
|
||||
if(sshPrompt->shellDirectory.empty() && !sshPrompt->startupCommand)
|
||||
{
|
||||
sshPrompt->startupCommand=value;
|
||||
return true;
|
||||
}
|
||||
setStatus(L"The SSH prompt is busy.");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::optional<fs::path> sshReportedDirectory(std::wstring_view encoded)
|
||||
{
|
||||
if(encoded.empty() || encoded.size()>49152) return {};
|
||||
DWORD length{};
|
||||
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
|
||||
nullptr,&length,nullptr,nullptr) || !length) return {};
|
||||
auto bytes=std::string(length,'\0');
|
||||
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
|
||||
reinterpret_cast<BYTE*>(bytes.data()),&length,nullptr,nullptr) || bytes.front()!='/' ||
|
||||
bytes.find_first_of("\\:\r\n")!=bytes.npos || bytes.find('\0')!=bytes.npos) return {};
|
||||
auto path=fs::path(ks::wide(bytes)).lexically_normal();
|
||||
return isFtpFolderPath(path)?std::optional(std::move(path)):std::nullopt;
|
||||
}
|
||||
|
||||
void acceptSshDirectory(HWND owner,std::wstring_view message)
|
||||
{
|
||||
if(!panelMatchesSshPrompt() || sshPrompt->finished || message.size()<33 || message[32]!=L':' ||
|
||||
message.substr(0,32)!=ks::wide(sshPrompt->token)) return;
|
||||
const auto reported=sshReportedDirectory(message.substr(33));
|
||||
if(!reported) return;
|
||||
auto &panel=panels[active];
|
||||
auto &prompt=*sshPrompt;
|
||||
const bool initial=prompt.shellDirectory.empty();
|
||||
const bool command=std::exchange(prompt.raw,false);
|
||||
prompt.shellDirectory=*reported;
|
||||
prompt.waiting=false;
|
||||
if(command)
|
||||
{
|
||||
sshView.post(L"ssh-input:off");
|
||||
if(GetForegroundWindow()==owner) restoreCommandFocus();
|
||||
}
|
||||
if(prompt.startupCommand)
|
||||
{
|
||||
const auto pending=std::exchange(prompt.startupCommand,{});
|
||||
if(!sendSshCommand(owner,prompt.panelDirectory,*pending) && !GetWindowTextLengthW(terminalInput))
|
||||
SetWindowTextW(terminalInput,pending->c_str());
|
||||
return;
|
||||
}
|
||||
if(panel.scan.valid() || panel.directory!=prompt.panelDirectory || panel.directory==*reported) return;
|
||||
if(initial || command)
|
||||
{
|
||||
prompt.panelDirectory=*reported;
|
||||
open(panel,*reported,false);
|
||||
}
|
||||
else setStatus(L"The SSH shell could not enter the panel folder.");
|
||||
}
|
||||
|
||||
void updateSshTerminal(HWND owner)
|
||||
{
|
||||
if(!sshPrompt) return;
|
||||
if(!panelMatchesSshPrompt()) {closeSshPrompt(owner);return;}
|
||||
if(!sshView.initialized()) return;
|
||||
const auto output=sshTerminal.takeOutput();
|
||||
if(!output.empty()) sshView.send(output);
|
||||
auto &prompt=*sshPrompt;
|
||||
if(!sshTerminal.running() && !prompt.finished)
|
||||
{
|
||||
auto reason=sshTerminal.takeError();
|
||||
if(reason.empty()) reason=L"SSH session disconnected.";
|
||||
sshView.send(ks::utf8(L"\r\n["+reason+L"]\r\n"));
|
||||
if(prompt.startupCommand && !GetWindowTextLengthW(terminalInput))
|
||||
SetWindowTextW(terminalInput,prompt.startupCommand->c_str());
|
||||
prompt.finished=true;
|
||||
prompt.raw=false;
|
||||
sshView.post(L"ssh-input:off");
|
||||
setStatus(reason);
|
||||
if(GetForegroundWindow()==owner) restoreCommandFocus();
|
||||
return;
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
if(prompt.finished || prompt.waiting || panel.scan.valid() || panel.directory==prompt.panelDirectory) return;
|
||||
prompt.panelDirectory=panel.directory;
|
||||
if(panel.directory!=prompt.shellDirectory && sshTerminal.write(sshChangeDirectory(panel.directory)+"\r"))
|
||||
prompt.waiting=true;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
std::string sshShellQuote(std::string_view text)
|
||||
{
|
||||
std::string quoted="'";
|
||||
for(const auto character:text)
|
||||
if(character=='\'') quoted+="'\\''";
|
||||
else quoted+=character;
|
||||
return quoted+"'";
|
||||
}
|
||||
|
||||
std::string sshChangeDirectory(const fs::path &path)
|
||||
{
|
||||
return "cd "+sshShellQuote(ks::utf8(ftpPath(path)));
|
||||
}
|
||||
|
||||
class FilesSshTerminal
|
||||
{
|
||||
std::mutex mutex_;
|
||||
std::string input_,output_;
|
||||
std::wstring error_;
|
||||
COORD size_{};
|
||||
std::atomic_bool running_{};
|
||||
std::jthread worker_;
|
||||
|
||||
void run(const TransferProfile &profile,const fs::path &directory,const std::string &token,
|
||||
COORD terminalSize,std::stop_token stop)
|
||||
{
|
||||
SshConnection connection(profile);
|
||||
if(stop.stop_requested()) return;
|
||||
SshChannel channel(libssh2_channel_open_session(connection.session()),libssh2_channel_free);
|
||||
if(!channel) connection.operationError("Could not open the SSH terminal");
|
||||
if(libssh2_channel_request_pty_ex(channel.get(),"xterm-256color",14,nullptr,0,
|
||||
terminalSize.X,terminalSize.Y,0,0)) connection.operationError("Could not allocate the SSH terminal");
|
||||
|
||||
// Expand the prompt after every command so panel navigation can follow even scripted directory changes.
|
||||
const auto report="printf '\\033]633;ks-ssh-dir:"+token+
|
||||
":%s\\007' \"$(printf '%s' \"$(pwd -P)\" | base64 | tr -d '\\r\\n')\"";
|
||||
const auto command=sshChangeDirectory(directory)+
|
||||
" || exit; command -v base64 >/dev/null 2>&1 || { echo 'SSH directory sync requires base64.'; exit 1; }; "
|
||||
"if command -v bash >/dev/null 2>&1; then exec env PS1='' PS2='> ' PROMPT_COMMAND="+
|
||||
sshShellQuote(report)+" bash --noprofile --norc -i; else exec env ENV=/dev/null PS2='> ' PS1="+
|
||||
sshShellQuote("$("+report+")")+" /bin/sh -i; fi";
|
||||
if(libssh2_channel_exec(channel.get(),command.c_str()))
|
||||
connection.operationError("Could not start the SSH shell");
|
||||
|
||||
connection.nonblocking();
|
||||
auto buffer=std::array<char,32768>{};
|
||||
std::string pending;
|
||||
size_t offset{};
|
||||
std::optional<COORD> resize;
|
||||
while(!stop.stop_requested())
|
||||
{
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
if(pending.empty()) pending.swap(input_);
|
||||
if(!resize && (terminalSize.X!=size_.X || terminalSize.Y!=size_.Y)) resize=size_;
|
||||
}
|
||||
bool progressed=false;
|
||||
if(resize)
|
||||
{
|
||||
const auto result=libssh2_channel_request_pty_size(channel.get(),resize->X,resize->Y);
|
||||
if(result!=LIBSSH2_ERROR_EAGAIN)
|
||||
{
|
||||
terminalSize=*resize;
|
||||
resize.reset();
|
||||
}
|
||||
}
|
||||
if(!pending.empty())
|
||||
{
|
||||
const auto count=libssh2_channel_write(channel.get(),pending.data()+offset,pending.size()-offset);
|
||||
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not send SSH terminal input");
|
||||
if(count>0)
|
||||
{
|
||||
offset+=count;
|
||||
if(offset==pending.size()) {pending.clear();offset=0;}
|
||||
progressed=true;
|
||||
}
|
||||
}
|
||||
for(int stream:{0,SSH_EXTENDED_DATA_STDERR})
|
||||
{
|
||||
const auto count=libssh2_channel_read_ex(channel.get(),stream,buffer.data(),buffer.size());
|
||||
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not read SSH terminal output");
|
||||
if(count>0)
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
output_.append(buffer.data(),count);
|
||||
constexpr size_t limit=1024*1024;
|
||||
if(output_.size()>limit) output_.erase(0,output_.size()-limit);
|
||||
progressed=true;
|
||||
}
|
||||
}
|
||||
if(!progressed)
|
||||
{
|
||||
if(libssh2_channel_eof(channel.get())) break;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
}
|
||||
// The connection owns all channels. Its teardown also handles a channel blocked in a nonblocking request.
|
||||
channel.release();
|
||||
}
|
||||
|
||||
public:
|
||||
bool running() const {return running_;}
|
||||
|
||||
void start(TransferProfile profile,fs::path directory,std::string token,COORD size)
|
||||
{
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
input_.clear();
|
||||
output_.clear();
|
||||
error_.clear();
|
||||
size_=size;
|
||||
}
|
||||
running_=true;
|
||||
try
|
||||
{
|
||||
worker_=std::jthread([this,profile=std::move(profile),directory=std::move(directory),
|
||||
token=std::move(token),size](std::stop_token stop)
|
||||
{
|
||||
try {run(profile,directory,token,size,stop);}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
error_=ks::wide(error.what());
|
||||
}
|
||||
running_=false;
|
||||
});
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
running_=false;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void stop() {worker_.request_stop();}
|
||||
|
||||
bool write(std::string_view input)
|
||||
{
|
||||
if(!running_) return false;
|
||||
const std::lock_guard lock(mutex_);
|
||||
constexpr size_t limit=256*1024;
|
||||
if(input.size()>limit-input_.size()) return false;
|
||||
input_+=input;
|
||||
return true;
|
||||
}
|
||||
|
||||
void resize(COORD size)
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
size_=size;
|
||||
}
|
||||
|
||||
std::string takeOutput()
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
return std::exchange(output_,{});
|
||||
}
|
||||
|
||||
std::wstring takeError()
|
||||
{
|
||||
const std::lock_guard lock(mutex_);
|
||||
return std::exchange(error_,{});
|
||||
}
|
||||
};
|
||||
@@ -127,7 +127,7 @@ public:
|
||||
return SUCCEEDED(web->PostWebMessageAsString(message.c_str()));
|
||||
}
|
||||
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed,
|
||||
bool markdown=false,std::function<bool(UINT)> handleKey={})
|
||||
bool markdown=false,std::function<bool(UINT)> handleKey={},bool ssh=false)
|
||||
{
|
||||
wchar_t exe[MAX_PATH]{};
|
||||
if(!GetModuleFileNameW(nullptr,exe,MAX_PATH)) return false;
|
||||
@@ -144,7 +144,7 @@ public:
|
||||
if(!length || length>=MAX_PATH) return false;
|
||||
const auto profile=std::filesystem::path(local)/L"KSwitcher"/(markdown?L"MarkdownWebView":L"TerminalWebView");
|
||||
const auto origin=markdown?L"kswitcher-markdown.invalid":L"kswitcher-terminal.invalid";
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
|
||||
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":ssh?L"/index.html?ssh":L"/index.html");
|
||||
const auto assets=folder/L"terminal";
|
||||
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
|
||||
waitForReady=!markdown;
|
||||
|
||||
+110
-9
@@ -1,4 +1,5 @@
|
||||
#include "files_text_document.h"
|
||||
#include "files_win32_replace.h"
|
||||
|
||||
#include <objbase.h>
|
||||
#include <algorithm>
|
||||
@@ -305,6 +306,114 @@ std::string TextDocument::readPage(uint64_t page) const
|
||||
return readOriginal(page);
|
||||
}
|
||||
|
||||
std::string TextDocument::readBytes(uint64_t offset,size_t count) const
|
||||
{
|
||||
if(path_.empty() || offset>=size_ || !count) return {};
|
||||
const auto length=static_cast<size_t>(std::min<uint64_t>({count,hexPageBytes,size_-offset}));
|
||||
File temporary{source_==INVALID_HANDLE_VALUE?openSource(path_,false):INVALID_HANDLE_VALUE};
|
||||
return read(source_==INVALID_HANDLE_VALUE?temporary.handle:source_,offset,length);
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
struct TextLineCounter
|
||||
{
|
||||
uint64_t line=1;
|
||||
bool afterCr{};
|
||||
|
||||
void consume(char value)
|
||||
{
|
||||
if(value=='\r' || (value=='\n' && !afterCr)) ++line;
|
||||
afterCr=value=='\r';
|
||||
}
|
||||
};
|
||||
|
||||
void checkLineScan(std::stop_token stop)
|
||||
{
|
||||
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t TextDocument::lineAt(uint64_t page,size_t offset,std::stop_token stop) const
|
||||
{
|
||||
TextLineCounter counter;
|
||||
page=std::min(page,pages()-1);
|
||||
for(uint64_t index=0;index<=page;++index)
|
||||
{
|
||||
checkLineScan(stop);
|
||||
const auto contents=readPage(index);
|
||||
const auto prefix=index==page?std::string_view(contents).substr(0,offset):std::string_view(contents);
|
||||
for(const char value:prefix) counter.consume(value);
|
||||
}
|
||||
return counter.line;
|
||||
}
|
||||
|
||||
std::optional<TextLineLocation> TextDocument::locateLine(uint64_t line,std::stop_token stop) const
|
||||
{
|
||||
if(!line) return {};
|
||||
TextLineCounter counter;
|
||||
const auto count=pages();
|
||||
size_t end=0;
|
||||
for(uint64_t index=0;index<count;++index)
|
||||
{
|
||||
checkLineScan(stop);
|
||||
const auto contents=readPage(index);
|
||||
end=contents.size();
|
||||
for(size_t offset=0;offset<end;++offset)
|
||||
{
|
||||
const auto value=contents[offset];
|
||||
if(counter.line==line && !(counter.afterCr && value=='\n'))
|
||||
return TextLineLocation{index,offset};
|
||||
counter.consume(value);
|
||||
}
|
||||
}
|
||||
return counter.line==line?std::optional(TextLineLocation{count-1,end}):std::nullopt;
|
||||
}
|
||||
|
||||
std::string formatHexAddress(uint64_t offset)
|
||||
{
|
||||
constexpr char digits[]="0123456789ABCDEF";
|
||||
std::string address(16,'0');
|
||||
for(size_t i=address.size();i;offset>>=4) address[--i]=digits[offset&15];
|
||||
return address;
|
||||
}
|
||||
|
||||
std::string formatHexPage(std::string_view bytes,uint64_t offset)
|
||||
{
|
||||
constexpr char digits[]="0123456789ABCDEF";
|
||||
constexpr size_t rowBytes=16;
|
||||
std::string formatted;
|
||||
formatted.reserve(((bytes.size()+rowBytes-1)/rowBytes)*88);
|
||||
for(size_t row=0;row<bytes.size();row+=rowBytes)
|
||||
{
|
||||
const auto length=std::min(rowBytes,bytes.size()-row);
|
||||
formatted+=formatHexAddress(offset+row);
|
||||
formatted+=" ";
|
||||
for(size_t column=0;column<rowBytes;++column)
|
||||
{
|
||||
if(column==8) formatted+=' ';
|
||||
if(column<length)
|
||||
{
|
||||
const auto value=static_cast<unsigned char>(bytes[row+column]);
|
||||
formatted+=digits[value>>4];
|
||||
formatted+=digits[value&15];
|
||||
}
|
||||
else formatted+=" ";
|
||||
formatted+=' ';
|
||||
}
|
||||
formatted+=" |";
|
||||
for(size_t column=0;column<length;++column)
|
||||
{
|
||||
const auto value=static_cast<unsigned char>(bytes[row+column]);
|
||||
formatted+=value>=0x20 && value<=0x7e?static_cast<char>(value):'.';
|
||||
}
|
||||
formatted.append(rowBytes-length,' ');
|
||||
formatted+="|\r\n";
|
||||
}
|
||||
if(!formatted.empty()) formatted.resize(formatted.size()-2);
|
||||
return formatted;
|
||||
}
|
||||
|
||||
std::string TextDocument::readOriginal(uint64_t page) const
|
||||
{
|
||||
if(path_.empty()) return {};
|
||||
@@ -385,16 +494,8 @@ bool TextDocument::save()
|
||||
File current{openSource(path_, true)};
|
||||
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
|
||||
const auto backup = temporaryPath(path_.parent_path());
|
||||
if (!ReplaceFileW(path_.c_str(), pending.path.c_str(), backup.c_str(), 0, nullptr, nullptr))
|
||||
if (const auto error=replaceFileWithBackup(path_,pending.path,backup))
|
||||
{
|
||||
const auto error = GetLastError();
|
||||
if (GetFileAttributesW(backup.c_str()) != INVALID_FILE_ATTRIBUTES &&
|
||||
!MoveFileExW(backup.c_str(), path_.c_str(), MOVEFILE_WRITE_THROUGH))
|
||||
{
|
||||
const auto location = backup.u8string();
|
||||
throw std::runtime_error("Could not restore the original name after a save error. The original is at " +
|
||||
std::string(location.begin(), location.end()));
|
||||
}
|
||||
SetLastError(error);
|
||||
fail("Replace original file");
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
@@ -12,6 +14,10 @@ namespace ks::files
|
||||
enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 };
|
||||
enum class TextLineEnding { preserve, crlf, lf, cr };
|
||||
|
||||
inline constexpr uint64_t hexPageBytes=64*1024;
|
||||
std::string formatHexAddress(uint64_t offset);
|
||||
std::string formatHexPage(std::string_view bytes,uint64_t offset);
|
||||
|
||||
struct TextSaveFormat
|
||||
{
|
||||
TextEncoding encoding=TextEncoding::utf8;
|
||||
@@ -19,6 +25,12 @@ struct TextSaveFormat
|
||||
TextLineEnding lineEnding=TextLineEnding::preserve;
|
||||
};
|
||||
|
||||
struct TextLineLocation
|
||||
{
|
||||
uint64_t page{};
|
||||
size_t offset{};
|
||||
};
|
||||
|
||||
class TextDocument
|
||||
{
|
||||
public:
|
||||
@@ -35,6 +47,9 @@ public:
|
||||
uint64_t size() const { return size_; }
|
||||
uint64_t boundary(uint64_t page) const;
|
||||
std::string readPage(uint64_t page) const;
|
||||
std::string readBytes(uint64_t offset,size_t count) const;
|
||||
uint64_t lineAt(uint64_t page,size_t offset,std::stop_token stop={}) const;
|
||||
std::optional<TextLineLocation> locateLine(uint64_t line,std::stop_token stop={}) const;
|
||||
void releaseReadHandle();
|
||||
void stage(uint64_t page, std::string_view utf8);
|
||||
bool modified() const { return !changes_.empty(); }
|
||||
|
||||
+508
-109
File diff suppressed because it is too large.
Load diff
+11
-1
@@ -61,6 +61,8 @@ struct TextOpenOptions
|
||||
{
|
||||
TextEncoding encoding=TextEncoding::automatic;
|
||||
bool draft{};
|
||||
bool hex{};
|
||||
uint64_t line{};
|
||||
};
|
||||
|
||||
struct RemoteTextRevision
|
||||
@@ -79,16 +81,24 @@ struct RemoteTextSource
|
||||
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
|
||||
const RemoteTextRevision &)> upload;
|
||||
};
|
||||
RemoteTextSource createLanTextSource(const lan::FilesPeer &peer);
|
||||
|
||||
inline constexpr UINT quickViewToggleMessage=WM_APP+31;
|
||||
HWND createQuickView(HWND owner,TextDialogs dialogs);
|
||||
void previewQuickViewFile(HWND window,const std::filesystem::path &path);
|
||||
HWND createImageQuickView(HWND owner,TextDialogs dialogs);
|
||||
void previewImageQuickViewFile(HWND window,const std::filesystem::path &path);
|
||||
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
|
||||
TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr);
|
||||
void showAllViewerBookmarks(HWND owner,TextDialogs dialogs);
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
|
||||
TextOpenOptions options={});
|
||||
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false);
|
||||
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={});
|
||||
void textWindowOwnerClosed();
|
||||
void standaloneFilesWindowOpened();
|
||||
void standaloneFilesWindowClosed();
|
||||
bool cycleTextWindows(HWND current,bool reverse);
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,251 @@
|
||||
struct ViewerBookmark
|
||||
{
|
||||
std::filesystem::path path;
|
||||
uint64_t line{};
|
||||
std::wstring name;
|
||||
};
|
||||
|
||||
int compareBookmarkPaths(const std::filesystem::path &left,const std::filesystem::path &right)
|
||||
{
|
||||
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)-CSTR_EQUAL;
|
||||
}
|
||||
|
||||
bool sameViewerBookmark(const ViewerBookmark &left,const ViewerBookmark &right)
|
||||
{
|
||||
return left.line==right.line && compareBookmarkPaths(left.path,right.path)==0;
|
||||
}
|
||||
|
||||
std::vector<ViewerBookmark> readViewerBookmarks(const std::filesystem::path &file)
|
||||
{
|
||||
if(!std::filesystem::exists(file)) return {};
|
||||
const auto saved=nlohmann::json::parse(readFile(file,2*1024*1024));
|
||||
if(!saved.is_array()) throw std::runtime_error("Could not read the Viewer bookmarks.");
|
||||
std::vector<ViewerBookmark> bookmarks;
|
||||
for(const auto &item:saved)
|
||||
{
|
||||
if(!item.is_object() || !item.contains("path") || !item["path"].is_string() ||
|
||||
!item.contains("line") || !item["line"].is_number_unsigned()) continue;
|
||||
std::filesystem::path path=wide(item["path"].get<std::string>());
|
||||
const auto line=item["line"].get<uint64_t>();
|
||||
if(!path.is_absolute() || !line || path.native().find(L'\0')!=std::wstring::npos) continue;
|
||||
std::wstring name;
|
||||
if(item.contains("name") && item["name"].is_string()) name=wide(item["name"].get<std::string>());
|
||||
if(name.find(L'\0')!=std::wstring::npos) name.clear();
|
||||
bookmarks.push_back({std::move(path),line,std::move(name)});
|
||||
}
|
||||
std::sort(bookmarks.begin(),bookmarks.end(),[](const auto &left,const auto &right) {
|
||||
const auto pathOrder=compareBookmarkPaths(left.path,right.path);
|
||||
return pathOrder?pathOrder<0:left.line<right.line;
|
||||
});
|
||||
bookmarks.erase(std::unique(bookmarks.begin(),bookmarks.end(),sameViewerBookmark),bookmarks.end());
|
||||
return bookmarks;
|
||||
}
|
||||
|
||||
std::filesystem::path viewerBookmarksFile()
|
||||
{
|
||||
return dataDirectory()/L"files-viewer-bookmarks.json";
|
||||
}
|
||||
|
||||
enum class BookmarkChange { upsert, rename, remove };
|
||||
|
||||
void changeViewerBookmark(const ViewerBookmark &bookmark,BookmarkChange change)
|
||||
{
|
||||
struct Lock
|
||||
{
|
||||
HANDLE handle=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.ViewerBookmarks");
|
||||
bool owned{};
|
||||
~Lock()
|
||||
{
|
||||
if(owned) ReleaseMutex(handle);
|
||||
if(handle) CloseHandle(handle);
|
||||
}
|
||||
} lock;
|
||||
if(!lock.handle) throw std::runtime_error("Could not open Viewer bookmark storage.");
|
||||
const auto wait=WaitForSingleObject(lock.handle,100);
|
||||
lock.owned=wait==WAIT_OBJECT_0 || wait==WAIT_ABANDONED;
|
||||
if(!lock.owned) throw std::runtime_error("Viewer bookmark storage is busy.");
|
||||
const auto file=viewerBookmarksFile();
|
||||
auto bookmarks=readViewerBookmarks(file);
|
||||
const auto existing=std::find_if(bookmarks.begin(),bookmarks.end(),[&](const auto &item) {
|
||||
return sameViewerBookmark(item,bookmark);
|
||||
});
|
||||
if(existing==bookmarks.end())
|
||||
{
|
||||
if(change!=BookmarkChange::upsert) throw std::runtime_error("This bookmark has already been removed.");
|
||||
bookmarks.push_back(bookmark);
|
||||
}
|
||||
else if(change==BookmarkChange::remove) bookmarks.erase(existing);
|
||||
else existing->name=bookmark.name;
|
||||
auto saved=nlohmann::json::array();
|
||||
for(const auto &entry:bookmarks)
|
||||
saved.push_back({{"path",utf8(entry.path.native())},{"line",entry.line},{"name",utf8(entry.name)}});
|
||||
const auto contents=saved.dump();
|
||||
if(contents.size()>2*1024*1024) throw std::runtime_error("Viewer bookmark storage is full.");
|
||||
atomicWrite(file,Bytes(contents.begin(),contents.end()));
|
||||
}
|
||||
|
||||
struct BookmarkPrompt
|
||||
{
|
||||
TextDialogs style;
|
||||
ViewerBookmark bookmark;
|
||||
bool rename{};
|
||||
};
|
||||
|
||||
constexpr int bookmarkName=535, bookmarkLine=536, bookmarkList=538, bookmarkRename=539, bookmarkRemove=540;
|
||||
|
||||
INT_PTR CALLBACK bookmarkNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
auto &prompt=*reinterpret_cast<BookmarkPrompt *>(lp);
|
||||
prompt.style.prepare(dialog);
|
||||
SetDlgItemTextW(dialog,bookmarkName,prompt.bookmark.name.c_str());
|
||||
SetDlgItemTextW(dialog,bookmarkLine,std::to_wstring(prompt.bookmark.line).c_str());
|
||||
SendDlgItemMessageW(dialog,bookmarkName,EM_SETLIMITTEXT,160,0);
|
||||
SendDlgItemMessageW(dialog,bookmarkLine,EM_SETLIMITTEXT,20,0);
|
||||
SendDlgItemMessageW(dialog,bookmarkLine,EM_SETREADONLY,prompt.rename,0);
|
||||
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
|
||||
SetFocus(GetDlgItem(dialog,bookmarkName));
|
||||
SendDlgItemMessageW(dialog,bookmarkName,EM_SETSEL,0,-1);
|
||||
return FALSE;
|
||||
}
|
||||
const auto prompt=reinterpret_cast<BookmarkPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!prompt) return FALSE;
|
||||
if(const auto painted=prompt->style.paint(dialog,message,wp,lp,prompt->rename?L" Rename bookmark ":L" Add bookmark "))
|
||||
return painted;
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
if(LOWORD(wp)==IDCANCEL) {prompt->style.finish(dialog,IDCANCEL);return TRUE;}
|
||||
if(LOWORD(wp)!=IDOK) return FALSE;
|
||||
wchar_t line[24]{};
|
||||
GetDlgItemTextW(dialog,bookmarkLine,line,static_cast<int>(std::size(line)));
|
||||
wchar_t *end=nullptr;
|
||||
errno=0;
|
||||
const auto number=std::wcstoull(line,&end,10);
|
||||
if(!number || errno==ERANGE || *end || line[0]<L'0' || line[0]>L'9')
|
||||
{
|
||||
prompt->style.message(dialog,L"Enter a positive line number.");
|
||||
SetFocus(GetDlgItem(dialog,bookmarkLine));
|
||||
return TRUE;
|
||||
}
|
||||
wchar_t name[161]{};
|
||||
GetDlgItemTextW(dialog,bookmarkName,name,static_cast<int>(std::size(name)));
|
||||
prompt->bookmark.line=number;
|
||||
prompt->bookmark.name=name;
|
||||
try {changeViewerBookmark(prompt->bookmark,prompt->rename?BookmarkChange::rename:BookmarkChange::upsert);}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
prompt->style.message(dialog,wide(error.what()).c_str());
|
||||
return TRUE;
|
||||
}
|
||||
prompt->style.finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
struct ViewerBookmarkList
|
||||
{
|
||||
TextDialogs style;
|
||||
std::filesystem::path filter;
|
||||
std::vector<ViewerBookmark> bookmarks;
|
||||
std::optional<ViewerBookmark> opening;
|
||||
};
|
||||
|
||||
void showBookmarkPath(HWND dialog,const ViewerBookmarkList &state)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,bookmarkList,LB_GETCURSEL,0,0);
|
||||
SetDlgItemTextW(dialog,541,row>=0 && static_cast<size_t>(row)<state.bookmarks.size()?
|
||||
state.bookmarks[row].path.c_str():L"No bookmarks");
|
||||
}
|
||||
|
||||
void renderBookmarkList(HWND dialog,ViewerBookmarkList &state,LRESULT oldSelection)
|
||||
{
|
||||
state.bookmarks=readViewerBookmarks(viewerBookmarksFile());
|
||||
if(!state.filter.empty()) std::erase_if(state.bookmarks,[&](const auto &item) {
|
||||
return compareBookmarkPaths(state.filter,item.path)!=0;
|
||||
});
|
||||
const auto list=GetDlgItem(dialog,bookmarkList);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
const auto dc=GetDC(list);
|
||||
HGDIOBJ oldFont{};
|
||||
if(dc)
|
||||
if(const auto font=SendMessageW(list,WM_GETFONT,0,0))
|
||||
oldFont=SelectObject(dc,reinterpret_cast<HFONT>(font));
|
||||
LONG width=0;
|
||||
for(const auto &item:state.bookmarks)
|
||||
{
|
||||
auto label=L"Line "+std::to_wstring(item.line);
|
||||
if(state.filter.empty()) label+=L" "+item.path.filename().native();
|
||||
if(!item.name.empty()) label+=L" "+item.name;
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
SIZE dimensions{};
|
||||
if(dc && GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.size()),&dimensions))
|
||||
width=std::max(width,dimensions.cx);
|
||||
}
|
||||
if(oldFont) SelectObject(dc,oldFont);
|
||||
if(dc) ReleaseDC(list,dc);
|
||||
SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0);
|
||||
const bool rows=!state.bookmarks.empty();
|
||||
if(rows) SendMessageW(list,LB_SETCURSEL,std::clamp<LRESULT>(oldSelection,0,state.bookmarks.size()-1),0);
|
||||
showBookmarkPath(dialog,state);
|
||||
for(const auto button:{IDOK,bookmarkRename,bookmarkRemove}) EnableWindow(GetDlgItem(dialog,button),rows);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK viewerBookmarkDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
auto &state=*reinterpret_cast<ViewerBookmarkList *>(lp);
|
||||
state.style.prepare(dialog);
|
||||
try {renderBookmarkList(dialog,state,0);}
|
||||
catch(const std::exception &error) {state.style.message(dialog,wide(error.what()).c_str());}
|
||||
SetFocus(GetDlgItem(dialog,state.bookmarks.empty()?IDCANCEL:bookmarkList));
|
||||
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
|
||||
return FALSE;
|
||||
}
|
||||
auto *state=reinterpret_cast<ViewerBookmarkList *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!state) return FALSE;
|
||||
if(const auto painted=state->style.paint(dialog,message,wp,lp,
|
||||
state->filter.empty()?L" All Viewer bookmarks ":L" Bookmarks in this file ")) return painted;
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
const auto id=LOWORD(wp);
|
||||
if(id==IDCANCEL) {state->style.finish(dialog,IDCANCEL);return TRUE;}
|
||||
if(id==bookmarkList && HIWORD(wp)==LBN_SELCHANGE) {showBookmarkPath(dialog,*state); return TRUE;}
|
||||
const bool open=id==IDOK || (id==bookmarkList && HIWORD(wp)==LBN_DBLCLK);
|
||||
if(!open && id!=bookmarkRename && id!=bookmarkRemove) return FALSE;
|
||||
const auto selected=SendDlgItemMessageW(dialog,bookmarkList,LB_GETCURSEL,0,0);
|
||||
if(selected<0 || static_cast<size_t>(selected)>=state->bookmarks.size()) return TRUE;
|
||||
const auto entry=state->bookmarks[selected];
|
||||
try
|
||||
{
|
||||
if(open)
|
||||
{
|
||||
const auto attr=GetFileAttributesW(entry.path.c_str());
|
||||
if(attr==INVALID_FILE_ATTRIBUTES || attr&FILE_ATTRIBUTE_DIRECTORY)
|
||||
throw std::runtime_error("The bookmarked file is unavailable.");
|
||||
state->opening=entry;
|
||||
state->style.finish(dialog,IDOK);
|
||||
}
|
||||
else if(id==bookmarkRename)
|
||||
{
|
||||
BookmarkPrompt prompt{state->style,entry,true};
|
||||
if(state->style.run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(613),dialog,bookmarkNameDialog,
|
||||
reinterpret_cast<LPARAM>(&prompt))==IDOK) renderBookmarkList(dialog,*state,selected);
|
||||
}
|
||||
else
|
||||
{
|
||||
changeViewerBookmark(entry,BookmarkChange::remove);
|
||||
renderBookmarkList(dialog,*state,selected);
|
||||
}
|
||||
}
|
||||
catch(const std::exception &error) {state->style.message(dialog,wide(error.what()).c_str());}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
std::optional<ViewerBookmark> selectViewerBookmark(HWND owner,TextDialogs style,std::filesystem::path filter={})
|
||||
{
|
||||
ViewerBookmarkList state{style,std::move(filter)};
|
||||
if(style.run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(614),owner,viewerBookmarkDialog,
|
||||
reinterpret_cast<LPARAM>(&state))==IDOK) return std::move(state.opening);
|
||||
return {};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline bool validFileName(std::wstring_view name)
|
||||
{
|
||||
return !name.empty() && name.back()!=L'.' && name.back()!=L' ' &&
|
||||
name.find_first_of(L"<>:\"/\\|?*")==name.npos &&
|
||||
std::none_of(name.begin(),name.end(),[](wchar_t ch){return ch<32;});
|
||||
}
|
||||
|
||||
inline bool validWindowsFileName(std::wstring_view name)
|
||||
{
|
||||
if(!validFileName(name)) return false;
|
||||
auto stem=name.substr(0,name.find(L'.'));
|
||||
stem=stem.substr(0,stem.find_last_not_of(L' ')+1);
|
||||
const auto equals=[&](std::wstring_view device)
|
||||
{
|
||||
return CompareStringOrdinal(stem.data(),static_cast<int>(stem.size()),
|
||||
device.data(),static_cast<int>(device.size()),TRUE)==CSTR_EQUAL;
|
||||
};
|
||||
for(const auto device:{L"CON",L"PRN",L"AUX",L"NUL",L"CONIN$",L"CONOUT$"})
|
||||
if(equals(device)) return false;
|
||||
return stem.size()!=4 || std::wstring_view(L"123456789¹²³").find(stem.back())==name.npos ||
|
||||
(CompareStringOrdinal(stem.data(),3,L"COM",3,TRUE)!=CSTR_EQUAL &&
|
||||
CompareStringOrdinal(stem.data(),3,L"LPT",3,TRUE)!=CSTR_EQUAL);
|
||||
}
|
||||
|
||||
template<class Visitor>
|
||||
DWORD visitDirectoryRecords(HANDLE directory,const Visitor &visit)
|
||||
{
|
||||
alignas(FILE_ID_BOTH_DIR_INFO) std::array<unsigned char,64*1024> buffer;
|
||||
constexpr auto header=offsetof(FILE_ID_BOTH_DIR_INFO,FileName);
|
||||
while(GetFileInformationByHandleEx(directory,FileIdBothDirectoryInfo,buffer.data(),
|
||||
static_cast<DWORD>(buffer.size())))
|
||||
{
|
||||
for(size_t offset=0;;)
|
||||
{
|
||||
const auto remaining=buffer.size()-offset;
|
||||
if(remaining<header) return ERROR_INVALID_DATA;
|
||||
const auto &entry=*reinterpret_cast<const FILE_ID_BOTH_DIR_INFO *>(buffer.data()+offset);
|
||||
const auto size=entry.NextEntryOffset?entry.NextEntryOffset:remaining;
|
||||
if(size>remaining || size<header || entry.FileNameLength>size-header ||
|
||||
entry.FileNameLength%sizeof(wchar_t)) return ERROR_INVALID_DATA;
|
||||
const std::wstring_view name(entry.FileName,entry.FileNameLength/sizeof(wchar_t));
|
||||
if(name.empty() || name.find_first_of(L"/\\:")!=name.npos || name.find(L'\0')!=name.npos)
|
||||
return ERROR_INVALID_DATA;
|
||||
if(name!=L"." && name!=L"..")
|
||||
{
|
||||
const auto result=visit(entry,name);
|
||||
if(result!=ERROR_SUCCESS) return result;
|
||||
}
|
||||
if(!entry.NextEntryOffset) break;
|
||||
if(size%alignof(FILE_ID_BOTH_DIR_INFO)) return ERROR_INVALID_DATA;
|
||||
offset+=size;
|
||||
}
|
||||
}
|
||||
const auto error=GetLastError();
|
||||
return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement,
|
||||
const std::filesystem::path &backup)
|
||||
{
|
||||
if(ReplaceFileW(original.c_str(),replacement.c_str(),backup.c_str(),0,nullptr,nullptr)) return ERROR_SUCCESS;
|
||||
const auto error=GetLastError();
|
||||
if(GetFileAttributesW(backup.c_str())!=INVALID_FILE_ATTRIBUTES &&
|
||||
!MoveFileExW(backup.c_str(),original.c_str(),MOVEFILE_WRITE_THROUGH))
|
||||
{
|
||||
const auto location=backup.u8string();
|
||||
throw std::runtime_error("Could not restore the original file name. The original is at "+
|
||||
std::string(location.begin(),location.end()));
|
||||
}
|
||||
return error;
|
||||
}
|
||||
}
|
||||
@@ -486,6 +486,77 @@ Clip textClip(const std::wstring &text)
|
||||
memcpy(f.data.data(), text.c_str(), f.data.size());
|
||||
return Clip{{std::move(f)}};
|
||||
}
|
||||
|
||||
Clip fileDropClip(std::span<const std::filesystem::path> paths)
|
||||
{
|
||||
std::wstring names;
|
||||
for(const auto &path:paths)
|
||||
{
|
||||
if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos)
|
||||
throw std::invalid_argument("A file clipboard path must be absolute and contain no nulls.");
|
||||
names+=path.native();
|
||||
names+=L'\0';
|
||||
}
|
||||
if(paths.empty()) names+=L'\0';
|
||||
names+=L'\0';
|
||||
DROPFILES header{};
|
||||
header.pFiles=sizeof(header);
|
||||
header.fWide=TRUE;
|
||||
Format files{CF_HDROP,{},Bytes(sizeof(header)+names.size()*sizeof(wchar_t))};
|
||||
memcpy(files.data.data(),&header,sizeof(header));
|
||||
memcpy(files.data.data()+sizeof(header),names.data(),names.size()*sizeof(wchar_t));
|
||||
const DWORD effect=DROPEFFECT_COPY;
|
||||
Format preferred{0,CFSTR_PREFERREDDROPEFFECT,Bytes(sizeof(effect))};
|
||||
memcpy(preferred.data.data(),&effect,sizeof(effect));
|
||||
return Clip{{std::move(files),std::move(preferred)}};
|
||||
}
|
||||
|
||||
std::vector<std::filesystem::path> fileDropPaths(HANDLE medium)
|
||||
{
|
||||
const auto size=medium?GlobalSize(medium):0;
|
||||
if(size<sizeof(DROPFILES)) return {};
|
||||
const auto bytes=static_cast<const unsigned char *>(GlobalLock(medium));
|
||||
if(!bytes) return {};
|
||||
DROPFILES header{};
|
||||
memcpy(&header,bytes,sizeof(header));
|
||||
bool terminated=false;
|
||||
if(header.pFiles>=sizeof(header) && header.pFiles<size)
|
||||
{
|
||||
const auto start=bytes+header.pFiles;
|
||||
if(!header.fWide)
|
||||
terminated=std::search_n(start,bytes+size,2,static_cast<unsigned char>(0))!=bytes+size;
|
||||
else if(header.pFiles%alignof(wchar_t)==0)
|
||||
{
|
||||
const auto names=reinterpret_cast<const wchar_t *>(start);
|
||||
const auto end=names+(size-header.pFiles)/sizeof(wchar_t);
|
||||
terminated=std::search_n(names,end,2,L'\0')!=end;
|
||||
}
|
||||
}
|
||||
GlobalUnlock(medium);
|
||||
if(!terminated) return {};
|
||||
const auto drop=reinterpret_cast<HDROP>(medium);
|
||||
const UINT count=DragQueryFileW(drop,UINT(-1),nullptr,0);
|
||||
std::vector<std::filesystem::path> paths;
|
||||
std::set<std::filesystem::path> seen;
|
||||
for(UINT index=0;index<count;++index)
|
||||
{
|
||||
const UINT length=DragQueryFileW(drop,index,nullptr,0);
|
||||
if(!length || length>32767) continue;
|
||||
std::wstring name(length+1,L'\0');
|
||||
if(DragQueryFileW(drop,index,name.data(),length+1)!=length) continue;
|
||||
name.resize(length);
|
||||
auto path=std::filesystem::path(std::move(name)).lexically_normal();
|
||||
if(path.is_absolute() && seen.insert(path).second) paths.push_back(std::move(path));
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
std::vector<std::filesystem::path> readClipboardFilePaths(HWND window)
|
||||
{
|
||||
ClipboardLock lock(window);
|
||||
return fileDropPaths(GetClipboardData(CF_HDROP));
|
||||
}
|
||||
|
||||
std::wstring Clip::text() const
|
||||
{
|
||||
for (const auto &f : formats)
|
||||
|
||||
@@ -59,6 +59,9 @@ Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024,
|
||||
DWORD writeClipboard(HWND, const Clip &);
|
||||
DWORD writeClipboardGuarded(HWND, const Clip &, std::optional<DWORD> expected);
|
||||
Clip textClip(const std::wstring &);
|
||||
Clip fileDropClip(std::span<const std::filesystem::path> paths);
|
||||
std::vector<std::filesystem::path> fileDropPaths(HANDLE medium);
|
||||
std::vector<std::filesystem::path> readClipboardFilePaths(HWND window);
|
||||
bool chord(WORD key, UINT modifiers = 0);
|
||||
bool chord(std::span<const WORD> keys);
|
||||
struct SystemVolume
|
||||
|
||||
@@ -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.' }
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
#include "files_archive.h"
|
||||
#include <windows.h>
|
||||
#include <archive.h>
|
||||
#include <archive_entry.h>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace
|
||||
{
|
||||
namespace fs=std::filesystem;
|
||||
using namespace ks::files;
|
||||
|
||||
void expect(bool success,const char *message)
|
||||
{
|
||||
if(!success) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
struct Temp
|
||||
{
|
||||
fs::path path;
|
||||
Temp()
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
expect(SUCCEEDED(CoCreateGuid(&id)) && StringFromGUID2(id,name,40),"temporary path");
|
||||
path=fs::temp_directory_path()/(L"ks-test-archive-"+std::wstring(name));
|
||||
expect(fs::create_directory(path),"temporary directory");
|
||||
}
|
||||
~Temp()
|
||||
{
|
||||
std::error_code error;
|
||||
fs::remove_all(path,error);
|
||||
}
|
||||
};
|
||||
|
||||
struct Entry
|
||||
{
|
||||
const char *name;
|
||||
std::string_view data{};
|
||||
unsigned type=AE_IFREG;
|
||||
};
|
||||
|
||||
void makeArchive(const fs::path &file,const std::vector<Entry> &members,bool sevenZip=false,bool encrypted=false)
|
||||
{
|
||||
std::unique_ptr<archive,decltype(&archive_write_free)> writer(archive_write_new(),archive_write_free);
|
||||
expect(writer!=nullptr,"archive writer");
|
||||
auto *out=writer.get();
|
||||
expect((sevenZip?archive_write_set_format_7zip(out):archive_write_set_format_zip(out))==ARCHIVE_OK,"archive format");
|
||||
if(sevenZip) expect(archive_write_set_options(out,"compression=lzma2")==ARCHIVE_OK,"LZMA2 format");
|
||||
else expect(archive_write_set_options(out,"hdrcharset=UTF-8")==ARCHIVE_OK,"UTF-8 ZIP names");
|
||||
if(encrypted)
|
||||
{
|
||||
expect(archive_write_set_options(out,"encryption=aes256")==ARCHIVE_OK,"encrypted ZIP");
|
||||
expect(archive_write_set_passphrase(out,"fixture-only")==ARCHIVE_OK,"fixture passphrase");
|
||||
}
|
||||
expect(archive_write_open_filename_w(out,file.c_str())==ARCHIVE_OK,"archive output");
|
||||
for(const auto &item:members)
|
||||
{
|
||||
std::unique_ptr<archive_entry,decltype(&archive_entry_free)> entry(archive_entry_new(),archive_entry_free);
|
||||
const int length=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,item.name,-1,nullptr,0);
|
||||
expect(length>0,"UTF-8 fixture filename");
|
||||
std::wstring name(length,L'\0');
|
||||
MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,item.name,-1,name.data(),length);
|
||||
archive_entry_copy_pathname_w(entry.get(),name.c_str());
|
||||
archive_entry_set_filetype(entry.get(),item.type);
|
||||
archive_entry_set_perm(entry.get(),item.type==AE_IFDIR?0755:0644);
|
||||
archive_entry_set_size(entry.get(),item.data.size());
|
||||
archive_entry_set_mtime(entry.get(),1738400000,0);
|
||||
if(item.type==AE_IFLNK) archive_entry_set_symlink(entry.get(),"../outside.txt");
|
||||
if(archive_write_header(out,entry.get())!=ARCHIVE_OK)
|
||||
throw std::runtime_error(std::string(item.name)+": "+archive_error_string(out));
|
||||
if(!item.data.empty())
|
||||
expect(archive_write_data(out,item.data.data(),item.data.size())==static_cast<la_ssize_t>(item.data.size()),
|
||||
"archive member contents");
|
||||
}
|
||||
expect(archive_write_close(out)==ARCHIVE_OK,"close archive");
|
||||
}
|
||||
|
||||
std::string contents(const fs::path &file)
|
||||
{
|
||||
std::ifstream in(file,std::ios::binary);
|
||||
return {std::istreambuf_iterator<char>(in),std::istreambuf_iterator<char>()};
|
||||
}
|
||||
|
||||
template<class Operation>
|
||||
void expectError(const Operation &operation,std::string_view word)
|
||||
{
|
||||
try {operation();}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
expect(std::string_view(error.what()).find(word)!=std::string_view::npos,error.what());
|
||||
return;
|
||||
}
|
||||
throw std::runtime_error("operation unexpectedly succeeded");
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try
|
||||
{
|
||||
Temp temp;
|
||||
for(const bool sevenZip:{false,true})
|
||||
{
|
||||
const auto file=temp.path/(sevenZip?L"каталог.7z":L"каталог.zip");
|
||||
const std::string data(1024*128,'a');
|
||||
makeArchive(file,{{"folder/sub/дані.txt",data},{"folder/empty/",{},AE_IFDIR},{"other.txt","skip"}},sevenZip);
|
||||
const auto entries=readArchive(file,{});
|
||||
expect(entries.size()==5 && entries.at(L"folder").directory && entries.at(L"folder\\sub").directory,
|
||||
"implicit directories in archive index");
|
||||
const auto staged=temp.path/(sevenZip?L"7z-out":L"zip-out");
|
||||
expect(fs::create_directory(staged),"extraction staging");
|
||||
extractArchiveSelection(file,L"folder",{L"folder\\sub",L"folder\\empty"},staged,{});
|
||||
expect(contents(staged/L"sub"/L"дані.txt")==data && fs::is_empty(staged/L"empty") &&
|
||||
!fs::exists(staged/L"other.txt"),"selective extraction");
|
||||
const auto fromRoot=staged/L"from-root";
|
||||
expect(fs::create_directory(fromRoot),"root extraction staging");
|
||||
extractArchiveSelection(file,{},{L"folder"},fromRoot,{});
|
||||
expect(contents(fromRoot/L"folder"/L"sub"/L"дані.txt")==data,"extract directory from archive root");
|
||||
const auto viewer=staged/L"content";
|
||||
const auto member=readArchiveMember(file,L"folder\\sub\\дані.txt",viewer,data.size(),{});
|
||||
expect(contents(viewer)==data && member.size==data.size() && member.modified!=0,"viewer stream and metadata");
|
||||
expectError([&]{readArchiveMember(file,L"folder\\sub\\дані.txt",staged/L"oversize",1,{});},"too large");
|
||||
}
|
||||
const auto protectedZip=temp.path/L"protected.zip";
|
||||
makeArchive(protectedZip,{{"protected.txt","secret"}},false,true);
|
||||
expect(readArchive(protectedZip,{}).at("protected.txt").encrypted,"password flag");
|
||||
expectError([&]{readArchiveMember(protectedZip,"protected.txt",temp.path/L"protected.txt",512,{});},"password");
|
||||
const auto unsafe=temp.path/L"unsafe.zip";
|
||||
for(const auto bad:{"../escape.txt","nested/../../escape.txt","C:/escape.txt","a/escape.txt:stream",
|
||||
"//server/escape.txt","nested/COM1.txt","nested/a. ","nested//escape.txt"})
|
||||
{
|
||||
makeArchive(unsafe,{{"safe.txt","safe"},{bad,"bad"}});
|
||||
expectError([&]{readArchive(unsafe,{});},"unsafe");
|
||||
}
|
||||
makeArchive(unsafe,{{"Same/a.txt","first"},{"same/b.txt","second"}});
|
||||
expectError([&]{readArchive(unsafe,{});},"conflicting");
|
||||
makeArchive(unsafe,{{"link",{},AE_IFLNK}});
|
||||
expectError([&]{readArchive(unsafe,{});},"link");
|
||||
expect(!fs::exists(temp.path/L"escape.txt") && !fs::exists(temp.path/L"protected.txt"),"no unsafe output");
|
||||
const auto source=temp.path/L"source", update=temp.path/L"update";
|
||||
fs::create_directories(source/L"empty");
|
||||
fs::create_directories(update);
|
||||
const auto item=source/L"дані.txt", replacement=update/L"дані.txt", added=update/L"new.txt";
|
||||
std::ofstream(item,std::ios::binary)<<"initial";
|
||||
std::ofstream(source/L"keep.txt",std::ios::binary)<<std::string(32*1024,'k');
|
||||
std::ofstream(replacement,std::ios::binary)<<"updated";
|
||||
std::ofstream(added,std::ios::binary)<<std::string(128*1024,'z');
|
||||
for(const auto extension:{L".zip",L".7z"})
|
||||
{
|
||||
const auto archive=temp.path/(std::wstring(L"write")+extension);
|
||||
writeArchive(archive,ArchiveWriteMode::create,{}, {source},{});
|
||||
SYSTEMTIME fixtureDate{2003,3,0,5};
|
||||
FILETIME creation{};
|
||||
expect(SystemTimeToFileTime(&fixtureDate,&creation),"fixture creation time");
|
||||
const HANDLE handle=CreateFileW(archive.c_str(),FILE_WRITE_ATTRIBUTES,FILE_SHARE_READ,
|
||||
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
expect(handle!=INVALID_HANDLE_VALUE,"open fixture archive attributes");
|
||||
const bool timeSet=SetFileTime(handle,&creation,nullptr,nullptr)!=0;
|
||||
CloseHandle(handle);
|
||||
expect(timeSet,"set fixture creation time");
|
||||
WIN32_FILE_ATTRIBUTE_DATA attributes{};
|
||||
expect(GetFileAttributesExW(archive.c_str(),GetFileExInfoStandard,&attributes),"read archive attributes");
|
||||
const auto creationBefore=attributes.ftCreationTime;
|
||||
const auto index=readArchive(archive,{});
|
||||
expect(index.at(L"source\\дані.txt").size==7 && index.at(L"source\\empty").directory,"archive creation");
|
||||
const auto before=contents(archive);
|
||||
bool canceled=false;
|
||||
try
|
||||
{
|
||||
writeArchive(archive,ArchiveWriteMode::update,L"source",{replacement,added},
|
||||
[](uint64_t done,uint64_t){return done==0;});
|
||||
}
|
||||
catch(const std::system_error &error) {canceled=error.code().value()==ERROR_CANCELLED;}
|
||||
expect(canceled && contents(archive)==before,"canceled update preserved original");
|
||||
expectError([&]{
|
||||
writeArchive(archive,ArchiveWriteMode::update,{}, {archive},{});
|
||||
},"contain itself");
|
||||
expect(contents(archive)==before,"invalid update preserved original");
|
||||
bool altered=false;
|
||||
expectError([&]{
|
||||
writeArchive(archive,ArchiveWriteMode::update,L"source",{replacement},[&](uint64_t done,uint64_t)
|
||||
{
|
||||
if(done && !altered)
|
||||
{
|
||||
altered=true;
|
||||
std::ofstream(replacement,std::ios::binary)<<"changed during rewrite";
|
||||
}
|
||||
return true;
|
||||
});
|
||||
},"changed before");
|
||||
expect(altered && contents(archive)==before,"failed rewrite preserved original");
|
||||
std::ofstream(replacement,std::ios::binary)<<"updated";
|
||||
writeArchive(archive,ArchiveWriteMode::update,L"source",{replacement,added},{});
|
||||
expect(GetFileAttributesExW(archive.c_str(),GetFileExInfoStandard,&attributes) &&
|
||||
CompareFileTime(&creationBefore,&attributes.ftCreationTime)==0,"update preserved creation time");
|
||||
const auto changed=readArchive(archive,{});
|
||||
expect(changed.at(L"source\\new.txt").size==128*1024 && changed.at(L"source\\empty").directory,
|
||||
"update preserved folder and added entry");
|
||||
const auto dest=temp.path/(std::wstring(L"updated")+extension);
|
||||
readArchiveMember(archive,L"source\\дані.txt",dest,100,{});
|
||||
expect(contents(dest)=="updated","update replaced matching file");
|
||||
}
|
||||
const auto encryptedBefore=contents(protectedZip);
|
||||
expectError([&]{writeArchive(protectedZip,ArchiveWriteMode::update,{}, {added},{});},"Password-protected");
|
||||
expect(contents(protectedZip)==encryptedBefore,"encrypted update preserved original");
|
||||
expectError([&]{writeArchive(temp.path/L"wrong.rar",ArchiveWriteMode::create,{}, {item},{});},"ZIP and 7z");
|
||||
const auto primary=temp.path/L"primary.zip", competing=temp.path/L"competing.zip";
|
||||
bool attempted=false;
|
||||
writeArchive(primary,ArchiveWriteMode::create,{}, {added},[&](uint64_t done,uint64_t)
|
||||
{
|
||||
if(done && !attempted)
|
||||
{
|
||||
attempted=true;
|
||||
expectError([&]{writeArchive(competing,ArchiveWriteMode::create,{}, {item},{});},"archive operation");
|
||||
}
|
||||
return true;
|
||||
});
|
||||
expect(attempted && fs::exists(primary) && !fs::exists(competing),"concurrent archive writes are serialized");
|
||||
const auto unchanged=contents(primary);
|
||||
expectError([&]{writeArchive(primary,ArchiveWriteMode::create,{}, {item},{});},"already exists");
|
||||
expect(contents(primary)==unchanged,"creating an existing archive preserved the original");
|
||||
return 0;
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
std::cerr<<error.what()<<'\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class FilesCommandsUi {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Point { public int X, Y; }
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect rect);
|
||||
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags);
|
||||
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr window, int command);
|
||||
[DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[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")]
|
||||
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(18, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(18, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-For([string]$Name, [scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 50; ++$attempt) {
|
||||
$value = & $Condition
|
||||
if ($value) { return $value }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
throw "Timed out waiting for $Name."
|
||||
}
|
||||
|
||||
function Invoke-FilesCommand([IntPtr]$Window, [string]$LabelPattern) {
|
||||
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr]132, [IntPtr]::Zero)
|
||||
$picker = [FilesCommandsUi]::GetDlgItem($Window, 121)
|
||||
[void](Wait-For 'the Commands menu' { [FilesCommandsUi]::IsWindowVisible($picker) })
|
||||
$count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
|
||||
for ($row = 0; $row -lt $count; ++$row) {
|
||||
$label = [Text.StringBuilder]::new(128)
|
||||
[void][FilesCommandsUi]::Read($picker, 393, [IntPtr]$row, $label)
|
||||
if ($label.ToString() -like $LabelPattern) {
|
||||
[void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero)
|
||||
[void][FilesCommandsUi]::Post($Window, 273, [IntPtr](0x20000 + 121), $picker)
|
||||
return
|
||||
}
|
||||
}
|
||||
throw "Missing Files command matching $LabelPattern."
|
||||
}
|
||||
@@ -2,53 +2,11 @@ param([Parameter(Mandatory)][string]$Executable)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class ComparisonSplitterUi {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Rect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct Point { public int X, Y; }
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid);
|
||||
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
|
||||
[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", 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")]
|
||||
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(18, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(18, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-For([string]$Name, [scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 50; ++$attempt) {
|
||||
$value = & $Condition
|
||||
if ($value) { return $value }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
throw "Timed out waiting for $Name."
|
||||
}
|
||||
. "$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()) {
|
||||
@@ -57,8 +15,26 @@ foreach ($name in $names) {
|
||||
}
|
||||
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
|
||||
$root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N'))
|
||||
$dpi = [ComparisonSplitterUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$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'
|
||||
@@ -68,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)
|
||||
}
|
||||
|
||||
@@ -78,59 +55,44 @@ try {
|
||||
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
|
||||
}
|
||||
foreach ($id in 102, 103) {
|
||||
$panel = [ComparisonSplitterUi]::GetDlgItem($main, $id)
|
||||
$panel = [FilesCommandsUi]::GetDlgItem($main, $id)
|
||||
[void](Wait-For 'the test file in the panel' {
|
||||
[ComparisonSplitterUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2
|
||||
[FilesCommandsUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2
|
||||
})
|
||||
[void][ComparisonSplitterUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
|
||||
[void][FilesCommandsUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
|
||||
}
|
||||
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr]132, [IntPtr]::Zero)
|
||||
$picker = [ComparisonSplitterUi]::GetDlgItem($main, 121)
|
||||
[void](Wait-For 'the Commands menu' { [ComparisonSplitterUi]::IsWindowVisible($picker) })
|
||||
$row = -1
|
||||
$count = [ComparisonSplitterUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64()
|
||||
for ($i = 0; $i -lt $count; ++$i) {
|
||||
$label = [Text.StringBuilder]::new(128)
|
||||
[void][ComparisonSplitterUi]::Read($picker, 393, [IntPtr]$i, $label)
|
||||
if ($label.ToString() -like 'Compare files*') { $row = $i; break }
|
||||
}
|
||||
if ($row -lt 0) { throw 'Missing Compare files command.' }
|
||||
[void][ComparisonSplitterUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero)
|
||||
[void][ComparisonSplitterUi]::Post($main, 273, [IntPtr](0x20000 + 121), $picker)
|
||||
$list = Wait-For 'the foreground comparison list' {
|
||||
Invoke-FilesCommand $main 'Compare files*'
|
||||
$comparison = Wait-For 'the rendered comparison window' {
|
||||
$dialog = [IntPtr]::Zero
|
||||
while (($dialog = [ComparisonSplitterUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
|
||||
while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
|
||||
[uint32]$ownerPid = 0
|
||||
[void][ComparisonSplitterUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
|
||||
[void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
|
||||
if ($ownerPid -ne $process.Id) { continue }
|
||||
$control = [ComparisonSplitterUi]::GetDlgItem($dialog, 402)
|
||||
if ([ComparisonSplitterUi]::IsWindowVisible($control) -and [ComparisonSplitterUi]::Activate($dialog)) {
|
||||
return $control
|
||||
$control = [FilesCommandsUi]::GetDlgItem($dialog, 402)
|
||||
if ([FilesCommandsUi]::IsWindowVisible($control)) {
|
||||
return $dialog
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$bounds = [ComparisonSplitterUi+Rect]::new()
|
||||
[void][ComparisonSplitterUi]::GetClientRect($list, [ref]$bounds)
|
||||
$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][ComparisonSplitterUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
|
||||
for ($x = $middle + 5; $x -lt $destination; $x += 5) {
|
||||
[void][ComparisonSplitterUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x))
|
||||
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
[void][FilesCommandsUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle))
|
||||
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][ComparisonSplitterUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
|
||||
[void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
$origin = [ComparisonSplitterUi+Point]::new()
|
||||
[void][ComparisonSplitterUi]::ClientToScreen($list, [ref]$origin)
|
||||
$bitmap = [Drawing.Bitmap]::new($bounds.Right, 1)
|
||||
[void][FilesCommandsUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
|
||||
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
|
||||
$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
|
||||
@@ -138,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) {
|
||||
@@ -146,7 +132,7 @@ try {
|
||||
else { $preferences.DeleteValue($name, $false) }
|
||||
}
|
||||
$preferences.Dispose()
|
||||
if ($dpi) { [void][ComparisonSplitterUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
if (Test-Path -LiteralPath $root) {
|
||||
$resolved = (Resolve-Path -LiteralPath $root).Path
|
||||
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-files-splitter-*') {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
#include "files_image_decode.h"
|
||||
#include <windows.h>
|
||||
#include <wincodec.h>
|
||||
#include <webp/encode.h>
|
||||
#include <array>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace
|
||||
{
|
||||
namespace fs=std::filesystem;
|
||||
using namespace ks::files;
|
||||
|
||||
void expect(bool condition,const char *message)
|
||||
{
|
||||
if(!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
template<class T>
|
||||
struct Com
|
||||
{
|
||||
T *value{};
|
||||
~Com(){if(value) value->Release();}
|
||||
T *operator->() const{return value;}
|
||||
};
|
||||
|
||||
void checked(HRESULT result)
|
||||
{
|
||||
expect(SUCCEEDED(result),"WIC fixture encoding failed.");
|
||||
}
|
||||
|
||||
void encodeNative(const fs::path &path,REFGUID container)
|
||||
{
|
||||
Com<IWICImagingFactory> factory;
|
||||
checked(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
|
||||
Com<IWICStream> stream;
|
||||
checked(factory->CreateStream(&stream.value));
|
||||
checked(stream->InitializeFromFilename(path.c_str(),GENERIC_WRITE));
|
||||
Com<IWICBitmapEncoder> encoder;
|
||||
checked(factory->CreateEncoder(container,nullptr,&encoder.value));
|
||||
checked(encoder->Initialize(stream.value,WICBitmapEncoderNoCache));
|
||||
Com<IWICBitmapFrameEncode> frame;
|
||||
checked(encoder->CreateNewFrame(&frame.value,nullptr));
|
||||
checked(frame->Initialize(nullptr));
|
||||
checked(frame->SetSize(8,6));
|
||||
auto pixelFormat=GUID_WICPixelFormat24bppBGR;
|
||||
checked(frame->SetPixelFormat(&pixelFormat));
|
||||
expect(pixelFormat==GUID_WICPixelFormat24bppBGR,"fixture pixel format");
|
||||
std::array<BYTE,8*6*3> pixels{};
|
||||
for(size_t i=0;i<pixels.size();i+=3)
|
||||
{
|
||||
pixels[i]=18;
|
||||
pixels[i+1]=90;
|
||||
pixels[i+2]=170;
|
||||
}
|
||||
checked(frame->WritePixels(6,8*3,pixels.size(),pixels.data()));
|
||||
checked(frame->Commit());
|
||||
checked(encoder->Commit());
|
||||
}
|
||||
|
||||
struct Temp
|
||||
{
|
||||
fs::path path;
|
||||
Temp()
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
expect(SUCCEEDED(CoCreateGuid(&id)) && StringFromGUID2(id,name,40),"temporary file prefix");
|
||||
path=fs::temp_directory_path()/(L"ks-test-image-"+std::wstring(name));
|
||||
expect(fs::create_directory(path),"temporary image directory");
|
||||
}
|
||||
~Temp(){std::error_code error; fs::remove_all(path,error);}
|
||||
};
|
||||
|
||||
void expectDecodeFailure(const fs::path &file,std::string_view text)
|
||||
{
|
||||
try {decodeImage(file,file);}
|
||||
catch(const std::runtime_error &e)
|
||||
{
|
||||
expect(std::string_view(e.what()).find(text)!=std::string_view::npos,e.what());
|
||||
return;
|
||||
}
|
||||
throw std::runtime_error("invalid image was decoded");
|
||||
}
|
||||
|
||||
std::vector<uint8_t> animatedWebp(const uint8_t *encoded,size_t size)
|
||||
{
|
||||
expect(size>12,"WebP fixture RIFF body");
|
||||
std::vector<uint8_t> bytes{'R','I','F','F',0,0,0,0,'W','E','B','P',
|
||||
'V','P','8','X',10,0,0,0,0x12,0,0,0,0,0,0,0,0,0,
|
||||
'A','N','I','M',6,0,0,0,0,0,0,0,0,0,
|
||||
'A','N','M','F',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,2};
|
||||
bytes.insert(bytes.end(),encoded+12,encoded+size);
|
||||
const auto storeSize=[&](size_t offset,size_t value) {
|
||||
for(unsigned i=0;i<4;++i) bytes[offset+i]=static_cast<uint8_t>(value>>(8*i));
|
||||
};
|
||||
storeSize(4,bytes.size()-8);
|
||||
storeSize(48,16+size-12);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
const auto apartment=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
|
||||
int result=0;
|
||||
try
|
||||
{
|
||||
expect(SUCCEEDED(apartment),"initialize COM");
|
||||
Temp temp;
|
||||
for(const auto &[name,container]:std::array{
|
||||
std::pair{L"знімок.PNG",&GUID_ContainerFormatPng},
|
||||
std::pair{L"picture.jpeg",&GUID_ContainerFormatJpeg},
|
||||
std::pair{L"picture.bmp",&GUID_ContainerFormatBmp}})
|
||||
{
|
||||
const auto path=temp.path/name;
|
||||
expect(isImagePath(path),"supported native extension");
|
||||
encodeNative(path,*container);
|
||||
const auto decoded=decodeImage(path,path);
|
||||
expect(decoded.width==8 && decoded.height==6 && decoded.pixels.size()==48,"native image dimensions");
|
||||
const auto first=decoded.pixels.front();
|
||||
expect((first>>24)==255 && ((first>>16)&255)>150,"native image color and opacity");
|
||||
}
|
||||
const auto gif=temp.path/L"picture.gif";
|
||||
constexpr unsigned char gifData[]{0x47,0x49,0x46,0x38,0x39,0x61,1,0,1,0,0x80,0,0,
|
||||
0,0,0,255,255,255,0x2c,0,0,0,0,1,0,1,0,0,2,2,0x44,1,0,0x3b};
|
||||
std::ofstream(gif,std::ios::binary).write(reinterpret_cast<const char *>(gifData),sizeof(gifData));
|
||||
const auto gifImage=decodeImage(gif,gif);
|
||||
expect(gifImage.width==1 && gifImage.height==1 && gifImage.pixels.size()==1,"GIF first frame");
|
||||
const auto webp=temp.path/L"picture.webp";
|
||||
const uint8_t pixel[]{12,84,200,128};
|
||||
uint8_t *encoded=nullptr;
|
||||
const auto length=WebPEncodeLosslessBGRA(pixel,1,1,4,&encoded);
|
||||
expect(length>0,"WebP fixture");
|
||||
std::ofstream(webp,std::ios::binary).write(reinterpret_cast<const char *>(encoded),length);
|
||||
auto animation=animatedWebp(encoded,length);
|
||||
WebPFree(encoded);
|
||||
const auto webpImage=decodeImage(webp,webp);
|
||||
expect(webpImage.width==1 && webpImage.height==1 && webpImage.pixels.size()==1,"WebP dimensions");
|
||||
const auto color=webpImage.pixels.front();
|
||||
expect((color>>24)==128 && ((color>>16)&255)>=99 && ((color>>16)&255)<=101,"WebP premultiplied alpha");
|
||||
const auto animated=temp.path/L"animated.webp";
|
||||
std::ofstream(animated,std::ios::binary).write(reinterpret_cast<const char *>(animation.data()),animation.size());
|
||||
const auto firstFrame=decodeImage(animated,animated);
|
||||
expect(firstFrame.width==1 && firstFrame.height==1 && firstFrame.pixels.front()==color,"animated WebP first frame");
|
||||
const auto hugeCanvas=temp.path/L"oversized-canvas.webp";
|
||||
animation[24]=0x1f;
|
||||
animation[25]=0x4e; // 20000 pixels, encoded as width minus one.
|
||||
std::ofstream(hugeCanvas,std::ios::binary).write(reinterpret_cast<const char *>(animation.data()),animation.size());
|
||||
expectDecodeFailure(hugeCanvas,"too large");
|
||||
const auto corrupt=temp.path/L"corrupt.png";
|
||||
std::ofstream(corrupt,std::ios::binary)<<"not an image";
|
||||
expectDecodeFailure(corrupt,"damaged");
|
||||
const auto large=temp.path/L"huge.bmp";
|
||||
{
|
||||
std::ofstream output(large,std::ios::binary);
|
||||
output.seekp(imageSourceLimit);
|
||||
output.put('\0');
|
||||
}
|
||||
expectDecodeFailure(large,"too large");
|
||||
std::stop_source canceled;
|
||||
canceled.request_stop();
|
||||
bool stopped=false;
|
||||
try{decodeImage(webp,webp,canceled.get_token());}
|
||||
catch(const std::system_error &error){stopped=error.code().value()==ERROR_CANCELLED;}
|
||||
expect(stopped,"canceled image load");
|
||||
}
|
||||
catch(const std::exception &error){std::cerr<<error.what()<<'\n';result=1;}
|
||||
if(SUCCEEDED(apartment)) CoUninitialize();
|
||||
return result;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
param([Parameter(Mandatory)][string]$Executable)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. "$PSScriptRoot/files_commands_ui.ps1"
|
||||
|
||||
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$process = $null
|
||||
try {
|
||||
$process = Start-Process -FilePath (Resolve-Path -LiteralPath $Executable) -PassThru
|
||||
$main = Wait-For 'the Files window' {
|
||||
$process.Refresh()
|
||||
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
|
||||
}
|
||||
[void][FilesCommandsUi]::ShowWindow($main, 9)
|
||||
$width = [int](350 * [FilesCommandsUi]::GetDpiForWindow($main) / 96)
|
||||
if (![FilesCommandsUi]::SetWindowPos($main, [IntPtr]::Zero, 0, 0, $width, 0, 22)) {
|
||||
throw 'Could not narrow the Files window.'
|
||||
}
|
||||
Invoke-FilesCommand $main 'Space Analyzer'
|
||||
$dialog = Wait-For 'the visible Space Analyzer' {
|
||||
$candidate = [IntPtr]::Zero
|
||||
while (($candidate = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $candidate, '#32770', 'Space Analyzer')) -ne [IntPtr]::Zero) {
|
||||
[uint32]$owner = 0
|
||||
[void][FilesCommandsUi]::GetWindowThreadProcessId($candidate, [ref]$owner)
|
||||
if ($owner -eq $process.Id -and [FilesCommandsUi]::IsWindowVisible($candidate)) { return $candidate }
|
||||
}
|
||||
}
|
||||
|
||||
$outer = [FilesCommandsUi+Rect]::new()
|
||||
if (![FilesCommandsUi]::GetWindowRect($dialog, [ref]$outer)) { throw 'Could not measure the Space Analyzer.' }
|
||||
$previousRight = $outer.Left
|
||||
$firstLeft = 0
|
||||
$midY = 0
|
||||
foreach ($id in 492, 493, 494, 1, 2) {
|
||||
$button = [FilesCommandsUi]::GetDlgItem($dialog, $id)
|
||||
$rect = [FilesCommandsUi+Rect]::new()
|
||||
if (![FilesCommandsUi]::IsWindowVisible($button) -or ![FilesCommandsUi]::GetWindowRect($button, [ref]$rect)) {
|
||||
throw "Space Analyzer footer button $id was unavailable."
|
||||
}
|
||||
if ($rect.Left -le $previousRight -or $rect.Right -ge $outer.Right -or $rect.Bottom -ge $outer.Bottom) {
|
||||
throw "Space Analyzer footer button $id was clipped or overlapped at narrow width."
|
||||
}
|
||||
if ($id -eq 492) {
|
||||
$firstLeft = $rect.Left
|
||||
$midY = $rect.Top + $rect.Bottom
|
||||
} elseif ([Math]::Abs($midY - $rect.Top - $rect.Bottom) -gt 1) {
|
||||
throw "Space Analyzer footer button $id was outside the shared button row."
|
||||
}
|
||||
$previousRight = $rect.Right
|
||||
}
|
||||
if ([Math]::Abs(($firstLeft + $previousRight) - ($outer.Left + $outer.Right)) -gt 2) {
|
||||
throw 'Space Analyzer footer buttons were off center.'
|
||||
}
|
||||
'Verified the full and centered Space Analyzer footer at narrow width.'
|
||||
} finally {
|
||||
# End this fixture without saving its temporary window dimensions.
|
||||
if ($process -and !$process.HasExited) {
|
||||
$process.Kill()
|
||||
$process.WaitForExit()
|
||||
}
|
||||
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "files_text_document.h"
|
||||
#include "files_compare_text.h"
|
||||
|
||||
#include <objbase.h>
|
||||
#include <winioctl.h>
|
||||
@@ -140,8 +141,71 @@ void sparseFile(const fs::path &file)
|
||||
const auto index = document.pages() - 1;
|
||||
check(document.size() == offset + 4 && document.boundary(index) == offset, "Use 64-bit offsets");
|
||||
check(document.readPage(index) == "last", "Read past 4 GiB");
|
||||
const auto raw=document.readBytes(offset-2,8);
|
||||
check(raw==std::string("\0\0last",6),"Read original bytes across a sparse section beyond 4 GiB");
|
||||
check(ks::files::formatHexPage(raw,offset-2).starts_with("000000013FFFFFFE 00 00 6C 61 73 74"),
|
||||
"Format a 64-bit hex offset and embedded NULs");
|
||||
document.stage(index, "edited");
|
||||
check(document.readPage(index) == "edited", "Stage an edit past 4 GiB");
|
||||
check(document.readBytes(offset,4)=="last","Hex reads original bytes instead of staged edits");
|
||||
}
|
||||
|
||||
void hexBytes(const fs::path &file)
|
||||
{
|
||||
const std::string bytes("\xef\xbb\xbf\0A\xff\x7f\r\n",9);
|
||||
writeFile(file,bytes);
|
||||
TextDocument document(file,false);
|
||||
check(document.boundary(0)==3 && document.readBytes(0,64)==bytes,"Hex includes the original BOM");
|
||||
check(document.readBytes(9,40).empty(),"Reading at EOF returns an empty block");
|
||||
const auto text=ks::files::formatHexPage(bytes,0);
|
||||
check(text.starts_with("0000000000000000 EF BB BF 00 41 FF 7F 0D 0A") &&
|
||||
text.ends_with("|....A.... |"),"Hex and ASCII columns retain unprintable bytes and alignment");
|
||||
const std::string twoRows(17,'a');
|
||||
check(ks::files::formatHexPage(twoRows,0).find("\r\n0000000000000010 61")!=std::string::npos,
|
||||
"Hex offsets advance by the row width");
|
||||
}
|
||||
|
||||
void bookmarkedLines(const fs::path &file)
|
||||
{
|
||||
const auto longLine=std::string(TextDocument::pageBytes+32,'x');
|
||||
writeFile(file,"first\r\n"+longLine+"\r\nending\rtail\n");
|
||||
TextDocument document(file,false);
|
||||
check(document.pages()==2 && document.lineAt(1,0)==3,"Absolute line numbering at a paged boundary");
|
||||
const auto second=document.locateLine(2);
|
||||
check(second && second->page==0 && second->offset==7,"Locate an original CRLF line");
|
||||
const auto third=document.locateLine(3);
|
||||
check(third && document.readPage(third->page).substr(third->offset).starts_with("ending"),
|
||||
"Find a line after a long line and a page boundary");
|
||||
const auto fourth=document.locateLine(4);
|
||||
check(fourth && document.readPage(fourth->page).substr(fourth->offset).starts_with("tail"),
|
||||
"Locate a line after CR");
|
||||
const auto empty=document.locateLine(5);
|
||||
check(empty && document.readPage(empty->page).size()==empty->offset && !document.locateLine(6),
|
||||
"Locate the trailing empty line and reject out-of-range bookmarks");
|
||||
std::stop_source canceled;
|
||||
canceled.request_stop();
|
||||
bool rejected=false;
|
||||
try {document.locateLine(3,canceled.get_token());}
|
||||
catch(const std::system_error &error) {rejected=error.code().value()==ERROR_CANCELLED;}
|
||||
check(rejected,"Cancel a bookmark scan");
|
||||
}
|
||||
|
||||
void comparisonEdits()
|
||||
{
|
||||
using namespace ks::files;
|
||||
auto mixed=splitComparisonText(L"alpha\r\nbeta\nlast\r");
|
||||
check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Round-trip mixed line endings");
|
||||
const auto replace=replaceComparisonText(mixed,{1,1,{L"new",L"extra"},{ComparisonEnding::lf,ComparisonEnding::crlf}});
|
||||
check(mixed.joined()==L"alpha\r\nnew\nextra\r\nlast\r","Replace a block and retain the other line endings");
|
||||
replaceComparisonText(mixed,replace);
|
||||
check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Undo a block replacement");
|
||||
const auto shorten=replaceComparisonText(mixed,{3,1,{},{}});
|
||||
check(mixed.joined()==L"alpha\r\nbeta\nlast","Remove the terminating empty line");
|
||||
replaceComparisonText(mixed,shorten);
|
||||
check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Undo preserves the original trailing separator");
|
||||
auto single=splitComparisonText(L"first");
|
||||
replaceComparisonText(single,{1,0,{L"second"},{ComparisonEnding::absent}});
|
||||
check(single.joined()==L"first\r\nsecond","Use the target convention when inserting past EOF");
|
||||
}
|
||||
|
||||
void saveDraft(const fs::path &file)
|
||||
@@ -191,6 +255,9 @@ int main()
|
||||
unicodeBoundaries(fixture.directory / L"unicode.txt");
|
||||
rejectExternalReplacement(fixture.directory / L"external.txt");
|
||||
saveDraft(fixture.directory / L"created.txt");
|
||||
hexBytes(fixture.directory / L"raw.bin");
|
||||
bookmarkedLines(fixture.directory / L"bookmarks.txt");
|
||||
comparisonEdits();
|
||||
sparseFile(fixture.directory / L"5gib.log");
|
||||
std::cout << "Files text document regressions passed.\n";
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user