Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4147ccc04a | ||
|
|
cde7dacffc | ||
|
|
f1077909ef |
No files matched your search
+15
-3
@@ -1,18 +1,19 @@
|
||||
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)
|
||||
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)
|
||||
@@ -153,6 +154,17 @@ 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(KSwitcherFilesModalTests tests/files_modal_dialog.cpp)
|
||||
target_include_directories(KSwitcherFilesModalTests PRIVATE src)
|
||||
target_link_libraries(KSwitcherFilesModalTests PRIVATE user32 comctl32)
|
||||
@@ -319,7 +331,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 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 .)
|
||||
|
||||
@@ -627,6 +627,12 @@ Warning і початковий фокус на No.
|
||||
панелі, результати пошуку й віртуальні елементи Explorer без локального
|
||||
шляху не підтримують перетягування. Files повідомляє причину в рядку стану.
|
||||
|
||||
## Архіви ZIP і 7z
|
||||
|
||||
- Enter на локальному архіві відкриває його в поточній панелі. Заголовок панелі починається з Read-only і містить ім’я архіву та шлях усередині нього. Enter відкриває папки всередині архіву, а рядок `..`, Alt+Up і Escape піднімають на один рівень. Вихід із кореня повертає курсор на архів.
|
||||
- F3 відкриває текстовий файл у спільному переглядачі. F5 копіює позначені записи або поточний запис у локальну папку через спільні діалоги Copy, конфлікту та прогресу. F4, F6, F7 і F8 не змінюють вміст архіву.
|
||||
- Небезпечні шляхи й посилання блокують читання архіву. Для зашифрованих записів та архівів із зашифрованими заголовками Files показує підказку про пароль.
|
||||
|
||||
## Діалог Copy
|
||||
|
||||
- Вирівнюй підпис Existing files по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені.
|
||||
|
||||
@@ -67,6 +67,10 @@ 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' }
|
||||
& $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)
|
||||
+2
-1
@@ -12,6 +12,7 @@ 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 '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 +21,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','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,217 @@
|
||||
#include "files_archive.h"
|
||||
#include "files_win32_directory.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)>;
|
||||
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.";
|
||||
|
||||
[[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.");
|
||||
constexpr int64_t epochOffset=11644473600, ticksPerSecond=10000000;
|
||||
const int64_t seconds=archive_entry_mtime(entry);
|
||||
const auto modified=archive_entry_mtime_is_set(entry) && seconds>=-epochOffset &&
|
||||
seconds<(INT64_MAX/ticksPerSecond-epochOffset)?
|
||||
static_cast<uint64_t>((seconds+epochOffset)*ticksPerSecond+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(),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.");
|
||||
struct Output
|
||||
{
|
||||
HANDLE file;
|
||||
~Output() {CloseHandle(file);}
|
||||
};
|
||||
const HANDLE handle=CreateFileW(output.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(handle==INVALID_HANDLE_VALUE) throw std::system_error(GetLastError(),std::system_category());
|
||||
const Output owned{handle};
|
||||
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(handle,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(handle,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 *,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,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,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.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
+218
-57
@@ -27,6 +27,7 @@
|
||||
#include <winternl.h>
|
||||
#include <wininet.h>
|
||||
#include "files_terminal.h"
|
||||
#include "files_archive.h"
|
||||
#include "files_win32_directory.h"
|
||||
#include "files_command_completion.h"
|
||||
#include "files_text_window.h"
|
||||
@@ -53,6 +54,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 +485,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 +498,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 +549,7 @@ struct Panel
|
||||
std::optional<FtpProfile> ftp;
|
||||
std::optional<FindOptions> find;
|
||||
std::optional<size_t> navigationPosition;
|
||||
std::optional<ArchiveLocation> archive;
|
||||
};
|
||||
struct ScanResult
|
||||
{
|
||||
@@ -552,6 +562,7 @@ struct Panel
|
||||
fs::path ftpInitialDirectory;
|
||||
std::vector<DirectoryRow> ordered;
|
||||
ColumnMetadataMap columnMetadata;
|
||||
std::shared_ptr<const ks::files::ArchiveEntries> archiveEntries;
|
||||
};
|
||||
struct TreeBranch
|
||||
{
|
||||
@@ -620,6 +631,11 @@ 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"Read-only · "+display.native();
|
||||
}
|
||||
return panel.findOrigin?L"Search results":panelLocation(panel);
|
||||
}
|
||||
|
||||
@@ -1989,7 +2005,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 +2049,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 +2076,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 +2200,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 +2233,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 +2564,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 +2572,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 +2728,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 +2821,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 +2829,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 +2857,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 +2928,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 +2944,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 +2969,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 +2977,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 +3023,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 +3061,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 +3096,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 +3115,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 +3222,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;
|
||||
@@ -3976,7 +4049,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,7 +4079,7 @@ 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{});
|
||||
}
|
||||
@@ -4021,7 +4094,7 @@ void toggleQuickView(HWND owner)
|
||||
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 +4124,39 @@ bool handleQuickViewKey(HWND window,const MSG &message)
|
||||
|
||||
ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile);
|
||||
|
||||
void openArchiveText(const Panel &panel,const fs::path &path)
|
||||
{
|
||||
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};
|
||||
},{}};
|
||||
ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive);
|
||||
}
|
||||
|
||||
void openSelectedText(const Panel &panel, bool edit, bool external)
|
||||
{
|
||||
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]);
|
||||
return;
|
||||
}
|
||||
if((panel.peer || panel.ftp) && external)
|
||||
{
|
||||
setStatus(L"Copy the remote file to a local panel before opening it.");
|
||||
@@ -4086,6 +4187,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 +4202,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 +4229,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 +4755,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 +4825,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 +4994,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 {
|
||||
@@ -5964,11 +6056,47 @@ 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(destination.archive || (!archive.empty() && move))
|
||||
{
|
||||
setStatus(L"Archive entries are read-only. Use F5 to extract them to a local folder.");
|
||||
return;
|
||||
}
|
||||
if(!archive.empty() && (destination.peer || destination.ftp))
|
||||
{
|
||||
setStatus(L"Open a local destination folder to extract archive entries.");
|
||||
return;
|
||||
}
|
||||
if(quickViewWindow && &destination!=&panels[quickViewSource] && !ftpRename)
|
||||
{
|
||||
setStatus(L"Close Quick View to use the destination pane.");
|
||||
@@ -6003,6 +6131,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 +6153,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 +6185,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 +6230,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 +6259,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 +6285,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 +6500,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)
|
||||
{
|
||||
@@ -6586,7 +6740,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent)
|
||||
bool pastePanelFiles(HWND owner,Panel &panel)
|
||||
{
|
||||
if(!IsClipboardFormatAvailable(CF_HDROP)) return false;
|
||||
if(panel.peer || panel.ftp || panel.findOrigin)
|
||||
if(panel.peer || panel.ftp || panel.findOrigin || panel.archive)
|
||||
{
|
||||
setStatus(L"Open a local folder before pasting files.");
|
||||
return true;
|
||||
@@ -6811,6 +6965,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 +7162,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,
|
||||
@@ -7897,7 +8053,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 +8433,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)));
|
||||
}
|
||||
@@ -8420,11 +8576,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,{});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,150 @@
|
||||
#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");
|
||||
return 0;
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
std::cerr<<error.what()<<'\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user