Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
872c03823f | ||
|
|
0c09fbdb88 | ||
|
|
50010c99ba | ||
|
|
e92984d124 | ||
|
|
6f2f1f38e2 | ||
|
|
dc4e503c84 | ||
|
|
06c35c893c | ||
|
|
74e3248434 | ||
|
|
1f4baed2ed | ||
|
|
4147ccc04a | ||
|
|
cde7dacffc | ||
|
|
f1077909ef |
No files matched your search
+29
-5
@@ -1,18 +1,20 @@
|
||||
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/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 +34,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 KSwitcherFilesImage)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
|
||||
else()
|
||||
@@ -153,6 +155,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)
|
||||
@@ -215,7 +239,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>")
|
||||
@@ -319,7 +343,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 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 .)
|
||||
|
||||
+38
-3
@@ -311,8 +311,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, активна панель не змінюється.
|
||||
@@ -390,6 +400,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 потоково записують нову копію в
|
||||
@@ -557,10 +576,18 @@ Warning і початковий фокус на No.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
- **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 показує
|
||||
останні відвідані локальні папки. Повторний візит підіймає один запис
|
||||
@@ -627,6 +654,14 @@ Warning і початковий фокус на No.
|
||||
панелі, результати пошуку й віртуальні елементи 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()
|
||||
+3
-1
@@ -12,6 +12,8 @@ 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 '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 +22,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','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.
|
||||
@@ -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"
|
||||
@@ -475,3 +499,15 @@ BEGIN
|
||||
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
|
||||
@@ -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);
|
||||
}
|
||||
@@ -807,7 +807,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 || ftpProfileList(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();
|
||||
|
||||
@@ -13,7 +13,7 @@ std::optional<POINT> panelDragStart;
|
||||
|
||||
bool localDropPanel(const Panel &panel)
|
||||
{
|
||||
return !panel.peer && !panel.ftp && !panel.findOrigin && panel.directory.is_absolute();
|
||||
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.archive && panel.directory.is_absolute();
|
||||
}
|
||||
|
||||
LRESULT panelRowAt(HWND window,POINT point,LRESULT top,LRESULT count)
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ void startFileSearch(Panel &panel,Panel::FindOptions options)
|
||||
|
||||
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;
|
||||
|
||||
@@ -145,7 +145,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 +351,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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+293
-74
@@ -27,6 +27,8 @@
|
||||
#include <winternl.h>
|
||||
#include <wininet.h>
|
||||
#include "files_terminal.h"
|
||||
#include "files_archive.h"
|
||||
#include "files_image_decode.h"
|
||||
#include "files_win32_directory.h"
|
||||
#include "files_command_completion.h"
|
||||
#include "files_text_window.h"
|
||||
@@ -53,6 +55,7 @@ using ks::lan::Json;
|
||||
using ks::lan::fileRequest;
|
||||
using ks::lan::filePath;
|
||||
using ks::lan::checkFileReply;
|
||||
using ks::files::validFileName;
|
||||
|
||||
struct FileInfo
|
||||
{
|
||||
@@ -483,6 +486,12 @@ struct DirectoryRow
|
||||
bool folder{};
|
||||
};
|
||||
|
||||
struct ArchiveLocation
|
||||
{
|
||||
fs::path file;
|
||||
std::shared_ptr<const ks::files::ArchiveEntries> entries;
|
||||
};
|
||||
|
||||
struct Panel
|
||||
{
|
||||
HWND path{}, list{}, heading{};
|
||||
@@ -490,6 +499,7 @@ struct Panel
|
||||
LocalNavigation navigation;
|
||||
std::optional<FilesPeer> peer;
|
||||
std::optional<FtpProfile> ftp;
|
||||
std::optional<ArchiveLocation> archive;
|
||||
struct DirectoryWatch
|
||||
{
|
||||
HANDLE handle=INVALID_HANDLE_VALUE;
|
||||
@@ -540,6 +550,7 @@ struct Panel
|
||||
std::optional<FtpProfile> ftp;
|
||||
std::optional<FindOptions> find;
|
||||
std::optional<size_t> navigationPosition;
|
||||
std::optional<ArchiveLocation> archive;
|
||||
};
|
||||
struct ScanResult
|
||||
{
|
||||
@@ -552,6 +563,7 @@ struct Panel
|
||||
fs::path ftpInitialDirectory;
|
||||
std::vector<DirectoryRow> ordered;
|
||||
ColumnMetadataMap columnMetadata;
|
||||
std::shared_ptr<const ks::files::ArchiveEntries> archiveEntries;
|
||||
};
|
||||
struct TreeBranch
|
||||
{
|
||||
@@ -620,11 +632,18 @@ bool hasPanelColumns(const Panel &panel)
|
||||
|
||||
std::wstring panelCaption(const Panel &panel)
|
||||
{
|
||||
if(panel.archive)
|
||||
{
|
||||
const auto display=panel.directory.lexically_relative(panel.archive->file.parent_path());
|
||||
return L"Archive · "+display.native();
|
||||
}
|
||||
return panel.findOrigin?L"Search results":panelLocation(panel);
|
||||
}
|
||||
|
||||
Panel panels[2];
|
||||
HWND quickViewWindow{};
|
||||
HWND quickImageWindow{};
|
||||
bool quickViewDisplaysImage{};
|
||||
int quickViewSource{};
|
||||
bool panelClipboardContext=true;
|
||||
void refreshQuickView(const Panel &panel);
|
||||
@@ -1560,9 +1579,14 @@ void layout(HWND window,bool activeOnly)
|
||||
{
|
||||
const int left=quickViewSource==0?middle+2:0;
|
||||
const int right=quickViewSource==0?width:middle-2;
|
||||
SetWindowPos(quickViewWindow,nullptr,left+5,4,std::max(0,right-left-10),
|
||||
std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
ShowWindow(quickViewWindow,terminalVisible?SW_HIDE:SW_SHOWNA);
|
||||
for(const auto preview:{quickViewWindow,quickImageWindow})
|
||||
{
|
||||
if(!preview) continue;
|
||||
SetWindowPos(preview,nullptr,left+5,4,std::max(0,right-left-10),
|
||||
std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
const bool current=quickViewDisplaysImage==(preview==quickImageWindow);
|
||||
ShowWindow(preview,!terminalVisible && current?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
}
|
||||
if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window);
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
|
||||
@@ -1989,7 +2013,7 @@ void copyPanelNames(HWND owner)
|
||||
|
||||
void copyPanelFiles(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(panel.peer || panel.ftp)
|
||||
if(panel.peer || panel.ftp || panel.archive)
|
||||
{
|
||||
setStatus(L"File clipboard copy requires local files.");
|
||||
return;
|
||||
@@ -2033,13 +2057,15 @@ void copyCommandLineOrPanelNames(HWND owner)
|
||||
}
|
||||
|
||||
void startFileSearch(Panel &panel,Panel::FindOptions options);
|
||||
void refreshArchive(Panel &panel);
|
||||
|
||||
void refreshPanel(Panel &panel)
|
||||
{
|
||||
cancelFolderSizes(panel);
|
||||
if(!panel.view.automaticSizes) panel.folderSizes.clear();
|
||||
updateSelectionSummary(panel);
|
||||
if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options);
|
||||
if(panel.archive) refreshArchive(panel);
|
||||
else if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options);
|
||||
else open(panel,panel.directory,false);
|
||||
}
|
||||
|
||||
@@ -2058,7 +2084,7 @@ std::wstring powerShellPath(const fs::path &path)
|
||||
void insertCurrentPanelPath(bool nameOnly = false)
|
||||
{
|
||||
const auto &panel=panels[active];
|
||||
if(panel.ftp) return;
|
||||
if(panel.ftp || panel.archive) return;
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(row==LB_ERR) return;
|
||||
const bool up=panel.sizes[row]==L"Up";
|
||||
@@ -2182,6 +2208,7 @@ bool startTerminal(HWND owner,const fs::path &directory)
|
||||
|
||||
bool showCommandOutput(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(panel.archive) return startTerminal(owner,panel.archive->file.parent_path());
|
||||
return panel.peer || panel.ftp?ensureTerminalView(owner):startTerminal(owner,panel.directory);
|
||||
}
|
||||
|
||||
@@ -2214,6 +2241,11 @@ void appendTerminalOutput(std::string_view output)
|
||||
bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
|
||||
{
|
||||
const auto owner=GetParent(panel.list);
|
||||
if(panel.archive)
|
||||
{
|
||||
setStatus(L"Shell commands require a local or LAN folder.");
|
||||
return false;
|
||||
}
|
||||
if(panel.ftp)
|
||||
{
|
||||
setStatus(L"Shell commands are unavailable in FTP panels.");
|
||||
@@ -2540,7 +2572,7 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
|
||||
{
|
||||
if(request.find) return scanFileMatches(request,entriesRead,stop);
|
||||
auto result=std::make_unique<Panel::ScanResult>();
|
||||
auto &[watch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata]=*result;
|
||||
auto &[watch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=*result;
|
||||
const auto &directory=request.directory;
|
||||
const auto &peer=request.peer;
|
||||
if(stop.stop_requested())
|
||||
@@ -2548,6 +2580,40 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
|
||||
error=ERROR_CANCELLED;
|
||||
return result;
|
||||
}
|
||||
if(request.archive)
|
||||
{
|
||||
try
|
||||
{
|
||||
const auto &source=*request.archive;
|
||||
archiveEntries=source.entries?source.entries:
|
||||
std::make_shared<const ks::files::ArchiveEntries>(ks::files::readArchive(source.file,stop));
|
||||
const auto inner=directory.lexically_relative(source.file);
|
||||
const auto relative=inner==L"."?fs::path{}:inner;
|
||||
if(!relative.empty())
|
||||
{
|
||||
const auto member=archiveEntries->find(relative);
|
||||
if(member==archiveEntries->end() || !member->second.directory)
|
||||
throw std::runtime_error("This folder is no longer present in the archive.");
|
||||
}
|
||||
for(const auto &[path,entry]:*archiveEntries)
|
||||
{
|
||||
if(stop.stop_requested()) {error=ERROR_CANCELLED; return result;}
|
||||
if(path.parent_path()!=relative) continue;
|
||||
const auto child=source.file/path;
|
||||
const DWORD attributes=entry.directory?FILE_ATTRIBUTE_DIRECTORY:FILE_ATTRIBUTE_NORMAL;
|
||||
metadata.emplace(child,FolderEntryMetadata{attributes,entry.size,entry.modified});
|
||||
(entry.directory?folders:files).push_back(child);
|
||||
}
|
||||
opened=true;
|
||||
}
|
||||
catch(const std::system_error &e)
|
||||
{
|
||||
if(e.code().value()==ERROR_CANCELLED) error=ERROR_CANCELLED;
|
||||
else failure=fileError(e);
|
||||
}
|
||||
catch(const std::exception &e) {failure=ks::wide(e.what());}
|
||||
return result;
|
||||
}
|
||||
if(request.ftp)
|
||||
{
|
||||
if(!request.ftp->name.empty())
|
||||
@@ -2670,7 +2736,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
auto &peer=request.peer;
|
||||
const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{};
|
||||
const bool sameDirectory=previousDirectory==directory;
|
||||
auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata]=scan;
|
||||
auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan;
|
||||
const bool partial=error==ERROR_CANCELLED;
|
||||
if(!failure.empty())
|
||||
{
|
||||
@@ -2763,7 +2829,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
panel.listReturnMarks.clear();
|
||||
}
|
||||
if(peer || request.ftp) panel.navigation={};
|
||||
else if(!finding)
|
||||
else if(!finding && !request.archive)
|
||||
{
|
||||
panel.navigation.opened(directory,request.navigationPosition);
|
||||
if(!sameDirectory && !panel.directory.empty() && !partial) updateRecentFolders(directory,true);
|
||||
@@ -2771,19 +2837,21 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
panel.directory = directory;
|
||||
panel.peer=std::move(peer);
|
||||
panel.ftp=std::move(request.ftp);
|
||||
panel.archive=std::move(request.archive);
|
||||
if(panel.archive) panel.archive->entries=std::move(archiveEntries);
|
||||
if(!sameDirectory)
|
||||
{
|
||||
cancelFolderSizes(panel);
|
||||
panel.folderSizes.clear();
|
||||
}
|
||||
if(partial || finding) panel.watch.reset();
|
||||
if(partial || finding || panel.archive) panel.watch.reset();
|
||||
else if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE)
|
||||
{
|
||||
panel.watch.reset();
|
||||
std::swap(panel.watch.handle,nextWatch.handle);
|
||||
}
|
||||
const bool profiles=ftpProfileList(panel);
|
||||
const bool renderTree=panel.view.tree && !finding && !profiles;
|
||||
const bool renderTree=panel.view.tree && !finding && !profiles && !panel.archive;
|
||||
panel.filteredMarks.clear();
|
||||
if(renderTree) replaceTreeRoot(panel,scan,sameDirectory,markedPaths);
|
||||
else
|
||||
@@ -2797,7 +2865,8 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
panel.metadata=std::move(metadata);
|
||||
panel.columnMetadata=std::move(columnMetadata);
|
||||
}
|
||||
const auto parent=finding?fs::path{}:panelParentPath(directory,!panel.peer && !panel.ftp);
|
||||
const auto parent=finding?fs::path{}:panel.archive?directory.parent_path():
|
||||
panelParentPath(directory,!panel.peer && !panel.ftp);
|
||||
const bool hasParent=!parent.empty();
|
||||
const auto rowCount=profiles?ftpProfiles.size():finding?files.size():
|
||||
renderTree?panel.tree.branches.at(panel.tree.root).ordered.size()+hasParent:ordered.size()+hasParent;
|
||||
@@ -2867,7 +2936,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
|
||||
else if(!partial && error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND)
|
||||
setStatus(L"Some entries could not be read.");
|
||||
else if(updateDetails && &panel==&panels[active]) showFileDetails(panel);
|
||||
if(!finding && !profiles) queueAutomaticPanelSizes(panel,true);
|
||||
if(!finding && !profiles && !panel.archive) queueAutomaticPanelSizes(panel,true);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2883,7 +2952,7 @@ std::future<std::unique_ptr<Panel::ScanResult>> scanDirectoryInBackground(HWND o
|
||||
if(result->opened && !request.find)
|
||||
{
|
||||
orderDirectoryRows(*result,view);
|
||||
if(columns && !request.peer && !request.ftp) readLocalColumnMetadata(*result,columns,stop);
|
||||
if(columns && !request.peer && !request.ftp && !request.archive) readLocalColumnMetadata(*result,columns,stop);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
@@ -2908,7 +2977,7 @@ void startDirectoryScan(Panel &panel)
|
||||
|
||||
void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional<FilesPeer> peer,
|
||||
fs::path selection={},fs::path fallback={},std::optional<FtpProfile> ftp={},
|
||||
std::optional<size_t> navigationPosition={})
|
||||
std::optional<size_t> navigationPosition={},std::optional<ArchiveLocation> archive={})
|
||||
{
|
||||
if(directory.empty() && !ftp) return;
|
||||
if(!panel.view.revealedFile.empty() &&
|
||||
@@ -2916,7 +2985,7 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
|
||||
if(directory!=panel.directory || !samePanelSource(panel,peer,ftp))
|
||||
cancelFolderSizes(panel);
|
||||
panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback),
|
||||
std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition};
|
||||
std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition,std::move(archive)};
|
||||
if(panel.scan.valid())
|
||||
{
|
||||
panel.scanSuperseded=true;
|
||||
@@ -2962,7 +3031,19 @@ void collectDirectoryScans()
|
||||
|
||||
void open(Panel &panel,const fs::path &directory,bool offerElevation=false)
|
||||
{
|
||||
openOn(panel,directory,offerElevation,panel.peer,{},{},panel.ftp);
|
||||
openOn(panel,directory,offerElevation,panel.peer,{},{},panel.ftp,{},panel.archive);
|
||||
}
|
||||
|
||||
void refreshArchive(Panel &panel)
|
||||
{
|
||||
openOn(panel,panel.directory,false,{},{},{},{},{},ArchiveLocation{panel.archive->file,{}});
|
||||
}
|
||||
|
||||
void parentArchive(Panel &panel)
|
||||
{
|
||||
if(panel.directory==panel.archive->file)
|
||||
openOn(panel,panel.directory.parent_path(),false,{},panel.archive->file);
|
||||
else open(panel,panel.directory.parent_path());
|
||||
}
|
||||
|
||||
#include "files_panel_tree.inl"
|
||||
@@ -2988,7 +3069,7 @@ void updatePanelView(Panel &panel)
|
||||
|
||||
void refreshPanelColumnData(Panel &panel)
|
||||
{
|
||||
if(panel.directory.empty() || panel.peer || panel.ftp || panel.findOrigin ||
|
||||
if(panel.directory.empty() || panel.peer || panel.ftp || panel.findOrigin || panel.archive ||
|
||||
(panel.scanRequest && panel.scanRequest->find)) return;
|
||||
if(panel.scanRequest)
|
||||
{
|
||||
@@ -3023,7 +3104,7 @@ void editPanelColumns(HWND owner,Panel &panel);
|
||||
|
||||
void setTreePanelMode(Panel &panel)
|
||||
{
|
||||
if(!panelViewAvailable(panel)) return;
|
||||
if(panel.archive || !panelViewAvailable(panel)) return;
|
||||
if(!panel.view.tree)
|
||||
{
|
||||
panel.view.tree=true;
|
||||
@@ -3042,7 +3123,7 @@ void setTreePanelMode(Panel &panel)
|
||||
|
||||
void toggleAutomaticPanelSizes(Panel &panel)
|
||||
{
|
||||
if(!panelViewAvailable(panel)) return;
|
||||
if(panel.archive || !panelViewAvailable(panel)) return;
|
||||
panel.view.automaticSizes=!panel.view.automaticSizes;
|
||||
savePanelView(static_cast<int>(&panel-panels));
|
||||
if(panel.view.automaticSizes) queueAutomaticPanelSizes(panel,true);
|
||||
@@ -3149,7 +3230,7 @@ bool calculateFolderSizes(Panel &panel,LRESULT current)
|
||||
|
||||
bool queueFolderMeasurements(Panel &panel,const std::vector<fs::path> &folders,bool foreground)
|
||||
{
|
||||
if(folders.empty()) return false;
|
||||
if(folders.empty() || panel.archive) return false;
|
||||
if(const auto running=panel.folderSizeJob)
|
||||
{
|
||||
bool queued=false;
|
||||
@@ -3300,9 +3381,12 @@ void collectFolderSizes(Panel &panel)
|
||||
if((finished || !completed.empty()) && &panel==&panels[active]) showFileDetails(panel);
|
||||
}
|
||||
|
||||
void openSelectedText(const Panel &panel, bool edit, bool external);
|
||||
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false);
|
||||
ks::files::TextDialogs textWindowDialogs();
|
||||
void findLocalFiles(HWND owner,Panel &panel);
|
||||
void compareSelectedFiles(HWND owner);
|
||||
void createArchive(HWND owner,Panel &panel);
|
||||
void addToArchive(HWND owner,Panel &panel,std::vector<fs::path> sources);
|
||||
INT_PTR confirmTextSave(HWND owner,bool draft);
|
||||
bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format);
|
||||
INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption);
|
||||
@@ -3454,6 +3538,9 @@ void selectDrive()
|
||||
else if(menuIndex==2 && row==10) toggleQuickView(owner);
|
||||
else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]);
|
||||
else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]);
|
||||
else if(menuIndex==2 && row==13) openSelectedText(panels[active],false,false,true);
|
||||
else if(menuIndex==2 && row==14) ks::files::showAllViewerBookmarks(owner,textWindowDialogs());
|
||||
else if(menuIndex==1 && row==4) createArchive(owner,panels[active]);
|
||||
else
|
||||
{
|
||||
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
|
||||
@@ -3976,7 +4063,7 @@ void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb
|
||||
|
||||
void openSelectedWithSystem(const Panel &panel)
|
||||
{
|
||||
if(panel.ftp) return;
|
||||
if(panel.ftp || panel.archive) return;
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(row==LB_ERR) return;
|
||||
if(panel.peer)
|
||||
@@ -4006,22 +4093,38 @@ void refreshQuickView(const Panel &panel)
|
||||
{
|
||||
if(!quickViewWindow || &panel!=&panels[quickViewSource]) return;
|
||||
const auto row=currentPanelRow(panel);
|
||||
const bool file=!panel.peer && !panel.ftp && row!=LB_ERR &&
|
||||
const bool file=!panel.peer && !panel.ftp && !panel.archive && row!=LB_ERR &&
|
||||
panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up";
|
||||
ks::files::previewQuickViewFile(quickViewWindow,file?panel.rows[row]:fs::path{});
|
||||
const auto path=file?panel.rows[row]:fs::path{};
|
||||
if(file && ks::files::isImagePath(path) && !quickImageWindow)
|
||||
{
|
||||
try {quickImageWindow=ks::files::createImageQuickView(GetParent(panel.list),textWindowDialogs());}
|
||||
catch(const std::exception &) {}
|
||||
}
|
||||
const bool image=quickImageWindow && file && ks::files::isImagePath(path);
|
||||
ks::files::previewQuickViewFile(quickViewWindow,image?fs::path{}:path);
|
||||
if(quickImageWindow) ks::files::previewImageQuickViewFile(quickImageWindow,image?path:fs::path{});
|
||||
if(std::exchange(quickViewDisplaysImage,image)!=image) layout(GetParent(panel.list));
|
||||
}
|
||||
|
||||
void closeQuickViews()
|
||||
{
|
||||
if(quickImageWindow) DestroyWindow(std::exchange(quickImageWindow,nullptr));
|
||||
if(quickViewWindow) DestroyWindow(std::exchange(quickViewWindow,nullptr));
|
||||
quickViewDisplaysImage=false;
|
||||
}
|
||||
|
||||
void toggleQuickView(HWND owner)
|
||||
{
|
||||
if(quickViewWindow)
|
||||
{
|
||||
DestroyWindow(std::exchange(quickViewWindow,nullptr));
|
||||
closeQuickViews();
|
||||
layout(owner);
|
||||
restoreCommandFocus();
|
||||
return;
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
if(panel.peer || panel.ftp || terminalVisible)
|
||||
if(panel.peer || panel.ftp || panel.archive || terminalVisible)
|
||||
{
|
||||
setStatus(L"Quick View requires a visible local file pane.");
|
||||
return;
|
||||
@@ -4051,11 +4154,51 @@ bool handleQuickViewKey(HWND window,const MSG &message)
|
||||
|
||||
ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile);
|
||||
|
||||
void openSelectedText(const Panel &panel, bool edit, bool external)
|
||||
void openPanelImage(const Panel &panel,const fs::path &path,const ks::files::RemoteTextSource *source=nullptr)
|
||||
{
|
||||
std::vector<fs::path> images;
|
||||
for(size_t row=0;row<panel.rows.size();++row)
|
||||
if(panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up" && ks::files::isImagePath(panel.rows[row]))
|
||||
images.push_back(panel.rows[row]);
|
||||
ks::files::openImageWindow(GetParent(panel.list),std::move(images),path,textWindowDialogs(),
|
||||
panel.peer?&*panel.peer:nullptr,source);
|
||||
}
|
||||
|
||||
void openArchiveText(const Panel &panel,const fs::path &path,bool hex=false)
|
||||
{
|
||||
const auto file=panel.archive->file;
|
||||
const auto member=path.lexically_relative(file);
|
||||
const auto found=panel.archive->entries->find(member);
|
||||
if(found==panel.archive->entries->end() || found->second.directory) return;
|
||||
if(found->second.encrypted)
|
||||
{
|
||||
setStatus(L"This archive entry requires a password. Password-protected entries cannot be opened in Files.");
|
||||
return;
|
||||
}
|
||||
const ks::files::RemoteTextSource archive{
|
||||
"archive:"+ks::utf8(file.native()),file.filename().native(),
|
||||
[file](const fs::path &original,const fs::path &cache,bool,const ks::files::ArchiveProgress &progress,uint64_t limit)
|
||||
{
|
||||
const auto relative=original.lexically_relative(file);
|
||||
const auto entry=ks::files::readArchiveMember(file,relative,cache,limit,progress);
|
||||
return ks::files::RemoteTextRevision{entry.size,entry.modified,false};
|
||||
},{}};
|
||||
if(!hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&archive);
|
||||
else ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive,{},
|
||||
false,{.hex=hex});
|
||||
}
|
||||
|
||||
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex)
|
||||
{
|
||||
if(ftpProfileList(panel)) return;
|
||||
const auto row=currentPanelRow(panel);
|
||||
if(row==LB_ERR || panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") return;
|
||||
if(panel.archive)
|
||||
{
|
||||
if(edit || external) setStatus(L"Archive entries are read-only. Use F5 to extract them.");
|
||||
else openArchiveText(panel,panel.rows[row],hex);
|
||||
return;
|
||||
}
|
||||
if((panel.peer || panel.ftp) && external)
|
||||
{
|
||||
setStatus(L"Copy the remote file to a local panel before opening it.");
|
||||
@@ -4064,14 +4207,17 @@ void openSelectedText(const Panel &panel, bool edit, bool external)
|
||||
const auto &path=panel.rows[row];
|
||||
if(panel.ftp)
|
||||
{
|
||||
ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftpTextSource(*panel.ftp));
|
||||
const auto ftp=ftpTextSource(*panel.ftp);
|
||||
if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp);
|
||||
else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp,{},false,{.hex=hex});
|
||||
return;
|
||||
}
|
||||
if(external)
|
||||
openPanelFile(panel,path,edit?L"edit":L"open",
|
||||
edit?L"No editor is registered for this file.":L"Cannot open the selected file.");
|
||||
else if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path);
|
||||
else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),
|
||||
panel.peer?&*panel.peer:nullptr);
|
||||
panel.peer?&*panel.peer:nullptr,{},false,{.hex=hex});
|
||||
}
|
||||
|
||||
void enter(Panel &panel)
|
||||
@@ -4086,6 +4232,13 @@ void enter(Panel &panel)
|
||||
return;
|
||||
}
|
||||
auto target = panel.rows[row];
|
||||
if(panel.archive)
|
||||
{
|
||||
if(panel.sizes[row]==L"Up") parentArchive(panel);
|
||||
else if(panel.sizes[row]==L"Folder") open(panel,target);
|
||||
else openArchiveText(panel,target);
|
||||
return;
|
||||
}
|
||||
if(panel.findOrigin)
|
||||
{
|
||||
revealLocalFile(panel,target);
|
||||
@@ -4094,6 +4247,8 @@ void enter(Panel &panel)
|
||||
if(panel.sizes[row]==L"Folder" && toggleTreeRow(panel,static_cast<size_t>(row))) return;
|
||||
if(panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") open(panel,target,true);
|
||||
else if(panel.ftp) openSelectedText(panel,false,false);
|
||||
else if(!panel.peer && ks::files::isArchivePath(target))
|
||||
openOn(panel,target,false,{},{},{},{},{},ArchiveLocation{target,{}});
|
||||
else openPanelFile(panel, target, nullptr, L"Cannot open the selected file.");
|
||||
}
|
||||
}
|
||||
@@ -4119,7 +4274,7 @@ struct CopyRequest
|
||||
std::future<CopyDestination> validation;
|
||||
std::wstring ftpDestination;
|
||||
bool upload{};
|
||||
bool ftpRename{}, externalSources{};
|
||||
bool ftpRename{}, externalSources{}, archiveSource{};
|
||||
};
|
||||
|
||||
bool directoryExists(const FilesPeer *peer,const fs::path &path)
|
||||
@@ -4645,32 +4800,13 @@ void installFarCheckbox(HWND field,FarCheckboxSurface surface)
|
||||
SetWindowSubclass(field,paintFarCheckbox,1,static_cast<DWORD_PTR>(surface));
|
||||
}
|
||||
|
||||
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;});
|
||||
}
|
||||
|
||||
bool validFtpCopyName(std::wstring_view name,bool upload)
|
||||
{
|
||||
if(upload)
|
||||
return !name.empty() && name!=L"." && name!=L".." &&
|
||||
name.find_first_of(L"/\\:\r\n") == name.npos &&
|
||||
std::none_of(name.begin(),name.end(),[](wchar_t ch){return ch<32;});
|
||||
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);
|
||||
return ks::files::validWindowsFileName(name);
|
||||
}
|
||||
|
||||
void drawFarComboRow(const DRAWITEMSTRUCT &item)
|
||||
@@ -4734,14 +4870,14 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring &
|
||||
else if(request.sources.size()==1)
|
||||
{
|
||||
const auto &name=value;
|
||||
if(!validFileName(name))
|
||||
if(request.archiveSource?!ks::files::validWindowsFileName(name):!validFileName(name))
|
||||
throw std::runtime_error(ks::utf8(L"Enter a valid name for the copy."));
|
||||
if(CompareStringOrdinal(name.c_str(),-1,request.sources.front().filename().c_str(),-1,TRUE)!=CSTR_EQUAL)
|
||||
request.newName=name;
|
||||
else request.newName.clear();
|
||||
}
|
||||
const auto sourceDirectory=request.sources.front().parent_path();
|
||||
const bool renameInSource=!request.externalSources && !request.move && !request.newName.empty();
|
||||
const bool renameInSource=!request.externalSources && !request.archiveSource && !request.move && !request.newName.empty();
|
||||
const auto destination=renameInSource?sourceDirectory:request.destination;
|
||||
std::error_code error;
|
||||
const auto peer=renameInSource?request.sourcePeer:request.destinationPeer;
|
||||
@@ -4903,6 +5039,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
|
||||
snapshot.ftpDestination=request.ftpDestination;
|
||||
snapshot.upload=request.upload;
|
||||
snapshot.externalSources=request.externalSources;
|
||||
snapshot.archiveSource=request.archiveSource;
|
||||
std::packaged_task<CopyDestination()> validation(
|
||||
[snapshot=std::move(snapshot),value=std::move(value),
|
||||
source=peer(request.sourcePeer),other=peer(request.otherPeer)]() mutable {
|
||||
@@ -4994,6 +5131,7 @@ struct CopyProgress
|
||||
std::atomic_bool canceled{};
|
||||
bool closeOwner{};
|
||||
bool move{}, fileSourcesOnly{};
|
||||
bool writingArchive{};
|
||||
int conflictChoice{};
|
||||
ConflictMode conflictMode{};
|
||||
bool askReadOnly=true;
|
||||
@@ -5528,7 +5666,7 @@ INT_PTR CALLBACK copyProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp
|
||||
}
|
||||
const auto operation=reinterpret_cast<const CopyProgress*>(GetWindowLongPtrW(window,DWLP_USER));
|
||||
if(const auto painted=paintCopyDialog(window,message,wp,lp,
|
||||
operation && operation->move?L" Move ":L" Copy ",false,{228,229}))
|
||||
operation && operation->writingArchive?L" Pack ":operation && operation->move?L" Move ":L" Copy ",false,{228,229}))
|
||||
return painted;
|
||||
if(message==WM_DPICHANGED)
|
||||
{
|
||||
@@ -5594,7 +5732,8 @@ INT_PTR CALLBACK copyProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp
|
||||
if(message!=WM_CLOSE && (message!=WM_COMMAND || LOWORD(wp)!=IDCANCEL)) return FALSE;
|
||||
auto &progress=*reinterpret_cast<CopyProgress*>(GetWindowLongPtrW(window,DWLP_USER));
|
||||
if(!progress.canceled)
|
||||
progress.canceled=confirmOperationCancellation(window,progress.move?
|
||||
progress.canceled=confirmOperationCancellation(window,progress.writingArchive?
|
||||
L"Do you really want to cancel writing the archive?":progress.move?
|
||||
L"Do you really want to cancel moving?":L"Do you really want to cancel copying?");
|
||||
return TRUE;
|
||||
}
|
||||
@@ -5964,11 +6103,37 @@ void pruneSearchResults(Panel &panel,const std::set<fs::path> &removed)
|
||||
updateSelectionSummary(panel);
|
||||
}
|
||||
|
||||
struct ArchiveStaging
|
||||
{
|
||||
fs::path directory;
|
||||
|
||||
void create()
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
|
||||
throw std::runtime_error("Could not create temporary storage for archive entries.");
|
||||
const auto path=fs::temp_directory_path()/(L"ks-files-archive-"+std::wstring(name));
|
||||
if(!fs::create_directory(path)) throw std::runtime_error("Could not create temporary storage for archive entries.");
|
||||
directory=path;
|
||||
}
|
||||
|
||||
~ArchiveStaging()
|
||||
{
|
||||
if(directory.empty()) return;
|
||||
std::error_code error;
|
||||
fs::remove_all(directory,error);
|
||||
}
|
||||
};
|
||||
|
||||
void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector<fs::path> external={},
|
||||
fs::path targetFolder={})
|
||||
{
|
||||
const auto sourceFtp=source.ftp;
|
||||
const bool ftpRename=move && sourceFtp && !ftpProfileList(source);
|
||||
const auto archive=source.archive?source.archive->file:fs::path{};
|
||||
auto archiveDirectory=archive.empty()?fs::path{}:source.directory.lexically_relative(archive);
|
||||
if(archiveDirectory==L".") archiveDirectory.clear();
|
||||
if(quickViewWindow && &destination!=&panels[quickViewSource] && !ftpRename)
|
||||
{
|
||||
setStatus(L"Close Quick View to use the destination pane.");
|
||||
@@ -5984,6 +6149,18 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
setStatus(L"Wait for the search to finish.");
|
||||
return;
|
||||
}
|
||||
if(destination.archive)
|
||||
{
|
||||
if(move || source.archive || source.peer || source.ftp)
|
||||
setStatus(L"Use F5 from a local folder to add files to an archive.");
|
||||
else addToArchive(owner,destination,external.empty()?selectedPanelPaths(source):std::move(external));
|
||||
return;
|
||||
}
|
||||
if(!archive.empty() && (move || destination.peer || destination.ftp))
|
||||
{
|
||||
setStatus(L"Use F5 to extract archive entries to a local folder.");
|
||||
return;
|
||||
}
|
||||
const bool fromSearch=source.findOrigin.has_value();
|
||||
const auto destinationFtp=ftpRename?sourceFtp:destination.ftp;
|
||||
const bool ftp=sourceFtp || destinationFtp;
|
||||
@@ -6003,6 +6180,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
request.move=move;
|
||||
request.ftpRename=ftpRename;
|
||||
request.externalSources=!external.empty();
|
||||
request.archiveSource=!archive.empty();
|
||||
if(ftp)
|
||||
{
|
||||
request.ftpDestination=panelLocation(destination);
|
||||
@@ -6024,7 +6202,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
if(result!=IDOK) return;
|
||||
|
||||
const bool renamed=!request.newName.empty();
|
||||
const bool renameInSource=renamed && !move && !ftp && !request.externalSources;
|
||||
const bool renameInSource=renamed && !move && !ftp && !request.externalSources && archive.empty();
|
||||
const auto targetDirectory=renameInSource?request.sources.front().parent_path():request.destination;
|
||||
const auto *targetPeer=renameInSource?request.sourcePeer:request.destinationPeer;
|
||||
const auto peerId=[](const FilesPeer *peer){return peer?peer->id:std::string{};};
|
||||
@@ -6056,7 +6234,26 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
{
|
||||
progress.ui.run(progress.window,progress.canceled,[&] {
|
||||
FileOperationElevation elevation(progress.window,progress.canceled,&progress.ui);
|
||||
auto *admin=!ftp && !request.sourcePeer && !targetPeer?&elevation:nullptr;
|
||||
auto *admin=archive.empty() && !ftp && !request.sourcePeer && !targetPeer?&elevation:nullptr;
|
||||
ArchiveStaging staging;
|
||||
auto sources=request.sources;
|
||||
if(!archive.empty())
|
||||
{
|
||||
staging.create();
|
||||
std::vector<fs::path> selection;
|
||||
for(auto &path:sources)
|
||||
{
|
||||
selection.push_back(path.lexically_relative(archive));
|
||||
path=staging.directory/path.filename();
|
||||
}
|
||||
progress.from=archive;
|
||||
progress.to=targetDirectory;
|
||||
ks::files::extractArchiveSelection(archive,archiveDirectory,selection,staging.directory,[&](uint64_t done,uint64_t total)
|
||||
{
|
||||
reportCopyProgress(progress,done,total);
|
||||
return !progress.canceled;
|
||||
});
|
||||
}
|
||||
CopyHost sourceHost(request.sourcePeer,sourceFtp,admin);
|
||||
if(ftpRename)
|
||||
{
|
||||
@@ -6082,12 +6279,13 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost,
|
||||
request.sourcePeer?request.sourcePeer->id:"local",!request.sourcePeer && !sourceFtp,
|
||||
!targetPeer && !destinationFtp};
|
||||
for(const auto &path:request.sources)
|
||||
for(const auto &path:sources)
|
||||
if(!countCopy(sourceHost,path,progress)) { failed=true; break; }
|
||||
reportCopyProgress(progress,0,0,true);
|
||||
for(const auto &path:request.sources)
|
||||
for(size_t i=0;i<sources.size();++i)
|
||||
{
|
||||
if(failed) break;
|
||||
const auto &path=sources[i];
|
||||
const auto to=targetDirectory/(renamed?request.newName:path.filename());
|
||||
if(sameHost)
|
||||
{
|
||||
@@ -6110,14 +6308,14 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
}
|
||||
if(failed) break;
|
||||
progress.renamedTarget.clear();
|
||||
const auto outcome=copyItem(hosts,path,to,progress,true,request.sources.size()==1);
|
||||
const auto outcome=copyItem(hosts,path,to,progress,true,sources.size()==1);
|
||||
if(outcome==CopyResult::failed) { failed=true; break; }
|
||||
if(outcome==CopyResult::skipped) { skipped=true; continue; }
|
||||
++copied;
|
||||
if(move && fromSearch) removed.insert(path);
|
||||
results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget);
|
||||
if(!request.externalSources) progress.ui.invoke([&] {
|
||||
const auto row=std::find(source.rows.begin(),source.rows.end(),path);
|
||||
const auto row=std::find(source.rows.begin(),source.rows.end(),request.sources[i]);
|
||||
if(row!=source.rows.end()) markPanelRow(source,row-source.rows.begin(),false);
|
||||
else if(treePanelActive(source)) source.tree.marks.erase(path);
|
||||
InvalidateRect(source.list,nullptr,FALSE);
|
||||
@@ -6136,7 +6334,11 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
|
||||
lockPaths.push_back(progress.localLockTarget);
|
||||
}
|
||||
}
|
||||
catch(const std::exception &){failed=true;failure=L"File connection interrupted.";}
|
||||
catch(const std::exception &e)
|
||||
{
|
||||
failed=true;
|
||||
failure=archive.empty()?L"File connection interrupted.":ks::wide(e.what());
|
||||
}
|
||||
const auto targetId=peerId(targetPeer);
|
||||
const bool restoreFocus=GetForegroundWindow()==progress.window;
|
||||
updateCopyProgress(progress,0,0);
|
||||
@@ -6347,6 +6549,7 @@ INT_PTR CALLBACK deleteProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM
|
||||
|
||||
void deleteSelection(HWND owner,Panel &panel,bool permanent)
|
||||
{
|
||||
if(panel.archive) {setStatus(L"Archive entries are read-only."); return;}
|
||||
const bool fromSearch=panel.findOrigin.has_value();
|
||||
if(fromSearch && panel.scanRequest)
|
||||
{
|
||||
@@ -6603,7 +6806,8 @@ bool pastePanelFiles(HWND owner,Panel &panel)
|
||||
setStatus(L"The clipboard has no usable file paths.");
|
||||
return true;
|
||||
}
|
||||
copySelection(owner,panel,panel,false,std::move(paths));
|
||||
if(panel.archive) addToArchive(owner,panel,std::move(paths));
|
||||
else copySelection(owner,panel,panel,false,std::move(paths));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -6657,6 +6861,8 @@ std::wstring dialogFieldText(HWND field)
|
||||
return value;
|
||||
}
|
||||
|
||||
#include "files_archive_dialog.inl"
|
||||
|
||||
INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
constexpr int label=360,field=361,divider=362,history=363,linkLabel=364,linkType=365,
|
||||
@@ -6811,6 +7017,7 @@ void makeFolder(HWND owner,Panel &panel)
|
||||
return;
|
||||
}
|
||||
if(panel.ftp) return;
|
||||
if(panel.archive) {setStatus(L"Archive entries are read-only."); return;}
|
||||
if(panel.directory.empty()) return;
|
||||
const auto directory=panel.directory;
|
||||
MakeFolderRequest request{directory,panel.peer?&*panel.peer:nullptr,{},
|
||||
@@ -7007,6 +7214,7 @@ void openOrCreateText(HWND owner,const Panel &panel)
|
||||
setStatus(L"Open/create file is available in local panels.");
|
||||
return;
|
||||
}
|
||||
if(panel.archive) {setStatus(L"Archive entries are read-only."); return;}
|
||||
if(panel.directory.empty()) return;
|
||||
TextFilePrompt prompt{panel.directory,{}, {.encoding=ks::files::TextEncoding::automatic}};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(611),owner,textFilePrompt,
|
||||
@@ -7299,19 +7507,19 @@ void openMenu(HWND window, int index)
|
||||
if(detailedPanel(panel)) rows.push_back(L" Columns…");
|
||||
}
|
||||
}
|
||||
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"};
|
||||
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10",L"Pack files…\tAlt+F5"};
|
||||
else if(index==2)
|
||||
{
|
||||
rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
|
||||
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
|
||||
L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(),
|
||||
L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q",
|
||||
L"Copy full path\tCtrl+Shift+C",L"Space Analyzer"};
|
||||
L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…"};
|
||||
}
|
||||
commandActions.clear();
|
||||
if(index==2)
|
||||
{
|
||||
commandActions={0,3,11,-1,1,2,4,5,8};
|
||||
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
|
||||
if(!panels[active].peer && !panels[active].ftp)
|
||||
{
|
||||
commandActions.insert(commandActions.begin()+1,9);
|
||||
@@ -7897,7 +8105,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
SetTextColor(item.hDC,colors[highlighted?Text:Frame]);
|
||||
SetBkMode(item.hDC,TRANSPARENT);
|
||||
DrawTextW(item.hDC,path.c_str(),-1,&bounds,
|
||||
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_PATH_ELLIPSIS|DT_NOPREFIX);
|
||||
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX|(panel.archive?DT_END_ELLIPSIS:DT_PATH_ELLIPSIS));
|
||||
if(saved) RestoreDC(item.hDC,saved);
|
||||
return TRUE;
|
||||
}
|
||||
@@ -8277,13 +8485,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
savePlacement(window);
|
||||
for(int i=0;i<2;++i)
|
||||
{
|
||||
const auto &path=panels[i].directory.native();
|
||||
const auto path=(panels[i].archive?panels[i].archive->file.parent_path():panels[i].directory).native();
|
||||
if(!panels[i].peer && !panels[i].ftp && !path.empty())
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(),
|
||||
static_cast<DWORD>((path.size()+1)*sizeof(wchar_t)));
|
||||
const auto row=SendMessageW(panels[i].list,LB_GETCURSEL,0,0);
|
||||
const auto cursor=row>=0 && static_cast<size_t>(row)<panels[i].rows.size() ?
|
||||
panels[i].rows[row].native() : std::wstring{};
|
||||
const auto cursor=panels[i].archive?panels[i].archive->file.native():
|
||||
row>=0 && static_cast<size_t>(row)<panels[i].rows.size()?panels[i].rows[row].native():std::wstring{};
|
||||
if(!panels[i].peer && !panels[i].ftp) RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelCursorKeys[i],REG_SZ,cursor.c_str(),
|
||||
static_cast<DWORD>((cursor.size()+1)*sizeof(wchar_t)));
|
||||
}
|
||||
@@ -8308,7 +8516,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
remoteCommandThread.request_stop();
|
||||
remoteCommandThread.join();
|
||||
}
|
||||
if(quickViewWindow) DestroyWindow(std::exchange(quickViewWindow,nullptr));
|
||||
closeQuickViews();
|
||||
ks::files::textWindowOwnerClosed();
|
||||
return 0;
|
||||
}
|
||||
@@ -8420,11 +8628,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
(message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list))
|
||||
{
|
||||
auto &panel=panels[active];
|
||||
if(panel.scanRequest && panel.scanRequest->find)
|
||||
if(panel.scanRequest && (panel.scanRequest->find || panel.scanRequest->archive))
|
||||
{
|
||||
if(!panel.scanSuperseded) stopDirectoryScan();
|
||||
continue;
|
||||
}
|
||||
if(panel.archive && !panel.scanRequest)
|
||||
{
|
||||
parentArchive(panel);
|
||||
continue;
|
||||
}
|
||||
if(panel.findOrigin && !panel.scanRequest)
|
||||
{
|
||||
openOn(panel,panel.directory,false,{});
|
||||
@@ -8442,7 +8655,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
}
|
||||
if(!terminalVisible && !copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(window) &&
|
||||
message.message==WM_SYSKEYDOWN && message.wParam==VK_F7 &&
|
||||
message.message==WM_SYSKEYDOWN && (message.wParam==VK_F5 || message.wParam==VK_F7) &&
|
||||
(message.lParam & (1LL<<29)) &&
|
||||
!((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
|
||||
{
|
||||
@@ -8450,7 +8663,8 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
{
|
||||
hidePicker();
|
||||
showMenu(false);
|
||||
findLocalFiles(window,panels[active]);
|
||||
if(message.wParam==VK_F5) createArchive(window,panels[active]);
|
||||
else findLocalFiles(window,panels[active]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -8585,6 +8799,11 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(shift && !ctrl && message.wParam==VK_F3 && !terminalVisible && commandLineAvailable(window))
|
||||
{
|
||||
if(!(message.lParam&(1LL<<30))) openSelectedText(panels[active],false,false,true);
|
||||
continue;
|
||||
}
|
||||
if(ctrl && !shift &&
|
||||
(message.wParam=='F' || message.wParam=='C' || message.wParam=='R' ||
|
||||
(message.wParam=='U' && !terminalVisible) ||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
bool localNavigationAvailable(const Panel &panel)
|
||||
{
|
||||
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.directory.empty();
|
||||
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.archive && !panel.directory.empty();
|
||||
}
|
||||
|
||||
enum class PathAction { back, forward, up, edit, ancestors, previous, folder };
|
||||
@@ -363,10 +363,18 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_
|
||||
|
||||
bool handleLocalPathKey(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(!localNavigationAvailable(panel)) return false;
|
||||
if(message.message==WM_KEYDOWN && message.wParam=='L' &&
|
||||
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000))
|
||||
{
|
||||
|
||||
@@ -608,7 +608,7 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l
|
||||
|
||||
void openSpaceAnalyzer(HWND owner,Panel &panel)
|
||||
{
|
||||
if(panel.peer || panel.ftp || panel.directory.empty())
|
||||
if(panel.peer || panel.ftp || panel.archive || panel.directory.empty())
|
||||
{
|
||||
setStatus(L"Space Analyzer requires an open local folder.");
|
||||
return;
|
||||
|
||||
+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(); }
|
||||
|
||||
+485
-108
@@ -1,4 +1,5 @@
|
||||
#include "files_text_window.h"
|
||||
#include "files_image_view.h"
|
||||
#include "files_text_preferences.h"
|
||||
#include "files_menu_paint.h"
|
||||
#include "files_menu_navigation.h"
|
||||
@@ -24,6 +25,7 @@
|
||||
#include "../vendor/json.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
@@ -199,7 +201,7 @@ enum Command : UINT
|
||||
{
|
||||
save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage,
|
||||
undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, switchMode,
|
||||
historyBack, historyForward, findPrevious, previewEscape,
|
||||
historyBack, historyForward, findPrevious, previewEscape, switchHex, addBookmark, currentBookmarks, allBookmarks,
|
||||
lexerStart = 1000,
|
||||
};
|
||||
|
||||
@@ -217,6 +219,8 @@ void initializePrompt(TextDialogs style, HWND dialog)
|
||||
SendDlgItemMessageW(dialog, 100, EM_SETSEL, 0, -1);
|
||||
}
|
||||
|
||||
#include "files_viewer_bookmarks.inl"
|
||||
|
||||
INT_PTR CALLBACK pageDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam)
|
||||
{
|
||||
if (message == WM_INITDIALOG)
|
||||
@@ -662,6 +666,19 @@ struct RemoteTextFile
|
||||
}
|
||||
};
|
||||
|
||||
std::future<std::unique_ptr<RemoteTextFile>> fetchRemoteText(const RemoteTextSource &source,
|
||||
const std::filesystem::path &path,const std::shared_ptr<std::atomic<bool>> &canceled)
|
||||
{
|
||||
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task([source,path,canceled] {
|
||||
auto file=std::make_unique<RemoteTextFile>(source,path);
|
||||
file->download(false,[canceled](uint64_t,uint64_t){return !*canceled;});
|
||||
return file;
|
||||
});
|
||||
auto result=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
return result;
|
||||
}
|
||||
|
||||
class TextWindow;
|
||||
std::map<HWND,std::shared_ptr<TextWindow>> textWindows;
|
||||
std::vector<HWND> textWindowOrder;
|
||||
@@ -742,11 +759,14 @@ public:
|
||||
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend,
|
||||
std::string_view fragment,TextOpenOptions options,bool quickView=false)
|
||||
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
|
||||
edit(editable), draft(options.draft), embedded(quickView), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
edit(editable), draft(options.draft), embedded(quickView), hex(options.hex && !editable),
|
||||
initialBookmark(options.line),
|
||||
prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
|
||||
search{dialogs}, previewFragment(fragment)
|
||||
{
|
||||
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
|
||||
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
|
||||
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,
|
||||
hex?TextEncoding::utf8:options.encoding);
|
||||
if(options.encoding!=TextEncoding::automatic)
|
||||
{
|
||||
newFormat.encoding=options.encoding;
|
||||
@@ -766,6 +786,7 @@ public:
|
||||
static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam);
|
||||
~TextWindow()
|
||||
{
|
||||
if(savedViewerFile) document.reset();
|
||||
if(smallIcon) DestroyIcon(smallIcon);
|
||||
if(largeIcon) DestroyIcon(largeIcon);
|
||||
}
|
||||
@@ -773,6 +794,7 @@ public:
|
||||
bool handleKey(const MSG &message);
|
||||
void goToFragment(std::string_view fragment);
|
||||
void previewFile(const std::filesystem::path &path);
|
||||
bool openBookmark(const ViewerBookmark &bookmark);
|
||||
std::filesystem::path original;
|
||||
const std::string peerId;
|
||||
|
||||
@@ -782,6 +804,25 @@ private:
|
||||
std::wstring filename;
|
||||
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
|
||||
bool draft{}, embedded{};
|
||||
bool hex{};
|
||||
uint64_t initialBookmark{};
|
||||
bool showBookmarkSource{};
|
||||
struct ViewerPosition
|
||||
{
|
||||
uint64_t page{};
|
||||
LRESULT anchor{}, caret{}, firstLine{}, horizontal{};
|
||||
};
|
||||
std::optional<ViewerPosition> beforeHex;
|
||||
struct SuspendedEditor
|
||||
{
|
||||
std::unique_ptr<TextDocument> document;
|
||||
ViewerPosition position;
|
||||
bool uploadPending{};
|
||||
};
|
||||
std::optional<SuspendedEditor> suspendedEditor;
|
||||
std::unique_ptr<RemoteTextFile> savedViewerFile;
|
||||
std::future<std::unique_ptr<RemoteTextFile>> savedViewerLoad;
|
||||
std::shared_ptr<std::atomic<bool>> cancelSavedViewer;
|
||||
TextSaveFormat newFormat;
|
||||
std::filesystem::path pendingSavePath;
|
||||
HICON smallIcon{},largeIcon{};
|
||||
@@ -804,7 +845,6 @@ private:
|
||||
int pageEol = SC_EOL_CRLF;
|
||||
size_t undoBytes{};
|
||||
bool uploadPending{};
|
||||
bool switchAfterSave{};
|
||||
FilesTerminalView preview;
|
||||
bool previewWanted{}, previewVisible{}, previewRetried{};
|
||||
ULONGLONG previewDeadline{};
|
||||
@@ -864,6 +904,18 @@ private:
|
||||
static constexpr UINT_PTR previewTimer = 3;
|
||||
static constexpr UINT_PTR navigationTimer = 4;
|
||||
static constexpr UINT_PTR quickViewTimer = 5;
|
||||
static constexpr UINT_PTR bookmarkTimer = 6;
|
||||
static constexpr UINT_PTR savedViewerTimer = 7;
|
||||
struct BookmarkLocation
|
||||
{
|
||||
std::filesystem::path path;
|
||||
uint64_t line{};
|
||||
bool adding{};
|
||||
std::optional<TextLineLocation> position;
|
||||
std::unique_ptr<TextDocument> source;
|
||||
};
|
||||
std::future<BookmarkLocation> bookmarkTask;
|
||||
std::stop_source bookmarkStop;
|
||||
struct QuickDocument
|
||||
{
|
||||
std::unique_ptr<TextDocument> document;
|
||||
@@ -922,6 +974,10 @@ private:
|
||||
void applyLineEnding();
|
||||
void installLexer();
|
||||
void loadPage(uint64_t index,std::optional<std::string> cached={});
|
||||
void toggleHex();
|
||||
void locateBookmark(uint64_t line);
|
||||
void finishBookmark();
|
||||
void pickBookmark(bool currentFile);
|
||||
void stagePage();
|
||||
void go(uint64_t index);
|
||||
void saveFile(bool closeWhenDone);
|
||||
@@ -929,6 +985,13 @@ private:
|
||||
void requestClose();
|
||||
void toggleMode();
|
||||
void changeMode();
|
||||
ViewerPosition currentPosition() const;
|
||||
void restorePosition(const ViewerPosition &position);
|
||||
void showTextMode(const ViewerPosition &position,std::string contents);
|
||||
void suspendEditor(std::unique_ptr<RemoteTextFile> saved={});
|
||||
void restoreEditor();
|
||||
void finishSavedViewer();
|
||||
void cancelSavedViewerLoad();
|
||||
bool needsSave() const;
|
||||
bool canPreview() const;
|
||||
void updatePreview();
|
||||
@@ -977,7 +1040,8 @@ void TextWindow::createMenu()
|
||||
const auto menu = CreateMenu();
|
||||
const auto file = addGroup(menu, L"&File");
|
||||
if (edit) addItem(file, save, L"&Save\tF2");
|
||||
addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6");
|
||||
if(!hex) addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6");
|
||||
if(!edit) addItem(file,switchHex,hex?L"&Text view\tF4":L"View as &hex\tF4");
|
||||
addItem(file, close, L"&Close\tF10");
|
||||
const auto actions = addGroup(menu, edit ? L"&Edit" : L"&Selection");
|
||||
if (edit)
|
||||
@@ -991,52 +1055,65 @@ void TextWindow::createMenu()
|
||||
addItem(actions, copy, L"&Copy\tCtrl+C");
|
||||
addItem(actions, selectAll, L"Select &page\tCtrl+A");
|
||||
const auto navigation = addGroup(menu, L"&Navigate");
|
||||
if (!edit)
|
||||
if (!edit && !hex)
|
||||
{
|
||||
addItem(navigation, historyBack, L"&Back\tAlt+Left");
|
||||
addItem(navigation, historyForward, L"F&orward\tAlt+Right");
|
||||
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
|
||||
}
|
||||
addItem(navigation, findText, L"&Find on page…\tCtrl+F");
|
||||
addItem(navigation, findNext, L"Find &next\tF3");
|
||||
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
|
||||
if(!hex)
|
||||
{
|
||||
addItem(navigation, findText, L"&Find on page…\tCtrl+F");
|
||||
addItem(navigation, findNext, L"Find &next\tF3");
|
||||
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
|
||||
}
|
||||
if(!edit && !hex)
|
||||
{
|
||||
addItem(navigation,addBookmark,L"Add &bookmark…\tCtrl+D");
|
||||
addItem(navigation,currentBookmarks,L"Bookmarks in &this file…");
|
||||
addItem(navigation,allBookmarks,L"&All bookmarks…");
|
||||
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
|
||||
}
|
||||
addItem(navigation, previousPage, L"&Previous page\tCtrl+PgUp");
|
||||
addItem(navigation, nextPage, L"N&ext page\tCtrl+PgDn");
|
||||
addItem(navigation, firstPage, L"F&irst page\tCtrl+Shift+Home");
|
||||
addItem(navigation, lastPage, L"&Last page\tCtrl+Shift+End");
|
||||
addItem(navigation, goToPage, L"&Go to page…\tF5");
|
||||
|
||||
const auto syntax = addGroup(menu, L"S&yntax");
|
||||
addItem(syntax, lexerAuto, L"&Automatic");
|
||||
addItem(syntax, lexerPlain, L"&Plain text");
|
||||
constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"};
|
||||
const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'};
|
||||
HMENU group{};
|
||||
size_t groupIndex{};
|
||||
std::wstring assignedKeys;
|
||||
for (size_t i = 0; i < lexers.size(); ++i)
|
||||
const auto syntax = hex?nullptr:addGroup(menu, L"S&yntax");
|
||||
if(syntax)
|
||||
{
|
||||
auto name = wide(lexers[i]);
|
||||
const auto letter = std::towlower(name.front());
|
||||
while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex])
|
||||
addItem(syntax, lexerAuto, L"&Automatic");
|
||||
addItem(syntax, lexerPlain, L"&Plain text");
|
||||
constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"};
|
||||
const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'};
|
||||
HMENU group{};
|
||||
size_t groupIndex{};
|
||||
std::wstring assignedKeys;
|
||||
for (size_t i = 0; i < lexers.size(); ++i)
|
||||
{
|
||||
++groupIndex;
|
||||
group = nullptr;
|
||||
assignedKeys.clear();
|
||||
}
|
||||
if (!group) group = addGroup(syntax, groups[groupIndex].data());
|
||||
for (size_t position = 0; position < name.size(); ++position)
|
||||
{
|
||||
const auto key = static_cast<wchar_t>(std::towlower(name[position]));
|
||||
if (((key >= L'a' && key <= L'z') || (key >= L'0' && key <= L'9')) &&
|
||||
assignedKeys.find(key) == assignedKeys.npos)
|
||||
auto name = wide(lexers[i]);
|
||||
const auto letter = std::towlower(name.front());
|
||||
while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex])
|
||||
{
|
||||
assignedKeys += key;
|
||||
name.insert(position, 1, L'&');
|
||||
break;
|
||||
++groupIndex;
|
||||
group = nullptr;
|
||||
assignedKeys.clear();
|
||||
}
|
||||
if (!group) group = addGroup(syntax, groups[groupIndex].data());
|
||||
for (size_t position = 0; position < name.size(); ++position)
|
||||
{
|
||||
const auto key = static_cast<wchar_t>(std::towlower(name[position]));
|
||||
if (((key >= L'a' && key <= L'z') || (key >= L'0' && key <= L'9')) &&
|
||||
assignedKeys.find(key) == assignedKeys.npos)
|
||||
{
|
||||
assignedKeys += key;
|
||||
name.insert(position, 1, L'&');
|
||||
break;
|
||||
}
|
||||
}
|
||||
addItem(group, static_cast<UINT>(lexerStart + i), name.c_str());
|
||||
}
|
||||
addItem(group, static_cast<UINT>(lexerStart + i), name.c_str());
|
||||
}
|
||||
addItem(menu, options, L"&Options…");
|
||||
menuRoot = menu;
|
||||
@@ -1190,7 +1267,7 @@ void TextWindow::updateMenus()
|
||||
|
||||
void TextWindow::installLexer()
|
||||
{
|
||||
lexer = createTextLexer(language);
|
||||
lexer = hex?nullptr:createTextLexer(language);
|
||||
send(SCI_SETILEXER, 0, reinterpret_cast<LPARAM>(lexer));
|
||||
applyPreferences();
|
||||
send(SCI_COLOURISE, 0, -1);
|
||||
@@ -1278,9 +1355,9 @@ void TextWindow::applyPreferences()
|
||||
send(SCI_SETUSETABS, !prefs.tabsAsSpaces);
|
||||
send(SCI_SETTABINDENTS, TRUE);
|
||||
send(SCI_SETBACKSPACEUNINDENTS, TRUE);
|
||||
send(SCI_SETWRAPMODE, prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE);
|
||||
send(SCI_SETVIEWWS, prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE);
|
||||
send(SCI_SETVIEWEOL, prefs.whitespace);
|
||||
send(SCI_SETWRAPMODE, !hex && prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE);
|
||||
send(SCI_SETVIEWWS, !hex && prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE);
|
||||
send(SCI_SETVIEWEOL, !hex && prefs.whitespace);
|
||||
applyLineEnding();
|
||||
updateLineNumberMargin();
|
||||
layout();
|
||||
@@ -1290,7 +1367,7 @@ void TextWindow::applyPreferences()
|
||||
void TextWindow::updateLineNumberMargin()
|
||||
{
|
||||
LRESULT width{};
|
||||
if (prefs.numbers)
|
||||
if (prefs.numbers && !hex)
|
||||
{
|
||||
const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size();
|
||||
const std::string sample(digits, '9');
|
||||
@@ -1311,12 +1388,13 @@ void TextWindow::applyLineEnding()
|
||||
|
||||
void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
|
||||
{
|
||||
auto data=cached?std::move(*cached):document->readPage(index);
|
||||
const auto offset = document->boundary(index);
|
||||
const auto offset=hex?index*hexPageBytes:document->boundary(index);
|
||||
auto data=cached?std::move(*cached):hex?formatHexPage(document->readBytes(offset,hexPageBytes),offset):
|
||||
document->readPage(index);
|
||||
page = index;
|
||||
pageOffset = offset;
|
||||
pageTotal = document->pages();
|
||||
fileSize = document->size();
|
||||
pageTotal = hex?1+(fileSize?fileSize-1:0)/hexPageBytes:document->pages();
|
||||
stagedDirty = document->modified();
|
||||
const auto eol = data.find_first_of("\r\n");
|
||||
pageEol = eol == data.npos ? SC_EOL_CRLF : data[eol] == '\n' ? SC_EOL_LF :
|
||||
@@ -1342,6 +1420,137 @@ void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
|
||||
invalidate();
|
||||
}
|
||||
|
||||
void TextWindow::toggleHex()
|
||||
{
|
||||
if(edit || embedded || !document) return;
|
||||
if(hex)
|
||||
{
|
||||
const auto restored=beforeHex.value_or(ViewerPosition{});
|
||||
const auto index=std::min(restored.page,document->pages()-1);
|
||||
auto normal=beforeHex?nullptr:std::make_unique<TextDocument>(remote?remote->cache:original,false);
|
||||
auto text=(normal?normal.get():document.get())->readPage(index);
|
||||
if(normal)
|
||||
{
|
||||
document=std::move(normal);
|
||||
language=automatic=detectLanguage(original,text);
|
||||
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
|
||||
}
|
||||
hex=false;
|
||||
beforeHex.reset();
|
||||
installLexer();
|
||||
loadPage(index,std::move(text));
|
||||
restorePosition(restored);
|
||||
updatePreview();
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto index=pageOffset/hexPageBytes;
|
||||
const auto offset=index*hexPageBytes;
|
||||
auto bytes=formatHexPage(document->readBytes(offset,hexPageBytes),offset);
|
||||
beforeHex=currentPosition();
|
||||
hex=true;
|
||||
stopPreview(false,true);
|
||||
installLexer();
|
||||
loadPage(index,std::move(bytes));
|
||||
focusContent();
|
||||
}
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
updateTitle();
|
||||
invalidate();
|
||||
}
|
||||
|
||||
bool TextWindow::openBookmark(const ViewerBookmark &bookmark)
|
||||
{
|
||||
if(edit || hex || embedded || remote || !document || compareBookmarkPaths(original,bookmark.path)!=0) return false;
|
||||
if(IsIconic(window)) ShowWindow(window,SW_RESTORE);
|
||||
SetForegroundWindow(window);
|
||||
locateBookmark(bookmark.line);
|
||||
return true;
|
||||
}
|
||||
|
||||
void TextWindow::locateBookmark(uint64_t line)
|
||||
{
|
||||
if(!document || edit || hex || embedded || remote)
|
||||
{
|
||||
search.style.message(window,L"Line bookmarks are available for local files in the text Viewer.");
|
||||
return;
|
||||
}
|
||||
if(bookmarkTask.valid()) bookmarkStop.request_stop();
|
||||
bookmarkStop=std::stop_source{};
|
||||
const auto token=bookmarkStop.get_token();
|
||||
const auto currentPage=page;
|
||||
const auto caret=static_cast<size_t>(std::max<LRESULT>(0,send(SCI_GETCURRENTPOS)));
|
||||
const auto encoding=document->encoding();
|
||||
std::packaged_task<BookmarkLocation()> task([path=original,currentPage,caret,encoding,line,token] {
|
||||
auto source=std::make_unique<TextDocument>(path,false,encoding);
|
||||
if(!line) return BookmarkLocation{path,source->lineAt(currentPage,caret,token),true,{},{}};
|
||||
const auto position=source->locateLine(line,token);
|
||||
return BookmarkLocation{path,line,false,position,std::move(source)};
|
||||
});
|
||||
if(!SetTimer(window,bookmarkTimer,40,nullptr)) throw std::runtime_error("Cannot start locating the bookmarked line.");
|
||||
bookmarkTask=task.get_future();
|
||||
try {std::thread(std::move(task)).detach();}
|
||||
catch(...)
|
||||
{
|
||||
bookmarkTask={};
|
||||
KillTimer(window,bookmarkTimer);
|
||||
throw;
|
||||
}
|
||||
invalidateStatus();
|
||||
}
|
||||
|
||||
void TextWindow::finishBookmark()
|
||||
{
|
||||
if(!bookmarkTask.valid() || bookmarkTask.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
KillTimer(window,bookmarkTimer);
|
||||
auto result=bookmarkTask.get();
|
||||
invalidateStatus();
|
||||
if(edit || hex || !document || compareBookmarkPaths(result.path,original)!=0) return;
|
||||
if(result.adding)
|
||||
{
|
||||
BookmarkPrompt prompt{search.style,{result.path,result.line,{}}};
|
||||
const auto bookmarks=readViewerBookmarks(viewerBookmarksFile());
|
||||
const auto same=std::find_if(bookmarks.begin(),bookmarks.end(),[&](const auto &entry){
|
||||
return sameViewerBookmark(entry,prompt.bookmark);
|
||||
});
|
||||
if(same!=bookmarks.end()) prompt.bookmark.name=same->name;
|
||||
if(search.style.run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(613),window,bookmarkNameDialog,
|
||||
reinterpret_cast<LPARAM>(&prompt))==IDOK) focusContent();
|
||||
return;
|
||||
}
|
||||
if(!result.position)
|
||||
{
|
||||
search.style.message(window,L"The bookmarked line is no longer in the file.");
|
||||
return;
|
||||
}
|
||||
showBookmarkSource=true;
|
||||
if(previewWanted || previewVisible) stopPreview(true,true);
|
||||
document=std::move(result.source);
|
||||
loadPage(result.position->page);
|
||||
send(SCI_GOTOPOS,result.position->offset);
|
||||
send(SCI_SCROLLCARET);
|
||||
focusContent();
|
||||
}
|
||||
|
||||
void openChosenBookmark(HWND owner,TextDialogs style,const ViewerBookmark &bookmark)
|
||||
{
|
||||
for(const auto &entry:textWindows)
|
||||
if(entry.second->openBookmark(bookmark)) return;
|
||||
openTextWindow(owner,bookmark.path,false,style,nullptr,{},true,{.line=bookmark.line});
|
||||
}
|
||||
|
||||
void TextWindow::pickBookmark(bool currentFile)
|
||||
{
|
||||
if(currentFile && remote)
|
||||
{
|
||||
search.style.message(window,L"Line bookmarks are available for local files in the text Viewer.");
|
||||
return;
|
||||
}
|
||||
const auto selected=selectViewerBookmark(window,search.style,currentFile?original:std::filesystem::path{});
|
||||
if(selected) openChosenBookmark(window,search.style,*selected);
|
||||
}
|
||||
|
||||
void TextWindow::stagePage()
|
||||
{
|
||||
if (!currentChanged()) return;
|
||||
@@ -1361,6 +1570,15 @@ void TextWindow::go(uint64_t index)
|
||||
|
||||
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
|
||||
{
|
||||
if(hex)
|
||||
{
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
installLexer();
|
||||
loadPage(0);
|
||||
updateTitle();
|
||||
return;
|
||||
}
|
||||
if(!firstPage) firstPage=document->readPage(0);
|
||||
automatic=detectLanguage(original,*firstPage);
|
||||
language=automatic;
|
||||
@@ -1374,6 +1592,7 @@ void TextWindow::initializeDocument(std::optional<std::string> firstPage)
|
||||
installLexer();
|
||||
loadPage(0,std::move(firstPage));
|
||||
updatePreview();
|
||||
if(initialBookmark) locateBookmark(std::exchange(initialBookmark,0));
|
||||
}
|
||||
|
||||
std::string readMarkdownDocument(TextDocument &document)
|
||||
@@ -1460,7 +1679,7 @@ void TextWindow::finishOpen()
|
||||
{
|
||||
opening.get();
|
||||
if(cancelOpen) { DestroyWindow(window); return; }
|
||||
document=std::make_unique<TextDocument>(remote->cache,edit);
|
||||
document=std::make_unique<TextDocument>(remote->cache,edit,hex?TextEncoding::utf8:TextEncoding::automatic);
|
||||
initializeDocument();
|
||||
invalidate();
|
||||
}
|
||||
@@ -1473,14 +1692,13 @@ void TextWindow::finishOpen()
|
||||
|
||||
void TextWindow::saveFile(bool closeWhenDone)
|
||||
{
|
||||
if (busy() || !edit) return;
|
||||
if (busy() || savedViewerLoad.valid() || !edit) return;
|
||||
auto destination=original;
|
||||
if(draft && !search.style.saveOptions(window,destination,newFormat)) return;
|
||||
stagePage();
|
||||
if (!draft && !stagedDirty && !uploadPending)
|
||||
{
|
||||
if (closeWhenDone) DestroyWindow(window);
|
||||
else if (std::exchange(switchAfterSave, false)) changeMode();
|
||||
return;
|
||||
}
|
||||
pendingCaret = send(SCI_GETCURRENTPOS);
|
||||
@@ -1521,7 +1739,6 @@ void TextWindow::finishSave()
|
||||
return;
|
||||
}
|
||||
send(SCI_SETREADONLY, !edit);
|
||||
const auto change = std::exchange(switchAfterSave, false);
|
||||
const auto reopened = saving.get();
|
||||
stagedDirty = false;
|
||||
const bool created=std::exchange(draft,false);
|
||||
@@ -1539,7 +1756,6 @@ void TextWindow::finishSave()
|
||||
return;
|
||||
}
|
||||
if (closeAfterSave) { DestroyWindow(window); return; }
|
||||
if (change) { changeMode(); return; }
|
||||
if(created)
|
||||
{
|
||||
initializeDocument();
|
||||
@@ -1560,11 +1776,17 @@ void TextWindow::requestClose()
|
||||
{
|
||||
if (opening.valid()) { cancelOpen=true; return; }
|
||||
if (busy()) return;
|
||||
cancelSavedViewerLoad();
|
||||
if (needsSave())
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window,draft);
|
||||
if (answer == IDCANCEL) return;
|
||||
if (answer == IDYES) { saveFile(true); return; }
|
||||
if (answer == IDYES)
|
||||
{
|
||||
if(suspendedEditor) restoreEditor();
|
||||
saveFile(true);
|
||||
return;
|
||||
}
|
||||
if (answer != IDNO) return;
|
||||
}
|
||||
DestroyWindow(window);
|
||||
@@ -1572,54 +1794,61 @@ void TextWindow::requestClose()
|
||||
|
||||
bool TextWindow::needsSave() const
|
||||
{
|
||||
if(suspendedEditor) return suspendedEditor->uploadPending || suspendedEditor->document->modified();
|
||||
return uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty);
|
||||
}
|
||||
|
||||
void TextWindow::toggleMode()
|
||||
{
|
||||
if (busy() || navigation.valid()) return;
|
||||
if(draft) return;
|
||||
if (edit && needsSave())
|
||||
if (busy() || navigation.valid() || savedViewerLoad.valid()) return;
|
||||
if(suspendedEditor)
|
||||
{
|
||||
const auto answer = search.style.confirmSave(window,false);
|
||||
if (answer == IDYES)
|
||||
restoreEditor();
|
||||
return;
|
||||
}
|
||||
if(edit && (draft || needsSave()))
|
||||
{
|
||||
if(!uploadPending) suspendEditor();
|
||||
else
|
||||
{
|
||||
switchAfterSave = true;
|
||||
try { saveFile(false); }
|
||||
catch (...) { switchAfterSave = false; throw; }
|
||||
return;
|
||||
}
|
||||
if (answer != IDNO) return;
|
||||
// The local LAN cache may already contain changes from a failed upload.
|
||||
if (uploadPending)
|
||||
{
|
||||
auto refreshed = std::make_unique<RemoteTextFile>(remote->source,original);
|
||||
refreshed->download(false,{});
|
||||
auto replacement = std::make_unique<TextDocument>(refreshed->cache,false);
|
||||
document.reset();
|
||||
remote = std::move(refreshed);
|
||||
document = std::move(replacement);
|
||||
uploadPending = false;
|
||||
auto cancel=std::make_shared<std::atomic<bool>>(false);
|
||||
if(!SetTimer(window,savedViewerTimer,75,nullptr))
|
||||
throw std::runtime_error("Cannot start loading the saved version.");
|
||||
try
|
||||
{
|
||||
savedViewerLoad=fetchRemoteText(remote->source,original,cancel);
|
||||
cancelSavedViewer=std::move(cancel);
|
||||
}
|
||||
catch(...) {KillTimer(window,savedViewerTimer); throw;}
|
||||
invalidate();
|
||||
}
|
||||
return;
|
||||
}
|
||||
changeMode();
|
||||
}
|
||||
|
||||
void TextWindow::changeMode()
|
||||
TextWindow::ViewerPosition TextWindow::currentPosition() const
|
||||
{
|
||||
return {page,send(SCI_GETANCHOR),send(SCI_GETCURRENTPOS),send(SCI_GETFIRSTVISIBLELINE),send(SCI_GETXOFFSET)};
|
||||
}
|
||||
|
||||
void TextWindow::restorePosition(const ViewerPosition &position)
|
||||
{
|
||||
const auto length=send(SCI_GETLENGTH);
|
||||
send(SCI_SETSEL,std::clamp<LRESULT>(position.anchor,0,length),std::clamp<LRESULT>(position.caret,0,length));
|
||||
send(SCI_SETFIRSTVISIBLELINE,position.firstLine);
|
||||
send(SCI_SETXOFFSET,position.horizontal);
|
||||
}
|
||||
|
||||
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents)
|
||||
{
|
||||
if (!edit && remote && !remote->revision.editable)
|
||||
throw std::runtime_error("The remote file does not support editing.");
|
||||
auto replacement = std::make_unique<TextDocument>(remote ? remote->cache : original, !edit);
|
||||
const auto caret = send(SCI_GETCURRENTPOS);
|
||||
document = std::move(replacement);
|
||||
edit = !edit;
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
prefs = loadTextPreferences().profiles[edit];
|
||||
releaseMenu();
|
||||
createMenu();
|
||||
installLexer();
|
||||
loadPage(std::min(page, document->pages() - 1));
|
||||
send(SCI_GOTOPOS, std::min(caret, send(SCI_GETLENGTH)));
|
||||
loadPage(position.page,std::move(contents));
|
||||
restorePosition(position);
|
||||
updateTitle();
|
||||
updateIcons(GetDpiForWindow(window));
|
||||
updateTaskbarGroup();
|
||||
@@ -1628,9 +1857,71 @@ void TextWindow::changeMode()
|
||||
focusContent();
|
||||
}
|
||||
|
||||
void TextWindow::changeMode()
|
||||
{
|
||||
if(!edit && remote && !remote->revision.editable)
|
||||
throw std::runtime_error("The remote file does not support editing.");
|
||||
auto position=currentPosition();
|
||||
auto replacement=std::make_unique<TextDocument>(remote?remote->cache:original,!edit,document->encoding());
|
||||
position.page=std::min(position.page,replacement->pages()-1);
|
||||
auto contents=replacement->readPage(position.page);
|
||||
document=std::move(replacement);
|
||||
edit=!edit;
|
||||
showTextMode(position,std::move(contents));
|
||||
}
|
||||
|
||||
void TextWindow::suspendEditor(std::unique_ptr<RemoteTextFile> saved)
|
||||
{
|
||||
const auto position=currentPosition();
|
||||
const auto path=draft?std::filesystem::path{}:saved?saved->cache:remote?remote->cache:original;
|
||||
auto replacement=std::make_unique<TextDocument>(path,false,document->encoding());
|
||||
auto viewing=position;
|
||||
viewing.page=std::min(viewing.page,replacement->pages()-1);
|
||||
auto contents=replacement->readPage(viewing.page);
|
||||
stagePage();
|
||||
suspendedEditor=SuspendedEditor{std::move(document),position,std::exchange(uploadPending,false)};
|
||||
document=std::move(replacement);
|
||||
savedViewerFile=std::move(saved);
|
||||
edit=false;
|
||||
showTextMode(viewing,std::move(contents));
|
||||
}
|
||||
|
||||
void TextWindow::restoreEditor()
|
||||
{
|
||||
const auto position=suspendedEditor->position;
|
||||
auto contents=suspendedEditor->document->readPage(position.page);
|
||||
document=std::move(suspendedEditor->document);
|
||||
uploadPending=suspendedEditor->uploadPending;
|
||||
suspendedEditor.reset();
|
||||
savedViewerFile.reset();
|
||||
edit=true;
|
||||
hex=false;
|
||||
beforeHex.reset();
|
||||
showTextMode(position,std::move(contents));
|
||||
}
|
||||
|
||||
void TextWindow::finishSavedViewer()
|
||||
{
|
||||
if(!savedViewerLoad.valid() || savedViewerLoad.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||||
KillTimer(window,savedViewerTimer);
|
||||
cancelSavedViewer.reset();
|
||||
invalidate();
|
||||
suspendEditor(savedViewerLoad.get());
|
||||
}
|
||||
|
||||
void TextWindow::cancelSavedViewerLoad()
|
||||
{
|
||||
if(!savedViewerLoad.valid()) return;
|
||||
*cancelSavedViewer=true;
|
||||
cancelSavedViewer.reset();
|
||||
savedViewerLoad={};
|
||||
KillTimer(window,savedViewerTimer);
|
||||
invalidate();
|
||||
}
|
||||
|
||||
void TextWindow::updateTitle()
|
||||
{
|
||||
const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") +
|
||||
const auto title = std::wstring(edit ? L"Editor — " : hex ? L"Hex Viewer — " : L"Viewer — ") +
|
||||
(remote ? remote->source.name + L" · " : std::wstring{}) + original.wstring();
|
||||
SetWindowTextW(window,title.c_str());
|
||||
}
|
||||
@@ -1668,7 +1959,8 @@ void TextWindow::updateTaskbarGroup(bool closing)
|
||||
|
||||
bool TextWindow::canPreview() const
|
||||
{
|
||||
return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit;
|
||||
return !edit && !hex && !showBookmarkSource && automatic.lexer=="markdown" && document &&
|
||||
document->size()<=TextDocument::editLimit;
|
||||
}
|
||||
|
||||
void TextWindow::updatePreview()
|
||||
@@ -1709,6 +2001,11 @@ bool TextWindow::startPreviewBrowser()
|
||||
PostMessageW(window,WM_COMMAND,key=='F'?findText:shift?findPrevious:findNext,0);
|
||||
return true;
|
||||
}
|
||||
if(ctrl && !alt && key=='D')
|
||||
{
|
||||
PostMessageW(window,WM_COMMAND,addBookmark,0);
|
||||
return true;
|
||||
}
|
||||
if(ctrl && !alt && key==VK_TAB)
|
||||
{
|
||||
PostMessageW(window,cycleWindow,(GetKeyState(VK_SHIFT)&0x8000)!=0,0);
|
||||
@@ -1719,8 +2016,8 @@ bool TextWindow::startPreviewBrowser()
|
||||
PostMessageW(window,WM_COMMAND,key==VK_LEFT || key==VK_BROWSER_BACK?historyBack:historyForward,0);
|
||||
return true;
|
||||
}
|
||||
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
|
||||
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0);
|
||||
if(key!=VK_F4 && key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
|
||||
PostMessageW(window,WM_COMMAND,key==VK_F4?switchHex:key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -1788,7 +2085,7 @@ void TextWindow::renderPreview(bool keepPosition)
|
||||
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
|
||||
if(!remote) document->releaseReadHandle();
|
||||
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
|
||||
{"canSave",!embedded && (!remote || remote->revision.editable)},{"compact",embedded},
|
||||
{"canSave",!embedded && !suspendedEditor && (!remote || remote->revision.editable)},{"compact",embedded},
|
||||
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
|
||||
{"keepPosition",keepPosition}};
|
||||
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
|
||||
@@ -1838,7 +2135,7 @@ void TextWindow::startMarkdownTask()
|
||||
{
|
||||
const auto task=std::exchange(pendingTask,{});
|
||||
if(!task) return;
|
||||
if(!previewVisible || edit || busy() || navigation.valid() || task->revision!=previewRevision ||
|
||||
if(!previewVisible || edit || suspendedEditor || busy() || navigation.valid() || task->revision!=previewRevision ||
|
||||
(remote && !remote->revision.editable))
|
||||
{
|
||||
reportMarkdownTask(task->revision,false);
|
||||
@@ -2028,13 +2325,18 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
|
||||
void TextWindow::syncNavigation()
|
||||
{
|
||||
preview.post(wide(nlohmann::json{{"action","history"},{"back",navigationIndex>0},
|
||||
{"forward",navigationIndex+1<navigationHistory.size()}}.dump()));
|
||||
preview.post(wide(nlohmann::json{{"action","history"},{"back",!suspendedEditor && navigationIndex>0},
|
||||
{"forward",!suspendedEditor && navigationIndex+1<navigationHistory.size()}}.dump()));
|
||||
}
|
||||
|
||||
void TextWindow::navigatePreview(PreviewLink request)
|
||||
{
|
||||
if(edit || busy() || pendingTask || navigation.valid() || navigationHistory.empty()) return;
|
||||
if(suspendedEditor)
|
||||
{
|
||||
if(request.direction) return;
|
||||
if(request.target.path!=original) request.newWindow=true;
|
||||
}
|
||||
if(request.newWindow)
|
||||
{
|
||||
if(remote)
|
||||
@@ -2055,19 +2357,11 @@ void TextWindow::navigatePreview(PreviewLink request)
|
||||
else destination=std::move(request.target);
|
||||
if(destination.path==original || !remote) { showLocation(nullptr); return; }
|
||||
auto cancel=std::make_shared<std::atomic<bool>>(false);
|
||||
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task(
|
||||
[backend=remote->source,path=destination.path,cancel] {
|
||||
auto file=std::make_unique<RemoteTextFile>(backend,path);
|
||||
file->download(false,[cancel](uint64_t,uint64_t){return !*cancel;});
|
||||
return file;
|
||||
});
|
||||
if(!SetTimer(window,navigationTimer,75,nullptr))
|
||||
throw std::runtime_error("Cannot start the remote navigation timer.");
|
||||
try
|
||||
{
|
||||
auto result=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
navigation=std::move(result);
|
||||
navigation=fetchRemoteText(remote->source,destination.path,cancel);
|
||||
cancelNavigation=std::move(cancel);
|
||||
}
|
||||
catch(...) { KillTimer(window,navigationTimer); throw; }
|
||||
@@ -2283,20 +2577,25 @@ void TextWindow::paint()
|
||||
const auto position=send(SCI_GETCURRENTPOS);
|
||||
const auto line=send(SCI_LINEFROMPOSITION,position)+1;
|
||||
const auto column=send(SCI_GETCOLUMN,position)+1;
|
||||
auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+
|
||||
const auto retained=suspendedEditor?L" │ Draft retained":L"";
|
||||
auto status=hex?filename+L" (Hex)"+retained+L" │ 0x"+wide(formatHexAddress(pageOffset+(line-1)*16)):
|
||||
filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+retained+
|
||||
L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+
|
||||
L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column);
|
||||
if(pageTotal>1)
|
||||
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
|
||||
L" @ "+std::to_wstring(pageOffset);
|
||||
status+=L" │ "+std::to_wstring(fileSize)+L" B";
|
||||
if(bookmarkTask.valid()) status+=L" │ Locating line…";
|
||||
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
|
||||
}
|
||||
const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" :
|
||||
const auto hints = busy() ? L"Saving…" : savedViewerLoad.valid()?L"Loading saved version…" :
|
||||
hex?L"F4 Text F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close":
|
||||
insertRejected ? L"Page edit limit: 8 MiB" :
|
||||
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
|
||||
previewVisible ? L"F6 Edit Ctrl+W Close" :
|
||||
previewVisible ? L"F4 Hex F6 Edit Ctrl+W Close" :
|
||||
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
|
||||
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
|
||||
L"F3 Find next F4 Hex F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
|
||||
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
|
||||
DrawTextW(dc, hints, -1, &bottom, format);
|
||||
SelectObject(dc, previous);
|
||||
@@ -2347,11 +2646,17 @@ void TextWindow::command(UINT id)
|
||||
{
|
||||
if(!document && id!=close) return;
|
||||
if (busy()) return;
|
||||
if(hex && (id==switchMode || id==historyBack || id==historyForward || id==findText || id==findNext ||
|
||||
id==findPrevious || id==lexerAuto || id==lexerPlain || id>=lexerStart)) return;
|
||||
switch (id)
|
||||
{
|
||||
case save: saveFile(false); return;
|
||||
case close: requestClose(); return;
|
||||
case switchMode: toggleMode(); return;
|
||||
case switchHex: toggleHex(); return;
|
||||
case addBookmark: if(!edit && !hex) locateBookmark(0); return;
|
||||
case currentBookmarks: if(!edit && !hex) pickBookmark(true); return;
|
||||
case allBookmarks: if(!edit && !hex) pickBookmark(false); return;
|
||||
case historyBack:
|
||||
case historyForward:
|
||||
if(previewVisible)
|
||||
@@ -2486,13 +2791,16 @@ bool TextWindow::handleKey(const MSG &message)
|
||||
UINT id{};
|
||||
if (key == VK_F2 || (ctrl && key == 'S')) id = save;
|
||||
if (key == VK_F3) id = findNext;
|
||||
if (key == VK_F4 && !ctrl && !shift && !edit) id = switchHex;
|
||||
if (key == VK_F5 || (ctrl && key == 'G')) id = goToPage;
|
||||
if (key == VK_F6) id = switchMode;
|
||||
if (key == VK_F9) id = 600;
|
||||
if (key == VK_ESCAPE || key == VK_F10 || (!edit && ctrl && key=='W')) id = close;
|
||||
if (key == VK_ESCAPE) id = hex && beforeHex?switchHex:close;
|
||||
if (key == VK_F10 || (!edit && ctrl && key=='W')) id = close;
|
||||
if (!edit && key==VK_BROWSER_BACK) id=historyBack;
|
||||
if (!edit && key==VK_BROWSER_FORWARD) id=historyForward;
|
||||
if (ctrl && key == 'F') id = findText;
|
||||
if (ctrl && key == 'D' && !edit && !hex) id = addBookmark;
|
||||
if (ctrl && key == VK_PRIOR) id = previousPage;
|
||||
if (ctrl && key == VK_NEXT) id = nextPage;
|
||||
if (ctrl && shift && key == VK_HOME) id = firstPage;
|
||||
@@ -2597,6 +2905,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
case WM_KEYDOWN:
|
||||
if(!self->embedded && self->previewWanted && !self->previewVisible)
|
||||
{
|
||||
if(wparam==VK_F4) self->command(switchHex);
|
||||
if(wparam==VK_F6) self->toggleMode();
|
||||
if(wparam==VK_ESCAPE || wparam==VK_F10 ||
|
||||
(wparam=='W' && (GetKeyState(VK_CONTROL)&0x8000))) self->requestClose();
|
||||
@@ -2657,6 +2966,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
if (wparam == previewTimer) self->pollImages();
|
||||
if (wparam == navigationTimer) self->finishNavigation();
|
||||
if (wparam == quickViewTimer) self->pollQuickView();
|
||||
if (wparam == bookmarkTimer) self->finishBookmark();
|
||||
if (wparam == savedViewerTimer) self->finishSavedViewer();
|
||||
return 0;
|
||||
case trimUndo:
|
||||
if (self->undoBytes >= 32 * TextDocument::pageBytes)
|
||||
@@ -2668,6 +2979,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
}
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
self->cancelSavedViewerLoad();
|
||||
self->bookmarkStop.request_stop();
|
||||
if(self->cancelNavigation) *self->cancelNavigation=true;
|
||||
if(!self->embedded) self->updateTaskbarGroup(true);
|
||||
self->stopPreview(false);
|
||||
@@ -2677,7 +2990,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
self->window=nullptr;
|
||||
textWindows.erase(window);
|
||||
std::erase(textWindowOrder,window);
|
||||
if(textOwnerClosed && textWindows.empty()) PostQuitMessage(0);
|
||||
if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -2795,12 +3108,12 @@ void textWindowOwnerClosed()
|
||||
{
|
||||
filesOwner=nullptr;
|
||||
textOwnerClosed=true;
|
||||
if(textWindows.empty()) PostQuitMessage(0);
|
||||
if(textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0);
|
||||
}
|
||||
|
||||
bool cycleTextWindows(HWND current,bool reverse)
|
||||
{
|
||||
if(!current || (current!=filesOwner && !textWindows.contains(current))) return false;
|
||||
if(!current) return false;
|
||||
std::vector<HWND> windows;
|
||||
if(filesOwner && IsWindowVisible(filesOwner)) windows.push_back(filesOwner);
|
||||
for(const auto window:textWindowOrder)
|
||||
@@ -2874,16 +3187,70 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
preview->second->previewFile(path);
|
||||
}
|
||||
|
||||
ImageViewStyle imageViewStyle(TextDialogs dialogs)
|
||||
{
|
||||
const auto font=dialogs.readFont();
|
||||
const auto colors=loadTextPreferences().profiles[0].colors;
|
||||
return {font.font,font.tenthsOfPoint,colors[0],colors[1],colors[2],colors[3],colors[4]};
|
||||
}
|
||||
|
||||
HWND createImageQuickView(HWND owner,TextDialogs dialogs)
|
||||
{
|
||||
return createImageView(owner,true,imageViewStyle(dialogs),{},{});
|
||||
}
|
||||
|
||||
void previewImageQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
{
|
||||
showImageViewFile(window,path);
|
||||
}
|
||||
|
||||
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
|
||||
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source)
|
||||
{
|
||||
try
|
||||
{
|
||||
const auto backend=source?std::optional(*source):peer?std::optional(lanTextSource(*peer)):std::nullopt;
|
||||
ImageLoad load;
|
||||
if(backend)
|
||||
load=[backend=*backend](const std::filesystem::path &original,std::stop_token stop) {
|
||||
RemoteTextFile file(backend,original);
|
||||
file.download(false,[&](uint64_t,uint64_t){return !stop.stop_requested();},imageSourceLimit);
|
||||
return decodeImage(file.cache,original,stop);
|
||||
};
|
||||
if(!textWindows.contains(owner)) filesOwner=owner;
|
||||
const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load),
|
||||
[](HWND closed) {
|
||||
std::erase(textWindowOrder,closed);
|
||||
if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0);
|
||||
});
|
||||
if(!window) throw std::runtime_error("Could not open the image viewer.");
|
||||
textWindowOrder.push_back(window);
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(IDI_FILES_VIEWER),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE);
|
||||
if(icon) SendMessageW(window,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(icon));
|
||||
setFileWindowTaskbar(window,IDI_FILES_VIEWER,L"HrynCo.KSwitcher.Files.Viewer");
|
||||
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
SetFocus(window);
|
||||
}
|
||||
catch(const std::exception &error) {dialogs.message(owner,wide(error.what()).c_str());}
|
||||
}
|
||||
|
||||
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options)
|
||||
{
|
||||
if(!edit && !options.draft && !options.hex && !options.line && isImagePath(path))
|
||||
{
|
||||
openImageWindow(owner,{path},path,dialogs,nullptr,backend);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if(!textWindows.contains(owner)) filesOwner=owner;
|
||||
std::error_code error;
|
||||
const auto identity=backend?path.lexically_normal():std::filesystem::weakly_canonical(path,error);
|
||||
const auto &original=error?path:identity;
|
||||
if(const auto existing=newWindow?nullptr:findOpenDocument(original,backend?backend->id:""))
|
||||
if(const auto existing=newWindow || options.hex || options.line?nullptr:
|
||||
findOpenDocument(original,backend?backend->id:""))
|
||||
{
|
||||
if(dialogs.confirmExisting(owner) && IsWindow(existing))
|
||||
{
|
||||
@@ -2898,7 +3265,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
if(!registerTextWindowClass(instance)) throw std::runtime_error("Cannot register the text window.");
|
||||
auto state=std::make_shared<TextWindow>(original,edit,dialogs,backend,fragment,options);
|
||||
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
|
||||
const auto title=std::wstring(edit?L"Editor — ":options.hex?L"Hex Viewer — ":L"Viewer — ")+
|
||||
(backend?backend->name+L" · ":std::wstring{})+path.wstring();
|
||||
RECT bounds{};
|
||||
GetWindowRect(owner,&bounds);
|
||||
@@ -2920,8 +3287,18 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
}
|
||||
|
||||
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
const RemoteTextSource &source,std::string_view fragment,bool newWindow)
|
||||
const RemoteTextSource &source,std::string_view fragment,bool newWindow,TextOpenOptions options)
|
||||
{
|
||||
openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,{});
|
||||
openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,options);
|
||||
}
|
||||
|
||||
void showAllViewerBookmarks(HWND owner,TextDialogs dialogs)
|
||||
{
|
||||
try
|
||||
{
|
||||
const auto selected=selectViewerBookmark(owner,dialogs);
|
||||
if(selected) openChosenBookmark(owner,dialogs,*selected);
|
||||
}
|
||||
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,8 @@ struct TextOpenOptions
|
||||
{
|
||||
TextEncoding encoding=TextEncoding::automatic;
|
||||
bool draft{};
|
||||
bool hex{};
|
||||
uint64_t line{};
|
||||
};
|
||||
|
||||
struct RemoteTextRevision
|
||||
@@ -83,12 +85,17 @@ struct RemoteTextSource
|
||||
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();
|
||||
bool cycleTextWindows(HWND current,bool reverse);
|
||||
}
|
||||
@@ -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 {};
|
||||
}
|
||||
@@ -1,12 +1,37 @@
|
||||
#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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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,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;
|
||||
}
|
||||
@@ -140,8 +140,53 @@ 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 saveDraft(const fs::path &file)
|
||||
@@ -191,6 +236,8 @@ 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");
|
||||
sparseFile(fixture.directory / L"5gib.log");
|
||||
std::cout << "Files text document regressions passed.\n";
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user