From 1f4baed2ed972e71867cd33699038b04d5543832 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 15:56:01 +0200 Subject: [PATCH] Create and safely update ZIP and 7z archives in Files Refs #100 --- FILES-UI.md | 4 +- resources/files.rc | 12 ++ src/files_archive.cpp | 332 +++++++++++++++++++++++++++++++++-- src/files_archive.h | 4 + src/files_archive_dialog.inl | 154 ++++++++++++++++ src/files_main.cpp | 47 +++-- src/files_text_document.cpp | 11 +- src/files_win32_replace.h | 24 +++ tests/files_archive.cpp | 82 +++++++++ 9 files changed, 624 insertions(+), 46 deletions(-) create mode 100644 src/files_archive_dialog.inl create mode 100644 src/files_win32_replace.h diff --git a/FILES-UI.md b/FILES-UI.md index 79d1e5c..061527e 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -629,9 +629,11 @@ Warning і початковий фокус на No. ## Архіви ZIP і 7z -- Enter на локальному архіві відкриває його в поточній панелі. Заголовок панелі починається з Read-only і містить ім’я архіву та шлях усередині нього. Enter відкриває папки всередині архіву, а рядок `..`, Alt+Up і Escape піднімають на один рівень. Вихід із кореня повертає курсор на архів. +- Enter на локальному архіві відкриває його в поточній панелі. Заголовок панелі починається з Archive і містить ім’я архіву та шлях усередині нього. Enter відкриває папки всередині архіву, а рядок `..`, Alt+Up і Escape піднімають на один рівень. Вихід із кореня повертає курсор на архів. - F3 відкриває текстовий файл у спільному переглядачі. F5 копіює позначені записи або поточний запис у локальну папку через спільні діалоги Copy, конфлікту та прогресу. F4, F6, F7 і F8 не змінюють вміст архіву. - Небезпечні шляхи й посилання блокують читання архіву. Для зашифрованих записів та архівів із зашифрованими заголовками Files показує підказку про пароль. +- **Files → Pack files** або **Alt+F5** створює в поточній локальній папці архів із позначених елементів або з поточного елемента. Розширення `.zip` чи `.7z` визначає формат. +- **F5** з локальної панелі в панель архіву та **Ctrl+V** зі списком локальних файлів додають елементи до відкритої папки архіву. Діалог підтвердження попереджає про заміну файлів з однаковими іменами. Скасування або помилка зберігають попередній архів. Режим запису підтримує звичайні ZIP і 7z. ## Діалог Copy diff --git a/resources/files.rc b/resources/files.rc index 56e7296..2fff9c9 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -475,3 +475,15 @@ BEGIN CONTROL "&Reset", 518, "Button", BS_OWNERDRAW | WS_TABSTOP, 88, 168, 74, 17 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 168, 64, 17 END + +120 DIALOGEX 0, 0, 290, 82 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "Pack files" +FONT 10, "Consolas" +BEGIN + LTEXT "Archive name (.zip or .7z)", 530, 16, 15, 258, 12 + FAR_EDIT(531, 0, 16, 32, 258, 15) + LTEXT "", 532, 10, 54, 1, 1, NOT WS_VISIBLE + CONTROL "&Create", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17 +END diff --git a/src/files_archive.cpp b/src/files_archive.cpp index a6c562e..2b20783 100644 --- a/src/files_archive.cpp +++ b/src/files_archive.cpp @@ -1,5 +1,7 @@ #include "files_archive.h" #include "files_win32_directory.h" +#include "files_win32_replace.h" +#include #include #include #include @@ -30,9 +32,23 @@ bool isArchivePath(const fs::path &path) namespace { using ArchiveReader=std::unique_ptr; +using ArchiveWriter=std::unique_ptr; +constexpr std::int64_t archiveEpochOffset=11644473600, archiveTicksPerSecond=10000000; constexpr char unsafePath[]="The archive contains an unsafe or conflicting path."; constexpr char encryptedArchive[]="This archive requires a password. Password-protected entries cannot be opened in Files."; +struct ArchiveFileHandle +{ + HANDLE value=INVALID_HANDLE_VALUE; + explicit ArchiveFileHandle(HANDLE handle) : value(handle) + { + if(value==INVALID_HANDLE_VALUE) throw std::system_error(GetLastError(),std::system_category()); + } + ArchiveFileHandle(const ArchiveFileHandle &)=delete; + ArchiveFileHandle &operator=(const ArchiveFileHandle &)=delete; + ~ArchiveFileHandle() {CloseHandle(value);} +}; + [[noreturn]] void archiveError(archive *reader) { const auto *error=archive_error_string(reader); @@ -84,11 +100,10 @@ std::pair decodeEntry(archive_entry *entry) 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((seconds+epochOffset)*ticksPerSecond+archive_entry_mtime_nsec(entry)/100):0; + const auto modified=archive_entry_mtime_is_set(entry) && seconds>=-archiveEpochOffset && + seconds<(INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)? + static_cast((seconds+archiveEpochOffset)*archiveTicksPerSecond+archive_entry_mtime_nsec(entry)/100):0; return {relative,{static_cast(size),modified,folder,archive_entry_is_encrypted(entry)!=0}}; } @@ -124,7 +139,7 @@ ArchiveEntries walkArchive(const fs::path &file,const Visit &visit) 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()); + if(!visit(reader.get(),raw,path,entry)) throw std::system_error(ERROR_CANCELLED,std::system_category()); } } @@ -133,14 +148,8 @@ void writeMember(archive *reader,const ArchiveEntry &entry,const fs::path &outpu { 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}; + const ArchiveFileHandle owned(CreateFileW(output.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW, + FILE_ATTRIBUTE_NORMAL,nullptr)); std::array buffer{}; uint64_t done=0; for(;;) @@ -152,7 +161,7 @@ void writeMember(archive *reader,const ArchiveEntry &entry,const fs::path &outpu if(static_cast(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(size),&written,nullptr) || + if(!WriteFile(owned.value,buffer.data(),static_cast(size),&written,nullptr) || written!=static_cast(size)) throw std::system_error(GetLastError(),std::system_category()); done+=written; @@ -161,7 +170,7 @@ void writeMember(archive *reader,const ArchiveEntry &entry,const fs::path &outpu if(entry.modified) { const FILETIME time{static_cast(entry.modified),static_cast(entry.modified>>32)}; - if(!SetFileTime(handle,nullptr,nullptr,&time)) + if(!SetFileTime(owned.value,nullptr,nullptr,&time)) throw std::system_error(GetLastError(),std::system_category()); } } @@ -169,14 +178,14 @@ void writeMember(archive *reader,const ArchiveEntry &entry,const fs::path &outpu ArchiveEntries readArchive(const fs::path &file,std::stop_token stop) { - return walkArchive(file,[&](auto *,const auto &,const auto &){return !stop.stop_requested();}); + return walkArchive(file,[&](auto *,auto *,const auto &,const auto &){return !stop.stop_requested();}); } ArchiveEntry readArchiveMember(const fs::path &file,const fs::path &member,const fs::path &output, uint64_t limit,const ArchiveProgress &progress) { std::optional found; - walkArchive(file,[&](archive *reader,const fs::path &path,const ArchiveEntry &entry) + walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry) { if(progress && !progress(found?found->size:0,found?found->size:0)) return false; if(!entry.directory && path==member) @@ -202,7 +211,7 @@ void extractArchiveSelection(const fs::path &file,const fs::path &directory,cons if(selected.contains(item)) return true; return false; }; - const auto entries=walkArchive(file,[&](archive *reader,const fs::path &path,const ArchiveEntry &entry) + const auto entries=walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry) { if(progress && !progress(0,0)) return false; if(!wanted(path)) return true; @@ -214,4 +223,291 @@ void extractArchiveSelection(const fs::path &file,const fs::path &directory,cons for(const auto &path:selected) if(!entries.contains(path)) throw std::runtime_error("A selected archive entry is no longer available."); } + +namespace +{ +BY_HANDLE_FILE_INFORMATION archiveFileInfo(HANDLE file) +{ + BY_HANDLE_FILE_INFORMATION info{}; + if(!GetFileInformationByHandle(file,&info)) throw std::system_error(GetLastError(),std::system_category()); + return info; +} + +uint64_t archiveFileSize(const BY_HANDLE_FILE_INFORMATION &info) +{ + return (uint64_t(info.nFileSizeHigh)<<32)|info.nFileSizeLow; +} + +bool sameArchiveFile(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right) +{ + return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh && + left.nFileIndexLow==right.nFileIndexLow && archiveFileSize(left)==archiveFileSize(right) && + CompareFileTime(&left.ftLastWriteTime,&right.ftLastWriteTime)==0; +} + +struct ArchiveTemporaryFile +{ + fs::path directory, file; + + explicit ArchiveTemporaryFile(const fs::path &parent) + { + GUID id{}; + wchar_t name[40]{}; + if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40)) + throw std::runtime_error("Could not prepare a temporary archive."); + directory=parent/(L".ks-files-pack-"+std::wstring(name)); + file=directory/L"archive"; + if(!fs::create_directory(directory)) throw std::runtime_error("Could not prepare a temporary archive."); + } + + ~ArchiveTemporaryFile() + { + std::error_code error; + fs::remove(file,error); + fs::remove(directory,error); + } +}; + +bool isZip(const fs::path &file) +{ + return CompareStringOrdinal(file.extension().c_str(),-1,L".zip",-1,TRUE)==CSTR_EQUAL; +} + +HANDLE lockArchiveFolder(const fs::path &directory) +{ + const auto lock=directory/L".ks-files-archive-write.lock"; + const HANDLE handle=CreateFileW(lock.c_str(),GENERIC_WRITE|DELETE,0,nullptr,CREATE_NEW, + FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr); + if(handle!=INVALID_HANDLE_VALUE) return handle; + const DWORD error=GetLastError(); + if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS || error==ERROR_SHARING_VIOLATION) + throw std::runtime_error("Another archive operation is active in this folder."); + throw std::system_error(error,std::system_category()); +} + +void checkArchiveWrite(int status) +{ + if(status!=ARCHIVE_OK) throw std::runtime_error("Could not create the ZIP or 7z data."); +} + +ArchiveWriter openArchiveWriter(const fs::path &file,bool zip) +{ + ArchiveWriter writer(archive_write_new(),archive_write_free); + if(!writer) throw std::runtime_error("Could not create the archive writer."); + checkArchiveWrite(zip?archive_write_set_format_zip(writer.get()):archive_write_set_format_7zip(writer.get())); + checkArchiveWrite(archive_write_set_options(writer.get(),zip?"hdrcharset=UTF-8":"compression=lzma2")); + checkArchiveWrite(archive_write_open_filename_w(writer.get(),file.c_str())); + return writer; +} + +struct ArchiveInput +{ + fs::path source; + BY_HANDLE_FILE_INFORMATION info; +}; + +using ArchiveInputs=std::map; + +void addArchiveInput(ArchiveInputs &inputs,const fs::path &source,const fs::path &member,const fs::path &target, + const std::function &checkCanceled) +{ + checkCanceled(); + if(member.empty() || member.filename().native().size()>255 || !validWindowsFileName(member.filename().native())) + throw std::runtime_error("A selected file has a name that cannot be stored safely in the archive."); + std::error_code error; + if(fs::equivalent(source,target,error)) throw std::runtime_error("The archive cannot contain itself."); + if(fs::equivalent(source,target.parent_path(),error)) + throw std::runtime_error("Choose an archive location outside the selected folders."); + const ArchiveFileHandle file(CreateFileW(source.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE, + nullptr,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)); + const auto info=archiveFileInfo(file.value); + if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT) + throw std::runtime_error("The selection contains a Windows link or reparse point."); + if(!inputs.emplace(member,ArchiveInput{source,info}).second) + throw std::runtime_error("The selection contains conflicting names."); + if(!(info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) return; + for(const auto &child:fs::directory_iterator(source)) + addArchiveInput(inputs,child.path(),member/child.path().filename(),target,checkCanceled); +} + +template +void transferArchiveData(archive *writer,uint64_t size,const Read &read,const std::function &advance) +{ + std::array buffer{}; + uint64_t bytes=0; + while(bytes(std::min(size-bytes,buffer.size()))); + if(!count) throw std::runtime_error("An archive input ended before its declared size."); + if(archive_write_data(writer,buffer.data(),count)!=static_cast(count)) + throw std::runtime_error("Could not write archive contents."); + bytes+=count; + advance(count); + } + if(read(buffer.data(),1)!=0) throw std::runtime_error("An archive input changed size while it was being written."); + checkArchiveWrite(archive_write_finish_entry(writer)); +} + +void archiveLocalInput(archive *writer,const fs::path &path,const ArchiveInput &input, + const std::function &advance) +{ + const bool folder=(input.info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0; + std::unique_ptr entry(archive_entry_new(),archive_entry_free); + if(!entry) throw std::runtime_error("Could not create an archive entry."); + const auto name=path.generic_wstring(); + archive_entry_copy_pathname_w(entry.get(),name.c_str()); + archive_entry_set_filetype(entry.get(),folder?AE_IFDIR:AE_IFREG); + archive_entry_set_perm(entry.get(),folder?0755:0644); + const uint64_t size=folder?0:archiveFileSize(input.info); + archive_entry_set_size(entry.get(),static_cast(size)); + const auto stamp=(uint64_t(input.info.ftLastWriteTime.dwHighDateTime)<<32)|input.info.ftLastWriteTime.dwLowDateTime; + archive_entry_set_mtime(entry.get(),static_cast(stamp/archiveTicksPerSecond)-archiveEpochOffset, + static_cast((stamp%archiveTicksPerSecond)*100)); + if(folder) + { + checkArchiveWrite(archive_write_header(writer,entry.get())); + checkArchiveWrite(archive_write_finish_entry(writer)); + return; + } + const ArchiveFileHandle file(CreateFileW(input.source.c_str(),GENERIC_READ,FILE_SHARE_READ,nullptr,OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_SEQUENTIAL_SCAN,nullptr)); + const auto current=archiveFileInfo(file.value); + if((current.dwFileAttributes&(FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY)) || + !sameArchiveFile(input.info,current)) + throw std::runtime_error("A selected file changed before it could be added."); + checkArchiveWrite(archive_write_header(writer,entry.get())); + transferArchiveData(writer,size,[&](char *buffer,DWORD goal) + { + DWORD used=0; + if(!ReadFile(file.value,buffer,goal,&used,nullptr)) + throw std::system_error(GetLastError(),std::system_category()); + return used; + },advance); +} +} + +void writeArchive(const fs::path &file,ArchiveWriteMode mode,const fs::path &directory, + const std::vector &sources,const ArchiveProgress &progress) +{ + if(!isArchivePath(file)) throw std::runtime_error("Files can write ZIP and 7z archives."); + if(!file.is_absolute() || !validWindowsFileName(file.filename().native()) || sources.empty()) + throw std::runtime_error("Select local files and enter a valid archive name."); + for(const auto &part:directory) + if(!validWindowsFileName(part.native())) throw std::runtime_error(unsafePath); + const bool zip=isZip(file); + const bool updating=mode==ArchiveWriteMode::update; + if(!updating && !directory.empty()) throw std::runtime_error("Create a new archive at its root."); + if(!updating && GetFileAttributesW(file.c_str())!=INVALID_FILE_ATTRIBUTES) + throw std::runtime_error("A file or folder with this archive name already exists."); + + uint64_t done=0, total=0; + const auto checkCanceled=[&] + { + if(progress && !progress(done,total)) throw std::system_error(ERROR_CANCELLED,std::system_category()); + }; + const auto advance=[&](uint64_t bytes) {done+=bytes;checkCanceled();}; + const auto plan=[&](uint64_t bytes) + { + if(UINT64_MAX-total original; + BY_HANDLE_FILE_INFORMATION originalInfo{}; + ArchiveEntries existing; + if(updating) + { + original.emplace(CreateFileW(file.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT,nullptr)); + originalInfo=archiveFileInfo(original->value); + if(originalInfo.dwFileAttributes&(FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_READONLY)) + throw std::runtime_error("This archive is read-only or is a Windows link."); + existing=walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry) + { + checkCanceled(); + const int expected=zip?ARCHIVE_FORMAT_ZIP:ARCHIVE_FORMAT_7ZIP; + if((archive_format(reader)&ARCHIVE_FORMAT_BASE_MASK)!=expected) + throw std::runtime_error("The archive contents do not match its ZIP or 7z extension."); + if(entry.encrypted) throw std::runtime_error("Password-protected archives cannot be updated in Files."); + if(!entry.directory && !inputs.contains(path)) plan(entry.size); + return true; + }); + if(!directory.empty()) + { + const auto parent=existing.find(directory); + if(parent==existing.end() || !parent->second.directory || parent->first.native()!=directory.native()) + throw std::runtime_error("This folder is no longer present in the archive."); + } + } + auto combined=existing; + for(const auto &[path,input]:inputs) + { + checkCanceled(); + const bool folder=(input.info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0; + if(const auto present=combined.find(path);present!=combined.end()) + { + if(present->first.native()!=path.native() || present->second.directory!=folder) + throw std::runtime_error(unsafePath); + } + else registerEntry(combined,path,ArchiveEntry{.directory=folder}); + if(!folder) plan(archiveFileSize(input.info)); + } + checkCanceled(); + const ArchiveTemporaryFile temp(file.parent_path()); + auto writer=openArchiveWriter(temp.file,zip); + if(updating) + walkArchive(file,[&](archive *reader,archive_entry *raw,const fs::path &path,const ArchiveEntry &entry) + { + checkCanceled(); + if(path.empty() || inputs.contains(path)) return true; + const auto name=path.generic_wstring(); + archive_entry_copy_pathname_w(raw,name.c_str()); + checkArchiveWrite(archive_write_header(writer.get(),raw)); + if(entry.directory) checkArchiveWrite(archive_write_finish_entry(writer.get())); + else transferArchiveData(writer.get(),entry.size,[&](char *buffer,DWORD goal) + { + const auto used=archive_read_data(reader,buffer,goal); + if(used<0) archiveError(reader); + return static_cast(used); + },advance); + return true; + }); + for(const auto &[path,input]:inputs) + { + checkCanceled(); + archiveLocalInput(writer.get(),path,input,advance); + } + checkArchiveWrite(archive_write_close(writer.get())); + writer.reset(); + { + const ArchiveFileHandle completed(CreateFileW(temp.file.c_str(),GENERIC_WRITE,FILE_SHARE_READ,nullptr, + OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr)); + if(!FlushFileBuffers(completed.value)) throw std::system_error(GetLastError(),std::system_category()); + } + if(updating) + { + const ArchiveFileHandle current(CreateFileW(file.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_DELETE, + nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)); + if(!sameArchiveFile(originalInfo,archiveFileInfo(current.value))) + throw std::runtime_error("The archive changed while it was being updated."); + } + checkCanceled(); + if(updating) + { + const auto backup=temp.directory/L"original"; + if(const auto error=replaceFileWithBackup(file,temp.file,backup)) + throw std::system_error(error,std::system_category()); + original.reset(); + DeleteFileW(backup.c_str()); + } + else if(!MoveFileExW(temp.file.c_str(),file.c_str(),MOVEFILE_WRITE_THROUGH)) + throw std::system_error(GetLastError(),std::system_category()); +} } diff --git a/src/files_archive.h b/src/files_archive.h index 832f3aa..3b118ec 100644 --- a/src/files_archive.h +++ b/src/files_archive.h @@ -30,4 +30,8 @@ ArchiveEntry readArchiveMember(const std::filesystem::path &file,const std::file void extractArchiveSelection(const std::filesystem::path &file,const std::filesystem::path &directory, const std::vector &selection,const std::filesystem::path &staging, const ArchiveProgress &progress); + +enum class ArchiveWriteMode { create, update }; +void writeArchive(const std::filesystem::path &file,ArchiveWriteMode mode,const std::filesystem::path &directory, + const std::vector &sources,const ArchiveProgress &progress); } diff --git a/src/files_archive_dialog.inl b/src/files_archive_dialog.inl new file mode 100644 index 0000000..60c9003 --- /dev/null +++ b/src/files_archive_dialog.inl @@ -0,0 +1,154 @@ +INT_PTR CALLBACK archiveNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + constexpr int field=531, footer=532; + const auto input=GetDlgItem(dialog,field); + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(dialog,DWLP_USER,lp); + const auto &name=*reinterpret_cast(lp); + prepareTextDialog(dialog); + fitFarEditToLine(input); + SetWindowTextW(input,name.c_str()); + SendMessageW(input,EM_SETLIMITTEXT,255,0); + layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL}); + SendMessageW(dialog,DM_SETDEFID,IDOK,0); + SetFocus(input); + SendMessageW(input,EM_SETSEL,0,static_cast(name.rfind(L'.'))); + return FALSE; + } + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Pack files ",false,{footer})) + return painted; + if(message!=WM_COMMAND) return FALSE; + if(LOWORD(wp)==IDCANCEL) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(LOWORD(wp)!=IDOK) return FALSE; + auto name=dialogFieldText(input); + if(!ks::files::validWindowsFileName(name) || !ks::files::isArchivePath(fs::path(name))) + { + showFilesNotice(dialog,L"Enter a file name ending in .zip or .7z.",L"Archive format", + {.tone=FilesNoticeTone::warning}); + SetFocus(input); + return TRUE; + } + auto &result=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + result=std::move(name); + FilesModalDialog::finish(dialog,IDOK); + return TRUE; +} + +void performArchiveWrite(HWND owner,Panel &panel,const fs::path &archive,ks::files::ArchiveWriteMode mode, + const fs::path &directory,const std::vector &sources) +{ + if(copyInProgress || sources.empty()) return; + const bool updating=mode==ks::files::ArchiveWriteMode::update; + CopyProgress progress; + progress.writingArchive=true; + progress.from=sources.size()==1?sources.front():sources.front().parent_path(); + progress.to=archive; + FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner, + copyProgressDialog,reinterpret_cast(&progress)); + progress.window=dialog.window(); + if(!progress.window) + { + setStatus(L"Could not open archive progress."); + return; + } + copyInProgress=true; + activeCopy=&progress; + dialog.show(); + bool committed=false; + std::wstring failure; + try + { + progress.ui.run(progress.window,progress.canceled,[&] { + ks::files::writeArchive(archive,mode,directory,sources,[&](uint64_t done,uint64_t total) { + progress.totalBytes=total; + reportCopyProgress(progress,done,total); + return !progress.canceled; + }); + committed=true; + }); + } + catch(const std::system_error &error) + { + if(error.code().value()!=ERROR_CANCELLED) failure=fileError(error); + } + catch(const std::exception &error) {failure=ks::wide(error.what());} + dialog.close(); + activeCopy=nullptr; + copyInProgress=false; + if(progress.closeOwner) + { + PostMessageW(owner,WM_CLOSE,0,0); + return; + } + if(committed) + { + if(!updating) + { + open(panel,panel.directory); + selectPanelPath(panel,archive); + } + for(auto &view:panels) + { + std::error_code error; + if(view.archive && fs::equivalent(view.archive->file,archive,error)) refreshArchive(view); + } + setStatus(updating?L"Archive updated.":L"Archive created."); + } + else if(failure.empty()) setStatus(L"Archive operation canceled."); + else + { + showFileOperationError(owner,updating?L"Archive update failed":L"Archive creation failed",failure); + setStatus(failure); + } +} + +void createArchive(HWND owner,Panel &panel) +{ + if(panel.peer || panel.ftp || panel.archive || !panel.directory.is_absolute()) + { + setStatus(L"Open a local folder to create an archive."); + return; + } + if(panel.scanRequest) + { + setStatus(L"Wait for the panel to finish reading."); + return; + } + const auto selection=selectedPanelPaths(panel); + if(selection.empty()) + { + setStatus(L"Select files or folders to pack."); + return; + } + auto stem=(selection.size()==1?selection.front().stem():panel.directory.filename()).wstring(); + if(stem.empty()) stem=L"Archive"; + auto name=stem+L".zip"; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(120),owner, + archiveNameDialog,reinterpret_cast(&name))!=IDOK) return; + performArchiveWrite(owner,panel,panel.directory/name,ks::files::ArchiveWriteMode::create,{},selection); +} + +void addToArchive(HWND owner,Panel &panel,std::vector sources) +{ + if(sources.empty()) + { + setStatus(L"Select local files or folders to add."); + return; + } + if(panel.scanRequest || !panel.archive) + { + setStatus(L"Wait for the archive panel to finish reading."); + return; + } + const auto file=panel.archive->file; + auto directory=panel.directory.lexically_relative(file); + if(directory==L".") directory.clear(); + const auto question=L"Add the selected items to "+file.filename().native()+L"?\r\nMatching files will be replaced."; + if(showFilesNotice(owner,question.c_str(),L"Add to archive",{.confirm=true})!=IDYES) return; + performArchiveWrite(owner,panel,file,ks::files::ArchiveWriteMode::update,directory,sources); +} diff --git a/src/files_main.cpp b/src/files_main.cpp index 291e149..bcfcb4f 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -634,7 +634,7 @@ 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 L"Archive · "+display.native(); } return panel.findOrigin?L"Search results":panelLocation(panel); } @@ -3376,6 +3376,8 @@ void collectFolderSizes(Panel &panel) void openSelectedText(const Panel &panel, bool edit, bool external); void findLocalFiles(HWND owner,Panel &panel); void compareSelectedFiles(HWND owner); +void createArchive(HWND owner,Panel &panel); +void addToArchive(HWND owner,Panel &panel,std::vector sources); INT_PTR confirmTextSave(HWND owner,bool draft); bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format); INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption); @@ -3527,6 +3529,7 @@ void selectDrive() else if(menuIndex==2 && row==10) toggleQuickView(owner); else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]); else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]); + else if(menuIndex==1 && row==4) createArchive(owner,panels[active]); else { const int command=menuIndex==1?113+static_cast(row):110+static_cast(row); @@ -5086,6 +5089,7 @@ struct CopyProgress std::atomic_bool canceled{}; bool closeOwner{}; bool move{}, fileSourcesOnly{}; + bool writingArchive{}; int conflictChoice{}; ConflictMode conflictMode{}; bool askReadOnly=true; @@ -5620,7 +5624,7 @@ INT_PTR CALLBACK copyProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp } const auto operation=reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); if(const auto painted=paintCopyDialog(window,message,wp,lp, - operation && operation->move?L" Move ":L" Copy ",false,{228,229})) + operation && operation->writingArchive?L" Pack ":operation && operation->move?L" Move ":L" Copy ",false,{228,229})) return painted; if(message==WM_DPICHANGED) { @@ -5686,7 +5690,8 @@ INT_PTR CALLBACK copyProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp if(message!=WM_CLOSE && (message!=WM_COMMAND || LOWORD(wp)!=IDCANCEL)) return FALSE; auto &progress=*reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); if(!progress.canceled) - progress.canceled=confirmOperationCancellation(window,progress.move? + progress.canceled=confirmOperationCancellation(window,progress.writingArchive? + L"Do you really want to cancel writing the archive?":progress.move? L"Do you really want to cancel moving?":L"Do you really want to cancel copying?"); return TRUE; } @@ -6087,16 +6092,6 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve 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."); @@ -6112,6 +6107,18 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve setStatus(L"Wait for the search to finish."); return; } + if(destination.archive) + { + if(move || source.archive || source.peer || source.ftp) + setStatus(L"Use F5 from a local folder to add files to an archive."); + else addToArchive(owner,destination,external.empty()?selectedPanelPaths(source):std::move(external)); + return; + } + if(!archive.empty() && (move || destination.peer || destination.ftp)) + { + setStatus(L"Use F5 to extract archive entries to a local folder."); + return; + } const bool fromSearch=source.findOrigin.has_value(); const auto destinationFtp=ftpRename?sourceFtp:destination.ftp; const bool ftp=sourceFtp || destinationFtp; @@ -6740,7 +6747,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 || panel.archive) + if(panel.peer || panel.ftp || panel.findOrigin) { setStatus(L"Open a local folder before pasting files."); return true; @@ -6757,7 +6764,8 @@ bool pastePanelFiles(HWND owner,Panel &panel) setStatus(L"The clipboard has no usable file paths."); return true; } - copySelection(owner,panel,panel,false,std::move(paths)); + if(panel.archive) addToArchive(owner,panel,std::move(paths)); + else copySelection(owner,panel,panel,false,std::move(paths)); return true; } @@ -6811,6 +6819,8 @@ std::wstring dialogFieldText(HWND field) return value; } +#include "files_archive_dialog.inl" + INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { constexpr int label=360,field=361,divider=362,history=363,linkLabel=364,linkType=365, @@ -7455,7 +7465,7 @@ void openMenu(HWND window, int index) if(detailedPanel(panel)) rows.push_back(L" Columns…"); } } - else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"}; + else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10",L"Pack files…\tAlt+F5"}; else if(index==2) { rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts", @@ -8603,7 +8613,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } } if(!terminalVisible && !copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(window) && - message.message==WM_SYSKEYDOWN && message.wParam==VK_F7 && + message.message==WM_SYSKEYDOWN && (message.wParam==VK_F5 || message.wParam==VK_F7) && (message.lParam & (1LL<<29)) && !((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) { @@ -8611,7 +8621,8 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { hidePicker(); showMenu(false); - findLocalFiles(window,panels[active]); + if(message.wParam==VK_F5) createArchive(window,panels[active]); + else findLocalFiles(window,panels[active]); } continue; } diff --git a/src/files_text_document.cpp b/src/files_text_document.cpp index ab013e8..7875f9d 100644 --- a/src/files_text_document.cpp +++ b/src/files_text_document.cpp @@ -1,4 +1,5 @@ #include "files_text_document.h" +#include "files_win32_replace.h" #include #include @@ -385,16 +386,8 @@ bool TextDocument::save() File current{openSource(path_, true)}; if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher."); const auto backup = temporaryPath(path_.parent_path()); - if (!ReplaceFileW(path_.c_str(), pending.path.c_str(), backup.c_str(), 0, nullptr, nullptr)) + if (const auto error=replaceFileWithBackup(path_,pending.path,backup)) { - const auto error = GetLastError(); - if (GetFileAttributesW(backup.c_str()) != INVALID_FILE_ATTRIBUTES && - !MoveFileExW(backup.c_str(), path_.c_str(), MOVEFILE_WRITE_THROUGH)) - { - const auto location = backup.u8string(); - throw std::runtime_error("Could not restore the original name after a save error. The original is at " + - std::string(location.begin(), location.end())); - } SetLastError(error); fail("Replace original file"); } diff --git a/src/files_win32_replace.h b/src/files_win32_replace.h new file mode 100644 index 0000000..b3e80bc --- /dev/null +++ b/src/files_win32_replace.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include +#include + +namespace ks::files +{ +inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement, + const std::filesystem::path &backup) +{ + if(ReplaceFileW(original.c_str(),replacement.c_str(),backup.c_str(),0,nullptr,nullptr)) return ERROR_SUCCESS; + const auto error=GetLastError(); + if(GetFileAttributesW(backup.c_str())!=INVALID_FILE_ATTRIBUTES && + !MoveFileExW(backup.c_str(),original.c_str(),MOVEFILE_WRITE_THROUGH)) + { + const auto location=backup.u8string(); + throw std::runtime_error("Could not restore the original file name. The original is at "+ + std::string(location.begin(),location.end())); + } + return error; +} +} diff --git a/tests/files_archive.cpp b/tests/files_archive.cpp index c83e060..346a505 100644 --- a/tests/files_archive.cpp +++ b/tests/files_archive.cpp @@ -140,6 +140,88 @@ int main() makeArchive(unsafe,{{"link",{},AE_IFLNK}}); expectError([&]{readArchive(unsafe,{});},"link"); expect(!fs::exists(temp.path/L"escape.txt") && !fs::exists(temp.path/L"protected.txt"),"no unsafe output"); + const auto source=temp.path/L"source", update=temp.path/L"update"; + fs::create_directories(source/L"empty"); + fs::create_directories(update); + const auto item=source/L"дані.txt", replacement=update/L"дані.txt", added=update/L"new.txt"; + std::ofstream(item,std::ios::binary)<<"initial"; + std::ofstream(source/L"keep.txt",std::ios::binary)<