Compare commits

..
23 changed files with 1446 additions and 187 deletions

No files matched your search

+15 -3
View File
@@ -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 .)
+17 -5
View File
@@ -294,7 +294,7 @@ Warning і початковий фокус на No.
- Ctrl+Shift+0–9 відкриває діалог Title і Path із поточною папкою. OK додає запис без дублювання, Escape скасовує. Title необов’язковий, порожнє значення показує шлях. Записи LAN зберігають ID ПК, а редагування Path залишає запис на тому самому ПК.
- Ctrl+0–9 відкриває лише папки, призначені натиснутій цифрі. Єдина папка відкривається одразу. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10 перемикає List і Tree. Ctrl+F11 перемикає фоновий підрахунок розмірів папок. Brief і Wide також доступні в меню Left/Right та Options.
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10 перемикає List і Tree. Ctrl+F11 перемикає фоновий підрахунок розмірів папок. Brief, Wide, Medium і Full доступні в меню Left/Right та Options → Panel layout.
## Налаштування Files
@@ -542,10 +542,16 @@ Warning і початковий фокус на No.
для прихованих фільтром елементів, які ще є в поточній папці.
Ctrl+F9 перемикає показ прихованих та системних елементів окремо для
кожної панелі. Типово їх видно. Маска діє до закриття вікна.
- Wide показує Name, Ext, Size і Modified. Modified відображає місцеву
дату, а сортування враховує повний час зміни. За вузької панелі лишаються
Name та Size. Ext враховує параметри вирівнювання розширень.
Межі стовпців збігаються в заголовку та списку.
- Brief показує імена. Medium додає Size. Wide показує також Ext і
Modified. Full додає Allocated, Links і Owner. Для локальних файлів
Allocated показує зайняте місце, Links — кількість жорстких посилань, а
Owner — власника за даними Windows. Для відсутніх метаданих показується —.
Modified показує місцеву дату. Сортування враховує повний час зміни.
- **Left/Right → Columns** налаштовує видимість стовпців і автоматичну
ширину для поточного режиму. Кожна панель зберігає свій режим і
налаштування Medium, Wide та Full. Автоматична ширина враховує вміст.
У вузькій панелі Name має пріоритет. Межі стовпців збігаються в заголовку
та списку. Стрілки, PgUp, PgDn, Home та End керують рядками в усіх режимах.
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
@@ -621,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 по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені.
+4
View File
@@ -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
+103
View File
@@ -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
View File
@@ -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()}
+110
View File
@@ -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.
+22 -2
View File
@@ -132,8 +132,10 @@ BEGIN
EDITTEXT 270, 8, 21, 113, 14, ES_AUTOHSCROLL
CONTROL "", 271, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 8, 40, 113, 240
LTEXT "", 272, 131, 8, 253, 12
AUTOCHECKBOX "Left panel: &Wide", 273, 132, 27, 115, 12
AUTOCHECKBOX "Right panel: W&ide", 274, 251, 27, 125, 12
LTEXT "&Left panel", 506, 132, 27, 108, 11
COMBOBOX 273, 132, 40, 108, 74, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "&Right panel", 507, 251, 27, 117, 11
COMBOBOX 274, 251, 40, 117, 74, CBS_DROPDOWNLIST | WS_TABSTOP
GROUPBOX "Wide panel columns", 275, 129, 27, 259, 59
LTEXT "Size column &width (6–16 characters)", 276, 138, 44, 175, 10
EDITTEXT 201, 335, 41, 43, 14, ES_NUMBER | ES_AUTOHSCROLL
@@ -455,3 +457,21 @@ BEGIN
CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16
END
119 DIALOGEX 0, 0, 260, 197
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Panel columns"
FONT 10, "Consolas"
BEGIN
AUTOCHECKBOX "E&xtension", 510, 18, 18, 224, 13
AUTOCHECKBOX "Si&ze", 511, 18, 36, 224, 13
AUTOCHECKBOX "&Modified", 512, 18, 54, 224, 13
AUTOCHECKBOX "A&llocated bytes", 513, 18, 72, 224, 13
AUTOCHECKBOX "Link cou&nt", 514, 18, 90, 224, 13
AUTOCHECKBOX "&Owner", 515, 18, 108, 224, 13
AUTOCHECKBOX "Automatic column &widths", 516, 18, 135, 224, 13
LTEXT "", 517, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&Apply", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 168, 62, 17
CONTROL "&Reset", 518, "Button", BS_OWNERDRAW | WS_TABSTOP, 88, 168, 74, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 168, 64, 17
END
+217
View File
@@ -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.");
}
}
+33
View File
@@ -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);
}
+86
View File
@@ -0,0 +1,86 @@
constexpr DWORD columnFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
std::optional<FILE_STANDARD_INFO> fileStorageInformation(HANDLE file)
{
FILE_STANDARD_INFO result{};
if(GetFileInformationByHandleEx(file,FileStandardInfo,&result,sizeof(result))) return result;
return {};
}
std::optional<uint64_t> allocatedFileBytes(HANDLE file,DWORD attributes,
const std::optional<FILE_STANDARD_INFO> &metadata)
{
if(attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) return {};
if(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))
{
FILE_COMPRESSION_INFO compression{};
if(GetFileInformationByHandleEx(file,FileCompressionInfo,&compression,sizeof(compression)) &&
compression.CompressedFileSize.QuadPart>=0)
return static_cast<uint64_t>(compression.CompressedFileSize.QuadPart);
return {};
}
if(metadata && !metadata->Directory && metadata->AllocationSize.QuadPart>=0)
return static_cast<uint64_t>(metadata->AllocationSize.QuadPart);
return {};
}
std::optional<uint64_t> allocatedFileBytes(const fs::path &path,DWORD attributes)
{
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,
OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return {};
const auto metadata=(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))?
std::optional<FILE_STANDARD_INFO>{}:fileStorageInformation(file.value);
return allocatedFileBytes(file.value,attributes,metadata);
}
std::wstring localOwnerName(const fs::path &path,std::map<std::wstring,std::wstring> &owners)
{
const Handle file{CreateFileW(path.c_str(),READ_CONTROL,columnFileShare,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return {};
PSECURITY_DESCRIPTOR descriptor=nullptr;
PSID owner=nullptr;
const auto result=GetSecurityInfo(file.value,SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,&owner,
nullptr,nullptr,nullptr,&descriptor);
const std::unique_ptr<void,decltype(&LocalFree)> security(descriptor,LocalFree);
if(result!=ERROR_SUCCESS || !owner) return {};
wchar_t *sidText=nullptr;
if(!ConvertSidToStringSidW(owner,&sidText)) return {};
const std::unique_ptr<void,decltype(&LocalFree)> sid(sidText,LocalFree);
if(const auto existing=owners.find(sidText);existing!=owners.end()) return existing->second;
wchar_t name[256]{},domain[256]{};
DWORD nameLength=static_cast<DWORD>(std::size(name)),domainLength=static_cast<DWORD>(std::size(domain));
SID_NAME_USE use{};
std::wstring label=sidText;
if(LookupAccountSidW(nullptr,owner,name,&nameLength,domain,&domainLength,&use))
label=*domain?std::wstring(domain)+L"\\"+name:name;
owners.emplace(sidText,label);
return label;
}
void readLocalColumnMetadata(Panel::ScanResult &result,DWORD mask,std::stop_token stop)
{
std::map<std::wstring,std::wstring> owners;
for(const auto &entry:result.ordered)
{
if(stop.stop_requested()) return;
const auto attributes=result.metadata.at(entry.path).attributes;
ColumnMetadata data;
if(mask&(columnMask(allocationColumn)|columnMask(linkColumn)))
{
const Handle file{CreateFileW(entry.path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,
OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value!=INVALID_HANDLE_VALUE)
{
const auto information=fileStorageInformation(file.value);
if((mask&columnMask(linkColumn)) && information) data.links=information->NumberOfLinks;
if(mask&columnMask(allocationColumn)) data.allocated=allocatedFileBytes(file.value,attributes,information);
}
}
if(mask&columnMask(ownerColumn)) data.owner=localOwnerName(entry.path,owners);
if(!data.owner.empty() || data.allocated || data.links)
result.columnMetadata.emplace(entry.path,std::move(data));
}
}
+1 -1
View File
@@ -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();
+1 -1
View File
@@ -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
View File
@@ -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;
+2 -2
View File
@@ -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;
+519 -137
View File
File diff suppressed because it is too large. Load diff
+29 -10
View File
@@ -11,7 +11,7 @@ constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Pop
L"Menu selection",L"Command bar",L"File cursor"};
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
constexpr const wchar_t *panelSectionNames[]{L"Panel layout",L"Wide panel columns",L"Status line columns"};
constexpr int panelLayoutControls[]{273,274};
constexpr int panelLayoutControls[]{506,273,507,274};
constexpr int wideColumnControls[]{275,276,201,202,204};
constexpr int statusColumnControls[]{277,203,205,206,207,208};
constexpr int colorOptionControls[]{279,280};
@@ -66,7 +66,7 @@ struct PanelProperty
DWORD defaultValue;
};
constexpr PanelProperty panelProperties[]{
{PanelLayout,273,L"Left panel: Wide",defaultWide},{PanelLayout,274,L"Right panel: Wide",defaultWide},
{PanelLayout,273,L"Left panel mode",defaultWide?1u:0u},{PanelLayout,274,L"Right panel mode",defaultWide?1u:0u},
{WideColumns,201,L"Size column width",defaultSizeWidth},
{WideColumns,202,L"Align file extensions",defaultAlignExtensions},
{WideColumns,204,L"Align folder extensions",defaultAlignFolders},
@@ -76,9 +76,24 @@ constexpr PanelProperty panelProperties[]{
void resetPanelProperty(HWND dialog,const PanelProperty &property)
{
if(property.control==201) SetDlgItemInt(dialog,property.control,property.defaultValue,FALSE);
else if(property.control==273 || property.control==274)
SendDlgItemMessageW(dialog,property.control,CB_SETCURSEL,property.defaultValue,0);
else CheckDlgButton(dialog,property.control,property.defaultValue);
}
PanelMode panelModeOption(HWND dialog,int index)
{
const auto selection=SendDlgItemMessageW(dialog,273+index,CB_GETCURSEL,0,0);
return selection>=0 && static_cast<size_t>(selection)<std::size(panelModeNames)?
static_cast<PanelMode>(selection):PanelMode::brief;
}
void showPanelModeOptions(HWND dialog)
{
for(int index=0;index<2;++index)
SendDlgItemMessageW(dialog,273+index,CB_SETCURSEL,static_cast<WPARAM>(panels[index].mode),0);
}
struct OptionsBaseline
{
LOGFONTW font=displayFont;
@@ -92,7 +107,7 @@ struct OptionsBaseline
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
std::array<bool,2> wide{panels[0].wide,panels[1].wide};
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
ks::files::TextSettings text=ks::files::loadTextPreferences();
ComparisonAppearance comparison=readComparisonAppearance();
WORD compareShortcut=comparisonShortcut;
@@ -164,7 +179,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
for(int i=0;i<4;++i) if(checked(205+i)) fields|=1u<<i;
const auto &base=draft.baseline;
const bool dirty=!valid || draft.markdownError || width!=base.width ||
checked(273)!=base.wide[0] || checked(274)!=base.wide[1] ||
panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] ||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
@@ -636,6 +651,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
SendDlgItemMessageW(dialog,201,EM_SETLIMITTEXT,2,0);
for(const auto id:{273,274})
for(const auto mode:panelModeNames)
SendDlgItemMessageW(dialog,id,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(mode));
SendDlgItemMessageW(dialog,markdownWidth,EM_SETLIMITTEXT,6,0);
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
@@ -661,8 +679,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,273,panels[0].wide);
CheckDlgButton(dialog,274,panels[1].wide);
showPanelModeOptions(dialog);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
@@ -1051,8 +1068,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
savePreference(L"FontPoints",fontPoints);
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",REG_BINARY,&displayFont,sizeof(displayFont));
}
saveChanged(L"LeftWide",checked(273),base.wide[0]);
saveChanged(L"RightWide",checked(274),base.wide[1]);
for(int index=0;index<2;++index)
{
const auto mode=panelModeOption(dialog,index);
if(mode!=base.modes[index]) savePanelMode(index,mode);
}
loadFilesPreferences(owner);
notifyFilesPreferences(owner);
const auto dialogOwner=GetWindow(dialog,GW_OWNER);
@@ -1072,8 +1092,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,273,panels[0].wide);
CheckDlgButton(dialog,274,panels[1].wide);
showPanelModeOptions(dialog);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
+78
View File
@@ -0,0 +1,78 @@
constexpr int panelColumnFirst=510,panelColumnAuto=516,panelColumnFooter=517,panelColumnReset=518;
void setColumnControls(HWND dialog,DWORD columns,bool automatic)
{
for(size_t i=1;i<panelColumnCount;++i)
CheckDlgButton(dialog,panelColumnFirst+static_cast<int>(i)-1,columns&(1u<<i)?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(dialog,panelColumnAuto,automatic?BST_CHECKED:BST_UNCHECKED);
}
struct PanelColumnPrompt
{
ColumnSettings draft;
PanelMode mode;
};
INT_PTR CALLBACK panelColumnsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
const auto &prompt=*reinterpret_cast<const PanelColumnPrompt *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,panelColumnFirst);
for(int id=panelColumnFirst;id<=panelColumnAuto;++id)
installFarCheckbox(GetDlgItem(dialog,id),FarCheckboxSurface::gray);
layoutDialogButtons(dialog,panelColumnFooter,{IDOK,panelColumnReset,IDCANCEL});
setColumnControls(dialog,prompt.draft.visibility,prompt.draft.automatic);
return TRUE;
}
if(message==WM_COMMAND)
{
const auto command=LOWORD(wp);
auto *prompt=reinterpret_cast<PanelColumnPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!prompt) return FALSE;
if(command==panelColumnReset)
{
setColumnControls(dialog,defaultVisibleColumns(prompt->mode),true);
return TRUE;
}
if(command==IDOK)
{
auto &draft=prompt->draft;
draft.visibility=0;
for(size_t i=1;i<panelColumnCount;++i)
if(IsDlgButtonChecked(dialog,panelColumnFirst+static_cast<int>(i)-1)==BST_CHECKED)
draft.visibility|=1u<<i;
draft.automatic=IsDlgButtonChecked(dialog,panelColumnAuto)==BST_CHECKED;
draft.customized=draft.visibility!=defaultVisibleColumns(prompt->mode);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Panel columns ",false,{panelColumnFooter});
}
void editPanelColumns(HWND owner,Panel &panel)
{
if(!hasPanelColumns(panel) || !panelViewAvailable(panel)) return;
auto &settings=panel.columns[static_cast<size_t>(panel.mode)];
auto draft=settings;
if(!draft.customized) draft.visibility=defaultVisibleColumns(panel.mode);
PanelColumnPrompt prompt{draft,panel.mode};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(119),owner,
panelColumnsDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
if(prompt.draft.visibility==draft.visibility && prompt.draft.automatic==draft.automatic) return;
settings=prompt.draft;
savePanelColumns(static_cast<int>(&panel-panels),panel.mode);
notifyFilesPreferences(owner);
if((draft.visibility^settings.visibility)&extendedColumnMask) refreshPanelColumnData(panel);
InvalidateRect(panel.heading,nullptr,FALSE);
InvalidateRect(panel.list,nullptr,TRUE);
InvalidateRect(owner,nullptr,FALSE);
}
+14
View File
@@ -10,6 +10,7 @@ public:
panel.dimmed.clear();
panel.marked.clear();
panel.fileExtensionLength=panel.folderExtensionLength=0;
panel.longestColumn.fill(0);
panel.rows.reserve(count);
panel.sizes.reserve(count);
panel.dimmed.reserve(count);
@@ -35,6 +36,19 @@ public:
const auto entry=up || profiles || found==panel.metadata.end()?FolderEntryMetadata{}:found->second;
panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0);
panel.sizes.push_back(profiles?L"":folder?(up?L"Up":L"Folder"):std::to_wstring(entry.size));
if(!up && !profiles)
{
auto &longest=panel.longestColumn;
longest[sizeColumn]=std::max(longest[sizeColumn],panel.sizes.back().size());
if(const auto extra=panel.columnMetadata.find(path);extra!=panel.columnMetadata.end())
{
longest[ownerColumn]=std::max(longest[ownerColumn],extra->second.owner.size());
if(extra->second.links)
longest[linkColumn]=std::max(longest[linkColumn],std::to_wstring(*extra->second.links).size());
if(extra->second.allocated)
longest[allocationColumn]=std::max(longest[allocationColumn],std::to_wstring(*extra->second.allocated).size());
}
}
return true;
}
+6 -1
View File
@@ -26,7 +26,7 @@ void startPendingTreeScans(Panel &panel)
try
{
branch.scan=scanDirectoryInBackground(GetParent(panel.list),std::move(request),panel.view,
std::make_shared<std::atomic_size_t>(0),branch.stop.get_token());
effectivePanelColumns(panel)&extendedColumnMask,std::make_shared<std::atomic_size_t>(0),branch.stop.get_token());
++running;
}
catch(const std::exception &) {branch.failed=true;}
@@ -50,6 +50,7 @@ void replaceTreeRoot(Panel &panel,Panel::ScanResult &scan,bool sameDirectory,con
root.expanded=root.loaded=true;
root.ordered=std::move(scan.ordered);
root.metadata=std::move(scan.metadata);
root.columnMetadata=std::move(scan.columnMetadata);
panel.tree.marks.insert(marks.begin(),marks.end());
if(scan.error!=ERROR_CANCELLED)
std::erase_if(panel.tree.marks,[&](const auto &path) {
@@ -88,6 +89,7 @@ void appendTreeRows(Panel &panel,PanelRowsUpdate &rows)
{
panel.tree.depths.clear();
panel.metadata.clear();
panel.columnMetadata.clear();
struct BranchRows {const Panel::TreeBranch *branch; size_t next;};
std::vector<BranchRows> stack{{&panel.tree.branches.at(panel.tree.root),0}};
while(!stack.empty())
@@ -104,6 +106,8 @@ void appendTreeRows(Panel &panel,PanelRowsUpdate &rows)
const auto metadata=current.branch->metadata.find(path);
if(metadata==current.branch->metadata.end() || !visibleToPanelView(panel.view,path,metadata->second)) continue;
panel.metadata.emplace(path,metadata->second);
if(const auto extra=current.branch->columnMetadata.find(path);extra!=current.branch->columnMetadata.end())
panel.columnMetadata.emplace(path,extra->second);
const auto label=treeRowPrefix(panel,path,entry.folder)+path.filename().native();
rows.add(path,label,entry.folder,panel.tree.marks.contains(path));
const auto child=panel.tree.branches.find(path);
@@ -164,6 +168,7 @@ void collectTreeBranches()
branch.loaded=true;
branch.ordered=std::move(scan->ordered);
branch.metadata=std::move(scan->metadata);
branch.columnMetadata=std::move(scan->columnMetadata);
if(!branch.failed) std::erase_if(panel.tree.marks,[&](const auto &marked) {
return marked.parent_path()==path && !branch.metadata.contains(marked);
});
+10 -2
View File
@@ -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))
{
+1 -21
View File
@@ -33,26 +33,6 @@ std::future<SpaceVolume> readSpaceVolume(const fs::path &folder)
return result;
}
std::optional<uint64_t> allocatedFileBytes(const fs::path &path,DWORD attributes)
{
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return {};
if(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))
{
FILE_COMPRESSION_INFO compression{};
if(GetFileInformationByHandleEx(file.value,FileCompressionInfo,&compression,sizeof(compression)) &&
compression.CompressedFileSize.QuadPart>=0)
return static_cast<uint64_t>(compression.CompressedFileSize.QuadPart);
return {};
}
FILE_STANDARD_INFO metadata{};
if(GetFileInformationByHandleEx(file.value,FileStandardInfo,&metadata,sizeof(metadata)) &&
!metadata.Directory && metadata.AllocationSize.QuadPart>=0)
return static_cast<uint64_t>(metadata.AllocationSize.QuadPart);
return {};
}
struct SpaceAllocation
{
FolderSize known;
@@ -628,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;
+25
View File
@@ -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)
{
+150
View File
@@ -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;
}
}